diff --git a/.commitlintrc.js b/.commitlintrc.js index e9c80b9247279..b706e527d77c0 100644 --- a/.commitlintrc.js +++ b/.commitlintrc.js @@ -7,5 +7,6 @@ module.exports = { 'header-max-length': [2, 'always', 80], 'subject-case': [0], 'body-max-line-length': [0], + 'footer-max-line-length': [0], }, } diff --git a/.eslintrc.js b/.eslintrc.js index b9ba04d34368a..58e76436686f4 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -12,6 +12,8 @@ module.exports = { root: true, ignorePatterns: [ 'tap-testdir*/', + '/node_modules/.bin/', + '/node_modules/.cache/', 'docs/**', 'smoke-tests/**', 'mock-globals/**', diff --git a/.gitattributes b/.gitattributes index 5d3dbc3b3ac65..4c25c056bd7e3 100644 --- a/.gitattributes +++ b/.gitattributes @@ -16,7 +16,9 @@ /node_modules/.gitignore text eol=lf /workspaces/arborist/test/fixtures/.gitignore text eol=lf /DEPENDENCIES.md text eol=lf +/DEPENDENCIES.json text eol=lf /AUTHORS text eol=lf +/docs/lib/content/nav.yml text eol=lf # fixture tarballs should be treated as binary /workspaces/*/test/fixtures/**/*.tgz binary diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 2c54b0d250372..b6ec921aa3a61 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,3 +1,3 @@ # This file is automatically added by @npmcli/template-oss. Do not edit. -* @npm/cli-team +* @npm/cli-team @npm/cli-triage diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index f285bcce4c81e..828bf2028a647 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -17,6 +17,13 @@ body: options: - label: I am using the latest npm required: true +- type: checkboxes + attributes: + label: This is not just a request to bump a dependency for a CVE + description: npm bundles its dependencies and updates them on a regular cadence, so CVEs in our bundled dependencies are picked up automatically. Issues opened solely to request a dependency bump for a CVE will be closed. To report an actual vulnerability in npm, please follow our [security policy](https://github.com/npm/cli/blob/latest/SECURITY.md) instead. + options: + - label: This is not solely a request to bump a dependency for a CVE + required: true - type: textarea attributes: label: Current Behavior diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 8bcac1c6dfdd9..a8ab263047bbc 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,8 @@ blank_issues_enabled: true contact_links: + - name: 🔒 Dependency CVE / security advisory in a bundled dependency + url: https://github.com/npm/cli/blob/latest/SECURITY.md + about: npm bundles its dependencies and updates them regularly, so CVEs in our bundled dependencies are picked up automatically. Please don't open an issue just to request a dependency bump for a CVE. To report a vulnerability in npm, see our security policy. - name: ❓ Help with issues in older versions of the CLI url: https://github.community/c/software-development/47 about: Find/file tickets with the community @@ -18,6 +21,6 @@ contact_links: - name: 📫 Support url: https://github.community/ about: For general support questions please open a topic over at github.community - - name: 🚑 Support Policy + - name: 🚑 Support Policy url: https://github.com/npm/cli/wiki/Support-Policy about: Information about what version(s) of the CLI we support diff --git a/.github/actions/create-check/action.yml b/.github/actions/create-check/action.yml index aa24a5b0f0581..d1220c90cfb11 100644 --- a/.github/actions/create-check/action.yml +++ b/.github/actions/create-check/action.yml @@ -25,7 +25,7 @@ runs: with: result-encoding: string script: | - const { repo: { owner, repo}, runId, serverUrl } = context + const { repo: { owner, repo}, runId, serverUrl } = context const { JOB_NAME, SHA } = process.env const job = await github.rest.actions.listJobsForWorkflowRun({ diff --git a/.github/actions/install-latest-npm/action.yml b/.github/actions/install-latest-npm/action.yml index 8339dbf03882d..580603dd40c92 100644 --- a/.github/actions/install-latest-npm/action.yml +++ b/.github/actions/install-latest-npm/action.yml @@ -44,7 +44,7 @@ runs: MATCH=$SPEC echo "Found compatible version: npm@$MATCH" break - fi + fi done if [ -z $MATCH ]; then diff --git a/.github/workflows/audit.yml b/.github/workflows/audit.yml index 589177f79660c..3731123f60770 100644 --- a/.github/workflows/audit.yml +++ b/.github/workflows/audit.yml @@ -8,6 +8,9 @@ on: # "At 08:00 UTC (01:00 PT) on Monday" https://crontab.guru/#0_8_*_*_1 - cron: "0 8 * * 1" +permissions: + contents: read + jobs: audit: name: Audit Dependencies @@ -18,17 +21,17 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/backport.yml b/.github/workflows/backport.yml new file mode 100644 index 0000000000000..59db13540b003 --- /dev/null +++ b/.github/workflows/backport.yml @@ -0,0 +1,97 @@ +name: Backport + +on: + pull_request_target: + types: [closed, labeled] + # TODO: Remove before merging — manual trigger for testing from any branch + workflow_dispatch: + inputs: + pr_number: + description: 'Merged PR number to test backporting' + required: true + type: number + +permissions: + actions: write + contents: write + pull-requests: write + +jobs: + backport: + name: Backport + runs-on: ubuntu-latest + # Run when a labeled PR is merged, or when a backport label is added to an already-merged PR. + # Uses pull_request_target so the token has write access even for PRs from forks. + if: >- + github.repository_owner == 'npm' && + github.event.pull_request.merged == true && + ( + (github.event.action == 'closed' && + contains(join(github.event.pull_request.labels.*.name, ','), 'backport:')) + || + (github.event.action == 'labeled' && + startsWith(github.event.label.name, 'backport:')) + ) + defaults: + run: + shell: bash + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Setup Git User + run: | + git config --global user.email "npm-cli+bot@github.com" + git config --global user.name "npm CLI robot" + - name: Create Backports + uses: actions/github-script@v7 + env: + MERGE_COMMIT_SHA: ${{ github.event.pull_request.merge_commit_sha }} + with: + script: | + const backport = require('./scripts/backport.js') + await backport({ github, context, core }) + + # TODO: Remove before merging — manual test job + backport-test: + name: Backport (Test) + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + defaults: + run: + shell: bash + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Setup Git User + run: | + git config --global user.email "npm-cli+bot@github.com" + git config --global user.name "npm CLI robot" + - name: Create Backports + uses: actions/github-script@v7 + with: + script: | + const { data: pr } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: ${{ inputs.pr_number }}, + }) + + if (!pr.merged) { + return core.setFailed('PR #${{ inputs.pr_number }} is not merged') + } + + process.env.MERGE_COMMIT_SHA = pr.merge_commit_sha + + const backport = require('./scripts/backport.js') + await backport({ + github, + core, + context: { + ...context, + payload: { action: 'closed', pull_request: pr }, + }, + }) diff --git a/.github/workflows/ci-libnpmaccess.yml b/.github/workflows/ci-libnpmaccess.yml index b44d964b93aa4..09d210133782f 100644 --- a/.github/workflows/ci-libnpmaccess.yml +++ b/.github/workflows/ci-libnpmaccess.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w libnpmaccess + run: npm run lint --ignore-scripts --workspace libnpmaccess - name: Post Lint - run: npm run postlint --ignore-scripts -w libnpmaccess + run: npm run postlint --ignore-scripts --workspace libnpmaccess test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,53 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -120,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w libnpmaccess + run: npm test --ignore-scripts --workspace libnpmaccess - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-libnpmdiff.yml b/.github/workflows/ci-libnpmdiff.yml index dbebd2c95d0be..c7bc23d7805f1 100644 --- a/.github/workflows/ci-libnpmdiff.yml +++ b/.github/workflows/ci-libnpmdiff.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w libnpmdiff + run: npm run lint --ignore-scripts --workspace libnpmdiff - name: Post Lint - run: npm run postlint --ignore-scripts -w libnpmdiff + run: npm run postlint --ignore-scripts --workspace libnpmdiff test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,53 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -120,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w libnpmdiff + run: npm test --ignore-scripts --workspace libnpmdiff - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-libnpmexec.yml b/.github/workflows/ci-libnpmexec.yml index e51248c69481a..79c6f7d48cb4a 100644 --- a/.github/workflows/ci-libnpmexec.yml +++ b/.github/workflows/ci-libnpmexec.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w libnpmexec + run: npm run lint --ignore-scripts --workspace libnpmexec - name: Post Lint - run: npm run postlint --ignore-scripts -w libnpmexec + run: npm run postlint --ignore-scripts --workspace libnpmexec test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,53 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -120,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w libnpmexec + run: npm test --ignore-scripts --workspace libnpmexec - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-libnpmfund.yml b/.github/workflows/ci-libnpmfund.yml index b628fe60e3d3f..1ddf0eff0a289 100644 --- a/.github/workflows/ci-libnpmfund.yml +++ b/.github/workflows/ci-libnpmfund.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w libnpmfund + run: npm run lint --ignore-scripts --workspace libnpmfund - name: Post Lint - run: npm run postlint --ignore-scripts -w libnpmfund + run: npm run postlint --ignore-scripts --workspace libnpmfund test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,53 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -120,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w libnpmfund + run: npm test --ignore-scripts --workspace libnpmfund - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-libnpmhook.yml b/.github/workflows/ci-libnpmhook.yml deleted file mode 100644 index 8512c98767407..0000000000000 --- a/.github/workflows/ci-libnpmhook.yml +++ /dev/null @@ -1,125 +0,0 @@ -# This file is automatically added by @npmcli/template-oss. Do not edit. - -name: CI - libnpmhook - -on: - workflow_dispatch: - pull_request: - paths: - - workspaces/libnpmhook/** - push: - branches: - - latest - - release/v* - paths: - - workspaces/libnpmhook/** - schedule: - # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - - cron: "0 9 * * 1" - -jobs: - lint: - name: Lint - if: github.repository_owner == 'npm' - runs-on: ubuntu-latest - defaults: - run: - shell: bash - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Setup Git User - run: | - git config --global user.email "npm-cli+bot@github.com" - git config --global user.name "npm CLI robot" - - name: Setup Node - uses: actions/setup-node@v4 - id: node - with: - node-version: 22.x - check-latest: contains('22.x', '.x') - cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - - name: Check Git Status - run: node scripts/git-dirty.js - - name: Reset Deps - run: node scripts/resetdeps.js - - name: Lint - run: npm run lint --ignore-scripts -w libnpmhook - - name: Post Lint - run: npm run postlint --ignore-scripts -w libnpmhook - - test: - name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} - if: github.repository_owner == 'npm' - strategy: - fail-fast: false - matrix: - platform: - - name: Linux - os: ubuntu-latest - shell: bash - - name: macOS - os: macos-latest - shell: bash - - name: macOS - os: macos-13 - shell: bash - - name: Windows - os: windows-latest - shell: cmd - node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x - - 22.x - exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 22.x - runs-on: ${{ matrix.platform.os }} - defaults: - run: - shell: ${{ matrix.platform.shell }} - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Setup Git User - run: | - git config --global user.email "npm-cli+bot@github.com" - git config --global user.name "npm CLI robot" - - name: Setup Node - uses: actions/setup-node@v4 - id: node - with: - node-version: ${{ matrix.node-version }} - check-latest: contains(matrix.node-version, '.x') - cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - - name: Check Git Status - run: node scripts/git-dirty.js - - name: Reset Deps - run: node scripts/resetdeps.js - - name: Add Problem Matcher - run: echo "::add-matcher::.github/matchers/tap.json" - - name: Test - run: npm test --ignore-scripts -w libnpmhook - - name: Check Git Status - run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-libnpmorg.yml b/.github/workflows/ci-libnpmorg.yml index 3cd3c4b13040e..0585a8177bf01 100644 --- a/.github/workflows/ci-libnpmorg.yml +++ b/.github/workflows/ci-libnpmorg.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w libnpmorg + run: npm run lint --ignore-scripts --workspace libnpmorg - name: Post Lint - run: npm run postlint --ignore-scripts -w libnpmorg + run: npm run postlint --ignore-scripts --workspace libnpmorg test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,53 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -120,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w libnpmorg + run: npm test --ignore-scripts --workspace libnpmorg - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-libnpmpack.yml b/.github/workflows/ci-libnpmpack.yml index ba21f86ff8f72..7d2d289ae3683 100644 --- a/.github/workflows/ci-libnpmpack.yml +++ b/.github/workflows/ci-libnpmpack.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w libnpmpack + run: npm run lint --ignore-scripts --workspace libnpmpack - name: Post Lint - run: npm run postlint --ignore-scripts -w libnpmpack + run: npm run postlint --ignore-scripts --workspace libnpmpack test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,53 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -120,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w libnpmpack + run: npm test --ignore-scripts --workspace libnpmpack - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-libnpmpublish.yml b/.github/workflows/ci-libnpmpublish.yml index 768bf8526a3ff..bfa7b456f990c 100644 --- a/.github/workflows/ci-libnpmpublish.yml +++ b/.github/workflows/ci-libnpmpublish.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w libnpmpublish + run: npm run lint --ignore-scripts --workspace libnpmpublish - name: Post Lint - run: npm run postlint --ignore-scripts -w libnpmpublish + run: npm run postlint --ignore-scripts --workspace libnpmpublish test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,53 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -120,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w libnpmpublish + run: npm test --ignore-scripts --workspace libnpmpublish - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-libnpmsearch.yml b/.github/workflows/ci-libnpmsearch.yml index 991ad7b103f85..2fc4f4c159ff7 100644 --- a/.github/workflows/ci-libnpmsearch.yml +++ b/.github/workflows/ci-libnpmsearch.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w libnpmsearch + run: npm run lint --ignore-scripts --workspace libnpmsearch - name: Post Lint - run: npm run postlint --ignore-scripts -w libnpmsearch + run: npm run postlint --ignore-scripts --workspace libnpmsearch test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,53 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -120,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w libnpmsearch + run: npm test --ignore-scripts --workspace libnpmsearch - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-libnpmteam.yml b/.github/workflows/ci-libnpmteam.yml index 5ba1b481ee998..7249871039682 100644 --- a/.github/workflows/ci-libnpmteam.yml +++ b/.github/workflows/ci-libnpmteam.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w libnpmteam + run: npm run lint --ignore-scripts --workspace libnpmteam - name: Post Lint - run: npm run postlint --ignore-scripts -w libnpmteam + run: npm run postlint --ignore-scripts --workspace libnpmteam test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,53 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -120,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w libnpmteam + run: npm test --ignore-scripts --workspace libnpmteam - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-libnpmversion.yml b/.github/workflows/ci-libnpmversion.yml index 17b656654582d..83cd1b062e306 100644 --- a/.github/workflows/ci-libnpmversion.yml +++ b/.github/workflows/ci-libnpmversion.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w libnpmversion + run: npm run lint --ignore-scripts --workspace libnpmversion - name: Post Lint - run: npm run postlint --ignore-scripts -w libnpmversion + run: npm run postlint --ignore-scripts --workspace libnpmversion test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,53 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -120,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w libnpmversion + run: npm test --ignore-scripts --workspace libnpmversion - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-npmcli-arborist.yml b/.github/workflows/ci-npmcli-arborist.yml index 95026777fa969..5d15cdbebb5a6 100644 --- a/.github/workflows/ci-npmcli-arborist.yml +++ b/.github/workflows/ci-npmcli-arborist.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w @npmcli/arborist + run: npm run lint --ignore-scripts --workspace @npmcli/arborist - name: Post Lint - run: npm run postlint --ignore-scripts -w @npmcli/arborist + run: npm run postlint --ignore-scripts --workspace @npmcli/arborist test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,53 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -120,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w @npmcli/arborist + run: npm test --ignore-scripts --workspace @npmcli/arborist - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-npmcli-config.yml b/.github/workflows/ci-npmcli-config.yml index cb8db1ef0641d..fb5d3f803afa1 100644 --- a/.github/workflows/ci-npmcli-config.yml +++ b/.github/workflows/ci-npmcli-config.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w @npmcli/config + run: npm run lint --ignore-scripts --workspace @npmcli/config - name: Post Lint - run: npm run postlint --ignore-scripts -w @npmcli/config + run: npm run postlint --ignore-scripts --workspace @npmcli/config test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,53 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 16.14.0 - - 16.x - - 18.0.0 - - 18.x - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.14.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 16.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.0.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -120,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w @npmcli/config + run: npm test --ignore-scripts --workspace @npmcli/config - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-npmcli-docs.yml b/.github/workflows/ci-npmcli-docs.yml index 6585662edc54f..d126494e1abee 100644 --- a/.github/workflows/ci-npmcli-docs.yml +++ b/.github/workflows/ci-npmcli-docs.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w @npmcli/docs + run: npm run lint --ignore-scripts --workspace @npmcli/docs - name: Post Lint - run: npm run postlint --ignore-scripts -w @npmcli/docs + run: npm run postlint --ignore-scripts --workspace @npmcli/docs test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,38 +65,34 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 22.x + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -105,7 +100,7 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w @npmcli/docs + run: npm test --ignore-scripts --workspace @npmcli/docs - name: Check Git Status run: node scripts/git-dirty.js @@ -118,7 +113,7 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 0 - name: Setup Git User @@ -126,16 +121,12 @@ jobs: git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps diff --git a/.github/workflows/ci-npmcli-mock-globals.yml b/.github/workflows/ci-npmcli-mock-globals.yml index 213a5d7cf8ec0..2cb2add4ac835 100644 --- a/.github/workflows/ci-npmcli-mock-globals.yml +++ b/.github/workflows/ci-npmcli-mock-globals.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w @npmcli/mock-globals + run: npm run lint --ignore-scripts --workspace @npmcli/mock-globals - name: Post Lint - run: npm run postlint --ignore-scripts -w @npmcli/mock-globals + run: npm run postlint --ignore-scripts --workspace @npmcli/mock-globals test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,50 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 18.17.0 - - 18.x - - 20.5.0 - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.17.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.5.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -117,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w @npmcli/mock-globals + run: npm test --ignore-scripts --workspace @npmcli/mock-globals - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-npmcli-mock-registry.yml b/.github/workflows/ci-npmcli-mock-registry.yml index 494f9ee4e14a4..0ee19f690c888 100644 --- a/.github/workflows/ci-npmcli-mock-registry.yml +++ b/.github/workflows/ci-npmcli-mock-registry.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w @npmcli/mock-registry + run: npm run lint --ignore-scripts --workspace @npmcli/mock-registry - name: Post Lint - run: npm run postlint --ignore-scripts -w @npmcli/mock-registry + run: npm run postlint --ignore-scripts --workspace @npmcli/mock-registry test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,50 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 18.17.0 - - 18.x - - 20.5.0 - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.17.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.5.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -117,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w @npmcli/mock-registry + run: npm test --ignore-scripts --workspace @npmcli/mock-registry - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-npmcli-smoke-tests.yml b/.github/workflows/ci-npmcli-smoke-tests.yml index d322fa0394c13..f04fc144c58cc 100644 --- a/.github/workflows/ci-npmcli-smoke-tests.yml +++ b/.github/workflows/ci-npmcli-smoke-tests.yml @@ -17,6 +17,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -27,30 +30,26 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: npm run lint --ignore-scripts -w @npmcli/smoke-tests + run: npm run lint --ignore-scripts --workspace @npmcli/smoke-tests - name: Post Lint - run: npm run postlint --ignore-scripts -w @npmcli/smoke-tests + run: npm run postlint --ignore-scripts --workspace @npmcli/smoke-tests test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} @@ -66,50 +65,49 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 18.17.0 - - 18.x - - 20.5.0 - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.17.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.5.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} check-latest: contains(matrix.node-version, '.x') cache: npm - - name: Install Latest npm - uses: ./.github/actions/install-latest-npm - with: - node: ${{ steps.node.outputs.node-version }} - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps @@ -117,6 +115,6 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: npm test --ignore-scripts -w @npmcli/smoke-tests + run: npm test --ignore-scripts --workspace @npmcli/smoke-tests - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/ci-release.yml b/.github/workflows/ci-release.yml index bd6cbf8ab4f1d..65e2ae9032ac4 100644 --- a/.github/workflows/ci-release.yml +++ b/.github/workflows/ci-release.yml @@ -18,6 +18,10 @@ on: required: true type: string +permissions: + contents: read + checks: write + jobs: lint-all: name: Lint All @@ -28,7 +32,7 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: ref: ${{ inputs.ref }} - name: Setup Git User @@ -44,23 +48,23 @@ jobs: token: ${{ secrets.GITHUB_TOKEN }} sha: ${{ inputs.check-sha }} - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - name: Lint - run: node . run lint --ignore-scripts -ws -iwr --if-present + run: node . run lint --ignore-scripts --workspaces --include-workspace-root --if-present - name: Post Lint - run: node . run postlint --ignore-scripts -ws -iwr --if-present + run: node . run postlint --ignore-scripts --workspaces --include-workspace-root --if-present - name: Conclude Check uses: LouisBrunner/checks-action@v1.6.0 - if: always() + if: steps.create-check.outputs.check-id && always() with: token: ${{ secrets.GITHUB_TOKEN }} conclusion: ${{ job.status }} @@ -80,35 +84,38 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 18.17.0 - - 18.x - - 20.5.0 - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.17.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.5.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: ref: ${{ inputs.ref }} - name: Setup Git User @@ -124,7 +131,7 @@ jobs: token: ${{ secrets.GITHUB_TOKEN }} sha: ${{ inputs.check-sha }} - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} @@ -137,23 +144,86 @@ jobs: - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test - run: node . test --ignore-scripts -ws -iwr --if-present + run: node . test --ignore-scripts --workspaces --include-workspace-root --if-present + - name: Check Git Status + run: node scripts/git-dirty.js + - name: Conclude Check + uses: LouisBrunner/checks-action@v1.6.0 + if: steps.create-check.outputs.check-id && always() + with: + token: ${{ secrets.GITHUB_TOKEN }} + conclusion: ${{ job.status }} + check_id: ${{ steps.create-check.outputs.check-id }} + + smoke-tests: + # This cant be tested on Windows because our node_modules directory + # checks in symlinks which are not supported there. This should be + # fixed somehow, because this means some forms of local development + # are likely broken on Windows as well. + name: Smoke Tests - ${{ matrix.platform.name }} - ${{ matrix.node-version }} + if: github.repository_owner == 'npm' + strategy: + fail-fast: false + matrix: + platform: + - name: Linux + os: ubuntu-latest + shell: bash + node-version: + - 22.22.2 + - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x + runs-on: ${{ matrix.platform.os }} + defaults: + run: + shell: ${{ matrix.platform.shell }} + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + ref: ${{ inputs.ref }} + - name: Setup Git User + run: | + git config --global user.email "npm-cli+bot@github.com" + git config --global user.name "npm CLI robot" + - name: Create Check + id: create-check + if: ${{ inputs.check-sha }} + uses: ./.github/actions/create-check + with: + name: "Smoke Tests - ${{ matrix.platform.name }} - ${{ matrix.node-version }}" + token: ${{ secrets.GITHUB_TOKEN }} + sha: ${{ inputs.check-sha }} + - name: Setup Node + uses: actions/setup-node@v6 + id: node + with: + node-version: ${{ matrix.node-version }} + check-latest: contains(matrix.node-version, '.x') + cache: npm - name: Check Git Status run: node scripts/git-dirty.js + - name: Reset Deps + run: node scripts/resetdeps.js + - name: Smoke Tests + run: ./scripts/smoke-tests.sh - name: Conclude Check uses: LouisBrunner/checks-action@v1.6.0 - if: always() + if: steps.create-check.outputs.check-id && always() with: token: ${{ secrets.GITHUB_TOKEN }} conclusion: ${{ job.status }} check_id: ${{ steps.create-check.outputs.check-id }} - smoke-publish: - # This cant be tested on Windows because our node_modules directory - # checks in symlinks which are not supported there. This should be - # fixed somehow, because this means some forms of local development - # are likely broken on Windows as well. - name: Smoke Publish - ${{ matrix.platform.name }} - ${{ matrix.node-version }} + publish-dryrun: + # This cant be tested on Windows because our node_modules directory + # checks in symlinks which are not supported there. This should be + # fixed somehow, because this means some forms of local development + # are likely broken on Windows as well. + name: Publish Dry-Run - ${{ matrix.platform.name }} - ${{ matrix.node-version }} if: github.repository_owner == 'npm' strategy: fail-fast: false @@ -163,18 +233,19 @@ jobs: os: ubuntu-latest shell: bash node-version: - - 18.17.0 - - 18.x - - 20.5.0 - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: ref: ${{ inputs.ref }} - name: Setup Git User @@ -186,11 +257,11 @@ jobs: if: ${{ inputs.check-sha }} uses: ./.github/actions/create-check with: - name: "Smoke Publish - ${{ matrix.platform.name }} - ${{ matrix.node-version }}" + name: "Publish Dry-Run - ${{ matrix.platform.name }} - ${{ matrix.node-version }}" token: ${{ secrets.GITHUB_TOKEN }} sha: ${{ inputs.check-sha }} - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} @@ -200,8 +271,8 @@ jobs: run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - - name: Smoke Publish - run: ./scripts/smoke-publish-test.sh + - name: Publish Dry-Run + run: node ./scripts/publish.js --pack-destination=$RUNNER_TEMP --smoke-publish=true - name: Conclude Check uses: LouisBrunner/checks-action@v1.6.0 if: steps.create-check.outputs.check-id && always() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5198cbeecb765..3c384ad13d639 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,6 +25,9 @@ on: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" +permissions: + contents: read + jobs: lint: name: Lint @@ -35,17 +38,17 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - name: Check Git Status run: node scripts/git-dirty.js @@ -70,41 +73,44 @@ jobs: os: macos-latest shell: bash - name: macOS - os: macos-13 + os: macos-15-intel shell: bash - name: Windows os: windows-latest shell: cmd node-version: - - 18.17.0 - - 18.x - - 20.5.0 - - 20.x + - 22.22.2 - 22.x + - 24.15.0 + - 24.x + - 26.0.0 + - 26.x exclude: - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.17.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 18.x - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.5.0 - - platform: { name: macOS, os: macos-13, shell: bash } - node-version: 20.x - - platform: { name: macOS, os: macos-13, shell: bash } + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 22.22.2 + - platform: { name: macOS, os: macos-15-intel, shell: bash } node-version: 22.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.15.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 24.x + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.0.0 + - platform: { name: macOS, os: macos-15-intel, shell: bash } + node-version: 26.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: node-version: ${{ matrix.node-version }} @@ -130,17 +136,17 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - name: Check Git Status run: node scripts/git-dirty.js @@ -150,6 +156,10 @@ jobs: run: node . run licenses smoke-tests: + # This cant be tested on Windows because our node_modules directory + # checks in symlinks which are not supported there. This should be + # fixed somehow, because this means some forms of local development + # are likely broken on Windows as well. name: Smoke Tests if: github.repository_owner == 'npm' runs-on: ubuntu-latest @@ -158,26 +168,90 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 + with: + ref: ${{ inputs.ref }} - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" + - name: Create Check + id: create-check + if: ${{ inputs.check-sha }} + uses: ./.github/actions/create-check + with: + name: "Smoke Tests" + token: ${{ secrets.GITHUB_TOKEN }} + sha: ${{ inputs.check-sha }} - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - name: Check Git Status run: node scripts/git-dirty.js - name: Reset Deps run: node scripts/resetdeps.js - - name: Run Smoke Tests - run: node . test -w smoke-tests --ignore-scripts + - name: Smoke Tests + run: ./scripts/smoke-tests.sh + - name: Conclude Check + uses: LouisBrunner/checks-action@v1.6.0 + if: steps.create-check.outputs.check-id && always() + with: + token: ${{ secrets.GITHUB_TOKEN }} + conclusion: ${{ job.status }} + check_id: ${{ steps.create-check.outputs.check-id }} + + publish-dryrun: + # This cant be tested on Windows because our node_modules directory + # checks in symlinks which are not supported there. This should be + # fixed somehow, because this means some forms of local development + # are likely broken on Windows as well. + name: Publish Dry-Run + if: github.repository_owner == 'npm' + runs-on: ubuntu-latest + defaults: + run: + shell: bash + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + ref: ${{ inputs.ref }} + - name: Setup Git User + run: | + git config --global user.email "npm-cli+bot@github.com" + git config --global user.name "npm CLI robot" + - name: Create Check + id: create-check + if: ${{ inputs.check-sha }} + uses: ./.github/actions/create-check + with: + name: "Publish Dry-Run" + token: ${{ secrets.GITHUB_TOKEN }} + sha: ${{ inputs.check-sha }} + - name: Setup Node + uses: actions/setup-node@v6 + id: node + with: + node-version: 26.x + check-latest: contains('26.x', '.x') + cache: npm - name: Check Git Status run: node scripts/git-dirty.js + - name: Reset Deps + run: node scripts/resetdeps.js + - name: Publish Dry-Run + run: node ./scripts/publish.js --pack-destination=$RUNNER_TEMP --smoke-publish=true + - name: Conclude Check + uses: LouisBrunner/checks-action@v1.6.0 + if: steps.create-check.outputs.check-id && always() + with: + token: ${{ secrets.GITHUB_TOKEN }} + conclusion: ${{ job.status }} + check_id: ${{ steps.create-check.outputs.check-id }} windows-shims: name: Windows Shims Tests @@ -187,17 +261,17 @@ jobs: shell: cmd steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 1e05817c06c03..66adaa1860027 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -15,6 +15,9 @@ on: # "At 10:00 UTC (03:00 PT) on Monday" https://crontab.guru/#0_10_*_*_1 - cron: "0 10 * * 1" +permissions: + contents: read + jobs: analyze: name: Analyze @@ -25,14 +28,14 @@ jobs: security-events: write steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 with: languages: javascript - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/create-node-pr.yml b/.github/workflows/create-node-pr.yml index c903220dbd2ca..6bc578aef6cd4 100644 --- a/.github/workflows/create-node-pr.yml +++ b/.github/workflows/create-node-pr.yml @@ -16,6 +16,9 @@ on: dryRun: description: "Setting this to anything will run all the steps except opening the PR" +permissions: + contents: write + jobs: create-pull-request: name: Create Node PR @@ -26,7 +29,7 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 0 - name: Setup Git User @@ -34,11 +37,11 @@ jobs: git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/node-integration.yml b/.github/workflows/node-integration.yml index 49beea2115d6f..054b7f1b657a7 100644 --- a/.github/workflows/node-integration.yml +++ b/.github/workflows/node-integration.yml @@ -80,7 +80,7 @@ jobs: echo "::group::extracting source from $nodeUrl" mkdir -p "$sourceDir" - curl -sSL "$nodeUrl" | tar xz -C "$sourceDir" --strip=1 + curl -sSL "$nodeUrl" | tar xz -C "$sourceDir" --strip=1 echo "::endgroup::" echo "::group::cloning npm" @@ -137,7 +137,7 @@ jobs: echo "build=$targetFile" >> $GITHUB_OUTPUT echo "::endgroup::" - name: upload artifacts - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: nodejs-${{ steps.build-nodejs.outputs.nodeVersion }} path: | @@ -156,7 +156,7 @@ jobs: with: override_cache_key: nodejs-${{ inputs.nodeVersion }} - name: download artifacts - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: nodejs-${{ needs.build-nodejs.outputs.nodeVersion }} - name: test nodejs @@ -173,7 +173,7 @@ jobs: - build-nodejs steps: - name: download artifacts - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: nodejs-${{ needs.build-nodejs.outputs.nodeVersion }} path: ${{ runner.temp }} @@ -361,7 +361,7 @@ jobs: include: ${{ fromJson(needs.generate-matrix.outputs.matrix) }} steps: - name: download artifacts - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: nodejs-${{ needs.build-nodejs.outputs.nodeVersion }} path: ${{ runner.temp }} diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 2c27dec822336..6a5bab5d1558b 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -10,6 +10,9 @@ on: - edited - synchronize +permissions: + contents: read + jobs: commitlint: name: Lint Commits @@ -20,7 +23,7 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 0 - name: Setup Git User @@ -28,11 +31,11 @@ jobs: git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - name: Check Git Status run: node scripts/git-dirty.js diff --git a/.github/workflows/release-integration.yml b/.github/workflows/release-integration.yml index cfb18e6abc8ba..5b49491731731 100644 --- a/.github/workflows/release-integration.yml +++ b/.github/workflows/release-integration.yml @@ -16,14 +16,17 @@ on: type: string description: 'A json array of releases. Required fields: publish: tagName, publishTag. publish check: pkgName, version' +permissions: + contents: read + jobs: publish: strategy: fail-fast: false matrix: nodeVersion: - - 18 - - 20 + - 22 + - 23 - nightly uses: ./.github/workflows/node-integration.yml with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 98c2034291478..140f2af9006c3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -31,17 +31,17 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - name: Check Git Status run: node scripts/git-dirty.js @@ -107,7 +107,7 @@ jobs: shell: bash steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 0 ref: ${{ needs.release.outputs.pr-branch }} @@ -116,11 +116,11 @@ jobs: git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 id: node with: - node-version: 22.x - check-latest: contains('22.x', '.x') + node-version: 26.x + check-latest: contains('26.x', '.x') cache: npm - name: Check Git Status run: node scripts/git-dirty.js @@ -140,7 +140,7 @@ jobs: - name: Run Post Pull Request Actions env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: node . run rp-pull-request --ignore-scripts -ws -iwr --if-present -- --pr="${{ needs.release.outputs.pr-number }}" --commentId="${{ needs.release.outputs.comment-id }}" + run: node . run rp-pull-request --ignore-scripts --workspaces --include-workspace-root --if-present -- --pr="${{ needs.release.outputs.pr-number }}" --commentId="${{ needs.release.outputs.comment-id }}" - name: Commit id: commit env: diff --git a/.gitignore b/.gitignore index 2a10ae9bd8888..93b77383ab9a0 100644 --- a/.gitignore +++ b/.gitignore @@ -2,20 +2,21 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore !/.commitlintrc.js +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitattributes !/.github/ !/.gitignore !/.licensee.json !/.mailmap !/.npmrc +!/.prettierignore +!/.prettierrc.js !/.release-please-manifest.json !/AUTHORS !/bin/ @@ -23,6 +24,7 @@ tap-testdir*/ !/CODE_OF_CONDUCT.md !/configure !/CONTRIBUTING.md +!/DEPENDENCIES.json !/DEPENDENCIES.md !/docs/ !/index.js @@ -41,6 +43,7 @@ tap-testdir*/ !/tap-snapshots/ !/test/ !/tsconfig.json +tap-testdir*/ !/docs/ !/smoke-tests/ !/mock-globals/ @@ -53,7 +56,6 @@ tap-testdir*/ !/workspaces/libnpmdiff/ !/workspaces/libnpmexec/ !/workspaces/libnpmfund/ -!/workspaces/libnpmhook/ !/workspaces/libnpmorg/ !/workspaces/libnpmpack/ !/workspaces/libnpmpublish/ diff --git a/.release-please-manifest.json b/.release-please-manifest.json index c9d6c5d3b823f..7843187bb932d 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,16 +1,15 @@ { - ".": "10.8.2", - "workspaces/arborist": "7.5.4", - "workspaces/libnpmaccess": "8.0.6", - "workspaces/libnpmdiff": "6.1.4", - "workspaces/libnpmexec": "8.1.3", - "workspaces/libnpmfund": "5.0.12", - "workspaces/libnpmhook": "10.0.5", - "workspaces/libnpmorg": "6.0.6", - "workspaces/libnpmpack": "7.0.4", - "workspaces/libnpmpublish": "9.0.9", - "workspaces/libnpmsearch": "7.0.6", - "workspaces/libnpmteam": "6.0.5", - "workspaces/libnpmversion": "6.0.3", - "workspaces/config": "8.3.4" + ".": "12.0.0-pre.1", + "workspaces/arborist": "10.0.0-pre.1", + "workspaces/libnpmaccess": "11.0.0-pre.0", + "workspaces/libnpmdiff": "9.0.0-pre.0", + "workspaces/libnpmexec": "11.0.0-pre.0", + "workspaces/libnpmfund": "8.0.0-pre.0", + "workspaces/libnpmorg": "9.0.0-pre.0", + "workspaces/libnpmpack": "10.0.0-pre.1", + "workspaces/libnpmpublish": "12.0.0-pre.0", + "workspaces/libnpmsearch": "10.0.0-pre.0", + "workspaces/libnpmteam": "9.0.0-pre.0", + "workspaces/libnpmversion": "9.0.0-pre.1", + "workspaces/config": "11.0.0-pre.1" } diff --git a/AUTHORS b/AUTHORS index 90a1d94834c8d..51b5823ebe37c 100644 --- a/AUTHORS +++ b/AUTHORS @@ -945,3 +945,88 @@ Leo Balter <301201+leobalter@users.noreply.github.com> drew4237 <57016082+drew4237@users.noreply.github.com> AmirHossein Sakhravi Hiroo Ono <49257691+oikumene@users.noreply.github.com> +Sonny <47546413+sonsurim@users.noreply.github.com> +Alessandro Diez +Rhys Evans +reggi +btea <2356281422@qq.com> +Sander Aalbers <31731300+Sanderovich@users.noreply.github.com> +Chris Sidi +Maksim Koryukov +Trevor Burnham +Michael Smith +terrainvidia +Tyler Albee +William Briggs <37094383+billy-briggs-dev@users.noreply.github.com> +Gabriel Bouyssou +Carl Gay +liang.chen +Milan Meva +Spencer Faith <45831293+13sfaith@users.noreply.github.com> +David Glasser +Alex Schwartz +xaos7991 <44319098+xaos7991@users.noreply.github.com> +Tom Mrazauskas +sam crochet +tarekwfa0110 <109884541+tarekwfa0110@users.noreply.github.com> +Marc Bernard +Gareth Jones <3151613+G-Rath@users.noreply.github.com> +Aaron Jensen +Jeepsboucher <42554351+Jeepsboucher@users.noreply.github.com> +Arkadiusz Czekajski +Liam Mitchell +Jon Jensen +Josh Soref <2119212+jsoref@users.noreply.github.com> +Tejas Mahajan <59790915+Tejas242@users.noreply.github.com> +Max Black +PiotrD +khanhkhanhlele +Artur Signell +Julian Flögel +Max Black +Yashwant Bezawada +Keegan Carruthers-Smith +Saksham Malhotra +Kai <2644614+Schweinepriester@users.noreply.github.com> +Mateusz Burzyński +Chris +Adam Stachowicz +Ishan Maitra +Umesh More <73871036+umeshmore45@users.noreply.github.com> +Manzoor Wani +JNC4 <137045298+JNC4@users.noreply.github.com> +Ajay Kemparaj +Yashraj Chouhan <129044960+Jadu07@users.noreply.github.com> +Lucas Gomes Santana +Mohamed Akram +Mitch Denny +Matt Van Horn +Daniel Foerster +Lovell Fuller +Josua Michalak +Caleb Everett +Open Source Zeal <269018900+opensourcezeal@users.noreply.github.com> +Rayan Salhab +lawrence3699 +Aryan Tiwari <53210551+yetanotheraryan@users.noreply.github.com> +Caleb Everett +Vishal Doshi +Mikael Kristiansson <1733784+mikaelkristiansson@users.noreply.github.com> +ecanturk <46566566+ecanturk@users.noreply.github.com> +Max <135263966+verifizieren@users.noreply.github.com> +Tea Reggi +raazkhnl +Oliver Byford +Zelys +Jamie Magee +Puneet Dixit +12122J +Jamie Magee +Shaan Majid <70789625+shaanmajid@users.noreply.github.com> +Minh Vu +Dexter.k <164054284+rootvector2@users.noreply.github.com> +meeech <4623+meeech@users.noreply.github.com> +Abhinav +Liang +ded-furby <190979964+ded-furby@users.noreply.github.com> +Oldřich Jedlička diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d1c704a2ea8d..0c7e3b154629d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,1016 +1,1076 @@ # Changelog -## [10.8.2](https://github.com/npm/cli/compare/v10.8.1...v10.8.2) (2024-07-09) - +## [12.0.0-pre.1](https://github.com/npm/cli/compare/v12.0.0-pre.0...v12.0.0-pre.1) (2026-06-19) +### ⚠️ BREAKING CHANGES +* Preserve https protocol when working with git (#8703) +* The default license for `npm init` has been changed from "ISC" to an empty string. If not set, the license field will be omitted from new packages. +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +* allow-git and allow-remote now default to "none"; set them to "all" (or "root") to install git or user-supplied tarball-URL dependencies. +* root \`preinstall\` now runs before dependencies are installed. +* unknown configs in .npmrc, unknown CLI flags, abbreviated flags, and single-hyphen multi-char shorthands now throw instead of warning. +### Features +* [`ce7681f`](https://github.com/npm/cli/commit/ce7681fe7dbcc20abb5f1379558e14ddd069654f) [#9496](https://github.com/npm/cli/pull/9496) packageExtensions for root-owned dependency manifest repairs (#9496) (@manzoorwanijk) +* [`1db885c`](https://github.com/npm/cli/commit/1db885c84b2dfc5126ab663abb12262b533922c1) [#9439](https://github.com/npm/cli/pull/9439) native dependency patching (npm patch add/commit/update/ls/rm) (#9439) (@manzoorwanijk) +* [`fc80bb3`](https://github.com/npm/cli/commit/fc80bb359502699bb0a055157e01eaedd5bd73c8) [#9234](https://github.com/npm/cli/pull/9234) remove default license for npm init (@owlstronaut) +* [`be8053c`](https://github.com/npm/cli/commit/be8053c390a2be3902b9382d3c7d4ad9012fa1c2) [#9544](https://github.com/npm/cli/pull/9544) warn when min-release-age blocks an audit fix (#9544) (@JamieMagee) +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +* [`c3e1a71`](https://github.com/npm/cli/commit/c3e1a7175c6475553e212e2f7671bd31bfe07aba) [#9532](https://github.com/npm/cli/pull/9532) add min-release-age-exclude config (@JamieMagee, @caseyjhol) +* [`5cd5150`](https://github.com/npm/cli/commit/5cd5150d3e85dcf5d246e7e5c9de216c2ff849db) [#9424](https://github.com/npm/cli/pull/9424) default-deny install scripts (allowScripts opt-in) [v12] (@JamieMagee) +* [`64e3f79`](https://github.com/npm/cli/commit/64e3f798344e66f4c500636cb8aec5c8111a1fe9) [#9480](https://github.com/npm/cli/pull/9480) allowScripts tooling and inBundle hardening (#9480) (@JamieMagee) +* [`caa3295`](https://github.com/npm/cli/commit/caa329568d32587e53f6e098f43b550dd2685034) [#9466](https://github.com/npm/cli/pull/9466) default allow-git and allow-remote to none (@owlstronaut) +* [`f2e4a28`](https://github.com/npm/cli/commit/f2e4a285ec5ed43055462a47db6d330758a16e64) [#9351](https://github.com/npm/cli/pull/9351) add a global npmignore file (#9351) (@ljharb) +* [`c9be2d1`](https://github.com/npm/cli/commit/c9be2d1efadd353e743bcebd52faaa5aa64e2fc0) [#9153](https://github.com/npm/cli/pull/9153) publish --access=private alias for restricted (#9153) (@reggi, @Copilot) +* [`7068d42`](https://github.com/npm/cli/commit/7068d4286eb446fdb0ded08d15d7b5c3883d80f5) [#9360](https://github.com/npm/cli/pull/9360) Phase 1 of `allowScripts` opt-in install-script policy (#9360) (@JamieMagee) +* [`979518d`](https://github.com/npm/cli/commit/979518dd198b9f2beb788c6c3cdcd1e055b03d22) [#9276](https://github.com/npm/cli/pull/9276) error on unknown configs, flags, and abbreviations (#9276) (@owlstronaut) ### Bug Fixes - -* [`3101a40`](https://github.com/npm/cli/commit/3101a4045bd7030f232d6cb2ae61339214968321) [#7631](https://github.com/npm/cli/pull/7631) limit concurrent open files during 'npm cache verify' (#7631) (@oikumene) -* [`2273183`](https://github.com/npm/cli/commit/22731831e22011e32fa0ca12178e242c2ee2b33d) [#7595](https://github.com/npm/cli/pull/7595) outdated: fixed wanted range for alias with version range (#7595) (@milaninfy) -* [`15be6dd`](https://github.com/npm/cli/commit/15be6dd33bfab8bdfaf8c3dece435d7139c1bf6d) [#7574](https://github.com/npm/cli/pull/7574) don't try parsing workspaces if none exist (@wraithgar) - +* [`e96a7de`](https://github.com/npm/cli/commit/e96a7decbd00d637ec8d9121c62cef2930abbb69) [#8703](https://github.com/npm/cli/pull/8703) Preserve https protocol when working with git (#8703) (@oldium) +* [`a847d28`](https://github.com/npm/cli/commit/a847d28d787f4f864de00ad1fd3344ccac016c62) [#9575](https://github.com/npm/cli/pull/9575) patch: warn when `patch update --to` targets an uninstalled version (#9575) (@manzoorwanijk) +* [`62b0694`](https://github.com/npm/cli/commit/62b0694d5ec4c529076bf968c3fe6cd47c3f2bb0) [#9576](https://github.com/npm/cli/pull/9576) patch: explain out-of-sync lockfile after --ignore-patch-failures (#9576) (@manzoorwanijk) +* [`5ddf6cc`](https://github.com/npm/cli/commit/5ddf6ccce5255d35da217d3e7342dde2bcb478d1) [#9567](https://github.com/npm/cli/pull/9567) patch: keep the update marker on a no-op commit so a retry finalizes (#9567) (@manzoorwanijk) +* [`fc3ef5a`](https://github.com/npm/cli/commit/fc3ef5a096854a73817af407fabb5eb5f98b50b1) [#9559](https://github.com/npm/cli/pull/9559) adapt to @npmcli/run-script@11 breaking changes (@owlstronaut) +* [`abf78b3`](https://github.com/npm/cli/commit/abf78b3c143a1825de910c0e401d01c0d3f5199b) [#9540](https://github.com/npm/cli/pull/9540) match dotted and versioned args in approve-scripts/deny-scripts (@owlstronaut) +* [`f6270d1`](https://github.com/npm/cli/commit/f6270d1069dcf60b4798f83eb87b6580162902e6) [#9531](https://github.com/npm/cli/pull/9531) emit valid JSON from approve-scripts/deny-scripts --json (@owlstronaut) +* [`0e55f97`](https://github.com/npm/cli/commit/0e55f97deea0f2395196dd572fac5fd7c9fbee38) [#9492](https://github.com/npm/cli/pull/9492) pass script-shell to publish lifecycle hooks (@Zelys-DFKH) +* [`2cbb13b`](https://github.com/npm/cli/commit/2cbb13b77edd9410704eac6f30ffea30a18c7046) [#9490](https://github.com/npm/cli/pull/9490) recognize allowScripts for local link targets (#9490) (@cyphercodes, @cyphercodes) +* [`bf623e0`](https://github.com/npm/cli/commit/bf623e0a9ea568a47b777c563e48a097cb12e442) [#9473](https://github.com/npm/cli/pull/9473) validate registry path for allow-remote tarballs (@Abhinav-143x) +* [`6be874b`](https://github.com/npm/cli/commit/6be874b88174e87f004b31cbbdda54d0d50cb399) [#9479](https://github.com/npm/cli/pull/9479) list pending scripts in approve-scripts when ignore-scripts is set (#9479) (@JamieMagee) +* [`6603b2c`](https://github.com/npm/cli/commit/6603b2c5fdbb5d4ec504199b2f10b5b378168016) [#9469](https://github.com/npm/cli/pull/9469) suggest --allow-scripts for global installs in unreviewed-scripts warnings (#9469) (@JamieMagee) +* [`fe820b6`](https://github.com/npm/cli/commit/fe820b6f2bbac9fdb3c8937d6d5bf6544bac55fc) [#9442](https://github.com/npm/cli/pull/9442) invalid issue template YAML indentation (#9442) (@fallintoplace) +* [`fe41ae7`](https://github.com/npm/cli/commit/fe41ae7c6b38e7e9957b646bf379e2b5daae03f9) [#9404](https://github.com/npm/cli/pull/9404) show full parent command path in subcommand usage errors (#9404) (@shaanmajid) +* [`75bf7de`](https://github.com/npm/cli/commit/75bf7decec60da0e68296356b8da82d3eb18f0bc) [#9456](https://github.com/npm/cli/pull/9456) respect allowScripts policy in prune, dedupe, uninstall, audit fix, and link (@JamieMagee) +* [`6efac6e`](https://github.com/npm/cli/commit/6efac6ead98af50c5a40fc45cb657bbee496a584) [#9453](https://github.com/npm/cli/pull/9453) config: clarify --all help so it's accurate for approve-scripts and deny-scripts (@JamieMagee) +* [`b97edc0`](https://github.com/npm/cli/commit/b97edc0193017800ecb1f26d212977729ca19739) [#9430](https://github.com/npm/cli/pull/9430) audit: don't apply min-release-age before filter when verifying installed signatures (@JamieMagee) +* [`080e3b2`](https://github.com/npm/cli/commit/080e3b29e69d35d7b0f4823a9ac7ab4e1e4d1af6) [#9425](https://github.com/npm/cli/pull/9425) block forbidden keys in Queryable setter to prevent prototype pollution (@12122J, @claude) +* [`c5292fa`](https://github.com/npm/cli/commit/c5292fa8a09a56b25394d393faf21e47ffb096c0) [#9422](https://github.com/npm/cli/pull/9422) use prerelease strategy without a bug (@owlstronaut) +* [`33aebaa`](https://github.com/npm/cli/commit/33aebaa58541ac0af3882cc0b56f09b1b676740a) [#9410](https://github.com/npm/cli/pull/9410) fix typo of fullMetadata (@owlstronaut) +* [`2a03860`](https://github.com/npm/cli/commit/2a03860fcafe92b22770fc554b25994b29bacbdb) [#9267](https://github.com/npm/cli/pull/9267) run root preinstall before reify (@owlstronaut) +* [`c0fc549`](https://github.com/npm/cli/commit/c0fc54935af8e17a3a96cbdeac52bb4c597803b6) [#9372](https://github.com/npm/cli/pull/9372) config: pause progress spinner during interactive editor spawn (#9372) (@Zelys-DFKH, @claude) ### Documentation - -* [`ac937d4`](https://github.com/npm/cli/commit/ac937d4f29b27fb877f79f33034ee1144c7202c4) [#7616](https://github.com/npm/cli/pull/7616) install: add save-peer flag (#7616) (@drew4237) -* [`55639ef`](https://github.com/npm/cli/commit/55639efd2d3094ca0931ddf9276c93f6880cd6e6) [#7615](https://github.com/npm/cli/pull/7615) use git+https in package.com url examples (#7615) (@MikeMcC399) -* [`93883bb`](https://github.com/npm/cli/commit/93883bb6459208a916584cad8c6c72a315cf32af) [#7582](https://github.com/npm/cli/pull/7582) Improve manpage section for `package.json` `funding` properties (#7582) (@kemitchell) -* [`92e71e6`](https://github.com/npm/cli/commit/92e71e6b0c7889e243e6b54ef8b4eb9656de95f8) [#7576](https://github.com/npm/cli/pull/7576) fix links to community discussions (#7576) (@leobalter) - +* [`357e8cd`](https://github.com/npm/cli/commit/357e8cdcb8f44326a50cee2539219a91d8bfbbe5) [#9520](https://github.com/npm/cli/pull/9520) approve-scripts only throws EGLOBAL when run with -g (@JamieMagee) +* [`bcf01c6`](https://github.com/npm/cli/commit/bcf01c6b1889ac97cf0f8a339da298a64f0767ef) [#9505](https://github.com/npm/cli/pull/9505) clarify package.json override value specs (#9505) (@ded-furby) +* [`455aa4a`](https://github.com/npm/cli/commit/455aa4a17b92a77ffbd474c4dc17a16f71cfe6b1) [#9401](https://github.com/npm/cli/pull/9401) use the latest version for global update and outdated's `wanted` (#9401) (@liangmiQwQ) +* [`aac80dc`](https://github.com/npm/cli/commit/aac80dc00748863ed4bdec90a49e33b0d9d3ed93) [#9470](https://github.com/npm/cli/pull/9470) update minimum npm required for npm trust (@meeech) +* [`d124c08`](https://github.com/npm/cli/commit/d124c0858da0b138cda2addcb0987b063ca86a47) [#9385](https://github.com/npm/cli/pull/9385) Document `npm_old_version` and `npm_new_version` environment variables (#9385) (@36degrees) ### Dependencies - -* [`1c1adae`](https://github.com/npm/cli/commit/1c1adaeeb59401db32d3d1ac4074654c87cd6f25) [#7636](https://github.com/npm/cli/pull/7636) `npm-pick-manifest@9.1.0` -* [`5e4fa18`](https://github.com/npm/cli/commit/5e4fa18dc02cd6b99df51e220661d82b2db12c3d) [#7636](https://github.com/npm/cli/pull/7636) `socks-proxy-agent@8.0.4` -* [`d8fa116`](https://github.com/npm/cli/commit/d8fa116f142044d3774439cf64dd51e8acb5bcff) [#7636](https://github.com/npm/cli/pull/7636) `https-proxy-agent@7.0.5` -* [`76dab91`](https://github.com/npm/cli/commit/76dab917eb22f5079cbb8bc052ec7c5bb07e9389) [#7636](https://github.com/npm/cli/pull/7636) `normalize-package-data@6.0.2` -* [`094c4ea`](https://github.com/npm/cli/commit/094c4ea17398d092a8b2c631564209c10183d417) [#7636](https://github.com/npm/cli/pull/7636) `minimatch@9.0.5` -* [`1c8d41d`](https://github.com/npm/cli/commit/1c8d41ddafc5810511d54fd227ce964c503464e0) [#7636](https://github.com/npm/cli/pull/7636) `@npmcli/git@5.0.8` -* [`e5451e1`](https://github.com/npm/cli/commit/e5451e1e91d7a71546f21daca604fb956c1cac3f) [#7605](https://github.com/npm/cli/pull/7605) `jackspeak@3.4.0` -* [`7b584d3`](https://github.com/npm/cli/commit/7b584d3b60ff118fd04f3ee5693816d9e948ff1b) [#7605](https://github.com/npm/cli/pull/7605) `foreground-child@3.2.1` -* [`941d0d7`](https://github.com/npm/cli/commit/941d0d7b596ec4cc2d21f86fb03876e2c6360987) [#7605](https://github.com/npm/cli/pull/7605) `debug@4.3.5` -* [`8b8ce7a`](https://github.com/npm/cli/commit/8b8ce7a23543a4d28c850fa27cd411de68a74cfd) [#7605](https://github.com/npm/cli/pull/7605) `glob@10.4.2` -* [`4646768`](https://github.com/npm/cli/commit/46467680d0e75c95406e46b5e2f754d2b7df1f7b) [#7605](https://github.com/npm/cli/pull/7605) `npm-registry-fetch@17.1.0` -* [`6f0d7ce`](https://github.com/npm/cli/commit/6f0d7cec260993d269294e05e18eacf23935b78a) [#7605](https://github.com/npm/cli/pull/7605) `@npmcli/redact@2.0.1` -* [`29204c8`](https://github.com/npm/cli/commit/29204c8ad4be0a1ffbca6f40393b00278bb34b3e) [#7605](https://github.com/npm/cli/pull/7605) `@npmcli/package-json@5.2.0` -* [`04d6910`](https://github.com/npm/cli/commit/04d6910e474003762b4606837960b4eb10d7bcd9) [#7574](https://github.com/npm/cli/pull/7574) `@npmcli/package-json@5.1.1` -* [`4ef4830`](https://github.com/npm/cli/commit/4ef4830dd792c2f23d3ffc7a10f797fc4ac8e5cb) [#7574](https://github.com/npm/cli/pull/7574) remove read-package-json-fast -## [10.8.2](https://github.com/npm/cli/compare/v10.8.1...v10.8.2) (2024-07-09) - +* [`9cbba72`](https://github.com/npm/cli/commit/9cbba7258a41dd141eca070edcf661afc8ca159d) [#9579](https://github.com/npm/cli/pull/9579) `npm-profile@13.0.1` +* [`d4e0a70`](https://github.com/npm/cli/commit/d4e0a70f3231992f73ea4a80b60c81c103f421cb) [#9559](https://github.com/npm/cli/pull/9559) `@tufjs/repo-mock@5.0.0` +* [`3ef66bb`](https://github.com/npm/cli/commit/3ef66bb796f5029da2fdfc2a5dcf33585d67381f) [#9559](https://github.com/npm/cli/pull/9559) bundle arborist runtime deps for bootstrap +* [`5dce6fb`](https://github.com/npm/cli/commit/5dce6fb61493bf72a895f4b670cb8dec660b35db) [#9559](https://github.com/npm/cli/pull/9559) `npm-packlist@11.2.0` +* [`ad05528`](https://github.com/npm/cli/commit/ad055282671363fd72d3729fb2de020fbb319293) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/git@8.0.0` +* [`cc45055`](https://github.com/npm/cli/commit/cc450554861ec9f6ec8f1c4494fa9144379eb741) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/node-gyp@6.0.0` +* [`a12e2c8`](https://github.com/npm/cli/commit/a12e2c8f40e0d551e79f12df25e1f1d93ac90ac5) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/name-from-folder@5.0.0` +* [`cc96d57`](https://github.com/npm/cli/commit/cc96d57246df7cbcaedca6c2540d4e45190d9bb8) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/installed-package-contents@5.0.0` +* [`3dc18e5`](https://github.com/npm/cli/commit/3dc18e561b3304778f38f9e7637ab5e0b696797e) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/git@8.0.0` +* [`428afa6`](https://github.com/npm/cli/commit/428afa666b96b54a69ae72b25ab6fa48d3d19e61) [#9559](https://github.com/npm/cli/pull/9559) `sigstore@5.0.0` +* [`95ed19c`](https://github.com/npm/cli/commit/95ed19cd940f6cfef17279be2399f400694fbb00) [#9559](https://github.com/npm/cli/pull/9559) regenerate bundled dependencies +* [`b62db95`](https://github.com/npm/cli/commit/b62db95b7768049f58a0aca0d7266cba6ed17757) [#9559](https://github.com/npm/cli/pull/9559) `bin-links@7.0.0` +* [`2f5da83`](https://github.com/npm/cli/commit/2f5da83be1e90f00542f0445f06b142084f1ec5a) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/fs@6.0.0` +* [`370f9c6`](https://github.com/npm/cli/commit/370f9c6f069094fcb8b668fe7c9241106eef1bde) [#9559](https://github.com/npm/cli/pull/9559) `node-gyp@13.0.0` +* [`e459d7a`](https://github.com/npm/cli/commit/e459d7af61a5f3611a8faadd21d99e9440552368) [#9559](https://github.com/npm/cli/pull/9559) `which@7.0.0` +* [`5032af3`](https://github.com/npm/cli/commit/5032af36d7d1832f4ecb850f51d9b2b10d281336) [#9559](https://github.com/npm/cli/pull/9559) `validate-npm-package-name@8.0.0` +* [`13d97ac`](https://github.com/npm/cli/commit/13d97acea43ccab49eb7efeec8eda54a50f80c8c) [#9559](https://github.com/npm/cli/pull/9559) `tar@7.5.16` +* [`1502286`](https://github.com/npm/cli/commit/15022869509f110510fa8336144500108cdc6677) [#9559](https://github.com/npm/cli/pull/9559) `ssri@14.0.0` +* [`68eb39c`](https://github.com/npm/cli/commit/68eb39caa238479aa476beb71a9ec2ee2ea054d3) [#9559](https://github.com/npm/cli/pull/9559) `semver@7.8.4` +* [`3484d7f`](https://github.com/npm/cli/commit/3484d7f1cdb7595353562129e6ab6ef83204f227) [#9559](https://github.com/npm/cli/pull/9559) `read@6.0.0` +* [`21df0ab`](https://github.com/npm/cli/commit/21df0ab3c629496511a3c481ee721b0e62c16e92) [#9559](https://github.com/npm/cli/pull/9559) `proc-log@7.0.0` +* [`8f85646`](https://github.com/npm/cli/commit/8f856463d0e85f7083312b3825d0b72304f369e7) [#9559](https://github.com/npm/cli/pull/9559) `parse-conflict-json@6.0.0` +* [`a44c1cf`](https://github.com/npm/cli/commit/a44c1cf1635de5ecda02ed80af70f5d7360111b6) [#9559](https://github.com/npm/cli/pull/9559) `pacote@22.0.0` +* [`171bba3`](https://github.com/npm/cli/commit/171bba3011b45f6629b03f7ff3c59b71d09ab1fa) [#9559](https://github.com/npm/cli/pull/9559) `npm-user-validate@5.0.0` +* [`1f9c567`](https://github.com/npm/cli/commit/1f9c56792493f80fb3b3d61710086ed748312f2a) [#9559](https://github.com/npm/cli/pull/9559) `npm-registry-fetch@20.0.1` +* [`1fd247a`](https://github.com/npm/cli/commit/1fd247a79a814292db35d01d723c1fd05713707e) [#9559](https://github.com/npm/cli/pull/9559) `npm-profile@13.0.0` +* [`998ff1d`](https://github.com/npm/cli/commit/998ff1d50816061706c88c56664d131fcfe83f31) [#9559](https://github.com/npm/cli/pull/9559) `npm-pick-manifest@12.0.0` +* [`d80859a`](https://github.com/npm/cli/commit/d80859a2dd97376e4ea621812b3bc7de6a218d21) [#9559](https://github.com/npm/cli/pull/9559) `npm-package-arg@14.0.0` +* [`5e1d513`](https://github.com/npm/cli/commit/5e1d513b9c5e8eef7e318125bd2c34276ffe3858) [#9559](https://github.com/npm/cli/pull/9559) `npm-install-checks@9.0.0` +* [`faf97e5`](https://github.com/npm/cli/commit/faf97e5fadd5ae42ac3c92513df2c08654e9566b) [#9559](https://github.com/npm/cli/pull/9559) `npm-audit-report@8.0.0` +* [`471309f`](https://github.com/npm/cli/commit/471309f580efdf7f8055020ac0a08610f692a4f4) [#9559](https://github.com/npm/cli/pull/9559) `nopt@10.0.1` +* [`40395b8`](https://github.com/npm/cli/commit/40395b85e98596751a8b0a136c7687438339776f) [#9559](https://github.com/npm/cli/pull/9559) `make-fetch-happen@16.0.1` +* [`30e89d9`](https://github.com/npm/cli/commit/30e89d922c0ee790524151a98049aad47de70773) [#9559](https://github.com/npm/cli/pull/9559) `json-parse-even-better-errors@6.0.0` +* [`d44db96`](https://github.com/npm/cli/commit/d44db96fbc7b26fa6c53ed73eb8e1a267070a06c) [#9559](https://github.com/npm/cli/pull/9559) `is-cidr@7.0.0` +* [`350fb18`](https://github.com/npm/cli/commit/350fb188e9789ac7bb701fc9533ff9e271f87ee7) [#9559](https://github.com/npm/cli/pull/9559) `init-package-json@9.0.0` +* [`406820a`](https://github.com/npm/cli/commit/406820a15bc2c19543c7457a4331ea40ae8d0cf6) [#9559](https://github.com/npm/cli/pull/9559) `ini@7.0.0` +* [`d867351`](https://github.com/npm/cli/commit/d867351cf9d3b75956b555659040c56334f8f4c1) [#9559](https://github.com/npm/cli/pull/9559) `hosted-git-info@10.1.1` +* [`66d46bc`](https://github.com/npm/cli/commit/66d46bc23909f06433237985452c0102181e8fc9) [#9559](https://github.com/npm/cli/pull/9559) `cacache@21.0.1` +* [`0d15aec`](https://github.com/npm/cli/commit/0d15aecf3dbc918d599c2588b23f0c53e3637c95) [#9559](https://github.com/npm/cli/pull/9559) `abbrev@5.0.0` +* [`9bbdefb`](https://github.com/npm/cli/commit/9bbdefbfd54e59c8494d1467c89a3aee5f225423) [#9559](https://github.com/npm/cli/pull/9559) `@sigstore/tuf@5.0.0` +* [`9d13ebf`](https://github.com/npm/cli/commit/9d13ebfc2adca5543e4797632039adaa7a318985) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/run-script@11.0.0` +* [`27c4dcc`](https://github.com/npm/cli/commit/27c4dcc7e4aa3521563c1af80617e7697d88cd16) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/redact@5.0.0` +* [`f0eaef3`](https://github.com/npm/cli/commit/f0eaef370ab7ff0be1cfd833a6986f8ef0378a4c) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/promise-spawn@10.0.0` +* [`0be6ae2`](https://github.com/npm/cli/commit/0be6ae21c79eb3986a76d5d769d5dd5ef00283c2) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/package-json@8.0.0` +* [`f86a019`](https://github.com/npm/cli/commit/f86a0198bec5a70153bbb29d276fddb30c682792) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/metavuln-calculator@10.0.0` +* [`4d234b2`](https://github.com/npm/cli/commit/4d234b22e59416f6307eb75bef52ac9b43ee6628) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/map-workspaces@6.0.0` +* [`d28783e`](https://github.com/npm/cli/commit/d28783e3f00feecf4ca76b497e80ffd281af1655) [#9420](https://github.com/npm/cli/pull/9420) `undici@6.26.0` +* [`7f6c6ef`](https://github.com/npm/cli/commit/7f6c6ef49023286bed47a334cc2bd0064cb8ec05) [#9420](https://github.com/npm/cli/pull/9420) `sigstore@4.1.1` +* [`ee61b6e`](https://github.com/npm/cli/commit/ee61b6e8279b1d26d28a47613d66a9deb5c06529) [#9420](https://github.com/npm/cli/pull/9420) `lru-cache@11.5.1` +* [`d5ddef2`](https://github.com/npm/cli/commit/d5ddef2571b5b26dfade31eb040dbd4a096aeed8) [#9420](https://github.com/npm/cli/pull/9420) `@sigstore/verify@3.1.1` +* [`11e7ac7`](https://github.com/npm/cli/commit/11e7ac72c3ea0490f8d5edfb4bd5a60729d25b66) [#9420](https://github.com/npm/cli/pull/9420) `@sigstore/core@3.2.1` +* [`11cd66e`](https://github.com/npm/cli/commit/11cd66e10490af0ef46ceeb5e8764a855580a2de) [#9420](https://github.com/npm/cli/pull/9420) `@npmcli/agent@4.0.2` +* [`8be4c04`](https://github.com/npm/cli/commit/8be4c046fbbbb8ede02a288b727fcbf7470956fb) [#9420](https://github.com/npm/cli/pull/9420) `semver@7.8.1` +* [`577d61d`](https://github.com/npm/cli/commit/577d61da646833994ecfda8b2f1dc993ec9b58d1) [#9420](https://github.com/npm/cli/pull/9420) `make-fetch-happen@15.0.6` +### Chores +* [`059c06e`](https://github.com/npm/cli/commit/059c06e52f00e2d9cd2fa28baf6a6acd5be3b297) [#9560](https://github.com/npm/cli/pull/9560) add web-login proxy doneUrl regression for npm-profile fix (#9560) (@manzoorwanijk) +* [`1453954`](https://github.com/npm/cli/commit/1453954f9328a6b2480c183f9d1903ac93764915) [#9559](https://github.com/npm/cli/pull/9559) `nock@14.0.0` (@owlstronaut) +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`acdd6d5`](https://github.com/npm/cli/commit/acdd6d57fc90312ceb2eabfda21e05e9da1c1477) [#9559](https://github.com/npm/cli/pull/9559) bumping @npmcli/template-oss from 4.29.0 to 5.1.0 (@owlstronaut) +* [`4e2496a`](https://github.com/npm/cli/commit/4e2496a6a7ae015483dd9ff9072830c939baddff) [#9513](https://github.com/npm/cli/pull/9513) update issue templates - better language (@owlstronaut) +* [`7a997ac`](https://github.com/npm/cli/commit/7a997ac48ead642efcbb48fc5da5d99f0c850389) [#9512](https://github.com/npm/cli/pull/9512) update issue templates (#9512) (@owlstronaut) +* [`da63c79`](https://github.com/npm/cli/commit/da63c79be758fd9d3faa9f5edf962219c805c579) [#9420](https://github.com/npm/cli/pull/9420) dev dependency updates (@owlstronaut) +* [`5fc9bc0`](https://github.com/npm/cli/commit/5fc9bc0f202aadedd7b123394560047671afca6b) [#9393](https://github.com/npm/cli/pull/9393) sanitize newlines in flags table default and type values (#9393) (@reggi, @Copilot) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v10.0.0-pre.1): `@npmcli/arborist@10.0.0-pre.1` +* [workspace](https://github.com/npm/cli/releases/tag/config-v11.0.0-pre.1): `@npmcli/config@11.0.0-pre.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v11.0.0-pre.0): `libnpmaccess@11.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v9.0.0-pre.0): `libnpmdiff@9.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v11.0.0-pre.0): `libnpmexec@11.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v8.0.0-pre.0): `libnpmfund@8.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmorg-v9.0.0-pre.0): `libnpmorg@9.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v10.0.0-pre.1): `libnpmpack@10.0.0-pre.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v12.0.0-pre.0): `libnpmpublish@12.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmsearch-v10.0.0-pre.0): `libnpmsearch@10.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmteam-v9.0.0-pre.0): `libnpmteam@9.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v9.0.0-pre.1): `libnpmversion@9.0.0-pre.1` + +## [12.0.0-pre.0.0](https://github.com/npm/cli/compare/v11.12.1...v12.0.0-pre.0.0) (2026-05-20) +### ⚠️ BREAKING CHANGES +* npm view --json now always returns an array. +* `npm sbom --sbom-format=cyclonedx` now reports the `name` field from each package's `package.json` instead of the on-disk directory name. The `name`, `bom-ref`, and `purl` of the root component and of aliased dependencies may change. +* npm no longer registers man pages with the system when installed globally. `man npm-install` will no longer work, but `npm help install` is unaffected. +* The `npm pkg` output is no longer forced to json. This means you can get single values without having to worry about wrapping of the values. It also outputs non-json content more similarly to `npm view`. +* `npm shrinkwrap` is removed, the `shrinkwrap` config alias is removed, and `npm-shrinkwrap.json` is no longer loaded or honored at the project root or from inside dependency tarballs. Rename project-root `npm-shrinkwrap.json` to `package-lock.json`; use `bundleDependencies` if you need to ship a locked dependency tree. +* The Twitter and Freenode profile fields have been removed from the npm registry. This means that users will no longer be able to set or view these fields in their npm profiles. +* npm will no longer attempt to resolve the path to node via whichnode. process.execPath is already set by Node to the resolved real path of the node binary, so the lookup was redundant. Scripts that expected npm to override process.execPath with a PATH-resolved (potentially symlinked) node path may be affected. +* the --json output of `npm pack` and `npm publish` have changed. They are now always consistent, and in the same format. +* the `star`, `stars` and `unstar` commands have been removed +* The `npm adduser` command has been removed. Create and manage user accounts on the npm website, and use `npm login` to authenticate on the command line. +### Features +* [`254809e`](https://github.com/npm/cli/commit/254809e318ee0046092d07d68a99154c3f672147) [#9201](https://github.com/npm/cli/pull/9201) npm stage (#9201) (@reggi, @Copilot) +* [`cf94dbe`](https://github.com/npm/cli/commit/cf94dbe2432251623966bb7be1c6ded15ea97e14) [#9248](https://github.com/npm/cli/pull/9248) add permissions support to trust commands (#9248) (@reggi, @Copilot) +* [`e0f12f7`](https://github.com/npm/cli/commit/e0f12f7e57aca36f71c9615bd971f427ed23e91a) [#9348](https://github.com/npm/cli/pull/9348) add allow-git/allow-file/allow-directory/allow-remote configs (@owlstronaut) +* [`916cb4b`](https://github.com/npm/cli/commit/916cb4b262df1d188ce7644e916b138fbc78c4e7) [#9287](https://github.com/npm/cli/pull/9287) add allow-directory, allow-file, and allow-remote (#9287) (@wraithgar) +* [`2e5dcad`](https://github.com/npm/cli/commit/2e5dcad17a59ee9f69eeec27fc5b087b5b032df7) [#9262](https://github.com/npm/cli/pull/9262) drop npm-shrinkwrap.json support (@owlstronaut) +* [`2397196`](https://github.com/npm/cli/commit/239719668a73afbacc02eedcedcd3d3dd7f36b01) [#9265](https://github.com/npm/cli/pull/9265) Remove Twitter and Freenode profile fields (@owlstronaut) +* [`738be10`](https://github.com/npm/cli/commit/738be10651522e94038f1eff0da12f15b10438ea) [#9196](https://github.com/npm/cli/pull/9196) remove star commands (#9196) (@wraithgar) +* [`db7c1f8`](https://github.com/npm/cli/commit/db7c1f887eb1c1cb281ea7c9f6d84fba8f10d44d) [#9163](https://github.com/npm/cli/pull/9163) add `u` as alias for `update` command (#9163) (@Ausoj) +* [`45e44dd`](https://github.com/npm/cli/commit/45e44dd7ac2a3af815684ece3bdc99ada2f317f7) [#9228](https://github.com/npm/cli/pull/9228) adds a backport script (@owlstronaut) ### Bug Fixes - -* [`3101a40`](https://github.com/npm/cli/commit/3101a4045bd7030f232d6cb2ae61339214968321) [#7631](https://github.com/npm/cli/pull/7631) limit concurrent open files during 'npm cache verify' (#7631) (@oikumene) -* [`2273183`](https://github.com/npm/cli/commit/22731831e22011e32fa0ca12178e242c2ee2b33d) [#7595](https://github.com/npm/cli/pull/7595) outdated: fixed wanted range for alias with version range (#7595) (@milaninfy) -* [`15be6dd`](https://github.com/npm/cli/commit/15be6dd33bfab8bdfaf8c3dece435d7139c1bf6d) [#7574](https://github.com/npm/cli/pull/7574) don't try parsing workspaces if none exist (@wraithgar) - +* [`2a13550`](https://github.com/npm/cli/commit/2a1355011540a06eac841c04136f07cdf086fd75) [#9380](https://github.com/npm/cli/pull/9380) key stage download --json output by package name (#9380) (@reggi, @Copilot) +* [`ca585c8`](https://github.com/npm/cli/commit/ca585c80dee759fedb85c5c20f9dd3ea8d017be4) [#9368](https://github.com/npm/cli/pull/9368) allow min-release-age in npmrc to coexist with --before (@raazkhnl) +* [`f550eb4`](https://github.com/npm/cli/commit/f550eb415de0aff83a5fa297850104f5390a6e30) [#9348](https://github.com/npm/cli/pull/9348) refactor #failureNode, adjust tests and safety (@owlstronaut) +* [`1f17566`](https://github.com/npm/cli/commit/1f17566ad90353b88e81fa1f8a4da5879d3ec7a3) [#9348](https://github.com/npm/cli/pull/9348) allow-remote=none does not block registry tarballs (@owlstronaut) +* [`70af7b3`](https://github.com/npm/cli/commit/70af7b3c727fed6c7078d4ff7177fe02349e9b65) [#9327](https://github.com/npm/cli/pull/9327) remove settings (#9327) (@owlstronaut) +* [`d623988`](https://github.com/npm/cli/commit/d6239889dc9b4eff776cd2a258fbaf5b645f5585) [#9311](https://github.com/npm/cli/pull/9311) sbom: dedupe per-node dependsOn / relationships (#9311) (@mikaelkristiansson) +* [`d36945d`](https://github.com/npm/cli/commit/d36945dec26ffdc6899b3dc561260cd1b980a2f8) [#9160](https://github.com/npm/cli/pull/9160) do not unwrap single-item arrays in --json output (@yetanotheraryan) +* [`faf7348`](https://github.com/npm/cli/commit/faf7348549c418de3c2a5be26f0a882e7189b5b2) [#9284](https://github.com/npm/cli/pull/9284) align CycloneDX SBOM component names with SPDX (#9284) (@cyphercodes, @cyphercodes) +* [`e20424b`](https://github.com/npm/cli/commit/e20424b01a2d60c6ff5edb0480dcea529edf2dec) [#9035](https://github.com/npm/cli/pull/9035) don't install man pages in system locations (@owlstronaut) +* [`01d9acd`](https://github.com/npm/cli/commit/01d9acd41c357f6b607d026bf5bc1cc44ad92db6) [#9269](https://github.com/npm/cli/pull/9269) pkg: output like npm view does, do not force json output (@wraithgar) +* [`27567ab`](https://github.com/npm/cli/commit/27567ab27bef8af303bde0b2d7da0386da182b81) [#9257](https://github.com/npm/cli/pull/9257) ignore intended error code (@owlstronaut) +* [`4ef5b6e`](https://github.com/npm/cli/commit/4ef5b6e0439297048dee92729b5c93529ad39488) [#9039](https://github.com/npm/cli/pull/9039) stop resolving node path via whichnode (@owlstronaut) +* [`2e9b26e`](https://github.com/npm/cli/commit/2e9b26eff18114b2fe34ea7c8159500b5eafb98e) [#9247](https://github.com/npm/cli/pull/9247) sync json output of pack and publish (#9247) (@wraithgar) +* [`7357d7f`](https://github.com/npm/cli/commit/7357d7fd82a61657618d632b5a842d4d04335be5) [#9036](https://github.com/npm/cli/pull/9036) remove npm adduser command (@owlstronaut) ### Documentation - -* [`ac937d4`](https://github.com/npm/cli/commit/ac937d4f29b27fb877f79f33034ee1144c7202c4) [#7616](https://github.com/npm/cli/pull/7616) install: add save-peer flag (#7616) (@drew4237) -* [`55639ef`](https://github.com/npm/cli/commit/55639efd2d3094ca0931ddf9276c93f6880cd6e6) [#7615](https://github.com/npm/cli/pull/7615) use git+https in package.com url examples (#7615) (@MikeMcC399) -* [`93883bb`](https://github.com/npm/cli/commit/93883bb6459208a916584cad8c6c72a315cf32af) [#7582](https://github.com/npm/cli/pull/7582) Improve manpage section for `package.json` `funding` properties (#7582) (@kemitchell) -* [`92e71e6`](https://github.com/npm/cli/commit/92e71e6b0c7889e243e6b54ef8b4eb9656de95f8) [#7576](https://github.com/npm/cli/pull/7576) fix links to community discussions (#7576) (@leobalter) - +* [`c97b39b`](https://github.com/npm/cli/commit/c97b39b1e3436cd20a67ab5f4012a5f395c538b9) [#9363](https://github.com/npm/cli/pull/9363) add example to optionalDependencies section (#9363) (@verifizieren) +* [`6704ab2`](https://github.com/npm/cli/commit/6704ab2c8a025800d871571889466e06399bf6a2) [#9335](https://github.com/npm/cli/pull/9335) npm view with json outputs array docs update (#9335) (@yetanotheraryan) ### Dependencies - -* [`1c1adae`](https://github.com/npm/cli/commit/1c1adaeeb59401db32d3d1ac4074654c87cd6f25) [#7636](https://github.com/npm/cli/pull/7636) `npm-pick-manifest@9.1.0` -* [`5e4fa18`](https://github.com/npm/cli/commit/5e4fa18dc02cd6b99df51e220661d82b2db12c3d) [#7636](https://github.com/npm/cli/pull/7636) `socks-proxy-agent@8.0.4` -* [`d8fa116`](https://github.com/npm/cli/commit/d8fa116f142044d3774439cf64dd51e8acb5bcff) [#7636](https://github.com/npm/cli/pull/7636) `https-proxy-agent@7.0.5` -* [`76dab91`](https://github.com/npm/cli/commit/76dab917eb22f5079cbb8bc052ec7c5bb07e9389) [#7636](https://github.com/npm/cli/pull/7636) `normalize-package-data@6.0.2` -* [`094c4ea`](https://github.com/npm/cli/commit/094c4ea17398d092a8b2c631564209c10183d417) [#7636](https://github.com/npm/cli/pull/7636) `minimatch@9.0.5` -* [`1c8d41d`](https://github.com/npm/cli/commit/1c8d41ddafc5810511d54fd227ce964c503464e0) [#7636](https://github.com/npm/cli/pull/7636) `@npmcli/git@5.0.8` -* [`e5451e1`](https://github.com/npm/cli/commit/e5451e1e91d7a71546f21daca604fb956c1cac3f) [#7605](https://github.com/npm/cli/pull/7605) `jackspeak@3.4.0` -* [`7b584d3`](https://github.com/npm/cli/commit/7b584d3b60ff118fd04f3ee5693816d9e948ff1b) [#7605](https://github.com/npm/cli/pull/7605) `foreground-child@3.2.1` -* [`941d0d7`](https://github.com/npm/cli/commit/941d0d7b596ec4cc2d21f86fb03876e2c6360987) [#7605](https://github.com/npm/cli/pull/7605) `debug@4.3.5` -* [`8b8ce7a`](https://github.com/npm/cli/commit/8b8ce7a23543a4d28c850fa27cd411de68a74cfd) [#7605](https://github.com/npm/cli/pull/7605) `glob@10.4.2` -* [`4646768`](https://github.com/npm/cli/commit/46467680d0e75c95406e46b5e2f754d2b7df1f7b) [#7605](https://github.com/npm/cli/pull/7605) `npm-registry-fetch@17.1.0` -* [`6f0d7ce`](https://github.com/npm/cli/commit/6f0d7cec260993d269294e05e18eacf23935b78a) [#7605](https://github.com/npm/cli/pull/7605) `@npmcli/redact@2.0.1` -* [`29204c8`](https://github.com/npm/cli/commit/29204c8ad4be0a1ffbca6f40393b00278bb34b3e) [#7605](https://github.com/npm/cli/pull/7605) `@npmcli/package-json@5.2.0` -* [`04d6910`](https://github.com/npm/cli/commit/04d6910e474003762b4606837960b4eb10d7bcd9) [#7574](https://github.com/npm/cli/pull/7574) `@npmcli/package-json@5.1.1` -* [`4ef4830`](https://github.com/npm/cli/commit/4ef4830dd792c2f23d3ffc7a10f797fc4ac8e5cb) [#7574](https://github.com/npm/cli/pull/7574) remove read-package-json-fast - -### Chores - -* [`2490b49`](https://github.com/npm/cli/commit/2490b492cc8d9a351841d2c643b13a47a3254f41) [#7621](https://github.com/npm/cli/pull/7621) remove .github/workflows/benchmark.yml (#7621) (@wraithgar) -* [`3b8b111`](https://github.com/npm/cli/commit/3b8b11161ee2f88817dcc19b4770040d5bc73261) [#7605](https://github.com/npm/cli/pull/7605) update devDependencies in lockfile (@wraithgar) - +* [`d151521`](https://github.com/npm/cli/commit/d1515210085586c147a6653cdc6ae25f672d45db) [#9382](https://github.com/npm/cli/pull/9382) `socks@2.8.9` +* [`a77416e`](https://github.com/npm/cli/commit/a77416ee08e8884f35b1a2390ee98f6b570b3a0d) [#9382](https://github.com/npm/cli/pull/9382) `lru-cache@11.5.0` +* [`b2717e4`](https://github.com/npm/cli/commit/b2717e46e4ea6c70b137f68b37440ef7f016bc66) [#9382](https://github.com/npm/cli/pull/9382) `ip-address@10.2.0` +* [`1c4a796`](https://github.com/npm/cli/commit/1c4a79667af9703ede9683c2cc0f33b05983b724) [#9382](https://github.com/npm/cli/pull/9382) `brace-expansion@5.0.6` +* [`e36a4e3`](https://github.com/npm/cli/commit/e36a4e3f237d0e60d7b85490da8ff8e3663fdea9) [#9382](https://github.com/npm/cli/pull/9382) `bin-links@6.0.2` +* [`91bd674`](https://github.com/npm/cli/commit/91bd674ff822adc0f84bb79069e8b21d640bb40e) [#9382](https://github.com/npm/cli/pull/9382) `tar@7.5.15` +* [`66c7ff1`](https://github.com/npm/cli/commit/66c7ff1e66e3d0bf5b9ed5cae172ac6a7501ce4c) [#9382](https://github.com/npm/cli/pull/9382) `semver@7.8.0` +* [`514c71b`](https://github.com/npm/cli/commit/514c71b253f7e91afc3aa17a28aa6cb6f7d01b30) [#9382](https://github.com/npm/cli/pull/9382) `hosted-git-info@9.0.3` +* [`fbe1dd0`](https://github.com/npm/cli/commit/fbe1dd03a9a4b0690725df8ca40e96c49a0319ac) [#9316](https://github.com/npm/cli/pull/9316) `socks@10.1.1` +* [`af65766`](https://github.com/npm/cli/commit/af65766bd2d18923e5d24cc86f6a0e502450db33) [#9316](https://github.com/npm/cli/pull/9316) `ip-address@10.1.1` +* [`37bd0c6`](https://github.com/npm/cli/commit/37bd0c63a176ca8fe7012c08b8acbebff2e65865) [#9316](https://github.com/npm/cli/pull/9316) `cidr-regex@5.0.5` +* [`5af02ec`](https://github.com/npm/cli/commit/5af02ecf3e3ed27e62b57ceaf59a293f42d3e309) [#9270](https://github.com/npm/cli/pull/9270) `lru-cache@11.3.5` +* [`799866f`](https://github.com/npm/cli/commit/799866f4d877241cdd30501229901a0ba355adbb) [#9270](https://github.com/npm/cli/pull/9270) `node-gyp@12.3.0` +* [`79d394e`](https://github.com/npm/cli/commit/79d394e9f5e74b6fba3adb09e4bfd6e7b63e9839) [#9270](https://github.com/npm/cli/pull/9270) `is-cidr@6.0.4` +* [`9669d31`](https://github.com/npm/cli/commit/9669d31060a2ed7220e140c354a45cfe993a0e7d) [#9207](https://github.com/npm/cli/pull/9207) `@sigstore/protobuf-specs@0.5.1` +* [`b09a5ac`](https://github.com/npm/cli/commit/b09a5ac3c59f6a70f05ee035c9c6ee03dfdd1eda) [#9207](https://github.com/npm/cli/pull/9207) `tinyglobby@0.2.16` +* [`150231d`](https://github.com/npm/cli/commit/150231d74a90ff1fb34ec588eefb94aeb4979fd2) [#9207](https://github.com/npm/cli/pull/9207) `picomatch@4.0.4` +* [`413e0a0`](https://github.com/npm/cli/commit/413e0a00aee08b4f190bffd360b53efb20783ad1) [#9207](https://github.com/npm/cli/pull/9207) `lru-cache@11.3.3` +* [`6faa25e`](https://github.com/npm/cli/commit/6faa25ecff4eb72aa9c16adba53bf46d39d556df) [#9207](https://github.com/npm/cli/pull/9207) `diff@8.0.4` +* [`87bb9d0`](https://github.com/npm/cli/commit/87bb9d069375e74354bcd69f39a081ad960009de) [#9207](https://github.com/npm/cli/pull/9207) `minimatch@10.2.5` +* [`2501dd8`](https://github.com/npm/cli/commit/2501dd83ea9e9fc39b0bf6814728a132dd57fa6d) [#9207](https://github.com/npm/cli/pull/9207) `tar@7.5.13` +* [`ccce5f6`](https://github.com/npm/cli/commit/ccce5f611daf50727a134ba1df46ac9c53caa61a) [#9207](https://github.com/npm/cli/pull/9207) `minipass-flush@1.0.6` ### Chores - -* [`2490b49`](https://github.com/npm/cli/commit/2490b492cc8d9a351841d2c643b13a47a3254f41) [#7621](https://github.com/npm/cli/pull/7621) remove .github/workflows/benchmark.yml (#7621) (@wraithgar) -* [`3b8b111`](https://github.com/npm/cli/commit/3b8b11161ee2f88817dcc19b4770040d5bc73261) [#7605](https://github.com/npm/cli/pull/7605) update devDependencies in lockfile (@wraithgar) - -## [10.8.1](https://github.com/npm/cli/compare/v10.8.0...v10.8.1) (2024-05-29) - +* [`f502c4f`](https://github.com/npm/cli/commit/f502c4f07fb14eef041f4dfb04ad5d9f287c6ba4) [#9382](https://github.com/npm/cli/pull/9382) dev dependency updates (@owlstronaut) +* [`4259e57`](https://github.com/npm/cli/commit/4259e57f26640a137b38cb7e0b1eda04e6c42026) [#9316](https://github.com/npm/cli/pull/9316) dev dependency updates (@owlstronaut) +* [`d68bd36`](https://github.com/npm/cli/commit/d68bd365960da9933b215c87b3335b0b8d9b2bda) [#9317](https://github.com/npm/cli/pull/9317) add cli-triage team as codeowner (#9317) (@owlstronaut) +* [`b9332e6`](https://github.com/npm/cli/commit/b9332e6370cb4c3ee32c7b87cfab5847f4657acc) [#9270](https://github.com/npm/cli/pull/9270) dev dependency updates (@owlstronaut) +* [`cc468a8`](https://github.com/npm/cli/commit/cc468a81fd9fc000dc430c782ba05f0c6fcea079) [#9269](https://github.com/npm/cli/pull/9269) refactor tests (@wraithgar) +* [`2ca36c4`](https://github.com/npm/cli/commit/2ca36c4b37f50419303db41cf482d05f5ec69023) [#9261](https://github.com/npm/cli/pull/9261) fixed non-functional typos throughout the codebase (@opensourcezeal) +* [`8131de4`](https://github.com/npm/cli/commit/8131de4453af45a351fd610a660a1d60724ef74f) [#9239](https://github.com/npm/cli/pull/9239) add action permission for backport workflow (@owlstronaut) +* [`6df5f91`](https://github.com/npm/cli/commit/6df5f918a350e30d865a647cbbbe0a8e713d0189) [#9232](https://github.com/npm/cli/pull/9232) backports can trigger CI (@owlstronaut) +* [`07552f5`](https://github.com/npm/cli/commit/07552f58111dea3aa563693ea103342fb625d47b) [#9224](https://github.com/npm/cli/pull/9224) don't run npm update in CI (@owlstronaut) +* [`05dbba5`](https://github.com/npm/cli/commit/05dbba5b8d727ddb2c098ce0553714eae791c5f2) [#9195](https://github.com/npm/cli/pull/9195) enable prerelease mode (#9195) (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v10.0.0-pre.0.0): `@npmcli/arborist@10.0.0-pre.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/config-v11.0.0-pre.0.0): `@npmcli/config@11.0.0-pre.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.1.6-pre.0.0): `libnpmdiff@8.1.6-pre.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.2.6-pre.0.0): `libnpmexec@10.2.6-pre.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.20-pre.0.0): `libnpmfund@7.0.20-pre.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v10.0.0-pre.0.0): `libnpmpack@10.0.0-pre.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v11.2.0-pre.0.0): `libnpmpublish@11.2.0-pre.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v9.0.0-pre.0.0): `libnpmversion@9.0.0-pre.0.0` + +## [11.12.1](https://github.com/npm/cli/compare/v11.12.0...v11.12.1) (2026-03-24) ### Bug Fixes - -* [`6b55646`](https://github.com/npm/cli/commit/6b556468f9d6ed62c681954bfe6ad012315e3b53) [#7569](https://github.com/npm/cli/pull/7569) exec: look in workspace and root for bin entries (#7569) (@wraithgar) -* [`e4c7a41`](https://github.com/npm/cli/commit/e4c7a410f590e5c9c81f6410f600181a4deef005) [#7564](https://github.com/npm/cli/pull/7564) publish: skip workspace packages marked private on publish (#7564) (@milaninfy) -* [`8f94ae8`](https://github.com/npm/cli/commit/8f94ae8c4d36cd397c53e8dc9f54d4332bf1b847) [#7556](https://github.com/npm/cli/pull/7556) utils/tar: index access while match is null (#7555) (#7556) (@NormanPerrin) -* [`2d1d8d0`](https://github.com/npm/cli/commit/2d1d8d0ef18a10ac7938380884745f1d3c3cb078) [#7559](https://github.com/npm/cli/pull/7559) adds `node:` specifier to all native node modules (#7559) (@reggi) -* [`7d89b55`](https://github.com/npm/cli/commit/7d89b55341160459e0fcd3374c3720d758b16339) [#7490](https://github.com/npm/cli/pull/7490) ci: rm workspace node_modules (#7490) (@reggi) -* [`9122fb6`](https://github.com/npm/cli/commit/9122fb65ac05d793a69f4fdcbd03b59595adf937) [#7516](https://github.com/npm/cli/pull/7516) cache: add both full and minified packument to cache (#7516) (@milaninfy) -* [`9e6686b`](https://github.com/npm/cli/commit/9e6686bb965fa6843ea483cb802f14282eabf3e5) [#7545](https://github.com/npm/cli/pull/7545) send proper otp token on web auth (#7545) (@wraithgar) -* [`b1db070`](https://github.com/npm/cli/commit/b1db070cb4a497fd91fd61cf197d28b5d47274bb) [#7534](https://github.com/npm/cli/pull/7534) refactor: use output.buffer and set explicit json mode in query (#7534) (@lukekarrys) -* [`53cda32`](https://github.com/npm/cli/commit/53cda32aa35f3a592fb0ddf37e43c028f93ef613) [#7542](https://github.com/npm/cli/pull/7542) refactor ls to use output.buffer for json (#7542) (@lukekarrys) -* [`61d5771`](https://github.com/npm/cli/commit/61d57719e6443978c5e9a91ca7a63397be3065fa) [#7541](https://github.com/npm/cli/pull/7541) remove json.stringify from all commands (#7541) (@lukekarrys) -* [`4dfc7d2`](https://github.com/npm/cli/commit/4dfc7d20b58eaa3d231ef5dc86b9802e1c0d0e68) [#7540](https://github.com/npm/cli/pull/7540) pass strings to JSON.stringify in --json mode (#7540) (@lukekarrys) -* [`3cefdf6`](https://github.com/npm/cli/commit/3cefdf6eaab5bfb4371149f674dc95e9b9c54853) [#7538](https://github.com/npm/cli/pull/7538) outdated: return array for outdated deps from multiple workspaces (@lukekarrys) -* [`ef4c975`](https://github.com/npm/cli/commit/ef4c975f2784f70ab86a3e7e6e40c99279e5a3e3) [#7508](https://github.com/npm/cli/pull/7508) view: dont immediately exit on first workspace 404 (#7508) (@lukekarrys) - +* [`596706a`](https://github.com/npm/cli/commit/596706a3d10100587e3751d860b4cfcc59342d2f) [#9148](https://github.com/npm/cli/pull/9148) revert prefer-offline/prefer-online exclusivity (#9129) (@owlstronaut) ### Documentation +* [`d1ee8a5`](https://github.com/npm/cli/commit/d1ee8a524783e6ce33209fc48c83c89af5a5ccdf) [#9140](https://github.com/npm/cli/pull/9140) Add note on relative path prefix for npm publish (#9140) (@pydsigner) -* [`fd6479f`](https://github.com/npm/cli/commit/fd6479f85b9cf14a23cb4f9a049e0ea68632d8e9) [#7560](https://github.com/npm/cli/pull/7560) update publish docs: dist-tag + publish case (#7560) (@davidlj95) ### Dependencies -* [`e3f0fd4`](https://github.com/npm/cli/commit/e3f0fd45d97569a0d6c2a67e179e4a5f13eb9442) [#7568](https://github.com/npm/cli/pull/7568) `@npmcli/package-json@5.1.1` -* [`447a8d7`](https://github.com/npm/cli/commit/447a8d7f3124bf9f69453098ce31b56bad20efd7) [#7566](https://github.com/npm/cli/pull/7566) `spdx-license-ids@3.0.18` -* [`83fed2e`](https://github.com/npm/cli/commit/83fed2e8ec253051d60babdf2b10e2f2c64df318) [#7566](https://github.com/npm/cli/pull/7566) `sigstore@2.3.1` -* [`41291ba`](https://github.com/npm/cli/commit/41291bab34d3f7351c94e97e89ac1f85b0950188) [#7566](https://github.com/npm/cli/pull/7566) `@sigstore/tuf@2.3.4` -* [`18b42a4`](https://github.com/npm/cli/commit/18b42a46abdbc26a28f2e16ea74a1812d8de4c4d) [#7566](https://github.com/npm/cli/pull/7566) `glob@10.4.1` -* [`5c6759d`](https://github.com/npm/cli/commit/5c6759decb00dfbe377c0ad41f85a3222f79a36a) [#7566](https://github.com/npm/cli/pull/7566) `postcss-selector-parser@6.1.0` -* [`2508a83`](https://github.com/npm/cli/commit/2508a83e6d2936d15c210b9dee41098131ed6aff) [#7566](https://github.com/npm/cli/pull/7566) `is-cidr@5.1.0` -* [`6278fe4`](https://github.com/npm/cli/commit/6278fe430bb7c3ecfae730f9ea084501e57c0e2c) [#7566](https://github.com/npm/cli/pull/7566) `ini@4.1.3` -## [10.8.1](https://github.com/npm/cli/compare/v10.8.0...v10.8.1) (2024-05-29) +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.8.1): `@npmcli/config@10.8.1` +## [11.12.0](https://github.com/npm/cli/compare/v11.11.1...v11.12.0) (2026-03-18) +### Features +* [`8eff5fb`](https://github.com/npm/cli/commit/8eff5fb31afc996c71c8f159defa324cb86dfc5a) [#9049](https://github.com/npm/cli/pull/9049) audit: add --include-attestations flag to output sigstore bundles (#9049) (@mitchdenny) ### Bug Fixes - -* [`6b55646`](https://github.com/npm/cli/commit/6b556468f9d6ed62c681954bfe6ad012315e3b53) [#7569](https://github.com/npm/cli/pull/7569) exec: look in workspace and root for bin entries (#7569) (@wraithgar) -* [`e4c7a41`](https://github.com/npm/cli/commit/e4c7a410f590e5c9c81f6410f600181a4deef005) [#7564](https://github.com/npm/cli/pull/7564) publish: skip workspace packages marked private on publish (#7564) (@milaninfy) -* [`8f94ae8`](https://github.com/npm/cli/commit/8f94ae8c4d36cd397c53e8dc9f54d4332bf1b847) [#7556](https://github.com/npm/cli/pull/7556) utils/tar: index access while match is null (#7555) (#7556) (@NormanPerrin) -* [`2d1d8d0`](https://github.com/npm/cli/commit/2d1d8d0ef18a10ac7938380884745f1d3c3cb078) [#7559](https://github.com/npm/cli/pull/7559) adds `node:` specifier to all native node modules (#7559) (@reggi) -* [`7d89b55`](https://github.com/npm/cli/commit/7d89b55341160459e0fcd3374c3720d758b16339) [#7490](https://github.com/npm/cli/pull/7490) ci: rm workspace node_modules (#7490) (@reggi) -* [`9122fb6`](https://github.com/npm/cli/commit/9122fb65ac05d793a69f4fdcbd03b59595adf937) [#7516](https://github.com/npm/cli/pull/7516) cache: add both full and minified packument to cache (#7516) (@milaninfy) -* [`9e6686b`](https://github.com/npm/cli/commit/9e6686bb965fa6843ea483cb802f14282eabf3e5) [#7545](https://github.com/npm/cli/pull/7545) send proper otp token on web auth (#7545) (@wraithgar) -* [`b1db070`](https://github.com/npm/cli/commit/b1db070cb4a497fd91fd61cf197d28b5d47274bb) [#7534](https://github.com/npm/cli/pull/7534) refactor: use output.buffer and set explicit json mode in query (#7534) (@lukekarrys) -* [`53cda32`](https://github.com/npm/cli/commit/53cda32aa35f3a592fb0ddf37e43c028f93ef613) [#7542](https://github.com/npm/cli/pull/7542) refactor ls to use output.buffer for json (#7542) (@lukekarrys) -* [`61d5771`](https://github.com/npm/cli/commit/61d57719e6443978c5e9a91ca7a63397be3065fa) [#7541](https://github.com/npm/cli/pull/7541) remove json.stringify from all commands (#7541) (@lukekarrys) -* [`4dfc7d2`](https://github.com/npm/cli/commit/4dfc7d20b58eaa3d231ef5dc86b9802e1c0d0e68) [#7540](https://github.com/npm/cli/pull/7540) pass strings to JSON.stringify in --json mode (#7540) (@lukekarrys) -* [`3cefdf6`](https://github.com/npm/cli/commit/3cefdf6eaab5bfb4371149f674dc95e9b9c54853) [#7538](https://github.com/npm/cli/pull/7538) outdated: return array for outdated deps from multiple workspaces (@lukekarrys) -* [`ef4c975`](https://github.com/npm/cli/commit/ef4c975f2784f70ab86a3e7e6e40c99279e5a3e3) [#7508](https://github.com/npm/cli/pull/7508) view: dont immediately exit on first workspace 404 (#7508) (@lukekarrys) - -### Documentation - -* [`fd6479f`](https://github.com/npm/cli/commit/fd6479f85b9cf14a23cb4f9a049e0ea68632d8e9) [#7560](https://github.com/npm/cli/pull/7560) update publish docs: dist-tag + publish case (#7560) (@davidlj95) - +* [`03af94d`](https://github.com/npm/cli/commit/03af94d9020b35d09c838b9bd4f26697e49bf08b) [#9123](https://github.com/npm/cli/pull/9123) skip synopsis code block when command has no usage (@owlstronaut) +* [`21ea382`](https://github.com/npm/cli/commit/21ea382a60b3693ff6c44c81447caa5d0294169c) [#9110](https://github.com/npm/cli/pull/9110) arborist: resolve sibling override sets via common ancestor (#9110) (@manzoorwanijk) ### Dependencies - -* [`e3f0fd4`](https://github.com/npm/cli/commit/e3f0fd45d97569a0d6c2a67e179e4a5f13eb9442) [#7568](https://github.com/npm/cli/pull/7568) `@npmcli/package-json@5.1.1` -* [`447a8d7`](https://github.com/npm/cli/commit/447a8d7f3124bf9f69453098ce31b56bad20efd7) [#7566](https://github.com/npm/cli/pull/7566) `spdx-license-ids@3.0.18` -* [`83fed2e`](https://github.com/npm/cli/commit/83fed2e8ec253051d60babdf2b10e2f2c64df318) [#7566](https://github.com/npm/cli/pull/7566) `sigstore@2.3.1` -* [`41291ba`](https://github.com/npm/cli/commit/41291bab34d3f7351c94e97e89ac1f85b0950188) [#7566](https://github.com/npm/cli/pull/7566) `@sigstore/tuf@2.3.4` -* [`18b42a4`](https://github.com/npm/cli/commit/18b42a46abdbc26a28f2e16ea74a1812d8de4c4d) [#7566](https://github.com/npm/cli/pull/7566) `glob@10.4.1` -* [`5c6759d`](https://github.com/npm/cli/commit/5c6759decb00dfbe377c0ad41f85a3222f79a36a) [#7566](https://github.com/npm/cli/pull/7566) `postcss-selector-parser@6.1.0` -* [`2508a83`](https://github.com/npm/cli/commit/2508a83e6d2936d15c210b9dee41098131ed6aff) [#7566](https://github.com/npm/cli/pull/7566) `is-cidr@5.1.0` -* [`6278fe4`](https://github.com/npm/cli/commit/6278fe430bb7c3ecfae730f9ea084501e57c0e2c) [#7566](https://github.com/npm/cli/pull/7566) `ini@4.1.3` - +* [`03f4c3a`](https://github.com/npm/cli/commit/03f4c3a443bbd2a93e318bc5657ddb07e7a84fa7) [#9131](https://github.com/npm/cli/pull/9131) `@sigstore/tuf@4.0.2` +* [`4d5f7d9`](https://github.com/npm/cli/commit/4d5f7d9d33a41d124c2f7fedb4f267e3ce2ca5d8) [#9131](https://github.com/npm/cli/pull/9131) `@gar/promise-retry@1.0.3` +* [`8dcfe69`](https://github.com/npm/cli/commit/8dcfe693deda7e756b6b98ce8de8f28f8ecc584d) [#9131](https://github.com/npm/cli/pull/9131) `@sigstore/sign@4.1.1` +* [`e5a7e22`](https://github.com/npm/cli/commit/e5a7e222c7dc76fd1eed1efa31ca2d416ff20074) [#9127](https://github.com/npm/cli/pull/9127) `lru-cache@11.2.7` +* [`82deab6`](https://github.com/npm/cli/commit/82deab60ef2649c64830e734c48977090294dc7b) [#9127](https://github.com/npm/cli/pull/9127) `make-fetch-happen@15.0.5` +* [`ce195dc`](https://github.com/npm/cli/commit/ce195dc698e917d2169c3c0e632e5691f1fbbcdf) [#9127](https://github.com/npm/cli/pull/9127) `cacache@20.0.4` ### Chores - -* [`2d84091`](https://github.com/npm/cli/commit/2d840917bbeff6a1eb5accc10a5ec1c2280b9470) [#7568](https://github.com/npm/cli/pull/7568) fix snapshots for updated @npmcli/package-json (@wraithgar) -* [`6574dc9`](https://github.com/npm/cli/commit/6574dc98705cf0a88ea6fe41a57d0d0adfcea439) [#7566](https://github.com/npm/cli/pull/7566) dev dependency updates (@wraithgar) - +* [`95fa7f4`](https://github.com/npm/cli/commit/95fa7f4d8f560bb9993141f2d2e55c8b8add02c8) [#9132](https://github.com/npm/cli/pull/9132) fix docs test snapshot (#9132) (@wraithgar) +* [`7e9d538`](https://github.com/npm/cli/commit/7e9d53841be2a944739b7e226647b68f68b5742e) [#9127](https://github.com/npm/cli/pull/9127) dev dependency updates (@wraithgar) +* [`920e5ed`](https://github.com/npm/cli/commit/920e5ed32d859041978e8b63e7af228ab12a4346) [#9127](https://github.com/npm/cli/pull/9127) test snapshots (@wraithgar) +* [`98ccf92`](https://github.com/npm/cli/commit/98ccf9246ea07b33c6813f34fc98e88889177297) [#9125](https://github.com/npm/cli/pull/9125) fix snap tests (@owlstronaut) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.2): `@npmcli/arborist@9.4.2` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.8.0): `@npmcli/config@10.8.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.1.5): `libnpmdiff@8.1.5` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.2.5): `libnpmexec@10.2.5` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.19): `libnpmfund@7.0.19` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.1.5): `libnpmpack@9.1.5` + +## [11.11.1](https://github.com/npm/cli/compare/v11.11.0...v11.11.1) (2026-03-10) +### Bug Fixes +* [`a9d242b`](https://github.com/npm/cli/commit/a9d242bc4f04440630141743949ddb0d323f90b4) [#9099](https://github.com/npm/cli/pull/9099) include all subcommands on main command help (#9099) (@wraithgar) +* [`29b8407`](https://github.com/npm/cli/commit/29b8407971af1b9a2a3dcdb3849adfa04363fa7f) [#9087](https://github.com/npm/cli/pull/9087) unwrap comments and lines meant for output (#9087) (@wraithgar) +* [`b56986a`](https://github.com/npm/cli/commit/b56986acb0661fba2c80135eff3d140aa659dcf5) [#9095](https://github.com/npm/cli/pull/9095) ls: suppress false UNMET DEPENDENCYs in linked strategy (#9095) (@manzoorwanijk) +* [`76c76e5`](https://github.com/npm/cli/commit/76c76e5ad7cc5c7f641a92334b900c9d0c9a3fbd) [#9083](https://github.com/npm/cli/pull/9083) ci: don't error on optional deps in the lockfile (#9083) (@wraithgar) +* [`a29aeee`](https://github.com/npm/cli/commit/a29aeee18f3ddc2348a8e00787d237c874642789) [#9028](https://github.com/npm/cli/pull/9028) arborist: retry bin-links on Windows EPERM (#9028) (@manzoorwanijk) +* [`6565eeb`](https://github.com/npm/cli/commit/6565eeb818494e1feb4e14492804ce936b394b4a) [#9045](https://github.com/npm/cli/pull/9045) bypass packument cache to prevent ETARGET errors after publish (#9045) (@Jadu07) +### Documentation +* [`3b96929`](https://github.com/npm/cli/commit/3b96929166a55f7f0c346f9715988ec1e1ce195d) [#9074](https://github.com/npm/cli/pull/9074) scripts: remove mention of obsolete root user behavior (#9074) (@mohd-akram) +* [`16ac4e0`](https://github.com/npm/cli/commit/16ac4e02796248f3abb4fa043427236cda22a902) [#9054](https://github.com/npm/cli/pull/9054) fix workspace cross-dependency documentation (@owlstronaut) +### Dependencies +* [`075ae23`](https://github.com/npm/cli/commit/075ae23e46d821c56a0f50f56b2d6c745fe7367e) [#9086](https://github.com/npm/cli/pull/9086) `tar@7.5.11` +* [`13fa40d`](https://github.com/npm/cli/commit/13fa40d4ce8f7b0ea3e437056faca693472b3efa) [#9086](https://github.com/npm/cli/pull/9086) `pacote@21.5.0` +* [`bf7ea2b`](https://github.com/npm/cli/commit/bf7ea2b19f5446d3c3a33de2844f7504cc418570) [#9060](https://github.com/npm/cli/pull/9060) `brace-expansion@5.0.4` +* [`2000d2c`](https://github.com/npm/cli/commit/2000d2ce858c79664c6255d78485580b0d65f5b4) [#9060](https://github.com/npm/cli/pull/9060) `minimatch@10.2.4` +* [`d86b260`](https://github.com/npm/cli/commit/d86b260103358e6f8dd7d9cc2526ac3144d595c8) [#9060](https://github.com/npm/cli/pull/9060) `tar@7.5.10` +* [`dff1853`](https://github.com/npm/cli/commit/dff1853ed6e5b4acfdd36d0109cb2ebe27693a6f) [#9060](https://github.com/npm/cli/pull/9060) `@npmcli/run-script@10.0.4` +* [`93c3365`](https://github.com/npm/cli/commit/93c33658f6ac4e83cff83a0e064b222f1b36a515) [#9060](https://github.com/npm/cli/pull/9060) `write-file-atomic@7.0.1` ### Chores - -* [`2d84091`](https://github.com/npm/cli/commit/2d840917bbeff6a1eb5accc10a5ec1c2280b9470) [#7568](https://github.com/npm/cli/pull/7568) fix snapshots for updated @npmcli/package-json (@wraithgar) -* [`6574dc9`](https://github.com/npm/cli/commit/6574dc98705cf0a88ea6fe41a57d0d0adfcea439) [#7566](https://github.com/npm/cli/pull/7566) dev dependency updates (@wraithgar) - -## [10.8.0](https://github.com/npm/cli/compare/v10.7.0...v10.8.0) (2024-05-15) - +* [`d1996a7`](https://github.com/npm/cli/commit/d1996a7a79982f616600d134dbdcfb223cd0d81d) [#9060](https://github.com/npm/cli/pull/9060) dev dependency updates (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.1): `@npmcli/arborist@9.4.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.1.4): `libnpmdiff@8.1.4` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.2.4): `libnpmexec@10.2.4` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.18): `libnpmfund@7.0.18` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.1.4): `libnpmpack@9.1.4` + +## [11.11.0](https://github.com/npm/cli/compare/v11.10.1...v11.11.0) (2026-02-25) ### Features - -* [`1e375c1`](https://github.com/npm/cli/commit/1e375c1f8d16ac114b615c2a2f374099345b0b69) [#7442](https://github.com/npm/cli/pull/7442) create exit handler class (#7442) (@lukekarrys) - +* [`4fcd352`](https://github.com/npm/cli/commit/4fcd352c553fdc0f13a87ad71ef66d7515c11886) [#9017](https://github.com/npm/cli/pull/9017) add :type(registry) to query selector syntax (#9017) (@wraithgar) +* [`e1b21f0`](https://github.com/npm/cli/commit/e1b21f03e20dfd7b9cc1e631041027a013721df4) [#8909](https://github.com/npm/cli/pull/8909) adds circleci to trust command (#8909) (@owlstronaut) +* [`9a33ad0`](https://github.com/npm/cli/commit/9a33ad03c0ac2a3feed2db5f8a84c25635865186) [#8925](https://github.com/npm/cli/pull/8925) adds circleci to oidc (#8925) (@owlstronaut) ### Bug Fixes - -* [`d5c3289`](https://github.com/npm/cli/commit/d5c32899b6ffc6254c96f62a06a854bb2c2b95c5) [#7513](https://github.com/npm/cli/pull/7513) refactor: use output buffer and error for more commands (#7513) (@lukekarrys) -* [`12f103c`](https://github.com/npm/cli/commit/12f103ce55ed21c9c04f87a101fb64d55ac02d3c) [#7533](https://github.com/npm/cli/pull/7533) add first param titles to logs where missing (#7533) (@lukekarrys) -* [`badeac2`](https://github.com/npm/cli/commit/badeac28faf9fde5f8c05d235219be840999a646) [#7521](https://github.com/npm/cli/pull/7521) config: use redact on config output (#7521) (@lukekarrys) -* [`76aef74`](https://github.com/npm/cli/commit/76aef7423ab7e47a5f9b73849b47ba029730d75a) [#7520](https://github.com/npm/cli/pull/7520) view: refactor exec and execWorkspaces to call same methods (#7520) (@lukekarrys) -* [`b54cdb8`](https://github.com/npm/cli/commit/b54cdb836d6c4146a1aa8e1a5fe9655ba2ed0a6a) [#7515](https://github.com/npm/cli/pull/7515) refactor: create new error output primitives (#7515) (@lukekarrys) -* [`e40454c`](https://github.com/npm/cli/commit/e40454c35f75b5b814e7b5167c8a8b05664246f3) [#7506](https://github.com/npm/cli/pull/7506) view: dont unwrap arrays in json mode (#7506) (@lukekarrys) -* [`6f64148`](https://github.com/npm/cli/commit/6f6414829fd82704233fbb56375b167495a0aaf5) require stdout to be a TTY for progress (#7507) (@lukekarrys) -* [`db62910`](https://github.com/npm/cli/commit/db6291036f076bf0251b74a504bd5b693c29c4bb) [#7504](https://github.com/npm/cli/pull/7504) config: be more aggressive about hiding protected values (#7504) (@wraithgar) -* [`6d456bb`](https://github.com/npm/cli/commit/6d456bba46d6afe1e2cf9464908e6ad99375cb7c) [#7497](https://github.com/npm/cli/pull/7497) dont write log file for completion commands (#7497) (@lukekarrys) -* [`722c0fa`](https://github.com/npm/cli/commit/722c0faa387ae6e35886f08eefb238c03ae85db1) [#7463](https://github.com/npm/cli/pull/7463) limit packument cache size based on heap size (@wraithgar) -* [`ca1a68d`](https://github.com/npm/cli/commit/ca1a68d14d184f2535720ed4715f388965ade21a) [#7474](https://github.com/npm/cli/pull/7474) log if `npm deprecate` does not match any version (#7474) (@mbtools) -* [`261ea19`](https://github.com/npm/cli/commit/261ea193c96aaa73ce5630e21c6a31de9f19ef5b) [#7457](https://github.com/npm/cli/pull/7457) run input.start around help and openining urls (@lukekarrys) -* [`4ab6cf4`](https://github.com/npm/cli/commit/4ab6cf4a9e7fca64f95422f4099b33cdbb9efa25) [#7459](https://github.com/npm/cli/pull/7459) publish: validate dist-tag (#7459) (@reggi) - +* [`4426411`](https://github.com/npm/cli/commit/4426411bda7807afbb47aa01d8bf789e8c91eaff) [#9026](https://github.com/npm/cli/pull/9026) npm audit signatures for keyless attestation registries (#9026) (@ajayk) +* [`658b323`](https://github.com/npm/cli/commit/658b32373e3490c72826b0bbcc6c1b74129e3ced) [#9010](https://github.com/npm/cli/pull/9010) handle legacy licenses array in sbom output (#9010) (@JNC4) ### Documentation - -* [`b2ce025`](https://github.com/npm/cli/commit/b2ce0250e32abaaaf60d895cda210914bdf903ea) [#7518](https://github.com/npm/cli/pull/7518) suggest correct bin entry (#7518) (@Santoshraj2) -* [`bdd2aae`](https://github.com/npm/cli/commit/bdd2aae12b213815b5d800902b0a9722b263a03c) [#7502](https://github.com/npm/cli/pull/7502) remove obsolete removal using make uninstall (#7502) (@avinal) -* [`c3d2819`](https://github.com/npm/cli/commit/c3d281984ed363ed03d6a7abe083f301c1dd2c88) [#7496](https://github.com/npm/cli/pull/7496) npm help json/global command on windows (#7496) (@klm-turing, @lukekarrys) -* [`268303c`](https://github.com/npm/cli/commit/268303c3b40551ae558f201841d3d5977769a7c9) [#7479](https://github.com/npm/cli/pull/7479) add npm version to every local help output (#7479) (@klm-turing) -* [`e39d422`](https://github.com/npm/cli/commit/e39d422d69c2275ed1e3a606447a9b9d87bdca4f) [#7473](https://github.com/npm/cli/pull/7473) suggest "npm repo" for showing the repo of a package (#7473) (@full-stop) -* [`f6fff32`](https://github.com/npm/cli/commit/f6fff3295d19b63003cf49eb1c4805f453c5390a) [#7433](https://github.com/npm/cli/pull/7433) clarify what peerDependenciesMeta does (#7433) (@xuhdev, @wraithgar) - +* [`143f8cd`](https://github.com/npm/cli/commit/143f8cdf4c6503240cc655b383ba865c0b9ea599) [#9007](https://github.com/npm/cli/pull/9007) docs shouldn't wrap yaml description (#9007) (@owlstronaut) ### Dependencies - -* [`1cdc662`](https://github.com/npm/cli/commit/1cdc662bd2835531fbe790011a00f88ddb5f6868) [#7522](https://github.com/npm/cli/pull/7522) `@tufjs/repo-mock@2.0.1` -* [`898bcfd`](https://github.com/npm/cli/commit/898bcfda5c5ac192b2cf5f47d0b939794c1b2164) [#7522](https://github.com/npm/cli/pull/7522) `@sigstore/protobuf-specs@0.3.2` -* [`fec3c94`](https://github.com/npm/cli/commit/fec3c947d7dcc71071a8f527aa5bd81f47015486) [#7522](https://github.com/npm/cli/pull/7522) `path-scurry@1.11.1` -* [`cb85973`](https://github.com/npm/cli/commit/cb8597316a8d53815835901ae9d5756d4dc481ea) [#7522](https://github.com/npm/cli/pull/7522) `glob@10.3.15` -* [`e189873`](https://github.com/npm/cli/commit/e18987371399f508cb224e159987b10ddb922bb8) [#7498](https://github.com/npm/cli/pull/7498) `@sigstore/sign@2.3.1` -* [`c2b28f9`](https://github.com/npm/cli/commit/c2b28f9d6cba12e88f849e5b4a82607e2c218a16) [#7498](https://github.com/npm/cli/pull/7498) `minipass@7.1.1` -* [`9064ffc`](https://github.com/npm/cli/commit/9064ffc6c85309de2e9e798fdc6caca209f5fa18) [#7498](https://github.com/npm/cli/pull/7498) `@sigstore/tuf@2.3.3` -* [`fd42986`](https://github.com/npm/cli/commit/fd429866c79cc001979135857c019d7d2873f291) [#7498](https://github.com/npm/cli/pull/7498) `@npmcli/fs@3.1.1` -* [`4e53e33`](https://github.com/npm/cli/commit/4e53e33757c88ca9c413e3943b17e0cb246e955c) [#7498](https://github.com/npm/cli/pull/7498) `semver@7.6.2` -* [`f078c82`](https://github.com/npm/cli/commit/f078c8224f6775d53da98f310531524c616e6099) [#7495](https://github.com/npm/cli/pull/7495) `glob@10.3.14` -* [`58f773c`](https://github.com/npm/cli/commit/58f773c99742ef55ac2a9eca23c27b32800c2cf1) [#7495](https://github.com/npm/cli/pull/7495) `path-scurry@1.11.0` -* [`ea0b07d`](https://github.com/npm/cli/commit/ea0b07da149767265f11d5d77d2156e2c9f43e63) [#7482](https://github.com/npm/cli/pull/7482) `pacote@18.0.6` -* [`8d161a4`](https://github.com/npm/cli/commit/8d161a414160dab7a930b1668c3af3ba280e8532) [#7482](https://github.com/npm/cli/pull/7482) `semver@7.6.1` -* [`5b2317b`](https://github.com/npm/cli/commit/5b2317b472342428c6521d7b0d550d0fcc9bb202) [#7463](https://github.com/npm/cli/pull/7463) add lru-cache -* [`26fefb8`](https://github.com/npm/cli/commit/26fefb82b3bd812009b8b627e3c19032a931aade) [#7480](https://github.com/npm/cli/pull/7480) `promzard@1.0.2` -* [`2146e1f`](https://github.com/npm/cli/commit/2146e1f83ae94debecfaf08ef32e319c02223c12) [#7480](https://github.com/npm/cli/pull/7480) `npm-bundled@3.0.1` -* [`ff6c5d1`](https://github.com/npm/cli/commit/ff6c5d161b52e8961e0c2ebf0467bc1382ef72d2) [#7480](https://github.com/npm/cli/pull/7480) `minipass-fetch@3.0.5` -* [`419f9b9`](https://github.com/npm/cli/commit/419f9b9d9d6806d56b68d96bd50f7d25274a8f48) [#7480](https://github.com/npm/cli/pull/7480) `cmd-shim@6.0.3` -* [`dade2c8`](https://github.com/npm/cli/commit/dade2c88d23289d57351d614feaa876d9e1e17f4) [#7480](https://github.com/npm/cli/pull/7480) `minipass@7.1.0` -* [`18e5312`](https://github.com/npm/cli/commit/18e53129f0f3a19725e377b336336aa85ade3ba5) [#7480](https://github.com/npm/cli/pull/7480) `validate-npm-package-name@5.0.1` -* [`d440011`](https://github.com/npm/cli/commit/d44001164f66d15daa3fd27da004194478b7c99c) [#7480](https://github.com/npm/cli/pull/7480) `npm-user-validate@2.0.1` -* [`552113e`](https://github.com/npm/cli/commit/552113e7a663efdcebfcbcc6148b1d51be55596b) [#7480](https://github.com/npm/cli/pull/7480) `ignore-walk@6.0.5` -* [`7e15b6d`](https://github.com/npm/cli/commit/7e15b6d56abbf47456c12fa2d5688d5d187a0ae7) [#7480](https://github.com/npm/cli/pull/7480) `@npmcli/metavuln-calculator@7.1.1` -* [`8b20f8c`](https://github.com/npm/cli/commit/8b20f8c8ba70e43ad222538fc396dedb071b1680) [#7480](https://github.com/npm/cli/pull/7480) `ssri@10.0.6` -* [`a9a6dcd`](https://github.com/npm/cli/commit/a9a6dcd4427ec82e491a2cad5672d8183e12180f) [#7480](https://github.com/npm/cli/pull/7480) `pacote@18.0.5` -* [`e2fdb65`](https://github.com/npm/cli/commit/e2fdb651cda9ec603f009f5713a5a2b489d49e15) [#7480](https://github.com/npm/cli/pull/7480) `npm-pick-manifest@9.0.1` -* [`310a7a5`](https://github.com/npm/cli/commit/310a7a5583d14da761d38b7421ebb6cee65600b6) [#7480](https://github.com/npm/cli/pull/7480) `normalize-package-data@6.0.1` -* [`e71f541`](https://github.com/npm/cli/commit/e71f541b020de7940faccffab68d0255c4079e1a) [#7480](https://github.com/npm/cli/pull/7480) `nopt@7.2.1` -* [`18c3b40`](https://github.com/npm/cli/commit/18c3b4058c7f721ff585de2f2766e53da897e16e) [#7480](https://github.com/npm/cli/pull/7480) `json-parse-even-better-errors@3.0.2` -* [`4c5bf77`](https://github.com/npm/cli/commit/4c5bf77af6db3b447f9b9abc3b67b211d7bb82b8) [#7480](https://github.com/npm/cli/pull/7480) `init-package-json@6.0.3` -* [`714e3e1`](https://github.com/npm/cli/commit/714e3e1e1ce014cba71db41c2d6c02d9dd53fcd3) [#7480](https://github.com/npm/cli/pull/7480) `hosted-git-info@7.0.2` -* [`f94d672`](https://github.com/npm/cli/commit/f94d6726a6ca96cad0da88ea499fa22f35b7c4c0) [#7480](https://github.com/npm/cli/pull/7480) `cacache@18.0.3` -* [`43331e4`](https://github.com/npm/cli/commit/43331e4d0647c3af4cc2aa3db8b47d797584a6d8) [#7480](https://github.com/npm/cli/pull/7480) `bin-links@4.0.4` -* [`8234412`](https://github.com/npm/cli/commit/823441219ce63d7863aede8b22b4b1d07021fd22) [#7480](https://github.com/npm/cli/pull/7480) `@npmcli/promise-spawn@7.0.2` -* [`6dfaebb`](https://github.com/npm/cli/commit/6dfaebb8f08acf992ac36faf4db8b650e8e55eae) [#7480](https://github.com/npm/cli/pull/7480) `@npmcli/git@5.0.7` -* [`63ef498`](https://github.com/npm/cli/commit/63ef498bf2916a882a92c0b9fe6de6728584694a) [#7457](https://github.com/npm/cli/pull/7457) `npm-registry-fetch@17.0.1` -* [`4cbc2d4`](https://github.com/npm/cli/commit/4cbc2d402174933052c7addd6ea55b1ecee202c5) [#7457](https://github.com/npm/cli/pull/7457) `npm-profile@10.0.0` -## [10.8.0](https://github.com/npm/cli/compare/v10.7.0...v10.8.0) (2024-05-15) - -### Features - -* [`1e375c1`](https://github.com/npm/cli/commit/1e375c1f8d16ac114b615c2a2f374099345b0b69) [#7442](https://github.com/npm/cli/pull/7442) create exit handler class (#7442) (@lukekarrys) - +* [`7798b6e`](https://github.com/npm/cli/commit/7798b6e3a9515b6114d4143c3b692e21242307fb) [#9027](https://github.com/npm/cli/pull/9027) `@gar/promise-retry@1.0.2` +* [`4838864`](https://github.com/npm/cli/commit/4838864bd0693897a3059d13b1297b941454b3d7) [#9027](https://github.com/npm/cli/pull/9027) `balanced-match@4.0.4` +* [`0c200dd`](https://github.com/npm/cli/commit/0c200ddca74c7b57c526d6742451f4104a0f5af1) [#9027](https://github.com/npm/cli/pull/9027) `brace-expansion@5.0.3` +* [`f0606bb`](https://github.com/npm/cli/commit/f0606bbfb06de39ce230afaa0f1f167fd1e10124) [#9027](https://github.com/npm/cli/pull/9027) `spdx-license-ids@3.0.23` +* [`d43f350`](https://github.com/npm/cli/commit/d43f35071cbef1d9ed9841684a5c32503727ed12) [#9027](https://github.com/npm/cli/pull/9027) `make-fetch-happen@15.0.4` +* [`4d0918a`](https://github.com/npm/cli/commit/4d0918a913bf60766c37c178f41693c75b29f6a3) [#9027](https://github.com/npm/cli/pull/9027) `@npmcli/git@7.0.2` +* [`8912ca7`](https://github.com/npm/cli/commit/8912ca7488f9e0e78bf7fcb51bf4dbe98b51eb5b) [#9027](https://github.com/npm/cli/pull/9027) `minipass-fetch@5.0.2` +* [`450ff35`](https://github.com/npm/cli/commit/450ff35d9cc70f5196040c31221cce0601d8a3a1) [#9027](https://github.com/npm/cli/pull/9027) `npm-packlist@10.0.4` +* [`20ef5a5`](https://github.com/npm/cli/commit/20ef5a5b6596891ba632410d97cdf5cb90b17bb3) [#9027](https://github.com/npm/cli/pull/9027) `pacote@21.4.0` +* [`60f332c`](https://github.com/npm/cli/commit/60f332c9df28e736f510ef8ac1f207175687dcad) [#9008](https://github.com/npm/cli/pull/9008) remove promise-retry +* [`cb8b9c7`](https://github.com/npm/cli/commit/cb8b9c7a45d81883ada7891f492afbf998574d10) [#9008](https://github.com/npm/cli/pull/9008) add `@gar/promise-retry@1.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.0): `@npmcli/arborist@9.4.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.1.3): `libnpmdiff@8.1.3` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.2.3): `libnpmexec@10.2.3` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.17): `libnpmfund@7.0.17` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.1.3): `libnpmpack@9.1.3` + +## [11.10.1](https://github.com/npm/cli/compare/v11.10.0...v11.10.1) (2026-02-19) ### Bug Fixes - -* [`d5c3289`](https://github.com/npm/cli/commit/d5c32899b6ffc6254c96f62a06a854bb2c2b95c5) [#7513](https://github.com/npm/cli/pull/7513) refactor: use output buffer and error for more commands (#7513) (@lukekarrys) -* [`12f103c`](https://github.com/npm/cli/commit/12f103ce55ed21c9c04f87a101fb64d55ac02d3c) [#7533](https://github.com/npm/cli/pull/7533) add first param titles to logs where missing (#7533) (@lukekarrys) -* [`badeac2`](https://github.com/npm/cli/commit/badeac28faf9fde5f8c05d235219be840999a646) [#7521](https://github.com/npm/cli/pull/7521) config: use redact on config output (#7521) (@lukekarrys) -* [`76aef74`](https://github.com/npm/cli/commit/76aef7423ab7e47a5f9b73849b47ba029730d75a) [#7520](https://github.com/npm/cli/pull/7520) view: refactor exec and execWorkspaces to call same methods (#7520) (@lukekarrys) -* [`b54cdb8`](https://github.com/npm/cli/commit/b54cdb836d6c4146a1aa8e1a5fe9655ba2ed0a6a) [#7515](https://github.com/npm/cli/pull/7515) refactor: create new error output primitives (#7515) (@lukekarrys) -* [`e40454c`](https://github.com/npm/cli/commit/e40454c35f75b5b814e7b5167c8a8b05664246f3) [#7506](https://github.com/npm/cli/pull/7506) view: dont unwrap arrays in json mode (#7506) (@lukekarrys) -* [`6f64148`](https://github.com/npm/cli/commit/6f6414829fd82704233fbb56375b167495a0aaf5) require stdout to be a TTY for progress (#7507) (@lukekarrys) -* [`db62910`](https://github.com/npm/cli/commit/db6291036f076bf0251b74a504bd5b693c29c4bb) [#7504](https://github.com/npm/cli/pull/7504) config: be more aggressive about hiding protected values (#7504) (@wraithgar) -* [`6d456bb`](https://github.com/npm/cli/commit/6d456bba46d6afe1e2cf9464908e6ad99375cb7c) [#7497](https://github.com/npm/cli/pull/7497) dont write log file for completion commands (#7497) (@lukekarrys) -* [`722c0fa`](https://github.com/npm/cli/commit/722c0faa387ae6e35886f08eefb238c03ae85db1) [#7463](https://github.com/npm/cli/pull/7463) limit packument cache size based on heap size (@wraithgar) -* [`ca1a68d`](https://github.com/npm/cli/commit/ca1a68d14d184f2535720ed4715f388965ade21a) [#7474](https://github.com/npm/cli/pull/7474) log if `npm deprecate` does not match any version (#7474) (@mbtools) -* [`261ea19`](https://github.com/npm/cli/commit/261ea193c96aaa73ce5630e21c6a31de9f19ef5b) [#7457](https://github.com/npm/cli/pull/7457) run input.start around help and openining urls (@lukekarrys) -* [`4ab6cf4`](https://github.com/npm/cli/commit/4ab6cf4a9e7fca64f95422f4099b33cdbb9efa25) [#7459](https://github.com/npm/cli/pull/7459) publish: validate dist-tag (#7459) (@reggi) - +* [`9fac412`](https://github.com/npm/cli/commit/9fac412105c4bbd116cffb6e27dda54a2adecf33) [#8995](https://github.com/npm/cli/pull/8995) improve unknown config warning with .npmrc section hint (#8995) (@umeshmore45) +* [`bb135cc`](https://github.com/npm/cli/commit/bb135cc8998b8b936f2cb412ec3303ae02d6920c) [#8981](https://github.com/npm/cli/pull/8981) arborist: fix `peerOptional` dependency resolution in `buildIdealTree` (#8981) (@Saibamen, @cursoragent) +* [`5c03826`](https://github.com/npm/cli/commit/5c03826e7aabedc03aaeaaa2f6863e6259519443) [#8993](https://github.com/npm/cli/pull/8993) remove tabular output from "npm view" (@wraithgar) +* [`4648f26`](https://github.com/npm/cli/commit/4648f26f2e68c86306161b7ed6550c06adba4483) [#8993](https://github.com/npm/cli/pull/8993) remove tabular output from "npm team" (@wraithgar) ### Documentation - -* [`b2ce025`](https://github.com/npm/cli/commit/b2ce0250e32abaaaf60d895cda210914bdf903ea) [#7518](https://github.com/npm/cli/pull/7518) suggest correct bin entry (#7518) (@Santoshraj2) -* [`bdd2aae`](https://github.com/npm/cli/commit/bdd2aae12b213815b5d800902b0a9722b263a03c) [#7502](https://github.com/npm/cli/pull/7502) remove obsolete removal using make uninstall (#7502) (@avinal) -* [`c3d2819`](https://github.com/npm/cli/commit/c3d281984ed363ed03d6a7abe083f301c1dd2c88) [#7496](https://github.com/npm/cli/pull/7496) npm help json/global command on windows (#7496) (@klm-turing, @lukekarrys) -* [`268303c`](https://github.com/npm/cli/commit/268303c3b40551ae558f201841d3d5977769a7c9) [#7479](https://github.com/npm/cli/pull/7479) add npm version to every local help output (#7479) (@klm-turing) -* [`e39d422`](https://github.com/npm/cli/commit/e39d422d69c2275ed1e3a606447a9b9d87bdca4f) [#7473](https://github.com/npm/cli/pull/7473) suggest "npm repo" for showing the repo of a package (#7473) (@full-stop) -* [`f6fff32`](https://github.com/npm/cli/commit/f6fff3295d19b63003cf49eb1c4805f453c5390a) [#7433](https://github.com/npm/cli/pull/7433) clarify what peerDependenciesMeta does (#7433) (@xuhdev, @wraithgar) - +* [`0a5756d`](https://github.com/npm/cli/commit/0a5756d5d06972dcf29cdee6978f5317dce92e6b) [#8998](https://github.com/npm/cli/pull/8998) clarify unsupported custom .npmrc keys and recommend alternatives (#8998) (@maitrawebtech) +* [`22c9153`](https://github.com/npm/cli/commit/22c91534d057dc4474495ed1d675fc9b15829275) [#8985](https://github.com/npm/cli/pull/8985) fix typo and grammar in README (#8985) (@csmit195, Chris) ### Dependencies - -* [`1cdc662`](https://github.com/npm/cli/commit/1cdc662bd2835531fbe790011a00f88ddb5f6868) [#7522](https://github.com/npm/cli/pull/7522) `@tufjs/repo-mock@2.0.1` -* [`898bcfd`](https://github.com/npm/cli/commit/898bcfda5c5ac192b2cf5f47d0b939794c1b2164) [#7522](https://github.com/npm/cli/pull/7522) `@sigstore/protobuf-specs@0.3.2` -* [`fec3c94`](https://github.com/npm/cli/commit/fec3c947d7dcc71071a8f527aa5bd81f47015486) [#7522](https://github.com/npm/cli/pull/7522) `path-scurry@1.11.1` -* [`cb85973`](https://github.com/npm/cli/commit/cb8597316a8d53815835901ae9d5756d4dc481ea) [#7522](https://github.com/npm/cli/pull/7522) `glob@10.3.15` -* [`e189873`](https://github.com/npm/cli/commit/e18987371399f508cb224e159987b10ddb922bb8) [#7498](https://github.com/npm/cli/pull/7498) `@sigstore/sign@2.3.1` -* [`c2b28f9`](https://github.com/npm/cli/commit/c2b28f9d6cba12e88f849e5b4a82607e2c218a16) [#7498](https://github.com/npm/cli/pull/7498) `minipass@7.1.1` -* [`9064ffc`](https://github.com/npm/cli/commit/9064ffc6c85309de2e9e798fdc6caca209f5fa18) [#7498](https://github.com/npm/cli/pull/7498) `@sigstore/tuf@2.3.3` -* [`fd42986`](https://github.com/npm/cli/commit/fd429866c79cc001979135857c019d7d2873f291) [#7498](https://github.com/npm/cli/pull/7498) `@npmcli/fs@3.1.1` -* [`4e53e33`](https://github.com/npm/cli/commit/4e53e33757c88ca9c413e3943b17e0cb246e955c) [#7498](https://github.com/npm/cli/pull/7498) `semver@7.6.2` -* [`f078c82`](https://github.com/npm/cli/commit/f078c8224f6775d53da98f310531524c616e6099) [#7495](https://github.com/npm/cli/pull/7495) `glob@10.3.14` -* [`58f773c`](https://github.com/npm/cli/commit/58f773c99742ef55ac2a9eca23c27b32800c2cf1) [#7495](https://github.com/npm/cli/pull/7495) `path-scurry@1.11.0` -* [`ea0b07d`](https://github.com/npm/cli/commit/ea0b07da149767265f11d5d77d2156e2c9f43e63) [#7482](https://github.com/npm/cli/pull/7482) `pacote@18.0.6` -* [`8d161a4`](https://github.com/npm/cli/commit/8d161a414160dab7a930b1668c3af3ba280e8532) [#7482](https://github.com/npm/cli/pull/7482) `semver@7.6.1` -* [`5b2317b`](https://github.com/npm/cli/commit/5b2317b472342428c6521d7b0d550d0fcc9bb202) [#7463](https://github.com/npm/cli/pull/7463) add lru-cache -* [`26fefb8`](https://github.com/npm/cli/commit/26fefb82b3bd812009b8b627e3c19032a931aade) [#7480](https://github.com/npm/cli/pull/7480) `promzard@1.0.2` -* [`2146e1f`](https://github.com/npm/cli/commit/2146e1f83ae94debecfaf08ef32e319c02223c12) [#7480](https://github.com/npm/cli/pull/7480) `npm-bundled@3.0.1` -* [`ff6c5d1`](https://github.com/npm/cli/commit/ff6c5d161b52e8961e0c2ebf0467bc1382ef72d2) [#7480](https://github.com/npm/cli/pull/7480) `minipass-fetch@3.0.5` -* [`419f9b9`](https://github.com/npm/cli/commit/419f9b9d9d6806d56b68d96bd50f7d25274a8f48) [#7480](https://github.com/npm/cli/pull/7480) `cmd-shim@6.0.3` -* [`dade2c8`](https://github.com/npm/cli/commit/dade2c88d23289d57351d614feaa876d9e1e17f4) [#7480](https://github.com/npm/cli/pull/7480) `minipass@7.1.0` -* [`18e5312`](https://github.com/npm/cli/commit/18e53129f0f3a19725e377b336336aa85ade3ba5) [#7480](https://github.com/npm/cli/pull/7480) `validate-npm-package-name@5.0.1` -* [`d440011`](https://github.com/npm/cli/commit/d44001164f66d15daa3fd27da004194478b7c99c) [#7480](https://github.com/npm/cli/pull/7480) `npm-user-validate@2.0.1` -* [`552113e`](https://github.com/npm/cli/commit/552113e7a663efdcebfcbcc6148b1d51be55596b) [#7480](https://github.com/npm/cli/pull/7480) `ignore-walk@6.0.5` -* [`7e15b6d`](https://github.com/npm/cli/commit/7e15b6d56abbf47456c12fa2d5688d5d187a0ae7) [#7480](https://github.com/npm/cli/pull/7480) `@npmcli/metavuln-calculator@7.1.1` -* [`8b20f8c`](https://github.com/npm/cli/commit/8b20f8c8ba70e43ad222538fc396dedb071b1680) [#7480](https://github.com/npm/cli/pull/7480) `ssri@10.0.6` -* [`a9a6dcd`](https://github.com/npm/cli/commit/a9a6dcd4427ec82e491a2cad5672d8183e12180f) [#7480](https://github.com/npm/cli/pull/7480) `pacote@18.0.5` -* [`e2fdb65`](https://github.com/npm/cli/commit/e2fdb651cda9ec603f009f5713a5a2b489d49e15) [#7480](https://github.com/npm/cli/pull/7480) `npm-pick-manifest@9.0.1` -* [`310a7a5`](https://github.com/npm/cli/commit/310a7a5583d14da761d38b7421ebb6cee65600b6) [#7480](https://github.com/npm/cli/pull/7480) `normalize-package-data@6.0.1` -* [`e71f541`](https://github.com/npm/cli/commit/e71f541b020de7940faccffab68d0255c4079e1a) [#7480](https://github.com/npm/cli/pull/7480) `nopt@7.2.1` -* [`18c3b40`](https://github.com/npm/cli/commit/18c3b4058c7f721ff585de2f2766e53da897e16e) [#7480](https://github.com/npm/cli/pull/7480) `json-parse-even-better-errors@3.0.2` -* [`4c5bf77`](https://github.com/npm/cli/commit/4c5bf77af6db3b447f9b9abc3b67b211d7bb82b8) [#7480](https://github.com/npm/cli/pull/7480) `init-package-json@6.0.3` -* [`714e3e1`](https://github.com/npm/cli/commit/714e3e1e1ce014cba71db41c2d6c02d9dd53fcd3) [#7480](https://github.com/npm/cli/pull/7480) `hosted-git-info@7.0.2` -* [`f94d672`](https://github.com/npm/cli/commit/f94d6726a6ca96cad0da88ea499fa22f35b7c4c0) [#7480](https://github.com/npm/cli/pull/7480) `cacache@18.0.3` -* [`43331e4`](https://github.com/npm/cli/commit/43331e4d0647c3af4cc2aa3db8b47d797584a6d8) [#7480](https://github.com/npm/cli/pull/7480) `bin-links@4.0.4` -* [`8234412`](https://github.com/npm/cli/commit/823441219ce63d7863aede8b22b4b1d07021fd22) [#7480](https://github.com/npm/cli/pull/7480) `@npmcli/promise-spawn@7.0.2` -* [`6dfaebb`](https://github.com/npm/cli/commit/6dfaebb8f08acf992ac36faf4db8b650e8e55eae) [#7480](https://github.com/npm/cli/pull/7480) `@npmcli/git@5.0.7` -* [`63ef498`](https://github.com/npm/cli/commit/63ef498bf2916a882a92c0b9fe6de6728584694a) [#7457](https://github.com/npm/cli/pull/7457) `npm-registry-fetch@17.0.1` -* [`4cbc2d4`](https://github.com/npm/cli/commit/4cbc2d402174933052c7addd6ea55b1ecee202c5) [#7457](https://github.com/npm/cli/pull/7457) `npm-profile@10.0.0` - +* [`aa8ffbf`](https://github.com/npm/cli/commit/aa8ffbf955a0ba768e58af1865988894d3404d78) [#9002](https://github.com/npm/cli/pull/9002) `init-package-json@8.2.5` (#9002) +* [`67a0f09`](https://github.com/npm/cli/commit/67a0f09ad2e6a4e217963d73cd61e60ae9a27192) [#9001](https://github.com/npm/cli/pull/9001) `glob@13.0.6` +* [`56b8fd4`](https://github.com/npm/cli/commit/56b8fd43467f49607eb52095ade83138ae35583b) [#9001](https://github.com/npm/cli/pull/9001) `minimatch@10.2.2` +* [`aa7fef5`](https://github.com/npm/cli/commit/aa7fef50603457a0f74828042ab0f4ae124c0617) [#9001](https://github.com/npm/cli/pull/9001) `minipass@7.1.3` +* [`d3a4161`](https://github.com/npm/cli/commit/d3a41615d857437af43ddc5c94f0f644c3cc2491) [#9000](https://github.com/npm/cli/pull/9000) `@npmcli/package-json@7.0.5` (#9000) +* [`7aa9338`](https://github.com/npm/cli/commit/7aa9338565bd5b1fa9364727900225089746f0c9) [#8993](https://github.com/npm/cli/pull/8993) remove cli-columns +* [`f7f7c53`](https://github.com/npm/cli/commit/f7f7c5383f9d599cd1982783e9afcb3e45b0e7e7) [#8991](https://github.com/npm/cli/pull/8991) hoist balanced-match +* [`10cb575`](https://github.com/npm/cli/commit/10cb575743deb1ca0459c957fd19e50129116afe) [#8991](https://github.com/npm/cli/pull/8991) hoist latest yallist +* [`1b3dc9a`](https://github.com/npm/cli/commit/1b3dc9a79a2bfc9ac9217bca724a38ce504eca0a) [#8991](https://github.com/npm/cli/pull/8991) `cidr-regex@5.0.3` +* [`4307af6`](https://github.com/npm/cli/commit/4307af6c1d5a0a6a9d301f109546181e1d747c5a) [#8991](https://github.com/npm/cli/pull/8991) `glob@13.0.5` +* [`13b4d6a`](https://github.com/npm/cli/commit/13b4d6a715b2369363a7e2d237eed8e45a5752aa) [#8991](https://github.com/npm/cli/pull/8991) `minimatch@10.2.1` +* [`45d4000`](https://github.com/npm/cli/commit/45d40008877357c645256de4c244e065d20b8932) [#8991](https://github.com/npm/cli/pull/8991) `tar@7.5.9` ### Chores - -* [`10256e8`](https://github.com/npm/cli/commit/10256e8cbe3583b65cb253a19ba9ee64f21c9584) [#7522](https://github.com/npm/cli/pull/7522) dev dependency updates (@wraithgar) -* [`dcfc3de`](https://github.com/npm/cli/commit/dcfc3deba2bb0066ec5d8b1870719f730adc2e97) [#7517](https://github.com/npm/cli/pull/7517) convert run-script tests to snapshots (#7517) (@lukekarrys) -* [`8add914`](https://github.com/npm/cli/commit/8add914841775f239acd838b1d8d52b251d0e1b2) [#7505](https://github.com/npm/cli/pull/7505) create single bug report issue template (#7505) (@lukekarrys) -* [`7c7fba4`](https://github.com/npm/cli/commit/7c7fba4fc92528287e1f2ef5fb8256e60760c201) [#7500](https://github.com/npm/cli/pull/7500) benchmarks: fix emoji reaction to comment (#7500) (@lukekarrys) -* [`d3b9587`](https://github.com/npm/cli/commit/d3b958756144d71c25cc4bd2020e040a940fbe3b) [#7494](https://github.com/npm/cli/pull/7494) disable progress on npm pack test (@wraithgar) -* [`67ebb66`](https://github.com/npm/cli/commit/67ebb66d3ffa61582f8dd63ddbb5679649a5d2a4) [#7494](https://github.com/npm/cli/pull/7494) disable color in config tests (@wraithgar) -* [`2ec2e75`](https://github.com/npm/cli/commit/2ec2e75ee81361a850bca643341d240441870334) [#7494](https://github.com/npm/cli/pull/7494) disable progress on shellout exit tests (@wraithgar) -* [`e9fdc9a`](https://github.com/npm/cli/commit/e9fdc9a792666d5b9aa73833c65516bafcb80863) [#7483](https://github.com/npm/cli/pull/7483) create smoke-publish-test.sh script (#7483) (@lukekarrys) -* [`1524cfd`](https://github.com/npm/cli/commit/1524cfd94daaca131ab16180c27323999fab07b3) [#7484](https://github.com/npm/cli/pull/7484) remove extra quotes from benchmark event_type (#7484) (@lukekarrys) -* [`9c4d3c4`](https://github.com/npm/cli/commit/9c4d3c402c77bd7aaa514ee9e02d7fd87223343e) [#7467](https://github.com/npm/cli/pull/7467) template-oss-apply (@lukekarrys) -* [`2b7ec54`](https://github.com/npm/cli/commit/2b7ec54f52f9e8aee568ccb4e34ce4a5733af21a) [#7467](https://github.com/npm/cli/pull/7467) `template-oss@4.22.0` (@lukekarrys) -* [`8ded848`](https://github.com/npm/cli/commit/8ded848b099297a12a81ec008d6229f3ad3494a6) [#7457](https://github.com/npm/cli/pull/7457) remove doctor snapshot stack traces (@lukekarrys) - +* [`40fcab4`](https://github.com/npm/cli/commit/40fcab45d356545f8db7f34df3e5630116d0dd40) [#8991](https://github.com/npm/cli/pull/8991) `@npmcli/template-oss@4.29.0` (@wraithgar) +* [`1598adb`](https://github.com/npm/cli/commit/1598adb05de18cb738c9a7fbcc63692059f46a17) [#8991](https://github.com/npm/cli/pull/8991) dev dependency updates (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.3.1): `@npmcli/arborist@9.3.1` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.7.1): `@npmcli/config@10.7.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.1.2): `libnpmdiff@8.1.2` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.2.2): `libnpmexec@10.2.2` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.16): `libnpmfund@7.0.16` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.1.2): `libnpmpack@9.1.2` + +## [11.10.0](https://github.com/npm/cli/compare/v11.9.0...v11.10.0) (2026-02-11) +### Features +* [`cf56a1e`](https://github.com/npm/cli/commit/cf56a1e4df9c8ae7b7e9752437d827a183e4040e) [#8899](https://github.com/npm/cli/pull/8899) npm trust, per-command config (@reggi) +* [`cf56a1e`](https://github.com/npm/cli/commit/cf56a1e4df9c8ae7b7e9752437d827a183e4040e) [#8899](https://github.com/npm/cli/pull/8899) npm trust (@reggi) +* [`66d6e11`](https://github.com/npm/cli/commit/66d6e11f3ecdbc823ede24ef83257f3bb6e69d46) [#8965](https://github.com/npm/cli/pull/8965) add min-release-age (#8965) (@wraithgar) +### Dependencies +* [`aae84bf`](https://github.com/npm/cli/commit/aae84bf5a90bb42599b27631734a9899735d4016) [#8973](https://github.com/npm/cli/pull/8973) `pacote@21.3.1` +* [`8bcb675`](https://github.com/npm/cli/commit/8bcb6754b95628da78bd4b6ddcc8c8ff40f7d0fb) [#8973](https://github.com/npm/cli/pull/8973) `cidr-regex@5.0.2` +* [`f87aaab`](https://github.com/npm/cli/commit/f87aaab974931766b1372fbd5d5ef9daa645b1ad) [#8973](https://github.com/npm/cli/pull/8973) `lru-cache@11.2.6` +* [`acec871`](https://github.com/npm/cli/commit/acec871478eeb4cf75d89216feb9e6a70efc1d33) [#8973](https://github.com/npm/cli/pull/8973) `ssri@13.0.1` +* [`1e42a86`](https://github.com/npm/cli/commit/1e42a86aa2460d39e8e3e450025d7df75e911d87) [#8973](https://github.com/npm/cli/pull/8973) `glob@13.0.2` +* [`e1c08a4`](https://github.com/npm/cli/commit/e1c08a4cf10465c76f037bfe31c0666a183feb7c) [#8973](https://github.com/npm/cli/pull/8973) `is-cidr@6.0.3` +* [`dfb0e34`](https://github.com/npm/cli/commit/dfb0e3466b444a5e1f25f785d42e8b8936bf5c3f) [#8973](https://github.com/npm/cli/pull/8973) `semver@7.7.4` +* [`0ee7776`](https://github.com/npm/cli/commit/0ee7776b17bb0f1ae745ed9cb0db61347a64d37d) [#8973](https://github.com/npm/cli/pull/8973) `which@6.0.1` ### Chores - -* [`10256e8`](https://github.com/npm/cli/commit/10256e8cbe3583b65cb253a19ba9ee64f21c9584) [#7522](https://github.com/npm/cli/pull/7522) dev dependency updates (@wraithgar) -* [`dcfc3de`](https://github.com/npm/cli/commit/dcfc3deba2bb0066ec5d8b1870719f730adc2e97) [#7517](https://github.com/npm/cli/pull/7517) convert run-script tests to snapshots (#7517) (@lukekarrys) -* [`8add914`](https://github.com/npm/cli/commit/8add914841775f239acd838b1d8d52b251d0e1b2) [#7505](https://github.com/npm/cli/pull/7505) create single bug report issue template (#7505) (@lukekarrys) -* [`7c7fba4`](https://github.com/npm/cli/commit/7c7fba4fc92528287e1f2ef5fb8256e60760c201) [#7500](https://github.com/npm/cli/pull/7500) benchmarks: fix emoji reaction to comment (#7500) (@lukekarrys) -* [`d3b9587`](https://github.com/npm/cli/commit/d3b958756144d71c25cc4bd2020e040a940fbe3b) [#7494](https://github.com/npm/cli/pull/7494) disable progress on npm pack test (@wraithgar) -* [`67ebb66`](https://github.com/npm/cli/commit/67ebb66d3ffa61582f8dd63ddbb5679649a5d2a4) [#7494](https://github.com/npm/cli/pull/7494) disable color in config tests (@wraithgar) -* [`2ec2e75`](https://github.com/npm/cli/commit/2ec2e75ee81361a850bca643341d240441870334) [#7494](https://github.com/npm/cli/pull/7494) disable progress on shellout exit tests (@wraithgar) -* [`e9fdc9a`](https://github.com/npm/cli/commit/e9fdc9a792666d5b9aa73833c65516bafcb80863) [#7483](https://github.com/npm/cli/pull/7483) create smoke-publish-test.sh script (#7483) (@lukekarrys) -* [`1524cfd`](https://github.com/npm/cli/commit/1524cfd94daaca131ab16180c27323999fab07b3) [#7484](https://github.com/npm/cli/pull/7484) remove extra quotes from benchmark event_type (#7484) (@lukekarrys) -* [`9c4d3c4`](https://github.com/npm/cli/commit/9c4d3c402c77bd7aaa514ee9e02d7fd87223343e) [#7467](https://github.com/npm/cli/pull/7467) template-oss-apply (@lukekarrys) -* [`2b7ec54`](https://github.com/npm/cli/commit/2b7ec54f52f9e8aee568ccb4e34ce4a5733af21a) [#7467](https://github.com/npm/cli/pull/7467) `template-oss@4.22.0` (@lukekarrys) -* [`8ded848`](https://github.com/npm/cli/commit/8ded848b099297a12a81ec008d6229f3ad3494a6) [#7457](https://github.com/npm/cli/pull/7457) remove doctor snapshot stack traces (@lukekarrys) - -## [10.7.0](https://github.com/npm/cli/compare/v10.6.0...v10.7.0) (2024-04-30) - +* [`eb81df8`](https://github.com/npm/cli/commit/eb81df8f6acba2e8921f06983d3f8ba44ea79094) [#8973](https://github.com/npm/cli/pull/8973) dev dependency updates (@wraithgar) +* [`995e757`](https://github.com/npm/cli/commit/995e7579d66dfedbf20e3602b9523bc992dde139) [#8966](https://github.com/npm/cli/pull/8966) Clean up some todos, add tests for previously skipped blocks (@owlstronaut) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.3.0): `@npmcli/arborist@9.3.0` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.7.0): `@npmcli/config@10.7.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.1.1): `libnpmdiff@8.1.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.2.1): `libnpmexec@10.2.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.15): `libnpmfund@7.0.15` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.1.1): `libnpmpack@9.1.1` + +## [11.9.0](https://github.com/npm/cli/compare/v11.8.0...v11.9.0) (2026-02-04) ### Features - -* [`7e349f4`](https://github.com/npm/cli/commit/7e349f45363bb8dbe1cc803f8b48befc01aae7fd) [#7432](https://github.com/npm/cli/pull/7432) add spinner (#7432) (@lukekarrys) - +* [`f5f6cf7`](https://github.com/npm/cli/commit/f5f6cf7c9fc9315b96eb29c5c7d5ab63ad3a9122) [#8943](https://github.com/npm/cli/pull/8943) config: add --allow-git (@wraithgar) ### Bug Fixes - -* [`d679ce8`](https://github.com/npm/cli/commit/d679ce80fd9b761b2323777ec5cd84ebc5c164fe) [#7449](https://github.com/npm/cli/pull/7449) linting: no-unused-vars (@wraithgar) -* [`2558283`](https://github.com/npm/cli/commit/25582837b0ebb8c2de2932c04224332b11d0e1d5) [#7450](https://github.com/npm/cli/pull/7450) powershell: fallback to script root if globalPrefix does not exist (#7450) (@lukekarrys) -* [`bc4c342`](https://github.com/npm/cli/commit/bc4c3426c35201baff7230c2b3beee2cf5936296) [#7448](https://github.com/npm/cli/pull/7448) account for registries with no publisher in search (#7448) (@wraithgar) -* [`bcc781a`](https://github.com/npm/cli/commit/bcc781abf10b46aa5b04da996fc4602524be9b0e) [#7439](https://github.com/npm/cli/pull/7439) move run-script banners to stderr when in json mode (#7439) (@lukekarrys) -* [`104fcb5`](https://github.com/npm/cli/commit/104fcb53282653a1c5610a6590afecc207920a6b) [#7438](https://github.com/npm/cli/pull/7438) remove doctor log for each file permission check (#7438) (@lukekarrys) -* [`5230647`](https://github.com/npm/cli/commit/52306473da03123ef5623e9e152e10285c8097f3) [#7422](https://github.com/npm/cli/pull/7422) rewrite powershell scripts to use PSScriptRoot (#7422) (@lukekarrys) -* [`71cbd91`](https://github.com/npm/cli/commit/71cbd91b6f01875a99eeae989ea67489bdd0178d) [#7421](https://github.com/npm/cli/pull/7421) hide banner for exec and explore (#7421) (@lukekarrys) -* [`57ebebf`](https://github.com/npm/cli/commit/57ebebf03d55d4eda2b6439149a97b595a191aaf) [#7418](https://github.com/npm/cli/pull/7418) update repository.url in package.json (#7418) (@wraithgar) - -### Documentation - -* [`1674136`](https://github.com/npm/cli/commit/1674136bc14b0f708bb01f75d65474346c863bd9) [#7441](https://github.com/npm/cli/pull/7441) correct search help output (#7441) (@wraithgar) - +* [`2242f25`](https://github.com/npm/cli/commit/2242f2515826474a4fb8664fc679f1919ecaf458) [#8952](https://github.com/npm/cli/pull/8952) webauth: improve error messages around webauth in non-TTY (#8952) (@Andarist) ### Dependencies - -* [`80eec03`](https://github.com/npm/cli/commit/80eec03462e5747cb4434d43aff25939826b7850) [#7453](https://github.com/npm/cli/pull/7453) `@npmcli/redact@2.0.0` -* [`a7145d4`](https://github.com/npm/cli/commit/a7145d422485fcbcb9427efa775c15180c7ee1c2) [#7453](https://github.com/npm/cli/pull/7453) `npm-registry-fetch@17.0.0` -* [`a785766`](https://github.com/npm/cli/commit/a785766325141335cde39d43eb631062e32d6605) [#7453](https://github.com/npm/cli/pull/7453) `pacote@18.0.3` -* [`65d76db`](https://github.com/npm/cli/commit/65d76dbd2fb11c83141302500ec4a3f5128ff12f) [#7453](https://github.com/npm/cli/pull/7453) `npm-profile@9.0.2` -* [`cadc0f0`](https://github.com/npm/cli/commit/cadc0f0cad8909755ae8ac72f2dd5802a0d34943) [#7449](https://github.com/npm/cli/pull/7449) hoist production copy of sprintf-js -* [`2cffdfe`](https://github.com/npm/cli/commit/2cffdfef45b9a13d189f5059cc69fc7319620fda) [#7449](https://github.com/npm/cli/pull/7449) `lru-cache@10.2.2` -* [`432efb5`](https://github.com/npm/cli/commit/432efb5ee313ac5bd08642a9cef2b7c52da23ea9) [#7449](https://github.com/npm/cli/pull/7449) `make-fetch-happen@13.0.1` -* [`9da5738`](https://github.com/npm/cli/commit/9da57388ebd5c643c2a95bbf63abc745cad45ccc) [#7437](https://github.com/npm/cli/pull/7437) `@npmcli/run-script@8.1.0` (#7437) -* [`762888a`](https://github.com/npm/cli/commit/762888a3b603704c7c53a94a704b8a7f3edea918) [#7429](https://github.com/npm/cli/pull/7429) update dependencies for workspaces (#7429) -* [workspace](https://github.com/npm/cli/releases/tag/arborist-v7.5.1): `@npmcli/arborist@7.5.1` -* [workspace](https://github.com/npm/cli/releases/tag/config-v8.3.1): `@npmcli/config@8.3.1` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v8.0.5): `libnpmaccess@8.0.5` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.1.1): `libnpmdiff@6.1.1` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v8.1.0): `libnpmexec@8.1.0` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v5.0.9): `libnpmfund@5.0.9` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmhook-v10.0.4): `libnpmhook@10.0.4` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmorg-v6.0.5): `libnpmorg@6.0.5` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v7.0.1): `libnpmpack@7.0.1` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v9.0.7): `libnpmpublish@9.0.7` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmsearch-v7.0.4): `libnpmsearch@7.0.4` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmteam-v6.0.4): `libnpmteam@6.0.4` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v6.0.1): `libnpmversion@6.0.1` - +* [`332c9f3`](https://github.com/npm/cli/commit/332c9f355ff7c9a9a9e624100a84130a9b7c4162) [#8960](https://github.com/npm/cli/pull/8960) `glob@13.0.1` +* [`eca02c7`](https://github.com/npm/cli/commit/eca02c78c993af969f837c55068239468794932a) [#8960](https://github.com/npm/cli/pull/8960) `minimatch@10.1.2` `@isaacs/brace-expansion@5.0.1` +* [`b3f8475`](https://github.com/npm/cli/commit/b3f847568bcc95e1466668476cf3dcf1a4993ac3) [#8951](https://github.com/npm/cli/pull/8951) `minipass-fetch@5.0.1` +* [`924171b`](https://github.com/npm/cli/commit/924171bf5794f16f688b8544912a6205ec1d1fb5) [#8951](https://github.com/npm/cli/pull/8951) `is-cidr@6.0.2` +* [`4404002`](https://github.com/npm/cli/commit/4404002a16502e710625c7668cbc9b3a932d6fe8) [#8951](https://github.com/npm/cli/pull/8951) `ci-info@4.4.0` +* [`b65af73`](https://github.com/npm/cli/commit/b65af737d8b05b1fec4540dfefeda4edd84e4aea) [#8951](https://github.com/npm/cli/pull/8951) `lru-cache@11.2.5` +* [`164c355`](https://github.com/npm/cli/commit/164c35580ba9dd26461d9bcdf0c993b7a0eee5a6) [#8951](https://github.com/npm/cli/pull/8951) `tar@7.5.7` +* [`a74a19c`](https://github.com/npm/cli/commit/a74a19ce52501e63af19db5a542b793c8ad2477b) [#8951](https://github.com/npm/cli/pull/8951) `node-gyp@12.2.0` +* [`e0bc212`](https://github.com/npm/cli/commit/e0bc2129c9ba0ba5ac61c07e07aefd99adff5fb6) [#8943](https://github.com/npm/cli/pull/8943) `pacote@21.1.0` ### Chores - -* [`356c374`](https://github.com/npm/cli/commit/356c374817711845719902184547e1e0ac359b22) [#7453](https://github.com/npm/cli/pull/7453) fix test fixture for new redact behavior (@wraithgar) -* [`2fba4b7`](https://github.com/npm/cli/commit/2fba4b7b6218900fd895daf5218682edeb4253a4) [#7449](https://github.com/npm/cli/pull/7449) update devDependencies in lockfile (@wraithgar) - -## [10.6.0](https://github.com/npm/cli/compare/v10.5.2...v10.6.0) (2024-04-25) - +* [`4a82a8f`](https://github.com/npm/cli/commit/4a82a8f2e8873853ce3ef2f91c459ec9fd5aebde) [#8951](https://github.com/npm/cli/pull/8951) dev dependency updates (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.2.0): `@npmcli/arborist@9.2.0` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.6.0): `@npmcli/config@10.6.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.1.0): `libnpmdiff@8.1.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.2.0): `libnpmexec@10.2.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.14): `libnpmfund@7.0.14` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.1.0): `libnpmpack@9.1.0` + +## [11.8.0](https://github.com/npm/cli/compare/v11.7.0...v11.8.0) (2026-01-21) ### Features - -* [`9123de4`](https://github.com/npm/cli/commit/9123de4d282bfd19ea17ad613f5a2acab0e0e162) [#7373](https://github.com/npm/cli/pull/7373) do all ouput over proc-log events (@lukekarrys) -* [`9622597`](https://github.com/npm/cli/commit/9622597399ec93224fddf90a9209a98dbcfd6b2f) [#7339](https://github.com/npm/cli/pull/7339) refactor terminal display (#7339) (@lukekarrys) - +* [`545e861`](https://github.com/npm/cli/commit/545e86154cc847766ceb356c3b1229d0573314c0) [#8828](https://github.com/npm/cli/pull/8828) show proxy environment variables in npm config list (Max Black) ### Bug Fixes - -* [`0e74ee4`](https://github.com/npm/cli/commit/0e74ee42cbd2cbe438e64a2426767dad1868e70d) [#7416](https://github.com/npm/cli/pull/7416) clean up npm object (#7416) (@wraithgar) -* [`c060e60`](https://github.com/npm/cli/commit/c060e60a7ce767f6fdb32782c0d373e717df7856) [#7415](https://github.com/npm/cli/pull/7415) return command and argv from load (@lukekarrys) -* [`180b919`](https://github.com/npm/cli/commit/180b919d2322e55ec5d58bbd476c3ecc31880479) [#7415](https://github.com/npm/cli/pull/7415) remove unused npm.setCmd method (@lukekarrys) -* [`0708b3b`](https://github.com/npm/cli/commit/0708b3b2dbfc811b0e692133557b6b2e698519fd) [#7414](https://github.com/npm/cli/pull/7414) use name of level instead of label for logging prefixes (#7414) (@lukekarrys) -* [`7f4e667`](https://github.com/npm/cli/commit/7f4e66772ee631158b47fcfcd8e22b7b6b9b9cce) [#7403](https://github.com/npm/cli/pull/7403) redact when displaying non-ascii arguments (@lukekarrys) -* [`06202f0`](https://github.com/npm/cli/commit/06202f0e13d91f5ee6edfe2da6ee21bafbf18cca) [#7403](https://github.com/npm/cli/pull/7403) store unref promises for awaiting in tests (@lukekarrys) -* [`e5f1948`](https://github.com/npm/cli/commit/e5f1948a569224c59a9a4fdeb0e3b82312fb87c6) [#7403](https://github.com/npm/cli/pull/7403) run update notifier after exec but before waiting (@lukekarrys) -* [`f309c1c`](https://github.com/npm/cli/commit/f309c1cd8ab26b9cdc3b1224499aba345edfc582) [#7403](https://github.com/npm/cli/pull/7403) refactor: move timer and error logfile messages to lib/npm (@lukekarrys) -* [`43e6194`](https://github.com/npm/cli/commit/43e619480568493433af78208e2b3c48843185ef) [#7403](https://github.com/npm/cli/pull/7403) dont show run script banners in silent (@lukekarrys) -* [`694dba9`](https://github.com/npm/cli/commit/694dba9fd9a8d71facc7b832bf8f00ca9468e68a) [#7403](https://github.com/npm/cli/pull/7403) dont expose as many public properties of timers (@lukekarrys) -* [`7ca6d84`](https://github.com/npm/cli/commit/7ca6d8490b675c9d4c402ae8e41c9afd5871aa35) [#7403](https://github.com/npm/cli/pull/7403) use proc-log META for flush and force (@lukekarrys) -* [`2538438`](https://github.com/npm/cli/commit/25384388e01d1c9d6c4cae4a49149407b0024176) [#7403](https://github.com/npm/cli/pull/7403) dont write timing logs to file unless requested (@lukekarrys) -* [`7e04417`](https://github.com/npm/cli/commit/7e04417d4b084043300d1cdd5b4dce8ea7184d9e) [#7403](https://github.com/npm/cli/pull/7403) rename base-cmd to match other commands (@lukekarrys) -* [`fc68547`](https://github.com/npm/cli/commit/fc68547eb9b06a1a6a2a0feb7e422accec50230d) [#7403](https://github.com/npm/cli/pull/7403) remove some npm.load timers and exit earlier for --versions (@lukekarrys) -* [`28019d5`](https://github.com/npm/cli/commit/28019d50fdb1b2395199516694180edc7b4f8dd6) [#7403](https://github.com/npm/cli/pull/7403) cleanup: move cli specific files to separate dir (@lukekarrys) -* [`469f788`](https://github.com/npm/cli/commit/469f7885ca47f79bbd3c7171dc56a471a3e422a2) [#7403](https://github.com/npm/cli/pull/7403) cleanup: newlines and whitespace (@lukekarrys) -* [`4ab6401`](https://github.com/npm/cli/commit/4ab64013236925e7bceb9f88cfcc81f4a65f292f) [#7403](https://github.com/npm/cli/pull/7403) cleanup: dont nest files utils dir (@lukekarrys) -* [`78447d7`](https://github.com/npm/cli/commit/78447d7a35fab870456ba66eee408b2baddca23e) [#7399](https://github.com/npm/cli/pull/7399) prefer fs/promises over promisify (#7399) (@lukekarrys) -* [`d531f8b`](https://github.com/npm/cli/commit/d531f8b9237fabf640d421a8c4ea3c4284e00f0a) [#7407](https://github.com/npm/cli/pull/7407) Remove table output from search and tar summary (@wraithgar) -* [`c209e98`](https://github.com/npm/cli/commit/c209e989b405fa3e86df7015c22e6840e18313b8) [#7401](https://github.com/npm/cli/pull/7401) Remove table output from many commands (@wraithgar) -* [`ad7ab8c`](https://github.com/npm/cli/commit/ad7ab8c19994c1d2a452278edba65968185d3871) [#7388](https://github.com/npm/cli/pull/7388) perf: lazy loading optimizations (#7388) (@wraithgar) -* [`8eae4b3`](https://github.com/npm/cli/commit/8eae4b3b30a7375f0f9dd4172a8b683efe0bb354) [#7385](https://github.com/npm/cli/pull/7385) token: properly await registry request (#7385) (@wraithgar) -* [`9216d59`](https://github.com/npm/cli/commit/9216d5985fb3e2a2754be5bf0b1d43fc321cf723) [#7377](https://github.com/npm/cli/pull/7377) better output colors (#7377) (@wraithgar) -* [`6512112`](https://github.com/npm/cli/commit/65121122d99855541f63aa787f8ee8bb4eea4a3f) [#7378](https://github.com/npm/cli/pull/7378) use proc-log for all timers (@lukekarrys) -* [`2a80dab`](https://github.com/npm/cli/commit/2a80dab2ed1feedf3cd3af8ff7f41846567b2fd3) [#7370](https://github.com/npm/cli/pull/7370) typo in `npm access` usage (#7370) (@mbtools) - +* [`c2f784d`](https://github.com/npm/cli/commit/c2f784dbb5a83106558ff6ee7cc60bfc088ee9ed) [#8859](https://github.com/npm/cli/pull/8859) preserve serialNumber UUID in CycloneDX SBOM output #8837 (#8859) (@saksham-malhotra-27) +* [`f2c3af7`](https://github.com/npm/cli/commit/f2c3af7de1906b0517bba1e7e5b9247d57960d99) [#8840](https://github.com/npm/cli/pull/8840) more intuitive byte formatting boundaries for rounding (#8840) (@watilde) ### Documentation - -* [`dfa4cab`](https://github.com/npm/cli/commit/dfa4cabdccdd1c82cc160bb435c29c45ed05fdf4) [#7401](https://github.com/npm/cli/pull/7401) update output examples (@wraithgar) -* [`140b9c9`](https://github.com/npm/cli/commit/140b9c988d08beb6c3cd95b67cd4135ed32a19e6) [#7382](https://github.com/npm/cli/pull/7382) package-json: note that line endings are inferred (#7382) (@ertw) -* [`c16dd4e`](https://github.com/npm/cli/commit/c16dd4e46b58d6c4490284e6edc5c255862e322b) [#7367](https://github.com/npm/cli/pull/7367) Document that overrides only work in the root `package.json` (#7367) (@s100) - +* [`3474ec3`](https://github.com/npm/cli/commit/3474ec35fb579873d20a4b6747983ca369d61592) [#8866](https://github.com/npm/cli/pull/8866) fix typo/logic error in npm-dedupe docs (#8866) (@Schweinepriester) +* [`5552e46`](https://github.com/npm/cli/commit/5552e465125c72e5d591fb6dff76c450e78c7c70) [#8797](https://github.com/npm/cli/pull/8797) npm-install: explain package-lock.json behavior (#8797) (@MaxBlack-dev, Max Black) ### Dependencies - -* [`36adff3`](https://github.com/npm/cli/commit/36adff36c41f56315fe582e1e4dda29060f7fdf7) [#7408](https://github.com/npm/cli/pull/7408) `pacote@18.0.2` -* [`486d46c`](https://github.com/npm/cli/commit/486d46cd5b5678ad1ab6c23ee12cf7559477805a) [#7408](https://github.com/npm/cli/pull/7408) `@npmcli/installed-package-contents@2.1.0` -* [`157d0ae`](https://github.com/npm/cli/commit/157d0aebfe5710880d0c91bddee970316b8a6612) [#7408](https://github.com/npm/cli/pull/7408) `@npmcli/package-json@5.1.0` -* [`b0ca163`](https://github.com/npm/cli/commit/b0ca16310d9db944dd13f80ecce534c65eea42c5) [#7409](https://github.com/npm/cli/pull/7409) remove @npmcli/disparity-colors -* [`c77f035`](https://github.com/npm/cli/commit/c77f035fc18fdc0a9eb3ef0a7d1faf2c7aec6af3) [#7407](https://github.com/npm/cli/pull/7407) remove columnify -* [`2ec690d`](https://github.com/npm/cli/commit/2ec690da99fb441cdd7069480b42b6302e098005) [#7401](https://github.com/npm/cli/pull/7401) move cli-table3 to devDependencies -* [`fc6e291`](https://github.com/npm/cli/commit/fc6e291e9c2154c2e76636cb7ebf0a17be307585) [#7392](https://github.com/npm/cli/pull/7392) `proc-log@4.2.0` (#7392) -* [`38ed048`](https://github.com/npm/cli/commit/38ed048ac0d7a36785dbff0eeca3618cb7f084c5) [#7378](https://github.com/npm/cli/pull/7378) `@npmcli/metavuln-calculator@7.1.0` -* [`7678a3d`](https://github.com/npm/cli/commit/7678a3d92835457bb402c82e4ca7ea3fa734d23b) [#7378](https://github.com/npm/cli/pull/7378) `proc-log@4.1.0` -* [`87f6c09`](https://github.com/npm/cli/commit/87f6c094ac47f4e6eb5d5d6a03a0ad97711b51e9) [#7373](https://github.com/npm/cli/pull/7373) `@npmcli/metavuln-calculator@7.0.1` -* [`b8f8b41`](https://github.com/npm/cli/commit/b8f8b414d8ad9635e3efedc6e491c8c6e3df0973) [#7373](https://github.com/npm/cli/pull/7373) `@npmcli/run-script@8.0.0` -* [`79f79c7`](https://github.com/npm/cli/commit/79f79c7460be8a74f2b77c647100bcefd89b2efa) [#7373](https://github.com/npm/cli/pull/7373) `proc-log@4.0.0` -* [`9027266`](https://github.com/npm/cli/commit/90272661b16d861a5926af8ec394d32ec0f307fd) [#7373](https://github.com/npm/cli/pull/7373) `pacote@18.0.0` -* [`ee4b3e0`](https://github.com/npm/cli/commit/ee4b3e0e741545045dc03741c7147560961d867d) [#7373](https://github.com/npm/cli/pull/7373) `npm-registry-fetch@16.2.1` -* [`0e7789b`](https://github.com/npm/cli/commit/0e7789b7d9ec88c89edcdade9fc898c131ed492a) [#7373](https://github.com/npm/cli/pull/7373) `npm-profile@9.0.1` -* [`ac98fd3`](https://github.com/npm/cli/commit/ac98fd3a8514f2552555d2b8af74a52e64888797) [#7373](https://github.com/npm/cli/pull/7373) `npm-package-arg@11.0.2` -* [`9351570`](https://github.com/npm/cli/commit/93515700efbb2147a6e929cf117da9e6e87c0aca) [#7373](https://github.com/npm/cli/pull/7373) `@npmcli/package-json@5.0.3` -* [`d3a0cfa`](https://github.com/npm/cli/commit/d3a0cfad06ddffe6a3d4968257b7993aea68fc7c) [#7373](https://github.com/npm/cli/pull/7373) `@npmcli/git@5.0.6` -* [workspace](https://github.com/npm/cli/releases/tag/arborist-v7.5.0): `@npmcli/arborist@7.5.0` -* [workspace](https://github.com/npm/cli/releases/tag/config-v8.3.0): `@npmcli/config@8.3.0` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v8.0.4): `libnpmaccess@8.0.4` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.1.0): `libnpmdiff@6.1.0` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v8.0.0): `libnpmexec@8.0.0` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v5.0.8): `libnpmfund@5.0.8` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmhook-v10.0.3): `libnpmhook@10.0.3` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmorg-v6.0.4): `libnpmorg@6.0.4` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v7.0.0): `libnpmpack@7.0.0` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v9.0.6): `libnpmpublish@9.0.6` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmsearch-v7.0.3): `libnpmsearch@7.0.3` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmteam-v6.0.3): `libnpmteam@6.0.3` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v6.0.0): `libnpmversion@6.0.0` - +* [`f478ca0`](https://github.com/npm/cli/commit/f478ca0efb6e3dd7b32a3d7b51c896fdd5f5cd90) [#8919](https://github.com/npm/cli/pull/8919) `postcss-selector-parser@7.1.1` +* [`2b6a71f`](https://github.com/npm/cli/commit/2b6a71fae386e76e142dbab8e1bbc368d5ef0487) [#8919](https://github.com/npm/cli/pull/8919) `path-scurry@2.0.1` +* [`19096f2`](https://github.com/npm/cli/commit/19096f28883706a96a5146d4ec313dffbcc148f7) [#8919](https://github.com/npm/cli/pull/8919) `sigstore@4.1.0` +* [`e7f5d1e`](https://github.com/npm/cli/commit/e7f5d1e445f599c60791a849484c4c0167392d10) [#8919](https://github.com/npm/cli/pull/8919) `lru-cache@11.2.4` +* [`9e756ae`](https://github.com/npm/cli/commit/9e756ae2b51b8ae6b4661ab47a1401690b82ce31) [#8919](https://github.com/npm/cli/pull/8919) `ip-address@10.1.0` +* [`f951820`](https://github.com/npm/cli/commit/f95182001771ad5d52dfc57934d7ce1b97055b70) [#8919](https://github.com/npm/cli/pull/8919) `common-ancestor-path@2.0.0` +* [`7a949ad`](https://github.com/npm/cli/commit/7a949ad8967c93c6b38ed9d4ee469703d269eea5) [#8919](https://github.com/npm/cli/pull/8919) `@sigstore/verify@3.1.0` +* [`6979ce1`](https://github.com/npm/cli/commit/6979ce1e0455042038d953d1631eaf8ed5cbb90a) [#8919](https://github.com/npm/cli/pull/8919) `@sigstore/sign@4.1.0` +* [`b4a6a41`](https://github.com/npm/cli/commit/b4a6a41bcc17694047c85fd71b3155ab0cb29302) [#8919](https://github.com/npm/cli/pull/8919) `@sigstore/core@3.1.0` +* [`dc8a8e8`](https://github.com/npm/cli/commit/dc8a8e8090deffc244f836fde2328d6444fc8ffc) [#8919](https://github.com/npm/cli/pull/8919) `@sigstore/tuf@4.0.1` +* [`be221ea`](https://github.com/npm/cli/commit/be221eae2974a04fadb1c80fc423eb949e4df723) [#8919](https://github.com/npm/cli/pull/8919) `validate-npm-package-name@7.0.2` +* [`149823d`](https://github.com/npm/cli/commit/149823de9a920e8ea25ed11399d79d3758f592ef) [#8919](https://github.com/npm/cli/pull/8919) `diff@8.0.3` +* [`32b2001`](https://github.com/npm/cli/commit/32b2001f552078eac8f4ec863d704fc91346efe3) [#8919](https://github.com/npm/cli/pull/8919) `tar@7.5.4` ### Chores - -* [`3cbc258`](https://github.com/npm/cli/commit/3cbc25800bbd14a8b22ee3feddad715b3a6436d7) [#7403](https://github.com/npm/cli/pull/7403) test for early version exit (@lukekarrys) -* [`08e0c0e`](https://github.com/npm/cli/commit/08e0c0ed1ad7bc2f12b4f358eb3e6b18bdbca053) [#7403](https://github.com/npm/cli/pull/7403) move sigstore json files to fixtures dir (@lukekarrys) -* [`ea66e95`](https://github.com/npm/cli/commit/ea66e9534f4b9004f8b4c53a2f8adb7688ee9b36) [#7380](https://github.com/npm/cli/pull/7380) remove licensee as a devDependency (#7380) (@lukekarrys, @wraithgar) -* [`9333e9d`](https://github.com/npm/cli/commit/9333e9df9b6ad3143f084a25b0e7ea347c8094d3) [#7386](https://github.com/npm/cli/pull/7386) reduce windows shim test flakes (#7386) (@lukekarrys) - -## [10.5.2](https://github.com/npm/cli/compare/v10.5.1...v10.5.2) (2024-04-10) - +* [`8f599df`](https://github.com/npm/cli/commit/8f599df6a3888fd9a06a5c17748657cbb45076c3) [#8919](https://github.com/npm/cli/pull/8919) pin jsdom to 27.0.0 (@wraithgar) +* [`f4f1161`](https://github.com/npm/cli/commit/f4f1161520e6c2b4b9038d4bd723ccef235e4273) [#8919](https://github.com/npm/cli/pull/8919) dev dependency updates (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.10): `@npmcli/arborist@9.1.10` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.5.0): `@npmcli/config@10.5.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.13): `libnpmdiff@8.0.13` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.12): `libnpmexec@10.1.12` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.13): `libnpmfund@7.0.13` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.13): `libnpmpack@9.0.13` + +## [11.7.0](https://github.com/npm/cli/compare/v11.6.4...v11.7.0) (2025-12-09) +### Features +* [`b380d15`](https://github.com/npm/cli/commit/b380d155050be21a9ee5ce08d50e184c06a13f36) [#8697](https://github.com/npm/cli/pull/8697) add deduping to notices unless in verbose+ mode (@owlstronaut) ### Bug Fixes - -* [`ef381b1`](https://github.com/npm/cli/commit/ef381b1449c99e174437665aa767e7a9b60edf22) [#7363](https://github.com/npm/cli/pull/7363) use @npmcli/redact for url cleaning (#7363) (@lukekarrys) -* [`3760dd2`](https://github.com/npm/cli/commit/3760dd275aaa53cd2cee92e6a7b90aaf62f663cf) [#7361](https://github.com/npm/cli/pull/7361) perf: do less work loading config (#7361) (@wraithgar) -* [`64bcf4c`](https://github.com/npm/cli/commit/64bcf4cf09e284ca18988615ab8696b55d27d829) [#7360](https://github.com/npm/cli/pull/7360) perf: only initialize workpaces when we are inside a workspace (#7360) (@H4ad) -* [`5a28a29`](https://github.com/npm/cli/commit/5a28a29799aac2c89b4e7a3d5c1d1d880346b743) [#7352](https://github.com/npm/cli/pull/7352) perf: lazy load workspace dependency (#7352) (@H4ad) -* [`5fc0f9d`](https://github.com/npm/cli/commit/5fc0f9dfdac3f95fd2eb6855beb2020941b2a361) [#7347](https://github.com/npm/cli/pull/7347) lazy load validate npm package name on error message (#7347) (@H4ad) -* [`c929ed1`](https://github.com/npm/cli/commit/c929ed180b3d3361d1541737a4c3c9932cd480c6) [#7321](https://github.com/npm/cli/pull/7321) prioritize CLI flags over publishConfig settings (#7321) (@roni-berlin) -* [`70497cb`](https://github.com/npm/cli/commit/70497cbcd4e6b32948253b644ccd7a3f0ee29270) [#7346](https://github.com/npm/cli/pull/7346) perf: avoid importing the entire semver package for update-notifier (#7346) (@H4ad) - +* [`4ebb831`](https://github.com/npm/cli/commit/4ebb831d93f13cc0b980754bf36abb2982b131f7) [#8839](https://github.com/npm/cli/pull/8839) updates hints to use cli paradigm (@owlstronaut) +* [`7896e51`](https://github.com/npm/cli/commit/7896e51812d6b3d7f204f32a92a6721affd257a5) [#8838](https://github.com/npm/cli/pull/8838) update the token list text (@owlstronaut) +* [`8ab8668`](https://github.com/npm/cli/commit/8ab86685baee32ef9428ab202f60b8b631e40ca9) [#8836](https://github.com/npm/cli/pull/8836) query: support package-lock-only in workspaces (@watilde) +* [`35e8d38`](https://github.com/npm/cli/commit/35e8d38ef880239b5dd2c61a8112f6aa11d10eab) [#8322](https://github.com/npm/cli/pull/8322) properly handle newlines with input when using the spinner (#8322) (@mbtools) +* [`0c0faae`](https://github.com/npm/cli/commit/0c0faae91d47fe1303de77aae7c6b38709972d2f) [#8780](https://github.com/npm/cli/pull/8780) adduser: improve email prompt (#8780) (@mbtools) ### Documentation +* [`7f2ab9d`](https://github.com/npm/cli/commit/7f2ab9dac62b56343204e13194f8f53421c19f3b) [#8810](https://github.com/npm/cli/pull/8810) scripts: replace deprecated prepublish and install examples with prepare (Max Black) +* [`91ebab7`](https://github.com/npm/cli/commit/91ebab777e5bfac6f34537e58c228209f7cc961a) [#8847](https://github.com/npm/cli/pull/8847) remove note about token create being disabled (@owlstronaut) +* [`2030250`](https://github.com/npm/cli/commit/2030250fbce3ac99ab116b6aee7e4d06f395134b) [#8822](https://github.com/npm/cli/pull/8822) scripts: clarify prepare script runs with --production (Max Black) +* [`33a50d7`](https://github.com/npm/cli/commit/33a50d7981492e71f533448d93fc586429e603fd) [#8821](https://github.com/npm/cli/pull/8821) scripts: update npm_package_* environment variables documentation (Max Black) +* [`50508f9`](https://github.com/npm/cli/commit/50508f9b18051761ec466de85cf0ecbee3130165) [#8793](https://github.com/npm/cli/pull/8793) package-json: add documentation for type field (#8793) (@MaxBlack-dev, Max Black) +* [`aa1dd7e`](https://github.com/npm/cli/commit/aa1dd7e974176225973bd1aa1683ef4ae3c418eb) [#8823](https://github.com/npm/cli/pull/8823) scripts: document that prepare scripts run concurrently in workspaces (Max Black) +* [`3f48487`](https://github.com/npm/cli/commit/3f48487aa343003bce0e55e1dfcd5fc8a9b3e198) [#8820](https://github.com/npm/cli/pull/8820) package-spec: fix alias syntax in examples (Max Black) +* [`dd104da`](https://github.com/npm/cli/commit/dd104da7d7c2ddd00731df716a082595df4a89b0) [#8812](https://github.com/npm/cli/pull/8812) version: add note about git version requirements (Max Black) +* [`58afdcc`](https://github.com/npm/cli/commit/58afdcc2094bd245c9916a02a62640a76ace8e72) [#8792](https://github.com/npm/cli/pull/8792) install: clarify prerelease version range behavior (Max Black) +* [`9f818e8`](https://github.com/npm/cli/commit/9f818e8cdfb4f10e36c7659e9aa86ddc4633e503) [#8795](https://github.com/npm/cli/pull/8795) npm-view: clarify object property access syntax and provide examples (Max Black) +* [`39c2f2e`](https://github.com/npm/cli/commit/39c2f2ef890b3af97aad85f71fbcb148f8965259) [#8791](https://github.com/npm/cli/pull/8791) add examples for command line flags including --prefix (Max Black) +* [`1298530`](https://github.com/npm/cli/commit/1298530af04f6982b7ba8b2cb677f23090fb806f) [#8790](https://github.com/npm/cli/pull/8790) clarify version field can be omitted in package-lock (Max Black) +* [`090b6ca`](https://github.com/npm/cli/commit/090b6cacb8228b2050e0e3746655441d2739a2ab) [#8794](https://github.com/npm/cli/pull/8794) npx: clarify that arguments are passed to executed command (Max Black) +* [`a864f80`](https://github.com/npm/cli/commit/a864f80799b407ee90f6482d5eb966dd66d13b56) [#8787](https://github.com/npm/cli/pull/8787) document gypfile field in package.json (Max Black) +* [`2fc689d`](https://github.com/npm/cli/commit/2fc689dfa0a69d66d7599997b4fa51a64111a619) [#8788](https://github.com/npm/cli/pull/8788) add field access patterns to npm view (Max Black) +* [`4850639`](https://github.com/npm/cli/commit/48506391c6248837cfd357aec28f5a3beb3cf184) [#8796](https://github.com/npm/cli/pull/8796) package-json: add examples for replacing dependencies with forks in overrides (Max Black) +* [`4864dd4`](https://github.com/npm/cli/commit/4864dd4289272e310065ccd43b254e1d3232d07f) [#8798](https://github.com/npm/cli/pull/8798) npm-install: document engines field priority when installing packages (Max Black) +* [`95d25cd`](https://github.com/npm/cli/commit/95d25cd97d88baa3ae11c69d5e69a1e850c39701) [#8799](https://github.com/npm/cli/pull/8799) package-json: clarify repository field normalization during publish (Max Black) +* [`a367f9b`](https://github.com/npm/cli/commit/a367f9bdac86f34769acfc427200e11f21e0c3ce) [#8800](https://github.com/npm/cli/pull/8800) package-lock-json: clarify that version field may be omitted for certain dependencies (Max Black) +* [`ffc9b71`](https://github.com/npm/cli/commit/ffc9b713b6a4ef762d6231ade70b008e9f296cb7) [#8801](https://github.com/npm/cli/pull/8801) npm-install: clarify --tag does not override package.json (#8801) (@MaxBlack-dev, Max Black) +* [`73688ca`](https://github.com/npm/cli/commit/73688ca5eb984d0027abcc72980cc287a892e5c8) [#8735](https://github.com/npm/cli/pull/8735) clarify npm version behavior with prerelease versions (#8735) (@yashwantbezawada) +* [`4a32606`](https://github.com/npm/cli/commit/4a32606ff50c71309455a0e3324d5ca90c1bbecc) [#8785](https://github.com/npm/cli/pull/8785) updates the token create documentation (#8785) (@owlstronaut, @wraithgar) +### Chores +* [`54929ce`](https://github.com/npm/cli/commit/54929cef8e26a4698234e5d2499a43b746569b12) [#8836](https://github.com/npm/cli/pull/8836) update baseline-browser-mapping (@watilde) -* [`90ba1c9`](https://github.com/npm/cli/commit/90ba1c9fd6c1ea89173ed7712cf1da205732b164) [#7340](https://github.com/npm/cli/pull/7340) fix incorrect ISO 8601 reference (#7340) (@emmanuel-ferdman) ### Dependencies -* [`699a1de`](https://github.com/npm/cli/commit/699a1de9d22e6c552141f87e468f5b37ed825206) [#7362](https://github.com/npm/cli/pull/7362) `@npmcli/map-workspaces@3.0.6` -* [`49fb9b7`](https://github.com/npm/cli/commit/49fb9b7cc22a348f608ab443c6953d950955c9e2) [#7362](https://github.com/npm/cli/pull/7362) `socks@2.8.3` -* [`f69052e`](https://github.com/npm/cli/commit/f69052e16c21ce87c3f8f53a3769cc42ae68db63) [#7362](https://github.com/npm/cli/pull/7362) `@npmcli/package-json@5.0.2` -* [`c18a0ad`](https://github.com/npm/cli/commit/c18a0ade8c4e7f6e35ffa937aa7afe06351b4b60) [#7357](https://github.com/npm/cli/pull/7357) `sigstore@2.3.0` -* [`fd4153b`](https://github.com/npm/cli/commit/fd4153b3ccbc8d49b3aff90fed5e853f35fd6beb) [#7357](https://github.com/npm/cli/pull/7357) `socks@2.8.2` -* [`d6b705a`](https://github.com/npm/cli/commit/d6b705a474a39b83b3d75516a95e34af92793034) [#7357](https://github.com/npm/cli/pull/7357) `postcss-selector-parser@6.0.16` -* [`248c177`](https://github.com/npm/cli/commit/248c1771b8b406337ec96cffc6b8bc8f9b3b55b4) [#7357](https://github.com/npm/cli/pull/7357) `hasown@2.0.2` -* [`4af9e86`](https://github.com/npm/cli/commit/4af9e863d1a3ad4a934315113745bad4f3c29bb0) [#7357](https://github.com/npm/cli/pull/7357) `builtins@5.1.0` -* [`7546b56`](https://github.com/npm/cli/commit/7546b5608d86fdefc5d2f080cd9c0223150ab2f7) [#7357](https://github.com/npm/cli/pull/7357) `@npmcli/agent@2.2.2` -* [`d38fd4f`](https://github.com/npm/cli/commit/d38fd4f6035a6ec9fbd366079d6761cf9c25b471) [#7357](https://github.com/npm/cli/pull/7357) `spdx-expression-parse@4.0.0` -* [`913b326`](https://github.com/npm/cli/commit/913b326f62319c95df3b576dd71cdbb04be26782) [#7357](https://github.com/npm/cli/pull/7357) `is-cidr@5.0.5` -* [`84bbbd4`](https://github.com/npm/cli/commit/84bbbd4b61be12025cfa952c9d2a522a1b996245) [#7357](https://github.com/npm/cli/pull/7357) `@npmcli/package-json@5.0.1` -* [`a0f5048`](https://github.com/npm/cli/commit/a0f504808b81af7442f47343366724eea1bc8623) [#7357](https://github.com/npm/cli/pull/7357) `@npmcli/git@5.0.5` -* [workspace](https://github.com/npm/cli/releases/tag/arborist-v7.4.2): `@npmcli/arborist@7.4.2` -* [workspace](https://github.com/npm/cli/releases/tag/config-v8.2.2): `@npmcli/config@8.2.2` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.0.9): `libnpmdiff@6.0.9` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v7.0.10): `libnpmexec@7.0.10` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v5.0.7): `libnpmfund@5.0.7` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v6.0.9): `libnpmpack@6.0.9` - -### Chores - -* [`81be28d`](https://github.com/npm/cli/commit/81be28de88fb5f3951e782a474548214f61eef70) [#7357](https://github.com/npm/cli/pull/7357) dev dependency updates (@wraithgar) - -## [10.5.1](https://github.com/npm/cli/compare/v10.5.0...v10.5.1) (2024-04-03) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.9): `@npmcli/arborist@9.1.9` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.4.5): `@npmcli/config@10.4.5` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.12): `libnpmdiff@8.0.12` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.11): `libnpmexec@10.1.11` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.12): `libnpmfund@7.0.12` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.12): `libnpmpack@9.0.12` +## [11.6.4](https://github.com/npm/cli/compare/v11.6.3...v11.6.4) (2025-11-25) +### Documentation +* [`dfb83c7`](https://github.com/npm/cli/commit/dfb83c7887810abd555a2ab62a681858aabe2430) [#8749](https://github.com/npm/cli/pull/8749) add example for keywords field (#8749) (@MaxBlack-dev, Max Black) +* [`1b1e227`](https://github.com/npm/cli/commit/1b1e227d234dc6132832e1a65141260d3601838b) [#8750](https://github.com/npm/cli/pull/8750) remove outdated roadmap link (#8750) (@MaxBlack-dev, Max Black) +* [`1333d57`](https://github.com/npm/cli/commit/1333d576448c3868a29a65cf9cfb0d07ccfccd93) [#8752](https://github.com/npm/cli/pull/8752) clarify .npmrc naming convention for environment variable overrides (#8752) (@MaxBlack-dev) +* [`22cddb8`](https://github.com/npm/cli/commit/22cddb83f884c179258dabe6f20954246074c623) [#8755](https://github.com/npm/cli/pull/8755) add workspace dependencies example to workspaces (Max Black) +* [`17e154c`](https://github.com/npm/cli/commit/17e154cac7394b1baa3987c5b9b168762d9ba4ad) [#8756](https://github.com/npm/cli/pull/8756) standardize env vars to uppercase convention (Max Black) +* [`1e51a25`](https://github.com/npm/cli/commit/1e51a25d02508fbfa1d5d53602d35669115e55ff) [#8754](https://github.com/npm/cli/pull/8754) fix lifecycle event order for prepare script (Max Black) +* [`8d72bc9`](https://github.com/npm/cli/commit/8d72bc99dc705e04e25f24b05cac0f72934608b4) [#8753](https://github.com/npm/cli/pull/8753) add os, cpu, and funding fields to package-lock.json (Max Black) +### Dependencies +* [`f56bb13`](https://github.com/npm/cli/commit/f56bb133bbd07f92b32f776f310bcd2aa26cbdfc) [#8779](https://github.com/npm/cli/pull/8779) `proc-log@6.1.0` (#8779) +* [`f963223`](https://github.com/npm/cli/commit/f96322350e497f90a54c8a1cfd952b3329f00492) [#8770](https://github.com/npm/cli/pull/8770) `proggy@4.0.0` +* [`f51e4aa`](https://github.com/npm/cli/commit/f51e4aaf06ac6703abe053a95fe25b8efca3c527) [#8770](https://github.com/npm/cli/pull/8770) `nopt@9.0.0` +* [`2d15040`](https://github.com/npm/cli/commit/2d15040390697cd78c9a9db3f0dbafab51a6e3e9) [#8770](https://github.com/npm/cli/pull/8770) `@npmcli/query@5.0.0` +* [`9d77b84`](https://github.com/npm/cli/commit/9d77b84ce961a28941af8b1a597a03e308828cd4) [#8770](https://github.com/npm/cli/pull/8770) `@npmcli/installed-package-contents@4.0.0` +* [`e2ac092`](https://github.com/npm/cli/commit/e2ac092fdab0ccbf3b20abbac7ff1ebb7cda9a88) [#8770](https://github.com/npm/cli/pull/8770) `read@5.0.1` +* [`6e5bfd9`](https://github.com/npm/cli/commit/6e5bfd93f5423ab0b89fd81493969af108438066) [#8770](https://github.com/npm/cli/pull/8770) `init-package-json@8.2.4` +* [`7f8e237`](https://github.com/npm/cli/commit/7f8e2376e289fc46410f68b7c686d3868ad837c0) [#8770](https://github.com/npm/cli/pull/8770) `p-map@7.0.4` +* [`a4aa218`](https://github.com/npm/cli/commit/a4aa218fa0a3cc5fc65bc516bc4c83fd4bac7fd8) [#8770](https://github.com/npm/cli/pull/8770) `npm-user-validate@4.0.0` +* [`6430446`](https://github.com/npm/cli/commit/643044690be9554366e0cbd5bc42afa77c4acc45) [#8770](https://github.com/npm/cli/pull/8770) `npm-audit-report@7.0.0` +* [`58650dc`](https://github.com/npm/cli/commit/58650dc089c74d090c51d1cb2f269f2d605dcca0) [#8770](https://github.com/npm/cli/pull/8770) `@npmcli/fs@5.0.0` +* [`4a11146`](https://github.com/npm/cli/commit/4a11146aa7e3d06c42793ef5daf3c19b37bdc7ce) [#8770](https://github.com/npm/cli/pull/8770) `glob@13.0.0` +* [`00511d4`](https://github.com/npm/cli/commit/00511d426a7f8d761700b315a0f660854a782353) [#8770](https://github.com/npm/cli/pull/8770) `@npmcli/cacache@20.0.3` +* [`224afa2`](https://github.com/npm/cli/commit/224afa27174f43695ac308de9f849529419a59b2) [#8770](https://github.com/npm/cli/pull/8770) `@npmcli/map-workspaces@5.0.3` +* [`664ac34`](https://github.com/npm/cli/commit/664ac341efef746ac47d08fcd8cc4cc105f1445b) [#8770](https://github.com/npm/cli/pull/8770) `@npmcli/package-json@7.0.4` +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.8): `@npmcli/arborist@9.1.8` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.4.4): `@npmcli/config@10.4.4` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.11): `libnpmdiff@8.0.11` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.10): `libnpmexec@10.1.10` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.11): `libnpmfund@7.0.11` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.11): `libnpmpack@9.0.11` + +## [11.6.3](https://github.com/npm/cli/compare/v11.6.2...v11.6.3) (2025-11-19) ### Bug Fixes - -* [`17d97d2`](https://github.com/npm/cli/commit/17d97d266807f69cfc2a7a3982e8db126f90c48a) [#7334](https://github.com/npm/cli/pull/7334) use @npmcli/redact for log redactions (@lukekarrys) -* [`8cab136`](https://github.com/npm/cli/commit/8cab136f731c69be079be08d79e3514e01bbd563) [#7324](https://github.com/npm/cli/pull/7324) ensure maxSockets is respected (#7324) (@lukekarrys) -* [`9bffa13`](https://github.com/npm/cli/commit/9bffa13e0b96efe1039d9075fdcb11d5946b2f90) [#7320](https://github.com/npm/cli/pull/7320) query: properly return :missing nodes (#7320) (@wraithgar) -* [`9d4e85f`](https://github.com/npm/cli/commit/9d4e85f2379eded50b54f4e0b6f307031037f1ec) [#7297](https://github.com/npm/cli/pull/7297) search: include searchlimit option in help output (#7297) (@10xLaCroixDrinker) -* [`bdb3c28`](https://github.com/npm/cli/commit/bdb3c28167f757060474ef2b82c92f3a1f210972) [#7274](https://github.com/npm/cli/pull/7274) added check for dry-run (#7274) (@cod1r) -* [`7f1ab88`](https://github.com/npm/cli/commit/7f1ab8822a8d50403338595ab9f218e4d63f37fa) [#7271](https://github.com/npm/cli/pull/7271) more lightweight npm bin discovery in windows (#7271) (@wraithgar) - +* [`c6242d9`](https://github.com/npm/cli/commit/c6242d92e5227e0a772d9cfe474ea57776af79e0) [#8706](https://github.com/npm/cli/pull/8706) change npm profile to create tokens with GAT support (#8706) (@owlstronaut, @wraithgar) +* [`cbc6fa9`](https://github.com/npm/cli/commit/cbc6fa9cd7c582053be77a56677191313c7e8d98) [#8731](https://github.com/npm/cli/pull/8731) order of version information in error message (#8731) (@piotrd, @pd-be) +* [`11dbd7e`](https://github.com/npm/cli/commit/11dbd7e36287695801f02a43e53b24fc2d72a545) [#8709](https://github.com/npm/cli/pull/8709) display full token when creating authentication tokens (#8709) (@MaxBlack-dev, Max Black) +* [`49a4eef`](https://github.com/npm/cli/commit/49a4eefd613dbb60bcff3dac39129f70586d3cff) [#8676](https://github.com/npm/cli/pull/8676) use look behind regex for trailing slash stripping (#8676) (@wraithgar) +* [`b1aee62`](https://github.com/npm/cli/commit/b1aee62082d7b25ec07f64e906afd76840907fbd) [#8645](https://github.com/npm/cli/pull/8645) dep flag calculation (#8645) (@liamcmitchell) ### Documentation - -* [`1da5cf0`](https://github.com/npm/cli/commit/1da5cf0ace30d89edf05833b91ce80467c7864bd) [#7198](https://github.com/npm/cli/pull/7198) add link to engines section (#7198) (@uiolee) -* [`1114a12`](https://github.com/npm/cli/commit/1114a12f2b4691d403d0863d4dca44f25580f57d) [#7307](https://github.com/npm/cli/pull/7307) fix incorrect npm audit key response link (#7307) (@davidlj95) -* [`9807caf`](https://github.com/npm/cli/commit/9807cafbaf274eca2a0abbd04a9b2b55e850de9d) [#7304](https://github.com/npm/cli/pull/7304) update audit docs with provenance info (#7304) (@bdehamer) -* [`e1ecfa7`](https://github.com/npm/cli/commit/e1ecfa7829be91282373862669b92ef42b9e48df) [#7285](https://github.com/npm/cli/pull/7285) Correct capitalization for URL (#7285) (@coliff) - +* [`ca53c21`](https://github.com/npm/cli/commit/ca53c21e8a0f0e659e891415735e184443b8f48b) [#8745](https://github.com/npm/cli/pull/8745) add workspace usage examples (#8745) (@MaxBlack-dev, Max Black) +* [`e71ca0e`](https://github.com/npm/cli/commit/e71ca0e1934b805c97485b39501653655a54c919) [#8746](https://github.com/npm/cli/pull/8746) add --save flag to documentation (#8746) (@MaxBlack-dev, Max Black) +* [`06510a8`](https://github.com/npm/cli/commit/06510a8720fa180e9ef9093d9caee2e85bbc5165) [#8683](https://github.com/npm/cli/pull/8683) add ignore-scripts option to npm version help and docs (#8683) (@Tejas242) ### Dependencies - -* [`87a61fc`](https://github.com/npm/cli/commit/87a61fc8bb65c950cda389ab3d14ae250ab2345d) [#7334](https://github.com/npm/cli/pull/7334) `npm-registry-fetch@16.2.0` -* [`5469614`](https://github.com/npm/cli/commit/54696148f25986bcdf39e1acb5aca4bf09e7d1a0) [#7327](https://github.com/npm/cli/pull/7327) `init-package-json@6.0.2` -* [`5469614`](https://github.com/npm/cli/commit/54696148f25986bcdf39e1acb5aca4bf09e7d1a0) [#7327](https://github.com/npm/cli/pull/7327) `promzard@1.0.1` -* [`5469614`](https://github.com/npm/cli/commit/54696148f25986bcdf39e1acb5aca4bf09e7d1a0) [#7327](https://github.com/npm/cli/pull/7327) `read@3.0.1` (#7327) -* [`9ccff72`](https://github.com/npm/cli/commit/9ccff72c332e6062e6ebcf8123c7888d8d617091) [#7329](https://github.com/npm/cli/pull/7329) `tar@6.2.1` -* [`7201a00`](https://github.com/npm/cli/commit/7201a00632f5cedf50101e8411a4b3c514439efb) [#7329](https://github.com/npm/cli/pull/7329) `node-gyp@10.1.0` -* [`6fd94f2`](https://github.com/npm/cli/commit/6fd94f249f43080ae183da36b971981e8ad00882) [#7329](https://github.com/npm/cli/pull/7329) `minimatch@9.0.4` -* [`b048592`](https://github.com/npm/cli/commit/b048592a9583dca6f75a9c837edee57ab4e12ab0) [#7329](https://github.com/npm/cli/pull/7329) `ini@4.1.2` -* [`c54a84a`](https://github.com/npm/cli/commit/c54a84ab5fdd7513913518734c0ece5f3d3e39c9) [#7329](https://github.com/npm/cli/pull/7329) `glob@10.3.12` -* [`6853531`](https://github.com/npm/cli/commit/6853531da30bc8fecb776c823144766915b5e421) [#7329](https://github.com/npm/cli/pull/7329) `cli-table3@0.6.4` -* [`c9315cb`](https://github.com/npm/cli/commit/c9315cb240be02babbbd99585f7ef23679e1d963) [#7329](https://github.com/npm/cli/pull/7329) `binary-extensions@2.3.0` -* [`5bb0031`](https://github.com/npm/cli/commit/5bb003147423a644969c04222e2ba1b6cf407e6f) [#7329](https://github.com/npm/cli/pull/7329) `@sigstore/tuf@2.3.2` -* [`8cab136`](https://github.com/npm/cli/commit/8cab136f731c69be079be08d79e3514e01bbd563) [#7324](https://github.com/npm/cli/pull/7324) `agent-base@7.1.1` (@lukekarrys) -* [workspace](https://github.com/npm/cli/releases/tag/arborist-v7.4.1): `@npmcli/arborist@7.4.1` -* [workspace](https://github.com/npm/cli/releases/tag/config-v8.2.1): `@npmcli/config@8.2.1` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v8.0.3): `libnpmaccess@8.0.3` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.0.8): `libnpmdiff@6.0.8` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v7.0.9): `libnpmexec@7.0.9` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v5.0.6): `libnpmfund@5.0.6` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmhook-v10.0.2): `libnpmhook@10.0.2` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmorg-v6.0.3): `libnpmorg@6.0.3` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v6.0.8): `libnpmpack@6.0.8` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v9.0.5): `libnpmpublish@9.0.5` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmsearch-v7.0.2): `libnpmsearch@7.0.2` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmteam-v6.0.2): `libnpmteam@6.0.2` - +* [`7f72238`](https://github.com/npm/cli/commit/7f7223833b9f655ea82039cf389ed8d03fb3b212) [#8723](https://github.com/npm/cli/pull/8723) `cacache@20.0.2` +* [`7ac9db8`](https://github.com/npm/cli/commit/7ac9db8564312ffd57a8f622634d6f3de080c472) [#8723](https://github.com/npm/cli/pull/8723) `init-package-json@8.2.3` +* [`41e97c6`](https://github.com/npm/cli/commit/41e97c65d1d9d0bf7fa80d4b018ff4c051b1487b) [#8723](https://github.com/npm/cli/pull/8723) `validate-npm-package-name@7.0.0` +* [`6b1fbe1`](https://github.com/npm/cli/commit/6b1fbe1ef3db7f5782809abdcdf6c53ff7542330) [#8723](https://github.com/npm/cli/pull/8723) `npm-package-arg@13.0.2` +* [`aa1d486`](https://github.com/npm/cli/commit/aa1d486a4e4a82de16d4c63154a1b1a89ad09e6d) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/promise-spawn@9.0.1` +* [`599c819`](https://github.com/npm/cli/commit/599c819e525f235bab08c9395e7f357d4d2454a6) [#8723](https://github.com/npm/cli/pull/8723) `which@6.0.0` +* [`e49286e`](https://github.com/npm/cli/commit/e49286e2189dfe1604d957ccc415038957a64d19) [#8723](https://github.com/npm/cli/pull/8723) `ini@5.0.0` +* [`b7c9f96`](https://github.com/npm/cli/commit/b7c9f960063da93c8476739d1d6a717746255f93) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/promise-spawn@9.0.0` +* [`8cc9f70`](https://github.com/npm/cli/commit/8cc9f70c2769f068ea0ef77a602162cdd949998e) [#8723](https://github.com/npm/cli/pull/8723) `ssri@13.0.0` +* [`0b7274f`](https://github.com/npm/cli/commit/0b7274fa39edacc7103eacf2a72c074d01451284) [#8723](https://github.com/npm/cli/pull/8723) `pacote@21.0.4` +* [`59b3c6a`](https://github.com/npm/cli/commit/59b3c6adf5fb7e5c8e0f990ade7417677270057a) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/redact@4.0.0` +* [`578abad`](https://github.com/npm/cli/commit/578abad64d57dee1db460f1013c8514099e08136) [#8723](https://github.com/npm/cli/pull/8723) `node-gyp@12.1.0` +* [`89c4151`](https://github.com/npm/cli/commit/89c4151a9182ddb77eff1beaeaaa2c0279578a2e) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/git@7.0.1` +* [`c6d109d`](https://github.com/npm/cli/commit/c6d109d7ad59b0be87225917e6393bcc9838f64d) [#8723](https://github.com/npm/cli/pull/8723) `make-fetch-happen@15.0.3` +* [`34d8599`](https://github.com/npm/cli/commit/34d8599987bdd4335391394fc00f80b395fb3a7c) [#8723](https://github.com/npm/cli/pull/8723) `npm-registry-fetch@19.1.1` +* [`4811a86`](https://github.com/npm/cli/commit/4811a86a563d4361b15dd33415857410785a8e81) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/run-script@10.0.3` +* [`6cb77df`](https://github.com/npm/cli/commit/6cb77df37989cb7c165cb2c35c735fb12dc1385a) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/installed-package-contents@4.0.0` +* [`05ac7a7`](https://github.com/npm/cli/commit/05ac7a7ea2a4d258658537a19ba350e07df34fda) [#8723](https://github.com/npm/cli/pull/8723) `proc-log@6.0.0` +* [`0a74f6d`](https://github.com/npm/cli/commit/0a74f6d1d8643f3a089f6e63502df77e6e3038ff) [#8723](https://github.com/npm/cli/pull/8723) `bin-links@6.0.0` +* [`c02ce5c`](https://github.com/npm/cli/commit/c02ce5c132ea6e2b3d1941520228b10a10ad50f1) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/package-json@7.0.2` +* [`9c0cefa`](https://github.com/npm/cli/commit/9c0cefa8417d9e14ee19dd5e833019f0f99ce837) [#8723](https://github.com/npm/cli/pull/8723) `json-parse-even-better-errors@5.0.0` +* [`041b9b2`](https://github.com/npm/cli/commit/041b9b29b30c539c5bf8b8cd26ea2202f94862b3) [#8723](https://github.com/npm/cli/pull/8723) `parse-conflict-json@5.0.1` +* [`a1b0fea`](https://github.com/npm/cli/commit/a1b0feac64ff681b2aec6938eb5136f5e177a07a) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/name-from-folder@4.0.0` +* [`a085745`](https://github.com/npm/cli/commit/a085745da65662f5ce02933b99109f77542fc3bb) [#8723](https://github.com/npm/cli/pull/8723) `abbrev@4.0.0` +* [`00d9c7d`](https://github.com/npm/cli/commit/00d9c7da4173cd48c4295d32d4d8b47d3c8d8701) [#8723](https://github.com/npm/cli/pull/8723) `nopt@9.0.0` +* [`3404dca`](https://github.com/npm/cli/commit/3404dca3d986d1bf0de3e74cf8b61856778711c6) [#8723](https://github.com/npm/cli/pull/8723) `npm-install-checks@8.0.0` +* [`542fcf3`](https://github.com/npm/cli/commit/542fcf3eee92cc41e86838c97c4036a97d749155) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/node-gyp@5.0.0` +* [`89e14d3`](https://github.com/npm/cli/commit/89e14d376fa4d0dc3bb15fefcd932e3f949dbbaa) [#8723](https://github.com/npm/cli/pull/8723) `tar@7.5.2` +* [`5383f3a`](https://github.com/npm/cli/commit/5383f3aa680a028bc6f66ce76383d0259cc5a80d) [#8723](https://github.com/npm/cli/pull/8723) `npm-registry-fetch@19.1.0` +* [`1bb9a7d`](https://github.com/npm/cli/commit/1bb9a7d4ce779cca184d665c7ee4a4d3c9494168) [#8723](https://github.com/npm/cli/pull/8723) `npm-profile@12.0.1` +* [`de619a4`](https://github.com/npm/cli/commit/de619a40eccaa34eafb68b026bd6790ec38d2249) [#8723](https://github.com/npm/cli/pull/8723) `npm-pick-manifest@11.0.3` +* [`0e042ec`](https://github.com/npm/cli/commit/0e042ec4ed6eab646c645506378d409746b324bc) [#8723](https://github.com/npm/cli/pull/8723) `npm-packlist@10.0.3` +* [`2a3c338`](https://github.com/npm/cli/commit/2a3c33871471f327444a0e477199b3c1885683ed) [#8723](https://github.com/npm/cli/pull/8723) `node-gyp@11.5.0` +* [`b96e86c`](https://github.com/npm/cli/commit/b96e86cca5b0c63d98f3cfb92883f9a26882a1dd) [#8723](https://github.com/npm/cli/pull/8723) `minimatch@10.1.1` +* [`d347329`](https://github.com/npm/cli/commit/d347329513229ed2ba5954b996c322e9fd3d807d) [#8723](https://github.com/npm/cli/pull/8723) `exponential-backoff@3.1.3` +* [`d6830f4`](https://github.com/npm/cli/commit/d6830f4fac3b03090d97dce4cac26d5ff0b903d7) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/run-script@10.0.2` +* [`bcc7ec8`](https://github.com/npm/cli/commit/bcc7ec83ad69b2a80d98cfced94553d7f6e8c943) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/metavuln-calculator@9.0.3` +* [`7a419df`](https://github.com/npm/cli/commit/7a419df651b3d8d6fbf9571b80d2f4009e7a5e37) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/map-workspaces@5.0.1` ### Chores - -* [`8cab136`](https://github.com/npm/cli/commit/8cab136f731c69be079be08d79e3514e01bbd563) [#7324](https://github.com/npm/cli/pull/7324) add smoke-test for large prod installs (@lukekarrys) -* [`0dab381`](https://github.com/npm/cli/commit/0dab3810e6b84e1b4afcc2a315c878fffccb328b) [#7258](https://github.com/npm/cli/pull/7258) `jsdom@24.0.0` (#7258) (@wraithgar) -* [`af3c48e`](https://github.com/npm/cli/commit/af3c48e074d03caebaa8ed24d39405329f545497) [#7262](https://github.com/npm/cli/pull/7262) test refactor (#7262) (@wraithgar) - -## [10.5.0](https://github.com/npm/cli/compare/v10.4.0...v10.5.0) (2024-02-28) - -### Features - -* [`2366edc`](https://github.com/npm/cli/commit/2366edcaf2b32b5d1c6a7c03184c59eef0e08eae) [#7218](https://github.com/npm/cli/pull/7218) query: add :vuln pseudo selector (@wraithgar) -* [`4f3ddbb`](https://github.com/npm/cli/commit/4f3ddbbe88df7c94d1e06e660928a962e973f332) [#5966](https://github.com/npm/cli/pull/5966) add --expect-entries to `npm query` (@wraithgar) - +* [`32bdd83`](https://github.com/npm/cli/commit/32bdd833f83cf2a939ed56eba1972d5d729c677c) [#8723](https://github.com/npm/cli/pull/8723) fix package-lock (@wraithgar) +* [`4bff14b`](https://github.com/npm/cli/commit/4bff14b536f70b998b38ca984cbcab94a6c65bf9) [#8670](https://github.com/npm/cli/pull/8670) write tarball to testDir (#8670) (@wraithgar) +* [`679486b`](https://github.com/npm/cli/commit/679486b095f262d478daa21629d01f68f0240c9b) [#8672](https://github.com/npm/cli/pull/8672) fix lockfile (#8672) (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.7): `@npmcli/arborist@9.1.7` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.4.3): `@npmcli/config@10.4.3` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.10): `libnpmdiff@8.0.10` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.9): `libnpmexec@10.1.9` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.10): `libnpmfund@7.0.10` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.10): `libnpmpack@9.0.10` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v11.1.3): `libnpmpublish@11.1.3` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v8.0.3): `libnpmversion@8.0.3` + +## [11.6.2](https://github.com/npm/cli/compare/v11.6.1...v11.6.2) (2025-10-08) ### Bug Fixes - -* [`818957c`](https://github.com/npm/cli/commit/818957c0f88c859bf3ea90ff440ec5d9d9e990b9) [#7158](https://github.com/npm/cli/pull/7158) pack, publish: default foreground-scripts to true (#7158) (@ljharb) -* [`d04111d`](https://github.com/npm/cli/commit/d04111d48ca59fce27909712b328fe5cfc4d016d) [#7197](https://github.com/npm/cli/pull/7197) view: filter out invalid semver (#7197) (@wraithgar) -* [`b0a3ba0`](https://github.com/npm/cli/commit/b0a3ba0b99ce5920722244f1ccb8b830826abef4) [#7195](https://github.com/npm/cli/pull/7195) prevent adding invalid dist-tag (#7195) (@wraithgar) - +* [`c54d1e9`](https://github.com/npm/cli/commit/c54d1e96f37e7fd4bf2645c4905535c9b3d93e3b) [#8633](https://github.com/npm/cli/pull/8633) progress bar code cleanup (#8633) (@wraithgar) +* [`d352e27`](https://github.com/npm/cli/commit/d352e27a679b1b7f4417ff5f7e3ac73fe13b403a) [#8629](https://github.com/npm/cli/pull/8629) do not redact notice logs going to stdout (#8629) (@wraithgar) +* [`5ac3678`](https://github.com/npm/cli/commit/5ac3678feabbb28b1d0d8a78838bf8da79f63c1b) [#8617](https://github.com/npm/cli/pull/8617) spelling in ./lib and ./test/lib (#8617) (@jsoref) +* [`9197995`](https://github.com/npm/cli/commit/9197995ef0b760738454f2d255c0683d0731b24c) [#8619](https://github.com/npm/cli/pull/8619) spelling (#8619) (@jsoref) +* [`dd884e3`](https://github.com/npm/cli/commit/dd884e371c1fba7e2b7c1540baec405dd30ac3e7) [#8618](https://github.com/npm/cli/pull/8618) spelling (#8618) (@jsoref) +* [`f6028e6`](https://github.com/npm/cli/commit/f6028e67aa1b2696e60e115d870182a026bae07f) [#8614](https://github.com/npm/cli/pull/8614) skip redacting urls meant for opening by the user (#8614) (@wraithgar, @jolyndenning) +* [`54fd27f`](https://github.com/npm/cli/commit/54fd27f9f6af54ca9fd11165aafbc8a13a38f39e) [#8602](https://github.com/npm/cli/pull/8602) refactor node.ideallyInert to node.inert (#8602) (@liamcmitchell) +* [`79e3c1e`](https://github.com/npm/cli/commit/79e3c1eff776ed7bbc76c1aa53b02cfdea40a6e7) [#8593](https://github.com/npm/cli/pull/8593) use @npmcli/package-json to normalize package data (@wraithgar) ### Documentation - -* [`c4741fe`](https://github.com/npm/cli/commit/c4741fee8b4e6cdca90c6773385ff710c8b3f7f5) [#7254](https://github.com/npm/cli/pull/7254) Remove additional example and comments about uninstall script (#7254) (@rveerd) -* [`686a622`](https://github.com/npm/cli/commit/686a622480d32eabf2d69982e422ba3dcd8a6f7c) [#7247](https://github.com/npm/cli/pull/7247) scope: update example command to work in windows (#7247) (@robertobasile84) -* [`95b5057`](https://github.com/npm/cli/commit/95b505738a73ba740227a41b8c7c87013af5acaf) [#5966](https://github.com/npm/cli/pull/5966) clarify in-range and out-of-range in dependency selectors (@wraithgar) -* [`5b7184f`](https://github.com/npm/cli/commit/5b7184f3aaf5a9ca58418b6d029616088964ed0a) [#7190](https://github.com/npm/cli/pull/7190) workspaces: fix grammar (#7190) (@alekstech) -* [`0dd03f9`](https://github.com/npm/cli/commit/0dd03f9450e0cf57fa85ad2ef74b5a54f3c775a9) [#7182](https://github.com/npm/cli/pull/7182) fix typos (#7182) (@GoodDaisy) - +* [`0469c5e`](https://github.com/npm/cli/commit/0469c5ebec7d4998f957d7c69702796af6797c57) [#8639](https://github.com/npm/cli/pull/8639) rewrap markdown (#8639) (@jsoref) +* [`9ceb9c1`](https://github.com/npm/cli/commit/9ceb9c1d18d2c52a5c3328b4939e979baca7edea) [#8636](https://github.com/npm/cli/pull/8636) rewrap markdown (#8636) (@jsoref) +* [`6324370`](https://github.com/npm/cli/commit/63243709429ab7d95f360caebce6c31946d41857) [#8616](https://github.com/npm/cli/pull/8616) fix spelling (#8616) (@jsoref) +* [`1b0429a`](https://github.com/npm/cli/commit/1b0429af3b837e12fc5063d153393641435a856d) [#8607](https://github.com/npm/cli/pull/8607) Fix spelling (#8607) (@jsoref) +* [`7fbe07a`](https://github.com/npm/cli/commit/7fbe07a6ad9eff81a41776fb6068fce9e7b557d1) [#8603](https://github.com/npm/cli/pull/8603) clean up deprecated `npm access` commands (#8603) (@jsoref) ### Dependencies - -* [`16d4c9f`](https://github.com/npm/cli/commit/16d4c9f0e48a18719f1461460504a4228f8f663d) [#7218](https://github.com/npm/cli/pull/7218) `@npmcli/query@3.1.0` -* [`06247d1`](https://github.com/npm/cli/commit/06247d18fd3573d48b220512e84f87eaab06210a) [#7242](https://github.com/npm/cli/pull/7242) `spdx-license-ids@3.0.17` -* [`79d1e0b`](https://github.com/npm/cli/commit/79d1e0bc9f781b02af876f0615595976958ca410) [#7242](https://github.com/npm/cli/pull/7242) `spdx-exceptions@2.5.0` -* [`67e853a`](https://github.com/npm/cli/commit/67e853a507ab31af5b82fd3fcbcb2fe2f18cad5d) [#7242](https://github.com/npm/cli/pull/7242) `socks@2.8.0` -* [`4c9fe4b`](https://github.com/npm/cli/commit/4c9fe4be4df39960cfadef2ca07465c90d9ee414) [#7242](https://github.com/npm/cli/pull/7242) `lru-cache@10.2.0` -* [`4a50c5a`](https://github.com/npm/cli/commit/4a50c5adaa0f28a8e9f6433c34b0eedfc73885a1) [#7242](https://github.com/npm/cli/pull/7242) `https-proxy-agent@7.0.4` -* [`ed3f254`](https://github.com/npm/cli/commit/ed3f254a09d8f0da49e927e8b7fbd81c1232208e) [#7242](https://github.com/npm/cli/pull/7242) `http-proxy-agent@7.0.2` -* [`8ec4fd5`](https://github.com/npm/cli/commit/8ec4fd541be937a965e685ad4dbbfb57ae3b2462) [#7242](https://github.com/npm/cli/pull/7242) `hasown@2.0.1` -* [`98b1189`](https://github.com/npm/cli/commit/98b11894b770065979c8fefb87861c156ad0c895) [#7242](https://github.com/npm/cli/pull/7242) `@npmcli/agent@2.2.1` -* [`dafa903`](https://github.com/npm/cli/commit/dafa903fe9083343fd17bdd3a5acc6f9acc8f356) [#7242](https://github.com/npm/cli/pull/7242) `sigstore@2.2.2` -* [`d0bcb76`](https://github.com/npm/cli/commit/d0bcb76bd635eefcb1fae39e831e227a1852ef68) [#7242](https://github.com/npm/cli/pull/7242) `diff@5.2.0` -* [`a13808e`](https://github.com/npm/cli/commit/a13808e2e8ed0507e12ad27f8b212e5b0b6ccae8) [#7242](https://github.com/npm/cli/pull/7242) `semver@7.6.0` -* [`d6521ac`](https://github.com/npm/cli/commit/d6521ac9c43ccf909ff4d1564dffa0f07e260503) [#7242](https://github.com/npm/cli/pull/7242) `@sigstore/tuf@2.3.1` -* [`43cac2f`](https://github.com/npm/cli/commit/43cac2f990aefca283d49e26ff83ba5d6fb28313) [#7242](https://github.com/npm/cli/pull/7242) `ip@2.0.1` -* [workspace](https://github.com/npm/cli/releases/tag/arborist-v7.4.0): `@npmcli/arborist@7.4.0` -* [workspace](https://github.com/npm/cli/releases/tag/config-v8.2.0): `@npmcli/config@8.2.0` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.0.7): `libnpmdiff@6.0.7` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v7.0.8): `libnpmexec@7.0.8` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v5.0.5): `libnpmfund@5.0.5` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v6.0.7): `libnpmpack@6.0.7` - +* [`fa7cc6f`](https://github.com/npm/cli/commit/fa7cc6f9338e6d9c0be1dbe7002d683fd389794a) [#8662](https://github.com/npm/cli/pull/8662) `ci-info@4.3.1` (#8662) +* [`b05461b`](https://github.com/npm/cli/commit/b05461b6b16f262179efdea45fccf388f88ddc51) [#8663](https://github.com/npm/cli/pull/8663) `@sigstore/sign@4.0.1` (#8663) +* [`c31de22`](https://github.com/npm/cli/commit/c31de22970930bedf43c1f92ff771bccf435271b) [#8661](https://github.com/npm/cli/pull/8661) downgrade ci-info to 4.3.0 (#8661) (@wraithgar) +* [`c5191b5`](https://github.com/npm/cli/commit/c5191b542a9a49edf121be7127110e2958309df0) [#8659](https://github.com/npm/cli/pull/8659) `ci-info@4.3.1` +* [`f255c92`](https://github.com/npm/cli/commit/f255c92abf6281af7b7f148b9683194ad09d9ba9) [#8659](https://github.com/npm/cli/pull/8659) `hosted-git-info@9.0.2` +* [`bdaf323`](https://github.com/npm/cli/commit/bdaf323a160e47862ca228fa82e90555dcb567a8) [#8659](https://github.com/npm/cli/pull/8659) `is-cidr@6.0.1` +* [`a33f106`](https://github.com/npm/cli/commit/a33f1062c3cacd889cea0d989de77a704931f54c) [#8659](https://github.com/npm/cli/pull/8659) `lru-cache@11.2.2` +* [`8044e07`](https://github.com/npm/cli/commit/8044e07000c2b00e7db33693b1f7fb8e96978e02) [#8659](https://github.com/npm/cli/pull/8659) `npm-package-arg@13.0.1` +* [`f577504`](https://github.com/npm/cli/commit/f5775043e7d2739256db20937ae072a1b1b3fb57) [#8659](https://github.com/npm/cli/pull/8659) `npm-packlist@10.0.2` +* [`9aa4fa6`](https://github.com/npm/cli/commit/9aa4fa6687ee85a5c0085b3c3c96330eb9a9c7df) [#8659](https://github.com/npm/cli/pull/8659) `semver@7.7.3` +* [`fe9484a`](https://github.com/npm/cli/commit/fe9484a17707f5a6bc16cdc91f29f848a4b54d31) [#8593](https://github.com/npm/cli/pull/8593) remove normalize-package-data ### Chores - -* [`d6bc684`](https://github.com/npm/cli/commit/d6bc6840edce1957c0ea0ed618819cbfe23fa611) [#7242](https://github.com/npm/cli/pull/7242) update devDependencies in lockfile (@wraithgar) - -## [10.4.0](https://github.com/npm/cli/compare/v10.3.0...v10.4.0) (2024-01-24) - -### Features - -* [`35a098c`](https://github.com/npm/cli/commit/35a098cc54ef208c53e7329bfb65a7e5656c559b) [#7175](https://github.com/npm/cli/pull/7175) display tree diff on `--long` (@wraithgar) -* [`dffca29`](https://github.com/npm/cli/commit/dffca29f0690be82692eaa44a1dd02a0807a70ae) [#7174](https://github.com/npm/cli/pull/7174) format: print `--dry-run` diffs in table format (#7174) (@ritaaktay) -* [`6d5f9ac`](https://github.com/npm/cli/commit/6d5f9acd0dc7f755a9ef4d27e1dac7076ec7e469) [#7133](https://github.com/npm/cli/pull/7133) dedupe - display difference when `--dry-run` is enabled (#7133) (@Blaumaus) - +* [`b3409f4`](https://github.com/npm/cli/commit/b3409f480fef2b9885fd071c951ad8313de2754e) [#8659](https://github.com/npm/cli/pull/8659) dev dependency updates (@wraithgar) +* [`e8de81b`](https://github.com/npm/cli/commit/e8de81bc8202cfe1253676fd3f9785508e9051a6) [#8643](https://github.com/npm/cli/pull/8643) Add automatically generated annotation to dependencies.md (#8643) (@jsoref) +* [`67cfaf3`](https://github.com/npm/cli/commit/67cfaf35295fa2f5d7aa01d37c423c60ad7afeca) [#8627](https://github.com/npm/cli/pull/8627) fix spelling: different (#8627) (@jsoref) +* [`17ddc0d`](https://github.com/npm/cli/commit/17ddc0d6af1b56c4670b36b2c2705d31bdfa7749) [#8622](https://github.com/npm/cli/pull/8622) fix spelling (#8622) (@jsoref) +* [`c3e1790`](https://github.com/npm/cli/commit/c3e1790c98d5c7fabc92bcfb1a5fa170f4c7fc1d) [#8605](https://github.com/npm/cli/pull/8605) Remove reference to nonexistent calendar (#8605) (@jsoref) +* [`ac9143e`](https://github.com/npm/cli/commit/ac9143eafd46a89f707f525381b0ddb109b3beb6) [#8604](https://github.com/npm/cli/pull/8604) Improve link accessibility for screen reader users (#8604) (@jsoref) +* [`62d73e7`](https://github.com/npm/cli/commit/62d73e763fa2deffa629a4451a80b7e58032b8e0) [#8601](https://github.com/npm/cli/pull/8601) remove references to benchmarks workflow (#8601) (@jsoref) +* [`bb4b739`](https://github.com/npm/cli/commit/bb4b73953ada43285aa43dad626f48dafc53fea2) [#8598](https://github.com/npm/cli/pull/8598) remove stale comment (#8598) (@jsoref) +* [`f73e65d`](https://github.com/npm/cli/commit/f73e65d86d425bcf6b1693553e981bd05d2daeaf) [#8592](https://github.com/npm/cli/pull/8592) fix build url code for remark-github@12 (#8592) (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.6): `@npmcli/arborist@9.1.6` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.4.2): `@npmcli/config@10.4.2` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v10.0.3): `libnpmaccess@10.0.3` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.9): `libnpmdiff@8.0.9` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.8): `libnpmexec@10.1.8` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.9): `libnpmfund@7.0.9` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.9): `libnpmpack@9.0.9` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v11.1.2): `libnpmpublish@11.1.2` + +## [11.6.1](https://github.com/npm/cli/compare/v11.6.0...v11.6.1) (2025-09-23) ### Bug Fixes - -* [`ec06f77`](https://github.com/npm/cli/commit/ec06f7712bbdc3b38c546593e9970962fee127ed) [#7175](https://github.com/npm/cli/pull/7175) inline diff table code w/ summary code (@wraithgar) -* [`d4ebfba`](https://github.com/npm/cli/commit/d4ebfba91991423b52edf5f9431424faa6618073) [#7157](https://github.com/npm/cli/pull/7157) use util.stripVTControlCharacters instead of strip-ansi (@wraithgar) -* [`81c95c7`](https://github.com/npm/cli/commit/81c95c7de71b40831ad46356d75ed56b20c66372) [#7063](https://github.com/npm/cli/pull/7063) don't reset update notifier duration on every check (#7063) (@wraithgar) - +* [`d389614`](https://github.com/npm/cli/commit/d3896147c61b06d6d39a55bbb609f878548e0107) [#8579](https://github.com/npm/cli/pull/8579) corrects peer dependency flag propagation (@owlstronaut) +* [`5db81c3`](https://github.com/npm/cli/commit/5db81c350654dbbe2e1442d623efada9a24e04f1) [#8512](https://github.com/npm/cli/pull/8512) allow concurrent non-local npx calls (#8512) (@jenseng, @wraithgar) ### Documentation - -* [`2b7eaad`](https://github.com/npm/cli/commit/2b7eaade0620b3ea69e8b0b21335ed25af082351) [#7168](https://github.com/npm/cli/pull/7168) package-json: Reword warning about publishing local dependencies (#7168) (@DanKaplanSES) -* [`67ab0f7`](https://github.com/npm/cli/commit/67ab0f745ad182fa8250cc1da53b618df2e0d95a) [#7142](https://github.com/npm/cli/pull/7142) update: Replace comma with period in run on sentence (#7142) (@DanKaplanSES) -* [`05c69dc`](https://github.com/npm/cli/commit/05c69dc7ac70d27f1ec1d58ea0dd7111770fd0aa) [#7150](https://github.com/npm/cli/pull/7150) config: State default configuration file affected by `npm config set` (#7150) (@DanKaplanSES) -* [`44f4518`](https://github.com/npm/cli/commit/44f45187ef8ee20c373e89407f3c32708bef9f0f) [#7149](https://github.com/npm/cli/pull/7149) Link to the config command in the npm configuration description (#7149) (@DanKaplanSES) -* [`dd5699f`](https://github.com/npm/cli/commit/dd5699f7f0dcf9e5ad1c5549f3eaacaa1715f8eb) [#7152](https://github.com/npm/cli/pull/7152) update: Fix a typo and remove unneeded statement (#7152) (@DanKaplanSES) - +* [`7a09902`](https://github.com/npm/cli/commit/7a099029dbeeeab821498b9b462abce1269461f4) [#8582](https://github.com/npm/cli/pull/8582) bring back certfile (#8582) (@jenseng) ### Dependencies - -* [`ec77e81`](https://github.com/npm/cli/commit/ec77e81f5ecc3603bb7c9963f860a8c46f6a61ec) [#7124](https://github.com/npm/cli/pull/7124) `promise-call-limit@3.0.1` -* [`e32189c`](https://github.com/npm/cli/commit/e32189c768181d58ab72825d67307a3a653652ac) [#7173](https://github.com/npm/cli/pull/7173) deduplicate tree -* [`b7af4d9`](https://github.com/npm/cli/commit/b7af4d9bb96a86abee6a745b4a756b84d54d6e79) [#7173](https://github.com/npm/cli/pull/7173) `tar-stream@3.1.7` -* [`6883743`](https://github.com/npm/cli/commit/68837432c0b78bf7a4382a443f35ce2484449952) [#7173](https://github.com/npm/cli/pull/7173) `@npmcli/run-script@7.0.4` -* [`739634d`](https://github.com/npm/cli/commit/739634d76168f438934f1f8287618dabe2f3b968) [#7157](https://github.com/npm/cli/pull/7157) remove strip-ansi -* [`162c82e`](https://github.com/npm/cli/commit/162c82e845d410ede643466f9f8af78a312296cc) [#7148](https://github.com/npm/cli/pull/7148) `pacote@17.0.6` (#7148) (@bdehamer) -* [`a50b03b`](https://github.com/npm/cli/commit/a50b03b10046cf769cd328df96adcf292db5c067) [#7141](https://github.com/npm/cli/pull/7141) `sigstore@2.2.0` (#7141) (@bdehamer) -* [`f696b51`](https://github.com/npm/cli/commit/f696b517a39bea1be0f7116983a5b4c8ed6f01b7) [#7132](https://github.com/npm/cli/pull/7132) `@sigstore/tuf@2.3.0` (#7132) (@bdehamer) -* [workspace](https://github.com/npm/cli/releases/tag/arborist-v7.3.1): `@npmcli/arborist@7.3.1` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.0.6): `libnpmdiff@6.0.6` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v7.0.7): `libnpmexec@7.0.7` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v5.0.4): `libnpmfund@5.0.4` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v6.0.6): `libnpmpack@6.0.6` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v9.0.4): `libnpmpublish@9.0.4` - +* [`849dcb6`](https://github.com/npm/cli/commit/849dcb6dc22a16f01869ba9c6bf9146143000b25) [#8589](https://github.com/npm/cli/pull/8589) `tar@7.5.1` (#8589) +* [`ea15731`](https://github.com/npm/cli/commit/ea15731e3246ca698ad3f63fadd696479a906633) [#8576](https://github.com/npm/cli/pull/8576) `binary-extensions@3.1.0` +* [`0f41bac`](https://github.com/npm/cli/commit/0f41bace5677d0d624c67ff3fac5e2caeebcb399) [#8576](https://github.com/npm/cli/pull/8576) `tiny-relative-date@2.0.2` +* [`07bf540`](https://github.com/npm/cli/commit/07bf5402fbec900f1d69c05b7cb73a987d963d2c) [#8576](https://github.com/npm/cli/pull/8576) `is-cidr@6.0.0` +* [`ef87ec6`](https://github.com/npm/cli/commit/ef87ec6612fe5924d3466967aa7e104f3f98bf15) [#8576](https://github.com/npm/cli/pull/8576) `diff@8.0.2` +* [`48285e0`](https://github.com/npm/cli/commit/48285e04fd0a89b34d0c214295d5e76f68413f91) [#8576](https://github.com/npm/cli/pull/8576) add fdir, isexe, and picomatch to node_modules +* [`099238a`](https://github.com/npm/cli/commit/099238ac13ba535c99ff51bde348fcd9f6b86542) [#8576](https://github.com/npm/cli/pull/8576) `fdir@6.5.0` +* [`6e4d673`](https://github.com/npm/cli/commit/6e4d673138ee4026081e72bea1f6cdfc14516a98) [#8576](https://github.com/npm/cli/pull/8576) `isexe@3.1.1` +* [`09a7494`](https://github.com/npm/cli/commit/09a7494b59a89faa1f550864ce9f68b0c86179f1) [#8576](https://github.com/npm/cli/pull/8576) `supports-color@10.2.2` +* [`c5157c9`](https://github.com/npm/cli/commit/c5157c978fc235dea3a70235b6d08902473058f4) [#8576](https://github.com/npm/cli/pull/8576) `chalk@5.6.2` +* [`46035db`](https://github.com/npm/cli/commit/46035dbf4d87dad76051410c6b1b2536a874d9ed) [#8576](https://github.com/npm/cli/pull/8576) `debug@4.4.3` +* [`5f6664b`](https://github.com/npm/cli/commit/5f6664b7a8f622cfdd356d776e97dc8bae7e0ada) [#8576](https://github.com/npm/cli/pull/8576) `spdx-license-ids@3.0.22` +* [`5516583`](https://github.com/npm/cli/commit/5516583de7982f4b8d5142510429b809654d8f75) [#8576](https://github.com/npm/cli/pull/8576) `socks@2.8.7` +* [`6a392f3`](https://github.com/npm/cli/commit/6a392f36312b71cc4b0e71c25b4c95f47d1eeaf8) [#8576](https://github.com/npm/cli/pull/8576) `tinyglobby@0.2.15` +* [`9519f18`](https://github.com/npm/cli/commit/9519f189a427eb0a56c846379fdd92ff95078a5b) [#8576](https://github.com/npm/cli/pull/8576) `npm-install-checks@7.1.2` +* [`34bafd1`](https://github.com/npm/cli/commit/34bafd153f20954b5f8efdbf068fe1ec384ab489) [#8576](https://github.com/npm/cli/pull/8576) `node-gyp@11.4.2` +* [`dfd034e`](https://github.com/npm/cli/commit/dfd034eaf9c8fac8c40276aab42c65e2736158c8) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/promise-spawn@8.0.3` +* [`d4eef14`](https://github.com/npm/cli/commit/d4eef14dcdc30ef3a09e88180168b649ea82d72e) [#8576](https://github.com/npm/cli/pull/8576) `rimraf@6.0.1` +* [`566f1b7`](https://github.com/npm/cli/commit/566f1b7b487ad80604c61162ddde769d5ac2b241) [#8576](https://github.com/npm/cli/pull/8576) `minimatch@10.0.3` +* [`ac33497`](https://github.com/npm/cli/commit/ac334979ab94a52085b81a276c64788fa688e735) [#8576](https://github.com/npm/cli/pull/8576) `mkdirp@3.0.1` +* [`1676626`](https://github.com/npm/cli/commit/167662683d7ebbb34b1d65cf1cb74d69db12c871) [#8576](https://github.com/npm/cli/pull/8576) `glob@11.0.3` +* [`817f0b1`](https://github.com/npm/cli/commit/817f0b1eb57b9b0e5893beac11f053e3a7d3f765) [#8576](https://github.com/npm/cli/pull/8576) `ignore-walk@8.0.0` +* [`79a4e67`](https://github.com/npm/cli/commit/79a4e67c358b491f0456162fa9307e0f5a99167b) [#8576](https://github.com/npm/cli/pull/8576) `minizlib@3.0.2` +* [`38fa2c2`](https://github.com/npm/cli/commit/38fa2c2e67bed4c6e69d894cdbed0175d30ad085) [#8576](https://github.com/npm/cli/pull/8576) `negotiator@1.0.0` +* [`24252a1`](https://github.com/npm/cli/commit/24252a16fc45bfa6a4c1112269016568484006e1) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/agent@4.0.0` +* [`ea7ca5f`](https://github.com/npm/cli/commit/ea7ca5f49d6cab81e9ce3d412963c48acd87b7c0) [#8576](https://github.com/npm/cli/pull/8576) `lru-cache@11.2.1` +* [`521823b`](https://github.com/npm/cli/commit/521823bc398de0eb85135a3ef09e217db93ed1ce) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/git@7.0.0` +* [`bf6b686`](https://github.com/npm/cli/commit/bf6b6862731e03002cc6fa3b86b6f090df46b009) [#8576](https://github.com/npm/cli/pull/8576) `npm-package-arg@13.0.0` +* [`9392488`](https://github.com/npm/cli/commit/9392488d6036dfc9696e29cc8d463335517974ca) [#8576](https://github.com/npm/cli/pull/8576) `npm-package-manifest@11.0.1` +* [`0082083`](https://github.com/npm/cli/commit/0082083fe4f52d3ef40241e9d8b991f7ed4a60dc) [#8576](https://github.com/npm/cli/pull/8576) `normalize-package-data@8.0.0` +* [`633c4ed`](https://github.com/npm/cli/commit/633c4ed76ea13b8dfb5837a397e984e44cccb820) [#8576](https://github.com/npm/cli/pull/8576) `hosted-git-info@9.0.0` +* [`66f64eb`](https://github.com/npm/cli/commit/66f64eb1426beaad314321c22b5debff64b2357a) [#8576](https://github.com/npm/cli/pull/8576) `make-fetch-happen@15.0.2` +* [`1f85f94`](https://github.com/npm/cli/commit/1f85f94ec2e5dcf295c68c02b21d0b830b2082c2) [#8576](https://github.com/npm/cli/pull/8576) `@sigstore/tuf@4.0.0` +* [`a2bdecc`](https://github.com/npm/cli/commit/a2bdecc6677abcd58ed3037ab0edafb419ea86fa) [#8576](https://github.com/npm/cli/pull/8576) `sigstore@4.0.0` +* [`1149971`](https://github.com/npm/cli/commit/11499711e4c10e4ddb97bf3e1ef1652d151894fb) [#8576](https://github.com/npm/cli/pull/8576) `npm-registry-fetch@19.0.0` +* [`b5bd5e3`](https://github.com/npm/cli/commit/b5bd5e351061b46d6417210cd73c0f64c39e6819) [#8576](https://github.com/npm/cli/pull/8576) `npm-profile@12.0.0` +* [`6221e27`](https://github.com/npm/cli/commit/6221e277b4b841df09225b4d72f9eda70db1f15a) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/metavuln-calculator@9.0.2` +* [`da81a37`](https://github.com/npm/cli/commit/da81a3702fdf7ea2dc7223fc6ece4c7a19e32ad1) [#8576](https://github.com/npm/cli/pull/8576) `cacache@20.0.1` +* [`6b4c5f9`](https://github.com/npm/cli/commit/6b4c5f92865230ed9a260cd3e8486bf3991120eb) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/run-script@10.0.0` +* [`cb36a8a`](https://github.com/npm/cli/commit/cb36a8ad38df37579f59cf794d6c23ed7274fba9) [#8576](https://github.com/npm/cli/pull/8576) `init-package-json@8.2.2` +* [`b6bb9ae`](https://github.com/npm/cli/commit/b6bb9aea4134c47f0593c111a734eda12ec3c20d) [#8576](https://github.com/npm/cli/pull/8576) `pacote@21.0.3` +* [`1b4433f`](https://github.com/npm/cli/commit/1b4433fdb85623e019a6194cb01ff85c7f64ccad) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/map-workspaces@5.0.0` +* [`ceae674`](https://github.com/npm/cli/commit/ceae674c32a080b81e62d79003c2d537d7ca93d2) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/package-json@7.0.1` +* [`4f37534`](https://github.com/npm/cli/commit/4f37534300553e9ddfbc413c14d1ef15b02b46f2) [#8576](https://github.com/npm/cli/pull/8576) remove read-package-json-fast ### Chores - -* [`a82ccc5`](https://github.com/npm/cli/commit/a82ccc5f97a60698fb0ee413347a621d0662f493) [#7173](https://github.com/npm/cli/pull/7173) `nock@13.5.0` (@wraithgar) -* [`dcaa99c`](https://github.com/npm/cli/commit/dcaa99c5138ad20a3210a8396772177aa1fa33da) [#7173](https://github.com/npm/cli/pull/7173) fix exec test (@wraithgar) -* [`0d96080`](https://github.com/npm/cli/commit/0d96080fa8c08b5eb77bbd6ae64111379fa24465) [#7162](https://github.com/npm/cli/pull/7162) release: do not exclude docs directory from CLI release commits (#7162) (@lukekarrys) - -## [10.3.0](https://github.com/npm/cli/compare/v10.2.5...v10.3.0) (2024-01-10) - +* [`7eb5c09`](https://github.com/npm/cli/commit/7eb5c09eb4c9d20095fd285a32275743f10cf80b) [#8576](https://github.com/npm/cli/pull/8576) update package-lock with peer flag fixes (@wraithgar) +* [`0d00fd8`](https://github.com/npm/cli/commit/0d00fd862c75d743a38ed4c5336636696129cf3b) [#8576](https://github.com/npm/cli/pull/8576) `jsdom@27.0.0` (@wraithgar) +* [`420a569`](https://github.com/npm/cli/commit/420a569762e65b50d18338706420a85f24e3e0ee) [#8576](https://github.com/npm/cli/pull/8576) `unified@11.0.5` (@wraithgar) +* [`064deb3`](https://github.com/npm/cli/commit/064deb3b329a953d86c3cbaee26805987ff82d0d) [#8576](https://github.com/npm/cli/pull/8576) `remark-rehype@11.1.2` (@wraithgar) +* [`30fe3ba`](https://github.com/npm/cli/commit/30fe3ba2455caa66e0aaf7d1e9343ed9872faba0) [#8576](https://github.com/npm/cli/pull/8576) `remark-man@9.0.0` (@wraithgar) +* [`1c6bb4c`](https://github.com/npm/cli/commit/1c6bb4c54f515fdb7ead06cb05d24e0b9d403f8b) [#8576](https://github.com/npm/cli/pull/8576) `rehype-stringify@10.0.1` (@wraithgar) +* [`208cb93`](https://github.com/npm/cli/commit/208cb93fabae2b11993497382ceb48dacc41e490) [#8576](https://github.com/npm/cli/pull/8576) `remark-gfm@4.0.1` (@wraithgar) +* [`4a46b5a`](https://github.com/npm/cli/commit/4a46b5aaaeaa68ce718d4d4a95a74b9e49da8129) [#8576](https://github.com/npm/cli/pull/8576) `remark-github@12.0.0` (@wraithgar) +* [`93d190b`](https://github.com/npm/cli/commit/93d190bcb02342ce4d159168f12b86f071d6fca7) [#8576](https://github.com/npm/cli/pull/8576) `remark-parse@11.0.0` (@wraithgar) +* [`05301a4`](https://github.com/npm/cli/commit/05301a49fb3feed88736722c8b511dde3a1117e6) [#8576](https://github.com/npm/cli/pull/8576) `remark@15.0.1` (@wraithgar) +* [`6afdda9`](https://github.com/npm/cli/commit/6afdda99ed20c7e1fb95ed379fcc9665ef4f340d) [#8576](https://github.com/npm/cli/pull/8576) `ajv-formats@3.0.1` (@wraithgar) +* [`402a0ab`](https://github.com/npm/cli/commit/402a0ab1b4e5d1a8414dd063d0cbde0c0bc5a192) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/template-oss@4.25.1` (@wraithgar) +* [`3b43bf7`](https://github.com/npm/cli/commit/3b43bf79d36a04ee65f562528c7ac54ebafaf79b) [#8576](https://github.com/npm/cli/pull/8576) dev dependency updates (@wraithgar) +* [`9f9146f`](https://github.com/npm/cli/commit/9f9146f99c638361aed606a67156854c7cf2c2cf) [#8576](https://github.com/npm/cli/pull/8576) `@tufjs/repo-mock@4.0.0` (@wraithgar) +* [`eed8a10`](https://github.com/npm/cli/commit/eed8a10f09831cc01bdc7d07c4fae5c27dcf966c) [#8576](https://github.com/npm/cli/pull/8576) use latest/local arborist in mock-registry (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.5): `@npmcli/arborist@9.1.5` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.4.1): `@npmcli/config@10.4.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v10.0.2): `libnpmaccess@10.0.2` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.8): `libnpmdiff@8.0.8` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.7): `libnpmexec@10.1.7` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.8): `libnpmfund@7.0.8` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmorg-v8.0.1): `libnpmorg@8.0.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.8): `libnpmpack@9.0.8` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v11.1.1): `libnpmpublish@11.1.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmsearch-v9.0.1): `libnpmsearch@9.0.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmteam-v8.0.2): `libnpmteam@8.0.2` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v8.0.2): `libnpmversion@8.0.2` + +## [11.6.0](https://github.com/npm/cli/compare/v11.5.2...v11.6.0) (2025-09-03) ### Features - -* [`6673c77`](https://github.com/npm/cli/commit/6673c77bc4222d0f1719449fe903b7461b3e6907) [#6914](https://github.com/npm/cli/pull/6914) add `--libc` option to override platform specific install (#6914) (@wraithgar, @Brooooooklyn) - +* [`bdcc10d`](https://github.com/npm/cli/commit/bdcc10d9f848940987b3d326ccd4673fab2bcfef) [#8359](https://github.com/npm/cli/pull/8359) add support for optional env var replacements in .npmrc (#8359) (@aczekajski, @owlstronaut) ### Bug Fixes +* [`dd4cee9`](https://github.com/npm/cli/commit/dd4cee9026c8e2dd5e4c28fd45ac8bceae74fb89) [#8539](https://github.com/npm/cli/pull/8539) powershell: improve argument parsing (#8539) (@alexsch01) +* [`5f18557`](https://github.com/npm/cli/commit/5f1855778b5e376c5f1389e0ee5f204dc86c4d32) [#8532](https://github.com/npm/cli/pull/8532) powershell: fix issue with modified InvocationName (#8532) (@alexsch01) +* [`9e5abf1`](https://github.com/npm/cli/commit/9e5abf19b93359881b2035bc371e09794a1dad01) [#8529](https://github.com/npm/cli/pull/8529) add redaction to log format egress (#8529) (@wraithgar) +* [`75ce64a`](https://github.com/npm/cli/commit/75ce64a5b21b806be203b97f35a48497b4afcb56) [#8524](https://github.com/npm/cli/pull/8524) revert handle signal exits gracefully (#8524) (@owlstronaut) +* [`5d82d0b`](https://github.com/npm/cli/commit/5d82d0b4a4bd1424031fb68b4df740c1bbe5b172) [#8469](https://github.com/npm/cli/pull/8469) ps1 scripts in powershell 5.1 (#8469) (@splatteredbits) -* [`b7fc10a`](https://github.com/npm/cli/commit/b7fc10aa37bc2422f479119558f82e01bdaab6cd) [#7113](https://github.com/npm/cli/pull/7113) filter C0 and C1 control characters from logs and cli output (#7113) (@wraithgar) ### Dependencies -* [`3fd5213`](https://github.com/npm/cli/commit/3fd521393461639b6b768df43f0b5b71d3ee7dd2) [#7121](https://github.com/npm/cli/pull/7121) `npm-packlist@8.0.2` -* [`5698415`](https://github.com/npm/cli/commit/56984154b445c479236effdb844888b1ef409250) [#7121](https://github.com/npm/cli/pull/7121) `postcss-selector-parser@6.0.15` -* [`e56a4f3`](https://github.com/npm/cli/commit/e56a4f3dff9de349917d530074e698c644471080) [#7121](https://github.com/npm/cli/pull/7121) `are-we-there-yet@4.0.2` -* [`8495b7c`](https://github.com/npm/cli/commit/8495b7c088118e383ff6f3c7ce744df9c0d8e106) [#7121](https://github.com/npm/cli/pull/7121) `cacache@18.0.2` -* [`796d1c7`](https://github.com/npm/cli/commit/796d1c7507d69382181e515d6c6987930c9ec636) [#7121](https://github.com/npm/cli/pull/7121) `@npmcli/run-script@7.0.3` -* [`3b7f6f2`](https://github.com/npm/cli/commit/3b7f6f274aceed4218e5e903752d879a41d3a547) [#7121](https://github.com/npm/cli/pull/7121) `@npmcli/promise-spawn@7.0.1` -* [`7ecd146`](https://github.com/npm/cli/commit/7ecd146a3241723602693ca67c78ca5e2da8cb57) [#7121](https://github.com/npm/cli/pull/7121) `npmcli/git@5.0.4` -* [workspace](https://github.com/npm/cli/releases/tag/arborist-v7.3.0): `@npmcli/arborist@7.3.0` -* [workspace](https://github.com/npm/cli/releases/tag/config-v8.1.0): `@npmcli/config@8.1.0` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.0.5): `libnpmdiff@6.0.5` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v7.0.6): `libnpmexec@7.0.6` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v5.0.3): `libnpmfund@5.0.3` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v6.0.5): `libnpmpack@6.0.5` - -### Chores - -* [`2fd8292`](https://github.com/npm/cli/commit/2fd8292eff1155ec84a53f6d4321e6a386df93c7) [#7121](https://github.com/npm/cli/pull/7121) work around @npmcli/git lazy loading (@wraithgar) -* [`cd9a66d`](https://github.com/npm/cli/commit/cd9a66df2476d602fe3d36a6c3c6185f1bd8c676) [#7121](https://github.com/npm/cli/pull/7121) update devDependencies in lockfile (@wraithgar) -* [`2dda715`](https://github.com/npm/cli/commit/2dda715c9e72eefe69b49ee07c87fa126c84ff10) [#7121](https://github.com/npm/cli/pull/7121) `tap@16.3.10` (@wraithgar) - -## [10.2.5](https://github.com/npm/cli/compare/v10.2.4...v10.2.5) (2023-12-06) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.4): `@npmcli/arborist@9.1.4` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.4.0): `@npmcli/config@10.4.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.7): `libnpmdiff@8.0.7` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.6): `libnpmexec@10.1.6` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.7): `libnpmfund@7.0.7` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.7): `libnpmpack@9.0.7` +## [11.5.2](https://github.com/npm/cli/compare/v11.5.1...v11.5.2) (2025-07-30) ### Bug Fixes +* [`7d900c4`](https://github.com/npm/cli/commit/7d900c4656cfffc8cca93240c6cda4b441fbbfaa) [#8467](https://github.com/npm/cli/pull/8467) oidc visibility check for provenance (#8467) (@reggi, @wraithgar) +### Documentation +* [`d4e56b2`](https://github.com/npm/cli/commit/d4e56b2976ef1d2af273a6750d10b217adf4bf8e) [#8459](https://github.com/npm/cli/pull/8459) update snapshot generation command (#8459) (@MikeMcC399) -* [`c7a592c`](https://github.com/npm/cli/commit/c7a592c9c400e73dd27264c11ad6459616023e4c) [#7061](https://github.com/npm/cli/pull/7061) dont use cache for update notifier manifest request (@lukekarrys) -* [`7b952f6`](https://github.com/npm/cli/commit/7b952f64b882bd891fab5c21c7c3b49838c8a995) [#7049](https://github.com/npm/cli/pull/7049) unpublish: bubble up all errors parsing local package.json (#7049) (@wraithgar) -* [`be4741f`](https://github.com/npm/cli/commit/be4741f5bc20239f11842f780047d91fda23935d) [#7039](https://github.com/npm/cli/pull/7039) unpublish bugfixes (#7039) (@wraithgar) -* [`bc7f53d`](https://github.com/npm/cli/commit/bc7f53db793d362d2015d3e55ce121e6b4d3d91f) [#7036](https://github.com/npm/cli/pull/7036) reverse direction of SPDX SBOM dependency rels (#7036) (@bdehamer, @antonbauhofer) -* [`11ec231`](https://github.com/npm/cli/commit/11ec231e895300e5b7292ac16685d37d1d5df3b9) [#7033](https://github.com/npm/cli/pull/7033) skip creation of log directory if `logs-max` is set to 0 (#7033) (@JJ) -* [`6267f54`](https://github.com/npm/cli/commit/6267f543c2ac134c0f8433f8b48659a3949bf210) [#7005](https://github.com/npm/cli/pull/7005) properly catch missing url opener error on interactive prompt (#7005) (@wraithgar) +## [11.5.1](https://github.com/npm/cli/compare/v11.5.0...v11.5.1) (2025-07-24) +### Bug Fixes +* [`476bf17`](https://github.com/npm/cli/commit/476bf174c1c9874fa2a92df7257c3d445e3e16d3) [#8457](https://github.com/npm/cli/pull/8457) provenance should only default for oidc (@reggi) +## [11.5.0](https://github.com/npm/cli/compare/v11.4.2...v11.5.0) (2025-07-24) +### Features +* [`1cce318`](https://github.com/npm/cli/commit/1cce31810eb5ff1e0f7c8ee4516e7c73cedb38a1) [#8336](https://github.com/npm/cli/pull/8336) adds support for oidc publish (#8336) (@reggi) +### Bug Fixes +* [`7f66f0a`](https://github.com/npm/cli/commit/7f66f0ae8fb84f567fe83a9a5738d06c7fe8fb54) [#8447](https://github.com/npm/cli/pull/8447) add better hint for `before` and clean up description (@wraithgar) +* [`280817a`](https://github.com/npm/cli/commit/280817a0a5b4e2aebd4b2f39c79ac9af58165edf) [#8447](https://github.com/npm/cli/pull/8447) add --before param to command help output (@wraithgar) +* [`6e47325`](https://github.com/npm/cli/commit/6e47325e59f19e4e563b5f9308cff165739088a2) [#8441](https://github.com/npm/cli/pull/8441) Makes 404 errors less scary without revealing existence (#8441) (@owlstronaut) +* [`0a97ffd`](https://github.com/npm/cli/commit/0a97ffdf8b2df40a5f24b710415eb0c9aaa82f5d) [#8429](https://github.com/npm/cli/pull/8429) handle signal exits gracefully (@owlstronaut) +* [`5b858c6`](https://github.com/npm/cli/commit/5b858c6b2c275f0e670e09c52de5b931936d6e07) [#8411](https://github.com/npm/cli/pull/8411) ensure progress bars display consistently across all environments (#8411) (@owlstronaut) +### Documentation +* [`ef3529e`](https://github.com/npm/cli/commit/ef3529ec4b45901c95182850e8e9da8dae833227) [#8435](https://github.com/npm/cli/pull/8435) add test snapshot (#8435) (@reggi, @wraithgar) +* [`b7758d7`](https://github.com/npm/cli/commit/b7758d73d6b715a62e6d0c48e11b87017ce2b71c) [#8418](https://github.com/npm/cli/pull/8418) remove reference to Node.js download less common os (#8418) (@MikeMcC399) +* [`746ac5d`](https://github.com/npm/cli/commit/746ac5d95dc19a74c519a8e3f3e1eed029957921) [#8380](https://github.com/npm/cli/pull/8380) remove duplicate info (#8380) (@alexsch01) +* [`4673e9c`](https://github.com/npm/cli/commit/4673e9c165b39563e16409f3b1ca06fdc32e7d44) [#8371](https://github.com/npm/cli/pull/8371) rebrand OS X references to macOS (@MikeMcC399) ### Dependencies - -* [`ff1204a`](https://github.com/npm/cli/commit/ff1204aff0651e32679ecd09d0a2a62de49f4eac) [#7058](https://github.com/npm/cli/pull/7058) `lru-cache@10.1.0` -* [`c648020`](https://github.com/npm/cli/commit/c648020cdc0fa0916bc618b6d1191e68dcfc8d73) [#7058](https://github.com/npm/cli/pull/7058) `json-parse-even-better-errors@3.0.1` -* [`53aa8f2`](https://github.com/npm/cli/commit/53aa8f2c110f38a10f98f976cb40f54ea6d95844) [#7058](https://github.com/npm/cli/pull/7058) `pacote@17.0.5` -* [`2e5331c`](https://github.com/npm/cli/commit/2e5331c75df8606b1f92bf61c8612f5e7b0274aa) [#7058](https://github.com/npm/cli/pull/7058) `npm-packlist@8.0.1` -* [`937b7b7`](https://github.com/npm/cli/commit/937b7b7b11ec21fbe373ab93f4e4e170625dd6b1) [#7058](https://github.com/npm/cli/pull/7058) `ignore-walk@6.0.4` -* [`35371c8`](https://github.com/npm/cli/commit/35371c8796a08a269ac3f7017c35e5fcb7ef0968) [#7058](https://github.com/npm/cli/pull/7058) `cacache@18.0.1` -* [workspace](https://github.com/npm/cli/releases/tag/arborist-v7.2.2): `@npmcli/arborist@7.2.2` -* [workspace](https://github.com/npm/cli/releases/tag/config-v8.0.3): `@npmcli/config@8.0.3` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v8.0.2): `libnpmaccess@8.0.2` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.0.4): `libnpmdiff@6.0.4` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v7.0.5): `libnpmexec@7.0.5` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v5.0.2): `libnpmfund@5.0.2` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmhook-v10.0.1): `libnpmhook@10.0.1` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmorg-v6.0.2): `libnpmorg@6.0.2` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v6.0.4): `libnpmpack@6.0.4` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v9.0.3): `libnpmpublish@9.0.3` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmsearch-v7.0.1): `libnpmsearch@7.0.1` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmteam-v6.0.1): `libnpmteam@6.0.1` -* [workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v5.0.2): `libnpmversion@5.0.2` - +* [`398fed4`](https://github.com/npm/cli/commit/398fed45af63a8f7e3f5da8fc882674befd39216) [#8450](https://github.com/npm/cli/pull/8450) `normalize-package-data@7.0.1` +* [`5b242c9`](https://github.com/npm/cli/commit/5b242c9302e9ae1405b5ecbc76eb290c0f72634d) [#8450](https://github.com/npm/cli/pull/8450) `validate-npm-package-name@6.0.2` +* [`d4e8a8a`](https://github.com/npm/cli/commit/d4e8a8aba42f146a5feb20da262f92d0c3100986) [#8450](https://github.com/npm/cli/pull/8450) `tuf-js@3.1.0` +* [`e1b37b2`](https://github.com/npm/cli/commit/e1b37b2c84346eba3451369753756381658214b5) [#8450](https://github.com/npm/cli/pull/8450) `picomatch@4.0.3` +* [`3cb5884`](https://github.com/npm/cli/commit/3cb58842ff65a9ca2b31306e0e71ccf9ee5702e5) [#8450](https://github.com/npm/cli/pull/8450) `socks@2.8.6` +* [`daea981`](https://github.com/npm/cli/commit/daea98168b636b89ced80ab6d895ba7d9c5c8e20) [#8450](https://github.com/npm/cli/pull/8450) `ci-info@4.3.0` +* [`39ad47d`](https://github.com/npm/cli/commit/39ad47dd46dd69bcf16eb7dd5b6d8efec0d5d1c2) [#8450](https://github.com/npm/cli/pull/8450) `aproba@2.1.0` +* [`a789f33`](https://github.com/npm/cli/commit/a789f334757b691db02fcc182781d02b41e8bb5c) [#8450](https://github.com/npm/cli/pull/8450) `agent-base@7.1.4` +* [`1c0d257`](https://github.com/npm/cli/commit/1c0d257aa015297b703d0f413928bff661ed1430) [#8450](https://github.com/npm/cli/pull/8450) `@npmcli/metavuln-calculator@9.0.1` ### Chores - -* [`f656b66`](https://github.com/npm/cli/commit/f656b669e549286844f2071b9b62cf23f7958034) [#7062](https://github.com/npm/cli/pull/7062) `@npmcli/template-oss@4.21.3` (#7062) (@lukekarrys) -* [`9754b17`](https://github.com/npm/cli/commit/9754b173de26f3173e7f41eab34733fe9ba50f1d) [#7051](https://github.com/npm/cli/pull/7051) use global npm for workspace tests (@lukekarrys) -* [`3891757`](https://github.com/npm/cli/commit/3891757f54d6d960cbf5f0d93d183d6424e8bed6) [#7051](https://github.com/npm/cli/pull/7051) `@npmcli/template-oss@4.21.2` (@lukekarrys) -* [`71f70fa`](https://github.com/npm/cli/commit/71f70fa0e86448b20a63b9eec922ad25971a9377) [#7058](https://github.com/npm/cli/pull/7058) `nock@13.4.0` (@wraithgar) -* [`43674a4`](https://github.com/npm/cli/commit/43674a449816e364265205e56270ad547718069c) [#7058](https://github.com/npm/cli/pull/7058) `tap@16.3.9` (@wraithgar) -* [`4ba585c`](https://github.com/npm/cli/commit/4ba585ce0e1a2ea4591d64d7166b81b7fe92010b) [#7040](https://github.com/npm/cli/pull/7040) fix tests for zlib differences between node versions (#7040) (@wraithgar) - -## [10.2.4](https://github.com/npm/cli/compare/v10.2.3...v10.2.4) (2023-11-14) - +* [`804a964`](https://github.com/npm/cli/commit/804a9646e41d3aaa11ed084aa0c9997b7375882f) [#8450](https://github.com/npm/cli/pull/8450) update devDependencies in lockfile (@wraithgar) +* [`643ae71`](https://github.com/npm/cli/commit/643ae7104e5246a8ea10bfbd4f98540945c8430d) [#8450](https://github.com/npm/cli/pull/8450) update mock-registry to use local arborist (@wraithgar) +* [`cf023d7`](https://github.com/npm/cli/commit/cf023d71135427f2fdb290162432802e8a1514da) [#8421](https://github.com/npm/cli/pull/8421) contributing: prepare easier copy-paste contributing commands (#8421) (@MikeMcC399) +* [`3f60b5f`](https://github.com/npm/cli/commit/3f60b5f9621b43ae0b8796d3a7160a603748f756) [#8383](https://github.com/npm/cli/pull/8383) `@npmcli/template-oss@4.24.4` (#8383) (@wraithgar) +* [`01f8cc6`](https://github.com/npm/cli/commit/01f8cc6f001e3211135fa0563f7129aed09dc46c) [#8381](https://github.com/npm/cli/pull/8381) `@npmcli/template-oss@4.24.3` (#8381) (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.3): `@npmcli/arborist@9.1.3` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.3.1): `@npmcli/config@10.3.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.6): `libnpmdiff@8.0.6` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.5): `libnpmexec@10.1.5` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.6): `libnpmfund@7.0.6` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.6): `libnpmpack@9.0.6` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v11.1.0): `libnpmpublish@11.1.0` + +## [11.4.2](https://github.com/npm/cli/compare/v11.4.1...v11.4.2) (2025-06-11) ### Bug Fixes - -* [`cd291e7`](https://github.com/npm/cli/commit/cd291e7aa52e56fc45f8245e67c77e0ed3711b07) [#6995](https://github.com/npm/cli/pull/6995) refactor search formatting code (#6995) (@wraithgar) -* [`f3a7380`](https://github.com/npm/cli/commit/f3a7380a45323dbf6c74015e418de3963fb11a69) [#6973](https://github.com/npm/cli/pull/6973) look in workspace for exec commands (#6973) (@wraithgar) -* [`d11496b`](https://github.com/npm/cli/commit/d11496b26dfee5957e7e2a1b328f346b2aca9348) [#6977](https://github.com/npm/cli/pull/6977) pkg: properly output in workspace mode (#6977) (@wraithgar) -* [`0f70088`](https://github.com/npm/cli/commit/0f7008851f1c250405e8dc326f15d535e8fc1eae) [#6969](https://github.com/npm/cli/pull/6969) correctly handle object licenses in SBOM generation (#6969) (@jamietanna) -* [`dce3b08`](https://github.com/npm/cli/commit/dce3b0896ba81b2109fea42ab32edd8a3193324c) [#6951](https://github.com/npm/cli/pull/6951) properly catch missing url opener error (#6951) (@wraithgar) - +* [`f2d6947`](https://github.com/npm/cli/commit/f2d69478923b919c77bbb8bdb70c30ddeb59ffe7) [#8345](https://github.com/npm/cli/pull/8345) move warning to new line when `npm init` is canceled (@mbtools) +* [`e758dd7`](https://github.com/npm/cli/commit/e758dd7bec58efed2cc865a6d360b0432ccc9f57) [#8318](https://github.com/npm/cli/pull/8318) powershell: multiple Invoke-Expression fixes (#8318) (@alexsch01) ### Documentation - -* [`a38836c`](https://github.com/npm/cli/commit/a38836ce9d703f5012ff4d4a8a4e3b9a9aedc025) [#6616](https://github.com/npm/cli/pull/6616) add path usage for view command (#6616) (@RobinKnipe) -* [`da18e4f`](https://github.com/npm/cli/commit/da18e4f9baa180beeb325a384759a26a19ac2919) [#6987](https://github.com/npm/cli/pull/6987) update npm-prune description (#6987) (@Eomm) - +* [`7233cb3`](https://github.com/npm/cli/commit/7233cb3a159872236338b97bcb9d3797864abb33) [#8355](https://github.com/npm/cli/pull/8355) remove deprecated section related temp files (#8355) (@milaninfy) +* [`fb7a498`](https://github.com/npm/cli/commit/fb7a498d557abdd0c1a6945522d47878cf930a27) [#8351](https://github.com/npm/cli/pull/8351) clarify shell used for script (#8351) (@milaninfy) +* [`8b55d38`](https://github.com/npm/cli/commit/8b55d38cd2815a9503aed664c85eb678203dc4d4) [#8329](https://github.com/npm/cli/pull/8329) Rename "command" to "script" (#8329) (@DanKaplanSES) ### Dependencies +* [`7b05420`](https://github.com/npm/cli/commit/7b0542028f9c3cc326c26a1986c34cec7eb04931) [#8358](https://github.com/npm/cli/pull/8358) `fdir@6.4.6` +* [`e1a3b23`](https://github.com/npm/cli/commit/e1a3b23ebca0cb9b42c62a8c7b506ae9c2cc1a03) [#8358](https://github.com/npm/cli/pull/8358) `tinyglobby@0.2.14` +* [`522efa2`](https://github.com/npm/cli/commit/522efa2641780e1703d3578baeb94d3e57bcc8af) [#8358](https://github.com/npm/cli/pull/8358) `socks@2.8.5` +* [`7a0723f`](https://github.com/npm/cli/commit/7a0723f142b29065efec602e9e7d6585175e87a1) [#8358](https://github.com/npm/cli/pull/8358) `debug@4.4.1` +* [`9a342a4`](https://github.com/npm/cli/commit/9a342a4afb40d0668ab6a2c3820be7cacb4b79f7) [#8358](https://github.com/npm/cli/pull/8358) `brace-expansion@2.0.2` +* [`e691ba0`](https://github.com/npm/cli/commit/e691ba0918ea8526be9655f4c4c51e0887f7c623) [#8358](https://github.com/npm/cli/pull/8358) `@sigstore/protobuf-specs@0.4.3` +* [`42ef765`](https://github.com/npm/cli/commit/42ef765008ed76e5cc2521a92ba2d329933524b7) [#8358](https://github.com/npm/cli/pull/8358) `validate-npm-package-name@6.0.1` +* [`774c0b1`](https://github.com/npm/cli/commit/774c0b1e9c5704ffa24196fdcc44ba9575b04ca0) [#8358](https://github.com/npm/cli/pull/8358) `@npmcli/redact@3.2.2` +* [`dda6f87`](https://github.com/npm/cli/commit/dda6f871331280eeb37493a4ccc57361a27949eb) [#8317](https://github.com/npm/cli/pull/8317) `@npmcli/package-json@6.2.0` +* [`bc08ac7`](https://github.com/npm/cli/commit/bc08ac7a82f047485885d9c41a8b6fc48e8981b0) [#8317](https://github.com/npm/cli/pull/8317) remove normalize-package-data +### Chores +* [`0ad1444`](https://github.com/npm/cli/commit/0ad1444d76b0b68e4a4d48d7f22ebd4cd0d0e850) [#8358](https://github.com/npm/cli/pull/8358) dev dependency updates (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.2): `@npmcli/arborist@9.1.2` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.5): `libnpmdiff@8.0.5` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.4): `libnpmexec@10.1.4` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.5): `libnpmfund@7.0.5` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.5): `libnpmpack@9.0.5` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v11.0.1): `libnpmpublish@11.0.1` + +## [11.4.1](https://github.com/npm/cli/compare/v11.4.0...v11.4.1) (2025-05-21) +### Documentation +* [`3ed764a`](https://github.com/npm/cli/commit/3ed764aa08f2087fa1d1bd7391a646ba47565294) [#8308](https://github.com/npm/cli/pull/8308) Clarify script working directory behavior (fixes #8305) (#8308) (@tarekwfa0110, @owlstronaut) +### Chores +* [`2f30251`](https://github.com/npm/cli/commit/2f302516401928239593dd2eebc171729df60537) [#8314](https://github.com/npm/cli/pull/8314) remove references to skimdb.npmjs.com (#8314) (@shmam) +* [`9cb9d50`](https://github.com/npm/cli/commit/9cb9d5030b1fdb83e3ffa45b7c8d2de80a657768) [#8298](https://github.com/npm/cli/pull/8298) add contributor to changelog entry (#8298) (@wraithgar) -* [`e9ec2f7`](https://github.com/npm/cli/commit/e9ec2f7005e7326d9a819978b251cf0a05062538) [#6994](https://github.com/npm/cli/pull/6994) `lru-cache@10.0.2` -* [`faf9eff`](https://github.com/npm/cli/commit/faf9efffb7bfe6efde6e53830cb054b34c3a6ea3) [#6994](https://github.com/npm/cli/pull/6994) `is-core-module@2.13.1` -* [`b00e780`](https://github.com/npm/cli/commit/b00e7808e370513e79ca31c261958377984e7444) [#6994](https://github.com/npm/cli/pull/6994) `@sigstore/sign@2.2.0` -* [`4613774`](https://github.com/npm/cli/commit/461377426d998ed79400501b09e1ee67c32bee23) [#6994](https://github.com/npm/cli/pull/6994) hoisting newer deps in favor of older ones -* [`54c4f7b`](https://github.com/npm/cli/commit/54c4f7b8705b2c9d5b8bc5bb846f4e7863735b7e) [#6994](https://github.com/npm/cli/pull/6994) `signal-exit@4.1.0` -* [`8c5882f`](https://github.com/npm/cli/commit/8c5882f3eed305bbd3514d7143f9d92e9577e1b9) [#6994](https://github.com/npm/cli/pull/6994) `strip-ansi@7.1.0` -* [`cd0c649`](https://github.com/npm/cli/commit/cd0c649ec2b421b59012854e61788a11a77194f2) [#6994](https://github.com/npm/cli/pull/6994) `ci-info@4.0.0` -* [`a0a58b7`](https://github.com/npm/cli/commit/a0a58b735c418d8555a06890b63098c68f53106e) [#6994](https://github.com/npm/cli/pull/6994) `@sigstore/tuf@2.2.0` -* [`b3a53c6`](https://github.com/npm/cli/commit/b3a53c6ab5fd933fc7f8258c155ed31be834393e) [#6949](https://github.com/npm/cli/pull/6949) `is-cidr@5.0.3` (#6949) -* [Workspace](https://github.com/npm/cli/releases/tag/config-v8.0.2): `@npmcli/config@8.0.2` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v7.0.4): `libnpmexec@7.0.4` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v9.0.2): `libnpmpublish@9.0.2` - -## [10.2.3](https://github.com/npm/cli/compare/v10.2.2...v10.2.3) (2023-11-02) ### Dependencies -* [`b5dedf3`](https://github.com/npm/cli/commit/b5dedf39dd772192ed6639926ad4c99ff5dfd28a) [#6958](https://github.com/npm/cli/pull/6958) `node-gyp@10.0.1` - -## [10.2.2](https://github.com/npm/cli/compare/v10.2.1...v10.2.2) (2023-10-31) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.1): `@npmcli/arborist@9.1.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.4): `libnpmdiff@8.0.4` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.3): `libnpmexec@10.1.3` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.4): `libnpmfund@7.0.4` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.4): `libnpmpack@9.0.4` +## [11.4.0](https://github.com/npm/cli/compare/v11.3.0...v11.4.0) (2025-05-15) +### Features +* [`a0e60fb`](https://github.com/npm/cli/commit/a0e60fb1893ac77a78380d9a9faaaaa54da1fe85) [#8246](https://github.com/npm/cli/pull/8246) added init-private option (@owlstronaut) +* [`57aa89f`](https://github.com/npm/cli/commit/57aa89ff70e0c6186a43888b944b5799b25c7bc8) [#8265](https://github.com/npm/cli/pull/8265) use run by default and run-script as the alias (#8265) (@owlstronaut) +* [`0d4c023`](https://github.com/npm/cli/commit/0d4c023914f835927540bd0110c1ca5716b84056) [#8234](https://github.com/npm/cli/pull/8234) install: add package info to json output (#8234) (@wraithgar) ### Bug Fixes - -* [`8ed6d28`](https://github.com/npm/cli/commit/8ed6d28fa14b40d7a05784ad0a1e80661256b466) [#6910](https://github.com/npm/cli/pull/6910) make npm link respect --no-save (#6910) (@Santoshraj2) -* [`eacec5f`](https://github.com/npm/cli/commit/eacec5f49060d3dfcdc3c7043115619e4bb22864) [#6941](https://github.com/npm/cli/pull/6941) add back bin/node-gyp-bin/node-gyp files (#6941) (@lukekarrys) -* [`b776753`](https://github.com/npm/cli/commit/b776753f9cfeab329169105f604bc55ed03bd0e1) [#6928](https://github.com/npm/cli/pull/6928) Grammar mistake in authentication error message (#6928) (@Gekuro, gek) - +* [`8794fd9`](https://github.com/npm/cli/commit/8794fd9161c29fea3f51ae8581f54172011d4069) [#8297](https://github.com/npm/cli/pull/8297) powershell: support pipeline input with Invoke-Expression (#8297) (@alexsch01) +* [`b5173d1`](https://github.com/npm/cli/commit/b5173d13c182efa5434ef4ca413e62ce1437f47a) [#8293](https://github.com/npm/cli/pull/8293) docs: corrected github_path (#8293) (@xaos7991) +* [`2210d7a`](https://github.com/npm/cli/commit/2210d7a670ac3522ceee8856a3399e8f44e77bbe) [#8278](https://github.com/npm/cli/pull/8278) powershell: use Invoke-Expression to pass args (#8278) (@alexsch01, @mbtools) +* [`8669d09`](https://github.com/npm/cli/commit/8669d0931abd0ae4b655cf9e5a024065054a8bb4) [#8228](https://github.com/npm/cli/pull/8228) add otplease for enable-2fa, disable-2fa, access (#8228) (@reggi, @wraithgar) +* [`78b5a6f`](https://github.com/npm/cli/commit/78b5a6fa9cd103bb80a25957ddfcb5832bc1f937) [#8269](https://github.com/npm/cli/pull/8269) correctly handle scenario where prefix is the cwd (#8269) (@owlstronaut, @ficocelliguy) +* [`fdc3413`](https://github.com/npm/cli/commit/fdc3413019c2f34f1fde35449e5f3a6b0fb51ba2) [#8221](https://github.com/npm/cli/pull/8221) exec: Fails to Execute Binaries Named After Shell Keywords (#8221) (@13sfaith) +* [`4b08e2e`](https://github.com/npm/cli/commit/4b08e2ed252a18f85a360b76c7273a7aa7a994ca) [#8245](https://github.com/npm/cli/pull/8245) docs: prepare script runs for local package links (@milaninfy) +* [`1622ac4`](https://github.com/npm/cli/commit/1622ac456f07403e6afe02352b8f95db14dcf9eb) [#8241](https://github.com/npm/cli/pull/8241) handle missing `time` in packument to prevent crash on `npm view` (@owlstronaut) +* [`db8f5da`](https://github.com/npm/cli/commit/db8f5da886326ae40d44a8cceedb99e2e6a00855) [#8110](https://github.com/npm/cli/pull/8110) outdated: add dependent location in long output (#8110) (@milaninfy, @wraithgar) ### Documentation - -* [`c422a01`](https://github.com/npm/cli/commit/c422a01e1564d25148c821ee257196ebe60e8e6c) [#6924](https://github.com/npm/cli/pull/6924) use markdown links instead of html (@lukekarrys) -* [`dd03aa0`](https://github.com/npm/cli/commit/dd03aa0b9acc535283daf39699de9831202348cb) [#6921](https://github.com/npm/cli/pull/6921) add v9 and above for lockfile version 3 (#6921) (@MikeMcC399) - +* [`d2498df`](https://github.com/npm/cli/commit/d2498df8efa558c3048f71324be0ef189c14bd49) [#8295](https://github.com/npm/cli/pull/8295) Remove `CHANGELOG` from never-ignored list (#8295) (@mrazauskas) +* [`4d5c3c1`](https://github.com/npm/cli/commit/4d5c3c1d8d99e352b1b4906c2607752ee3051a75) [#8283](https://github.com/npm/cli/pull/8283) fix `overrides` example in package-json.md (#8283) (@glasser) +* [`96cc4f9`](https://github.com/npm/cli/commit/96cc4f9a87a231abf4c9584a277765368ba6663d) [#8226](https://github.com/npm/cli/pull/8226) format publish as code to highlight it (@LiangYingC) +* [`4990ea0`](https://github.com/npm/cli/commit/4990ea0f0c017e4702cf2da2fbd99dad61c77015) [#8226](https://github.com/npm/cli/pull/8226) clarify legacy token creation in npm login and adduser commands (@LiangYingC) ### Dependencies - -* [`dfb6298`](https://github.com/npm/cli/commit/dfb6298c3eb9fb7ef452906765ac5f23ea6fec49) [#6937](https://github.com/npm/cli/pull/6937) `node-gyp@10.0.0` (#6937) -* [Workspace](https://github.com/npm/cli/releases/tag/arborist-v7.2.1): `@npmcli/arborist@7.2.1` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.0.3): `libnpmdiff@6.0.3` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v7.0.3): `libnpmexec@7.0.3` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v5.0.1): `libnpmfund@5.0.1` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v6.0.3): `libnpmpack@6.0.3` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v5.0.1): `libnpmversion@5.0.1` - -## [10.2.1](https://github.com/npm/cli/compare/v10.2.0...v10.2.1) (2023-10-18) - +* [`c97ef8a`](https://github.com/npm/cli/commit/c97ef8ae62187b5330c82887e9f566a4d2466cc4) [#8246](https://github.com/npm/cli/pull/8246) `init-package-json@8.2.1` +* [`f48613d`](https://github.com/npm/cli/commit/f48613d0403a5267a7a55cbaa9d1e814d2033fe4) [#8292](https://github.com/npm/cli/pull/8292) `@sigstore/verify@2.1.1` +* [`a4c5e74`](https://github.com/npm/cli/commit/a4c5e7455b621a4dffa893fef0ebf8ffa2307b1f) [#8292](https://github.com/npm/cli/pull/8292) `tinyglobby@0.2.13` +* [`b9156d2`](https://github.com/npm/cli/commit/b9156d2144ca387edd13178547c0ec276450f118) [#8292](https://github.com/npm/cli/pull/8292) `http-cache-semantics@4.2.0` +* [`472a685`](https://github.com/npm/cli/commit/472a685a8fe4d120a86ea6c7ee50e304bc8e7e94) [#8292](https://github.com/npm/cli/pull/8292) `binary-extensions@3.1.0` +* [`988696e`](https://github.com/npm/cli/commit/988696eb93548e703ae04496d0e361a6015cb0d3) [#8292](https://github.com/npm/cli/pull/8292) `@sigstore/tuf@3.1.1` +* [`569ac84`](https://github.com/npm/cli/commit/569ac84537f05450260e05d006361cdfe586359b) [#8292](https://github.com/npm/cli/pull/8292) `semver@7.7.2` +* [`2521c9b`](https://github.com/npm/cli/commit/2521c9ba18172c2ade525cbe9a675d293a0484d9) [#8233](https://github.com/npm/cli/pull/8233) `@sigstore/protobuf-specs@0.4.1` +* [`3274d68`](https://github.com/npm/cli/commit/3274d68b13595415586b41445838cc258543173a) [#8233](https://github.com/npm/cli/pull/8233) `@npmcli/query@4.0.1` +* [`c263626`](https://github.com/npm/cli/commit/c2636268e83b8049789534e78f4c15913e047c89) [#8233](https://github.com/npm/cli/pull/8233) `abbrev@3.0.1` +* [`78df711`](https://github.com/npm/cli/commit/78df711a60aaf8538b9fcaf13f2f9d50ce62b7b8) [#8233](https://github.com/npm/cli/pull/8233) `hosted-git-info@8.1.0` +### Chores +* [`e80e38e`](https://github.com/npm/cli/commit/e80e38eb961865de4006dc0e2ea991aebb1a3bdf) [#8292](https://github.com/npm/cli/pull/8292) dev dependency updates (@wraithgar) +* [`3231ee9`](https://github.com/npm/cli/commit/3231ee9afefcadce2b17a143fd51d365de4d6dea) [#8244](https://github.com/npm/cli/pull/8244) update snapshots (@owlstronaut) +* [`c561a33`](https://github.com/npm/cli/commit/c561a3307b18f9c208eb7305db0f2a51db61277d) [#8233](https://github.com/npm/cli/pull/8233) dev dependency updates (@owlstronaut) +* [`7eca19c`](https://github.com/npm/cli/commit/7eca19cb5ddc32688a8e331d5468d58f14684bff) [#8215](https://github.com/npm/cli/pull/8215) update workflow permissions for updating Node PR (@owlstronaut) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.0): `@npmcli/arborist@9.1.0` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.3.0): `@npmcli/config@10.3.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v10.0.1): `libnpmaccess@10.0.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.3): `libnpmdiff@8.0.3` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.2): `libnpmexec@10.1.2` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.3): `libnpmfund@7.0.3` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.3): `libnpmpack@9.0.3` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmteam-v8.0.1): `libnpmteam@8.0.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v8.0.1): `libnpmversion@8.0.1` + +## [11.3.0](https://github.com/npm/cli/compare/v11.2.0...v11.3.0) (2025-04-08) +### Features +* [`b306d25`](https://github.com/npm/cli/commit/b306d25df2f2e6ae75fd4f6657e0858b6dd71c43) [#8129](https://github.com/npm/cli/pull/8129) add `node-gyp` as actual config (@wraithgar) ### Bug Fixes - -* [`35c92fe`](https://github.com/npm/cli/commit/35c92fec3d053d303cc8057faa0ff4fe6e7cdc8a) [#6902](https://github.com/npm/cli/pull/6902) Add check to pkg command to deal with empty values (#6902) (@NeonArray) -* [`5b6172f`](https://github.com/npm/cli/commit/5b6172f01c88b73e83a75a508bbdcad92231ead5) [#6895](https://github.com/npm/cli/pull/6895) logout from custom registry (@wraithgar) -* [`8423d4f`](https://github.com/npm/cli/commit/8423d4f133a40c8ceb0e1a75d23aa95fbf4f5b65) [#6895](https://github.com/npm/cli/pull/6895) delete auth from proper location on logout (@wraithgar) -* [`0cfe9de`](https://github.com/npm/cli/commit/0cfe9de1c74b20d3e04ecc26ccf594196d101afe) [#6873](https://github.com/npm/cli/pull/6873) audit: spelling error in message (#6873) (@Fdawgs) - +* [`2f5392a`](https://github.com/npm/cli/commit/2f5392ae1f87fd3df3d7e521e0e69222fb9899e5) [#8135](https://github.com/npm/cli/pull/8135) make `npm run` autocomplete work with workspaces (#8135) (@terrainvidia) ### Documentation - -* [`5142735`](https://github.com/npm/cli/commit/5142735c462e285a7a7d9bcbd562885c6ef96c96) [#6894](https://github.com/npm/cli/pull/6894) update npm build description (#6894) (@siemhesda) -* [`2e4b4ad`](https://github.com/npm/cli/commit/2e4b4ad8bef158def1b2302846ab294fe7a83de4) [#6861](https://github.com/npm/cli/pull/6861) npm publish content modification (#6861) (@jpg619) - +* [`26b6454`](https://github.com/npm/cli/commit/26b64543ebb27e421c05643eb996f6765c13444c) fix grammar in local path note (@cgay) +* [`1c0e83d`](https://github.com/npm/cli/commit/1c0e83d6c165a714c7c37c0887e350042e53cf34) [#7886](https://github.com/npm/cli/pull/7886) fix typo in package-json.md (#7886) (@stoneLeaf) +* [`14efa57`](https://github.com/npm/cli/commit/14efa57f13b2bbbf10b0b217b981f919556789cd) [#8178](https://github.com/npm/cli/pull/8178) fix example package name in `overrides` explainer (#8178) (@G-Rath) +* [`4183cba`](https://github.com/npm/cli/commit/4183cba3e13bcfea83fa3ef2b6c5b0c9685f79bc) [#8162](https://github.com/npm/cli/pull/8162) logging: replace proceeding with preceding in loglevels details (#8162) (@tyleralbee) ### Dependencies - -* [`96e1637`](https://github.com/npm/cli/commit/96e1637117b6614b5ad861d86d828746d5db356c) [#6915](https://github.com/npm/cli/pull/6915) `cmd-shim@6.0.2` (#6915) -* [`b405da1`](https://github.com/npm/cli/commit/b405da1672e05d55bd22e476091891c443bcbeab) [#6899](https://github.com/npm/cli/pull/6899) `bin-links@4.0.3` -* [`ef69d36`](https://github.com/npm/cli/commit/ef69d362fa81640ac3ca60a6e01921c17f7a76cb) [#6895](https://github.com/npm/cli/pull/6895) `npm-registry-fetch@16.1.0` -* [`337c903`](https://github.com/npm/cli/commit/337c9038605b97431e06d2f470229f4370703b13) [#6882](https://github.com/npm/cli/pull/6882) `spdx-license-ids@3.0.16` -* [`e6b0be7`](https://github.com/npm/cli/commit/e6b0be7d3b3cd7f66612f9adb6c4de829335b607) [#6882](https://github.com/npm/cli/pull/6882) `socks-proxy-agent@8.0.2` -* [`ee6892e`](https://github.com/npm/cli/commit/ee6892e69079b07c0a8747d873018819a97e3877) [#6882](https://github.com/npm/cli/pull/6882) `readable-stream@4.4.2` -* [`61c3ee9`](https://github.com/npm/cli/commit/61c3ee9a073528b30676ec66fdd29788ea7be09d) [#6882](https://github.com/npm/cli/pull/6882) `minipass@7.0.4` -* [`14d31fd`](https://github.com/npm/cli/commit/14d31fdcc747f420158d254d0ac258a848bc888c) [#6882](https://github.com/npm/cli/pull/6882) `is-core-module@2.13.0` -* [`03f3d2e`](https://github.com/npm/cli/commit/03f3d2e1d13cd12f23a946cfb9065b8e8fbe129b) [#6882](https://github.com/npm/cli/pull/6882) `https-proxy-agent@7.0.2` -* [`e0163c6`](https://github.com/npm/cli/commit/e0163c6787f3877c3ad6c84d8af44378f7eed23b) [#6882](https://github.com/npm/cli/pull/6882) `are-we-there-yet@4.0.1` -* [`fca804a`](https://github.com/npm/cli/commit/fca804adec57e176bb2a2e60bf84df44e661478f) [#6882](https://github.com/npm/cli/pull/6882) `ci-info@3.9.0` -* [`6af582f`](https://github.com/npm/cli/commit/6af582f23bf046a224d5679e917977f0bb3f95e3) [#6882](https://github.com/npm/cli/pull/6882) `npm-install-checks@6.3.0` -* [Workspace](https://github.com/npm/cli/releases/tag/config-v8.0.1): `@npmcli/config@8.0.1` - -## [10.2.0](https://github.com/npm/cli/compare/v10.1.0...v10.2.0) (2023-10-02) - +* [`e57f112`](https://github.com/npm/cli/commit/e57f1126e496aa88e7164bf3102147b95d96c9c8) [#8207](https://github.com/npm/cli/pull/8207) `minipass-fetch@4.0.1` +* [`3daabb1`](https://github.com/npm/cli/commit/3daabb1a0cd048db303a9246ab6855f2a0550c96) [#8207](https://github.com/npm/cli/pull/8207) `minizlib@3.0.2` +* [`c7a7527`](https://github.com/npm/cli/commit/c7a752709509baffe674ca6d49e480835ff4a2df) [#8207](https://github.com/npm/cli/pull/8207) `ci-info@4.2.0` +* [`20b09b6`](https://github.com/npm/cli/commit/20b09b67bedca8d2d49404d32d031bf1d875bf81) [#8207](https://github.com/npm/cli/pull/8207) `node-gyp@11.2.0` +* [`679bc4a`](https://github.com/npm/cli/commit/679bc4a71614bffedfbea3058af13c7deb69fcd4) [#8129](https://github.com/npm/cli/pull/8129) `@npmcli/run-script@9.1.0` +### Chores +* [`3fbed84`](https://github.com/npm/cli/commit/3fbed848c1f909cf1321ad0916f938bae116219f) [#8207](https://github.com/npm/cli/pull/8207) install rimraf as a devdependency for smoke tests (@owlstronaut) +* [`43f0b41`](https://github.com/npm/cli/commit/43f0b41a17b32997e7de9369c485acc8aa661c0a) [#8207](https://github.com/npm/cli/pull/8207) dev dependency updates (@wraithgar) +* [`26803bc`](https://github.com/npm/cli/commit/26803bc46cf85e400b66644c975ee99f6fd0575e) [#8147](https://github.com/npm/cli/pull/8147) release integration node 23 yml (#8147) (@reggi) +* [`d679a1a`](https://github.com/npm/cli/commit/d679a1ae9e22eb01663d3390b9522b1b5380db32) [#8146](https://github.com/npm/cli/pull/8146) release integration node 23 (#8146) (@reggi) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.2): `@npmcli/arborist@9.0.2` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.2.0): `@npmcli/config@10.2.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.2): `libnpmdiff@8.0.2` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.1): `libnpmexec@10.1.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.2): `libnpmfund@7.0.2` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.2): `libnpmpack@9.0.2` + +## [11.2.0](https://github.com/npm/cli/compare/v11.1.0...v11.2.0) (2025-03-05) ### Features - -* [`7c459d2`](https://github.com/npm/cli/commit/7c459d28ca987264028d4d2ca21b0825493c1537) [#6801](https://github.com/npm/cli/pull/6801) add npm sbom command (#6801) (@bdehamer) -* [`81a460f`](https://github.com/npm/cli/commit/81a460f6e6317aca2288d16cda591aa6541540c6) [#6732](https://github.com/npm/cli/pull/6732) add package-lock-only mode to npm query (@wraithgar) -* [`0d29855`](https://github.com/npm/cli/commit/0d2985535c9cc3dfc3e1f355580570c9cce37d61) [#6732](https://github.com/npm/cli/pull/6732) add no-package-lock mode to npm audit (@wraithgar) - +* [`247ee1d`](https://github.com/npm/cli/commit/247ee1d95a12983e181c3c3f2f1fdb790dd21794) [#8100](https://github.com/npm/cli/pull/8100) cache: add npx commands (@wraithgar) +* [`3a80a7b`](https://github.com/npm/cli/commit/3a80a7b7d168c23b5e297cba7b47ba5b9875934d) [#8081](https://github.com/npm/cli/pull/8081) add --init-type flag (#8081) (@reggi) +* [`2a1e11f`](https://github.com/npm/cli/commit/2a1e11f1f6e4a4c948b8ac52b9cda8f370d8674b) [#8071](https://github.com/npm/cli/pull/8071) move nerfDart list into @npmcli/config (@wraithgar) ### Bug Fixes - -* [`2207628`](https://github.com/npm/cli/commit/22076286a46499e3d0b3f8564b7ba07008317be4) [#6823](https://github.com/npm/cli/pull/6823) use strip-ansi module instead of internal regex (#6823) (@wraithgar) -* [`d46d052`](https://github.com/npm/cli/commit/d46d0526be12eae2cd458fd08dd5c0a0320cc8bd) [#6798](https://github.com/npm/cli/pull/6798) tolerate null bugs URLs (#6798) (@vladh) -* [`fb1b674`](https://github.com/npm/cli/commit/fb1b6741bd52d865b8f8a93ad3fd6c8afa758b6a) [#6758](https://github.com/npm/cli/pull/6758) deprecate: ignore implicit workspace mode (#6758) (@wraithgar) - -### Documentation - -* [`68031f2`](https://github.com/npm/cli/commit/68031f2ae1cd5d49b0fb263da1a7eae62712ff97) [#6844](https://github.com/npm/cli/pull/6844) update `CONTRIBUTING.md` to prevent errors (#6844) (@darcyclarke) -* [`3ac703c`](https://github.com/npm/cli/commit/3ac703c95e7bb851d0f6145f1d612749ed479fef) [#6831](https://github.com/npm/cli/pull/6831) add `include `param to commands that have `omit` param (#6831) (@siemhesda) -* [`03912db`](https://github.com/npm/cli/commit/03912dbaeb92559270ab3f7df75b507b2f35a119) [#6819](https://github.com/npm/cli/pull/6819) add init-specific params to init docs/help (#6819) (@wraithgar) -* [`8088325`](https://github.com/npm/cli/commit/8088325281bc976e8a8aea4d7527b54f4e25fb5f) [#6800](https://github.com/npm/cli/pull/6800) Update npm-doctor.md (#6800) (@siemhesda) - +* [`8461186`](https://github.com/npm/cli/commit/846118686849f821b084775f7891038013f7ba97) [#8100](https://github.com/npm/cli/pull/8100) update npx cache if possible when spec is a range (@wraithgar) +* [`e345cc5`](https://github.com/npm/cli/commit/e345cc58ecad0e1e18eefc00638d7fa32966c2b7) [#8050](https://github.com/npm/cli/pull/8050) don't suggest npm update outside of valid engine range (#8050) (@milaninfy) +* [`811ca29`](https://github.com/npm/cli/commit/811ca2927eed733c8fabf308bf9d467e7c959163) [#8115](https://github.com/npm/cli/pull/8115) stop working around bug fixed in `npm-package-arg@12.0.2` (@TrevorBurnham) +* [`879303c`](https://github.com/npm/cli/commit/879303cd7c529a04d855f47d14dce433118ac626) [#8078](https://github.com/npm/cli/pull/8078) warn on invalid publishConfig (#8078) (@wraithgar) +* [`41417de`](https://github.com/npm/cli/commit/41417de9f493969a5826d05d7024fdd1da8d88da) [#8080](https://github.com/npm/cli/pull/8080) warn when TUF fetching of keys fails (#8080) (@wraithgar) +* [`593c849`](https://github.com/npm/cli/commit/593c84921b0df963cef2ca7b13e44acc20cbd558) [#8076](https://github.com/npm/cli/pull/8076) warn on invalid single-hyphen cli flags (#8076) (@wraithgar) ### Dependencies - -* [`aa6728b`](https://github.com/npm/cli/commit/aa6728b1d003f0fc620b074ba0396a3e07f2db6a) [#6859](https://github.com/npm/cli/pull/6859) `tar@6.2.0` -* [`ce9089f`](https://github.com/npm/cli/commit/ce9089f604a01297d3d2dd544283696a6297dce5) [#6859](https://github.com/npm/cli/pull/6859) `npm-package-arg@11.0.1` -* [`39d7f04`](https://github.com/npm/cli/commit/39d7f046f1c39017b398cb242ad07e874484e86c) [#6859](https://github.com/npm/cli/pull/6859) `minipass@7.0.4` -* [`0a47af5`](https://github.com/npm/cli/commit/0a47af509d66071908c7e0bf065dcf2f4c877669) [#6859](https://github.com/npm/cli/pull/6859) `hosted-git-info@7.0.1` -* [`af93130`](https://github.com/npm/cli/commit/af93130fe949f07df23891286c634c77ecf38c53) [#6859](https://github.com/npm/cli/pull/6859) `glob@10.3.10` -* [`3ebc474`](https://github.com/npm/cli/commit/3ebc4744433d906e5c491d183fc077ffe79958cf) [#6859](https://github.com/npm/cli/pull/6859) `@npmcli/query@3.0.1` -* [`284cbfd`](https://github.com/npm/cli/commit/284cbfd168879b9277c9999e8a28dad8f72ecc02) [#6858](https://github.com/npm/cli/pull/6858) `@npmcli/agent@2.2.0` -* [Workspace](https://github.com/npm/cli/releases/tag/arborist-v7.2.0): `@npmcli/arborist@7.2.0` -* [Workspace](https://github.com/npm/cli/releases/tag/config-v8.0.0): `@npmcli/config@8.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v8.0.1): `libnpmaccess@8.0.1` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.0.2): `libnpmdiff@6.0.2` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v7.0.2): `libnpmexec@7.0.2` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v5.0.0): `libnpmfund@5.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmorg-v6.0.1): `libnpmorg@6.0.1` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v6.0.2): `libnpmpack@6.0.2` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v9.0.1): `libnpmpublish@9.0.1` - -## [10.1.0](https://github.com/npm/cli/compare/v10.0.0...v10.1.0) (2023-09-08) - +* [`3d8b257`](https://github.com/npm/cli/commit/3d8b257bd667e76e74236c756aaa2dceaa6d6e5e) [#8100](https://github.com/npm/cli/pull/8100) `@npmcli/package-json@6.1.1` +* [`ab17523`](https://github.com/npm/cli/commit/ab175238dd885e2aa6cf2be21796055c629ec1e5) [#8134](https://github.com/npm/cli/pull/8134) `supports-color@10.0.0` +* [`3cbe21a`](https://github.com/npm/cli/commit/3cbe21ae64d5c1276c9aa6b53876fe86c165867d) [#8134](https://github.com/npm/cli/pull/8134) `foreground-child@3.3.1` +* [`ee5e1aa`](https://github.com/npm/cli/commit/ee5e1aa43e69e89da5ce210969a2f4cc1e3e08b0) [#8118](https://github.com/npm/cli/pull/8118) `@npmcli/redact@3.1.1` +* [`5df69b4`](https://github.com/npm/cli/commit/5df69b42be4e16b770d4452520a37f9456c26b66) [#8118](https://github.com/npm/cli/pull/8118) `exponential-backoff@3.1.2` +* [`80c3273`](https://github.com/npm/cli/commit/80c3273901e9878ec5492e8d99cca5ef14324a60) [#8118](https://github.com/npm/cli/pull/8118) `read@4.1.0` +* [`7fd70fa`](https://github.com/npm/cli/commit/7fd70fa2660c549cb564f956db0f5d0d2363db98) [#8118](https://github.com/npm/cli/pull/8118) `node-gyp@11.1.0` +* [`7aeffff`](https://github.com/npm/cli/commit/7aeffff2a39446b28319cbac5dbbd949d1965412) [#8118](https://github.com/npm/cli/pull/8118) `cidr-regex@4.1.3` +* [`b0c0490`](https://github.com/npm/cli/commit/b0c04908d413e71704cf8f5c6f469ab005c7385b) [#8118](https://github.com/npm/cli/pull/8118) `is-cidr@5.1.1` +* [`ef49d6b`](https://github.com/npm/cli/commit/ef49d6bcc8130f3e25f92b123bc46abe8a64e773) [#8118](https://github.com/npm/cli/pull/8118) `sigstore@3.1.0` +* [`1399bfb`](https://github.com/npm/cli/commit/1399bfb24ac04fcdc3d7464488dc4e8cd191b9da) [#8118](https://github.com/npm/cli/pull/8118) `socks@2.8.4` +* [`6b72107`](https://github.com/npm/cli/commit/6b72107063757bfd4b061dde01029a8a75c5e8b4) [#8118](https://github.com/npm/cli/pull/8118) `semver@7.7.1` +* [`c9ad0c4`](https://github.com/npm/cli/commit/c9ad0c4bbee2ee13a1521e10268edbbb3b794e8e) [#8118](https://github.com/npm/cli/pull/8118) `@npmcli/git@6.0.3` +* [`b153927`](https://github.com/npm/cli/commit/b153927feca3717598440b82a705281d652b4bf0) [#8115](https://github.com/npm/cli/pull/8115) `npm-package-arg@12.0.2` +* [`f0f6265`](https://github.com/npm/cli/commit/f0f626526b86bb54862bb4c0e3c24adfc0f1c8ce) [#8071](https://github.com/npm/cli/pull/8071) `nopt@8.1.0` +### Chores +* [`cc72b89`](https://github.com/npm/cli/commit/cc72b89cc07993a0fa3a7fb55ab91ac2798de7a2) [#8143](https://github.com/npm/cli/pull/8143) fix smoke tests to account for new release versions within a workspace (#8143) (@reggi) +* [`c3810bc`](https://github.com/npm/cli/commit/c3810bc8735336e6983fefb811f8e08279f7cddf) [#8134](https://github.com/npm/cli/pull/8134) dev dependency updates (@wraithgar) +* [`9dc40e6`](https://github.com/npm/cli/commit/9dc40e6c96c2c019c95fdc745bc1756da08bcc28) [#8118](https://github.com/npm/cli/pull/8118) dev dependency updates (@wraithgar) +* [`7ec0831`](https://github.com/npm/cli/commit/7ec0831b22eb65b69c0f0908139e582ff5b5af15) [#8118](https://github.com/npm/cli/pull/8118) update jsonpath-plus (@wraithgar) +* [`ed85b01`](https://github.com/npm/cli/commit/ed85b014bfb050ae4ae04827133d49b0f78c5df0) [#8071](https://github.com/npm/cli/pull/8071) tests for config warnings/changes (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.1): `@npmcli/arborist@9.0.1` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.1.0): `@npmcli/config@10.1.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.1): `libnpmdiff@8.0.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.1.0): `libnpmexec@10.1.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.1): `libnpmfund@7.0.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.1): `libnpmpack@9.0.1` + +## [11.1.0](https://github.com/npm/cli/compare/v11.0.0...v11.1.0) (2025-01-29) ### Features - -* [`1c93c44`](https://github.com/npm/cli/commit/1c93c4430300e3b3bd2cb5bab327c1732f470bca) [#6755](https://github.com/npm/cli/pull/6755) Add `--cpu` and `--os` option to override platform specific install (#6755) (@yukukotani) - +* [`7f6c997`](https://github.com/npm/cli/commit/7f6c9973dc9a4dfebd76e52e060a9d8496b8bd98) [#8009](https://github.com/npm/cli/pull/8009) add dry-run to deprecate/undeprecate commands (@wraithgar) +* [`1764a37`](https://github.com/npm/cli/commit/1764a37f1913b6a0811a85d89e029fc1dc79da54) [#8009](https://github.com/npm/cli/pull/8009) add npm undeprecate command (@wraithgar) ### Bug Fixes - -* [`7bf2374`](https://github.com/npm/cli/commit/7bf2374a1dde0e9b4a4345eeaafb23316a9a5a0b) [#6762](https://github.com/npm/cli/pull/6762) make `$npm_execpath` always point to npm (@rotu) - +* [`31455b2`](https://github.com/npm/cli/commit/31455b2e177b721292f3382726e3f5f3f2963b1d) [#8054](https://github.com/npm/cli/pull/8054) publish: honor force for no dist tag and registry version check (#8054) (@reggi) +* [`dc31c1b`](https://github.com/npm/cli/commit/dc31c1bdc6658ab69554adcf2988ee99a615c409) [#8038](https://github.com/npm/cli/pull/8038) remove max-len linting bypasses (@wraithgar) +* [`8a911ff`](https://github.com/npm/cli/commit/8a911ff895967678aa786595db3418fc28e6966a) [#8038](https://github.com/npm/cli/pull/8038) publish: disregard deprecated versions when calculating highest version (@wraithgar) +* [`7f72944`](https://github.com/npm/cli/commit/7f72944e43f009cf4d55ff4fe24c459e07f588fd) [#8038](https://github.com/npm/cli/pull/8038) publish: accept publishConfig.tag to override highest semver check (@wraithgar) +* [`ab9ddc0`](https://github.com/npm/cli/commit/ab9ddc0413374fbf4879da535f82e03bc4e62cf3) [#7992](https://github.com/npm/cli/pull/7992) sbom: deduplicate sbom dependencies (#7992) (@bdehamer) +* [`f7da341`](https://github.com/npm/cli/commit/f7da341322c2f860156e8144b208583596504479) [#7980](https://github.com/npm/cli/pull/7980) search: properly display multiple search terms (#7980) (@wraithgar) ### Documentation - -* [`09d8e0a`](https://github.com/npm/cli/commit/09d8e0a20bd11f53a9fafac1fff4f1ec0b7b379e) [#6759](https://github.com/npm/cli/pull/6759) fix versions of node.js in readme (#6759) (@JoaoOtavioS) - +* [`3644e79`](https://github.com/npm/cli/commit/3644e79a73e511bc54d857bc2026b071fe18a6fe) [#8055](https://github.com/npm/cli/pull/8055) update readme for Node.js versions, remove badges (#8055) (@wraithgar) +* [`f1af61f`](https://github.com/npm/cli/commit/f1af61f917e58a0a45d2b15d1e5600988b2c824f) [#8041](https://github.com/npm/cli/pull/8041) fix typos in "package-json" (#8041) (@maxkoryukov) +* [`e90c6fe`](https://github.com/npm/cli/commit/e90c6feeacdf9ad010d4d73b65d7dd7d3b86efe2) [#8051](https://github.com/npm/cli/pull/8051) depth flag default value (#8051) (@milaninfy) +* [`866b5ee`](https://github.com/npm/cli/commit/866b5ee3ae5ed508ecbe832d01f5ebd6b00f6789) [#8030](https://github.com/npm/cli/pull/8030) safer documentation urls, repos, packages (#8030) (@reggi) ### Dependencies - -* [`f76066a`](https://github.com/npm/cli/commit/f76066a047e4a0e819149356b68a1c50fd30f9de) [#6771](https://github.com/npm/cli/pull/6771) `@npmcli/agent@2.1.1` -* [Workspace](https://github.com/npm/cli/releases/tag/arborist-v7.1.0): `@npmcli/arborist@7.1.0` -* [Workspace](https://github.com/npm/cli/releases/tag/config-v7.2.0): `@npmcli/config@7.2.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.0.1): `libnpmdiff@6.0.1` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v7.0.1): `libnpmexec@7.0.1` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v4.1.1): `libnpmfund@4.1.1` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v6.0.1): `libnpmpack@6.0.1` - -## [10.0.0](https://github.com/npm/cli/compare/v10.0.0-pre.1...v10.0.0) (2023-08-31) - -### Features - -* [`48a7b07`](https://github.com/npm/cli/commit/48a7b077d70cbe5bc808db6aae2c734aa202938a) remove prerelease flags (@lukekarrys) - +* [`7ddfbad`](https://github.com/npm/cli/commit/7ddfbadd1d51d07e68afbe1b91a36106d98c7bea) [#8053](https://github.com/npm/cli/pull/8053) `@npmcli/package-json@6.1.1` +* [`9473a86`](https://github.com/npm/cli/commit/9473a8638257297c420136009de567c131d2f299) [#8053](https://github.com/npm/cli/pull/8053) `spdx-license-ids@3.0.21` +* [`a65e5ce`](https://github.com/npm/cli/commit/a65e5ceb15c4aad6bde1ffdbee7da6f685caf81e) [#8053](https://github.com/npm/cli/pull/8053) `@sigstore/protobuf-specs@0.3.3` +* [`215ebe4`](https://github.com/npm/cli/commit/215ebe4d8f6c7f30d4b6a68fa11a3372c132929e) [#8053](https://github.com/npm/cli/pull/8053) `chalk@5.4.1` +### Chores +* [`61f00e3`](https://github.com/npm/cli/commit/61f00e3c23211d37c7980ebd6d1cf8d1dac49f18) [#8069](https://github.com/npm/cli/pull/8069) splits out smoke-tests from publish-dryrun tests (#8069) (@reggi) +* [`6d0f46e`](https://github.com/npm/cli/commit/6d0f46e67e9673e8a2dc6edb92144a73f853950c) [#8058](https://github.com/npm/cli/pull/8058) stop publish smoke from check git clean (#8058) (@reggi) +* [`9281ebf`](https://github.com/npm/cli/commit/9281ebf8e428d40450ad75ba61bc6f040b3bf896) [#8057](https://github.com/npm/cli/pull/8057) fix smoke tests prerelease needs separate string args (#8057) (@reggi) +* [`aa202e9`](https://github.com/npm/cli/commit/aa202e9dac2f927bedcaaed4db0eef7b3415fc68) [#8056](https://github.com/npm/cli/pull/8056) smoke tests using a preid (#8056) (@reggi) +* [`18e0449`](https://github.com/npm/cli/commit/18e0449ae41703a7980cee73bae69521db6fa53e) [#8053](https://github.com/npm/cli/pull/8053) dev dependency updates (@wraithgar) +* [`859a71c`](https://github.com/npm/cli/commit/859a71c59ea5f91f21a8410db46585a2fc0a8126) [#8052](https://github.com/npm/cli/pull/8052) update node versions for release integration tests (#8052) (@wraithgar) +* [`7e7961d`](https://github.com/npm/cli/commit/7e7961d8936e277f3dbc8e44f9e7b07daaeb36ca) [#8038](https://github.com/npm/cli/pull/8038) bump @npmcli/eslint-config to 5.1.0 (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.0.1): `@npmcli/config@10.0.1` + +## [11.0.0](https://github.com/npm/cli/compare/v11.0.0-pre.1...v11.0.0) (2024-12-16) +### Documentation +* [`8a911da`](https://github.com/npm/cli/commit/8a911da452b9785bcd051778570beeb2d8b27421) [#7963](https://github.com/npm/cli/pull/7963) ls: removed design change pending section note (#7963) (@milaninfy) ### Dependencies - -* [Workspace](https://github.com/npm/cli/releases/tag/arborist-v7.0.0): `@npmcli/arborist@7.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/config-v7.1.0): `@npmcli/config@7.1.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v8.0.0): `libnpmaccess@8.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.0.0): `libnpmdiff@6.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v7.0.0): `libnpmexec@7.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v4.1.0): `libnpmfund@4.1.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmhook-v10.0.0): `libnpmhook@10.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmorg-v6.0.0): `libnpmorg@6.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v6.0.0): `libnpmpack@6.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v9.0.0): `libnpmpublish@9.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmsearch-v7.0.0): `libnpmsearch@7.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmteam-v6.0.0): `libnpmteam@6.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v5.0.0): `libnpmversion@5.0.0` - -## [10.0.0-pre.1](https://github.com/npm/cli/compare/v10.0.0-pre.0...v10.0.0-pre.1) (2023-08-31) - +* [`5319e48`](https://github.com/npm/cli/commit/5319e48a5a91768dccdfe728392dc2040e7ce27e) [#7973](https://github.com/npm/cli/pull/7973) remove unnecessary sprintf-js files in node_modules (#7973) +* [`d369c77`](https://github.com/npm/cli/commit/d369c7716d753580da708723a2a4f8b3be767cb1) [#7976](https://github.com/npm/cli/pull/7976) `socks-proxy-agent@8.0.5` +* [`3b2951a`](https://github.com/npm/cli/commit/3b2951a3ba1521b9866d9b33960aa3307d4f31dd) [#7976](https://github.com/npm/cli/pull/7976) `https-proxy-agent@7.0.6` +* [`a598b7b`](https://github.com/npm/cli/commit/a598b7bd3de2b02bd14a3fa2f49c14a5ca50a43e) [#7976](https://github.com/npm/cli/pull/7976) `agent-base@7.1.3` +* [`52bcaf6`](https://github.com/npm/cli/commit/52bcaf6464f44b30137ee3d3fe79322c1b1646ef) [#7976](https://github.com/npm/cli/pull/7976) `debug@4.4.0` +* [`aabf345`](https://github.com/npm/cli/commit/aabf345a524f8aba7e0f45c0d4b8c86d5160d0cc) [#7976](https://github.com/npm/cli/pull/7976) `p-map@7.0.3` +* [`28e8761`](https://github.com/npm/cli/commit/28e876135411cd9a93dbdd74906869c54286d7bc) [#7976](https://github.com/npm/cli/pull/7976) `npm-package-arg@12.0.1` +### Chores +* [`ecd7190`](https://github.com/npm/cli/commit/ecd719026860d464557223b212acec4347477128) [#7976](https://github.com/npm/cli/pull/7976) dev dependency updates (@wraithgar) +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) +* [`687ab12`](https://github.com/npm/cli/commit/687ab12eb5ea0ee1017101f3a83d42fd76299627) [#7970](https://github.com/npm/cli/pull/7970) remove pre-release mode from npm 11 and workspaces (#7970) (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0): `@npmcli/arborist@9.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.0.0): `@npmcli/config@10.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v10.0.0): `libnpmaccess@10.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.0): `libnpmdiff@8.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.0.0): `libnpmexec@10.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.0): `libnpmfund@7.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmorg-v8.0.0): `libnpmorg@8.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.0): `libnpmpack@9.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v11.0.0): `libnpmpublish@11.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmsearch-v9.0.0): `libnpmsearch@9.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmteam-v8.0.0): `libnpmteam@8.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v8.0.0): `libnpmversion@8.0.0` + +## [11.0.0-pre.1](https://github.com/npm/cli/compare/v11.0.0-pre.0...v11.0.0-pre.1) (2024-12-06) ### ⚠️ BREAKING CHANGES - -* support for node <=16.13 has been removed -* support for node 14 has been removed -* support for node 14 has been removed -* support for node 14 has been removed -* support for node 14 has been removed -* support for node 14 has been removed -* support for node 14 has been removed -* support for node 14 has been removed -* support for node 14 has been removed -* support for node 14 has been removed -* support for node 14 has been removed - +* Upon publishing, in order to apply a default "latest" dist tag, the command now retrieves all prior versions of the package. It will require that the version you're trying to publish is above the latest semver version in the registry, not including pre-release tags. +* `npm init` now has a `type` prompt, and sorts the entries in created packages differently +* `bun.lockb` files are now included in the strict ignore list during packing +### Features +* [`f3ac7b7`](https://github.com/npm/cli/commit/f3ac7b7460e1d9e1f9d3d8056317e36bb9813d5d) [#7939](https://github.com/npm/cli/pull/7939) no implicit latest tag on publish when latest > version (#7939) (@reggi, @ljharb) ### Bug Fixes - -* [`b34ee65`](https://github.com/npm/cli/commit/b34ee65ad1c82b53d5b5b28595203e18163fe4df) [#6706](https://github.com/npm/cli/pull/6706) set objectMode for search filter stream (@lukekarrys) -* [`6b251b1`](https://github.com/npm/cli/commit/6b251b1009648b36d49b83a2cc407c348fa225e0) [#6706](https://github.com/npm/cli/pull/6706) drop node 16.13.x support (@lukekarrys) -* [`d857c4a`](https://github.com/npm/cli/commit/d857c4ac7321211848076d148a4bea46af7058fd) [#6706](https://github.com/npm/cli/pull/6706) drop node14 support (@lukekarrys) -* [`37a99eb`](https://github.com/npm/cli/commit/37a99eb98b8846ab9481cc4ebd7a7278a8bc89bd) [#6706](https://github.com/npm/cli/pull/6706) drop node14 support (@lukekarrys) -* [`ee7292e`](https://github.com/npm/cli/commit/ee7292ed78c362927736471e0584217b2000f493) [#6706](https://github.com/npm/cli/pull/6706) drop node14 support (@lukekarrys) -* [`8b0e755`](https://github.com/npm/cli/commit/8b0e755b78098d9c0800e69f0cc2f6a457ce28a6) [#6706](https://github.com/npm/cli/pull/6706) drop node14 support (@lukekarrys) -* [`5c8c6cc`](https://github.com/npm/cli/commit/5c8c6ccc0be6e544f6884ecc1189de02450b7dfc) [#6706](https://github.com/npm/cli/pull/6706) drop node14 support (@lukekarrys) -* [`d431647`](https://github.com/npm/cli/commit/d4316479a7894290586718e412d7c670316a36f2) [#6706](https://github.com/npm/cli/pull/6706) drop node14 support (@lukekarrys) -* [`b6f2205`](https://github.com/npm/cli/commit/b6f220569791d655ab3c423990356cee47ca5218) [#6706](https://github.com/npm/cli/pull/6706) drop node14 support (@lukekarrys) -* [`4caedd0`](https://github.com/npm/cli/commit/4caedd0e49641e9f1757f5622e5845b5b49c56c1) [#6706](https://github.com/npm/cli/pull/6706) drop node14 support (@lukekarrys) -* [`355bac8`](https://github.com/npm/cli/commit/355bac87eb66b105c9f0c2338ae37fed5f973b66) [#6706](https://github.com/npm/cli/pull/6706) drop node14 support (@lukekarrys) -* [`e3a377d`](https://github.com/npm/cli/commit/e3a377d3b047c0436e05096d70cc5697714e413d) [#6706](https://github.com/npm/cli/pull/6706) drop node14 support (@lukekarrys) -* [`f916d33`](https://github.com/npm/cli/commit/f916d333c16b4f0433d8a304e856b73ed4f949cd) [#6715](https://github.com/npm/cli/pull/6715) allow searching packages with no description (@lukekarrys) - +* [`e362c6d`](https://github.com/npm/cli/commit/e362c6d3a6c8bc0221b8c8a6c3dd623da9e6ae04) [#7944](https://github.com/npm/cli/pull/7944) prefix: remove duplicate -g from usage output (#7944) (@wraithgar) ### Documentation - -* [`c736b62`](https://github.com/npm/cli/commit/c736b622b8504b07f5a19f631ade42dd40063269) [#6686](https://github.com/npm/cli/pull/6686) add missing bugs key in package-json.md (#6686) (@airscripts) -* [`c1e01d9`](https://github.com/npm/cli/commit/c1e01d97da3b775edf104de158ee5db5cf027d0d) [#6680](https://github.com/npm/cli/pull/6680) Update package-json.md (#6680) (@p-chan, @ljharb) - +* [`2af31dd`](https://github.com/npm/cli/commit/2af31dd30f4c226f43ce7295cd0b5fbb3f3cb2a6) [#7947](https://github.com/npm/cli/pull/7947) change certfile to cafile (#7947) (@wraithgar) +* [`1be8e95`](https://github.com/npm/cli/commit/1be8e9500826e7aef041976fd908658f473caf23) [#7945](https://github.com/npm/cli/pull/7945) update ignore rules (@wraithgar) ### Dependencies - -* [`5ab3f7e`](https://github.com/npm/cli/commit/5ab3f7e944b12481cb1164175c7a79d24d5e3ac5) [#6706](https://github.com/npm/cli/pull/6706) `@npmcli/git@5.0.3` -* [`eb41977`](https://github.com/npm/cli/commit/eb41977c56cbac88fa7d02f88dbf630cc652471a) [#6706](https://github.com/npm/cli/pull/6706) `@npmcli/run-script@7.0.1` -* [`f30c9e3`](https://github.com/npm/cli/commit/f30c9e30c2a6d777ea31157a90fddadc81fd11d0) [#6706](https://github.com/npm/cli/pull/6706) `@npmcli/git@5.0.2` -* [`f334466`](https://github.com/npm/cli/commit/f334466c53669e7debd4b9c67eafca74955509ee) [#6706](https://github.com/npm/cli/pull/6706) `pacote@17.0.4` -* [`bb63bf9`](https://github.com/npm/cli/commit/bb63bf945b2db8f3074e7429aff6343721c55cd1) [#6706](https://github.com/npm/cli/pull/6706) `@npmcli/run-script@7.0.0` -* [`75642c6`](https://github.com/npm/cli/commit/75642c6041195e093ef15ee2a42e1fc6a381c572) [#6706](https://github.com/npm/cli/pull/6706) `@npmcli/promise-spawn@7.0.0` -* [`dbb18f4`](https://github.com/npm/cli/commit/dbb18f4778a97915cd8bbb737a807f3db51c4619) [#6706](https://github.com/npm/cli/pull/6706) `@npmcli/agent@2.1.0` -* [`812aa6d`](https://github.com/npm/cli/commit/812aa6d2027ed42453b86b22f4cf8de25f6e0180) [#6706](https://github.com/npm/cli/pull/6706) `sigstore@2.1.0` -* [`7fab9d3`](https://github.com/npm/cli/commit/7fab9d3d2efd71f505658216dc44d802bc3203a6) [#6706](https://github.com/npm/cli/pull/6706) `@sigstore/tuf@2.1.0` -* [`12337cc`](https://github.com/npm/cli/commit/12337cc9d43bae2c5ad75e295b6a4d70e15a39cf) [#6706](https://github.com/npm/cli/pull/6706) `which@4.0.0` -* [`b1ad3ad`](https://github.com/npm/cli/commit/b1ad3ad194d046aa6209a4efad961429b379393c) [#6706](https://github.com/npm/cli/pull/6706) `npm-packlist@8.0.0` -* [`43831d0`](https://github.com/npm/cli/commit/43831d0fe4b02cb18d1c533f2831aaeedf5102e1) [#6706](https://github.com/npm/cli/pull/6706) `pacote@17.0.3` -* [`44e8fec`](https://github.com/npm/cli/commit/44e8fec3f28ce3bdd0500b92cbcf8f211da3c866) [#6706](https://github.com/npm/cli/pull/6706) `pacote@17.0.2` -* [`0d2e2c9`](https://github.com/npm/cli/commit/0d2e2c9d09ff760d8db09774fcd7ad417a88c4c7) [#6706](https://github.com/npm/cli/pull/6706) bump sigstore from 1.7.0 to 2.0.0 -* [`dbd5885`](https://github.com/npm/cli/commit/dbd5885364648d3f2fe1c7b672e8aeadcd06edd1) [#6706](https://github.com/npm/cli/pull/6706) `npm-profile@9.0.0` -* [`2ee0fb3`](https://github.com/npm/cli/commit/2ee0fb3ac0c5e49f9eba545d6b05e20be1352414) [#6706](https://github.com/npm/cli/pull/6706) `npm-registry-fetch@16.0.0` -* [`81ff4df`](https://github.com/npm/cli/commit/81ff4dfd17024efb068816c9b0824ffc709a7cc4) [#6706](https://github.com/npm/cli/pull/6706) `pacote@17.0.1` -* [`2b23d44`](https://github.com/npm/cli/commit/2b23d44a9f0f01370d4999853aedecec4f1d8dd3) [#6706](https://github.com/npm/cli/pull/6706) hoist `read-package-json@7.0.0` -* [`325ed05`](https://github.com/npm/cli/commit/325ed05be53b57096727fb962925bf362edf9730) [#6706](https://github.com/npm/cli/pull/6706) hoist `normalize-package-data@6.0.0` -* [`c3a1a02`](https://github.com/npm/cli/commit/c3a1a021780d948a3023b622700b98aabb0df2f4) [#6706](https://github.com/npm/cli/pull/6706) `@npmcli/metavuln-calculator@7.0.0` -* [`f1dd130`](https://github.com/npm/cli/commit/f1dd1305fdcba0b7f5496223b5a65f0fe7e29975) [#6706](https://github.com/npm/cli/pull/6706) `@npmcli/git@5.0.1` -* [`10792ea`](https://github.com/npm/cli/commit/10792ea951a3ef8fc138f82d7b81484006213ce9) [#6706](https://github.com/npm/cli/pull/6706) `init-package-json@6.0.0` -* [`cac0725`](https://github.com/npm/cli/commit/cac07256e7234d0782a4833dae207732c71fef95) [#6706](https://github.com/npm/cli/pull/6706) `pacote@17.0.0` -* [`fd8beaf`](https://github.com/npm/cli/commit/fd8beaf4de23b8fbd9d5b968e10a5034d1a8f7bd) [#6706](https://github.com/npm/cli/pull/6706) `npm-pick-manifest@9.0.0` -* [`65f435e`](https://github.com/npm/cli/commit/65f435ee0a088d6593d8e985c2519cdd783f9a6d) [#6706](https://github.com/npm/cli/pull/6706) hoist `lru-cache@10.0.1` -* [`c784b57`](https://github.com/npm/cli/commit/c784b57b654d25e8d932e6fe415b87e75dcf9026) [#6706](https://github.com/npm/cli/pull/6706) `npm-package-arg@11.0.0` -* [`d6b1790`](https://github.com/npm/cli/commit/d6b1790492d9bc96c196d85d8fc9fd98d62d0087) [#6706](https://github.com/npm/cli/pull/6706) `normalize-package-data@6.0.0` -* [`2f03fb9`](https://github.com/npm/cli/commit/2f03fb9d8f25fd2b047d46edb608eb75f1f36017) [#6706](https://github.com/npm/cli/pull/6706) `make-fetch-happen@13.0.0` -* [`729e893`](https://github.com/npm/cli/commit/729e893cf610de725142f72cc344d1c11f42d7af) [#6706](https://github.com/npm/cli/pull/6706) `hosted-git-info@7.0.0` -* [`7af81c7`](https://github.com/npm/cli/commit/7af81c7360a6df31cdb0a8f18104b42656166378) [#6706](https://github.com/npm/cli/pull/6706) `cacache@18.0.0` -* [`b0849ab`](https://github.com/npm/cli/commit/b0849ab6feb62bf307ee362389bfcaf0e85653be) [#6706](https://github.com/npm/cli/pull/6706) `@npmcli/package-json@5.0.0` -* [`c9587d7`](https://github.com/npm/cli/commit/c9587d79c7c02aff4f53b093bf6702026ecea53a) [#6706](https://github.com/npm/cli/pull/6706) `@npmcli/git@5.0.0` -* [`e28d426`](https://github.com/npm/cli/commit/e28d42674deb791d862e07756bb453190773e6ec) [#6706](https://github.com/npm/cli/pull/6706) `minipass-fetch@3.0.4` -* [`61e9b00`](https://github.com/npm/cli/commit/61e9b00e096ce2e3122f1b21d22f3073ff22f2ce) [#6706](https://github.com/npm/cli/pull/6706) `@npmcli/metavuln-calculator@6.0.1` -* [`2c5542d`](https://github.com/npm/cli/commit/2c5542d29ba207e7c5c4337ac9ad7f296188508a) [#6706](https://github.com/npm/cli/pull/6706) `minipass@7.0.3` -* [`ede7f5e`](https://github.com/npm/cli/commit/ede7f5e74ad4d88559fec2532ddba2facbd7af7f) [#6706](https://github.com/npm/cli/pull/6706) `glob@10.3.3` -* [`4c9eb17`](https://github.com/npm/cli/commit/4c9eb1703bd41555e4ef7c2fc087a349b90c9b4c) [#6706](https://github.com/npm/cli/pull/6706) `npm-install-checks@6.2.0` -* [`88ece81`](https://github.com/npm/cli/commit/88ece8161021997cb5c22040b34d0dffff55fcf1) [#6706](https://github.com/npm/cli/pull/6706) `npm-pick-manifest@8.0.2` -* [`9117a4f`](https://github.com/npm/cli/commit/9117a4fcf05291ce7609bcad5bb810df9a5158e7) [#6706](https://github.com/npm/cli/pull/6706) `ssri@10.0.5` -* [`45f8d6f`](https://github.com/npm/cli/commit/45f8d6f15f82067f27d56357159a7f965b857f5d) [#6706](https://github.com/npm/cli/pull/6706) `make-fetch-happen@12.0.0` -* [`f6f6a18`](https://github.com/npm/cli/commit/f6f6a18120b31626259cdd4da834524a034aa4cb) [#6706](https://github.com/npm/cli/pull/6706) `fs-minipass@3.0.3` -* [`5eea975`](https://github.com/npm/cli/commit/5eea975437ab27d02afa2aaee59b2d4f98831df3) [#6706](https://github.com/npm/cli/pull/6706) `cacache@17.1.4` -* [`ca33c98`](https://github.com/npm/cli/commit/ca33c9840533435bda634adefb61757f30fad5ab) [#6706](https://github.com/npm/cli/pull/6706) `@npmcli/metavuln-calculator@6.0.0` -* [`7be541a`](https://github.com/npm/cli/commit/7be541a7a82cf1fb0de58953605b69c058f7efe0) [#6706](https://github.com/npm/cli/pull/6706) `npm-profile@8.0.0` -* [`edbc25a`](https://github.com/npm/cli/commit/edbc25a5980c34e0d28aac7503475cd33e07f7d2) [#6706](https://github.com/npm/cli/pull/6706) `pacote@16.0.0` -* [`5d0d859`](https://github.com/npm/cli/commit/5d0d8592cbf3b816d9fe44c36d390200ec15e87a) [#6706](https://github.com/npm/cli/pull/6706) `npm-registry-fetch@15.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/arborist-v7.0.0-pre.0): `@npmcli/arborist@7.0.0-pre.0` -* [Workspace](https://github.com/npm/cli/releases/tag/config-v7.0.1): `@npmcli/config@7.0.1` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v8.0.0-pre.0): `libnpmaccess@8.0.0-pre.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v6.0.0-pre.0): `libnpmdiff@6.0.0-pre.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v7.0.0-pre.0): `libnpmexec@7.0.0-pre.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v4.0.20): `libnpmfund@4.0.20` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmhook-v10.0.0-pre.0): `libnpmhook@10.0.0-pre.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmorg-v6.0.0-pre.0): `libnpmorg@6.0.0-pre.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v6.0.0-pre.0): `libnpmpack@6.0.0-pre.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v9.0.0-pre.0): `libnpmpublish@9.0.0-pre.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmsearch-v7.0.0-pre.0): `libnpmsearch@7.0.0-pre.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmteam-v6.0.0-pre.0): `libnpmteam@6.0.0-pre.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v5.0.0-pre.0): `libnpmversion@5.0.0-pre.0` - -## [10.0.0-pre.0](https://github.com/npm/cli/compare/v9.8.1...v10.0.0-pre.0) (2023-07-26) - +* [`bc9b14d`](https://github.com/npm/cli/commit/bc9b14dc35378262c36ef5f59f96455b21a430cc) [#7955](https://github.com/npm/cli/pull/7955) `@npmcli/run-script@9.0.2` +* [`fecfcf4`](https://github.com/npm/cli/commit/fecfcf4987e30cc5ed04b0b77ccc9eb30c2b5c8f) [#7955](https://github.com/npm/cli/pull/7955) `node-gyp@11.0.0` +* [`8905037`](https://github.com/npm/cli/commit/890503767c733a1eacfdd562b01eb37ac253906c) [#7955](https://github.com/npm/cli/pull/7955) `p-map@7.0.2` +* [`ac8eb39`](https://github.com/npm/cli/commit/ac8eb390b0e0a21346fcdc5476ee0b884278b3a9) [#7955](https://github.com/npm/cli/pull/7955) `diff@7.0.0` +* [`c0bcc2a`](https://github.com/npm/cli/commit/c0bcc2a860fec5c86234dec44f5474364c25aefc) [#7955](https://github.com/npm/cli/pull/7955) `walk-up-path@4.0.0` +* [`d463a6f`](https://github.com/npm/cli/commit/d463a6f071da79b7a2151eeeea8a6f6cceea182f) [#7955](https://github.com/npm/cli/pull/7955) `init-package-json@8.0.0` +* [`b87ba24`](https://github.com/npm/cli/commit/b87ba2402ab86532d54b7b4e09b38582c0f11a5e) [#7945](https://github.com/npm/cli/pull/7945) `@npmcli/package-json@6.1.0` +* [`4bf1901`](https://github.com/npm/cli/commit/4bf1901f6dc57748d851ebe82262e9bef85a4ba7) [#7945](https://github.com/npm/cli/pull/7945) `@npmcli/metavuln-calculator@9.0.0` +* [`ca84b22`](https://github.com/npm/cli/commit/ca84b22a18806495c37ef6ee2aecd42a1c7bb7f6) [#7945](https://github.com/npm/cli/pull/7945) `pacote@21.0.0` +* [`4906f3d`](https://github.com/npm/cli/commit/4906f3ddf05c97f6e9832617a22c7ae228b46985) [#7945](https://github.com/npm/cli/pull/7945) `npm-packlist@10.0.0` +### Chores +* [`cfdf214`](https://github.com/npm/cli/commit/cfdf2147b5bfd80c7478486d07cb085de6fb8c4c) [#7943](https://github.com/npm/cli/pull/7943) fork changelog (#7943) (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0-pre.1): `@npmcli/arborist@9.0.0-pre.1` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.0.0-pre.1): `@npmcli/config@10.0.0-pre.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.0-pre.1): `libnpmdiff@8.0.0-pre.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.0.0-pre.1): `libnpmexec@10.0.0-pre.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.0-pre.1): `libnpmfund@7.0.0-pre.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmorg-v8.0.0-pre.1): `libnpmorg@8.0.0-pre.1` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.0-pre.1): `libnpmpack@9.0.0-pre.1` + +## [11.0.0-pre.0](https://github.com/npm/cli/compare/v10.9.0...v11.0.0-pre.0) (2024-11-26) ### ⚠️ BREAKING CHANGES - -* the "ci-name" config has been removed -* npm no longer treats missing scripts as a special case in workspace mode. Use `if-present` to ignore missing scripts. -* npm now supports node `^18.17.0 || >=20.5.0` - +* When publishing a package with a pre-release version, you must explicitly specify a tag. +* `--ignore-scripts` now applies to all lifecycle scripts, include `prepare` +* npm will no longer fall back to the old audit endpoint if the bulk advisory request fails. +* npm will no longer switch to global mode if aliased to "npmg" or "npm-g" etc. +* The `npm hook` command has been removed +* Attestations made by this package will no longer validate in npm versions prior to 10.6.0 +* npm now supports node `^20.17.0 || >=22.9.0` +* @npmcli/docs now supports node `^20.17.0 || >=22.9.0` ### Features - -* [`b6cf113`](https://github.com/npm/cli/commit/b6cf113f5199d3c23f632dbe35d8020515c6c623) [#6674](https://github.com/npm/cli/pull/6674) set engines and prerelease for npm 10 (#6674) (@lukekarrys) - +* [`6995303`](https://github.com/npm/cli/commit/6995303687ab59541b727bf611f73624d1829b6c) [#7850](https://github.com/npm/cli/pull/7850) adds `--ignore-scripts` flag to `pack` (@reggi) ### Bug Fixes - -* [`e0d3edd`](https://github.com/npm/cli/commit/e0d3edd9908f8303abb9941bdd2f6e9aa31bc9d7) [#6641](https://github.com/npm/cli/pull/6641) remove "ci-name" config (@wraithgar) -* [`0318f44`](https://github.com/npm/cli/commit/0318f442fe6c18275607a5d574c383f085484e6e) [#6641](https://github.com/npm/cli/pull/6641) remove implicit if-present logic from run-script workspaces (@wraithgar) - +* [`16b7367`](https://github.com/npm/cli/commit/16b7367245a0ea7228a27a43555eefb3c6b16870) [#7910](https://github.com/npm/cli/pull/7910) publishing prerelease requires explicit tag (#7910) (@reggi) +* [`e19bff0`](https://github.com/npm/cli/commit/e19bff0ece79b189497720f076c0b324cb641061) [#7901](https://github.com/npm/cli/pull/7901) perf: enable compile cache if present (#7901) (@H4ad) +* [`080a0f2`](https://github.com/npm/cli/commit/080a0f2d3f09a81f0a5b2992431e0bc7feb8d701) [#7911](https://github.com/npm/cli/pull/7911) remove old audit fallback request (@wraithgar) +* [`780afc5`](https://github.com/npm/cli/commit/780afc50e3a345feb1871a28e33fa48235bc3bd5) [#7855](https://github.com/npm/cli/pull/7855) pkg: display if any of multiple attributes exist (#7855) (@Sanderovich) +* [`ecd2d23`](https://github.com/npm/cli/commit/ecd2d23d429b2fee833e534e679cce97e4190b1b) [#7842](https://github.com/npm/cli/pull/7842) don't go into global mode if aliased to npmg (#7842) (@wraithgar) +* [`62c71e5`](https://github.com/npm/cli/commit/62c71e5128a01283f97bd62da30ddc673bddda0b) [#7835](https://github.com/npm/cli/pull/7835) removes `npm hook` command (@reggi) +* [`7f541e8`](https://github.com/npm/cli/commit/7f541e82a0b2908cc0cfef9a36b714eeab40c029) [#7815](https://github.com/npm/cli/pull/7815) make pack and exec work with git hash refs (#7815) (@milaninfy) +* [`3162620`](https://github.com/npm/cli/commit/316262004747e04dfdcf2628abbc45cd366c86b8) [#7831](https://github.com/npm/cli/pull/7831) sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +* [`4c8ba0a`](https://github.com/npm/cli/commit/4c8ba0aa678b532146200e4cc082f151983b0d82) [#7831](https://github.com/npm/cli/pull/7831) for @npmcli/docs sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +* [`70cd88d`](https://github.com/npm/cli/commit/70cd88d95aa06ac96154c14ee262076704af807f) [#7808](https://github.com/npm/cli/pull/7808) view: sort and truncate dist-tags (#7808) (@wraithgar) +* [`534ad77`](https://github.com/npm/cli/commit/534ad7789e5c61f579f44d782bdd18ea3ff1ee20) [#7795](https://github.com/npm/cli/pull/7795) remove unused parameters catch statements (#7795) (@btea) ### Documentation - -* [`e5338af`](https://github.com/npm/cli/commit/e5338af3ca5d1aea78348f4894481eef3b1f7354) [#6672](https://github.com/npm/cli/pull/6672) remove link to deprecated `npm set-script` command (#6672) (@emmanuel-ferdman) - +* [`feb54f7`](https://github.com/npm/cli/commit/feb54f7e9a39bd52519221bae4fafc8bc70f235e) [#7822](https://github.com/npm/cli/pull/7822) package.json: add libc field (#7822) (@wraithgar) ### Dependencies - -* [Workspace](https://github.com/npm/cli/releases/tag/config-v7.0.0): `@npmcli/config@7.0.0` -* [Workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v8.0.0): `libnpmpublish@8.0.0` +* [`78293ad`](https://github.com/npm/cli/commit/78293ad9b58b30b373dd69d15ea4e5735e720f55) [#7937](https://github.com/npm/cli/pull/7937) `spdx-license-ids@3.0.20` +* [`33cf580`](https://github.com/npm/cli/commit/33cf5801308b4b0b2a055e842a340135367f8a8d) [#7937](https://github.com/npm/cli/pull/7937) `promise-call-limit@3.0.2` +* [`ef1c368`](https://github.com/npm/cli/commit/ef1c3687b35295993258127ad7a5b0fd323fba8b) [#7937](https://github.com/npm/cli/pull/7937) `package-json-from-dist@1.0.1` +* [`92e6f07`](https://github.com/npm/cli/commit/92e6f076789b3bc39377308b84ee834b98855258) [#7937](https://github.com/npm/cli/pull/7937) `npm-registry-fetch@18.0.2` +* [`e32284a`](https://github.com/npm/cli/commit/e32284a8ebb679e41a2e8f0c8c63cc704296810c) [#7937](https://github.com/npm/cli/pull/7937) `npm-install-checks@7.1.1` +* [`5dffd11`](https://github.com/npm/cli/commit/5dffd112ba85864582b9af688ffc0b6d1a6a0166) [#7937](https://github.com/npm/cli/pull/7937) `negotiator@0.6.4` +* [`69d9f01`](https://github.com/npm/cli/commit/69d9f01ab11cb79bede2bde00423b9511d048c56) [#7937](https://github.com/npm/cli/pull/7937) `make-fetch-happen@14.0.3` +* [`884bbde`](https://github.com/npm/cli/commit/884bbde5a2865722fae0eb4de386f4d55ebdba93) [#7937](https://github.com/npm/cli/pull/7937) `hosted-git-info@8.0.2` +* [`3c74ec0`](https://github.com/npm/cli/commit/3c74ec00e1244178226b88331f703aded3c9d1e2) [#7937](https://github.com/npm/cli/pull/7937) `debug@4.3.7` +* [`f00359f`](https://github.com/npm/cli/commit/f00359f422d00ea6d209d624e2885e072b0a8f60) [#7937](https://github.com/npm/cli/pull/7937) `cross-spawn@7.0.6` +* [`534bbe8`](https://github.com/npm/cli/commit/534bbe8482f04f65c96c34fdd8734be91b29b18a) [#7937](https://github.com/npm/cli/pull/7937) `ci-info@4.1.0` +* [`8cbf1a7`](https://github.com/npm/cli/commit/8cbf1a75e12c586cdf77f03f7494ecb17b7030df) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/promise-spawn@8.0.2` +* [`1bd39e7`](https://github.com/npm/cli/commit/1bd39e7f766373021cc137fecc3cc3076967b444) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/map-workspaces@4.0.2` +* [`eb6498d`](https://github.com/npm/cli/commit/eb6498dc543fa117ba4d4bc87c7bc77423e2b72a) [#7937](https://github.com/npm/cli/pull/7937) `ansi-regex@6.1.0` +* [`66fc8c9`](https://github.com/npm/cli/commit/66fc8c997a37b0e28d35cb537fc68f6ed5466a73) [#7850](https://github.com/npm/cli/pull/7850) `@npmcli/metavuln-calculator@8.0.1` +* [`7dbef6f`](https://github.com/npm/cli/commit/7dbef6f3a3ead089b1b8b9fe6b2fa25e24309000) [#7850](https://github.com/npm/cli/pull/7850) `pacote@20.0.0` +* [`75a3f12`](https://github.com/npm/cli/commit/75a3f1228865f426d8790be27f1258e501f2c450) [#7859](https://github.com/npm/cli/pull/7859) remove unused deps (#7859) +* [`f36dc59`](https://github.com/npm/cli/commit/f36dc593ecbfe77439a1d0e31afb5a45de3b8d14) [#7833](https://github.com/npm/cli/pull/7833) `pacote@19.0.1` +* [`7ee15bb`](https://github.com/npm/cli/commit/7ee15bbdc1da0ed85297f47952b66089f29ed3fd) [#7833](https://github.com/npm/cli/pull/7833) bump sigstore from 2.x to 3.0.0 (@bdehamer) +### Chores +* [`2d530a5`](https://github.com/npm/cli/commit/2d530a5db705e72569d4beec02d86a2939b212f3) [#7941](https://github.com/npm/cli/pull/7941) tests: account for when npm is a prerelease (#7941) (@wraithgar) +* [`2c1b369`](https://github.com/npm/cli/commit/2c1b36951b1af9b798ece9392d778d4f9eff2268) [#7937](https://github.com/npm/cli/pull/7937) dev dependency updates (@wraithgar) +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) +* [`475285b`](https://github.com/npm/cli/commit/475285b81e8db441ccadca1273b2bae9d83fc941) [#7920](https://github.com/npm/cli/pull/7920) clean up dependency graph repos (#7920) (@hashtagchris) +* [`ec57f5f`](https://github.com/npm/cli/commit/ec57f5f0831e6e82b87b9ed9ebdfa9fc3d5ba1ee) [#7911](https://github.com/npm/cli/pull/7911) fix dependencies script for circular workspace deps (@wraithgar) +* [`ccd8420`](https://github.com/npm/cli/commit/ccd84201e4e369992289842a5117cb3b531a7a36) [#7911](https://github.com/npm/cli/pull/7911) fix cli tests for audit fallback removal (@wraithgar) +* [`720b4d8`](https://github.com/npm/cli/commit/720b4d807bd2e214a045a9ffa9c56435823a7a05) [#7833](https://github.com/npm/cli/pull/7833) bump @npmcli/arborist to 8.0.0 (@wraithgar) +* [`286739c`](https://github.com/npm/cli/commit/286739c0224bad88c4a38927bafd61973f71098c) [#7824](https://github.com/npm/cli/pull/7824) add creation of a DEPENDENCIES.json file (#7824) (@reggi) +* [`852dd8b`](https://github.com/npm/cli/commit/852dd8bdcb958439d343bcd9fb27fb4f07e95991) [#7831](https://github.com/npm/cli/pull/7831) sets npm 11 to prerelease (@reggi) +* [`95d009e`](https://github.com/npm/cli/commit/95d009e606b187b9e148f4f1119b8a19e5beb7f0) [#7831](https://github.com/npm/cli/pull/7831) update engine `^20.17.0 || >=22.9.0` in actions (@reggi) +* [`5a74478`](https://github.com/npm/cli/commit/5a744782af53d6655669e49d911468934ea5e027) [#7831](https://github.com/npm/cli/pull/7831) update engines `^20.17.0 || >=22.9.0` in package template (@reggi) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0-pre.0): `@npmcli/arborist@9.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/config-v10.0.0-pre.0): `@npmcli/config@10.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmaccess-v10.0.0-pre.0): `libnpmaccess@10.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmdiff-v8.0.0-pre.0): `libnpmdiff@8.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmexec-v10.0.0-pre.0): `libnpmexec@10.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmfund-v7.0.0-pre.0): `libnpmfund@7.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmorg-v8.0.0-pre.0): `libnpmorg@8.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpack-v9.0.0-pre.0): `libnpmpack@9.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmpublish-v11.0.0-pre.0): `libnpmpublish@11.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmsearch-v9.0.0-pre.0): `libnpmsearch@9.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmteam-v8.0.0-pre.0): `libnpmteam@8.0.0-pre.0` +* [workspace](https://github.com/npm/cli/releases/tag/libnpmversion-v8.0.0-pre.0): `libnpmversion@8.0.0-pre.0` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f05f05ae612b0..a6cbabb062eb4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,13 +13,13 @@ When submitting a new bug report, please first [search](https://github.com/npm/c **1. Clone this repository...** ```bash -$ git clone git@github.com:npm/cli.git npm +git clone git@github.com:npm/cli.git npm ``` **2. Navigate into project & install development-specific dependencies...** ```bash -$ cd ./npm && node ./scripts/resetdeps.js +cd ./npm && node ./scripts/resetdeps.js ``` **3. Write some code &/or add some tests...** @@ -30,7 +30,7 @@ $ cd ./npm && node ./scripts/resetdeps.js **4. Run tests & ensure they pass...** ``` -$ node . run test +node . run test ``` **5. Open a [Pull Request](https://github.com/npm/cli/pulls) for your work & become the newest contributor to `npm`! 🎉** @@ -61,24 +61,17 @@ node . exec ``` For example instead of: -```bash +```bash npm exec -- -``` +``` Use: ```bash node . exec -- ``` - - -## Performance & Benchmarks - -We've set up an automated [benchmark](https://github.com/npm/benchmarks) integration that will run against all Pull Requests; Posting back a comment with the results of the run. - -**Example:** - -![image](https://user-images.githubusercontent.com/2818462/72312698-e2e57f80-3656-11ea-9fcf-4a8f6b97b0d1.png) - -You can learn more about this tool, including how to run & configure it manually, [here](https://github.com/npm/benchmarks) +To update the snapshots run: +```bash +TAP_SNAPSHOT=1 node . run test +``` ## What _not_ to contribute? diff --git a/DEPENDENCIES.json b/DEPENDENCIES.json new file mode 100644 index 0000000000000..802d9bdd93373 --- /dev/null +++ b/DEPENDENCIES.json @@ -0,0 +1,92 @@ +[ + [ + "npm" + ], + [ + "@npmcli/mock-registry", + "libnpmdiff", + "libnpmexec", + "libnpmfund", + "libnpmpack" + ], + [ + "@npmcli/arborist" + ], + [ + "@npmcli/metavuln-calculator" + ], + [ + "pacote", + "@npmcli/config", + "libnpmversion" + ], + [ + "@npmcli/run-script", + "@npmcli/map-workspaces", + "libnpmaccess", + "libnpmorg", + "libnpmpublish", + "libnpmsearch", + "libnpmteam", + "init-package-json", + "npm-profile" + ], + [ + "@npmcli/package-json", + "npm-registry-fetch" + ], + [ + "@npmcli/git", + "make-fetch-happen" + ], + [ + "@npmcli/smoke-tests", + "npm-pick-manifest", + "@npmcli/installed-package-contents", + "cacache", + "promzard" + ], + [ + "@npmcli/docs", + "npm-package-arg", + "@npmcli/promise-spawn", + "npm-install-checks", + "npm-bundled", + "@npmcli/fs", + "npm-packlist", + "@npmcli/mock-globals", + "bin-links", + "nopt", + "parse-conflict-json", + "read" + ], + [ + "@npmcli/eslint-config", + "@npmcli/template-oss", + "ignore-walk", + "semver", + "hosted-git-info", + "proc-log", + "validate-npm-package-name", + "which", + "ini", + "npm-normalize-package-bin", + "json-parse-even-better-errors", + "@npmcli/node-gyp", + "ssri", + "@npmcli/redact", + "@npmcli/agent", + "minipass-fetch", + "@npmcli/name-from-folder", + "@npmcli/query", + "cmd-shim", + "read-cmd-shim", + "write-file-atomic", + "abbrev", + "proggy", + "minify-registry-metadata", + "mute-stream", + "npm-audit-report", + "npm-user-validate" + ] +] diff --git a/DEPENDENCIES.md b/DEPENDENCIES.md index f612fd4a3834e..7e64150920914 100644 --- a/DEPENDENCIES.md +++ b/DEPENDENCIES.md @@ -1,3 +1,5 @@ + + # npm dependencies ## `github.com/npm/` only @@ -5,12 +7,11 @@ graph LR; bin-links-->cmd-shim; bin-links-->npm-normalize-package-bin; + bin-links-->proc-log; bin-links-->read-cmd-shim; bin-links-->write-file-atomic; - cacache-->fs-minipass; cacache-->npmcli-fs["@npmcli/fs"]; cacache-->ssri; - cacache-->unique-filename; init-package-json-->npm-package-arg; init-package-json-->npmcli-package-json["@npmcli/package-json"]; init-package-json-->promzard; @@ -33,19 +34,16 @@ graph LR; libnpmexec-->npmcli-arborist["@npmcli/arborist"]; libnpmexec-->npmcli-eslint-config["@npmcli/eslint-config"]; libnpmexec-->npmcli-mock-registry["@npmcli/mock-registry"]; + libnpmexec-->npmcli-package-json["@npmcli/package-json"]; libnpmexec-->npmcli-run-script["@npmcli/run-script"]; libnpmexec-->npmcli-template-oss["@npmcli/template-oss"]; libnpmexec-->pacote; libnpmexec-->proc-log; - libnpmexec-->read-package-json-fast; libnpmexec-->read; libnpmexec-->semver; libnpmfund-->npmcli-arborist["@npmcli/arborist"]; libnpmfund-->npmcli-eslint-config["@npmcli/eslint-config"]; libnpmfund-->npmcli-template-oss["@npmcli/template-oss"]; - libnpmhook-->npm-registry-fetch; - libnpmhook-->npmcli-eslint-config["@npmcli/eslint-config"]; - libnpmhook-->npmcli-template-oss["@npmcli/template-oss"]; libnpmorg-->npm-registry-fetch; libnpmorg-->npmcli-eslint-config["@npmcli/eslint-config"]; libnpmorg-->npmcli-template-oss["@npmcli/template-oss"]; @@ -55,12 +53,12 @@ graph LR; libnpmpack-->npmcli-run-script["@npmcli/run-script"]; libnpmpack-->npmcli-template-oss["@npmcli/template-oss"]; libnpmpack-->pacote; - libnpmpublish-->normalize-package-data; libnpmpublish-->npm-package-arg; libnpmpublish-->npm-registry-fetch; libnpmpublish-->npmcli-eslint-config["@npmcli/eslint-config"]; libnpmpublish-->npmcli-mock-globals["@npmcli/mock-globals"]; libnpmpublish-->npmcli-mock-registry["@npmcli/mock-registry"]; + libnpmpublish-->npmcli-package-json["@npmcli/package-json"]; libnpmpublish-->npmcli-template-oss["@npmcli/template-oss"]; libnpmpublish-->proc-log; libnpmpublish-->semver; @@ -81,14 +79,13 @@ graph LR; make-fetch-happen-->cacache; make-fetch-happen-->minipass-fetch; make-fetch-happen-->npmcli-agent["@npmcli/agent"]; + make-fetch-happen-->npmcli-redact["@npmcli/redact"]; make-fetch-happen-->proc-log; make-fetch-happen-->ssri; nopt-->abbrev; - normalize-package-data-->hosted-git-info; - normalize-package-data-->semver; npm-->abbrev; + npm-->bin-links; npm-->cacache; - npm-->fs-minipass; npm-->hosted-git-info; npm-->ini; npm-->init-package-json; @@ -97,7 +94,6 @@ graph LR; npm-->libnpmdiff; npm-->libnpmexec; npm-->libnpmfund; - npm-->libnpmhook; npm-->libnpmorg; npm-->libnpmpack; npm-->libnpmpublish; @@ -106,7 +102,6 @@ graph LR; npm-->libnpmversion; npm-->make-fetch-happen; npm-->nopt; - npm-->normalize-package-data; npm-->npm-audit-report; npm-->npm-install-checks; npm-->npm-package-arg; @@ -121,9 +116,13 @@ graph LR; npm-->npmcli-eslint-config["@npmcli/eslint-config"]; npm-->npmcli-fs["@npmcli/fs"]; npm-->npmcli-git["@npmcli/git"]; + npm-->npmcli-installed-package-contents["@npmcli/installed-package-contents"]; npm-->npmcli-map-workspaces["@npmcli/map-workspaces"]; + npm-->npmcli-metavuln-calculator["@npmcli/metavuln-calculator"]; npm-->npmcli-mock-globals["@npmcli/mock-globals"]; npm-->npmcli-mock-registry["@npmcli/mock-registry"]; + npm-->npmcli-name-from-folder["@npmcli/name-from-folder"]; + npm-->npmcli-node-gyp["@npmcli/node-gyp"]; npm-->npmcli-package-json["@npmcli/package-json"]; npm-->npmcli-promise-spawn["@npmcli/promise-spawn"]; npm-->npmcli-redact["@npmcli/redact"]; @@ -137,7 +136,7 @@ graph LR; npm-->semver; npm-->ssri; npm-->validate-npm-package-name; - npm-->write-file-atomic; + npm-->which; npm-bundled-->npm-normalize-package-bin; npm-install-checks-->semver; npm-package-arg-->hosted-git-info; @@ -145,6 +144,7 @@ graph LR; npm-package-arg-->semver; npm-package-arg-->validate-npm-package-name; npm-packlist-->ignore-walk; + npm-packlist-->proc-log; npm-pick-manifest-->npm-install-checks; npm-pick-manifest-->npm-normalize-package-bin; npm-pick-manifest-->npm-package-arg; @@ -159,7 +159,6 @@ graph LR; npmcli-arborist-->bin-links; npmcli-arborist-->cacache; npmcli-arborist-->hosted-git-info; - npmcli-arborist-->json-parse-even-better-errors; npmcli-arborist-->minify-registry-metadata; npmcli-arborist-->nopt; npmcli-arborist-->npm-install-checks; @@ -171,6 +170,7 @@ graph LR; npmcli-arborist-->npmcli-installed-package-contents["@npmcli/installed-package-contents"]; npmcli-arborist-->npmcli-map-workspaces["@npmcli/map-workspaces"]; npmcli-arborist-->npmcli-metavuln-calculator["@npmcli/metavuln-calculator"]; + npmcli-arborist-->npmcli-mock-registry["@npmcli/mock-registry"]; npmcli-arborist-->npmcli-name-from-folder["@npmcli/name-from-folder"]; npmcli-arborist-->npmcli-node-gyp["@npmcli/node-gyp"]; npmcli-arborist-->npmcli-package-json["@npmcli/package-json"]; @@ -182,9 +182,9 @@ graph LR; npmcli-arborist-->parse-conflict-json; npmcli-arborist-->proc-log; npmcli-arborist-->proggy; - npmcli-arborist-->read-package-json-fast; npmcli-arborist-->semver; npmcli-arborist-->ssri; + npmcli-arborist-->validate-npm-package-name; npmcli-config-->ini; npmcli-config-->nopt; npmcli-config-->npmcli-eslint-config["@npmcli/eslint-config"]; @@ -204,10 +204,11 @@ graph LR; npmcli-git-->npmcli-promise-spawn["@npmcli/promise-spawn"]; npmcli-git-->proc-log; npmcli-git-->semver; + npmcli-git-->which; npmcli-installed-package-contents-->npm-bundled; npmcli-installed-package-contents-->npm-normalize-package-bin; npmcli-map-workspaces-->npmcli-name-from-folder["@npmcli/name-from-folder"]; - npmcli-map-workspaces-->read-package-json-fast; + npmcli-map-workspaces-->npmcli-package-json["@npmcli/package-json"]; npmcli-metavuln-calculator-->cacache; npmcli-metavuln-calculator-->json-parse-even-better-errors; npmcli-metavuln-calculator-->pacote; @@ -222,10 +223,10 @@ graph LR; npmcli-mock-registry-->pacote; npmcli-package-json-->hosted-git-info; npmcli-package-json-->json-parse-even-better-errors; - npmcli-package-json-->normalize-package-data; npmcli-package-json-->npmcli-git["@npmcli/git"]; npmcli-package-json-->proc-log; npmcli-package-json-->semver; + npmcli-promise-spawn-->which; npmcli-run-script-->npmcli-node-gyp["@npmcli/node-gyp"]; npmcli-run-script-->npmcli-package-json["@npmcli/package-json"]; npmcli-run-script-->npmcli-promise-spawn["@npmcli/promise-spawn"]; @@ -234,9 +235,8 @@ graph LR; npmcli-smoke-tests-->npmcli-mock-registry["@npmcli/mock-registry"]; npmcli-smoke-tests-->npmcli-promise-spawn["@npmcli/promise-spawn"]; npmcli-smoke-tests-->npmcli-template-oss["@npmcli/template-oss"]; - npmcli-smoke-tests-->semver; + npmcli-smoke-tests-->which; pacote-->cacache; - pacote-->fs-minipass; pacote-->npm-package-arg; pacote-->npm-packlist; pacote-->npm-pick-manifest; @@ -251,19 +251,14 @@ graph LR; parse-conflict-json-->json-parse-even-better-errors; promzard-->read; read-->mute-stream; - read-package-json-fast-->json-parse-even-better-errors; - read-package-json-fast-->npm-normalize-package-bin; - unique-filename-->unique-slug; ``` ## all dependencies ```mermaid graph LR; - agent-base-->debug; - aggregate-error-->clean-stack; - aggregate-error-->indent-string; bin-links-->cmd-shim; bin-links-->npm-normalize-package-bin; + bin-links-->proc-log; bin-links-->read-cmd-shim; bin-links-->write-file-atomic; brace-expansion-->balanced-match; @@ -277,30 +272,19 @@ graph LR; cacache-->npmcli-fs["@npmcli/fs"]; cacache-->p-map; cacache-->ssri; - cacache-->tar; - cacache-->unique-filename; - cidr-regex-->ip-regex; - cli-columns-->string-width; - cli-columns-->strip-ansi; - cross-spawn-->path-key; - cross-spawn-->shebang-command; - cross-spawn-->which; debug-->ms; - encoding-->iconv-lite; - foreground-child-->cross-spawn; - foreground-child-->signal-exit; + fdir-->picomatch; fs-minipass-->minipass; - glob-->foreground-child; - glob-->jackspeak; glob-->minimatch; glob-->minipass; - glob-->package-json-from-dist; glob-->path-scurry; hosted-git-info-->lru-cache; http-proxy-agent-->agent-base; http-proxy-agent-->debug; + http-proxy-agent-->proxy-agent-negotiate; https-proxy-agent-->agent-base; https-proxy-agent-->debug; + https-proxy-agent-->proxy-agent-negotiate; iconv-lite-->safer-buffer; ignore-walk-->minimatch; init-package-json-->npm-package-arg; @@ -308,20 +292,9 @@ graph LR; init-package-json-->promzard; init-package-json-->read; init-package-json-->semver; - init-package-json-->validate-npm-package-license; init-package-json-->validate-npm-package-name; - ip-address-->jsbn; - ip-address-->sprintf-js; is-cidr-->cidr-regex; - isaacs-cliui-->string-width-cjs; - isaacs-cliui-->string-width; - isaacs-cliui-->strip-ansi-cjs; - isaacs-cliui-->strip-ansi; - isaacs-cliui-->wrap-ansi-cjs; - isaacs-cliui-->wrap-ansi; - jackspeak-->isaacs-cliui["@isaacs/cliui"]; - jackspeak-->pkgjs-parseargs["@pkgjs/parseargs"]; - libnpmaccess-->nock; + isaacs-fs-minipass-->minipass; libnpmaccess-->npm-package-arg; libnpmaccess-->npm-registry-fetch; libnpmaccess-->npmcli-eslint-config["@npmcli/eslint-config"]; @@ -342,31 +315,27 @@ graph LR; libnpmexec-->bin-links; libnpmexec-->chalk; libnpmexec-->ci-info; + libnpmexec-->gar-promise-retry["@gar/promise-retry"]; libnpmexec-->just-extend; libnpmexec-->just-safe-set; libnpmexec-->npm-package-arg; libnpmexec-->npmcli-arborist["@npmcli/arborist"]; libnpmexec-->npmcli-eslint-config["@npmcli/eslint-config"]; libnpmexec-->npmcli-mock-registry["@npmcli/mock-registry"]; + libnpmexec-->npmcli-package-json["@npmcli/package-json"]; libnpmexec-->npmcli-run-script["@npmcli/run-script"]; libnpmexec-->npmcli-template-oss["@npmcli/template-oss"]; libnpmexec-->pacote; libnpmexec-->proc-log; - libnpmexec-->read-package-json-fast; libnpmexec-->read; libnpmexec-->semver; + libnpmexec-->signal-exit; libnpmexec-->tap; libnpmexec-->walk-up-path; libnpmfund-->npmcli-arborist["@npmcli/arborist"]; libnpmfund-->npmcli-eslint-config["@npmcli/eslint-config"]; libnpmfund-->npmcli-template-oss["@npmcli/template-oss"]; libnpmfund-->tap; - libnpmhook-->aproba; - libnpmhook-->nock; - libnpmhook-->npm-registry-fetch; - libnpmhook-->npmcli-eslint-config["@npmcli/eslint-config"]; - libnpmhook-->npmcli-template-oss["@npmcli/template-oss"]; - libnpmhook-->tap; libnpmorg-->aproba; libnpmorg-->minipass; libnpmorg-->nock; @@ -384,13 +353,12 @@ graph LR; libnpmpack-->spawk; libnpmpack-->tap; libnpmpublish-->ci-info; - libnpmpublish-->nock; - libnpmpublish-->normalize-package-data; libnpmpublish-->npm-package-arg; libnpmpublish-->npm-registry-fetch; libnpmpublish-->npmcli-eslint-config["@npmcli/eslint-config"]; libnpmpublish-->npmcli-mock-globals["@npmcli/mock-globals"]; libnpmpublish-->npmcli-mock-registry["@npmcli/mock-registry"]; + libnpmpublish-->npmcli-package-json["@npmcli/package-json"]; libnpmpublish-->npmcli-template-oss["@npmcli/template-oss"]; libnpmpublish-->proc-log; libnpmpublish-->semver; @@ -418,21 +386,21 @@ graph LR; libnpmversion-->semver; libnpmversion-->tap; make-fetch-happen-->cacache; + make-fetch-happen-->gar-promise-retry["@gar/promise-retry"]; make-fetch-happen-->http-cache-semantics; - make-fetch-happen-->is-lambda; make-fetch-happen-->minipass-fetch; make-fetch-happen-->minipass-flush; make-fetch-happen-->minipass-pipeline; make-fetch-happen-->minipass; make-fetch-happen-->negotiator; make-fetch-happen-->npmcli-agent["@npmcli/agent"]; + make-fetch-happen-->npmcli-redact["@npmcli/redact"]; make-fetch-happen-->proc-log; - make-fetch-happen-->promise-retry; make-fetch-happen-->ssri; minimatch-->brace-expansion; minipass-->yallist; minipass-collect-->minipass; - minipass-fetch-->encoding; + minipass-fetch-->iconv-lite; minipass-fetch-->minipass-sized; minipass-fetch-->minipass; minipass-fetch-->minizlib; @@ -440,30 +408,26 @@ graph LR; minipass-pipeline-->minipass; minipass-sized-->minipass; minizlib-->minipass; - minizlib-->yallist; node-gyp-->env-paths; node-gyp-->exponential-backoff; - node-gyp-->glob; node-gyp-->graceful-fs; - node-gyp-->make-fetch-happen; node-gyp-->nopt; node-gyp-->proc-log; node-gyp-->semver; node-gyp-->tar; + node-gyp-->tinyglobby; + node-gyp-->undici; node-gyp-->which; nopt-->abbrev; - normalize-package-data-->hosted-git-info; - normalize-package-data-->semver; - normalize-package-data-->validate-npm-package-license; npm-->abbrev; npm-->ajv-formats-draft2019; npm-->ajv-formats; npm-->ajv; npm-->archy; + npm-->bin-links; npm-->cacache; npm-->chalk; npm-->ci-info; - npm-->cli-columns; npm-->cli-table3; npm-->diff; npm-->fastest-levenshtein; @@ -480,7 +444,6 @@ graph LR; npm-->libnpmdiff; npm-->libnpmexec; npm-->libnpmfund; - npm-->libnpmhook; npm-->libnpmorg; npm-->libnpmpack; npm-->libnpmpublish; @@ -495,7 +458,6 @@ graph LR; npm-->nock; npm-->node-gyp; npm-->nopt; - npm-->normalize-package-data; npm-->npm-audit-report; npm-->npm-install-checks; npm-->npm-package-arg; @@ -510,9 +472,13 @@ graph LR; npm-->npmcli-eslint-config["@npmcli/eslint-config"]; npm-->npmcli-fs["@npmcli/fs"]; npm-->npmcli-git["@npmcli/git"]; + npm-->npmcli-installed-package-contents["@npmcli/installed-package-contents"]; npm-->npmcli-map-workspaces["@npmcli/map-workspaces"]; + npm-->npmcli-metavuln-calculator["@npmcli/metavuln-calculator"]; npm-->npmcli-mock-globals["@npmcli/mock-globals"]; npm-->npmcli-mock-registry["@npmcli/mock-registry"]; + npm-->npmcli-name-from-folder["@npmcli/name-from-folder"]; + npm-->npmcli-node-gyp["@npmcli/node-gyp"]; npm-->npmcli-package-json["@npmcli/package-json"]; npm-->npmcli-promise-spawn["@npmcli/promise-spawn"]; npm-->npmcli-redact["@npmcli/redact"]; @@ -543,14 +509,15 @@ graph LR; npm-->tufjs-repo-mock["@tufjs/repo-mock"]; npm-->validate-npm-package-name; npm-->which; - npm-->write-file-atomic; npm-bundled-->npm-normalize-package-bin; npm-install-checks-->semver; npm-package-arg-->hosted-git-info; npm-package-arg-->proc-log; npm-package-arg-->semver; npm-package-arg-->validate-npm-package-name; + npm-packlist-->glob; npm-packlist-->ignore-walk; + npm-packlist-->proc-log; npm-pick-manifest-->npm-install-checks; npm-pick-manifest-->npm-normalize-package-bin; npm-pick-manifest-->npm-package-arg; @@ -574,9 +541,10 @@ graph LR; npmcli-arborist-->bin-links; npmcli-arborist-->cacache; npmcli-arborist-->common-ancestor-path; + npmcli-arborist-->diff; + npmcli-arborist-->gar-promise-retry["@gar/promise-retry"]; npmcli-arborist-->hosted-git-info; npmcli-arborist-->isaacs-string-locale-compare["@isaacs/string-locale-compare"]; - npmcli-arborist-->json-parse-even-better-errors; npmcli-arborist-->json-stringify-nice; npmcli-arborist-->lru-cache; npmcli-arborist-->minify-registry-metadata; @@ -592,6 +560,7 @@ graph LR; npmcli-arborist-->npmcli-installed-package-contents["@npmcli/installed-package-contents"]; npmcli-arborist-->npmcli-map-workspaces["@npmcli/map-workspaces"]; npmcli-arborist-->npmcli-metavuln-calculator["@npmcli/metavuln-calculator"]; + npmcli-arborist-->npmcli-mock-registry["@npmcli/mock-registry"]; npmcli-arborist-->npmcli-name-from-folder["@npmcli/name-from-folder"]; npmcli-arborist-->npmcli-node-gyp["@npmcli/node-gyp"]; npmcli-arborist-->npmcli-package-json["@npmcli/package-json"]; @@ -605,13 +574,13 @@ graph LR; npmcli-arborist-->proggy; npmcli-arborist-->promise-all-reject-late; npmcli-arborist-->promise-call-limit; - npmcli-arborist-->read-package-json-fast; npmcli-arborist-->semver; npmcli-arborist-->ssri; npmcli-arborist-->tap; npmcli-arborist-->tar-stream; npmcli-arborist-->tcompare; npmcli-arborist-->treeverse; + npmcli-arborist-->validate-npm-package-name; npmcli-arborist-->walk-up-path; npmcli-config-->ci-info; npmcli-config-->ini; @@ -641,13 +610,12 @@ graph LR; npmcli-docs-->unified; npmcli-docs-->yaml; npmcli-fs-->semver; + npmcli-git-->gar-promise-retry["@gar/promise-retry"]; npmcli-git-->ini; npmcli-git-->lru-cache; npmcli-git-->npm-pick-manifest; npmcli-git-->npmcli-promise-spawn["@npmcli/promise-spawn"]; npmcli-git-->proc-log; - npmcli-git-->promise-inflight; - npmcli-git-->promise-retry; npmcli-git-->semver; npmcli-git-->which; npmcli-installed-package-contents-->npm-bundled; @@ -655,7 +623,7 @@ graph LR; npmcli-map-workspaces-->glob; npmcli-map-workspaces-->minimatch; npmcli-map-workspaces-->npmcli-name-from-folder["@npmcli/name-from-folder"]; - npmcli-map-workspaces-->read-package-json-fast; + npmcli-map-workspaces-->npmcli-package-json["@npmcli/package-json"]; npmcli-metavuln-calculator-->cacache; npmcli-metavuln-calculator-->json-parse-even-better-errors; npmcli-metavuln-calculator-->pacote; @@ -675,10 +643,10 @@ graph LR; npmcli-package-json-->glob; npmcli-package-json-->hosted-git-info; npmcli-package-json-->json-parse-even-better-errors; - npmcli-package-json-->normalize-package-data; npmcli-package-json-->npmcli-git["@npmcli/git"]; npmcli-package-json-->proc-log; npmcli-package-json-->semver; + npmcli-package-json-->spdx-expression-parse; npmcli-promise-spawn-->which; npmcli-query-->postcss-selector-parser; npmcli-run-script-->node-gyp; @@ -686,18 +654,17 @@ graph LR; npmcli-run-script-->npmcli-package-json["@npmcli/package-json"]; npmcli-run-script-->npmcli-promise-spawn["@npmcli/promise-spawn"]; npmcli-run-script-->proc-log; - npmcli-run-script-->which; npmcli-smoke-tests-->npmcli-eslint-config["@npmcli/eslint-config"]; npmcli-smoke-tests-->npmcli-mock-registry["@npmcli/mock-registry"]; npmcli-smoke-tests-->npmcli-promise-spawn["@npmcli/promise-spawn"]; npmcli-smoke-tests-->npmcli-template-oss["@npmcli/template-oss"]; npmcli-smoke-tests-->proxy; - npmcli-smoke-tests-->semver; + npmcli-smoke-tests-->rimraf; npmcli-smoke-tests-->tap; npmcli-smoke-tests-->which; - p-map-->aggregate-error; pacote-->cacache; pacote-->fs-minipass; + pacote-->gar-promise-retry["@gar/promise-retry"]; pacote-->minipass; pacote-->npm-package-arg; pacote-->npm-packlist; @@ -709,7 +676,6 @@ graph LR; pacote-->npmcli-promise-spawn["@npmcli/promise-spawn"]; pacote-->npmcli-run-script["@npmcli/run-script"]; pacote-->proc-log; - pacote-->promise-retry; pacote-->sigstore; pacote-->ssri; pacote-->tar; @@ -720,13 +686,9 @@ graph LR; path-scurry-->minipass; postcss-selector-parser-->cssesc; postcss-selector-parser-->util-deprecate; - promise-retry-->err-code; - promise-retry-->retry; promzard-->read; + proxy-agent-negotiate-->kerberos; read-->mute-stream; - read-package-json-fast-->json-parse-even-better-errors; - read-package-json-fast-->npm-normalize-package-bin; - shebang-command-->shebang-regex; sigstore-->sigstore-bundle["@sigstore/bundle"]; sigstore-->sigstore-core["@sigstore/core"]; sigstore-->sigstore-protobuf-specs["@sigstore/protobuf-specs"]; @@ -734,9 +696,9 @@ graph LR; sigstore-->sigstore-tuf["@sigstore/tuf"]; sigstore-->sigstore-verify["@sigstore/verify"]; sigstore-bundle-->sigstore-protobuf-specs["@sigstore/protobuf-specs"]; + sigstore-sign-->gar-promise-retry["@gar/promise-retry"]; sigstore-sign-->make-fetch-happen; sigstore-sign-->proc-log; - sigstore-sign-->promise-retry; sigstore-sign-->sigstore-bundle["@sigstore/bundle"]; sigstore-sign-->sigstore-core["@sigstore/core"]; sigstore-sign-->sigstore-protobuf-specs["@sigstore/protobuf-specs"]; @@ -750,36 +712,22 @@ graph LR; socks-proxy-agent-->agent-base; socks-proxy-agent-->debug; socks-proxy-agent-->socks; - spdx-correct-->spdx-expression-parse; - spdx-correct-->spdx-license-ids; spdx-expression-parse-->spdx-exceptions; spdx-expression-parse-->spdx-license-ids; ssri-->minipass; - string-width-->eastasianwidth; - string-width-->emoji-regex; - string-width-->is-fullwidth-code-point; - string-width-->strip-ansi; - strip-ansi-->ansi-regex; tar-->chownr; - tar-->fs-minipass; + tar-->isaacs-fs-minipass["@isaacs/fs-minipass"]; tar-->minipass; tar-->minizlib; - tar-->mkdirp; tar-->yallist; + tinyglobby-->fdir; + tinyglobby-->picomatch; tuf-js-->debug; - tuf-js-->make-fetch-happen; + tuf-js-->gar-promise-retry["@gar/promise-retry"]; tuf-js-->tufjs-models["@tufjs/models"]; tufjs-models-->minimatch; tufjs-models-->tufjs-canonical-json["@tufjs/canonical-json"]; - unique-filename-->unique-slug; - unique-slug-->imurmurhash; - validate-npm-package-license-->spdx-correct; - validate-npm-package-license-->spdx-expression-parse; which-->isexe; - wrap-ansi-->ansi-styles; - wrap-ansi-->string-width; - wrap-ansi-->strip-ansi; - write-file-atomic-->imurmurhash; write-file-atomic-->signal-exit; ``` @@ -790,14 +738,13 @@ Each group depends on packages lower down the chain, nothing depends on packages higher up the chain. - npm - - @npmcli/smoke-tests, libnpmaccess, libnpmexec, libnpmpublish - - @npmcli/mock-registry, libnpmdiff, libnpmfund, libnpmpack + - @npmcli/mock-registry, libnpmdiff, libnpmexec, libnpmfund, libnpmpack - @npmcli/arborist - @npmcli/metavuln-calculator - - pacote, libnpmversion - - @npmcli/run-script, @npmcli/config, libnpmhook, libnpmorg, libnpmsearch, libnpmteam, init-package-json, npm-profile + - pacote, @npmcli/config, libnpmversion + - @npmcli/run-script, @npmcli/map-workspaces, libnpmaccess, libnpmorg, libnpmpublish, libnpmsearch, libnpmteam, init-package-json, npm-profile - @npmcli/package-json, npm-registry-fetch - @npmcli/git, make-fetch-happen - - @npmcli/installed-package-contents, @npmcli/map-workspaces, cacache, npm-pick-manifest, promzard - - @npmcli/docs, @npmcli/fs, npm-bundled, read-package-json-fast, unique-filename, npm-install-checks, npm-package-arg, normalize-package-data, npm-packlist, bin-links, nopt, parse-conflict-json, @npmcli/mock-globals, read - - @npmcli/eslint-config, @npmcli/template-oss, ignore-walk, semver, npm-normalize-package-bin, @npmcli/name-from-folder, json-parse-even-better-errors, fs-minipass, ssri, unique-slug, @npmcli/promise-spawn, ini, hosted-git-info, proc-log, validate-npm-package-name, @npmcli/node-gyp, @npmcli/redact, @npmcli/agent, minipass-fetch, @npmcli/query, cmd-shim, read-cmd-shim, write-file-atomic, abbrev, proggy, minify-registry-metadata, mute-stream, npm-audit-report, npm-user-validate + - @npmcli/smoke-tests, npm-pick-manifest, @npmcli/installed-package-contents, cacache, promzard + - @npmcli/docs, npm-package-arg, @npmcli/promise-spawn, npm-install-checks, npm-bundled, @npmcli/fs, npm-packlist, @npmcli/mock-globals, bin-links, nopt, parse-conflict-json, read + - @npmcli/eslint-config, @npmcli/template-oss, ignore-walk, semver, hosted-git-info, proc-log, validate-npm-package-name, which, ini, npm-normalize-package-bin, json-parse-even-better-errors, @npmcli/node-gyp, ssri, @npmcli/redact, @npmcli/agent, minipass-fetch, @npmcli/name-from-folder, @npmcli/query, cmd-shim, read-cmd-shim, write-file-atomic, abbrev, proggy, minify-registry-metadata, mute-stream, npm-audit-report, npm-user-validate diff --git a/README.md b/README.md index 3dc35a3842554..4d79b192e1f47 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,8 @@ # npm - a JavaScript package manager -[![npm version](https://img.shields.io/npm/v/npm.svg)](https://npm.im/npm) -[![license](https://img.shields.io/npm/l/npm.svg)](https://npm.im/npm) -[![CI - cli](https://github.com/npm/cli/actions/workflows/ci.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci.yml) -[![Benchmark Suite](https://github.com/npm/cli/actions/workflows/benchmark.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/benchmark.yml) - ### Requirements -One of the following versions of [Node.js](https://nodejs.org/en/download/) must be installed to run **`npm`**: - -* `18.x.x` >= `18.17.0` -* `20.5.0` or higher +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 @@ -39,18 +31,16 @@ npm * [**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) +* [**Support**](https://www.npmjs.com/support) - Experiencing problems with the **npm** [website](https://npmjs.com) or [registry](https://registry.npmjs.org)? [File a ticket](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) +* You can configure `npm` to use any other compatible registry you prefer. You can read more about [configuring third-party registries](https://docs.npmjs.com/cli/v7/using-npm/registry) ### FAQ on Branding @@ -60,4 +50,4 @@ npm #### 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". +Contrary to popular belief, **`npm`** **is not** an acronym for "Node Package Manager." It is a recursive backronymic abbreviation for **"npm is not an acronym"** (if the project were 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 ever considered an acronym, it would be as "node pm" or, potentially, "new pm". diff --git a/SECURITY.md b/SECURITY.md index 9cd2deaf4fd34..4fe06a2a32c77 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,7 +2,7 @@ GitHub takes the security of our software products and services seriously, including the open source code repositories managed through our GitHub organizations, such as [GitHub](https://github.com/GitHub). -If you believe you have found a security vulnerability in this GitHub-owned open source repository, you can report it to us in one of two ways. +If you believe you have found a security vulnerability in this GitHub-owned open source repository, you can report it to us in one of two ways. If the vulnerability you have found is *not* [in scope for the GitHub Bug Bounty Program](https://bounty.github.com/#scope) or if you do not wish to be considered for a bounty reward, please report the issue to us directly through [opensource-security@github.com](mailto:opensource-security@github.com). diff --git a/bin/npm.ps1 b/bin/npm.ps1 index 04a1fd478ef9d..efed03fe5655e 100644 --- a/bin/npm.ps1 +++ b/bin/npm.ps1 @@ -1,5 +1,7 @@ #!/usr/bin/env pwsh +Set-StrictMode -Version 'Latest' + $NODE_EXE="$PSScriptRoot/node.exe" if (-not (Test-Path $NODE_EXE)) { $NODE_EXE="$PSScriptRoot/node" @@ -22,11 +24,27 @@ if (Test-Path $NPM_PREFIX_NPM_CLI_JS) { $NPM_CLI_JS=$NPM_PREFIX_NPM_CLI_JS } -# Support pipeline input -if ($MyInvocation.ExpectingInput) { +if ($MyInvocation.ExpectingInput) { # takes pipeline input $input | & $NODE_EXE $NPM_CLI_JS $args -} else { +} elseif (-not $MyInvocation.Line) { # used "-File" argument & $NODE_EXE $NPM_CLI_JS $args +} else { # used "-Command" argument + if (($MyInvocation | Get-Member -Name 'Statement') -and $MyInvocation.Statement) { + $NPM_ORIGINAL_COMMAND = $MyInvocation.Statement + } else { + $NPM_ORIGINAL_COMMAND = ( + [Management.Automation.InvocationInfo].GetProperty('ScriptPosition', [Reflection.BindingFlags] 'Instance, NonPublic') + ).GetValue($MyInvocation).Text + } + + $NODE_EXE = $NODE_EXE.Replace("``", "````") + $NPM_CLI_JS = $NPM_CLI_JS.Replace("``", "````") + + $NPM_COMMAND_ARRAY = [Management.Automation.Language.Parser]::ParseInput($NPM_ORIGINAL_COMMAND, [ref] $null, [ref] $null). + EndBlock.Statements.PipelineElements.CommandElements.Extent.Text + $NPM_ARGS = ($NPM_COMMAND_ARRAY | Select-Object -Skip 1) -join ' ' + + Invoke-Expression "& `"$NODE_EXE`" `"$NPM_CLI_JS`" $NPM_ARGS" } exit $LASTEXITCODE diff --git a/bin/npx.ps1 b/bin/npx.ps1 index 28dae51b22ca9..3fe7b5435763a 100644 --- a/bin/npx.ps1 +++ b/bin/npx.ps1 @@ -1,5 +1,7 @@ #!/usr/bin/env pwsh +Set-StrictMode -Version 'Latest' + $NODE_EXE="$PSScriptRoot/node.exe" if (-not (Test-Path $NODE_EXE)) { $NODE_EXE="$PSScriptRoot/node" @@ -22,11 +24,27 @@ if (Test-Path $NPM_PREFIX_NPX_CLI_JS) { $NPX_CLI_JS=$NPM_PREFIX_NPX_CLI_JS } -# Support pipeline input -if ($MyInvocation.ExpectingInput) { +if ($MyInvocation.ExpectingInput) { # takes pipeline input $input | & $NODE_EXE $NPX_CLI_JS $args -} else { +} elseif (-not $MyInvocation.Line) { # used "-File" argument & $NODE_EXE $NPX_CLI_JS $args +} else { # used "-Command" argument + if (($MyInvocation | Get-Member -Name 'Statement') -and $MyInvocation.Statement) { + $NPX_ORIGINAL_COMMAND = $MyInvocation.Statement + } else { + $NPX_ORIGINAL_COMMAND = ( + [Management.Automation.InvocationInfo].GetProperty('ScriptPosition', [Reflection.BindingFlags] 'Instance, NonPublic') + ).GetValue($MyInvocation).Text + } + + $NODE_EXE = $NODE_EXE.Replace("``", "````") + $NPX_CLI_JS = $NPX_CLI_JS.Replace("``", "````") + + $NPX_COMMAND_ARRAY = [Management.Automation.Language.Parser]::ParseInput($NPX_ORIGINAL_COMMAND, [ref] $null, [ref] $null). + EndBlock.Statements.PipelineElements.CommandElements.Extent.Text + $NPX_ARGS = ($NPX_COMMAND_ARRAY | Select-Object -Skip 1) -join ' ' + + Invoke-Expression "& `"$NODE_EXE`" `"$NPX_CLI_JS`" $NPX_ARGS" } exit $LASTEXITCODE diff --git a/docs/.gitignore b/docs/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/docs/.gitignore +++ b/docs/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/docs/lib/build.js b/docs/lib/build.js index cf047f3000938..40a0aaf255f6c 100644 --- a/docs/lib/build.js +++ b/docs/lib/build.js @@ -7,6 +7,281 @@ const parseFrontMatter = require('front-matter') const checkNav = require('./check-nav.js') const { DOC_EXT, ...transform } = require('./index.js') +// Helper to check if a directory exists +const dirExists = async (path) => { + try { + const stat = await fs.stat(path) + return stat.isDirectory() + } catch { + return false + } +} + +// Helper to read docs from a section directory +const readSectionDocs = async (contentPath, section, orderedUrls) => { + const sectionPath = join(contentPath, section) + if (!await dirExists(sectionPath)) { + return [] + } + + const files = await fs.readdir(sectionPath) + const docFiles = files.filter(f => f.endsWith(DOC_EXT)) + + // If no doc files exist, return empty array + /* istanbul ignore if - defensive check for empty directories */ + if (docFiles.length === 0) { + return [] + } + + // Parse each doc file to get title and description from frontmatter + const docs = await Promise.all( + docFiles.map(async (file) => { + const content = await fs.readFile(join(sectionPath, file), 'utf-8') + const { attributes } = parseFrontMatter(content) + const name = basename(file, DOC_EXT) + + return { + title: attributes.title, + url: `/${section}/${name}`, + description: attributes.description, + name, + } + }) + ) + + // Preserve order from orderedUrls, append any new files at the end sorted alphabetically + const orderedDocs = [] + const docsByUrl = new Map(docs.map(d => [d.url, d])) + + // First, add docs in the order they appear in orderedUrls + for (const url of orderedUrls) { + const doc = docsByUrl.get(url) + if (doc) { + orderedDocs.push(doc) + docsByUrl.delete(url) + } + } + + return orderedDocs.map(({ name, ...rest }) => rest) +} + +// Generate nav.yml from the filesystem +const generateNav = async (contentPath, navPath) => { + const docsCommandsPath = join(contentPath, 'commands') + + // Read all command files + const commandFiles = await dirExists(docsCommandsPath) ? await fs.readdir(docsCommandsPath) : [] + const commandDocs = commandFiles.filter(f => f.endsWith(DOC_EXT)) + + // Parse each command file to get title and description + const allCommands = await Promise.all( + commandDocs.map(async (file) => { + const content = await fs.readFile(join(docsCommandsPath, file), 'utf-8') + const { attributes } = parseFrontMatter(content) + const name = basename(file, DOC_EXT) + const title = (attributes.title || name).replace(/^npm-/, 'npm ') + + return { + title, + url: `/commands/${name}`, + description: attributes.description || '', + name, + } + }) + ) + + // Sort commands: npm first, then alphabetically, npx last + const npm = allCommands.find(c => c.name === 'npm') + const npx = allCommands.find(c => c.name === 'npx') + const others = allCommands + .filter(c => c.name !== 'npm' && c.name !== 'npx') + .sort((a, b) => a.name.localeCompare(b.name)) + + // Remove the name field + const commands = [npm, ...others, npx].filter(Boolean).map(({ name, ...rest }) => rest) + + // Hardcoded order for configuring-npm section (only urls - title/description come from frontmatter) + const configuringNpmOrder = [ + '/configuring-npm/install', + '/configuring-npm/folders', + '/configuring-npm/npmrc', + '/configuring-npm/package-json', + '/configuring-npm/package-lock-json', + '/configuring-npm/npm-extension', + ] + + // Hardcoded order for using-npm section (only urls - title/description come from frontmatter) + const usingNpmOrder = [ + '/using-npm/registry', + '/using-npm/package-spec', + '/using-npm/config', + '/using-npm/logging', + '/using-npm/scope', + '/using-npm/scripts', + '/using-npm/workspaces', + '/using-npm/orgs', + '/using-npm/dependency-selectors', + '/using-npm/developers', + '/using-npm/removal', + ] + + // Read actual docs from configuring-npm and using-npm directories + const configuringNpmDocs = await readSectionDocs(contentPath, 'configuring-npm', configuringNpmOrder) + const usingNpmDocs = await readSectionDocs(contentPath, 'using-npm', usingNpmOrder) + + // Build the navigation structure - only include sections with content + const navData = [] + + if (commands.length > 0) { + navData.push({ + title: 'CLI Commands', + shortName: 'Commands', + url: '/commands', + children: commands, + }) + } + + if (configuringNpmDocs.length > 0) { + navData.push({ + title: 'Configuring npm', + shortName: 'Configuring', + url: '/configuring-npm', + children: configuringNpmDocs, + }) + } + + if (usingNpmDocs.length > 0) { + navData.push({ + title: 'Using npm', + shortName: 'Using', + url: '/using-npm', + children: usingNpmDocs, + }) + } + + const prefix = `# This is the navigation for the documentation pages; it is not used +# directly within the CLI documentation. Instead, it will be used +# for the https://docs.npmjs.com/ site. +` + await fs.writeFile(navPath, `${prefix}\n${yaml.stringify(navData, { indent: 2, indentSeq: false, lineWidth: 0 })}`, 'utf-8') +} + +// Auto-generate doc templates for commands without docs +const autoGenerateMissingDocs = async (contentPath, navPath, commandsPath = null) => { + commandsPath = commandsPath || join(__dirname, '../../lib/commands') + const docsCommandsPath = join(contentPath, 'commands') + + // Get all commands from commandsPath directory + let commands + try { + const cmdListPath = join(commandsPath, '..', 'utils', 'cmd-list.js') + const cmdList = require(cmdListPath) + commands = cmdList.commands + } catch { + // Fall back to reading command files from commandsPath + const cmdFiles = await fs.readdir(commandsPath) + commands = cmdFiles + .filter(f => f.endsWith('.js')) + .map(f => basename(f, '.js')) + } + + // Get existing doc files + const existingDocs = await fs.readdir(docsCommandsPath) + const documentedCommands = existingDocs + .filter(f => f.startsWith('npm-') && f.endsWith(DOC_EXT)) + .map(f => f.replace('npm-', '').replace(DOC_EXT, '')) + + // Find commands without docs + const missingDocs = commands.filter(cmd => !documentedCommands.includes(cmd)) + + // Generate docs for missing commands + const newEntries = [] + for (const cmd of missingDocs) { + const Command = require(join(commandsPath, `${cmd}.js`)) + const description = Command.description || `The ${cmd} command` + const docPath = join(docsCommandsPath, `npm-${cmd}${DOC_EXT}`) + + const template = `--- +title: npm-${cmd} +section: 1 +description: ${description} +--- + +### Synopsis + + + +### Description + +${description} + +### Configuration + + + +### See Also + +* [npm help config](/commands/npm-config) +` + + await fs.writeFile(docPath, template, 'utf-8') + + // Track new entry for nav update + newEntries.push({ + title: `npm ${cmd}`, + url: `/commands/npm-${cmd}`, + description, + }) + } + + // Update nav.yml if there are new entries + if (newEntries.length > 0) { + const navContent = await fs.readFile(navPath, 'utf-8') + const navData = yaml.parse(navContent) + + // Find CLI Commands section + let commandsSection = navData.find(s => s.title === 'CLI Commands') + if (!commandsSection) { + // Create CLI Commands section if it doesn't exist + commandsSection = { + title: 'CLI Commands', + shortName: 'Commands', + url: '/commands', + children: [], + } + navData.unshift(commandsSection) + } + + if (!commandsSection.children) { + commandsSection.children = [] + } + + // Add new entries that don't already exist + for (const entry of newEntries) { + const exists = commandsSection.children.some(c => c.url === entry.url) + if (!exists) { + commandsSection.children.push(entry) + } + } + + // Sort children: npm first, then alphabetically, npx last + const npm = commandsSection.children.find(c => c.title === 'npm') + const npx = commandsSection.children.find(c => c.title === 'npx') + const others = commandsSection.children + .filter(c => c.title !== 'npm' && c.title !== 'npx') + .sort((a, b) => a.title.localeCompare(b.title)) + + commandsSection.children = [npm, ...others, npx].filter(Boolean) + + // Write updated nav + const prefix = `# This is the navigation for the documentation pages; it is not used +# directly within the CLI documentation. Instead, it will be used +# for the https://docs.npmjs.com/ site. +` + await fs.writeFile(navPath, `${prefix}\n${yaml.stringify(navData, { indent: 2, indentSeq: false, lineWidth: 0 })}`, 'utf-8') + } +} + const mkDirs = async (paths) => { const uniqDirs = [...new Set(paths.map((p) => dirname(p)))] return Promise.all(uniqDirs.map((d) => fs.mkdir(d, { recursive: true }))) @@ -28,7 +303,21 @@ const pAll = async (obj) => { }, {}) } -const run = async ({ content, template, nav, man, html, md }) => { +const run = async (opts) => { + const { + content, template, nav, man, html, md, + skipAutoGenerate, skipGenerateNav, commandLoader, + } = opts + // Auto-generate docs for commands without documentation + if (!skipAutoGenerate) { + await autoGenerateMissingDocs(content, nav) + } + + // Generate nav.yml from filesystem + if (!skipGenerateNav) { + await generateNav(content, nav) + } + await rmAll(man, html, md) const [contentPaths, navFile, options] = await Promise.all([ readDocs(content), @@ -73,11 +362,12 @@ const run = async ({ content, template, nav, man, html, md }) => { }) => { const applyTransforms = makeTransforms({ path: childPath, + commandLoader, data: { ...data, github_repo: 'npm/cli', github_branch: 'latest', - github_path: 'docs/content', + github_path: 'docs/lib/content', }, frontmatter, ...options, @@ -86,7 +376,7 @@ const run = async ({ content, template, nav, man, html, md }) => { const transformedSrc = applyTransforms(body, [ transform.version, ...(fullName.startsWith('commands/') - ? [transform.usage, transform.params] + ? [transform.usage, transform.definitions] : []), ...(fullName === 'using-npm/config' ? [transform.shorthands, transform.config] @@ -145,3 +435,5 @@ const run = async ({ content, template, nav, man, html, md }) => { } module.exports = run +module.exports.generateNav = generateNav +module.exports.autoGenerateMissingDocs = autoGenerateMissingDocs diff --git a/docs/lib/check-nav.js b/docs/lib/check-nav.js index ac2c01038f438..0f9b3529c7546 100644 --- a/docs/lib/check-nav.js +++ b/docs/lib/check-nav.js @@ -29,17 +29,17 @@ function ensureNavigationComplete (nav, fsPaths, ext) { const errors = [] if (missingNav.length) { - errors.push('The following path(s) exist on disk but are not present in nav.yml:') + errors.push('The following path(s) exist on disk but are not present in /lib/content/nav.yml:') errors.push(...missingNav.map(n => ` ${n}`)) } if (missingFs.length) { - errors.push('The following path(s) exist in nav.yml but are not present on disk:') + errors.push('The following path(s) exist in lib/content/nav.yml but are not present on disk:') errors.push(...missingFs.map(n => ` ${n}`)) } if (errors.length) { - errors.unshift('Documentation navigation (nav.yml) does not match filesystem.') + errors.unshift('Documentation navigation (lib/content/nav.yml) does not match filesystem.') errors.push('Update nav.yml to ensure that all files are listed in the appropriate place.') throw new Error(errors.join('\n')) } diff --git a/docs/lib/content/commands/npm-access.md b/docs/lib/content/commands/npm-access.md index 312546f05c88e..6b846e9158f6f 100644 --- a/docs/lib/content/commands/npm-access.md +++ b/docs/lib/content/commands/npm-access.md @@ -12,56 +12,28 @@ description: Set access level on published packages Used to set access controls on private packages. -For all of the subcommands, `npm access` will perform actions on the packages -in the current working directory if no package name is passed to the -subcommand. +For all of the subcommands, `npm access` will perform actions on the packages in the current working directory if no package name is passed to the subcommand. -* public / restricted (deprecated): - Set a package to be either publicly accessible or restricted. - -* grant / revoke (deprecated): - Add or remove the ability of users and teams to have read-only or read-write - access to a package. - -* 2fa-required / 2fa-not-required (deprecated): - Configure whether a package requires that anyone publishing it have two-factor - authentication enabled on their account. - -* ls-packages (deprecated): - Show all of the packages a user or a team is able to access, along with the - access level, except for read-only public packages (it won't print the whole - registry listing) - -* ls-collaborators (deprecated): - Show all of the access privileges for a package. Will only show permissions - for packages to which you have at least read access. If `` is passed in, - the list is filtered only to teams _that_ user happens to belong to. - -* edit (not implemented) +* grant / revoke: + Add or remove the ability of users and teams to have read-only or read-write access to a package. ### Details -`npm access` always operates directly on the current registry, configurable -from the command line using `--registry=`. +`npm access` always operates directly on the current registry, configurable from the command line using `--registry=`. Unscoped packages are *always public*. -Scoped packages *default to restricted*, but you can either publish them as -public using `npm publish --access=public`, or set their access as public using -`npm access public` after the initial publish. +Scoped packages *default to restricted*, but you can either publish them as public using `npm publish --access=public`, or set their access as public using `npm access set status=public` after the initial publish. You must have privileges to set the access of a package: * You are an owner of an unscoped or scoped package. * You are a member of the team that owns a scope. -* You have been given read-write privileges for a package, either as a member - of a team or directly as an owner. +* You have been given read-write privileges for a package, either as a member of a team or directly as an owner. -If you have two-factor authentication enabled then you'll be prompted to provide a second factor, or may use the `--otp=...` option to specify it on -the command line. +If you have two-factor authentication enabled then you'll be prompted to provide a second factor, or may use the `--otp=...` option to specify it on the command line. -If your account is not paid, then attempts to publish scoped packages will -fail with an HTTP 402 status code (logically enough), unless you use +If your account is not paid, then attempts to publish scoped packages will fail with an HTTP 402 status code (logically enough), unless you use `--access=public`. Management of teams and team memberships is done with the `npm team` command. diff --git a/docs/lib/content/commands/npm-adduser.md b/docs/lib/content/commands/npm-adduser.md deleted file mode 100644 index 061c020ecb28b..0000000000000 --- a/docs/lib/content/commands/npm-adduser.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: npm-adduser -section: 1 -description: Add a registry user account ---- - -### Synopsis - - - -### Description - -Create a new user in the specified registry, and save the credentials to -the `.npmrc` file. If no registry is specified, the default registry -will be used (see [`registry`](/using-npm/registry)). - -When using `legacy` for your `auth-type`, the username, password, and -email are read in from prompts. - -### Configuration - - - -### See Also - -* [npm registry](/using-npm/registry) -* [npm config](/commands/npm-config) -* [npmrc](/configuring-npm/npmrc) -* [npm owner](/commands/npm-owner) -* [npm whoami](/commands/npm-whoami) -* [npm token](/commands/npm-token) -* [npm profile](/commands/npm-profile) diff --git a/docs/lib/content/commands/npm-approve-scripts.md b/docs/lib/content/commands/npm-approve-scripts.md new file mode 100644 index 0000000000000..11a71f23bdc61 --- /dev/null +++ b/docs/lib/content/commands/npm-approve-scripts.md @@ -0,0 +1,82 @@ +--- +title: npm-approve-scripts +section: 1 +description: Approve install scripts for specific dependencies +--- + +### Synopsis + + + +### Description + +Manages the `allowScripts` field in your project's `package.json`, which +records which of your dependencies are permitted to run install scripts +(`preinstall`, `install`, `postinstall`, and `prepare` for non-registry +sources). This command is the recommended way to maintain that field. + +Dependency install scripts are blocked by default. Install commands +silently skip lifecycle scripts for any dependency that does not have a +matching entry in `allowScripts`, and end with a list of the packages +whose scripts were skipped so you can review them with this command. + +This command only works inside a project that has a `package.json`. Running +it with `--global` (`-g`) fails with an `EGLOBAL` error, since global +installs (`npm install -g`) and one-off executions (`npm exec` / `npx`) have +no project `package.json` to write to. To allow install scripts in those +contexts, use the `--allow-scripts` flag at install time (for example +`npm install -g --allow-scripts=canvas,sharp`) or persist the setting with +`npm config set allow-scripts=canvas,sharp --location=user`. + +There are three modes: + +```bash +npm approve-scripts [ ...] +npm approve-scripts --all +npm approve-scripts --allow-scripts-pending +``` + +`` matches every installed version of that package. By default the +command writes pinned entries (`pkg@1.2.3`), which keep their approval +narrowed to the specific version you reviewed. Pass `--no-allow-scripts-pin` to write +name-only entries that allow any future version. + +`--all` approves every package with unreviewed install scripts in one go. + +`--allow-scripts-pending` is read-only: it lists every package whose install scripts +are not yet covered by `allowScripts`, without modifying `package.json`. + +`approve-scripts` honours the asymmetric pin rule: if you re-approve a +package whose installed version has changed, the existing pin is rewritten +to track the new installed version. Multi-version statements +(`pkg@1 || 2`) are left alone, since they likely capture intent that +the command cannot infer. Existing `false` entries always win; +`approve-scripts` will not silently re-allow a package you previously +denied. + +### Examples + +```bash +# Approve all currently-installed install scripts after reviewing them +npm approve-scripts --all + +# Approve specific packages, pinned to their installed version +npm approve-scripts canvas sharp + +# Approve name-only (any version of this package is allowed) +npm approve-scripts --no-allow-scripts-pin canvas + +# Preview which packages still need review +npm approve-scripts --allow-scripts-pending +``` + +### Configuration + + + +### See Also + +* [npm deny-scripts](/commands/npm-deny-scripts) +* [npm install](/commands/npm-install) +* [npm rebuild](/commands/npm-rebuild) +* [package.json](/configuring-npm/package-json) diff --git a/docs/lib/content/commands/npm-audit.md b/docs/lib/content/commands/npm-audit.md index 3e5bc978b26e4..737caea05537f 100644 --- a/docs/lib/content/commands/npm-audit.md +++ b/docs/lib/content/commands/npm-audit.md @@ -10,32 +10,23 @@ description: Run a security audit ### Description -The audit command submits a description of the dependencies configured in -your project to your default registry and asks for a report of known -vulnerabilities. If any vulnerabilities are found, then the impact and -appropriate remediation will be calculated. If the `fix` argument is -provided, then remediations will be applied to the package tree. +The audit command submits a description of the dependencies configured in your project to your default registry and asks for a report of known vulnerabilities. +If any vulnerabilities are found, then the impact and appropriate remediation will be calculated. +If the `fix` argument is provided, then remediations will be applied to the package tree. The command will exit with a 0 exit code if no vulnerabilities were found. -Note that some vulnerabilities cannot be fixed automatically and will -require manual intervention or review. Also note that since `npm audit -fix` runs a full-fledged `npm install` under the hood, all configs that -apply to the installer will also apply to `npm install` -- so things like -`npm audit fix --package-lock-only` will work as expected. +Note that some vulnerabilities cannot be fixed automatically and will require manual intervention or review. +Also note that since `npm audit fix` runs a full-fledged `npm install` under the hood, all configs that apply to the installer will also apply to `npm install` -- so things like `npm audit fix --package-lock-only` will work as expected. -By default, the audit command will exit with a non-zero code if any -vulnerability is found. It may be useful in CI environments to include the -`--audit-level` parameter to specify the minimum vulnerability level that -will cause the command to fail. This option does not filter the report -output, it simply changes the command's failure threshold. +By default, the audit command will exit with a non-zero code if any vulnerability is found. +It may be useful in CI environments to include the `--audit-level` parameter to specify the minimum vulnerability level that will cause the command to fail. +This option does not filter the report output, it simply changes the command's failure threshold. ### Package lock -By default npm requires a package-lock or shrinkwrap in order to run the -audit. You can bypass the package lock with `--no-package-lock` but be -aware the results may be different with every run, since npm will -re-build the dependency tree each time. +By default npm requires a package-lock in order to run the audit. +You can bypass the package lock with `--no-package-lock` but be aware the results may be different with every run, since npm will re-build the dependency tree each time. ### Audit Signatures @@ -47,12 +38,19 @@ Registry signatures can be verified using the following `audit` command: $ npm audit signatures ``` -The `audit signatures` command will also verify the provenance attestations of -downloaded packages. Because provenance attestations are such a new feature, -security features may be added to (or changed in) the attestation format over -time. To ensure that you're always able to verify attestation signatures check -that you're running the latest version of the npm CLI. Please note this often -means updating npm beyond the version that ships with Node.js. +The `audit signatures` command will also verify the provenance attestations of downloaded packages. +Because provenance attestations are such a new feature, security features may be added to (or changed in) the attestation format over time. +To ensure that you're always able to verify attestation signatures check that you're running the latest version of the npm CLI. Please note this often means updating npm beyond the version that ships with Node.js. + +To include the full sigstore attestation bundles in JSON output, use: + +```bash +$ npm audit signatures --json --include-attestations +``` + +This adds a `verified` array to the JSON output containing the attestation +bundles (DSSE envelopes, verification material, and transparency log entries) +for each verified package. The npm CLI supports registry signatures and signing keys provided by any registry if the following conventions are followed: @@ -89,7 +87,7 @@ The `sig` is generated using the following template: `${package.name}@${package. Keys response: - `expires`: null or a simplified extended [ISO 8601 format](https://en.wikipedia.org/wiki/ISO_8601): `YYYY-MM-DDTHH:mm:ss.sssZ` -- `keydid`: sha256 fingerprint of the public key +- `keyid`: sha256 fingerprint of the public key - `keytype`: only `ecdsa-sha2-nistp256` is currently supported by the npm CLI - `scheme`: only `ecdsa-sha2-nistp256` is currently supported by the npm CLI - `key`: base64 encoded public key @@ -98,42 +96,29 @@ See this [example key's response from the public npm registry](https://registry. ### Audit Endpoints -There are two audit endpoints that npm may use to fetch vulnerability -information: the `Bulk Advisory` endpoint and the `Quick Audit` endpoint. +There are two audit endpoints that npm may use to fetch vulnerability information: the `Bulk Advisory` endpoint and the `Quick Audit` endpoint. #### Bulk Advisory Endpoint -As of version 7, npm uses the much faster `Bulk Advisory` endpoint to -optimize the speed of calculating audit results. +As of version 7, npm uses the much faster `Bulk Advisory` endpoint to optimize the speed of calculating audit results. -npm will generate a JSON payload with the name and list of versions of each -package in the tree, and POST it to the default configured registry at -the path `/-/npm/v1/security/advisories/bulk`. +npm will generate a JSON payload with the name and list of versions of each package in the tree, and POST it to the default configured registry at the path `/-/npm/v1/security/advisories/bulk`. -Any packages in the tree that do not have a `version` field in their -package.json file will be ignored. If any `--omit` options are specified -(either via the [`--omit` config](/using-npm/config#omit), or one of the -shorthands such as `--production`, `--only=dev`, and so on), then packages will -be omitted from the submitted payload as appropriate. +Any packages in the tree that do not have a `version` field in their package.json file will be ignored. +If any `--omit` options are specified (either via the [`--omit` config](/using-npm/config#omit), or one of the shorthands such as `--production`, `--only=dev`, and so on), then packages will be omitted from the submitted payload as appropriate. -If the registry responds with an error, or with an invalid response, then -npm will attempt to load advisory data from the `Quick Audit` endpoint. +If the registry responds with an error, or with an invalid response, then npm will attempt to load advisory data from the `Quick Audit` endpoint. -The expected result will contain a set of advisory objects for each -dependency that matches the advisory range. Each advisory object contains -a `name`, `url`, `id`, `severity`, `vulnerable_versions`, and `title`. +The expected result will contain a set of advisory objects for each dependency that matches the advisory range. +Each advisory object contains a `name`, `url`, `id`, `severity`, `vulnerable_versions`, and `title`. -npm then uses these advisory objects to calculate vulnerabilities and -meta-vulnerabilities of the dependencies within the tree. +npm then uses these advisory objects to calculate vulnerabilities and meta-vulnerabilities of the dependencies within the tree. #### Quick Audit Endpoint -If the `Bulk Advisory` endpoint returns an error, or invalid data, npm will -attempt to load advisory data from the `Quick Audit` endpoint, which is -considerably slower in most cases. +If the `Bulk Advisory` endpoint returns an error, or invalid data, npm will attempt to load advisory data from the `Quick Audit` endpoint, which is considerably slower in most cases. -The full package tree as found in `package-lock.json` is submitted, along -with the following pieces of additional metadata: +The full package tree as found in `package-lock.json` is submitted, along with the following pieces of additional metadata: * `npm_version` * `node_version` @@ -146,64 +131,41 @@ Omitted dependency types are skipped when generating the report. #### Scrubbing -Out of an abundance of caution, npm versions 5 and 6 would "scrub" any -packages from the submitted report if their name contained a `/` character, -so as to avoid leaking the names of potentially private packages or git -URLs. +Out of an abundance of caution, npm versions 5 and 6 would "scrub" any packages from the submitted report if their name contained a `/` character, so as to avoid leaking the names of potentially private packages or git URLs. -However, in practice, this resulted in audits often failing to properly -detect meta-vulnerabilities, because the tree would appear to be invalid -due to missing dependencies, and prevented the detection of vulnerabilities -in package trees that used git dependencies or private modules. +However, in practice, this resulted in audits often failing to properly detect meta-vulnerabilities, because the tree would appear to be invalid due to missing dependencies, and prevented the detection of vulnerabilities in package trees that used git dependencies or private modules. This scrubbing has been removed from npm as of version 7. #### Calculating Meta-Vulnerabilities and Remediations -npm uses the -[`@npmcli/metavuln-calculator`](http://npm.im/@npmcli/metavuln-calculator) -module to turn a set of security advisories into a set of "vulnerability" -objects. A "meta-vulnerability" is a dependency that is vulnerable by -virtue of dependence on vulnerable versions of a vulnerable package. +npm uses the [`@npmcli/metavuln-calculator`](http://npm.im/@npmcli/metavuln-calculator) module to turn a set of security advisories into a set of "vulnerability" objects. +A "meta-vulnerability" is a dependency that is vulnerable by virtue of dependence on vulnerable versions of a vulnerable package. -For example, if the package `foo` is vulnerable in the range `>=1.0.2 -<2.0.0`, and the package `bar` depends on `foo@^1.1.0`, then that version -of `bar` can only be installed by installing a vulnerable version of `foo`. +For example, if the package `foo` is vulnerable in the range `>=1.0.2 <2.0.0`, and the package `bar` depends on `foo@^1.1.0`, then that version of `bar` can only be installed by installing a vulnerable version of `foo`. In this case, `bar` is a "metavulnerability". -Once metavulnerabilities for a given package are calculated, they are -cached in the `~/.npm` folder and only re-evaluated if the advisory range -changes, or a new version of the package is published (in which case, the -new version is checked for metavulnerable status as well). +Once metavulnerabilities for a given package are calculated, they are cached in the `~/.npm` folder and only re-evaluated if the advisory range changes, or a new version of the package is published (in which case, the new version is checked for metavulnerable status as well). -If the chain of metavulnerabilities extends all the way to the root -project, and it cannot be updated without changing its dependency ranges, -then `npm audit fix` will require the `--force` option to apply the -remediation. If remediations do not require changes to the dependency -ranges, then all vulnerable packages will be updated to a version that does -not have an advisory or metavulnerability posted against it. +If the chain of metavulnerabilities extends all the way to the root project, and it cannot be updated without changing its dependency ranges, then `npm audit fix` will require the `--force` option to apply the remediation. +If remediations do not require changes to the dependency ranges, then all vulnerable packages will be updated to a version that does not have an advisory or metavulnerability posted against it. ### Exit Code -The `npm audit` command will exit with a 0 exit code if no vulnerabilities -were found. The `npm audit fix` command will exit with 0 exit code if no -vulnerabilities are found _or_ if the remediation is able to successfully -fix all vulnerabilities. +The `npm audit` command will exit with a 0 exit code if no vulnerabilities were found. +The `npm audit fix` command will exit with 0 exit code if no vulnerabilities are found _or_ if the remediation is able to successfully fix all vulnerabilities. -If vulnerabilities were found the exit code will depend on the -[`audit-level` config](/using-npm/config#audit-level). +If vulnerabilities were found the exit code will depend on the [`audit-level` config](/using-npm/config#audit-level). ### Examples -Scan your project for vulnerabilities and automatically install any compatible -updates to vulnerable dependencies: +Scan your project for vulnerabilities and automatically install any compatible updates to vulnerable dependencies: ```bash $ npm audit fix ``` -Run `audit fix` without modifying `node_modules`, but still updating the -pkglock: +Run `audit fix` without modifying `node_modules`, but still updating the pkglock: ```bash $ npm audit fix --package-lock-only @@ -215,22 +177,19 @@ Skip updating `devDependencies`: $ npm audit fix --only=prod ``` -Have `audit fix` install SemVer-major updates to toplevel dependencies, not -just SemVer-compatible ones: +Have `audit fix` install SemVer-major updates to toplevel dependencies, not just SemVer-compatible ones: ```bash $ npm audit fix --force ``` -Do a dry run to get an idea of what `audit fix` will do, and _also_ output -install information in JSON format: +Do a dry run to get an idea of what `audit fix` will do, and _also_ output install information in JSON format: ```bash $ npm audit fix --dry-run --json ``` -Scan your project for vulnerabilities and just show the details, without -fixing anything: +Scan your project for vulnerabilities and just show the details, without fixing anything: ```bash $ npm audit diff --git a/docs/lib/content/commands/npm-bugs.md b/docs/lib/content/commands/npm-bugs.md index 4cf90510d7124..e68361084196d 100644 --- a/docs/lib/content/commands/npm-bugs.md +++ b/docs/lib/content/commands/npm-bugs.md @@ -10,11 +10,8 @@ description: Report bugs for a package in a web browser ### Description -This command tries to guess at the likely location of a package's bug -tracker URL or the `mailto` URL of the support email, and then tries to -open it using the [`--browser` config](/using-npm/config#browser) param. If no -package name is provided, it will search for a `package.json` in the current -folder and use the `name` property. +This command tries to guess at the likely location of a package's bug tracker URL or the `mailto` URL of the support email, and then tries to open it using the [`--browser` config](/using-npm/config#browser) param. +If no package name is provided, it will search for a `package.json` in the current folder and use the `name` property. ### Configuration diff --git a/docs/lib/content/commands/npm-cache.md b/docs/lib/content/commands/npm-cache.md index 20836b512a12f..55835d23e1c92 100644 --- a/docs/lib/content/commands/npm-cache.md +++ b/docs/lib/content/commands/npm-cache.md @@ -10,56 +10,58 @@ description: Manipulates packages cache ### Description -Used to add, list, or clean the npm cache folder. +Used to add, list, or clean the `npm cache` folder. +Also used to view info about entries in the `npm exec` (aka `npx`) cache folder. + +#### `npm cache` * add: - Add the specified packages to the local cache. This command is primarily - intended to be used internally by npm, but it can provide a way to - add data to the local installation cache explicitly. + Add the specified packages to the local cache. + This command is primarily intended to be used internally by npm, but it can provide a way to add data to the local installation cache explicitly. * clean: - Delete all data out of the cache folder. Note that this is typically - unnecessary, as npm's cache is self-healing and resistant to data - corruption issues. + Delete a single entry or all entries out of the cache folder. + Note that this is typically unnecessary, as npm's cache is self-healing and resistant to data corruption issues. + +* ls: + List given entries or all entries in the local cache. * verify: - Verify the contents of the cache folder, garbage collecting any unneeded - data, and verifying the integrity of the cache index and all cached data. + Verify the contents of the cache folder, garbage collecting any unneeded data, and verifying the integrity of the cache index and all cached data. + +#### `npm cache npx` + +* ls: + List all entries in the npx cache. + +* rm: + Remove given entries or all entries from the npx cache. + +* info: + Get detailed information about given entries in the npx cache. ### Details -npm stores cache data in an opaque directory within the configured `cache`, -named `_cacache`. This directory is a -[`cacache`](http://npm.im/cacache)-based content-addressable cache that -stores all http request data as well as other package-related data. This -directory is primarily accessed through `pacote`, the library responsible -for all package fetching as of npm@5. +npm stores cache data in an opaque directory within the configured `cache`, named `_cacache`. +This directory is a [`cacache`](http://npm.im/cacache)-based content-addressable cache that stores all http request data as well as other package-related data. +This directory is primarily accessed through `pacote`, the library responsible for all package fetching as of npm@5. -All data that passes through the cache is fully verified for integrity on -both insertion and extraction. Cache corruption will either trigger an -error, or signal to `pacote` that the data must be refetched, which it will -do automatically. For this reason, it should never be necessary to clear -the cache for any reason other than reclaiming disk space, thus why `clean` -now requires `--force` to run. +All data that passes through the cache is fully verified for integrity on both insertion and extraction. +Cache corruption will either trigger an error, or signal to `pacote` that the data must be refetched, which it will do automatically. +For this reason, it should never be necessary to clear the cache for any reason other than reclaiming disk space, thus why `clean` now requires `--force` to run. -There is currently no method exposed through npm to inspect or directly -manage the contents of this cache. In order to access it, `cacache` must be -used directly. +There is currently no method exposed through npm to inspect or directly manage the contents of this cache. +In order to access it, `cacache` must be used directly. -npm will not remove data by itself: the cache will grow as new packages are -installed. +npm will not remove data by itself: the cache will grow as new packages are installed. ### A note about the cache's design -The npm cache is strictly a cache: it should not be relied upon as a -persistent and reliable data store for package data. npm makes no guarantee -that a previously-cached piece of data will be available later, and will -automatically delete corrupted contents. The primary guarantee that the -cache makes is that, if it does return data, that data will be exactly the -data that was inserted. +The npm cache is strictly a cache: it should not be relied upon as a persistent and reliable data store for package data. +npm makes no guarantee that a previously-cached piece of data will be available later, and will automatically delete corrupted contents. +The primary guarantee that the cache makes is that, if it does return data, that data will be exactly the data that was inserted. -To run an offline verification of existing cache contents, use `npm cache -verify`. +To run an offline verification of existing cache contents, use `npm cache verify`. ### Configuration @@ -74,6 +76,7 @@ verify`. * [npm install](/commands/npm-install) * [npm publish](/commands/npm-publish) * [npm pack](/commands/npm-pack) +* [npm exec](/commands/npm-exec) * https://npm.im/cacache * https://npm.im/pacote * https://npm.im/@npmcli/arborist diff --git a/docs/lib/content/commands/npm-ci.md b/docs/lib/content/commands/npm-ci.md index d26691c3c29c6..fb28e34e5f29b 100644 --- a/docs/lib/content/commands/npm-ci.md +++ b/docs/lib/content/commands/npm-ci.md @@ -10,29 +10,21 @@ description: Clean install a project ### Description -This command is similar to [`npm install`](/commands/npm-install), except -it's meant to be used in automated environments such as test platforms, -continuous integration, and deployment -- or any situation where you want -to make sure you're doing a clean install of your dependencies. +This command is similar to [`npm install`](/commands/npm-install), except it's meant to be used in automated environments such as test platforms, continuous integration, and deployment -- or any situation where you want to make sure you're doing a clean install of your dependencies. The main differences between using `npm install` and `npm ci` are: -* The project **must** have an existing `package-lock.json` or - `npm-shrinkwrap.json`. +* The project **must** have an existing `package-lock.json`. * If dependencies in the package lock do not match those in `package.json`, `npm ci` will exit with an error, instead of updating the package lock. -* `npm ci` can only install entire projects at a time: individual - dependencies cannot be added with this command. -* If a `node_modules` is already present, it will be automatically removed - before `npm ci` begins its install. -* It will never write to `package.json` or any of the package-locks: +* `npm ci` can only install entire projects at a time: individual dependencies cannot be added with this command. +* If a `node_modules` is already present, it will be automatically removed before `npm ci` begins its install. +* It will never write to `package.json` or `package-lock.json`: installs are essentially frozen. -NOTE: If you create your `package-lock.json` file by running `npm install` -with flags that can affect the shape of your dependency tree, such as -`--legacy-peer-deps` or `--install-links`, you _must_ provide the same -flags to `npm ci` or you are likely to encounter errors. An easy way to do -this is to run, for example, +NOTE: If you create your `package-lock.json` file by running `npm install` with flags that can affect the shape of your dependency tree, such as +`--legacy-peer-deps` or `--install-links`, you _must_ provide the same flags to `npm ci` or you are likely to encounter errors. +An easy way to do this is to run, for example, `npm config set legacy-peer-deps=true --location=project` and commit the `.npmrc` file to your repo. diff --git a/docs/lib/content/commands/npm-completion.md b/docs/lib/content/commands/npm-completion.md index dcc25997fa585..3019ce1fd4c5c 100644 --- a/docs/lib/content/commands/npm-completion.md +++ b/docs/lib/content/commands/npm-completion.md @@ -12,24 +12,19 @@ description: Tab Completion for npm Enables tab-completion in all npm commands. -The synopsis above -loads the completions into your current shell. Adding it to -your ~/.bashrc or ~/.zshrc will make the completions available -everywhere: +The synopsis above loads the completions into your current shell. +Adding it to your ~/.bashrc or ~/.zshrc will make the completions available everywhere: ```bash npm completion >> ~/.bashrc npm completion >> ~/.zshrc ``` -You may of course also pipe the output of `npm completion` to a file -such as `/usr/local/etc/bash_completion.d/npm` or +You may of course also pipe the output of `npm completion` to a file such as `/usr/local/etc/bash_completion.d/npm` or `/etc/bash_completion.d/npm` if you have a system that will read that file for you. -When `COMP_CWORD`, `COMP_LINE`, and `COMP_POINT` are defined in the -environment, `npm completion` acts in "plumbing mode", and outputs -completions based on the arguments. +When `COMP_CWORD`, `COMP_LINE`, and `COMP_POINT` are defined in the environment, `npm completion` acts in "plumbing mode", and outputs completions based on the arguments. ### See Also diff --git a/docs/lib/content/commands/npm-config.md b/docs/lib/content/commands/npm-config.md index c3a67f6349eb3..831876bac290d 100644 --- a/docs/lib/content/commands/npm-config.md +++ b/docs/lib/content/commands/npm-config.md @@ -10,17 +10,13 @@ description: Manage the npm configuration files ### Description -npm gets its config settings from the command line, environment -variables, `npmrc` files, and in some cases, the `package.json` file. +npm gets its config settings from the command line, environment variables, `npmrc` files, and in some cases, the `package.json` file. -See [npmrc](/configuring-npm/npmrc) for more information about the npmrc -files. +See [npmrc](/configuring-npm/npmrc) for more information about the npmrc files. -See [config](/using-npm/config) for a more thorough explanation of the -mechanisms involved, and a full list of config options available. +See [config](/using-npm/config) for a more thorough explanation of the mechanisms involved, and a full list of config options available. -The `npm config` command can be used to update and edit the contents -of the user and global npmrc files. +The `npm config` command can be used to update and edit the contents of the user and global npmrc files. ### Sub-commands @@ -33,13 +29,12 @@ npm config set key=value [key=value...] npm set key=value [key=value...] ``` -Sets each of the config keys to the value provided. Modifies the user configuration -file unless [`location`](/commands/npm-config#location) is passed. +Sets each of the config keys to the value provided. +Modifies the user configuration file unless [`location`](/commands/npm-config#location) is passed. If value is omitted, the key will be removed from your config file entirely. -Note: for backwards compatibility, `npm config set key value` is supported -as an alias for `npm config set key=value`. +Note: for backwards compatibility, `npm config set key value` is supported as an alias for `npm config set key=value`. #### get @@ -50,11 +45,9 @@ npm get [key ...] Echo the config value(s) to stdout. -If multiple keys are provided, then the values will be prefixed with the -key names. +If multiple keys are provided, then the values will be prefixed with the key names. -If no keys are provided, then this command behaves the same as `npm config -list`. +If no keys are provided, then this command behaves the same as `npm config list`. #### list @@ -62,8 +55,9 @@ list`. npm config list ``` -Show all the config settings. Use `-l` to also show defaults. Use `--json` -to show the settings in json format. +Show all the config settings. +Use `-l` to also show defaults. +Use `--json` to show the settings in json format. #### delete @@ -79,8 +73,8 @@ Deletes the specified keys from all configuration files. npm config edit ``` -Opens the config file in an editor. Use the `--global` flag to edit the -global config. +Opens the config file in an editor. +Use the `--global` flag to edit the global config. #### fix @@ -88,9 +82,9 @@ global config. npm config fix ``` -Attempts to repair invalid configuration items. Usually this means -attaching authentication config (i.e. `_auth`, `_authToken`) to the -configured `registry`. +Attempts to repair invalid configuration items. +Usually this means attaching authentication config (i.e. +`_auth`, `_authToken`) to the configured `registry`. ### Configuration diff --git a/docs/lib/content/commands/npm-dedupe.md b/docs/lib/content/commands/npm-dedupe.md index 877a130c1431c..e3ef8c6157fd7 100644 --- a/docs/lib/content/commands/npm-dedupe.md +++ b/docs/lib/content/commands/npm-dedupe.md @@ -10,9 +10,7 @@ description: Reduce duplication in the package tree ### Description -Searches the local package tree and attempts to simplify the overall -structure by moving dependencies further up the tree, where they can -be more effectively shared by multiple dependent packages. +Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages. For example, consider this dependency graph: @@ -33,9 +31,7 @@ a `-- c@1.0.10 ``` -Because of the hierarchical nature of node's module lookup, b and d -will both get their dependency met by the single c package at the root -level of the tree. +Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree. In some cases, you may have a dependency graph like this: @@ -47,29 +43,21 @@ a `-- c@1.9.9 ``` -During the installation process, the `c@1.0.3` dependency for `b` was -placed in the root of the tree. Though `d`'s dependency on `c@1.x` could -have been satisfied by `c@1.0.3`, the newer `c@1.9.0` dependency was used, -because npm favors updates by default, even when doing so causes -duplication. +During the installation process, the `c@1.0.3` dependency for `b` was placed in the root of the tree. +Though `d`'s dependency on `c@1.x` could have been satisfied by `c@1.0.3`, the newer `c@1.9.9` dependency was used, because npm favors updates by default, even when doing so causes duplication. -Running `npm dedupe` will cause npm to note the duplication and -re-evaluate, deleting the nested `c` module, because the one in the root is -sufficient. +Running `npm dedupe` will cause npm to note the duplication and re-evaluate, deleting the nested `c` module, because the one in the root is sufficient. -To prefer deduplication over novelty during the installation process, run -`npm install --prefer-dedupe` or `npm config set prefer-dedupe true`. +To prefer deduplication over novelty during the installation process, run `npm install --prefer-dedupe` or `npm config set prefer-dedupe true`. -Arguments are ignored. Dedupe always acts on the entire tree. +Arguments are ignored. +Dedupe always acts on the entire tree. -Note that this operation transforms the dependency tree, but will never -result in new modules being installed. +Note that this operation transforms the dependency tree, but will never result in new modules being installed. Using `npm find-dupes` will run the command in `--dry-run` mode. -Note: `npm dedupe` will never update the semver values of direct -dependencies in your project `package.json`, if you want to update -values in `package.json` you can run: `npm update --save` instead. +Note: `npm dedupe` will never update the semver values of direct dependencies in your project `package.json`, if you want to update values in `package.json` you can run: `npm update --save` instead. ### Configuration diff --git a/docs/lib/content/commands/npm-deny-scripts.md b/docs/lib/content/commands/npm-deny-scripts.md new file mode 100644 index 0000000000000..4aee897891c1d --- /dev/null +++ b/docs/lib/content/commands/npm-deny-scripts.md @@ -0,0 +1,58 @@ +--- +title: npm-deny-scripts +section: 1 +description: Deny install scripts for specific dependencies +--- + +### Synopsis + + + +### Description + +The companion command to [`npm approve-scripts`](/commands/npm-approve-scripts). +Writes `false` entries into the `allowScripts` field of your project's +`package.json`, recording that a dependency must not run install scripts +even if a future version would otherwise be eligible. + +Dependency install scripts are blocked by default. Adding a `false` +entry with `deny-scripts` makes the denial explicit (so it survives +`npm approve-scripts --all`) and excludes the package from any future +`--allow-scripts-pending` review prompts. + +```bash +npm deny-scripts [ ...] +npm deny-scripts --all +``` + +`` matches every installed version of that package. Denies are always +written name-only (`"pkg": false`), regardless of `--allow-scripts-pin`. Pinning a deny +to a specific version would silently re-allow scripts for any other version +of the same package, which defeats the purpose; the command picks the +safer default for you. + +`--all` denies every package with unreviewed install scripts. + +If a `true` (pinned or name-only) entry exists for a package and you then +deny it, the existing allow entries are removed so the name-only deny is +unambiguous. + +### Examples + +```bash +# Deny a specific package outright +npm deny-scripts telemetry-pkg + +# Deny everything that has install scripts and isn't already approved +npm deny-scripts --all +``` + +### Configuration + + + +### See Also + +* [npm approve-scripts](/commands/npm-approve-scripts) +* [npm install](/commands/npm-install) +* [package.json](/configuring-npm/package-json) diff --git a/docs/lib/content/commands/npm-deprecate.md b/docs/lib/content/commands/npm-deprecate.md index dbe785f05588c..d83320743ce0d 100644 --- a/docs/lib/content/commands/npm-deprecate.md +++ b/docs/lib/content/commands/npm-deprecate.md @@ -10,18 +10,16 @@ description: Deprecate a version of a package ### Description -This command will update the npm registry entry for a package, providing a -deprecation warning to all who attempt to install it. +This command will update the npm registry entry for a package, providing a deprecation warning to all who attempt to install it. -It works on [version ranges](https://semver.npmjs.com/) as well as specific -versions, so you can do something like this: +It works on [version ranges](https://semver.npmjs.com/) as well as specific versions, so you can do something like this: ```bash npm deprecate my-thing@"< 0.2.3" "critical bug fixed in v0.2.3" ``` -SemVer ranges passed to this command are interpreted such that they *do* -include prerelease versions. For example: +SemVer ranges passed to this command are interpreted such that they *do* include prerelease versions. +For example: ```bash npm deprecate my-thing@1.x "1.x is no longer supported" @@ -29,12 +27,11 @@ npm deprecate my-thing@1.x "1.x is no longer supported" In this case, a version `my-thing@1.0.0-beta.0` will also be deprecated. -You must be the package owner to deprecate something. See the `owner` and -`adduser` help topics. +You must be the package owner to deprecate something. +See the `owner` and `login` help topics. -To un-deprecate a package, specify an empty string (`""`) for the `message` -argument. Note that you must use double quotes with no space between them to -format an empty string. +To un-deprecate a package, specify an empty string (`""`) for the `message` argument. +Note that you must use double quotes with no space between them to format an empty string. ### Configuration @@ -46,4 +43,4 @@ format an empty string. * [npm publish](/commands/npm-publish) * [npm registry](/using-npm/registry) * [npm owner](/commands/npm-owner) -* [npm adduser](/commands/npm-adduser) +* [npm login](/commands/npm-login) diff --git a/docs/lib/content/commands/npm-diff.md b/docs/lib/content/commands/npm-diff.md index 5a10841a9c2d8..fa6580e2a1f7d 100644 --- a/docs/lib/content/commands/npm-diff.md +++ b/docs/lib/content/commands/npm-diff.md @@ -10,22 +10,16 @@ description: The registry diff command ### Description -Similar to its `git diff` counterpart, this command will print diff patches -of files for packages published to the npm registry. +Similar to its `git diff` counterpart, this command will print diff patches of files for packages published to the npm registry. * `npm diff --diff= --diff=` - Compares two package versions using their registry specifiers, e.g: - `npm diff --diff=pkg@1.0.0 --diff=pkg@^2.0.0`. It's also possible to - compare across forks of any package, - e.g: `npm diff --diff=pkg@1.0.0 --diff=pkg-fork@1.0.0`. + Compares two package versions using their registry specifiers, e.g: `npm diff --diff=pkg@1.0.0 --diff=pkg@^2.0.0`. + It's also possible to compare across forks of any package, e.g: `npm diff --diff=pkg@1.0.0 --diff=pkg-fork@1.0.0`. - Any valid spec can be used, so that it's also possible to compare - directories or git repositories, - e.g: `npm diff --diff=pkg@latest --diff=./packages/pkg` + Any valid spec can be used, so that it's also possible to compare directories or git repositories, e.g: `npm diff --diff=pkg@latest --diff=./packages/pkg` - Here's an example comparing two different versions of a package named - `abbrev` from the registry: + Here's an example comparing two different versions of a package named `abbrev` from the registry: ```bash npm diff --diff=abbrev@1.1.0 --diff=abbrev@1.1.1 @@ -48,39 +42,24 @@ of files for packages published to the npm registry. "main": "abbrev.js", ``` - Given the flexible nature of npm specs, you can also target local - directories or git repos just like when using `npm install`: + Given the flexible nature of npm specs, you can also target local directories or git repos just like when using `npm install`: ```bash npm diff --diff=https://github.com/npm/libnpmdiff --diff=./local-path ``` - In the example above we can compare the contents from the package installed - from the git repo at `github.com/npm/libnpmdiff` with the contents of the - `./local-path` that contains a valid package, such as a modified copy of - the original. + In the example above we can compare the contents from the package installed from the git repo at `github.com/npm/libnpmdiff` with the contents of the `./local-path` that contains a valid package, such as a modified copy of the original. * `npm diff` (in a package directory, no arguments): - If the package is published to the registry, `npm diff` will fetch the - tarball version tagged as `latest` (this value can be configured using the - `tag` option) and proceed to compare the contents of files present in that - tarball, with the current files in your local file system. + If the package is published to the registry, `npm diff` will fetch the tarball version tagged as `latest` (this value can be configured using the `tag` option) and proceed to compare the contents of files present in that tarball, with the current files in your local file system. - This workflow provides a handy way for package authors to see what - package-tracked files have been changed in comparison with the latest - published version of that package. + This workflow provides a handy way for package authors to see what package-tracked files have been changed in comparison with the latest published version of that package. * `npm diff --diff=` (in a package directory): - When using a single package name (with no version or tag specifier) as an - argument, `npm diff` will work in a similar way to - [`npm-outdated`](npm-outdated) and reach for the registry to figure out - what current published version of the package named `` - will satisfy its dependent declared semver-range. Once that specific - version is known `npm diff` will print diff patches comparing the - current version of `` found in the local file system with - that specific version returned by the registry. + When using a single package name (with no version or tag specifier) as an argument, `npm diff` will work in a similar way to [`npm-outdated`](npm-outdated) and reach for the registry to figure out what current published version of the package named `` will satisfy its dependent declared semver-range. + Once that specific version is known `npm diff` will print diff patches comparing the current version of `` found in the local file system with that specific version returned by the registry. Given a package named `abbrev` that is currently installed: @@ -88,19 +67,13 @@ of files for packages published to the npm registry. npm diff --diff=abbrev ``` - That will request from the registry its most up to date version and - will print a diff output comparing the currently installed version to this - newer one if the version numbers are not the same. + That will request from the registry its most up to date version and will print a diff output comparing the currently installed version to this newer one if the version numbers are not the same. * `npm diff --diff=` (in a package directory): - Similar to using only a single package name, it's also possible to declare - a full registry specifier version if you wish to compare the local version - of an installed package with the specific version/tag/semver-range provided - in ``. + Similar to using only a single package name, it's also possible to declare a full registry specifier version if you wish to compare the local version of an installed package with the specific version/tag/semver-range provided in ``. - An example: assuming `pkg@1.0.0` is installed in the current `node_modules` - folder, running: + An example: assuming `pkg@1.0.0` is installed in the current `node_modules` folder, running: ```bash npm diff --diff=pkg@2.0.0 @@ -111,39 +84,29 @@ of files for packages published to the npm registry. * `npm diff --diff= [--diff=]` (in a package directory): - Using `npm diff` along with semver-valid version numbers is a shorthand - to compare different versions of the current package. + Using `npm diff` along with semver-valid version numbers is a shorthand to compare different versions of the current package. - It needs to be run from a package directory, such that for a package named - `pkg` running `npm diff --diff=1.0.0 --diff=1.0.1` is the same as running - `npm diff --diff=pkg@1.0.0 --diff=pkg@1.0.1`. + It needs to be run from a package directory, such that for a package named `pkg` running `npm diff --diff=1.0.0 --diff=1.0.1` is the same as running `npm diff --diff=pkg@1.0.0 --diff=pkg@1.0.1`. - If only a single argument `` is provided, then the current local - file system is going to be compared against that version. + If only a single argument `` is provided, then the current local file system is going to be compared against that version. - Here's an example comparing two specific versions (published to the - configured registry) of the current project directory: + Here's an example comparing two specific versions (published to the configured registry) of the current project directory: ```bash npm diff --diff=1.0.0 --diff=1.1.0 ``` -Note that tag names are not valid `--diff` argument values, if you wish to -compare to a published tag, you must use the `pkg@tagname` syntax. +Note that tag names are not valid `--diff` argument values, if you wish to compare to a published tag, you must use the `pkg@tagname` syntax. #### Filtering files -It's possible to also specify positional arguments using file names or globs -pattern matching in order to limit the result of diff patches to only a subset -of files for a given package, e.g: +It's possible to also specify positional arguments using file names or globs pattern matching in order to limit the result of diff patches to only a subset of files for a given package, e.g: ```bash npm diff --diff=pkg@2 ./lib/ CHANGELOG.md ``` -In the example above the diff output is only going to print contents of files -located within the folder `./lib/` and changed lines of code within the -`CHANGELOG.md` file. +In the example above the diff output is only going to print contents of files located within the folder `./lib/` and changed lines of code within the `CHANGELOG.md` file. ### Configuration diff --git a/docs/lib/content/commands/npm-dist-tag.md b/docs/lib/content/commands/npm-dist-tag.md index 40484c63edad5..fdd6e048d066c 100644 --- a/docs/lib/content/commands/npm-dist-tag.md +++ b/docs/lib/content/commands/npm-dist-tag.md @@ -12,22 +12,16 @@ description: Modify package distribution tags Add, remove, and enumerate distribution tags on a package: -* add: Tags the specified version of the package with the specified tag, - or the [`--tag` config](/using-npm/config#tag) if not specified. If you have - two-factor authentication on auth-and-writes then you’ll need to include a - one-time password on the command line with - `--otp `, or go through a second factor flow based on your `authtype`. +* add: Tags the specified version of the package with the specified tag, or the [`--tag` config](/using-npm/config#tag) if not specified. + If you have two-factor authentication on auth-and-writes then you’ll need to include a one-time password on the command line with `--otp `, or go through a second factor flow based on your `authtype`. -* rm: Clear a tag that is no longer in use from the package. If you have - two-factor authentication on auth-and-writes then you’ll need to include - a one-time password on the command line with `--otp `, - or go through a second factor flow based on your `authtype` +* rm: Clear a tag that is no longer in use from the package. + If you have two-factor authentication on auth-and-writes then you’ll need to include a one-time password on the command line with `--otp `, or go through a second factor flow based on your `authtype` -* ls: Show all of the dist-tags for a package, defaulting to the package in - the current prefix. This is the default action if none is specified. +* ls: Show all of the dist-tags for a package, defaulting to the package in the current prefix. + This is the default action if none is specified. -A tag can be used when installing packages as a reference to a version instead -of using a specific version number: +A tag can be used when installing packages as a reference to a version instead of using a specific version number: ```bash npm install @ @@ -39,28 +33,22 @@ When installing dependencies, a preferred tagged version may be specified: npm install --tag ``` -(This also applies to any other commands that resolve and install -dependencies, such as `npm dedupe`, `npm update`, and `npm audit fix`.) +(This also applies to any other commands that resolve and install dependencies, such as `npm dedupe`, `npm update`, and `npm audit fix`.) -Publishing a package sets the `latest` tag to the published version unless the -`--tag` option is used. For example, `npm publish --tag=beta`. +Publishing a package sets the `latest` tag to the published version unless the `--tag` option is used. +For example, `npm publish --tag=beta`. -By default, `npm install ` (without any `@` or `@` -specifier) installs the `latest` tag. +By default, `npm install ` (without any `@` or `@` specifier) installs the `latest` tag. ### Purpose Tags can be used to provide an alias instead of version numbers. -For example, a project might choose to have multiple streams of development -and use a different tag for each stream, e.g., `stable`, `beta`, `dev`, +For example, a project might choose to have multiple streams of development and use a different tag for each stream, e.g., `stable`, `beta`, `dev`, `canary`. -By default, the `latest` tag is used by npm to identify the current version -of a package, and `npm install ` (without any `@` or `@` -specifier) installs the `latest` tag. Typically, projects only use the -`latest` tag for stable release versions, and use other tags for unstable -versions such as prereleases. +By default, the `latest` tag is used by npm to identify the current version of a package, and `npm install ` (without any `@` or `@` specifier) installs the `latest` tag. +Typically, projects only use the `latest` tag for stable release versions, and use other tags for unstable versions such as prereleases. The `next` tag is used by some projects to identify the upcoming version. @@ -68,19 +56,15 @@ Other than `latest`, no tag has any special significance to npm itself. ### Caveats -This command used to be known as `npm tag`, which only created new tags, -and so had a different syntax. +This command used to be known as `npm tag`, which only created new tags, and so had a different syntax. -Tags must share a namespace with version numbers, because they are -specified in the same slot: `npm install @` vs -`npm install @`. +Tags must share a namespace with version numbers, because they are specified in the same slot: `npm install @` vs `npm install @`. -Tags that can be interpreted as valid semver ranges will be rejected. For -example, `v1.4` cannot be used as a tag, because it is interpreted by -semver as `>=1.4.0 <1.5.0`. See . +Tags that can be interpreted as valid semver ranges will be rejected. +For example, `v1.4` cannot be used as a tag, because it is interpreted by semver as `>=1.4.0 <1.5.0`. +See . -The simplest way to avoid semver problems with tags is to use tags that do -not begin with a number or the letter `v`. +The simplest way to avoid semver problems with tags is to use tags that do not begin with a number or the letter `v`. ### Configuration diff --git a/docs/lib/content/commands/npm-docs.md b/docs/lib/content/commands/npm-docs.md index 140d23dfa7e86..816f228e6d527 100644 --- a/docs/lib/content/commands/npm-docs.md +++ b/docs/lib/content/commands/npm-docs.md @@ -10,11 +10,9 @@ description: Open documentation for a package in a web browser ### Description -This command tries to guess at the likely location of a package's -documentation URL, and then tries to open it using the -[`--browser` config](/using-npm/config#browser) param. You can pass multiple -package names at once. If no package name is provided, it will search for a -`package.json` in the current folder and use the `name` property. +This command tries to guess at the likely location of a package's documentation URL, and then tries to open it using the [`--browser` config](/using-npm/config#browser) param. +You can pass multiple package names at once. +If no package name is provided, it will search for a `package.json` in the current folder and use the `name` property. ### Configuration diff --git a/docs/lib/content/commands/npm-doctor.md b/docs/lib/content/commands/npm-doctor.md index b5c8126b272c0..3a007b4ee80f1 100644 --- a/docs/lib/content/commands/npm-doctor.md +++ b/docs/lib/content/commands/npm-doctor.md @@ -10,96 +10,71 @@ description: Check the health of your npm environment ### Description -`npm doctor` runs a set of checks to ensure that your npm installation has -what it needs to manage your JavaScript packages. npm is mostly a -standalone tool, but it does have some basic requirements that must be met: +`npm doctor` runs a set of checks to ensure that your npm installation has what it needs to manage your JavaScript packages. +npm is mostly a standalone tool, but it does have some basic requirements that must be met: + Node.js and git must be executable by npm. -+ The primary npm registry, `registry.npmjs.com`, or another service that - uses the registry API, is available. -+ The directories that npm uses, `node_modules` (both locally and - globally), exist and can be written by the current user. ++ The primary npm registry, `registry.npmjs.com`, or another service that uses the registry API, is available. ++ The directories that npm uses, `node_modules` (both locally and globally), exist and can be written by the current user. + The npm cache exists, and the package tarballs within it aren't corrupt. -Without all of these working properly, npm may not work properly. Many -issues are often attributable to things that are outside npm's code base, -so `npm doctor` confirms that the npm installation is in a good state. +Without all of these working properly, npm may not work properly. +Many issues are often attributable to things that are outside npm's code base, so `npm doctor` confirms that the npm installation is in a good state. -Also, in addition to this, there are also very many issue reports due to -using old versions of npm. Since npm is constantly improving, running -`npm@latest` is better than an old version. +Also, in addition to this, there are also very many issue reports due to using old versions of npm. +Since npm is constantly improving, running `npm@latest` is better than an old version. -`npm doctor` verifies the following items in your environment, and if -there are any recommended changes, it will display them. By default npm -runs all of these checks. You can limit what checks are ran by -specifying them as extra arguments. +`npm doctor` verifies the following items in your environment, and if there are any recommended changes, it will display them. +By default npm runs all of these checks. +You can limit what checks are ran by specifying them as extra arguments. #### `Connecting to the registry` By default, npm installs from the primary npm registry, -`registry.npmjs.org`. `npm doctor` hits a special connection testing -endpoint within the registry. This can also be checked with `npm ping`. -If this check fails, you may be using a proxy that needs to be -configured, or may need to talk to your IT staff to get access over -HTTPS to `registry.npmjs.org`. +`registry.npmjs.org`. +`npm doctor` hits a special connection testing endpoint within the registry. +This can also be checked with `npm ping`. +If this check fails, you may be using a proxy that needs to be configured, or may need to talk to your IT staff to get access over HTTPS to `registry.npmjs.org`. -This check is done against whichever registry you've configured (you can -see what that is by running `npm config get registry`), and if you're using -a private registry that doesn't support the `/whoami` endpoint supported by -the primary registry, this check may fail. +This check is done against whichever registry you've configured (you can see what that is by running `npm config get registry`), and if you're using a private registry that doesn't support the `/whoami` endpoint supported by the primary registry, this check may fail. #### `Checking npm version` -While Node.js may come bundled with a particular version of npm, it's the -policy of the CLI team that we recommend all users run `npm@latest` if they -can. As the CLI is maintained by a small team of contributors, there are -only resources for a single line of development, so npm's own long-term -support releases typically only receive critical security and regression -fixes. The team believes that the latest tested version of npm is almost -always likely to be the most functional and defect-free version of npm. +While Node.js may come bundled with a particular version of npm, it's the policy of the CLI team that we recommend all users run `npm@latest` if they can. +As the CLI is maintained by a small team of contributors, there are only resources for a single line of development, so npm's own long-term support releases typically only receive critical security and regression fixes. +The team believes that the latest tested version of npm is almost always likely to be the most functional and defect-free version of npm. #### `Checking node version` -For most users, in most circumstances, the best version of Node will be the -latest long-term support (LTS) release. Those of you who want access to new -ECMAscript features or bleeding-edge changes to Node's standard library may -be running a newer version, and some may be required to run an older -version of Node because of enterprise change control policies. That's OK! +For most users, in most circumstances, the best version of Node will be the latest long-term support (LTS) release. +Those of you who want access to new ECMAscript features or bleeding-edge changes to Node's standard library may be running a newer version, and some may be required to run an older version of Node because of enterprise change control policies. +That's OK! But in general, the npm team recommends that most users run Node.js LTS. #### `Checking configured npm registry` -You may be installing from private package registries for your project or -company. That's great! Others may be following tutorials or StackOverflow -questions in an effort to troubleshoot problems you may be having. -Sometimes, this may entail changing the registry you're pointing at. This -part of `npm doctor` just lets you, and maybe whoever's helping you with -support, know that you're not using the default registry. +You may be installing from private package registries for your project or company. +That's great! Others may be following tutorials or StackOverflow questions in an effort to troubleshoot problems you may be having. +Sometimes, this may entail changing the registry you're pointing at. +This part of `npm doctor` just lets you, and maybe whoever's helping you with support, know that you're not using the default registry. #### `Checking for git executable in PATH` -While it's documented in the README, it may not be obvious that npm needs -Git installed to do many of the things that it does. Also, in some cases -– especially on Windows – you may have Git set up in such a way that it's -not accessible via your `PATH` so that npm can find it. This check ensures -that Git is available. +While it's documented in the README, it may not be obvious that npm needs Git installed to do many of the things that it does. +Also, in some cases – especially on Windows – you may have Git set up in such a way that it's not accessible via your `PATH` so that npm can find it. +This check ensures that Git is available. #### Permissions checks * Your cache must be readable and writable by the user running npm. * Global package binaries must be writable by the user running npm. -* Your local `node_modules` path, if you're running `npm doctor` with a - project directory, must be readable and writable by the user running npm. +* Your local `node_modules` path, if you're running `npm doctor` with a project directory, must be readable and writable by the user running npm. #### Validate the checksums of cached packages -When an npm package is published, the publishing process generates a -checksum that npm uses at install time to verify that the package didn't -get corrupted in transit. `npm doctor` uses these checksums to validate the -package tarballs in your local cache (you can see where that cache is -located with `npm config get cache`). In the event that there are corrupt -packages in your cache, you should probably run `npm cache clean -f` and -reset the cache. +When an npm package is published, the publishing process generates a checksum that npm uses at install time to verify that the package didn't get corrupted in transit. +`npm doctor` uses these checksums to validate the package tarballs in your local cache (you can see where that cache is located with `npm config get cache`). +In the event that there are corrupt packages in your cache, you should probably run `npm cache clean -f` and reset the cache. ### Configuration diff --git a/docs/lib/content/commands/npm-edit.md b/docs/lib/content/commands/npm-edit.md index e00c4a345dc17..84186792aaf89 100644 --- a/docs/lib/content/commands/npm-edit.md +++ b/docs/lib/content/commands/npm-edit.md @@ -10,16 +10,11 @@ description: Edit an installed package ### Description -Selects a dependency in the current project and opens the package folder in -the default editor (or whatever you've configured as the npm `editor` -config -- see [`npm-config`](npm-config).) +Selects a dependency in the current project and opens the package folder in the default editor (or whatever you've configured as the npm `editor` config -- see [`npm-config`](npm-config).) -After it has been edited, the package is rebuilt so as to pick up any -changes in compiled packages. +After it has been edited, the package is rebuilt so as to pick up any changes in compiled packages. -For instance, you can do `npm install connect` to install connect -into your package, and then `npm edit connect` to make a few -changes to your locally installed copy. +For instance, you can do `npm install connect` to install connect into your package, and then `npm edit connect` to make a few changes to your locally installed copy. ### Configuration diff --git a/docs/lib/content/commands/npm-exec.md b/docs/lib/content/commands/npm-exec.md index 33fc1a08248ac..9869afe6ea41c 100644 --- a/docs/lib/content/commands/npm-exec.md +++ b/docs/lib/content/commands/npm-exec.md @@ -10,58 +10,34 @@ description: Run a command from a local or remote npm package ### Description -This command allows you to run an arbitrary command from an npm package -(either one installed locally, or fetched remotely), in a similar context -as running it via `npm run`. - -Run without positional arguments or `--call`, this allows you to -interactively run commands in the same sort of shell environment that -`package.json` scripts are run. Interactive mode is not supported in CI -environments when standard input is a TTY, to prevent hangs. - -Whatever packages are specified by the `--package` option will be -provided in the `PATH` of the executed command, along with any locally -installed package executables. The `--package` option may be -specified multiple times, to execute the supplied command in an environment -where all specified packages are available. - -If any requested packages are not present in the local project -dependencies, then a prompt is printed, which can be suppressed by -providing either `--yes` or `--no`. When standard input is not a TTY or a -CI environment is detected, `--yes` is assumed. The requested packages are -installed to a folder in the npm cache, which is added to the `PATH` -environment variable in the executed process. - -Package names provided without a specifier will be matched with whatever -version exists in the local project. Package names with a specifier will -only be considered a match if they have the exact same name and version as -the local dependency. - -If no `-c` or `--call` option is provided, then the positional arguments -are used to generate the command string. If no `--package` options -are provided, then npm will attempt to determine the executable name from -the package specifier provided as the first positional argument according -to the following heuristic: - -- If the package has a single entry in its `bin` field in `package.json`, - or if all entries are aliases of the same command, then that command - will be used. -- If the package has multiple `bin` entries, and one of them matches the - unscoped portion of the `name` field, then that command will be used. -- If this does not result in exactly one option (either because there are - no bin entries, or none of them match the `name` of the package), then - `npm exec` exits with an error. - -To run a binary _other than_ the named binary, specify one or more -`--package` options, which will prevent npm from inferring the package from -the first command argument. +This command allows you to run an arbitrary command from an npm package (either one installed locally, or fetched remotely), in a similar context as running it via `npm run`. + +Run without positional arguments or `--call`, this allows you to interactively run commands in the same sort of shell environment that `package.json` scripts are run. +Interactive mode is not supported in CI environments when standard input is a TTY, to prevent hangs. + +Whatever packages are specified by the `--package` option will be provided in the `PATH` of the executed command, along with any locally installed package executables. +The `--package` option may be specified multiple times, to execute the supplied command in an environment where all specified packages are available. + +If any requested packages are not present in the local project dependencies, then a prompt is printed, which can be suppressed by providing either `--yes` or `--no`. +When standard input is not a TTY or a CI environment is detected, `--yes` is assumed. +The requested packages are installed to a folder in the npm cache, which is added to the `PATH` environment variable in the executed process. + +Package names provided without a specifier will be matched with whatever version exists in the local project. +Package names with a specifier will only be considered a match if they have the exact same name and version as the local dependency. + +If no `-c` or `--call` option is provided, then the positional arguments are used to generate the command string. +If no `--package` options are provided, then npm will attempt to determine the executable name from the package specifier provided as the first positional argument according to the following heuristic: + +- If the package has a single entry in its `bin` field in `package.json`, or if all entries are aliases of the same command, then that command will be used. +- If the package has multiple `bin` entries, and one of them matches the unscoped portion of the `name` field, then that command will be used. +- If this does not result in exactly one option (either because there are no bin entries, or none of them match the `name` of the package), then `npm exec` exits with an error. + +To run a binary _other than_ the named binary, specify one or more `--package` options, which will prevent npm from inferring the package from the first command argument. ### `npx` vs `npm exec` -When run via the `npx` binary, all flags and options *must* be set prior to -any positional arguments. When run via `npm exec`, a double-hyphen `--` -flag can be used to suppress npm's parsing of switches and options that -should be sent to the executed command. +When run via the `npx` binary, all flags and options *must* be set prior to any positional arguments. +When run via `npm exec`, a double-hyphen `--` flag can be used to suppress npm's parsing of switches and options that should be sent to the executed command. For example: @@ -69,34 +45,29 @@ For example: $ npx foo@latest bar --package=@npmcli/foo ``` -In this case, npm will resolve the `foo` package name, and run the -following command: +In this case, npm will resolve the `foo` package name, and run the following command: ``` $ foo bar --package=@npmcli/foo ``` -Since the `--package` option comes _after_ the positional arguments, it is -treated as an argument to the executed command. +Since the `--package` option comes _after_ the positional arguments, it is treated as an argument to the executed command. -In contrast, due to npm's argument parsing logic, running this command is -different: +In contrast, due to npm's argument parsing logic, running this command is different: ``` $ npm exec foo@latest bar --package=@npmcli/foo ``` -In this case, npm will parse the `--package` option first, resolving the -`@npmcli/foo` package. Then, it will execute the following command in that -context: +In this case, npm will parse the `--package` option first, resolving the `@npmcli/foo` package. +Then, it will execute the following command in that context: ``` $ foo@latest bar ``` -The double-hyphen character is recommended to explicitly tell npm to stop -parsing command line options and switches. The following command would -thus be equivalent to the `npx` command above: +The double-hyphen character is recommended to explicitly tell npm to stop parsing command line options and switches. +The following command would thus be equivalent to the `npx` command above: ``` $ npm exec -- foo@latest bar --package=@npmcli/foo @@ -108,16 +79,14 @@ $ npm exec -- foo@latest bar --package=@npmcli/foo ### Examples -Run the version of `tap` in the local dependencies, with the provided -arguments: +Run the version of `tap` in the local dependencies, with the provided arguments: ``` $ npm exec -- tap --bail test/foo.js $ npx tap --bail test/foo.js ``` -Run a command _other than_ the command whose name matches the package name -by specifying a `--package` option: +Run a command _other than_ the command whose name matches the package name by specifying a `--package` option: ``` $ npm exec --package=foo -- bar --bar-argument @@ -134,13 +103,8 @@ $ npx -c 'eslint && say "hooray, lint passed"' ### Workspaces support -You may use the [`workspace`](/using-npm/config#workspace) or -[`workspaces`](/using-npm/config#workspaces) configs in order to run an -arbitrary command from an npm package (either one installed locally, or fetched -remotely) in the context of the specified workspaces. -If no positional argument or `--call` option is provided, it will open an -interactive subshell in the context of each of these configured workspaces one -at a time. +You may use the [`workspace`](/using-npm/config#workspace) or [`workspaces`](/using-npm/config#workspaces) configs in order to run an arbitrary command from an npm package (either one installed locally, or fetched remotely) in the context of the specified workspaces. +If no positional argument or `--call` option is provided, it will open an interactive subshell in the context of each of these configured workspaces one at a time. Given a project with configured workspaces, e.g: @@ -156,8 +120,8 @@ Given a project with configured workspaces, e.g: `-- package.json ``` -Assuming the workspace configuration is properly set up at the root level -`package.json` file. e.g: +Assuming the workspace configuration is properly set up at the root level `package.json` file. +e.g: ``` { @@ -165,10 +129,7 @@ Assuming the workspace configuration is properly set up at the root level } ``` -You can execute an arbitrary command from a package in the context of each of -the configured workspaces when using the -[`workspaces` config options](/using-npm/config#workspace), in this example -we're using **eslint** to lint any js file found within each workspace folder: +You can execute an arbitrary command from a package in the context of each of the configured workspaces when using the [`workspaces` config options](/using-npm/config#workspace), in this example we're using **eslint** to lint any js file found within each workspace folder: ``` npm exec --ws -- eslint ./*.js @@ -176,17 +137,14 @@ npm exec --ws -- eslint ./*.js #### Filtering workspaces -It's also possible to execute a command in a single workspace using the -`workspace` config along with a name or directory path: +It's also possible to execute a command in a single workspace using the `workspace` config along with a name or directory path: ``` npm exec --workspace=a -- eslint ./*.js ``` -The `workspace` config can also be specified multiple times in order to run a -specific script in the context of multiple workspaces. When defining values for -the `workspace` config in the command line, it also possible to use `-w` as a -shorthand, e.g: +The `workspace` config can also be specified multiple times in order to run a specific script in the context of multiple workspaces. +When defining values for the `workspace` config in the command line, it also possible to use `-w` as a shorthand, e.g: ``` npm exec -w a -w b -- eslint ./*.js @@ -197,69 +155,60 @@ This last command will run the `eslint` command in both `./packages/a` and ### Compatibility with Older npx Versions -The `npx` binary was rewritten in npm v7.0.0, and the standalone `npx` -package deprecated at that time. `npx` uses the `npm exec` -command instead of a separate argument parser and install process, with -some affordances to maintain backwards compatibility with the arguments it -accepted in previous versions. +The `npx` binary was rewritten in npm v7.0.0, and the standalone `npx` package deprecated at that time. +`npx` uses the `npm exec` command instead of a separate argument parser and install process, with some affordances to maintain backwards compatibility with the arguments it accepted in previous versions. This resulted in some shifts in its functionality: - Any `npm` config value may be provided. - To prevent security and user-experience problems from mistyping package - names, `npx` prompts before installing anything. Suppress this - prompt with the `-y` or `--yes` option. + names, `npx` prompts before installing anything. + Suppress this prompt with the `-y` or `--yes` option. - The `--no-install` option is deprecated, and will be converted to `--no`. - Shell fallback functionality is removed, as it is not advisable. -- The `-p` argument is a shorthand for `--parseable` in npm, but shorthand - for `--package` in npx. This is maintained, but only for the `npx` - executable. -- The `--ignore-existing` option is removed. Locally installed bins are - always present in the executed process `PATH`. -- The `--npm` option is removed. `npx` will always use the `npm` it ships - with. +- The `-p` argument is a shorthand for `--parseable` in npm, but shorthand for `--package` in npx. + This is maintained, but only for the `npx` executable. +- The `--ignore-existing` option is removed. + Locally installed bins are always present in the executed process `PATH`. +- The `--npm` option is removed. + `npx` will always use the `npm` it ships with. - The `--node-arg` and `-n` options are removed. - The `--always-spawn` option is redundant, and thus removed. -- The `--shell` option is replaced with `--script-shell`, but maintained - in the `npx` executable for backwards compatibility. +- The `--shell` option is replaced with `--script-shell`, but maintained in the `npx` executable for backwards compatibility. ### A note on caching -The npm cli utilizes its internal package cache when using the package -name specified. You can use the following to change how and when the -cli uses this cache. See [`npm cache`](/commands/npm-cache) for more on -how the cache works. +The npm cli utilizes its internal package cache when using the package name specified. +You can use the following to change how and when the cli uses this cache. +See [`npm cache`](/commands/npm-cache) for more on how the cache works. #### prefer-online -Forces staleness checks for packages, making the cli look for updates -immediately even if the package is already in the cache. +Forces staleness checks for packages, making the cli look for updates immediately even if the package is already in the cache. #### prefer-offline -Bypasses staleness checks for packages. Missing data will still be -requested from the server. To force full offline mode, use `offline`. +Bypasses staleness checks for packages. +Missing data will still be requested from the server. +To force full offline mode, use `offline`. #### offline -Forces full offline mode. Any packages not locally cached will result in -an error. +Forces full offline mode. +Any packages not locally cached will result in an error. #### workspace * Default: * Type: String (can be set multiple times) -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. +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 to selecting all of the - nested workspaces) +* Path to a parent workspace directory (will result to selecting all of the nested workspaces) This value is not exported to the environment for child processes. @@ -269,12 +218,11 @@ This value is not exported to the environment for child processes. * Type: Boolean * Default: `false` -Run scripts in the context of all configured workspaces for the current -project. +Run scripts in the context of all configured workspaces for the current project. ### See Also -* [npm run-script](/commands/npm-run-script) +* [npm run](/commands/npm-run) * [npm scripts](/using-npm/scripts) * [npm test](/commands/npm-test) * [npm start](/commands/npm-start) diff --git a/docs/lib/content/commands/npm-explain.md b/docs/lib/content/commands/npm-explain.md index 8de05c92f8b2c..577a6521919ae 100644 --- a/docs/lib/content/commands/npm-explain.md +++ b/docs/lib/content/commands/npm-explain.md @@ -10,11 +10,9 @@ description: Explain installed packages ### Description -This command will print the chain of dependencies causing a given package -to be installed in the current project. +This command will print the chain of dependencies causing a given package to be installed in the current project. -If one or more package specs are provided, then only packages matching -one of the specifiers will have their relationships explained. +If one or more package specs are provided, then only packages matching one of the specifiers will have their relationships explained. The package spec can also refer to a folder within `./node_modules` @@ -34,10 +32,8 @@ node_modules/tacks/node_modules/glob dev tacks@"^1.3.0" from the root project ``` -To explain just the package residing at a specific folder, pass that as the -argument to the command. This can be useful when trying to figure out -exactly why a given dependency is being duplicated to satisfy conflicting -version requirements within the project. +To explain just the package residing at a specific folder, pass that as the argument to the command. +This can be useful when trying to figure out exactly why a given dependency is being duplicated to satisfy conflicting version requirements within the project. ```bash $ npm explain node_modules/nyc/node_modules/find-up diff --git a/docs/lib/content/commands/npm-explore.md b/docs/lib/content/commands/npm-explore.md index c277e4bec7bd6..f92d46629bcee 100644 --- a/docs/lib/content/commands/npm-explore.md +++ b/docs/lib/content/commands/npm-explore.md @@ -12,18 +12,15 @@ description: Browse an installed package Spawn a subshell in the directory of the installed package specified. -If a command is specified, then it is run in the subshell, which then -immediately terminates. +If a command is specified, then it is run in the subshell, which then immediately terminates. -This is particularly handy in the case of git submodules in the -`node_modules` folder: +This is particularly handy in the case of git submodules in the `node_modules` folder: ```bash npm explore some-dependency -- git pull origin master ``` -Note that the package is *not* automatically rebuilt afterwards, so be -sure to use `npm rebuild ` if you make any changes. +Note that the package is *not* automatically rebuilt afterwards, so be sure to use `npm rebuild ` if you make any changes. ### Configuration diff --git a/docs/lib/content/commands/npm-find-dupes.md b/docs/lib/content/commands/npm-find-dupes.md index 1e0e8df3d21d0..ea77122aa3a47 100644 --- a/docs/lib/content/commands/npm-find-dupes.md +++ b/docs/lib/content/commands/npm-find-dupes.md @@ -10,8 +10,7 @@ description: Find duplication in the package tree ### Description -Runs `npm dedupe` in `--dry-run` mode, making npm only output the -duplications, without actually changing the package tree. +Runs `npm dedupe` in `--dry-run` mode, making npm only output the duplications, without actually changing the package tree. ### Configuration diff --git a/docs/lib/content/commands/npm-fund.md b/docs/lib/content/commands/npm-fund.md index f200aafc3e828..1e9cc2255c1ec 100644 --- a/docs/lib/content/commands/npm-fund.md +++ b/docs/lib/content/commands/npm-fund.md @@ -10,31 +10,23 @@ description: Retrieve funding information ### Description -This command retrieves information on how to fund the dependencies of a -given project. If no package name is provided, it will list all -dependencies that are looking for funding in a tree structure, listing -the type of funding and the url to visit. If a package name is provided -then it tries to open its funding url using the -[`--browser` config](/using-npm/config#browser) param; if there are multiple -funding sources for the package, the user will be instructed to pass the +This command retrieves information on how to fund the dependencies of a given project. +If no package name is provided, it will list all dependencies that are looking for funding in a tree structure, listing the type of funding and the url to visit. +If a package name is provided then it tries to open its funding url using the [`--browser` config](/using-npm/config#browser) param; if there are multiple funding sources for the package, the user will be instructed to pass the `--which` option to disambiguate. -The list will avoid duplicated entries and will stack all packages that -share the same url as a single entry. Thus, the list does not have the -same shape of the output from `npm ls`. +The list will avoid duplicated entries and will stack all packages that share the same url as a single entry. +Thus, the list does not have the same shape of the output from `npm ls`. #### Example ### Workspaces support -It's possible to filter the results to only include a single workspace -and its dependencies using the -[`workspace` config](/using-npm/config#workspace) option. +It's possible to filter the results to only include a single workspace and its dependencies using the [`workspace` config](/using-npm/config#workspace) option. #### Example: -Here's an example running `npm fund` in a project with a configured -workspace `a`: +Here's an example running `npm fund` in a project with a configured workspace `a`: ```bash $ npm fund @@ -49,8 +41,7 @@ test-workspaces-fund@1.0.0 `-- bar@2.0.0 ``` -And here is an example of the expected result when filtering only by a -specific workspace `a` in the same project: +And here is an example of the expected result when filtering only by a specific workspace `a` in the same project: ```bash $ npm fund -w a diff --git a/docs/lib/content/commands/npm-get.md b/docs/lib/content/commands/npm-get.md new file mode 100644 index 0000000000000..9e03458e7c8ce --- /dev/null +++ b/docs/lib/content/commands/npm-get.md @@ -0,0 +1,21 @@ +--- +title: npm-get +section: 1 +description: Get a value from the npm configuration +--- + +### Synopsis + + + +### Description + +Get a value from the npm configuration + +### Configuration + + + +### See Also + +* [npm help config](/commands/npm-config) diff --git a/docs/lib/content/commands/npm-help-search.md b/docs/lib/content/commands/npm-help-search.md index e419f03fdd438..095cb6878f337 100644 --- a/docs/lib/content/commands/npm-help-search.md +++ b/docs/lib/content/commands/npm-help-search.md @@ -10,14 +10,12 @@ description: Search npm help documentation ### Description -This command will search the npm markdown documentation files for the terms -provided, and then list the results, sorted by relevance. +This command will search the npm markdown documentation files for the terms provided, and then list the results, sorted by relevance. If only one result is found, then it will show that help topic. -If the argument to `npm help` is not a known help topic, then it will call -`help-search`. It is rarely if ever necessary to call this command -directly. +If the argument to `npm help` is not a known help topic, then it will call `help-search`. +It is rarely if ever necessary to call this command directly. ### Configuration diff --git a/docs/lib/content/commands/npm-help.md b/docs/lib/content/commands/npm-help.md index cefb917991113..a12a832243cee 100644 --- a/docs/lib/content/commands/npm-help.md +++ b/docs/lib/content/commands/npm-help.md @@ -12,10 +12,8 @@ description: Get help on npm If supplied a topic, then show the appropriate documentation page. -If the topic does not exist, or if multiple terms are provided, then npm -will run the `help-search` command to find a match. Note that, if -`help-search` finds a single subject, then it will run `help` on that -topic, so unique matches are equivalent to specifying a topic name. +If the topic does not exist, or if multiple terms are provided, then npm will run the `help-search` command to find a match. +Note that, if `help-search` finds a single subject, then it will run `help` on that topic, so unique matches are equivalent to specifying a topic name. ### Configuration diff --git a/docs/lib/content/commands/npm-hook.md b/docs/lib/content/commands/npm-hook.md deleted file mode 100644 index c1394e1baad80..0000000000000 --- a/docs/lib/content/commands/npm-hook.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: npm-hook -section: 1 -description: Manage registry hooks ---- - -### Synopsis - - - -### Description - -Allows you to manage [npm -hooks](https://blog.npmjs.org/post/145260155635/introducing-hooks-get-notifications-of-npm), -including adding, removing, listing, and updating. - -Hooks allow you to configure URL endpoints that will be notified whenever a -change happens to any of the supported entity types. Three different types -of entities can be watched by hooks: packages, owners, and scopes. - -To create a package hook, simply reference the package name. - -To create an owner hook, prefix the owner name with `~` (as in, -`~youruser`). - -To create a scope hook, prefix the scope name with `@` (as in, -`@yourscope`). - -The hook `id` used by `update` and `rm` are the IDs listed in `npm hook ls` -for that particular hook. - -The shared secret will be sent along to the URL endpoint so you can verify -the request came from your own configured hook. - -### Example - -Add a hook to watch a package for changes: - -```bash -$ npm hook add lodash https://example.com/ my-shared-secret -``` - -Add a hook to watch packages belonging to the user `substack`: - -```bash -$ npm hook add ~substack https://example.com/ my-shared-secret -``` - -Add a hook to watch packages in the scope `@npm` - -```bash -$ npm hook add @npm https://example.com/ my-shared-secret -``` - -List all your active hooks: - -```bash -$ npm hook ls -``` - -List your active hooks for the `lodash` package: - -```bash -$ npm hook ls lodash -``` - -Update an existing hook's url: - -```bash -$ npm hook update id-deadbeef https://my-new-website.here/ -``` - -Remove a hook: - -```bash -$ npm hook rm id-deadbeef -``` - -### Configuration - - - -### See Also - -* ["Introducing Hooks" blog post](https://blog.npmjs.org/post/145260155635/introducing-hooks-get-notifications-of-npm) diff --git a/docs/lib/content/commands/npm-init.md b/docs/lib/content/commands/npm-init.md index 832d786e66853..92092cff79f9f 100644 --- a/docs/lib/content/commands/npm-init.md +++ b/docs/lib/content/commands/npm-init.md @@ -10,16 +10,12 @@ description: Create a package.json file ### Description -`npm init ` can be used to set up a new or existing npm -package. +`npm init ` can be used to set up a new or existing npm package. `initializer` in this case is an npm package named `create-`, -which will be installed by [`npm-exec`](/commands/npm-exec), and then have its -main bin executed -- presumably creating or updating `package.json` and -running any other initialization-related operations. +which will be installed by [`npm-exec`](/commands/npm-exec), and then have its main bin executed -- presumably creating or updating `package.json` and running any other initialization-related operations. -The init command is transformed to a corresponding `npm exec` operation as -follows: +The init command is transformed to a corresponding `npm exec` operation as follows: * `npm init foo` -> `npm exec create-foo` * `npm init @usr/foo` -> `npm exec @usr/create-foo` @@ -27,46 +23,37 @@ follows: * `npm init @usr@2.0.0` -> `npm exec @usr/create@2.0.0` * `npm init @usr/foo@2.0.0` -> `npm exec @usr/create-foo@2.0.0` -If the initializer is omitted (by just calling `npm init`), init will fall -back to legacy init behavior. It will ask you a bunch of questions, and -then write a package.json for you. It will attempt to make reasonable -guesses based on existing fields, dependencies, and options selected. It is -strictly additive, so it will keep any fields and values that were already -set. You can also use `-y`/`--yes` to skip the questionnaire altogether. If -you pass `--scope`, it will create a scoped package. - -*Note:* if a user already has the `create-` package -globally installed, that will be what `npm init` uses. If you want npm -to use the latest version, or another specific version you must specify -it: - -* `npm init foo@latest` # fetches and runs the latest `create-foo` from - the registry +If the initializer is omitted (by just calling `npm init`), init will fall back to legacy init behavior. +It will ask you a bunch of questions, and then write a package.json for you. +It will attempt to make reasonable guesses based on existing fields, dependencies, and options selected. +It is strictly additive, so it will keep any fields and values that were already set. +You can also use `-y`/`--yes` to skip the questionnaire altogether. +If you pass `--scope`, it will create a scoped package. + +*Note:* if a user already has the `create-` package globally installed, that will be what `npm init` uses. +If you want npm to use the latest version, or another specific version you must specify it: + +* `npm init foo@latest` # fetches and runs the latest `create-foo` from the registry * `npm init foo@1.2.3` # runs `create-foo@1.2.3` specifically #### Forwarding additional options -Any additional options will be passed directly to the command, so `npm init -foo -- --hello` will map to `npm exec -- create-foo --hello`. +Any additional options will be passed directly to the command, so `npm init foo -- --hello` will map to `npm exec -- create-foo --hello`. -To better illustrate how options are forwarded, here's a more evolved -example showing options passed to both the **npm cli** and a create package, -both following commands are equivalent: +To better illustrate how options are forwarded, here's a more evolved example showing options passed to both the **npm cli** and a create package, both following commands are equivalent: - `npm init foo -y --registry= -- --hello -a` - `npm exec -y --registry= -- create-foo --hello -a` ### Examples -Create a new React-based project using -[`create-react-app`](https://npm.im/create-react-app): +Create a new React-based project using [`create-react-app`](https://npm.im/create-react-app): ```bash $ npm init react-app ./my-react-app ``` -Create a new `esm`-compatible package using -[`create-esm`](https://npm.im/create-esm): +Create a new `esm`-compatible package using [`create-esm`](https://npm.im/create-esm): ```bash $ mkdir my-esm-lib && cd my-esm-lib @@ -87,13 +74,15 @@ Generate it without having it ask any questions: $ npm init -y ``` +Set the private flag to `true` in package.json: +```bash +$ npm init --init-private -y +``` + ### Workspaces support -It's possible to create a new workspace within your project by using the -`workspace` config option. When using `npm init -w ` the cli will -create the folders and boilerplate expected while also adding a reference -to your project `package.json` `"workspaces": []` property in order to make -sure that new generated **workspace** is properly set up as such. +It's possible to create a new workspace within your project by using the `workspace` config option. +When using `npm init -w ` the cli will create the folders and boilerplate expected while also adding a reference to your project `package.json` `"workspaces": []` property in order to make sure that new generated **workspace** is properly set up as such. Given a project with no workspaces, e.g: @@ -108,8 +97,7 @@ You may generate a new workspace using the legacy init: $ npm init -w packages/a ``` -That will generate a new folder and `package.json` file, while also updating -your top-level `package.json` to add the reference to this new workspace: +That will generate a new folder and `package.json` file, while also updating your top-level `package.json` to add the reference to this new workspace: ``` . @@ -119,23 +107,15 @@ your top-level `package.json` to add the reference to this new workspace: `-- package.json ``` -The workspaces init also supports the `npm init -w ` -syntax, following the same set of rules explained earlier in the initial -**Description** section of this page. Similar to the previous example of -creating a new React-based project using -[`create-react-app`](https://npm.im/create-react-app), the following syntax -will make sure to create the new react app as a nested **workspace** within your -project and configure your `package.json` to recognize it as such: +The workspaces init also supports the `npm init -w ` syntax, following the same set of rules explained earlier in the initial +**Description** section of this page. +Similar to the previous example of creating a new React-based project using [`create-react-app`](https://npm.im/create-react-app), the following syntax will make sure to create the new react app as a nested **workspace** within your project and configure your `package.json` to recognize it as such: ```bash npm init -w packages/my-react-app react-app . ``` -This will make sure to generate your react app as expected, one important -consideration to have in mind is that `npm exec` is going to be run in the -context of the newly created folder for that workspace, and that's the reason -why in this example the initializer uses the initializer name followed with a -dot to represent the current directory in that context, e.g: `react-app .`: +This will make sure to generate your react app as expected, one important consideration to have in mind is that `npm exec` is going to be run in the context of the newly created folder for that workspace, and that's the reason why in this example the initializer uses the initializer name followed with a dot to represent the current directory in that context, e.g: `react-app .`: ``` . diff --git a/docs/lib/content/commands/npm-install-test.md b/docs/lib/content/commands/npm-install-test.md index 4a2798b41be29..33c988a6d82c7 100644 --- a/docs/lib/content/commands/npm-install-test.md +++ b/docs/lib/content/commands/npm-install-test.md @@ -10,8 +10,8 @@ description: Install package(s) and run tests ### Description -This command runs an `npm install` followed immediately by an `npm test`. It -takes exactly the same arguments as `npm install`. +This command runs an `npm install` followed immediately by an `npm test`. +It takes exactly the same arguments as `npm install`. ### Configuration diff --git a/docs/lib/content/commands/npm-install.md b/docs/lib/content/commands/npm-install.md index 1b783b1b13fc2..58ff90566f135 100644 --- a/docs/lib/content/commands/npm-install.md +++ b/docs/lib/content/commands/npm-install.md @@ -10,64 +10,56 @@ description: Install a package ### Description -This command installs a package and any packages that it depends on. If the -package has a package-lock, or an npm shrinkwrap file, or a yarn lock file, -the installation of dependencies will be driven by that, respecting the -following order of precedence: +This command installs a package and any packages that it depends on. +If the package has a package-lock or a yarn lock file, the installation of dependencies will be driven by that, respecting the following order of precedence: -* `npm-shrinkwrap.json` * `package-lock.json` * `yarn.lock` -See [package-lock.json](/configuring-npm/package-lock-json) and -[`npm shrinkwrap`](/commands/npm-shrinkwrap). +See [package-lock.json](/configuring-npm/package-lock-json). + +#### How `npm install` uses `package-lock.json` + +When you run `npm install` without arguments, npm compares `package.json` and `package-lock.json`: + +* **If the lockfile's resolved versions satisfy the `package.json` ranges:** npm uses the exact versions from `package-lock.json` to ensure reproducible builds across environments. + +* **If the ranges don't match:** npm resolves new versions that satisfy the `package.json` ranges and updates `package-lock.json` accordingly. This happens when you modify version ranges in `package.json` (e.g., changing `^7.0.0` to `^8.0.0`). Note that changing a range within the same major version (e.g., `^7.0.0` to `^7.1.0`) will only update the metadata in the lockfile if the currently installed version still satisfies the new range. + +In essence, `package-lock.json` locks your dependencies to specific versions, but `package.json` is the source of truth for acceptable version ranges. When the lockfile's versions satisfy the `package.json` ranges, the lockfile wins. When they conflict, `package.json` wins and the lockfile is updated. + +If you want to install packages while ensuring that `package.json` is not modified and that both files are strictly in sync, use [`npm ci`](/commands/npm-ci) instead. A `package` is: -* a) a folder containing a program described by a - [`package.json`](/configuring-npm/package-json) file +* a) a folder containing a program described by a [`package.json`](/configuring-npm/package-json) file * b) a gzipped tarball containing (a) * c) a url that resolves to (b) -* d) a `@` that is published on the registry (see - [`registry`](/using-npm/registry)) with (c) -* e) a `@` (see [`npm dist-tag`](/commands/npm-dist-tag)) that - points to (d) +* d) a `@` that is published on the registry (see [`registry`](/using-npm/registry)) with (c) +* e) a `@` (see [`npm dist-tag`](/commands/npm-dist-tag)) that points to (d) * f) a `` that has a "latest" tag satisfying (e) * g) a `` that resolves to (a) -Even if you never publish your package, you can still get a lot of benefits -of using npm if you just want to write a node program (a), and perhaps if -you also want to be able to easily install it elsewhere after packing it up -into a tarball (b). +Even if you never publish your package, you can still get a lot of benefits of using npm if you just want to write a node program (a), and perhaps if you also want to be able to easily install it elsewhere after packing it up into a tarball (b). * `npm install` (in a package directory, no arguments): Install the dependencies to the local `node_modules` folder. - In global mode (ie, with `-g` or `--global` appended to the command), - it installs the current package context (ie, the current working - directory) as a global package. + In global mode (ie, with `-g` or `--global` appended to the command), it installs the current package context (ie, the current working directory) as a global package. - By default, `npm install` will install all modules listed as - dependencies in [`package.json`](/configuring-npm/package-json). + By default, `npm install` will install all modules listed as dependencies in [`package.json`](/configuring-npm/package-json). - With the `--production` flag (or when the `NODE_ENV` environment - variable is set to `production`), npm will not install modules listed - in `devDependencies`. To install all modules listed in both - `dependencies` and `devDependencies` when `NODE_ENV` environment - variable is set to `production`, you can use `--production=false`. + With the `--production` flag (or when the `NODE_ENV` environment variable is set to `production`), npm will not install modules listed in `devDependencies`. + To install all modules listed in both `dependencies` and `devDependencies` when `NODE_ENV` environment variable is set to `production`, you can use `--production=false`. - > NOTE: The `--production` flag has no particular meaning when adding a - dependency to a project. + > NOTE: The `--production` flag has no particular meaning when adding a dependency to a project. * `npm install `: - If `` sits inside the root of your project, its dependencies will be installed and may - be hoisted to the top-level `node_modules` as they would for other - types of dependencies. If `` sits outside the root of your project, - *npm will not install the package dependencies* in the directory ``, - but it will create a symlink to ``. + If `` sits inside the root of your project, its dependencies will be installed and may be hoisted to the top-level `node_modules` as they would for other types of dependencies. + If `` sits outside the root of your project, *npm will not install the package dependencies* in the directory ``, but it will create a symlink to ``. > NOTE: If you want to install the content of a directory like a package from the registry instead of creating a link, you would need to use the `--install-links` option. @@ -80,19 +72,14 @@ into a tarball (b). * `npm install `: - Install a package that is sitting on the filesystem. Note: if you just - want to link a dev directory into your npm root, you can do this more - easily by using [`npm link`](/commands/npm-link). + Install a package that is sitting on the filesystem. + Note: if you just want to link a dev directory into your npm root, you can do this more easily by using [`npm link`](/commands/npm-link). Tarball requirements: - * The filename *must* use `.tar`, `.tar.gz`, or `.tgz` as the - extension. - * The package contents should reside in a subfolder inside the tarball - (usually it is called `package/`). npm strips one directory layer - when installing the package (an equivalent of `tar x - --strip-components=1` is run). - * The package must contain a `package.json` file with `name` and - `version` properties. + * The filename *must* use `.tar`, `.tar.gz`, or `.tgz` as the extension. + * The package contents should reside in a subfolder inside the tarball (usually it is called `package/`). + npm strips one directory layer when installing the package (an equivalent of `tar x --strip-components=1` is run). + * The package must contain a `package.json` file with `name` and `version` properties. Example: @@ -102,8 +89,8 @@ into a tarball (b). * `npm install `: - Fetch the tarball url, and then install it. In order to distinguish between - this and other options, the argument must start with "http://" or "https://" + Fetch the tarball url, and then install it. + In order to distinguish between this and other options, the argument must start with "http://" or "https://" Example: @@ -113,11 +100,13 @@ into a tarball (b). * `npm install [<@scope>/]`: - Do a `@` install, where `` is the "tag" config. (See - [`config`](/using-npm/config#tag). The config's default value is `latest`.) + Do a `@` install, where `` is the "tag" config. + (See [`config`](/using-npm/config#tag). + The config's default value is `latest`.) - In most cases, this will install the version of the modules tagged as - `latest` on the npm registry. + In most cases, this will install the version of the modules tagged as `latest` on the npm registry. + + **Note:** When installing by name without specifying a version or tag, npm prioritizes versions that match the current Node.js version based on the package's `engines` field. If the `latest` tag points to a version incompatible with your current Node.js version, npm will install the newest compatible version instead. To install a specific version regardless of `engines` compatibility, explicitly specify the version or tag: `npm install @latest`. Example: @@ -126,11 +115,10 @@ into a tarball (b). ``` `npm install` saves any specified packages into `dependencies` by default. - Additionally, you can control where and how they get saved with some - additional flags: + Additionally, you can control where and how they get saved with some additional flags: - * `-P, --save-prod`: Package will appear in your `dependencies`. This - is the default unless `-D` or `-O` are present. + * `-P, --save-prod`: Package will appear in your `dependencies`. + This is the default unless `-D` or `-O` are present. * `-D, --save-dev`: Package will appear in your `devDependencies`. @@ -141,26 +129,21 @@ into a tarball (b). * `--no-save`: Prevents saving to `dependencies`. - When using any of the above options to save dependencies to your - package.json, there are two additional, optional flags: + When using any of the above options to save dependencies to your package.json, there are two additional, optional flags: - * `-E, --save-exact`: Saved dependencies will be configured with an - exact version rather than using npm's default semver range operator. + * `-E, --save-exact`: Saved dependencies will be configured with an exact version rather than using npm's default semver range operator. - * `-B, --save-bundle`: Saved dependencies will also be added to your - `bundleDependencies` list. + * `-B, --save-bundle`: Saved dependencies will also be added to your `bundleDependencies` list. - Further, if you have an `npm-shrinkwrap.json` or `package-lock.json` - then it will be updated as well. + Further, if you have a `package-lock.json` then it will be updated as well. - `` is optional. The package will be downloaded from the registry - associated with the specified scope. If no registry is associated with - the given scope the default registry is assumed. See - [`scope`](/using-npm/scope). + `` is optional. + The package will be downloaded from the registry associated with the specified scope. + If no registry is associated with the given scope the default registry is assumed. + See [`scope`](/using-npm/scope). - Note: if you do not include the @-symbol on your scope name, npm will - interpret this as a GitHub repository instead, see below. Scopes names - must also be followed by a slash. + Note: if you do not include the @-symbol on your scope name, npm will interpret this as a GitHub repository instead, see below. + Scopes names must also be followed by a slash. Examples: @@ -174,19 +157,12 @@ into a tarball (b). npm install ansi-regex --save-bundle ``` - **Note**: If there is a file or folder named `` in the current - working directory, then it will try to install that, and only try to - fetch the package by name if it is not valid. - * `npm install @npm:`: - Install a package under a custom alias. Allows multiple versions of - a same-name package side-by-side, more convenient import names for - packages with otherwise long ones, and using git forks replacements - or forked npm packages as replacements. Aliasing works only on your - project and does not rename packages in transitive dependencies. - Aliases should follow the naming conventions stated in - [`validate-npm-package-name`](https://www.npmjs.com/package/validate-npm-package-name#naming-rules). + Install a package under a custom alias. + Allows multiple versions of a same-name package side-by-side, more convenient import names for packages with otherwise long ones, and using git forks replacements or forked npm packages as replacements. + Aliasing works only on your project and does not rename packages in transitive dependencies. + Aliases should follow the naming conventions stated in [`validate-npm-package-name`](https://www.npmjs.com/package/validate-npm-package-name#naming-rules). Examples: @@ -200,8 +176,7 @@ into a tarball (b). * `npm install [<@scope>/]@`: Install the version of the package that is referenced by the specified tag. - If the tag does not exist in the registry data for that package, then this - will fail. + If the tag does not exist in the registry data for that package, then this will fail. Example: @@ -212,8 +187,8 @@ into a tarball (b). * `npm install [<@scope>/]@`: - Install the specified version of the package. This will fail if the - version has not been published to the registry. + Install the specified version of the package. + This will fail if the version has not been published to the registry. Example: @@ -225,11 +200,9 @@ into a tarball (b). * `npm install [<@scope>/]@`: Install a version of the package matching the specified version range. - This will follow the same rules for resolving dependencies described in - [`package.json`](/configuring-npm/package-json). + This will follow the same rules for resolving dependencies described in [`package.json`](/configuring-npm/package-json). - Note that most version ranges must be put in quotes so that your shell - will treat it as a single argument. + Note that most version ranges must be put in quotes so that your shell will treat it as a single argument. Example: @@ -238,10 +211,19 @@ into a tarball (b). npm install @myorg/privatepackage@"16 - 17" ``` + **Prerelease versions:** By default, version ranges only match stable versions. To include prerelease versions, they must be explicitly specified in the range. Prerelease versions are tied to a specific version triple (major.minor.patch). For example, `^1.2.3-beta.1` will only match prereleases for `1.2.x`, not `1.3.x`. To match all prereleases for a major version, use a range like `^1.0.0-0`, which will include all `1.x.x` prereleases. + + Example: + + ```bash + npm install package@^1.2.3-beta.1 # Matches 1.2.3-beta.1, 1.2.3-beta.2, 1.2.4-beta.1, etc. + npm install package@^1.0.0-0 # Matches all 1.x.x prereleases and stable versions + ``` + * `npm install `: - Installs the package from the hosted git provider, cloning it with - `git`. For a full git remote url, only that URL will be attempted. + Installs the package from the hosted git provider, cloning it with `git`. + For a full git remote url, only that URL will be attempted. ```bash ://[[:]@][:][:][/][# | #semver:] @@ -250,23 +232,15 @@ into a tarball (b). `` is one of `git`, `git+ssh`, `git+http`, `git+https`, or `git+file`. - If `#` is provided, it will be used to clone exactly that - commit. If the commit-ish has the format `#semver:`, `` - can be any valid semver range or exact version, and npm will look for - any tags or refs matching that range in the remote repository, much as - it would for a registry dependency. If neither `#` or - `#semver:` is specified, then the default branch of the - repository is used. + If `#` is provided, it will be used to clone exactly that commit. + If the commit-ish has the format `#semver:`, `` can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. + If neither `#` or `#semver:` is specified, then the default branch of the repository is used. - If the repository makes use of submodules, those submodules will be - cloned as well. + If the repository makes use of submodules, those submodules will be cloned as well. - If the package being installed contains a `prepare` script, its - `dependencies` and `devDependencies` will be installed, and the prepare - script will be run, before the package is packaged and installed. + If the package being installed contains a `prepare` script, its `dependencies` and `devDependencies` will be installed, and the prepare script will be run, before the package is packaged and installed. - The following git environment variables are recognized by npm and will - be added to the environment when running git: + The following git environment variables are recognized by npm and will be added to the environment when running git: * `GIT_ASKPASS` * `GIT_EXEC_PATH` @@ -292,19 +266,13 @@ into a tarball (b). * `npm install /[#]`: * `npm install github:/[#]`: - Install the package at `https://github.com/githubname/githubrepo` by - attempting to clone it using `git`. + Install the package at `https://github.com/githubname/githubrepo` by attempting to clone it using `git`. - If `#` is provided, it will be used to clone exactly that - commit. If the commit-ish has the format `#semver:`, `` - can be any valid semver range or exact version, and npm will look for - any tags or refs matching that range in the remote repository, much as - it would for a registry dependency. If neither `#` or - `#semver:` is specified, then the default branch is used. + If `#` is provided, it will be used to clone exactly that commit. + If the commit-ish has the format `#semver:`, `` can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. + If neither `#` or `#semver:` is specified, then the default branch is used. - As with regular git dependencies, `dependencies` and `devDependencies` - will be installed if the package has a `prepare` script before the - package is done installing. + As with regular git dependencies, `dependencies` and `devDependencies` will be installed if the package has a `prepare` script before the package is done installing. Examples: @@ -315,13 +283,10 @@ into a tarball (b). * `npm install gist:[/][#|#semver:]`: - Install the package at `https://gist.github.com/gistID` by attempting to - clone it using `git`. The GitHub username associated with the gist is - optional and will not be saved in `package.json`. + Install the package at `https://gist.github.com/gistID` by attempting to clone it using `git`. + The GitHub username associated with the gist is optional and will not be saved in `package.json`. - As with regular git dependencies, `dependencies` and `devDependencies` will - be installed if the package has a `prepare` script before the package is - done installing. + As with regular git dependencies, `dependencies` and `devDependencies` will be installed if the package has a `prepare` script before the package is done installing. Example: @@ -331,19 +296,13 @@ into a tarball (b). * `npm install bitbucket:/[#]`: - Install the package at `https://bitbucket.org/bitbucketname/bitbucketrepo` - by attempting to clone it using `git`. + Install the package at `https://bitbucket.org/bitbucketname/bitbucketrepo` by attempting to clone it using `git`. - If `#` is provided, it will be used to clone exactly that - commit. If the commit-ish has the format `#semver:`, `` can - be any valid semver range or exact version, and npm will look for any tags - or refs matching that range in the remote repository, much as it would for a - registry dependency. If neither `#` or `#semver:` is - specified, then `master` is used. + If `#` is provided, it will be used to clone exactly that commit. + If the commit-ish has the format `#semver:`, `` can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. + If neither `#` or `#semver:` is specified, then `master` is used. - As with regular git dependencies, `dependencies` and `devDependencies` will - be installed if the package has a `prepare` script before the package is - done installing. + As with regular git dependencies, `dependencies` and `devDependencies` will be installed if the package has a `prepare` script before the package is done installing. Example: @@ -353,19 +312,13 @@ into a tarball (b). * `npm install gitlab:/[#]`: - Install the package at `https://gitlab.com/gitlabname/gitlabrepo` - by attempting to clone it using `git`. + Install the package at `https://gitlab.com/gitlabname/gitlabrepo` by attempting to clone it using `git`. - If `#` is provided, it will be used to clone exactly that - commit. If the commit-ish has the format `#semver:`, `` can - be any valid semver range or exact version, and npm will look for any tags - or refs matching that range in the remote repository, much as it would for a - registry dependency. If neither `#` or `#semver:` is - specified, then `master` is used. + If `#` is provided, it will be used to clone exactly that commit. + If the commit-ish has the format `#semver:`, `` can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. + If neither `#` or `#semver:` is specified, then `master` is used. - As with regular git dependencies, `dependencies` and `devDependencies` will - be installed if the package has a `prepare` script before the package is - done installing. + As with regular git dependencies, `dependencies` and `devDependencies` will be installed if the package has a `prepare` script before the package is done installing. Example: @@ -381,19 +334,16 @@ For example: npm install sax@">=0.1.0 <0.2.0" bench supervisor ``` -The `--tag` argument will apply to all of the specified install targets. If -a tag with the given name exists, the tagged version is preferred over -newer versions. +The `--tag` argument will apply to all of the specified install targets. +If a tag with the given name exists, the tagged version is preferred over newer versions. + +**Note:** The `--tag` option only affects packages specified on the command line. It does not override version ranges specified in `package.json`. For example, if `package.json` specifies `"foo": "^1.0.0"` and you run `npm install --tag beta`, npm will still install a version matching `^1.0.0` even if the `beta` tag points to a different version. To install a tagged version, specify the package explicitly: `npm install foo@beta`. -The `--dry-run` argument will report in the usual way what the install -would have done without actually installing anything. +The `--dry-run` argument will report in the usual way what the install would have done without actually installing anything. -The `--package-lock-only` argument will only update the -`package-lock.json`, instead of checking `node_modules` and downloading -dependencies. +The `--package-lock-only` argument will only update the `package-lock.json`, instead of checking `node_modules` and downloading dependencies. -The `-f` or `--force` argument will force npm to fetch remote resources -even if a local copy exists on disk. +The `-f` or `--force` argument will force npm to fetch remote resources even if a local copy exists on disk. ```bash npm install sax --force @@ -401,9 +351,8 @@ npm install sax --force ### Configuration -See the [`config`](/using-npm/config) help doc. Many of the configuration -params have some effect on installation, since that's most of what npm -does. +See the [`config`](/using-npm/config) help doc. +Many of the configuration params have some effect on installation, since that's most of what npm does. These are some of the most common options related to installation. @@ -411,8 +360,7 @@ These are some of the most common options related to installation. ### Algorithm -Given a `package{dep}` structure: `A{B,C}, B{C}, C{D}`, -the npm install algorithm produces: +Given a `package{dep}` structure: `A{B,C}, B{C}, C{D}`, the npm install algorithm produces: ```bash A @@ -421,9 +369,8 @@ A +-- D ``` -That is, the dependency from B to C is satisfied by the fact that A already -caused C to be installed at a higher level. D is still installed at the top -level because nothing conflicts with it. +That is, the dependency from B to C is satisfied by the fact that A already caused C to be installed at a higher level. +D is still installed at the top level because nothing conflicts with it. For `A{B,C}, B{C,D@1}, C{D@2}`, this algorithm produces: @@ -435,13 +382,10 @@ A +-- D@1 ``` -Because B's D@1 will be installed in the top-level, C now has to install -D@2 privately for itself. This algorithm is deterministic, but different -trees may be produced if two dependencies are requested for installation in -a different order. +Because B's D@1 will be installed in the top-level, C now has to install D@2 privately for itself. +This algorithm is deterministic, but different trees may be produced if two dependencies are requested for installation in a different order. -See [folders](/configuring-npm/folders) for a more detailed description of -the specific folder structures that npm creates. +See [folders](/configuring-npm/folders) for a more detailed description of the specific folder structures that npm creates. ### See Also @@ -457,6 +401,5 @@ the specific folder structures that npm creates. * [npm registry](/using-npm/registry) * [npm dist-tag](/commands/npm-dist-tag) * [npm uninstall](/commands/npm-uninstall) -* [npm shrinkwrap](/commands/npm-shrinkwrap) * [package.json](/configuring-npm/package-json) * [workspaces](/using-npm/workspaces) diff --git a/docs/lib/content/commands/npm-link.md b/docs/lib/content/commands/npm-link.md index 232e55ff9fcd9..347da3540b4a2 100644 --- a/docs/lib/content/commands/npm-link.md +++ b/docs/lib/content/commands/npm-link.md @@ -10,31 +10,23 @@ description: Symlink a package folder ### Description -This is handy for installing your own stuff, so that you can work on it and -test iteratively without having to continually rebuild. +This is handy for installing your own stuff, so that you can work on it and test iteratively without having to continually rebuild. Package linking is a two-step process. -First, `npm link` in a package folder with no arguments will create a -symlink in the global folder `{prefix}/lib/node_modules/` that -links to the package where the `npm link` command was executed. It will -also link any bins in the package to `{prefix}/bin/{name}`. Note that -`npm link` uses the global prefix (see `npm prefix -g` for its value). +First, `npm link` in a package folder with no arguments will create a symlink in the global folder `{prefix}/lib/node_modules/` that links to the package where the `npm link` command was executed. +It will also link any bins in the package to `{prefix}/bin/{name}`. +Note that `npm link` uses the global prefix (see `npm prefix -g` for its value). -Next, in some other location, `npm link package-name` will create a -symbolic link from globally-installed `package-name` to `node_modules/` of -the current folder. +Next, in some other location, `npm link package-name` will create a symbolic link from globally-installed `package-name` to `node_modules/` of the current folder. -Note that `package-name` is taken from `package.json`, _not_ from the -directory name. +Note that `package-name` is taken from `package.json`, _not_ from the directory name. -The package name can be optionally prefixed with a scope. See -[`scope`](/using-npm/scope). The scope must be preceded by an @-symbol and -followed by a slash. +The package name can be optionally prefixed with a scope. +See [`scope`](/using-npm/scope). +The scope must be preceded by an @-symbol and followed by a slash. -When creating tarballs for `npm publish`, the linked packages are -"snapshotted" to their current state by resolving the symbolic links, if -they are included in `bundleDependencies`. +When creating tarballs for `npm publish`, the linked packages are "snapshotted" to their current state by resolving the symbolic links, if they are included in `bundleDependencies`. For example: @@ -46,11 +38,11 @@ npm link redis # link-install the package ``` Now, any changes to `~/projects/node-redis` will be reflected in -`~/projects/node-bloggy/node_modules/node-redis/`. Note that the link -should be to the package name, not the directory name for that package. +`~/projects/node-bloggy/node_modules/node-redis/`. +Note that the link should be to the package name, not the directory name for that package. -You may also shortcut the two steps in one. For example, to do the -above use-case in a shorter way: +You may also shortcut the two steps in one. +For example, to do the above use-case in a shorter way: ```bash cd ~/projects/node-bloggy # go into the dir of your main project @@ -64,14 +56,12 @@ The second line is the equivalent of doing: npm link redis ``` -That is, it first creates a global link, and then links the global -installation target into your project's `node_modules` folder. +That is, it first creates a global link, and then links the global installation target into your project's `node_modules` folder. Note that in this case, you are referring to the directory name, `node-redis`, rather than the package name `redis`. -If your linked package is scoped (see [`scope`](/using-npm/scope)) your -link command must include that scope, e.g. +If your linked package is scoped (see [`scope`](/using-npm/scope)) your link command must include that scope, e.g. ```bash npm link @myorg/privatepackage @@ -79,30 +69,19 @@ npm link @myorg/privatepackage ### Caveat -Note that package dependencies linked in this way are _not_ saved to -`package.json` by default, on the assumption that the intention is to have -a link stand in for a regular non-link dependency. Otherwise, for example, -if you depend on `redis@^3.0.1`, and ran `npm link redis`, it would replace -the `^3.0.1` dependency with `file:../path/to/node-redis`, which you -probably don't want! Additionally, other users or developers on your -project would run into issues if they do not have their folders set up -exactly the same as yours. +Note that package dependencies linked in this way are _not_ saved to `package.json` by default, on the assumption that the intention is to have a link stand in for a regular non-link dependency. +Otherwise, for example, if you depend on `redis@^3.0.1`, and ran `npm link redis`, it would replace the `^3.0.1` dependency with `file:../path/to/node-redis`, which you probably don't want! Additionally, other users or developers on your project would run into issues if they do not have their folders set up exactly the same as yours. -If you are adding a _new_ dependency as a link, you should add it to the -relevant metadata by running `npm install --package-lock-only`. +If you are adding a _new_ dependency as a link, you should add it to the relevant metadata by running `npm install --package-lock-only`. -If you _want_ to save the `file:` reference in your `package.json` and -`package-lock.json` files, you can use `npm link --save` to do so. +If you _want_ to save the `file:` reference in your `package.json` and `package-lock.json` files, you can use `npm link --save` to do so. ### Workspace Usage -`npm link --workspace ` will link the relevant package as a -dependency of the specified workspace(s). Note that It may actually be -linked into the parent project's `node_modules` folder, if there are no -conflicting dependencies. +`npm link --workspace ` will link the relevant package as a dependency of the specified workspace(s). +Note that It may actually be linked into the parent project's `node_modules` folder, if there are no conflicting dependencies. -`npm link --workspace ` will create a global link to the specified -workspace(s). +`npm link --workspace ` will create a global link to the specified workspace(s). ### Configuration diff --git a/docs/lib/content/commands/npm-ll.md b/docs/lib/content/commands/npm-ll.md new file mode 100644 index 0000000000000..cceb4284592ef --- /dev/null +++ b/docs/lib/content/commands/npm-ll.md @@ -0,0 +1,21 @@ +--- +title: npm-ll +section: 1 +description: List installed packages +--- + +### Synopsis + + + +### Description + +List installed packages + +### Configuration + + + +### See Also + +* [npm help config](/commands/npm-config) diff --git a/docs/lib/content/commands/npm-login.md b/docs/lib/content/commands/npm-login.md index a3f416e5042e9..18d776e39a19b 100644 --- a/docs/lib/content/commands/npm-login.md +++ b/docs/lib/content/commands/npm-login.md @@ -11,20 +11,20 @@ description: Login to a registry user account ### Description Verify a user in the specified registry, and save the credentials to the -`.npmrc` file. If no registry is specified, the default registry will be -used (see [`config`](/using-npm/config)). +`.npmrc` file. +If no registry is specified, the default registry will be used (see [`config`](/using-npm/config)). -When using `legacy` for your `auth-type`, the username and password, are -read in from prompts. +When you run `npm login`, the CLI automatically generates a legacy token of `publish` type. +For more information, see [About legacy tokens](/about-access-tokens#about-legacy-tokens). + +When using `legacy` for your `auth-type`, the username and password, are read in from prompts. To reset your password, go to To change your email address, go to -You may use this command multiple times with the same user account to -authorize on a new machine. When authenticating on a new machine, -the username, password and email address must all match with -your existing record. +You may use this command multiple times with the same user account to authorize on a new machine. +When authenticating on a new machine, the username, password and email address must all match with your existing record. ### Configuration diff --git a/docs/lib/content/commands/npm-logout.md b/docs/lib/content/commands/npm-logout.md index 61f0219a19e11..05cf90b67c3f4 100644 --- a/docs/lib/content/commands/npm-logout.md +++ b/docs/lib/content/commands/npm-logout.md @@ -10,16 +10,13 @@ description: Log out of the registry ### Description -When logged into a registry that supports token-based authentication, tell -the server to end this token's session. This will invalidate the token -everywhere you're using it, not just for the current environment. +When logged into a registry that supports token-based authentication, tell the server to end this token's session. +This will invalidate the token everywhere you're using it, not just for the current environment. -When logged into a legacy registry that uses username and password -authentication, this will clear the credentials in your user configuration. +When logged into a legacy registry that uses username and password authentication, this will clear the credentials in your user configuration. In this case, it will _only_ affect the current environment. -If `--scope` is provided, this will find the credentials for the registry -connected to that scope, if set. +If `--scope` is provided, this will find the credentials for the registry connected to that scope, if set. ### Configuration @@ -27,7 +24,7 @@ connected to that scope, if set. ### See Also -* [npm adduser](/commands/npm-adduser) +* [npm login](/commands/npm-login) * [npm registry](/using-npm/registry) * [npm config](/commands/npm-config) * [npm whoami](/commands/npm-whoami) diff --git a/docs/lib/content/commands/npm-ls.md b/docs/lib/content/commands/npm-ls.md index 04c4f2cb6f1e2..e2fafbc7807fb 100644 --- a/docs/lib/content/commands/npm-ls.md +++ b/docs/lib/content/commands/npm-ls.md @@ -10,17 +10,13 @@ description: List installed packages ### Description -This command will print to stdout all the versions of packages that are -installed, as well as their dependencies when `--all` is specified, in a -tree structure. +This command will print to stdout all the versions of packages that are installed, as well as their dependencies when `--all` is specified, in a tree structure. -Note: to get a "bottoms up" view of why a given package is included in the -tree at all, use [`npm explain`](/commands/npm-explain). +Note: to get a "bottoms up" view of why a given package is included in the tree at all, use [`npm explain`](/commands/npm-explain). -Positional arguments are `name@version-range` identifiers, which will limit -the results to only the paths to the packages named. Note that nested -packages will *also* show the paths to the specified packages. For -example, running `npm ls promzard` in npm's source tree will show: +Positional arguments are `name@version-range` identifiers, which will limit the results to only the paths to the packages named. +Note that nested packages will *also* show the paths to the specified packages. +For example, running `npm ls promzard` in npm's source tree will show: ```bash npm@@VERSION@ /path/to/npm @@ -30,43 +26,12 @@ npm@@VERSION@ /path/to/npm It will print out extraneous, missing, and invalid packages. -If a project specifies git urls for dependencies these are shown -in parentheses after the `name@version` to make it easier for users to -recognize potential forks of a project. +If a project specifies git urls for dependencies these are shown in parentheses after the `name@version` to make it easier for users to recognize potential forks of a project. -The tree shown is the logical dependency tree, based on package -dependencies, not the physical layout of your `node_modules` folder. +The tree shown is the logical dependency tree, based on package dependencies, not the physical layout of your `node_modules` folder. When run as `ll` or `la`, it shows extended information by default. -### Note: Design Changes Pending - -The `npm ls` command's output and behavior made a _ton_ of sense when npm -created a `node_modules` folder that naively nested every dependency. In -such a case, the logical dependency graph and physical tree of packages on -disk would be roughly identical. - -With the advent of automatic install-time deduplication of dependencies in -npm v3, the `ls` output was modified to display the logical dependency -graph as a tree structure, since this was more useful to most users. -However, without using `npm ls -l`, it became impossible to show _where_ a -package was actually installed much of the time! - -With the advent of automatic installation of `peerDependencies` in npm v7, -this gets even more curious, as `peerDependencies` are logically -"underneath" their dependents in the dependency graph, but are always -physically at or above their location on disk. - -Also, in the years since npm got an `ls` command (in version 0.0.2!), -dependency graphs have gotten much larger as a general rule. Therefore, in -order to avoid dumping an excessive amount of content to the terminal, `npm -ls` now only shows the _top_ level dependencies, unless `--all` is -provided. - -A thorough re-examination of the use cases, intention, behavior, and output -of this command, is currently underway. Expect significant changes to at -least the default human-readable `npm ls` output in npm v8. - ### Configuration diff --git a/docs/lib/content/commands/npm-org.md b/docs/lib/content/commands/npm-org.md index cc12bf9573a84..3cf6f01dde7a3 100644 --- a/docs/lib/content/commands/npm-org.md +++ b/docs/lib/content/commands/npm-org.md @@ -48,9 +48,8 @@ $ npm org ls my-org @mx-santos ### Description -You can use the `npm org` commands to manage and view users of an -organization. It supports adding and removing users, changing their roles, -listing them, and finding specific ones and their roles. +You can use the `npm org` commands to manage and view users of an organization. +It supports adding and removing users, changing their roles, listing them, and finding specific ones and their roles. ### Configuration diff --git a/docs/lib/content/commands/npm-outdated.md b/docs/lib/content/commands/npm-outdated.md index c4d39a64f38b4..fb5db63d12d4b 100644 --- a/docs/lib/content/commands/npm-outdated.md +++ b/docs/lib/content/commands/npm-outdated.md @@ -10,38 +10,26 @@ description: Check for outdated packages ### Description -This command will check the registry to see if any (or, specific) installed -packages are currently outdated. +This command will check the registry to see if any (or, specific) installed packages are currently outdated. -By default, only the direct dependencies of the root project and direct -dependencies of your configured *workspaces* are shown. +By default, only the direct dependencies of the root project and direct dependencies of your configured *workspaces* are shown. Use `--all` to find all outdated meta-dependencies as well. In the output: -* `wanted` is the maximum version of the package that satisfies the semver - range specified in `package.json`. If there's no available semver range - (i.e. you're running `npm outdated --global`, or the package isn't - included in `package.json`), then `wanted` shows the currently-installed - version. +* `wanted` is the maximum version of the package that satisfies the semver range specified in `package.json`. + If there's no available semver range (i.e. you're running `npm outdated --global`, or the package isn't included in `package.json`), then `wanted` shows the latest version. * `latest` is the version of the package tagged as latest in the registry. - Running `npm publish` with no special configuration will publish the - package with a dist-tag of `latest`. This may or may not be the maximum - version of the package, or the most-recently published version of the - package, depending on how the package's developer manages the latest - [dist-tag](/commands/npm-dist-tag). + Running `npm publish` with no special configuration will publish the package with a dist-tag of `latest`. + This may or may not be the maximum version of the package, or the most-recently published version of the package, depending on how the package's developer manages the latest [dist-tag](/commands/npm-dist-tag). * `location` is where in the physical tree the package is located. * `depended by` shows which package depends on the displayed dependency -* `package type` (when using `--long` / `-l`) tells you whether this - package is a `dependency` or a dev/peer/optional dependency. Packages not - included in `package.json` are always marked `dependencies`. -* `homepage` (when using `--long` / `-l`) is the `homepage` value contained - in the package's packument -* Red means there's a newer version matching your semver requirements, so - you should update now. -* Yellow indicates that there's a newer version _above_ your semver - requirements (usually new major, or new 0.x minor) so proceed with - caution. +* `package type` (when using `--long` / `-l`) tells you whether this package is a `dependency` or a dev/peer/optional dependency. + Packages not included in `package.json` are always marked `dependencies`. +* `homepage` (when using `--long` / `-l`) is the `homepage` value contained in the package's packument +* `depended by location` (when using `--long` / `-l`) shows location of the package that depends on the displayed dependency +* Red means there's a newer version matching your semver requirements, so you should update now. +* Yellow indicates that there's a newer version _above_ your semver requirements (usually new major, or new 0.x minor) so proceed with caution. ### An example @@ -67,20 +55,14 @@ With these `dependencies`: A few things to note: -* `glob` requires `^5`, which prevents npm from installing `glob@6`, which - is outside the semver range. -* Git dependencies will always be reinstalled, because of how they're - specified. The installed committish might satisfy the dependency - specifier (if it's something immutable, like a commit SHA), or it might - not, so `npm outdated` and `npm update` have to fetch Git repos to check. - This is why currently doing a reinstall of a Git dependency always forces - a new clone and install. -* `npm@3.5.2` is marked as "wanted", but "latest" is `npm@3.5.1` because - npm uses dist-tags to manage its `latest` and `next` release channels. - `npm update` will install the _newest_ version, but `npm install npm` - (with no semver range) will install whatever's tagged as `latest`. -* `once` is just plain out of date. Reinstalling `node_modules` from - scratch or running `npm update` will bring it up to spec. +* `glob` requires `^5`, which prevents npm from installing `glob@6`, which is outside the semver range. +* Git dependencies will always be reinstalled, because of how they're specified. + The installed committish might satisfy the dependency specifier (if it's something immutable, like a commit SHA), or it might not, so `npm outdated` and `npm update` have to fetch Git repos to check. + This is why currently doing a reinstall of a Git dependency always forces a new clone and install. +* `npm@3.5.2` is marked as "wanted", but "latest" is `npm@3.5.1` because npm uses dist-tags to manage its `latest` and `next` release channels. + `npm update` will install the _newest_ version, but `npm install npm` (with no semver range) will install whatever's tagged as `latest`. +* `once` is just plain out of date. + Reinstalling `node_modules` from scratch or running `npm update` will bring it up to spec. ### Configuration diff --git a/docs/lib/content/commands/npm-owner.md b/docs/lib/content/commands/npm-owner.md index 9ff67b5784c59..32f9d28d6db20 100644 --- a/docs/lib/content/commands/npm-owner.md +++ b/docs/lib/content/commands/npm-owner.md @@ -12,20 +12,18 @@ description: Manage package owners Manage ownership of published packages. -* ls: List all the users who have access to modify a package and push new - versions. Handy when you need to know who to bug for help. -* add: Add a new user as a maintainer of a package. This user is enabled - to modify metadata, publish new versions, and add other owners. -* rm: Remove a user from the package owner list. This immediately revokes - their privileges. +* ls: List all the users who have access to modify a package and push new versions. +Handy when you need to know who to bug for help. +* add: Add a new user as a maintainer of a package. +This user is enabled to modify metadata, publish new versions, and add other owners. +* rm: Remove a user from the package owner list. +This immediately revokes their privileges. -Note that there is only one level of access. Either you can modify a package, -or you can't. Future versions may contain more fine-grained access levels, but -that is not implemented at this time. +Note that there is only one level of access. +Either you can modify a package, or you can't. +Future versions may contain more fine-grained access levels, but that is not implemented at this time. -If you have two-factor authentication enabled with `auth-and-writes` (see -[`npm-profile`](/commands/npm-profile)) then you'll need to go through a second factor -flow when changing ownership or include an otp on the command line with `--otp`. +If you have two-factor authentication enabled with `auth-and-writes` (see [`npm-profile`](/commands/npm-profile)) then you'll need to go through a second factor flow when changing ownership or include an otp on the command line with `--otp`. ### Configuration @@ -37,4 +35,4 @@ flow when changing ownership or include an otp on the command line with `--otp`. * [npm profile](/commands/npm-profile) * [npm publish](/commands/npm-publish) * [npm registry](/using-npm/registry) -* [npm adduser](/commands/npm-adduser) +* [npm login](/commands/npm-login) diff --git a/docs/lib/content/commands/npm-pack.md b/docs/lib/content/commands/npm-pack.md index 0793ee2d39217..b5f39bcc1ead0 100644 --- a/docs/lib/content/commands/npm-pack.md +++ b/docs/lib/content/commands/npm-pack.md @@ -14,14 +14,9 @@ description: Create a tarball from a package ### Description -For anything that's installable (that is, a package folder, tarball, -tarball url, git url, name@tag, name@version, name, or scoped name), this -command will fetch it to the cache, copy the tarball to the current working -directory as `-.tgz`, and then write the filenames out to -stdout. - -If the same package is specified multiple times, then the file will be -overwritten the second time. +For anything that's installable (that is, a package folder, tarball, tarball url, git url, name@tag, name@version, name, or scoped name), this command will fetch it to the cache, copy the tarball to the current working directory as `-.tgz`, and then write the filenames out to stdout. + +If the same package is specified multiple times, then the file will be overwritten the second time. If no arguments are supplied, then npm packs the current package folder. diff --git a/docs/lib/content/commands/npm-patch.md b/docs/lib/content/commands/npm-patch.md new file mode 100644 index 0000000000000..030c414f4d6ac --- /dev/null +++ b/docs/lib/content/commands/npm-patch.md @@ -0,0 +1,69 @@ +--- +title: npm-patch +section: 1 +description: Apply local patches to installed dependencies +--- + +### Synopsis + + + +### Description + +`npm patch` lets you apply small, local modifications to an installed +dependency and have them re-applied automatically on every install. Patches +are declared in the `patchedDependencies` field of your root `package.json`, +stored as plain unified diffs under the `patches/` directory, and recorded with +a content hash in `package-lock.json`. + +Because patches are applied during the install itself, they work regardless of +`install-strategy`, apply to transitive dependencies, and are **not** disabled +by `--ignore-scripts`. + +The bare form `npm patch ` is shorthand for `npm patch add `. A +package literally named like a subcommand must use the explicit form, e.g. +`npm patch add add`. + +* `npm patch add [@]` + + Prepares a package for editing. npm extracts a clean copy of the resolved + package tarball into a temporary directory outside `node_modules` and prints + its path. Edit the files there, then run `npm patch commit`. + + If more than one version of `` is installed, re-run with an exact + selector such as `npm patch add lodash@4.17.21`. + +* `npm patch commit ` + + Diffs the edited directory against a clean copy of the original tarball, + writes the unified diff to `/@.patch`, adds the + entry to `patchedDependencies`, and updates `package-lock.json`. + +* `npm patch ls` + + Lists registered patches and how many installed nodes each one matches. + +* `npm patch rm [@]` + + Removes the matching entries from `patchedDependencies`, deletes the patch + file when no other entry references it, and updates `package-lock.json`. If + `` is omitted, all entries for `` are removed. + +### Failure modes + +By default any patch problem is a hard error that aborts the install: a patch +that fails to apply, a registered patch that matches no installed package, a +missing patch file, or a patch whose hash does not match the lockfile. + +Two CLI-only flags relax this for one-off cases: `--allow-unused-patches` and +`--ignore-patch-failures`. + +### Configuration + + +## See Also + +* [npm install](/commands/npm-install) +* [npm ci](/commands/npm-ci) +* [package-lock.json](/configuring-npm/package-lock-json) +* [config](/commands/npm-config) diff --git a/docs/lib/content/commands/npm-pkg.md b/docs/lib/content/commands/npm-pkg.md index ae49409f81f2e..403b8f93cacc7 100644 --- a/docs/lib/content/commands/npm-pkg.md +++ b/docs/lib/content/commands/npm-pkg.md @@ -11,13 +11,9 @@ description: Manages your package.json ### Description A command that automates the management of `package.json` files. -`npm pkg` provide 3 different sub commands that allow you to modify or retrieve -values for given object keys in your `package.json`. +`npm pkg` provide 3 different sub commands that allow you to modify or retrieve values for given object keys in your `package.json`. -The syntax to retrieve and set fields is a dot separated representation of -the nested object properties to be found within your `package.json`, it's the -same notation used in [`npm view`](/commands/npm-view) to retrieve information -from the registry manifest, below you can find more examples on how to use it. +The syntax to retrieve and set fields is a dot separated representation of the nested object properties to be found within your `package.json`, it's the same notation used in [`npm view`](/commands/npm-view) to retrieve information from the registry manifest, below you can find more examples on how to use it. Returned values are always in **json** format. @@ -25,8 +21,7 @@ Returned values are always in **json** format. Retrieves a value `key`, defined in your `package.json` file. - For example, in order to retrieve the name of the current package, you - can run: + For example, in order to retrieve the name of the current package, you can run: ```bash npm pkg get name @@ -38,32 +33,29 @@ Returned values are always in **json** format. npm pkg get name version ``` - You can view child fields by separating them with a period. To retrieve - the value of a test `script` value, you would run the following command: + You can view child fields by separating them with a period. + To retrieve the value of a test `script` value, you would run the following command: ```bash npm pkg get scripts.test ``` - For fields that are arrays, requesting a non-numeric field will return - all of the values from the objects in the list. For example, to get all - the contributor emails for a package, you would run: + For fields that are arrays, requesting a non-numeric field will return all of the values from the objects in the list. + For example, to get all the contributor emails for a package, you would run: ```bash npm pkg get contributors.email ``` - You may also use numeric indices in square braces to specifically select - an item in an array field. To just get the email address of the first - contributor in the list, you can run: + You may also use numeric indices in square braces to specifically select an item in an array field. + To just get the email address of the first contributor in the list, you can run: ```bash npm pkg get contributors[0].email ``` - For complex fields you can also name a property in square brackets - to specifically select a child field. This is especially helpful - with the exports object: + For complex fields you can also name a property in square brackets to specifically select a child field. + This is especially helpful with the exports object: ```bash npm pkg get "exports[.].require" @@ -71,19 +63,12 @@ Returned values are always in **json** format. * `npm pkg set =` - Sets a `value` in your `package.json` based on the `field` value. When - saving to your `package.json` file the same set of rules used during - `npm install` and other cli commands that touches the `package.json` file - are used, making sure to respect the existing indentation and possibly - applying some validation prior to saving values to the file. + Sets a `value` in your `package.json` based on the `field` value. + When saving to your `package.json` file the same set of rules used during `npm install` and other cli commands that touches the `package.json` file are used, making sure to respect the existing indentation and possibly applying some validation prior to saving values to the file. - The same syntax used to retrieve values from your package can also be used - to define new properties or overriding existing ones, below are some - examples of how the dot separated syntax can be used to edit your - `package.json` file. + The same syntax used to retrieve values from your package can also be used to define new properties or overriding existing ones, below are some examples of how the dot separated syntax can be used to edit your `package.json` file. - Defining a new bin named `mynewcommand` in your `package.json` that points - to a file `cli.js`: + Defining a new bin named `mynewcommand` in your `package.json` that points to a file `cli.js`: ```bash npm pkg set bin.mynewcommand=cli.js @@ -95,23 +80,19 @@ Returned values are always in **json** format. npm pkg set description='Awesome package' engines.node='>=10' ``` - It's also possible to add to array values, for example to add a new - contributor entry: + It's also possible to add to array values, for example to add a new contributor entry: ```bash npm pkg set contributors[0].name='Foo' contributors[0].email='foo@bar.ca' ``` - You may also append items to the end of an array using the special - empty bracket notation: + You may also append items to the end of an array using the special empty bracket notation: ```bash npm pkg set contributors[].name='Foo' contributors[].name='Bar' ``` - It's also possible to parse values as json prior to saving them to your - `package.json` file, for example in order to set a `"private": true` - property: + It's also possible to parse values as json prior to saving them to your `package.json` file, for example in order to set a `"private": true` property: ```bash npm pkg set private=true --json @@ -127,9 +108,8 @@ Returned values are always in **json** format. Deletes a `key` from your `package.json` - The same syntax used to set values from your package can also be used - to remove existing ones. For example, in order to remove a script named - build: + The same syntax used to set values from your package can also be used to remove existing ones. + For example, in order to remove a script named build: ```bash npm pkg delete scripts.build @@ -137,28 +117,20 @@ Returned values are always in **json** format. * `npm pkg fix` - Auto corrects common errors in your `package.json`. npm already - does this during `publish`, which leads to subtle (mostly harmless) - differences between the contents of your `package.json` file and the - manifest that npm uses during installation. + Auto corrects common errors in your `package.json`. + npm already does this during `publish`, which leads to subtle (mostly harmless) differences between the contents of your `package.json` file and the manifest that npm uses during installation. ### Workspaces support -You can set/get/delete items across your configured workspaces by using the -[`workspace`](/using-npm/config#workspace) or -[`workspaces`](/using-npm/config#workspaces) config options. +You can set/get/delete items across your configured workspaces by using the [`workspace`](/using-npm/config#workspace) or [`workspaces`](/using-npm/config#workspaces) config options. -For example, setting a `funding` value across all configured workspaces -of a project: +For example, setting a `funding` value across all configured workspaces of a project: ```bash npm pkg set funding=https://example.com --ws ``` -When using `npm pkg get` to retrieve info from your configured workspaces, the -returned result will be in a json format in which top level keys are the -names of each workspace, the values of these keys will be the result values -returned from each of the configured workspaces, e.g: +When using `npm pkg get` to retrieve info from your configured workspaces, the returned result will be in a json format in which top level keys are the names of each workspace, the values of these keys will be the result values returned from each of the configured workspaces, e.g: ``` npm pkg get name version --ws diff --git a/docs/lib/content/commands/npm-prefix.md b/docs/lib/content/commands/npm-prefix.md index 913e7eea3a7e8..b038cc20e2f51 100644 --- a/docs/lib/content/commands/npm-prefix.md +++ b/docs/lib/content/commands/npm-prefix.md @@ -10,12 +10,11 @@ description: Display prefix ### Description -Print the local prefix to standard output. This is the closest parent directory -to contain a `package.json` file or `node_modules` directory, unless `-g` is -also specified. +Print the local prefix to standard output. +This is the closest parent directory to contain a `package.json` file or `node_modules` directory, unless `-g` is also specified. -If `-g` is specified, this will be the value of the global prefix. See -[`npm config`](/commands/npm-config) for more detail. +If `-g` is specified, this will be the value of the global prefix. +See [`npm config`](/commands/npm-config) for more detail. ### Example diff --git a/docs/lib/content/commands/npm-profile.md b/docs/lib/content/commands/npm-profile.md index ba6613393d736..f8cd1d327960d 100644 --- a/docs/lib/content/commands/npm-profile.md +++ b/docs/lib/content/commands/npm-profile.md @@ -10,12 +10,11 @@ description: Change settings on your registry profile ### Description -Change your profile information on the registry. Note that this command -depends on the registry implementation, so third-party registries may not -support this interface. +Change your profile information on the registry. +Note that this command depends on the registry implementation, so third-party registries may not support this interface. -* `npm profile get []`: Display all of the properties of your - profile, or one or more specific properties. It looks like: +* `npm profile get []`: Display all of the properties of your profile, or one or more specific properties. +It looks like: ``` name: example @@ -23,30 +22,24 @@ email: e@example.com (verified) two-factor auth: auth-and-writes fullname: Example User homepage: -freenode: -twitter: github: created: 2015-02-26T01:38:35.892Z updated: 2017-10-02T21:29:45.922Z ``` -* `npm profile set `: Set the value of a profile - property. You can set the following properties this way: email, fullname, - homepage, freenode, twitter, github +* `npm profile set `: Set the value of a profile property. +You can set the following properties this way: email, fullname, homepage, github -* `npm profile set password`: Change your password. This is interactive, - you'll be prompted for your current password and a new password. You'll - also be prompted for an OTP if you have two-factor authentication - enabled. +* `npm profile set password`: Change your password. +This is interactive, you'll be prompted for your current password and a new password. +You'll also be prompted for an OTP if you have two-factor authentication enabled. -* `npm profile enable-2fa [auth-and-writes|auth-only]`: Enables two-factor - authentication. Defaults to `auth-and-writes` mode. Modes are: - * `auth-only`: Require an OTP when logging in or making changes to your - account's authentication. The OTP will be required on both the website - and the command line. - * `auth-and-writes`: Requires an OTP at all the times `auth-only` does, - and also requires one when publishing a module, setting the `latest` - dist-tag, or changing access via `npm access` and `npm owner`. +* `npm profile enable-2fa [auth-and-writes|auth-only]`: Enables two-factor authentication. +Defaults to `auth-and-writes` mode. +Modes are: + * `auth-only`: Require an OTP when logging in or making changes to your account's authentication. +The OTP will be required on both the website and the command line. + * `auth-and-writes`: Requires an OTP at all the times `auth-only` does, and also requires one when publishing a module, setting the `latest` dist-tag, or changing access via `npm access` and `npm owner`. * `npm profile disable-2fa`: Disables two-factor authentication. @@ -60,7 +53,7 @@ Some of these commands may not be available on non npmjs.com registries. ### See Also -* [npm adduser](/commands/npm-adduser) +* [npm login](/commands/npm-login) * [npm registry](/using-npm/registry) * [npm config](/commands/npm-config) * [npmrc](/configuring-npm/npmrc) diff --git a/docs/lib/content/commands/npm-prune.md b/docs/lib/content/commands/npm-prune.md index d1f48a67be1bc..0bce8d7bff03a 100644 --- a/docs/lib/content/commands/npm-prune.md +++ b/docs/lib/content/commands/npm-prune.md @@ -10,25 +10,19 @@ description: Remove extraneous packages ### Description -This command removes "extraneous" packages. If a package name is provided, -then only packages matching one of the supplied names are removed. +This command removes "extraneous" packages. +If a package name is provided, then only packages matching one of the supplied names are removed. -Extraneous packages are those present in the `node_modules` folder that are -not listed as any package's dependency list. +Extraneous packages are those present in the `node_modules` folder that are not listed as any package's dependency list. -If the `--omit=dev` flag is specified or the `NODE_ENV` environment -variable is set to `production`, this command will remove the packages -specified in your `devDependencies`. +If the `--omit=dev` flag is specified or the `NODE_ENV` environment variable is set to `production`, this command will remove the packages specified in your `devDependencies`. If the `--dry-run` flag is used then no changes will actually be made. -If the `--json` flag is used, then the changes `npm prune` made (or would -have made with `--dry-run`) are printed as a JSON object. +If the `--json` flag is used, then the changes `npm prune` made (or would have made with `--dry-run`) are printed as a JSON object. -In normal operation, extraneous modules are pruned automatically, so you'll -only need this command with the `--production` flag. However, in the real -world, operation is not always "normal". When crashes or mistakes happen, -this command can help clean up any resulting garbage. +In normal operation, extraneous modules are pruned automatically, so you'll only need this command with the `--production` flag. +However, in the real world, operation is not always "normal". When crashes or mistakes happen, this command can help clean up any resulting garbage. ### Configuration diff --git a/docs/lib/content/commands/npm-publish.md b/docs/lib/content/commands/npm-publish.md index 7c97401440670..98c2960992ceb 100644 --- a/docs/lib/content/commands/npm-publish.md +++ b/docs/lib/content/commands/npm-publish.md @@ -12,76 +12,83 @@ description: Publish a package Publishes a package to the registry so that it can be installed by name. -By default npm will publish to the public registry. This can be -overridden by specifying a different default registry or using a -[`scope`](/using-npm/scope) in the name, combined with a -scope-configured registry (see -[`package.json`](/configuring-npm/package-json)). +### Examples +Publish the package in the current directory: -A `package` is interpreted the same way as other commands (like -`npm install`) and can be: +```bash +npm publish +``` -* a) a folder containing a program described by a - [`package.json`](/configuring-npm/package-json) file +Publish a specific workspace: + +```bash +npm publish --workspace= +``` + +Publish multiple workspaces: + +```bash +npm publish --workspace=workspace-a --workspace=workspace-b +``` + +Publish all workspaces: + +```bash +npm publish --workspaces +``` + +By default npm will publish to the public registry. +This can be overridden by specifying a different default registry or using a [`scope`](/using-npm/scope) in the name, combined with a scope-configured registry (see [`package.json`](/configuring-npm/package-json)). + + +A `package` is interpreted the same way as other commands (like `npm install`) and can be: + +* a) a folder containing a program described by a [`package.json`](/configuring-npm/package-json) file * b) a gzipped tarball containing (a) * c) a url that resolves to (b) -* d) a `@` that is published on the registry (see - [`registry`](/using-npm/registry)) with (c) -* e) a `@` (see [`npm dist-tag`](/commands/npm-dist-tag)) that - points to (d) +* d) a `@` that is published on the registry (see [`registry`](/using-npm/registry)) with (c) +* e) a `@` (see [`npm dist-tag`](/commands/npm-dist-tag)) that points to (d) * f) a `` that has a "latest" tag satisfying (e) * g) a `` that resolves to (a) -The publish will fail if the package name and version combination already -exists in the specified registry. +If either (a) or (b) is specified as a relative path, it should begin with an explicit `./` prefix. -Once a package is published with a given name and version, that specific -name and version combination can never be used again, even if it is removed -with [`npm unpublish`](/commands/npm-unpublish). +The publish will fail if the package name and version combination already exists in the specified registry. -As of `npm@5`, both a sha1sum and an integrity field with a sha512sum of the -tarball will be submitted to the registry during publication. Subsequent -installs will use the strongest supported algorithm to verify downloads. +Once a package is published with a given name and version, that specific name and version combination can never be used again, even if it is removed with [`npm unpublish`](/commands/npm-unpublish). -Similar to `--dry-run` see [`npm pack`](/commands/npm-pack), which figures -out the files to be included and packs them into a tarball to be uploaded -to the registry. +As of `npm@5`, both a sha1sum and an integrity field with a sha512sum of the tarball will be submitted to the registry during publication. +Subsequent installs will use the strongest supported algorithm to verify downloads. + +Similar to `--dry-run` see [`npm pack`](/commands/npm-pack), which figures out the files to be included and packs them into a tarball to be uploaded to the registry. ### Files included in package -To see what will be included in your package, run `npm pack --dry-run`. All -files are included by default, with the following exceptions: +To see what will be included in your package, run `npm pack --dry-run`. +All files are included by default, with the following exceptions: -- Certain files that are relevant to package installation and distribution - are always included. For example, `package.json`, `README.md`, +- Certain files that are relevant to package installation and distribution are always included. +For example, `package.json`, `README.md`, `LICENSE`, and so on. -- If there is a "files" list in - [`package.json`](/configuring-npm/package-json), then only the files - specified will be included. (If directories are specified, then they - will be walked recursively and their contents included, subject to the - same ignore rules.) +- If there is a "files" list in [`package.json`](/configuring-npm/package-json), then only the files specified will be included. + (If directories are specified, then they will be walked recursively and their contents included, subject to the same ignore rules.) -- If there is a `.gitignore` or `.npmignore` file, then ignored files in - that and all child directories will be excluded from the package. If - _both_ files exist, then the `.gitignore` is ignored, and only the +- If there is a `.gitignore` or `.npmignore` file, then ignored files in that and all child directories will be excluded from the package. + If _both_ files exist, then the `.gitignore` is ignored, and only the `.npmignore` is used. - `.npmignore` files follow the [same pattern - rules](https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository#_ignoring) - as `.gitignore` files + `.npmignore` files follow the [same pattern rules](https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository#_ignoring) as `.gitignore` files -- If the file matches certain patterns, then it will _never_ be included, - unless explicitly added to the `"files"` list in `package.json`, or - un-ignored with a `!` rule in a `.npmignore` or `.gitignore` file. +- If the file matches certain patterns, then it will _never_ be included, unless explicitly added to the `"files"` list in `package.json`, or un-ignored with a `!` rule in a `.npmignore` or `.gitignore` file. - Symbolic links are never included in npm packages. -See [`developers`](/using-npm/developers) for full details on what's -included in the published package, as well as details on how the package is -built. +See [`developers`](/using-npm/developers) for full details on what's included in the published package, as well as details on how the package is built. + +See [`package.json`](/configuring-npm/package-json) for more info on what can and can't be ignored. ### Configuration @@ -93,7 +100,7 @@ built. * [npm-packlist package](http://npm.im/npm-packlist) * [npm registry](/using-npm/registry) * [npm scope](/using-npm/scope) -* [npm adduser](/commands/npm-adduser) +* [npm login](/commands/npm-login) * [npm owner](/commands/npm-owner) * [npm deprecate](/commands/npm-deprecate) * [npm dist-tag](/commands/npm-dist-tag) diff --git a/docs/lib/content/commands/npm-query.md b/docs/lib/content/commands/npm-query.md index 490eccffcc4b3..e9dd2e4d76bc1 100644 --- a/docs/lib/content/commands/npm-query.md +++ b/docs/lib/content/commands/npm-query.md @@ -10,8 +10,7 @@ description: Dependency selector query ### Description -The `npm query` command allows for usage of css selectors in order to retrieve -an array of dependency objects. +The `npm query` command allows for usage of css selectors in order to retrieve an array of dependency objects. ### Piping npm query to other commands @@ -136,21 +135,16 @@ npm query ":type(git)" | jq 'map(.name)' | xargs -I {} npm why {} ### Expecting a certain number of results -One common use of `npm query` is to make sure there is only one version of -a certain dependency in your tree. This is especially common for -ecosystems like that rely on `typescript` where having state split -across two different but identically-named packages causes bugs. You -can use the `--expect-results` or `--expect-result-count` in your setup -to ensure that npm will exit with an exit code if your tree doesn't look -like you want it to. +One common use of `npm query` is to make sure there is only one version of a certain dependency in your tree. +This is especially common for ecosystems like that rely on `typescript` where having state split across two different but identically-named packages causes bugs. +You can use the `--expect-results` or `--expect-result-count` in your setup to ensure that npm will exit with an exit code if your tree doesn't look like you want it to. ```sh $ npm query '#react' --expect-result-count=1 ``` -Perhaps you want to quickly check if there are any production -dependencies that could be updated: +Perhaps you want to quickly check if there are any production dependencies that could be updated: ```sh $ npm query ':root>:outdated(in-range).prod' --no-expect-results @@ -158,7 +152,8 @@ $ npm query ':root>:outdated(in-range).prod' --no-expect-results ### Package lock only mode -If package-lock-only is enabled, only the information in the package lock (or shrinkwrap) is loaded. This means that information from the package.json files of your dependencies will not be included in the result set (e.g. description, homepage, engines). +If package-lock-only is enabled, only the information in the package lock is loaded. +This means that information from the package.json files of your dependencies will not be included in the result set (e.g. description, homepage, engines). ### Configuration diff --git a/docs/lib/content/commands/npm-rebuild.md b/docs/lib/content/commands/npm-rebuild.md index aee332e37d8a1..ed61ac8e8ffb7 100644 --- a/docs/lib/content/commands/npm-rebuild.md +++ b/docs/lib/content/commands/npm-rebuild.md @@ -32,7 +32,8 @@ If there is a `binding.gyp` file in the root of your package, then npm will use } ``` -This default behavior is suppressed if the `package.json` has its own `install` or `preinstall` scripts. It is also suppressed if the package specifies `"gypfile": false` +This default behavior is suppressed if the `package.json` has its own `install` or `preinstall` scripts. +It is also suppressed if the package specifies `"gypfile": false` ### Configuration diff --git a/docs/lib/content/commands/npm-repo.md b/docs/lib/content/commands/npm-repo.md index e5968b3378fac..75d39df6cd5ba 100644 --- a/docs/lib/content/commands/npm-repo.md +++ b/docs/lib/content/commands/npm-repo.md @@ -10,11 +10,8 @@ description: Open package repository page in the browser ### Description -This command tries to guess at the likely location of a package's -repository URL, and then tries to open it using the -[`--browser` config](/using-npm/config#browser) param. If no package name is -provided, it will search for a `package.json` in the current folder and use the -`repository` property. +This command tries to guess at the likely location of a package's repository URL, and then tries to open it using the [`--browser` config](/using-npm/config#browser) param. +If no package name is provided, it will search for a `package.json` in the current folder and use the `repository` property. ### Configuration diff --git a/docs/lib/content/commands/npm-restart.md b/docs/lib/content/commands/npm-restart.md index c337ed6456b95..a4d283c5fce1d 100644 --- a/docs/lib/content/commands/npm-restart.md +++ b/docs/lib/content/commands/npm-restart.md @@ -10,18 +10,16 @@ description: Restart a package ### Description -This restarts a project. It is equivalent to running `npm run-script -restart`. +This restarts a project. +It is equivalent to running `npm run restart`. -If the current project has a `"restart"` script specified in -`package.json`, then the following scripts will be run: +If the current project has a `"restart"` script specified in `package.json`, then the following scripts will be run: 1. prerestart 2. restart 3. postrestart -If it does _not_ have a `"restart"` script specified, but it does have -`stop` and/or `start` scripts, then the following scripts will be run: +If it does _not_ have a `"restart"` script specified, but it does have `stop` and/or `start` scripts, then the following scripts will be run: 1. prerestart 2. prestop @@ -38,7 +36,7 @@ If it does _not_ have a `"restart"` script specified, but it does have ### See Also -* [npm run-script](/commands/npm-run-script) +* [npm run](/commands/npm-run) * [npm scripts](/using-npm/scripts) * [npm test](/commands/npm-test) * [npm start](/commands/npm-start) diff --git a/docs/lib/content/commands/npm-root.md b/docs/lib/content/commands/npm-root.md index 60b77bb5a839c..48420f39dfe34 100644 --- a/docs/lib/content/commands/npm-root.md +++ b/docs/lib/content/commands/npm-root.md @@ -12,8 +12,8 @@ description: Display npm root Print the effective `node_modules` folder to standard out. -Useful for using npm in shell scripts that do things with the -`node_modules` folder. For example: +Useful for using npm in shell scripts that do things with the `node_modules` folder. +For example: ```bash #!/bin/bash diff --git a/docs/lib/content/commands/npm-run-script.md b/docs/lib/content/commands/npm-run-script.md deleted file mode 100644 index 3c35a4778d687..0000000000000 --- a/docs/lib/content/commands/npm-run-script.md +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: npm-run-script -section: 1 -description: Run arbitrary package scripts ---- - -### Synopsis - - - -### Description - -This runs an arbitrary command from a package's `"scripts"` object. If no -`"command"` is provided, it will list the available scripts. - -`run[-script]` is used by the test, start, restart, and stop commands, but -can be called directly, as well. When the scripts in the package are -printed out, they're separated into lifecycle (test, start, restart) and -directly-run scripts. - -Any positional arguments are passed to the specified script. Use `--` to -pass `-`-prefixed flags and options which would otherwise be parsed by npm. - -For example: - -```bash -npm run test -- --grep="pattern" -``` - -The arguments will only be passed to the script specified after `npm run` -and not to any `pre` or `post` script. - -The `env` script is a special built-in command that can be used to list -environment variables that will be available to the script at runtime. If an -"env" command is defined in your package, it will take precedence over the -built-in. - -In addition to the shell's pre-existing `PATH`, `npm run` adds -`node_modules/.bin` to the `PATH` provided to scripts. Any binaries -provided by locally-installed dependencies can be used without the -`node_modules/.bin` prefix. For example, if there is a `devDependency` on -`tap` in your package, you should write: - -```bash -"scripts": {"test": "tap test/*.js"} -``` - -instead of - -```bash -"scripts": {"test": "node_modules/.bin/tap test/*.js"} -``` - -The actual shell your script is run within is platform dependent. By default, -on Unix-like systems it is the `/bin/sh` command, on Windows it is -`cmd.exe`. -The actual shell referred to by `/bin/sh` also depends on the system. -You can customize the shell with the -[`script-shell` config](/using-npm/config#script-shell). - -Scripts are run from the root of the package folder, regardless of what the -current working directory is when `npm run` is called. If you want your -script to use different behavior based on what subdirectory you're in, you -can use the `INIT_CWD` environment variable, which holds the full path you -were in when you ran `npm run`. - -`npm run` sets the `NODE` environment variable to the `node` executable -with which `npm` is executed. - -If you try to run a script without having a `node_modules` directory and it -fails, you will be given a warning to run `npm install`, just in case you've -forgotten. - -### Workspaces support - -You may use the [`workspace`](/using-npm/config#workspace) or -[`workspaces`](/using-npm/config#workspaces) configs in order to run an -arbitrary command from a package's `"scripts"` object in the context of the -specified workspaces. If no `"command"` is provided, it will list the available -scripts for each of these configured workspaces. - -Given a project with configured workspaces, e.g: - -``` -. -+-- package.json -`-- packages - +-- a - | `-- package.json - +-- b - | `-- package.json - `-- c - `-- package.json -``` - -Assuming the workspace configuration is properly set up at the root level -`package.json` file. e.g: - -``` -{ - "workspaces": [ "./packages/*" ] -} -``` - -And that each of the configured workspaces has a configured `test` script, -we can run tests in all of them using the -[`workspaces` config](/using-npm/config#workspaces): - -``` -npm test --workspaces -``` - -#### Filtering workspaces - -It's also possible to run a script in a single workspace using the `workspace` -config along with a name or directory path: - -``` -npm test --workspace=a -``` - -The `workspace` config can also be specified multiple times in order to run a -specific script in the context of multiple workspaces. When defining values for -the `workspace` config in the command line, it also possible to use `-w` as a -shorthand, e.g: - -``` -npm test -w a -w b -``` - -This last command will run `test` in both `./packages/a` and `./packages/b` -packages. - -### Configuration - - - -### See Also - -* [npm scripts](/using-npm/scripts) -* [npm test](/commands/npm-test) -* [npm start](/commands/npm-start) -* [npm restart](/commands/npm-restart) -* [npm stop](/commands/npm-stop) -* [npm config](/commands/npm-config) -* [npm workspaces](/using-npm/workspaces) diff --git a/docs/lib/content/commands/npm-run.md b/docs/lib/content/commands/npm-run.md new file mode 100644 index 0000000000000..ddabd699e6962 --- /dev/null +++ b/docs/lib/content/commands/npm-run.md @@ -0,0 +1,123 @@ +--- +title: npm-run +section: 1 +description: Run arbitrary package scripts +--- + +### Synopsis + + + +### Description + +This runs an arbitrary command from a package's `"scripts"` object. +If no +`"command"` is provided, it will list the available scripts. + +`run[-script]` is used by the test, start, restart, and stop commands, but can be called directly, as well. +When the scripts in the package are printed out, they're separated into lifecycle (test, start, restart) and directly-run scripts. + +Any positional arguments are passed to the specified script. +Use `--` to pass `-`-prefixed flags and options which would otherwise be parsed by npm. + +For example: + +```bash +npm run test -- --grep="pattern" +``` + +The arguments will only be passed to the script specified after `npm run` and not to any `pre` or `post` script. + +The `env` script is a special built-in command that can be used to list environment variables that will be available to the script at runtime. +If an "env" command is defined in your package, it will take precedence over the built-in. + +In addition to the shell's pre-existing `PATH`, `npm run` adds `node_modules/.bin` to the `PATH` provided to scripts. +Any binaries provided by locally-installed dependencies can be used without the `node_modules/.bin` prefix. +For example, if there is a `devDependency` on `tap` in your package, you should write: + +```bash +"scripts": {"test": "tap test/*.js"} +``` + +instead of + +```bash +"scripts": {"test": "node_modules/.bin/tap test/*.js"} +``` + +The actual shell your script is run within is platform dependent. +By default, on Unix-like systems it is the `/bin/sh` command, on Windows it is `cmd.exe`. +The actual shell referred to by `/bin/sh` also depends on the system. +You can customize the shell with the [`script-shell` config](/using-npm/config#script-shell). + +Scripts are run from the root of the package folder, regardless of what the current working directory is when `npm run` is called. +If you want your script to use different behavior based on what subdirectory you're in, you can use the `INIT_CWD` environment variable, which holds the full path you were in when you ran `npm run`. + +`npm run` sets the `NODE` environment variable to the `node` executable with which `npm` is executed. + +If you try to run a script without having a `node_modules` directory and it fails, you will be given a warning to run `npm install`, just in case you've forgotten. + +### Workspaces support + +You may use the [`workspace`](/using-npm/config#workspace) or [`workspaces`](/using-npm/config#workspaces) configs in order to run an arbitrary command from a package's `"scripts"` object in the context of the specified workspaces. +If no `"command"` is provided, it will list the available scripts for each of these configured workspaces. + +Given a project with configured workspaces, e.g: + +``` +. ++-- package.json +`-- packages + +-- a + | `-- package.json + +-- b + | `-- package.json + `-- c + `-- package.json +``` + +Assuming the workspace configuration is properly set up at the root level `package.json` file. +e.g: + +``` +{ + "workspaces": [ "./packages/*" ] +} +``` + +And that each of the configured workspaces has a configured `test` script, we can run tests in all of them using the [`workspaces` config](/using-npm/config#workspaces): + +``` +npm test --workspaces +``` + +#### Filtering workspaces + +It's also possible to run a script in a single workspace using the `workspace` config along with a name or directory path: + +``` +npm test --workspace=a +``` + +The `workspace` config can also be specified multiple times in order to run a specific script in the context of multiple workspaces. +When defining values for the `workspace` config in the command line, it also possible to use `-w` as a shorthand, e.g: + +``` +npm test -w a -w b +``` + +This last command will run `test` in both `./packages/a` and `./packages/b` packages. + +### Configuration + + + +### See Also + +* [npm scripts](/using-npm/scripts) +* [npm test](/commands/npm-test) +* [npm start](/commands/npm-start) +* [npm restart](/commands/npm-restart) +* [npm stop](/commands/npm-stop) +* [npm config](/commands/npm-config) +* [npm workspaces](/using-npm/workspaces) diff --git a/docs/lib/content/commands/npm-sbom.md b/docs/lib/content/commands/npm-sbom.md index a5ac81baf6704..e9d23716a018b 100644 --- a/docs/lib/content/commands/npm-sbom.md +++ b/docs/lib/content/commands/npm-sbom.md @@ -10,9 +10,8 @@ description: Generate a Software Bill of Materials (SBOM) ### Description -The `npm sbom` command generates a Software Bill of Materials (SBOM) listing the -dependencies for the current project. SBOMs can be generated in either -[SPDX](https://spdx.dev/) or [CycloneDX](https://cyclonedx.org/) format. +The `npm sbom` command generates a Software Bill of Materials (SBOM) listing the dependencies for the current project. +SBOMs can be generated in either [SPDX](https://spdx.dev/) or [CycloneDX](https://cyclonedx.org/) format. ### Example CycloneDX SBOM @@ -206,10 +205,9 @@ dependencies for the current project. SBOMs can be generated in either ### Package lock only mode -If package-lock-only is enabled, only the information in the package -lock (or shrinkwrap) is loaded. This means that information from the -package.json files of your dependencies will not be included in the -result set (e.g. description, homepage, engines). +If package-lock-only is enabled, only the information in the package lock is loaded. +This means that information from the package.json files of your dependencies will not be included in the result set (e.g. +description, homepage, engines). ### Configuration diff --git a/docs/lib/content/commands/npm-search.md b/docs/lib/content/commands/npm-search.md index 52b66e93a6a0e..b5244df0d8117 100644 --- a/docs/lib/content/commands/npm-search.md +++ b/docs/lib/content/commands/npm-search.md @@ -10,26 +10,20 @@ description: Search for packages ### Description -Search the registry for packages matching the search terms. `npm search` -performs a linear, incremental, lexically-ordered search through package -metadata for all files in the registry. If your terminal has color -support, it will further highlight the matches in the results. This can -be disabled with the config item `color` - -Additionally, using the `--searchopts` and `--searchexclude` options -paired with more search terms will include and exclude further patterns. -The main difference between `--searchopts` and the standard search terms -is that the former does not highlight results in the output and you can -use them more fine-grained filtering. Additionally, you can add both of -these to your config to change default search filtering behavior. - -Search also allows targeting of maintainers in search results, by prefixing -their npm username with `=`. - -If a term starts with `/`, then it's interpreted as a regular expression -and supports standard JavaScript RegExp syntax. In this case search will -ignore a trailing `/` . (Note you must escape or quote many regular -expression characters in most shells.) +Search the registry for packages matching the search terms. +`npm search` +performs a linear, incremental, lexically-ordered search through package metadata for all files in the registry. +If your terminal has color support, it will further highlight the matches in the results. +This can be disabled with the config item `color` + +Additionally, using the `--searchopts` and `--searchexclude` options paired with more search terms will include and exclude further patterns. +The main difference between `--searchopts` and the standard search terms is that the former does not highlight results in the output and you can use them more fine-grained filtering. +Additionally, you can add both of these to your config to change default search filtering behavior. + +Search also allows targeting of maintainers in search results, by prefixing their npm username with `=`. + +If a term starts with `/`, then it's interpreted as a regular expression and supports standard JavaScript RegExp syntax. +In this case search will ignore a trailing `/` . (Note you must escape or quote many regular expression characters in most shells.) ### Configuration diff --git a/docs/lib/content/commands/npm-set.md b/docs/lib/content/commands/npm-set.md new file mode 100644 index 0000000000000..864ce81be43ba --- /dev/null +++ b/docs/lib/content/commands/npm-set.md @@ -0,0 +1,21 @@ +--- +title: npm-set +section: 1 +description: Set a value in the npm configuration +--- + +### Synopsis + + + +### Description + +Set a value in the npm configuration + +### Configuration + + + +### See Also + +* [npm help config](/commands/npm-config) diff --git a/docs/lib/content/commands/npm-shrinkwrap.md b/docs/lib/content/commands/npm-shrinkwrap.md deleted file mode 100644 index 8717a63f3fb16..0000000000000 --- a/docs/lib/content/commands/npm-shrinkwrap.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: npm-shrinkwrap -section: 1 -description: Lock down dependency versions for publication ---- - -### Synopsis - - - -### Description - -This command repurposes `package-lock.json` into a publishable -`npm-shrinkwrap.json` or simply creates a new one. The file created and -updated by this command will then take precedence over any other existing -or future `package-lock.json` files. For a detailed explanation of the -design and purpose of package locks in npm, see -[package-lock-json](/configuring-npm/package-lock-json). - -### See Also - -* [npm install](/commands/npm-install) -* [npm run-script](/commands/npm-run-script) -* [npm scripts](/using-npm/scripts) -* [package.json](/configuring-npm/package-json) -* [package-lock.json](/configuring-npm/package-lock-json) -* [npm-shrinkwrap.json](/configuring-npm/npm-shrinkwrap-json) -* [npm ls](/commands/npm-ls) diff --git a/docs/lib/content/commands/npm-stage.md b/docs/lib/content/commands/npm-stage.md new file mode 100644 index 0000000000000..563861f92239e --- /dev/null +++ b/docs/lib/content/commands/npm-stage.md @@ -0,0 +1,142 @@ +--- +title: npm-stage +section: 1 +description: Stage packages for publishing +--- + +### Synopsis + + + +### Description + +Staged publishing allows package maintainers to require proof-of-presence +for all publishes. Proof-of-presence is where a human is involved, +interjects, and provides authentication (2FA) during an action — in this +case, publishing an npm package. + +Typically when maintainers use automated workflows to publish, +proof-of-presence is lacking as there's no convenient way to interject the +process and provide 2FA, as is the case for publishing with a granular +access token with bypass and the trusted publishing flow. Staged publishing +allows users to have their automated workflows stage a package without a 2FA +prompt, deferring the act of 2FA, allowing the maintainer to approve the +staged package and publish at a later point. + +The `npm stage publish` command packs the current working directory and +places that version of the package into the registry in a state where it's +not available for public access, allowing maintainers to approve the package +at a later point in time. The act of staging does not prompt for 2FA and can be done with any token +type, the act of approving will. + +Key behaviors: + +* Staged packages share the same semver version unique index as published + packages — you cannot publish a version that already exists as a staged + version for that package. +* You can still publish packages normally while you have staged packages + pending. +* You can stage multiple versions of the same package. +* `npm stage publish` has parity with `npm publish` and will respect + `"private": true` in `package.json`, refusing to stage the package. + +### Prerequisites + +Before using `npm stage` commands, ensure the following requirements are met: + +* **Write permissions on the package:** You must have write access to the + package you're configuring. +* **Package must exist:** The package you're configuring must already exist + on the npm registry. +* **2FA enabled on your account:** Commands that require 2FA will prompt you + to authenticate. If you don't already have 2FA enabled on your account, + you must enable it before using these commands. + +### Subcommands + +* `npm stage publish []` - Stage a package for publishing +* `npm stage list []` - List all staged package versions +* `npm stage view ` - View details of a specific staged package +* `npm stage approve ` - Approve a staged package for publishing +* `npm stage reject ` - Reject a staged package +* `npm stage download ` - Download the tarball for inspection + +### 2FA Requirements by Subcommand + +| Command | Requires 2FA | Notes | +| --- | --- | --- | +| `npm stage publish` | No | Designed for automated workflows; defers 2FA to approval | +| `npm stage list` | No | View staged packages | +| `npm stage view` | No | View staged package details | +| `npm stage approve` | Yes | Prompts for 2FA to publish the staged package | +| `npm stage reject` | Yes | Prompts for 2FA to permanently remove the staged package | +| `npm stage download` | No | Downloads the tarball for local inspection | + +### Tag Behavior + +The `--tag` flag follows the same logic as `npm publish`. If no tag is +provided, the `latest` tag is used by default. For pre-release versions +(e.g., `1.0.0-beta.1`) and non-latest semver versions, the tag must be +explicitly provided — otherwise the CLI will error, just as `npm publish` +would. + +The tag is an immutable property of the staged package. Once a package is +staged with a given tag, the tag cannot be changed. If you need to stage the +same version with a different tag, you must first reject the existing staged +package using `npm stage reject` and then re-stage it with the desired tag. + +### Token Behavior + +The key difference with staged publishing is that `npm stage publish` never +requires a 2FA prompt, regardless of token type. This is what makes it +suitable for automated workflows. The goal of `npm stage publish` is +deferring proof-of-presence to a later point in time. + +| Token Type | `npm stage publish` | `npm publish` | +| --- | --- | --- | +| GAT with bypass | Can stage | Can publish (if allowed by package publishing access) | +| GAT without bypass | Can stage | 2FA prompt (if allowed by package publishing access) | +| Session token | Can stage | 2FA prompt | +| Trust token (OIDC) | Can stage (if allowed) | Can publish (if allowed) | + +### Trust Relationship Permissions + +With staged publishing, trust relationships now support granular command +permissions. Shortlived tokens issued through trust relationships can only be +used with `npm stage publish` and `npm publish`. Shortlived tokens cannot run +`npm stage` subcommands. + +`npm trust ` supports `--allow-publish` and `--allow-stage-publish` +to control which commands are available through each trust relationship. + +### Best Practices + +**Note:** The addition of staged publishing does not make your account or org +more secure. Maintainers must still use the best practices listed below. + +1. **Delete Granular Access Tokens (GAT) with bypass 2FA enabled.** + Now with staged publishing, we've eliminated the need for a GAT token + that can bypass 2FA. We encourage you to delete all your tokens with + bypass enabled and switch to using a trust relationship in your automated + workflows, or create a GAT without bypass and use `npm stage publish`. + +2. **Disallow tokens from publishing at the package level.** + All packages have their own access controls under "package access" + allowing packages to be published with bypass tokens, which is no longer + a necessity. We encourage you to select "Require two-factor + authentication and disallow tokens (recommended)" for all your packages + on the package access page. + +3. **Configure trust relationship permissions to prevent `npm publish`.** + We encourage you to only enable `npm stage publish` on your trust + relationships and disable `npm publish`. + +### Configuration + + + +### See Also + +* [npm publish](/commands/npm-publish) +* [npm unpublish](/commands/npm-unpublish) +* [npm trust](/commands/npm-trust) diff --git a/docs/lib/content/commands/npm-star.md b/docs/lib/content/commands/npm-star.md deleted file mode 100644 index 01d3a49d7e91f..0000000000000 --- a/docs/lib/content/commands/npm-star.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: npm-star -section: 1 -description: Mark your favorite packages ---- - -### Synopsis - - - -### Description - -"Starring" a package means that you have some interest in it. It's -a vaguely positive way to show that you care. - -It's a boolean thing. Starring repeatedly has no additional effect. - -### More - -There's also these extra commands to help you manage your favorite packages: - -#### Unstar - -You can also "unstar" a package using [`npm unstar`](/commands/npm-unstar) - -"Unstarring" is the same thing, but in reverse. - -#### Listing stars - -You can see all your starred packages using [`npm stars`](/commands/npm-stars) - -### Configuration - - - -### See Also - -* [package spec](/using-npm/package-spec) -* [npm unstar](/commands/npm-unstar) -* [npm stars](/commands/npm-stars) -* [npm view](/commands/npm-view) -* [npm whoami](/commands/npm-whoami) -* [npm adduser](/commands/npm-adduser) diff --git a/docs/lib/content/commands/npm-stars.md b/docs/lib/content/commands/npm-stars.md deleted file mode 100644 index 68f50815186b1..0000000000000 --- a/docs/lib/content/commands/npm-stars.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: npm-stars -section: 1 -description: View packages marked as favorites ---- - -### Synopsis - - - -### Description - -If you have starred a lot of neat things and want to find them again -quickly this command lets you do just that. - -You may also want to see your friend's favorite packages, in this case -you will most certainly enjoy this command. - -### Configuration - - - -### See Also - -* [npm star](/commands/npm-star) -* [npm unstar](/commands/npm-unstar) -* [npm view](/commands/npm-view) -* [npm whoami](/commands/npm-whoami) -* [npm adduser](/commands/npm-adduser) diff --git a/docs/lib/content/commands/npm-start.md b/docs/lib/content/commands/npm-start.md index c30dda963e9d6..3c28b43359fed 100644 --- a/docs/lib/content/commands/npm-start.md +++ b/docs/lib/content/commands/npm-start.md @@ -10,18 +10,14 @@ description: Start a package ### Description -This runs a predefined command specified in the `"start"` property of -a package's `"scripts"` object. +This runs a predefined command specified in the `"start"` property of a package's `"scripts"` object. -If the `"scripts"` object does not define a `"start"` property, npm -will run `node server.js`. +If the `"scripts"` object does not define a `"start"` property, npm will run `node server.js`. -Note that this is different from the default node behavior of running -the file specified in a package's `"main"` attribute when evoking with -`node .` +Note that this is different from the default node behavior of running the file specified in a package's `"main"` attribute when evoking with `node .` -As of [`npm@2.0.0`](https://blog.npmjs.org/post/98131109725/npm-2-0-0), you can -use custom arguments when executing scripts. Refer to [`npm run-script`](/commands/npm-run-script) for more details. +As of [`npm@2.0.0`](https://blog.npmjs.org/post/98131109725/npm-2-0-0), you can use custom arguments when executing scripts. +Refer to [`npm run`](/commands/npm-run) for more details. ### Example @@ -49,7 +45,7 @@ npm start ### See Also -* [npm run-script](/commands/npm-run-script) +* [npm run](/commands/npm-run) * [npm scripts](/using-npm/scripts) * [npm test](/commands/npm-test) * [npm restart](/commands/npm-restart) diff --git a/docs/lib/content/commands/npm-stop.md b/docs/lib/content/commands/npm-stop.md index e4924d44821ea..c2fb903296f10 100644 --- a/docs/lib/content/commands/npm-stop.md +++ b/docs/lib/content/commands/npm-stop.md @@ -10,11 +10,9 @@ description: Stop a package ### Description -This runs a predefined command specified in the "stop" property of a -package's "scripts" object. +This runs a predefined command specified in the "stop" property of a package's "scripts" object. -Unlike with [npm start](/commands/npm-start), there is no default script -that will run if the `"stop"` property is not defined. +Unlike with [npm start](/commands/npm-start), there is no default script that will run if the `"stop"` property is not defined. ### Example @@ -42,7 +40,7 @@ npm stop ### See Also -* [npm run-script](/commands/npm-run-script) +* [npm run](/commands/npm-run) * [npm scripts](/using-npm/scripts) * [npm test](/commands/npm-test) * [npm start](/commands/npm-start) diff --git a/docs/lib/content/commands/npm-team.md b/docs/lib/content/commands/npm-team.md index d3b7ca58fe2af..65830bf43fe46 100644 --- a/docs/lib/content/commands/npm-team.md +++ b/docs/lib/content/commands/npm-team.md @@ -10,22 +10,18 @@ description: Manage organization teams and team memberships ### Description -Used to manage teams in organizations, and change team memberships. Does not -handle permissions for packages. +Used to manage teams in organizations, and change team memberships. +Does not handle permissions for packages. -Teams must always be fully qualified with the organization/scope they belong to -when operating on them, separated by a colon (`:`). That is, if you have a -`newteam` team in an `org` organization, you must always refer to that team -as `@org:newteam` in these commands. +Teams must always be fully qualified with the organization/scope they belong to when operating on them, separated by a colon (`:`). +That is, if you have a `newteam` team in an `org` organization, you must always refer to that team as `@org:newteam` in these commands. -If you have two-factor authentication enabled in `auth-and-writes` mode, then -you can provide a code from your authenticator with `[--otp ]`. -If you don't include this then you will be taken through a second factor flow based -on your `authtype`. +If you have two-factor authentication enabled in `auth-and-writes` mode, then you can provide a code from your authenticator with `[--otp ]`. +If you don't include this then you will be taken through a second factor flow based on your `authtype`. * create / destroy: - Create a new team, or destroy an existing one. Note: You cannot remove the - `developers` team, [learn more.](https://docs.npmjs.com/about-developers-team) + Create a new team, or destroy an existing one. + Note: You cannot remove the `developers` team, [learn more.](https://docs.npmjs.com/about-developers-team) Here's how to create a new team `newteam` under the `org` org: @@ -33,8 +29,7 @@ on your `authtype`. npm team create @org:newteam ``` - You should see a confirming message such as: `+@org:newteam` once the new - team has been created. + You should see a confirming message such as: `+@org:newteam` once the new team has been created. * add: Add a user to an existing team. @@ -50,8 +45,7 @@ on your `authtype`. * rm: Using `npm team rm` you can also remove users from a team they belong to. - Here's an example removing user `username` from `newteam` team - in `org` organization: + Here's an example removing user `username` from `newteam` team in `org` organization: ```bash npm team rm @org:newteam username @@ -61,9 +55,8 @@ on your `authtype`. `username removed from @org:newteam` * ls: - If performed on an organization name, will return a list of existing teams - under that organization. If performed on a team, it will instead return a list - of all users belonging to that particular team. + If performed on an organization name, will return a list of existing teams under that organization. + If performed on a team, it will instead return a list of all users belonging to that particular team. Here's an example of how to list all teams from an org named `org`: @@ -79,18 +72,14 @@ on your `authtype`. ### Details -`npm team` always operates directly on the current registry, configurable from -the command line using `--registry=`. +`npm team` always operates directly on the current registry, configurable from the command line using `--registry=`. -You must be a *team admin* to create teams and manage team membership, under -the given organization. Listing teams and team memberships may be done by -any member of the organization. +You must be a *team admin* to create teams and manage team membership, under the given organization. +Listing teams and team memberships may be done by any member of the organization. -Organization creation and management of team admins and *organization* members -is done through the website, not the npm CLI. +Organization creation and management of team admins and *organization* members is done through the website, not the npm CLI. -To use teams to manage permissions on packages belonging to your organization, -use the `npm access` command to grant or revoke the appropriate permissions. +To use teams to manage permissions on packages belonging to your organization, use the `npm access` command to grant or revoke the appropriate permissions. ### Configuration diff --git a/docs/lib/content/commands/npm-test.md b/docs/lib/content/commands/npm-test.md index 11a4d793aa8da..143c3b60dca6d 100644 --- a/docs/lib/content/commands/npm-test.md +++ b/docs/lib/content/commands/npm-test.md @@ -10,8 +10,7 @@ description: Test a package ### Description -This runs a predefined command specified in the `"test"` property of -a package's `"scripts"` object. +This runs a predefined command specified in the `"test"` property of a package's `"scripts"` object. ### Example @@ -37,7 +36,7 @@ npm test ### See Also -* [npm run-script](/commands/npm-run-script) +* [npm run](/commands/npm-run) * [npm scripts](/using-npm/scripts) * [npm start](/commands/npm-start) * [npm restart](/commands/npm-restart) diff --git a/docs/lib/content/commands/npm-token.md b/docs/lib/content/commands/npm-token.md index d4d9d6bd83cce..5a1d2702340cc 100644 --- a/docs/lib/content/commands/npm-token.md +++ b/docs/lib/content/commands/npm-token.md @@ -12,44 +12,21 @@ description: Manage your authentication tokens This lets you list, create and revoke authentication tokens. -* `npm token list`: - Shows a table of all active authentication tokens. You can request - this as JSON with `--json` or tab-separated values with `--parseable`. +#### Listing tokens -``` -Read only token npm_1f… with id 7f3134 created 2017-10-21 +When listing tokens, an abbreviated token will be displayed. For security purposes the full token is not displayed. -Publish token npm_af… with id c03241 created 2017-10-02 -with IP Whitelist: 192.168.0.1/24 +#### Generating tokens -Publish token npm_… with id e0cf92 created 2017-10-02 +When generating tokens, you will be prompted you for your password and, if you have two-factor authentication enabled, an otp. -``` +Please refer to the [docs website](https://docs.npmjs.com/creating-and-viewing-access-tokens) for more information on generating tokens for CI/CD. -* `npm token create [--read-only] [--cidr=]`: - Create a new authentication token. It can be `--read-only`, or accept - a list of - [CIDR](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) - ranges with which to limit use of this token. This will prompt you for - your password, and, if you have two-factor authentication enabled, an - otp. +#### Revoking tokens - Currently, the cli can not generate automation tokens. Please refer to - the [docs - website](https://docs.npmjs.com/creating-and-viewing-access-tokens) - for more information on generating automation tokens. +When revoking a token, you can use the full token (e.g. what you get back from `npm token create`, or as can be found in an `.npmrc` file), or a truncated id. If the given truncated id is not distinct enough to differentiate between multiple existing tokens, you will need to use enough of the id to allow npm to distinguish between them. Full token ids can be found on the [npm website](https://www.npmjs.com), or in the `--parseable` or `--json` output of `npm token list`. This command will NOT accept the truncated token found in the normal `npm token list` output. -``` -Created publish token a73c9572-f1b9-8983-983d-ba3ac3cc913d -``` - -* `npm token revoke `: - Immediately removes an authentication token from the registry. You - will no longer be able to use it. This can accept both complete - tokens (such as those you get back from `npm token create`, and those - found in your `.npmrc`), and ids as seen in the parseable or json - output of `npm token list`. This will NOT accept the truncated token - found in the normal `npm token list` output. +A revoked token will immediately be removed from the registry and you will no longer be able to use it. ### Configuration @@ -57,7 +34,7 @@ Created publish token a73c9572-f1b9-8983-983d-ba3ac3cc913d ### See Also -* [npm adduser](/commands/npm-adduser) +* [npm login](/commands/npm-login) * [npm registry](/using-npm/registry) * [npm config](/commands/npm-config) * [npmrc](/configuring-npm/npmrc) diff --git a/docs/lib/content/commands/npm-trust.md b/docs/lib/content/commands/npm-trust.md new file mode 100644 index 0000000000000..64b00adbd1462 --- /dev/null +++ b/docs/lib/content/commands/npm-trust.md @@ -0,0 +1,68 @@ +--- +title: npm-trust +section: 1 +description: Manage trusted publishing relationships between packages and CI/CD providers +--- + +### Synopsis + + + +### Prerequisites + +Before using npm trust commands, ensure the following requirements are met: + +* **npm version**: `npm@11.15.0` or above is required. Use `npm install -g npm@^11.15.0` to update if needed. +* **Write permissions on the package**: You must have write access to the package you're configuring. +* **2FA enabled on account**: Two-factor authentication must be enabled at the account level. Even if it's not currently enabled, you must enable it to use trust commands. +* **Supported authentication methods**: Granular Access Tokens (GAT) with the bypass 2FA option are not supported. Legacy basic auth (username and password) credentials will not work for trust commands or endpoints. +* **Package must exist**: The package you're configuring must already exist on the npm registry. + +### Description + +Configure trust relationships between npm packages and CI/CD providers using OpenID Connect (OIDC). This is the command-line equivalent of managing trusted publisher configurations on the npm website. + +For a comprehensive overview of trusted publishing, see the [npm trusted publishers documentation](https://docs.npmjs.com/trusted-publishers). + +The `[package]` argument specifies the package name. If omitted, npm will use the name from the `package.json` in the current directory. + +Each trust relationship has its own set of configuration options and flags based on the OIDC claims provided by that provider. OIDC claims come from the CI/CD provider and include information such as repository name, workflow file, or environment. Since each provider's claims differ, the available flags and configuration keys are not universal—npm matches the claims supported by each provider's OIDC configuration. For specific details on which claims and flags are supported for a given provider, use `npm trust --help`. + +### Permissions + +When creating a trust relationship, you must specify at least one permission flag to indicate which operations the trusted publisher is allowed to perform: + +* `--allow-publish`: Allows the trusted publisher to run `npm publish` for the package. +* `--allow-stage-publish`: Allows the trusted publisher to run `npm stage` for the package. The alias `--allow-staged-publish` is also accepted. + +At least one of these flags is required when creating a trust configuration. You can specify both to grant both permissions. + +### Provider Options + +The required options depend on the CI/CD provider you're configuring. Detailed information about each option is available in the [managing trusted publisher configurations](https://docs.npmjs.com/trusted-publishers#managing-trusted-publisher-configurations) section of the npm documentation. If a provider is repository-based and the option is not provided, npm will use the `repository.url` field from your `package.json`, if available. + +Currently, the registry only supports one configuration per package. If you attempt to create a new trust relationship when one already exists, it will result in an error. To replace an existing configuration: + +1. Use `npm trust list [package]` to view the ID of the existing trusted publisher +2. Use `npm trust revoke --id [package]` to remove the existing configuration +3. Then create your new trust relationship + +### Bulk Usage + +For maintainers managing a large number of packages, you can configure trusted publishing in bulk using bash scripting. Create a loop that iterates through package names and their corresponding configuration details, executing the `npm trust ` command with the `--yes` flag for each package. + +The first request will require two-factor authentication. During two-factor authentication, you'll see an option on the npm website to skip two-factor authentication for the next 5 minutes. Enabling this option will allow subsequent `npm trust ` commands to proceed without two-factor authentication, streamlining the bulk configuration process. + +We recommend adding a 2-second sleep between each call to avoid rate limiting. With this approach, you can configure approximately 80 packages within the 5-minute two-factor authentication skip window. + +### Configuration + + + +### See Also + +* [npm publish](/commands/npm-publish) +* [npm token](/commands/npm-token) +* [npm access](/commands/npm-access) +* [npm config](/commands/npm-config) +* [npm registry](/using-npm/registry) diff --git a/docs/lib/content/commands/npm-undeprecate.md b/docs/lib/content/commands/npm-undeprecate.md new file mode 100644 index 0000000000000..5647990a56940 --- /dev/null +++ b/docs/lib/content/commands/npm-undeprecate.md @@ -0,0 +1,22 @@ +--- +title: npm-undeprecate +section: 1 +description: Undeprecate a version of a package +--- + +### Synopsis + + + +### Description + +This command will update the npm registry entry for a package, removing any deprecation warnings that currently exist. + +It works in the same way as [npm deprecate](/commands/npm-deprecate), except that this command removes deprecation warnings instead of adding them. + +### Configuration + + +### See Also + +* [npm deprecate](/commands/npm-deprecate) diff --git a/docs/lib/content/commands/npm-uninstall.md b/docs/lib/content/commands/npm-uninstall.md index 46e5af073e959..a3d54c5365eab 100644 --- a/docs/lib/content/commands/npm-uninstall.md +++ b/docs/lib/content/commands/npm-uninstall.md @@ -10,26 +10,19 @@ description: Remove a package ### Description -This uninstalls a package, completely removing everything npm installed -on its behalf. +This uninstalls a package, completely removing everything npm installed on its behalf. It also removes the package from the `dependencies`, `devDependencies`, -`optionalDependencies`, and `peerDependencies` objects in your -`package.json`. +`optionalDependencies`, and `peerDependencies` objects in your `package.json`. -Further, if you have an `npm-shrinkwrap.json` or `package-lock.json`, npm -will update those files as well. +Further, if you have a `package-lock.json`, npm will update that file as well. -`--no-save` will tell npm not to remove the package from your -`package.json`, `npm-shrinkwrap.json`, or `package-lock.json` files. +`--no-save` will tell npm not to remove the package from your `package.json` or `package-lock.json` files. -`--save` or `-S` will tell npm to remove the package from your -`package.json`, `npm-shrinkwrap.json`, and `package-lock.json` files. -This is the default, but you may need to use this if you have for -instance `save=false` in your `npmrc` file +`--save` or `-S` will tell npm to remove the package from your `package.json` and `package-lock.json` files. +This is the default, but you may need to use this if you have for instance `save=false` in your `npmrc` file -In global mode (ie, with `-g` or `--global` appended to the command), -it uninstalls the current package context as a global package. +In global mode (ie, with `-g` or `--global` appended to the command), it uninstalls the current package context as a global package. `--no-save` is ignored in this case. Scope is optional and follows the usual rules for [`scope`](/using-npm/scope). @@ -40,15 +33,14 @@ Scope is optional and follows the usual rules for [`scope`](/using-npm/scope). npm uninstall sax ``` -`sax` will no longer be in your `package.json`, `npm-shrinkwrap.json`, or -`package-lock.json` files. +`sax` will no longer be in your `package.json` or `package-lock.json` files. ```bash npm uninstall lodash --no-save ``` -`lodash` will not be removed from your `package.json`, -`npm-shrinkwrap.json`, or `package-lock.json` files. +`lodash` will not be removed from your `package.json` or +`package-lock.json` files. ### Configuration diff --git a/docs/lib/content/commands/npm-unpublish.md b/docs/lib/content/commands/npm-unpublish.md index 741fc83cee9aa..ffd04fd4ff7ec 100644 --- a/docs/lib/content/commands/npm-unpublish.md +++ b/docs/lib/content/commands/npm-unpublish.md @@ -8,35 +8,25 @@ description: Remove a package from the registry -To learn more about how the npm registry treats unpublish, see our -[unpublish policies](https://docs.npmjs.com/policies/unpublish). +To learn more about how the npm registry treats unpublish, see our [unpublish policies](https://docs.npmjs.com/policies/unpublish). ### Warning -Consider using the [`deprecate`](/commands/npm-deprecate) command instead, -if your intent is to encourage users to upgrade, or if you no longer -want to maintain a package. +Consider using the [`deprecate`](/commands/npm-deprecate) command instead, if your intent is to encourage users to upgrade, or if you no longer want to maintain a package. ### Description -This removes a package version from the registry, deleting its entry and -removing the tarball. +This removes a package version from the registry, deleting its entry and removing the tarball. -The npm registry will return an error if you are not [logged -in](/commands/npm-adduser). +The npm registry will return an error if you are not [logged in](/commands/npm-login). -If you do not specify a package name at all, the name and version to be -unpublished will be pulled from the project in the current directory. +If you do not specify a package name at all, the name and version to be unpublished will be pulled from the project in the current directory. -If you specify a package name but do not specify a version or if you -remove all of a package's versions then the registry will remove the -root package entry entirely. +If you specify a package name but do not specify a version or if you remove all of a package's versions then the registry will remove the root package entry entirely. -Even if you unpublish a package version, that specific name and version -combination can never be reused. In order to publish the package again, -you must use a new version number. If you unpublish the entire package, -you may not publish any new versions of that package until 24 hours have -passed. +Even if you unpublish a package version, that specific name and version combination can never be reused. +In order to publish the package again, you must use a new version number. +If you unpublish the entire package, you may not publish any new versions of that package until 24 hours have passed. ### Configuration @@ -48,6 +38,5 @@ passed. * [npm deprecate](/commands/npm-deprecate) * [npm publish](/commands/npm-publish) * [npm registry](/using-npm/registry) -* [npm adduser](/commands/npm-adduser) * [npm owner](/commands/npm-owner) -* [npm login](/commands/npm-adduser) +* [npm login](/commands/npm-login) diff --git a/docs/lib/content/commands/npm-unstar.md b/docs/lib/content/commands/npm-unstar.md deleted file mode 100644 index aedeb92a6d71e..0000000000000 --- a/docs/lib/content/commands/npm-unstar.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: npm-unstar -section: 1 -description: Remove an item from your favorite packages ---- - -### Synopsis - - - -### Description - -"Unstarring" a package is the opposite of [`npm star`](/commands/npm-star), -it removes an item from your list of favorite packages. - -### More - -There's also these extra commands to help you manage your favorite packages: - -#### Star - -You can "star" a package using [`npm star`](/commands/npm-star) - -#### Listing stars - -You can see all your starred packages using [`npm stars`](/commands/npm-stars) - -### Configuration - - - -### See Also - -* [npm star](/commands/npm-star) -* [npm stars](/commands/npm-stars) -* [npm view](/commands/npm-view) -* [npm whoami](/commands/npm-whoami) -* [npm adduser](/commands/npm-adduser) - diff --git a/docs/lib/content/commands/npm-update.md b/docs/lib/content/commands/npm-update.md index 65919a4a7f914..088737a53c63d 100644 --- a/docs/lib/content/commands/npm-update.md +++ b/docs/lib/content/commands/npm-update.md @@ -10,30 +10,21 @@ description: Update packages ### Description -This command will update all the packages listed to the latest version -(specified by the [`tag` config](/using-npm/config#tag)), respecting the semver -constraints of both your package and its dependencies (if they also require the -same package). +This command will update all the packages listed to the latest version (specified by the [`tag` config](/using-npm/config#tag)), respecting the semver constraints of both your package and its dependencies (if they also require the same package). It will also install missing packages. -If the `-g` flag is specified, this command will update globally installed -packages. +If the `-g` flag is specified, this command will update globally installed packages. -If no package name is specified, all packages in the specified location (global -or local) will be updated. +If no package name is specified, all packages in the specified location (global or local) will be updated. -Note that by default `npm update` will not update the semver values of direct -dependencies in your project `package.json`. If you want to also update -values in `package.json` you can run: `npm update --save` (or add the -`save=true` option to a [configuration file](/configuring-npm/npmrc) -to make that the default behavior). +Note that by default `npm update` will not update the semver values of direct dependencies in your project `package.json`. +If you want to also update values in `package.json` you can run: `npm update --save` (or add the `save=true` option to a [configuration file](/configuring-npm/npmrc) to make that the default behavior). ### Example -For the examples below, assume that the current package is `app` and it depends -on dependencies, `dep1` (`dep2`, .. etc.). The published versions of `dep1` -are: +For the examples below, assume that the current package is `app` and it depends on dependencies, `dep1` (`dep2`, .. etc.). +The published versions of `dep1` are: ```json { @@ -75,9 +66,9 @@ However, if `app`'s `package.json` contains: } ``` -In this case, running `npm update` will install `dep1@1.1.2`. Even though the -`latest` tag points to `1.2.2`, this version does not satisfy `~1.1.1`, which is -equivalent to `>=1.1.1 <1.2.0`. So the highest-sorting version that satisfies +In this case, running `npm update` will install `dep1@1.1.2`. +Even though the `latest` tag points to `1.2.2`, this version does not satisfy `~1.1.1`, which is equivalent to `>=1.1.1 <1.2.0`. +So the highest-sorting version that satisfies `~1.1.1` is used, which is `1.1.2`. #### Caret Dependencies below 1.0.0 @@ -100,8 +91,7 @@ If the dependence were on `^0.4.0`: } ``` -Then `npm update` will install `dep1@0.4.1`, because that is the highest-sorting -version that satisfies `^0.4.0` (`>= 0.4.0 <0.5.0`) +Then `npm update` will install `dep1@0.4.1`, because that is the highest-sorting version that satisfies `^0.4.0` (`>= 0.4.0 <0.5.0`) #### Subdependencies @@ -129,26 +119,18 @@ and `dep2` itself depends on this limited range of `dep1` } ``` -Then `npm update` will install `dep1@1.1.2` because that is the highest -version that `dep2` allows. npm will prioritize having a single version -of `dep1` in your tree rather than two when that single version can -satisfy the semver requirements of multiple dependencies in your tree. -In this case if you really did need your package to use a newer version -you would need to use `npm install`. +Then `npm update` will install `dep1@1.1.2` because that is the highest version that `dep2` allows. + npm will prioritize having a single version of `dep1` in your tree rather than two when that single version can satisfy the semver requirements of multiple dependencies in your tree. +In this case if you really did need your package to use a newer version you would need to use `npm install`. #### Updating Globally-Installed Packages -`npm update -g` will apply the `update` action to each globally installed -package that is `outdated` -- that is, has a version that is different from -`wanted`. +`npm update -g` will apply the `update` action to each globally installed package that is `outdated` -- that is, has a version that is different from `wanted`. -Note: Globally installed packages are treated as if they are installed with a -caret semver range specified. So if you require to update to `latest` you may -need to run `npm install -g [...]` +Note: Globally installed packages do not have a `package.json` semver range available, so their `wanted` version is `latest`. -NOTE: If a package has been upgraded to a version newer than `latest`, it will -be _downgraded_. +NOTE: If a package has been upgraded to a version newer than `latest`, it will be _downgraded_. ### Configuration @@ -158,7 +140,6 @@ be _downgraded_. * [npm install](/commands/npm-install) * [npm outdated](/commands/npm-outdated) -* [npm shrinkwrap](/commands/npm-shrinkwrap) * [npm registry](/using-npm/registry) * [npm folders](/configuring-npm/folders) * [npm ls](/commands/npm-ls) diff --git a/docs/lib/content/commands/npm-version.md b/docs/lib/content/commands/npm-version.md index 08e74ef307afd..cca8106a00831 100644 --- a/docs/lib/content/commands/npm-version.md +++ b/docs/lib/content/commands/npm-version.md @@ -14,69 +14,62 @@ description: Bump a package version ### 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 `git-tag-version` (see below), and can be -disabled on the command line by running `npm --no-git-tag-version version`. -It will fail if the working directory is not clean, unless the `-f` or -`--force` flag is set. - -If supplied with `-m` or [`--message` config](/using-npm/config#message) option, -npm will use it as a commit message when creating a version commit. If the -`message` config contains `%s` then that will be replaced with the resulting -version number. For example: +Run this in a package directory to bump the version and write the new data back to `package.json` and `package-lock.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. + +**Note:** If the current version is a prerelease version, `patch` will simply remove the prerelease suffix without incrementing the patch version number. For example, `1.2.0-5` becomes `1.2.0` with `npm version patch`, not `1.2.1`. + +If run in a git repo, it will also create a version commit and tag. +This behavior is controlled by `git-tag-version` (see below), and can be disabled on the command line by running `npm --no-git-tag-version version`. +It will fail if the working directory is not clean, unless the `-f` or `--force` flag is set. + +**Note:** Git integration requires a reasonably recent version of git (2.0.0 or later is recommended). If you encounter issues with git commands, ensure your git installation is up to date. + +If supplied with `-m` or [`--message` config](/using-npm/config#message) option, npm will use it as a commit message when creating a version commit. +If the `message` config contains `%s` then that will be replaced with the resulting version number. +For example: ```bash npm version patch -m "Upgrade to %s for reasons" ``` -If the [`sign-git-tag` config](/using-npm/config#sign-git-tag) 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. For example: +If the [`sign-git-tag` config](/using-npm/config#sign-git-tag) 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. +For example: ```bash $ npm config set sign-git-tag true $ npm version patch -You need a passphrase to unlock the secret key for -user: "isaacs (http://blog.izs.me/) " +You need a passphrase to unlock the secret key for user: "isaacs (http://blog.izs.me/) " 2048-bit RSA key, ID 6C481CF6, created 2010-08-31 Enter passphrase: ``` -If `preversion`, `version`, or `postversion` are in the `scripts` property -of the package.json, they will be executed as part of running `npm -version`. +If `preversion`, `version`, or `postversion` are in the `scripts` property of the package.json, they will be executed as part of running `npm version`. 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. +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`, 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`. +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`, 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. +6. Run the `postversion` script. + Use it to clean up the file system or automatically push the commit and/or tag. + +For the `preversion`, `version` and `postversion` scripts, npm also sets the [environment variables](/using-npm/scripts#environment) `npm_old_version` and `npm_new_version`. Take the following example: @@ -90,15 +83,14 @@ Take the following example: } ``` -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. +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. ### See Also * [npm init](/commands/npm-init) -* [npm run-script](/commands/npm-run-script) +* [npm run](/commands/npm-run) * [npm scripts](/using-npm/scripts) * [package.json](/configuring-npm/package-json) * [config](/using-npm/config) diff --git a/docs/lib/content/commands/npm-view.md b/docs/lib/content/commands/npm-view.md index 63ff520e7bd29..36b8b93c0ddc1 100644 --- a/docs/lib/content/commands/npm-view.md +++ b/docs/lib/content/commands/npm-view.md @@ -29,7 +29,8 @@ npm view ronn@0.3.5 dependencies ``` By default, `npm view` shows data about the current project context (by looking for a `package.json`). -To show field data for the current project use a file path (i.e. `.`): +To show field data for the current project use a file path (i.e. +`.`): ```bash npm view . dependencies @@ -42,25 +43,22 @@ To view the git repository URL for the latest version of `npm`, you would run th npm view npm repository.url ``` -This makes it easy to view information about a dependency with a bit of -shell scripting. For example, to view all the data about the version of -`opts` that `ronn` depends on, you could write the following: +This makes it easy to view information about a dependency with a bit of shell scripting. +For example, to view all the data about the version of `opts` that `ronn` depends on, you could write the following: ```bash npm view opts@$(npm view ronn dependencies.opts) ``` -For fields that are arrays, requesting a non-numeric field will return -all of the values from the objects in the list. For example, to get all -the contributor email addresses for the `express` package, you would run: +For fields that are arrays, requesting a non-numeric field will return all of the values from the objects in the list. +For example, to get all the contributor email addresses for the `express` package, you would run: ```bash npm view express contributors.email ``` -You may also use numeric indices in square braces to specifically select -an item in an array field. To just get the email address of the first -contributor in the list, you can run: +You may also use numeric indices in square braces to specifically select an item in an array field. +To just get the email address of the first contributor in the list, you can run: ```bash npm view express contributors[0].email @@ -72,54 +70,115 @@ If the field value you are querying for is a property of an object, you should r npm view express time'[4.8.0]' ``` +Note: When accessing object properties that contain special characters or numeric keys, you need to use quotes around the key name. +For example, to get the publish time of a specific version: + +```bash +npm view express "time[4.17.1]" +``` + +Without quotes, the shell may interpret the square brackets as glob patterns, causing the command to fail. +You can also access the time field for a specific version by specifying the version in the package descriptor: + +```bash +npm view express@4.17.1 time +``` + +This will return all version-time pairs, but the context will be for that specific version. + Multiple fields may be specified, and will be printed one after another. -For example, to get all the contributor names and email addresses, you -can do this: +For example, to get all the contributor names and email addresses, you can do this: ```bash npm view express contributors.name contributors.email ``` -"Person" fields are shown as a string if they would be shown as an -object. So, for example, this will show the list of `npm` contributors in -the shortened string format. (See [`package.json`](/configuring-npm/package-json) for more on this.) +"Person" fields are shown as a string if they would be shown as an object. +So, for example, this will show the list of `npm` contributors in the shortened string format. + (See [`package.json`](/configuring-npm/package-json) for more on this.) ```bash npm view npm contributors ``` -If a version range is provided, then data will be printed for every -matching version of the package. This will show which version of `jsdom` -was required by each matching version of `yui3`: +If a version range is provided, then data will be printed for every matching version of the package. +This will show which version of `jsdom` was required by each matching version of `yui3`: ```bash npm view yui3@'>0.5.4' dependencies.jsdom ``` -To show the `connect` package version history, you can do -this: +To show the `connect` package version history, you can do this: ```bash npm view connect versions ``` +### Field Access Patterns + +The `npm view` command supports different ways to access nested fields and array elements in package metadata. Understanding these patterns makes it easier to extract specific information. + +#### Nested Object Fields + +Use dot notation to access nested object fields: + +```bash +# Access nested properties +npm view npm repository.url +npm view express bugs.url +``` + +#### Array Element Access + +For arrays, use numeric indices in square brackets to access specific elements: + +```bash +# Get the first contributor's email +npm view express contributors[0].email + +# Get the second maintainer's name +npm view express maintainers[1].name +``` + +#### Object Property Access + +For object properties (like accessing specific versions in the `time` field), use bracket notation with the property name in quotes: + +```bash +# Get publish time for a specific version +npm view express "time[4.17.1]" + +# Get dist-tags +npm view express "dist-tags.latest" +``` + +#### Extracting Fields from Arrays + +Request a non-numeric field on an array to get all values from objects in the list: + +```bash +# Get all contributor emails +npm view express contributors.email + +# Get all contributor names +npm view express contributors.name +``` + ### Configuration ### Output -If only a single string field for a single version is output, then it -will not be colorized or quoted, to enable piping the output to -another command. If the field is an object, it will be output as a JavaScript object literal. +If only a single string field for a single version is output, then it will not be colorized or quoted, to enable piping the output to another command. +If the field is an object, it will be output as a JavaScript object literal. If the `--json` flag is given, the outputted fields will be JSON. +The output is always an array, even if only a single version matches. -If the version range matches multiple versions then each printed value -will be prefixed with the version it applies to. +If the version range matches multiple versions then each printed value will be prefixed with the version it applies to. -If multiple fields are requested, then each of them is prefixed with -the field name. +If multiple fields are requested, then each of them is prefixed with the field name. ### See Also diff --git a/docs/lib/content/commands/npm-whoami.md b/docs/lib/content/commands/npm-whoami.md index 99c787d62ef76..04a9e8b65e4a3 100644 --- a/docs/lib/content/commands/npm-whoami.md +++ b/docs/lib/content/commands/npm-whoami.md @@ -12,12 +12,9 @@ description: Display npm username Display the npm username of the currently logged-in user. -If logged into a registry that provides token-based authentication, then -connect to the `/-/whoami` registry endpoint to find the username -associated with the token, and print to standard output. +If logged into a registry that provides token-based authentication, then connect to the `/-/whoami` registry endpoint to find the username associated with the token, and print to standard output. -If logged into a registry that uses Basic Auth, then simply print the -`username` portion of the authentication string. +If logged into a registry that uses Basic Auth, then simply print the `username` portion of the authentication string. ### Configuration @@ -27,4 +24,4 @@ If logged into a registry that uses Basic Auth, then simply print the * [npm config](/commands/npm-config) * [npmrc](/configuring-npm/npmrc) -* [npm adduser](/commands/npm-adduser) +* [npm login](/commands/npm-login) diff --git a/docs/lib/content/commands/npm.md b/docs/lib/content/commands/npm.md index 5dac1b24bf66c..f4c8ff37742e1 100644 --- a/docs/lib/content/commands/npm.md +++ b/docs/lib/content/commands/npm.md @@ -14,134 +14,107 @@ description: javascript package manager ### Description -npm is the package manager for the Node JavaScript platform. It puts -modules in place so that node can find them, and manages dependency -conflicts intelligently. +npm is the package manager for the Node JavaScript platform. +It puts modules in place so that node can find them, and manages dependency conflicts intelligently. -It is extremely configurable to support a variety of use cases. Most -commonly, you use it to publish, discover, install, and develop node -programs. +It is extremely configurable to support a variety of use cases. +Most commonly, you use it to publish, discover, install, and develop node programs. Run `npm help` to get a list of available commands. ### Important -npm comes preconfigured to use npm's public registry at -https://registry.npmjs.org by default. Use of the npm public registry is -subject to terms of use available at -https://docs.npmjs.com/policies/terms. +npm comes preconfigured to use npm's public registry at https://registry.npmjs.org by default. +Use of the npm public registry is subject to terms of use available at https://docs.npmjs.com/policies/terms. -You can configure npm to use any compatible registry you like, and even -run your own registry. Use of someone else's registry is governed by -their terms of use. +You can configure npm to use any compatible registry you like, and even run your own registry. +Use of someone else's registry is governed by their terms of use. ### Introduction You probably got npm because you want to install stuff. -The very first thing you will most likely want to run in any node -program is `npm install` to install its dependencies. +The very first thing you will most likely want to run in any node program is `npm install` to install its dependencies. -You can also run `npm install blerg` to install the latest version of -"blerg". Check out [`npm install`](/commands/npm-install) for more -info. It can do a lot of stuff. +You can also run `npm install blerg` to install the latest version of "blerg". Check out [`npm install`](/commands/npm-install) for more info. +It can do a lot of stuff. -Use the `npm search` command to show everything that's available in the -public registry. Use `npm ls` to show everything you've installed. +Use the `npm search` command to show everything that's available in the public registry. +Use `npm ls` to show everything you've installed. ### Dependencies -If a package lists a dependency using a git URL, npm will install that -dependency using the [`git`](https://github.com/git-guides/install-git) -command and will generate an error if it is not installed. +If a package lists a dependency using a git URL, npm will install that dependency using the [`git`](https://github.com/git-guides/install-git) command and will generate an error if it is not installed. -If one of the packages npm tries to install is a native node module and -requires compiling of C++ Code, npm will use -[node-gyp](https://github.com/nodejs/node-gyp) for that task. -For a Unix system, [node-gyp](https://github.com/nodejs/node-gyp) -needs Python, make and a buildchain like GCC. On Windows, -Python and Microsoft Visual Studio C++ are needed. For more information -visit [the node-gyp repository](https://github.com/nodejs/node-gyp) and -the [node-gyp Wiki](https://github.com/nodejs/node-gyp/wiki). +If one of the packages npm tries to install is a native node module and requires compiling of C++ Code, npm will use [node-gyp](https://github.com/nodejs/node-gyp) for that task. +For a Unix system, [node-gyp](https://github.com/nodejs/node-gyp) needs Python, make and a buildchain like GCC. On Windows, Python and Microsoft Visual Studio C++ are needed. +For more information visit [the node-gyp repository](https://github.com/nodejs/node-gyp) and the [node-gyp Wiki](https://github.com/nodejs/node-gyp/wiki). ### Directories -See [`folders`](/configuring-npm/folders) to learn about where npm puts -stuff. +See [`folders`](/configuring-npm/folders) to learn about where npm puts stuff. In particular, npm has two modes of operation: * local mode: - npm installs packages into the current project directory, which - defaults to the current working directory. Packages install to - `./node_modules`, and bins to `./node_modules/.bin`. + npm installs packages into the current project directory, which defaults to the current working directory. + Packages install to `./node_modules`, and bins to `./node_modules/.bin`. * global mode: - npm installs packages into the install prefix at - `$npm_config_prefix/lib/node_modules` and bins to - `$npm_config_prefix/bin`. + npm installs packages into the install prefix at `$NPM_CONFIG_PREFIX/lib/node_modules` and bins to `$NPM_CONFIG_PREFIX/bin`. -Local mode is the default. Use `-g` or `--global` on any command to -run in global mode instead. +Local mode is the default. +Use `-g` or `--global` on any command to run in global mode instead. ### Developer Usage -If you're using npm to develop and publish your code, check out the -following help topics: +If you're using npm to develop and publish your code, check out the following help topics: * json: - Make a package.json file. See - [`package.json`](/configuring-npm/package-json). + Make a package.json file. + See [`package.json`](/configuring-npm/package-json). * link: - Links your current working code into Node's path, so that you don't - have to reinstall every time you make a change. Use [`npm - link`](/commands/npm-link) to do this. + Links your current working code into Node's path, so that you don't have to reinstall every time you make a change. + Use [`npm link`](/commands/npm-link) to do this. * install: - It's a good idea to install things if you don't need the symbolic - link. Especially, installing other peoples code from the registry is - done via [`npm install`](/commands/npm-install) -* adduser: - Create an account or log in. When you do this, npm will store - credentials in the user config file. + It's a good idea to install things if you don't need the symbolic link. + Especially, installing other peoples code from the registry is done via [`npm install`](/commands/npm-install) +* login: + Log in to the registry and store credentials. + When you do this, npm will store credentials in the user config file. * publish: - Use the [`npm publish`](/commands/npm-publish) command to upload your - code to the registry. + Use the [`npm publish`](/commands/npm-publish) command to upload your code to the registry. #### Configuration -npm is extremely configurable. It reads its configuration options from -5 places. +npm is extremely configurable. +It reads its configuration options from 5 places. * Command line switches: - Set a config with `--key val`. All keys take a value, even if they - are booleans (the config parser doesn't know what the options are at - the time of parsing). If you do not provide a value (`--key`) then - the option is set to boolean `true`. + Set a config with `--key val`. + All keys take a value, even if they are booleans (the config parser doesn't know what the options are at the time of parsing). + If you do not provide a value (`--key`) then the option is set to boolean `true`. * Environment Variables: - Set any config by prefixing the name in an environment variable with - `npm_config_`. For example, `export npm_config_key=val`. + Set any config by prefixing the name in an environment variable with `NPM_CONFIG_`. + For example, `export NPM_CONFIG_KEY=val`. * User Configs: - The file at `$HOME/.npmrc` is an ini-formatted list of configs. If - present, it is parsed. If the `userconfig` option is set in the cli - or env, that file will be used instead. + The file at `$HOME/.npmrc` is an ini-formatted list of configs. + If present, it is parsed. + If the `userconfig` option is set in the cli or env, that file will be used instead. * Global Configs: - The file found at `./etc/npmrc` (relative to the global prefix will be - parsed if it is found. See [`npm prefix`](/commands/npm-prefix) for - more info on the global prefix. If the `globalconfig` option is set - in the cli, env, or user config, then that file is parsed instead. + The file found at `./etc/npmrc` (relative to the global prefix will be parsed if it is found. + See [`npm prefix`](/commands/npm-prefix) for more info on the global prefix. + If the `globalconfig` option is set in the cli, env, or user config, then that file is parsed instead. * Defaults: - npm's default configuration options are defined in - `lib/utils/config/definitions.js`. These must not be changed. + npm's default configuration options are defined in `lib/utils/config/definitions.js`. + These must not be changed. -See [`config`](/using-npm/config) for much much more information. +See [`config`](/using-npm/config) for much, much, more information. ### Contributions Patches welcome! -If you would like to help, but don't know what to work on, read the -[contributing -guidelines](https://github.com/npm/cli/blob/latest/CONTRIBUTING.md) and -check the issues list. +If you would like to help, but don't know what to work on, read the [contributing guidelines](https://github.com/npm/cli/blob/latest/CONTRIBUTING.md) and check the issues list. ### Bugs diff --git a/docs/lib/content/commands/npx.md b/docs/lib/content/commands/npx.md index ca72b3e03bdae..598cbece85f67 100644 --- a/docs/lib/content/commands/npx.md +++ b/docs/lib/content/commands/npx.md @@ -10,52 +10,34 @@ description: Run a command from a local or remote npm package ### Description -This command allows you to run an arbitrary command from an npm package -(either one installed locally, or fetched remotely), in a similar context -as running it via `npm run`. - -Whatever packages are specified by the `--package` option will be -provided in the `PATH` of the executed command, along with any locally -installed package executables. The `--package` option may be -specified multiple times, to execute the supplied command in an environment -where all specified packages are available. - -If any requested packages are not present in the local project -dependencies, then they are installed to a folder in the npm cache, which -is added to the `PATH` environment variable in the executed process. A -prompt is printed (which can be suppressed by providing either `--yes` or -`--no`). - -Package names provided without a specifier will be matched with whatever -version exists in the local project. Package names with a specifier will -only be considered a match if they have the exact same name and version as -the local dependency. - -If no `-c` or `--call` option is provided, then the positional arguments -are used to generate the command string. If no `--package` options -are provided, then npm will attempt to determine the executable name from -the package specifier provided as the first positional argument according -to the following heuristic: - -- If the package has a single entry in its `bin` field in `package.json`, - or if all entries are aliases of the same command, then that command - will be used. -- If the package has multiple `bin` entries, and one of them matches the - unscoped portion of the `name` field, then that command will be used. -- If this does not result in exactly one option (either because there are - no bin entries, or none of them match the `name` of the package), then +This command allows you to run an arbitrary command from an npm package (either one installed locally, or fetched remotely), in a similar context as running it via `npm run`. + +Run this command to execute a package's binary. Any options and arguments after the package name are passed directly to the executed command, not to npx itself. For example, `npx create-react-app my-app --template typescript` will pass `my-app` and `--template typescript` to the `create-react-app` command. To see what options a specific package accepts, consult that package's documentation (e.g., at npmjs.com or in its repository). + +Whatever packages are specified by the `--package` option will be provided in the `PATH` of the executed command, along with any locally installed package executables. +The `--package` option may be specified multiple times, to execute the supplied command in an environment where all specified packages are available. + +If any requested packages are not present in the local project dependencies, then they are installed to a folder in the npm cache, which is added to the `PATH` environment variable in the executed process. +A prompt is printed (which can be suppressed by providing either `--yes` or `--no`). + +Package names provided without a specifier will be matched with whatever version exists in the local project. +Package names with a specifier will only be considered a match if they have the exact same name and version as the local dependency. + +If no `-c` or `--call` option is provided, then the positional arguments are used to generate the command string. +If no `--package` options are provided, then npm will attempt to determine the executable name from the package specifier provided as the first positional argument according to the following heuristic: + +- If the package has a single entry in its `bin` field in `package.json`, or if all entries are aliases of the same command, then that command will be used. +- If the package has multiple `bin` entries, and one of them matches the unscoped portion of the `name` field, then that command will be used. +- If this does not result in exactly one option (either because there are no bin entries, or none of them match the `name` of the package), then `npm exec` exits with an error. To run a binary _other than_ the named binary, specify one or more -`--package` options, which will prevent npm from inferring the package from -the first command argument. +`--package` options, which will prevent npm from inferring the package from the first command argument. ### `npx` vs `npm exec` -When run via the `npx` binary, all flags and options *must* be set prior to -any positional arguments. When run via `npm exec`, a double-hyphen `--` -flag can be used to suppress npm's parsing of switches and options that -should be sent to the executed command. +When run via the `npx` binary, all flags and options *must* be set prior to any positional arguments. +When run via `npm exec`, a double-hyphen `--` flag can be used to suppress npm's parsing of switches and options that should be sent to the executed command. For example: @@ -63,34 +45,30 @@ For example: $ npx foo@latest bar --package=@npmcli/foo ``` -In this case, npm will resolve the `foo` package name, and run the -following command: +In this case, npm will resolve the `foo` package name, and run the following command: ``` $ foo bar --package=@npmcli/foo ``` -Since the `--package` option comes _after_ the positional arguments, it is -treated as an argument to the executed command. +Since the `--package` option comes _after_ the positional arguments, it is treated as an argument to the executed command. -In contrast, due to npm's argument parsing logic, running this command is -different: +In contrast, due to npm's argument parsing logic, running this command is different: ``` $ npm exec foo@latest bar --package=@npmcli/foo ``` In this case, npm will parse the `--package` option first, resolving the -`@npmcli/foo` package. Then, it will execute the following command in that -context: +`@npmcli/foo` package. +Then, it will execute the following command in that context: ``` $ foo@latest bar ``` -The double-hyphen character is recommended to explicitly tell npm to stop -parsing command line options and switches. The following command would -thus be equivalent to the `npx` command above: +The double-hyphen character is recommended to explicitly tell npm to stop parsing command line options and switches. +The following command would thus be equivalent to the `npx` command above: ``` $ npm exec -- foo@latest bar --package=@npmcli/foo @@ -98,16 +76,14 @@ $ npm exec -- foo@latest bar --package=@npmcli/foo ### Examples -Run the version of `tap` in the local dependencies, with the provided -arguments: +Run the version of `tap` in the local dependencies, with the provided arguments: ``` $ npm exec -- tap --bail test/foo.js $ npx tap --bail test/foo.js ``` -Run a command _other than_ the command whose name matches the package name -by specifying a `--package` option: +Run a command _other than_ the command whose name matches the package name by specifying a `--package` option: ``` $ npm exec --package=foo -- bar --bar-argument @@ -124,36 +100,31 @@ $ npx -c 'eslint && say "hooray, lint passed"' ### Compatibility with Older npx Versions -The `npx` binary was rewritten in npm v7.0.0, and the standalone `npx` -package deprecated at that time. `npx` uses the `npm exec` -command instead of a separate argument parser and install process, with -some affordances to maintain backwards compatibility with the arguments it -accepted in previous versions. +The `npx` binary was rewritten in npm v7.0.0, and the standalone `npx` package deprecated at that time. + `npx` uses the `npm exec` command instead of a separate argument parser and install process, with some affordances to maintain backwards compatibility with the arguments it accepted in previous versions. This resulted in some shifts in its functionality: - Any `npm` config value may be provided. -- To prevent security and user-experience problems from mistyping package - names, `npx` prompts before installing anything. Suppress this - prompt with the `-y` or `--yes` option. +- To prevent security and user-experience problems from mistyping package names, `npx` prompts before installing anything. +Suppress this prompt with the `-y` or `--yes` option. - The `--no-install` option is deprecated, and will be converted to `--no`. - Shell fallback functionality is removed, as it is not advisable. -- The `-p` argument is a shorthand for `--parseable` in npm, but shorthand - for `--package` in npx. This is maintained, but only for the `npx` - executable. -- The `--ignore-existing` option is removed. Locally installed bins are - always present in the executed process `PATH`. -- The `--npm` option is removed. `npx` will always use the `npm` it ships - with. -- The `--node-arg` and `-n` options have been removed. Use [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#node_optionsoptions) instead: e.g., +- The `-p` argument is a shorthand for `--parseable` in npm, but shorthand for `--package` in npx. +This is maintained, but only for the `npx` executable. +- The `--ignore-existing` option is removed. +Locally installed bins are always present in the executed process `PATH`. +- The `--npm` option is removed. + `npx` will always use the `npm` it ships with. +- The `--node-arg` and `-n` options have been removed. +Use [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#node_optionsoptions) instead: e.g., `NODE_OPTIONS="--trace-warnings --trace-exit" npx foo --random=true` - The `--always-spawn` option is redundant, and thus removed. -- The `--shell` option is replaced with `--script-shell`, but maintained - in the `npx` executable for backwards compatibility. +- The `--shell` option is replaced with `--script-shell`, but maintained in the `npx` executable for backwards compatibility. ### See Also -* [npm run-script](/commands/npm-run-script) +* [npm run](/commands/npm-run) * [npm scripts](/using-npm/scripts) * [npm test](/commands/npm-test) * [npm start](/commands/npm-start) diff --git a/docs/lib/content/configuring-npm/folders.md b/docs/lib/content/configuring-npm/folders.md index 5fb4ca257fc33..20458512d8b90 100644 --- a/docs/lib/content/configuring-npm/folders.md +++ b/docs/lib/content/configuring-npm/folders.md @@ -1,65 +1,54 @@ --- -title: folders +title: Folders section: 5 -description: Folder Structures Used by npm +description: Folder structures used by npm --- ### Description -npm puts various things on your computer. That's its job. +npm puts various things on your computer. +That's its job. This document will tell you what it puts where. #### tl;dr -* Local install (default): puts stuff in `./node_modules` of the current - package root. -* Global install (with `-g`): puts stuff in /usr/local or wherever node - is installed. +* Local install (default): puts stuff in `./node_modules` of the current package root. +* Global install (with `-g`): puts stuff in /usr/local or wherever node is installed. * Install it **locally** if you're going to `require()` it. * Install it **globally** if you're going to run it on the command line. * If you need both, then install it in both places, or use `npm link`. #### prefix Configuration -The [`prefix` config](/using-npm/config#prefix) defaults to the location where -node is installed. On most systems, this is `/usr/local`. On Windows, it's -`%AppData%\npm`. On Unix systems, it's one level up, since node is typically -installed at `{prefix}/bin/node` rather than `{prefix}/node.exe`. +The [`prefix` config](/using-npm/config#prefix) defaults to the location where node is installed. +On most systems, this is `/usr/local`. +On Windows, it's `%AppData%\npm`. +On Unix systems, it's one level up, since node is typically installed at `{prefix}/bin/node` rather than `{prefix}/node.exe`. When the `global` flag is set, npm installs things into this prefix. -When it is not set, it uses the root of the current package, or the -current working directory if not in a package already. +When it is not set, it uses the root of the current package, or the current working directory if not in a package already. #### Node Modules Packages are dropped into the `node_modules` folder under the `prefix`. -When installing locally, this means that you can -`require("packagename")` to load its main module, or -`require("packagename/lib/path/to/sub/module")` to load other modules. +When installing locally, this means that you can `require("packagename")` to load its main module, or `require("packagename/lib/path/to/sub/module")` to load other modules. Global installs on Unix systems go to `{prefix}/lib/node_modules`. -Global installs on Windows go to `{prefix}/node_modules` (that is, no -`lib` folder.) +Global installs on Windows go to `{prefix}/node_modules` (that is, no `lib` folder.) -Scoped packages are installed the same way, except they are grouped together -in a sub-folder of the relevant `node_modules` folder with the name of that -scope prefix by the @ symbol, e.g. `npm install @myorg/package` would place -the package in `{prefix}/node_modules/@myorg/package`. See -[`scope`](/using-npm/scope) for more details. +Scoped packages are installed the same way, except they are grouped together in a sub-folder of the relevant `node_modules` folder with the name of that scope prefix by the @ symbol, e.g. `npm install @myorg/package` would place the package in `{prefix}/node_modules/@myorg/package`. +See [`scope`](/using-npm/scope) for more details. If you wish to `require()` a package, then install it locally. #### Executables -When in global mode, executables are linked into `{prefix}/bin` on Unix, -or directly into `{prefix}` on Windows. Ensure that path is in your -terminal's `PATH` environment to run them. +When in global mode, executables are linked into `{prefix}/bin` on Unix, or directly into `{prefix}` on Windows. +Ensure that path is in your terminal's `PATH` environment to run them. -When in local mode, executables are linked into -`./node_modules/.bin` so that they can be made available to scripts run -through npm. (For example, so that a test runner will be in the path -when you run `npm test`.) +When in local mode, executables are linked into `./node_modules/.bin` so that they can be made available to scripts run through npm. +(For example, so that a test runner will be in the path when you run `npm test`.) #### Man Pages @@ -71,76 +60,48 @@ Man pages are not installed on Windows systems. #### Cache -See [`npm cache`](/commands/npm-cache). Cache files are stored in `~/.npm` on Posix, or -`%LocalAppData%/npm-cache` on Windows. +See [`npm cache`](/commands/npm-cache). +Cache files are stored in `~/.npm` on Posix, or `%LocalAppData%/npm-cache` on Windows. This is controlled by the [`cache` config](/using-npm/config#cache) param. -#### Temp Files - -Temporary files are stored by default in the folder specified by the -[`tmp` config](/using-npm/config#tmp), which defaults to the TMPDIR, TMP, or -TEMP environment variables, or `/tmp` on Unix and `c:\windows\temp` on Windows. - -Temp files are given a unique folder under this root for each run of the -program, and are deleted upon successful exit. - ### More Information -When installing locally, npm first tries to find an appropriate -`prefix` folder. This is so that `npm install foo@1.2.3` will install -to the sensible root of your package, even if you happen to have `cd`ed -into some other folder. +When installing locally, npm first tries to find an appropriate `prefix` folder. +This is so that `npm install foo@1.2.3` will install to the sensible root of your package, even if you happen to have `cd`ed into some other folder. -Starting at the $PWD, npm will walk up the folder tree checking for a -folder that contains either a `package.json` file, or a `node_modules` -folder. If such a thing is found, then that is treated as the effective -"current directory" for the purpose of running npm commands. (This -behavior is inspired by and similar to git's .git-folder seeking -logic when running git commands in a working dir.) +Starting at the $PWD, npm will walk up the folder tree checking for a folder that contains either a `package.json` file, or a `node_modules` folder. +If such a thing is found, then that is treated as the effective "current directory" for the purpose of running npm commands. +(This behavior is inspired by and similar to git's .git-folder seeking logic when running git commands in a working dir.) If no package root is found, then the current folder is used. -When you run `npm install foo@1.2.3`, then the package is loaded into -the cache, and then unpacked into `./node_modules/foo`. Then, any of -foo's dependencies are similarly unpacked into -`./node_modules/foo/node_modules/...`. +When you run `npm install foo@1.2.3`, then the package is loaded into the cache, and then unpacked into `./node_modules/foo`. +Then, any of foo's dependencies are similarly unpacked into `./node_modules/foo/node_modules/...`. -Any bin files are symlinked to `./node_modules/.bin/`, so that they may -be found by npm scripts when necessary. +Any bin files are symlinked to `./node_modules/.bin/`, so that they may be found by npm scripts when necessary. #### Global Installation -If the [`global` config](/using-npm/config#global) is set to true, then npm will -install packages "globally". +If the [`global` config](/using-npm/config#global) is set to true, then npm will install packages "globally". -For global installation, packages are installed roughly the same way, -but using the folders described above. +For global installation, packages are installed roughly the same way, but using the folders described above. #### Cycles, Conflicts, and Folder Parsimony -Cycles are handled using the property of node's module system that it -walks up the directories looking for `node_modules` folders. So, at every -stage, if a package is already installed in an ancestor `node_modules` -folder, then it is not installed at the current location. - -Consider the case above, where `foo -> bar -> baz`. Imagine if, in -addition to that, baz depended on bar, so you'd have: -`foo -> bar -> baz -> bar -> baz ...`. However, since the folder -structure is: `foo/node_modules/bar/node_modules/baz`, there's no need to -put another copy of bar into `.../baz/node_modules`, since when baz calls -`require("bar")`, it will get the copy that is installed in -`foo/node_modules/bar`. - -This shortcut is only used if the exact same -version would be installed in multiple nested `node_modules` folders. It -is still possible to have `a/node_modules/b/node_modules/a` if the two -"a" packages are different versions. However, without repeating the -exact same package multiple times, an infinite regress will always be -prevented. - -Another optimization can be made by installing dependencies at the -highest level possible, below the localized "target" folder (hoisting). +Cycles are handled using the property of node's module system that it walks up the directories looking for `node_modules` folders. +So, at every stage, if a package is already installed in an ancestor `node_modules` folder, then it is not installed at the current location. + +Consider the case above, where `foo -> bar -> baz`. +Imagine if, in addition to that, baz depended on bar, so you'd have: +`foo -> bar -> baz -> bar -> baz ...`. +However, since the folder structure is: `foo/node_modules/bar/node_modules/baz`, there's no need to put another copy of bar into `.../baz/node_modules`, since when baz calls `require("bar")`, it will get the copy that is installed in `foo/node_modules/bar`. + +This shortcut is only used if the exact same version would be installed in multiple nested `node_modules` folders. +It is still possible to have `a/node_modules/b/node_modules/a` if the two "a" packages are different versions. +However, without repeating the exact same package multiple times, an infinite regress will always be prevented. + +Another optimization can be made by installing dependencies at the highest level possible, below the localized "target" folder (hoisting). Since version 3, npm hoists dependencies by default. #### Example @@ -161,8 +122,7 @@ foo `-- bar ``` -In this case, we might expect a folder structure like this -(with all dependencies hoisted to the highest level possible): +In this case, we might expect a folder structure like this (with all dependencies hoisted to the highest level possible): ```bash foo @@ -176,36 +136,29 @@ foo +-- quux (3.2.0) <---[E] ``` -Since foo depends directly on `bar@1.2.3` and `baz@1.2.3`, those are -installed in foo's `node_modules` folder. +Since foo depends directly on `bar@1.2.3` and `baz@1.2.3`, those are installed in foo's `node_modules` folder. -Even though the latest copy of blerg is 1.3.7, foo has a specific -dependency on version 1.2.5. So, that gets installed at [A]. Since the -parent installation of blerg satisfies bar's dependency on `blerg@1.x`, -it does not install another copy under [B]. +Even though the latest copy of blerg is 1.3.7, foo has a specific dependency on version 1.2.5. +So, that gets installed at [A]. +Since the parent installation of blerg satisfies bar's dependency on `blerg@1.x`, it does not install another copy under [B]. -Bar [B] also has dependencies on baz and asdf. Because it depends on `baz@2.x`, it cannot -re-use the `baz@1.2.3` installed in the parent `node_modules` folder [D], -and must install its own copy [C]. In order to minimize duplication, npm hoists -dependencies to the top level by default, so asdf is installed under [A]. +Bar [B] also has dependencies on baz and asdf. +Because it depends on `baz@2.x`, it cannot re-use the `baz@1.2.3` installed in the parent `node_modules` folder [D], and must install its own copy [C]. +In order to minimize duplication, npm hoists dependencies to the top level by default, so asdf is installed under [A]. Underneath bar, the `baz -> quux -> bar` dependency creates a cycle. -However, because bar is already in quux's ancestry [B], it does not -unpack another copy of bar into that folder. Likewise, quux's [E] -folder tree is empty, because its dependency on bar is satisfied -by the parent folder copy installed at [B]. +However, because bar is already in quux's ancestry [B], it does not unpack another copy of bar into that folder. +Likewise, quux's [E] folder tree is empty, because its dependency on bar is satisfied by the parent folder copy installed at [B]. For a graphical breakdown of what is installed where, use `npm ls`. #### Publishing -Upon publishing, npm will look in the `node_modules` folder. If any of -the items there are not in the `bundleDependencies` array, then they will -not be included in the package tarball. +Upon publishing, npm will look in the `node_modules` folder. +If any of the items there are not in the `bundleDependencies` array, then they will not be included in the package tarball. -This allows a package maintainer to install all of their dependencies -(and dev dependencies) locally, but only re-publish those items that -cannot be found elsewhere. See [`package.json`](/configuring-npm/package-json) for more information. +This allows a package maintainer to install all of their dependencies (and dev dependencies) locally, but only re-publish those items that cannot be found elsewhere. +See [`package.json`](/configuring-npm/package-json) for more information. ### See also diff --git a/docs/lib/content/configuring-npm/install.md b/docs/lib/content/configuring-npm/install.md index d9c1d32631fa1..4af74954692f8 100644 --- a/docs/lib/content/configuring-npm/install.md +++ b/docs/lib/content/configuring-npm/install.md @@ -1,32 +1,24 @@ --- -title: install +title: Install section: 5 description: Download and install node and npm --- ### Description -To publish and install packages to and from the public npm registry, you -must install Node.js and the npm command line interface using either a Node -version manager or a Node installer. **We strongly recommend using a Node -version manager to install Node.js and npm.** We do not recommend using a -Node installer, since the Node installation process installs npm in a -directory with local permissions and can cause permissions errors when you -run npm packages globally. +To publish and install packages to and from the public npm registry, you must install Node.js and the npm command line interface using either a Node version manager or a Node installer. +**We strongly recommend using a Node version manager to install Node.js and npm.** We do not recommend using a +Node installer, since the Node installation process installs npm in a directory with local permissions and can cause permissions errors when you run npm packages globally. ### Overview -- [Checking your version of npm and - Node.js](#checking-your-version-of-npm-and-nodejs) -- [Using a Node version manager to install Node.js and - npm](#using-a-node-version-manager-to-install-nodejs-and-npm) -- [Using a Node installer to install Node.js and - npm](#using-a-node-installer-to-install-nodejs-and-npm) +- [Checking your version of npm and Node.js](#checking-your-version-of-npm-and-nodejs) +- [Using a Node version manager to install Node.js and npm](#using-a-node-version-manager-to-install-nodejs-and-npm) +- [Using a Node installer to install Node.js and npm](#using-a-node-installer-to-install-nodejs-and-npm) ### Checking your version of npm and Node.js -To see if you already have Node.js and npm installed and check the -installed version, run the following commands: +To see if you already have Node.js and npm installed and check the installed version, run the following commands: ``` node -v @@ -35,44 +27,27 @@ npm -v ### Using a Node version manager to install Node.js and npm -Node version managers allow you to install and switch between multiple -versions of Node.js and npm on your system so you can test your -applications on multiple versions of npm to ensure they work for users on -different versions. You can -[search for them on GitHub](https://github.com/search?q=node+version+manager+archived%3Afalse&type=repositories&ref=advsearch). +Node version managers allow you to install and switch between multiple versions of Node.js and npm on your system so you can test your applications on multiple versions of npm to ensure they work for users on different versions. +You can [search for them on GitHub](https://github.com/search?q=node+version+manager+archived%3Afalse&type=repositories&ref=advsearch). ### Using a Node installer to install Node.js and npm -If you are unable to use a Node version manager, you can use a Node -installer to install both Node.js and npm on your system. +If you are unable to use a Node version manager, you can use a Node installer to install both Node.js and npm on your system. * [Node.js installer](https://nodejs.org/en/download/) -* [NodeSource installer](https://github.com/nodesource/distributions). If - you use Linux, we recommend that you use a NodeSource installer. +* [NodeSource installer](https://github.com/nodesource/distributions). +If you use Linux, we recommend that you use a NodeSource installer. -#### OS X or Windows Node installers +#### macOS or Windows Node installers -If you're using OS X or Windows, use one of the installers from the -[Node.js download page](https://nodejs.org/en/download/). Be sure to -install the version labeled **LTS**. Other versions have not yet been -tested with npm. +If you're using macOS or Windows, use one of the installers from the [Node.js download page](https://nodejs.org/en/download/). +Be sure to install the version labeled **LTS**. Other versions have not yet been tested with npm. #### Linux or other operating systems Node installers -If you're using Linux or another operating system, use one of the following -installers: +If you're using Linux or another operating system, use one of the following installers: -- [NodeSource installer](https://github.com/nodesource/distributions) - (recommended) -- One of the installers on the [Node.js download - page](https://nodejs.org/en/download/) +- [NodeSource installer](https://github.com/nodesource/distributions) (recommended) +- One of the installers on the [Node.js download page](https://nodejs.org/en/download/) -Or see [this page](https://nodejs.org/en/download/package-manager/) to -install npm for Linux in the way many Linux developers prefer. - -#### Less-common operating systems - -For more information on installing Node.js on a variety of operating -systems, see [this page][pkg-mgr]. - -[pkg-mgr]: https://nodejs.org/en/download/package-manager/ +Or see [this page](https://nodejs.org/en/download/package-manager/) to install npm for Linux in the way many Linux developers prefer. diff --git a/docs/lib/content/configuring-npm/npm-extension.md b/docs/lib/content/configuring-npm/npm-extension.md new file mode 100644 index 0000000000000..80ae3d90d7b33 --- /dev/null +++ b/docs/lib/content/configuring-npm/npm-extension.md @@ -0,0 +1,90 @@ +--- +title: .npm-extension +section: 5 +description: Imperative, root-owned manifest repairs +--- + +### Description + +A root-owned `.npm-extension.mjs` or `.npm-extension.cjs` file lets a project imperatively repair the manifests of third-party dependencies before npm resolves the dependency tree. It exports a `transformManifest(pkg, context)` function that receives a candidate dependency manifest and returns the effective manifest npm should use. + +`.npm-extension` is the imperative counterpart to the declarative [`packageExtensions`](/configuring-npm/package-json#packageextensions) field, and runs in the same pre-resolution phase, **before** `packageExtensions`. Prefer `packageExtensions` for simple, data-only repairs; reach for `.npm-extension` when you need comments and links explaining a repair, conditional logic, repeated repairs expressed as code, deletion or range rewrites, stale-repair guards, or a policy location outside `package.json`. + +### Example + +```js +// .npm-extension.mjs +export function transformManifest (pkg, context) { + if (pkg.name === 'foo' && pkg.version.startsWith('1.')) { + pkg.dependencies = { ...pkg.dependencies, bar: '^2.0.0' } + context.log(`added bar to ${pkg.name}@${pkg.version}`) + } + return pkg +} +``` + +The `.cjs` form uses CommonJS exports instead: + +```js +// .npm-extension.cjs +module.exports = { + transformManifest (pkg, context) { + return pkg + }, +} +``` + +### The `transformManifest` function + +`transformManifest(pkg, context)` receives a deeply isolated copy of a candidate dependency manifest. It may mutate and return that copy, or return a new manifest object. It **must** return a manifest object synchronously; returning `null`, `undefined`, a primitive, an array, or a promise fails the install. + +The `context` argument is intentionally small: + +* `context.log(message)` writes an npm debug log message. +* `context.root` is the absolute path to the project root. +* `context.extensionPoint` is the string `"transformManifest"`. + +npm provides no registry, fetch, lockfile, or extraction helpers. Keep the extension file self-contained or limited to Node builtins; npm does not guarantee that project dependencies are available when the file is loaded. + +### Supported mutations + +Only the four resolution-affecting fields may change: + +* `dependencies` +* `optionalDependencies` +* `peerDependencies` +* `peerDependenciesMeta` + +Within those fields you may add, replace, or delete entries. Changing any other field (such as `scripts`, `bin`, `engines`, `os`, `cpu`, `exports`, or `main`) is rejected, and the install fails with an error naming `.npm-extension` and the package being processed. The package tarball and the installed `node_modules//package.json` are never rewritten. + +### Discovery and `extension-file` + +npm looks for a single `.npm-extension.mjs` or `.npm-extension.cjs` at the project root (the workspace root in a workspace project). Having both files present is an error. A `.npm-extension` file in a dependency or in a non-root workspace is ignored; a non-root workspace file produces a warning. + +The [`extension-file`](/using-npm/config#extension-file) config selects a different project-local file. It must resolve inside the project root and use a `.mjs` or `.cjs` extension, and it is honored only from project config or the command line — never from user, global, or builtin config. + +### Interaction with `packageExtensions` and `overrides` + +When both are present, `transformManifest` runs first and `packageExtensions` is applied to its output. Avoid targeting the same package with both unless you intend to rely on that ordering. `overrides` still controls the final resolution target of any edge, including edges created by `transformManifest`. + +### Lockfile and `npm ci` + +A lockfile influenced by `.npm-extension` records an `npmExtensionHash` (a digest of the selected file's bytes and module format) on its root entry, and minimal `npmExtensionApplied` provenance on each affected package entry. Extension state requires `lockfileVersion: 4`. + +Changing the file's contents makes `npm install` re-resolve the affected packages. `npm ci` does **not** import or execute `.npm-extension`; it verifies the recorded hash against the file and reifies the locked graph, failing if the file and lockfile disagree (or if one has extension state and the other does not). + +The hash proves only that the install uses the same extension file bytes that generated the lockfile. It does not make arbitrary JavaScript deterministic: extension output that depends on environment variables, the network, the clock, or files imported by the extension can still produce non-reproducible installs. Treat `.npm-extension` as trusted, deterministic project code, and only enable it in repositories you trust. + +### Disabling + +Set [`ignore-extension`](/using-npm/config#ignore-extension) to skip importing and executing `.npm-extension`. [`ignore-scripts`](/using-npm/config#ignore-scripts) implies `ignore-extension`, since both disable root-owned install-time code. `npm ci` still verifies the file hash even when execution is disabled. + +### Publishing + +`.npm-extension.mjs` and `.npm-extension.cjs` are project configuration, not package contents. npm excludes the root file from the package tarball produced by `npm pack` and `npm publish`, even when the package's `files` list would include it, so a public package can keep `.npm-extension` in its repository for local use without publishing it. + +### See also + +* [package.json `packageExtensions`](/configuring-npm/package-json#packageextensions) +* [package-lock.json](/configuring-npm/package-lock-json) +* [config](/using-npm/config) diff --git a/docs/lib/content/configuring-npm/npm-shrinkwrap-json.md b/docs/lib/content/configuring-npm/npm-shrinkwrap-json.md deleted file mode 100644 index ab0a241079380..0000000000000 --- a/docs/lib/content/configuring-npm/npm-shrinkwrap-json.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: npm-shrinkwrap.json -section: 5 -description: A publishable lockfile ---- - -### Description - -`npm-shrinkwrap.json` is a file created by [`npm -shrinkwrap`](/commands/npm-shrinkwrap). It is identical to -`package-lock.json`, with one major caveat: Unlike `package-lock.json`, -`npm-shrinkwrap.json` may be included when publishing a package. - -The recommended use-case for `npm-shrinkwrap.json` is applications deployed -through the publishing process on the registry: for example, daemons and -command-line tools intended as global installs or `devDependencies`. It's -strongly discouraged for library authors to publish this file, since that -would prevent end users from having control over transitive dependency -updates. - -If both `package-lock.json` and `npm-shrinkwrap.json` are present in a -package root, `npm-shrinkwrap.json` will be preferred over the -`package-lock.json` file. - -For full details and description of the `npm-shrinkwrap.json` file format, -refer to the manual page for -[package-lock.json](/configuring-npm/package-lock-json). - -### See also - -* [npm shrinkwrap](/commands/npm-shrinkwrap) -* [package-lock.json](/configuring-npm/package-lock-json) -* [package.json](/configuring-npm/package-json) -* [npm install](/commands/npm-install) diff --git a/docs/lib/content/configuring-npm/npmrc.md b/docs/lib/content/configuring-npm/npmrc.md index 0aa99fc271013..b1e7d16be10c7 100644 --- a/docs/lib/content/configuring-npm/npmrc.md +++ b/docs/lib/content/configuring-npm/npmrc.md @@ -1,19 +1,16 @@ --- -title: npmrc +title: .npmrc section: 5 description: The npm config files --- ### Description -npm gets its config settings from the command line, environment variables, -and `npmrc` files. +npm gets its config settings from the command line, environment variables, and `npmrc` files. -The `npm config` command can be used to update and edit the contents of the -user and global npmrc files. +The `npm config` command can be used to update and edit the contents of the user and global npmrc files. -For a list of available configuration options, see -[config](/using-npm/config). +For a list of available configuration options, see [config](/using-npm/config). ### Files @@ -25,18 +22,21 @@ The four relevant files are: * npm builtin config file (`/path/to/npm/npmrc`) All npm config files are an ini-formatted list of `key = value` parameters. -Environment variables can be replaced using `${VARIABLE_NAME}`. For -example: +Environment variables can be replaced using `${VARIABLE_NAME}`. +By default if the variable is not defined, it is left unreplaced. +By adding `?` after variable name they can be forced to evaluate to an empty string instead. +For example: ```bash -prefix = ${HOME}/.npm-packages +cache = ${HOME}/.npm-packages +node-options = "${NODE_OPTIONS?} --use-system-ca" ``` -Each of these files is loaded, and config options are resolved in priority -order. For example, a setting in the userconfig file would override the -setting in the globalconfig file. +Each of these files is loaded, and config options are resolved in priority order. +For example, a setting in the userconfig file would override the setting in the globalconfig file. -Array values are specified by adding "[]" after the key name. For example: +Array values are specified by adding "[]" after the key name. +For example: ```bash key[] = "first value" @@ -46,7 +46,8 @@ key[] = "second value" #### Comments Lines in `.npmrc` files are interpreted as comments when they begin with a -`;` or `#` character. `.npmrc` files are parsed by +`;` or `#` character. +`.npmrc` files are parsed by [npm/ini](https://github.com/npm/ini), which specifies this comment syntax. For example: @@ -59,43 +60,35 @@ For example: #### Per-project config file -When working locally in a project, a `.npmrc` file in the root of the -project (ie, a sibling of `node_modules` and `package.json`) will set -config values specific to this project. +When working locally in a project, a `.npmrc` file in the root of the project (ie, a sibling of `node_modules` and `package.json`) will set config values specific to this project. -Note that this only applies to the root of the project that you're running -npm in. It has no effect when your module is published. For example, you -can't publish a module that forces itself to install globally, or in a -different location. +Note that this only applies to the root of the project that you're running npm in. +It has no effect when your module is published. +For example, you can't publish a module that forces itself to install globally, or in a different location. -Additionally, this file is not read in global mode, such as when running -`npm install -g`. +Additionally, this file is not read in global mode, such as when running `npm install -g`. #### Per-user config file -`$HOME/.npmrc` (or the `userconfig` param, if set in the environment or on -the command line) +`$HOME/.npmrc` (or the `userconfig` param, if set in the environment or on the command line) #### Global config file -`$PREFIX/etc/npmrc` (or the `globalconfig` param, if set above): This file -is an ini-file formatted list of `key = value` parameters. Environment -variables can be replaced as above. +`$PREFIX/etc/npmrc` (or the `globalconfig` param, if set above): This file is an ini-file formatted list of `key = value` parameters. +Environment variables can be replaced as above. #### Built-in config file `path/to/npm/itself/npmrc` -This is an unchangeable "builtin" configuration file that npm keeps -consistent across updates. Set fields in here using the `./configure` -script that comes with npm. This is primarily for distribution maintainers -to override default configs in a standard and consistent manner. +This is an unchangeable "builtin" configuration file that npm keeps consistent across updates. +Set fields in here using the `./configure` script that comes with npm. +This is primarily for distribution maintainers to override default configs in a standard and consistent manner. ### Auth related configuration -The settings `_auth`, `_authToken`, `username` and `_password` must all be -scoped to a specific registry. This ensures that `npm` will never send -credentials to the wrong host. +The settings `_auth`, `_authToken`, `username`, `_password`, `certfile`, and `keyfile` must all be scoped to a specific registry. +This ensures that `npm` will never send credentials to the wrong host. The full list is: - `_auth` (base64 authentication string) @@ -103,15 +96,48 @@ The full list is: - `username` - `_password` - `email` + - `cafile` (path to certificate authority file) - `certfile` (path to certificate file) - `keyfile` (path to key file) In order to scope these values, they must be prefixed by a URI fragment. -If the credential is meant for any request to a registry on a single host, -the scope may look like `//registry.npmjs.org/:`. If it must be scoped to a -specific path on the host that path may also be provided, such as +If the credential is meant for any request to a registry on a single host, the scope may look like `//registry.npmjs.org/:`. +If it must be scoped to a specific path on the host that path may also be provided, such as `//my-custom-registry.org/unique/path:`. +### Unsupported Custom Configuration Keys + +Starting in npm v11.2.0, npm warns when unknown configuration keys are defined in `.npmrc`. In a future major version of npm, these unknown keys may no longer be accepted. + +Only configuration keys that npm officially supports are recognized. Custom keys intended for third-party tools (for example, `electron-builder`) should not be placed in `.npmrc`. + +If you need package-level configuration for use in scripts, use the `config` field in your `package.json` instead: + +```json +{ + "name": "my-package", + "config": { + "mirror": "https://example.com/" + } +} + +``` + +Values defined in `package.json#config` are exposed to scripts as environment variables prefixed with `npm_package_config_`. For example: + +``` +npm_package_config_mirror +``` + +If you need to pass arguments to a script command, use `--` to separate npm arguments from script arguments: + +``` +npm run build -- --customFlag +``` + +Using environment variables is also recommended for cross-platform configuration instead of defining unsupported keys in `.npmrc`. + + ``` ; bad config _authToken=MYTOKEN @@ -120,14 +146,44 @@ _authToken=MYTOKEN @myorg:registry=https://somewhere-else.com/myorg @another:registry=https://somewhere-else.com/another //registry.npmjs.org/:_authToken=MYTOKEN + ; would apply to both @myorg and @another -; //somewhere-else.com/:_authToken=MYTOKEN +//somewhere-else.com/:_authToken=MYTOKEN + ; would apply only to @myorg //somewhere-else.com/myorg/:_authToken=MYTOKEN1 + ; would apply only to @another //somewhere-else.com/another/:_authToken=MYTOKEN2 ``` +### Custom / third-party config keys + +npm only recognizes its own [configuration options](/using-npm/config). +If your `.npmrc` contains keys that are not part of npm's config definitions +(for example, `electron_mirror` or `sass_binary_site`), npm will emit a +warning: + +``` +warn Unknown user config "electron_mirror". +This will stop working in the next major version of npm. +``` + +These keys were historically tolerated but are not officially supported. +A future major version of npm will treat unknown top-level keys as errors. + +Some tools (such as `@electron/get` or `node-sass`) read their own +configuration from environment variables or from `.npmrc` by convention. +You can set these values as environment variables instead: + +```bash +export ELECTRON_MIRROR="https://mirrorexample.npmjs.org/mirrors/electron/" +export ELECTRON_CUSTOM_DIR="{{ version }}" +``` + +Environment variables are the most portable approach and work regardless +of `.npmrc` format. + ### See also * [npm folders](/configuring-npm/folders) diff --git a/docs/lib/content/configuring-npm/package-json.md b/docs/lib/content/configuring-npm/package-json.md index 755071c6f10bd..56724afe699ab 100644 --- a/docs/lib/content/configuring-npm/package-json.md +++ b/docs/lib/content/configuring-npm/package-json.md @@ -6,72 +6,74 @@ description: Specifics of npm's package.json handling ### Description -This document is all you need to know about what's required in your -package.json file. It must be actual JSON, not just a JavaScript object -literal. +This document is all you need to know about what's required in your package.json file. +It must be actual JSON, not just a JavaScript object literal. -A lot of the behavior described in this document is affected by the config -settings described in [`config`](/using-npm/config). +A lot of the behavior described in this document is affected by the config settings described in [`config`](/using-npm/config). ### name -If you plan to publish your package, the *most* important things in your -package.json are the name and version fields as they will be required. The -name and version together form an identifier that is assumed to be -completely unique. Changes to the package should come along with changes -to the version. If you don't plan to publish your package, the name and -version fields are optional. +If you plan to publish your package, the *most* important things in your package.json are the name and version fields as they will be required. +The name and version together form an identifier that is assumed to be completely unique. +Changes to the package should come along with changes to the version. +If you don't plan to publish your package, the name and version fields are optional. The name is what your thing is called. Some rules: -* The name must be less than or equal to 214 characters. This includes the - scope for scoped packages. -* The names of scoped packages can begin with a dot or an underscore. This - is not permitted without a scope. +* The name must be less than or equal to 214 characters. + This includes the scope for scoped packages. +* The names of scoped packages can begin with a dot or an underscore. + This is not permitted without a scope. * New packages must not have uppercase letters in the name. -* The name ends up being part of a URL, an argument on the command line, - and a folder name. Therefore, the name can't contain any non-URL-safe - characters. +* The name ends up being part of a URL, an argument on the command line, and a folder name. + Therefore, the name can't contain any non-URL-safe characters. Some tips: * Don't use the same name as a core Node module. -* Don't put "js" or "node" in the name. It's assumed that it's js, since - you're writing a package.json file, and you can specify the engine using - the "[engines](#engines)" field. (See below.) -* The name will probably be passed as an argument to require(), so it - should be something short, but also reasonably descriptive. -* You may want to check the npm registry to see if there's something by - that name already, before you get too attached to it. +* Don't put "js" or "node" in the name. + It's assumed that it's js, since you're writing a package.json file, and you can specify the engine using the "[engines](#engines)" field. + (See below.) +* The name will probably be passed as an argument to require(), so it should be something short, but also reasonably descriptive. +* You may want to check the npm registry to see if there's something by that name already, before you get too attached to it. -A name can be optionally prefixed by a scope, e.g. `@myorg/mypackage`. See -[`scope`](/using-npm/scope) for more detail. +A name can be optionally prefixed by a scope, e.g. `@npm/example`. +See [`scope`](/using-npm/scope) for more detail. ### version -If you plan to publish your package, the *most* important things in your -package.json are the name and version fields as they will be required. The -name and version together form an identifier that is assumed to be -completely unique. Changes to the package should come along with changes -to the version. If you don't plan to publish your package, the name and -version fields are optional. +If you plan to publish your package, the *most* important things in your package.json are the name and version fields as they will be required. +The name and version together form an identifier that is assumed to be completely unique. +Changes to the package should come along with changes to the version. +If you don't plan to publish your package, the name and version fields are optional. -Version must be parseable by -[node-semver](https://github.com/npm/node-semver), which is bundled with -npm as a dependency. (`npm install semver` to use it yourself.) +Version must be parseable by [node-semver](https://github.com/npm/node-semver), which is bundled with npm as a dependency. +(`npm install semver` to use it yourself.) ### description -Put a description in it. It's a string. This helps people discover your -package, as it's listed in `npm search`. +Put a description in it. +It's a string. +This helps people discover your package, as it's listed in `npm search`. ### keywords -Put keywords in it. It's an array of strings. This helps people discover -your package as it's listed in `npm search`. +Put keywords in it. +It's an array of strings. +This helps people discover your package as it's listed in `npm search`. + +Example: + +```json +"keywords": [ + "node", + "javascript", + "npm" +] +``` ### homepage @@ -80,39 +82,35 @@ The URL to the project homepage. Example: ```json -"homepage": "https://github.com/owner/project#readme" +"homepage": "https://github.com/npm/example#readme" ``` ### bugs -The URL to your project's issue tracker and / or the email address to which -issues should be reported. These are helpful for people who encounter -issues with your package. +The URL to your project's issue tracker and / or the email address to which issues should be reported. +These are helpful for people who encounter issues with your package. It should look like this: ```json { "bugs": { - "url": "https://github.com/owner/project/issues", - "email": "project@hostname.com" + "url": "https://github.com/npm/example/issues", + "email": "example@npmjs.com" } } ``` -You can specify either one or both values. If you want to provide only a -URL, you can specify the value for "bugs" as a simple string instead of an -object. +You can specify either one or both values. +If you want to provide only a URL, you can specify the value for "bugs" as a simple string instead of an object. If a URL is provided, it will be used by the `npm bugs` command. ### license -You should specify a license for your package so that people know how they -are permitted to use it, and any restrictions you're placing on it. +You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you're placing on it. -If you're using a common license such as BSD-2-Clause or MIT, add a current -SPDX license identifier for the license you're using, like this: +If you're using a common license such as BSD-2-Clause or MIT, add a current SPDX license identifier for the license you're using, like this: ```json { @@ -120,21 +118,17 @@ SPDX license identifier for the license you're using, like this: } ``` -You can check [the full list of SPDX license -IDs](https://spdx.org/licenses/). Ideally you should pick one that is -[OSI](https://opensource.org/licenses/) approved. +You can check [the full list of SPDX license IDs](https://spdx.org/licenses/). +Ideally, you should pick one that is [OSI](https://opensource.org/licenses/) approved. -If your package is licensed under multiple common licenses, use an [SPDX -license expression syntax version 2.0 -string](https://spdx.dev/specifications/), like this: +If your package is licensed under multiple common licenses, use an [SPDX license expression syntax version 2.0 string](https://spdx.dev/specifications/), like this: ```json { "license" : "(ISC OR GPL-3.0)" } ``` -If you are using a license that hasn't been assigned an SPDX identifier, or if -you are using a custom license, use a string value like this one: +If you are using a license that hasn't been assigned an SPDX identifier, or if you are using a custom license, use a string value like this one: ```json { @@ -143,8 +137,7 @@ you are using a custom license, use a string value like this one: ``` Then include a file named `` at the top level of the package. -Some old packages used license objects or a "licenses" property containing -an array of license objects: +Some old packages used license objects or a "licenses" property containing an array of license objects: ```json // Not valid metadata @@ -170,7 +163,8 @@ an array of license objects: } ``` -Those styles are now deprecated. Instead, use SPDX expressions, like this: +Those styles are now deprecated. +Instead, use SPDX expressions, like this: ```json { @@ -184,8 +178,7 @@ Those styles are now deprecated. Instead, use SPDX expressions, like this: } ``` -Finally, if you do not wish to grant others the right to use a private or -unpublished package under any terms: +Finally, if you do not wish to grant others the right to use a private or unpublished package under any terms: ```json { @@ -197,24 +190,23 @@ Consider also setting `"private": true` to prevent accidental publication. ### people fields: author, contributors -The "author" is one person. "contributors" is an array of people. A -"person" is an object with a "name" field and optionally "url" and "email", -like this: +The "author" is one person. +"contributors" is an array of people. +A "person" is an object with a "name" field and optionally "url" and "email", like this: ```json { "name" : "Barney Rubble", - "email" : "b@rubble.com", - "url" : "http://barnyrubble.tumblr.com/" + "email" : "barney@npmjs.com", + "url" : "http://barnyrubble.npmjs.com/" } ``` -Or you can shorten that all into a single string, and npm will parse it for -you: +Or you can shorten that all into a single string, and npm will parse it for you: ```json { - "author": "Barney Rubble (http://barnyrubble.tumblr.com/)" + "author": "Barney Rubble (http://barnyrubble.npmjs.com/)" } ``` @@ -224,15 +216,13 @@ npm also sets a top-level "maintainers" field with your npm user info. ### funding -You can specify an object containing a URL that provides up-to-date -information about ways to help fund development of your package, a -string URL, or an array of objects and string URLs: +You can specify an object containing a URL that provides up-to-date information about ways to help fund development of your package, a string URL, or an array of objects and string URLs: ```json { "funding": { "type" : "individual", - "url" : "http://example.com/donate" + "url" : "http://npmjs.com/donate" } } ``` @@ -241,14 +231,14 @@ string URL, or an array of objects and string URLs: { "funding": { "type" : "patreon", - "url" : "https://www.patreon.com/my-account" + "url" : "https://www.patreon.com/user" } } ``` ```json { - "funding": "http://example.com/donate" + "funding": "http://npmjs.com/donate" } ``` @@ -257,41 +247,33 @@ string URL, or an array of objects and string URLs: "funding": [ { "type" : "individual", - "url" : "http://example.com/donate" + "url" : "http://npmjs.com/donate" }, - "http://example.com/donateAlso", + "http://npmjs.com/donate-also", { "type" : "patreon", - "url" : "https://www.patreon.com/my-account" + "url" : "https://www.patreon.com/user" } ] } ``` -Users can use the `npm fund` subcommand to list the `funding` URLs of all -dependencies of their project, direct and indirect. A shortcut to visit -each funding URL is also available when providing the project name such as: -`npm fund ` (when there are multiple URLs, the first one will -be visited) +Users can use the `npm fund` subcommand to list the `funding` URLs of all dependencies of their project, direct and indirect. +A shortcut to visit each funding URL is also available when providing the project name such as: +`npm fund ` (when there are multiple URLs, the first one will be visited) ### files -The optional `files` field is an array of file patterns that describes the -entries to be included when your package is installed as a dependency. File -patterns follow a similar syntax to `.gitignore`, but reversed: including a -file, directory, or glob pattern (`*`, `**/*`, and such) will make it so -that file is included in the tarball when it's packed. Omitting the field -will make it default to `["*"]`, which means it will include all files. +The optional `files` field is an array of file patterns that describes the entries to be included when your package is installed as a dependency. +File patterns follow a similar syntax to `.gitignore`, but reversed: including a file, directory, or glob pattern (`*`, `**/*`, and such) will make it so that file is included in the tarball when it's packed. +Omitting the field will make it default to `["*"]`, which means it will include all files. -Some special files and directories are also included or excluded regardless -of whether they exist in the `files` array (see below). +Some special files and directories are also included or excluded regardless of whether they exist in the `files` array (see below). -You can also provide a `.npmignore` file in the root of your package or in -subdirectories, which will keep files from being included. At the root of -your package it will not override the "files" field, but in subdirectories -it will. The `.npmignore` file works just like a `.gitignore`. If there is -a `.gitignore` file, and `.npmignore` is missing, `.gitignore`'s contents -will be used instead. +You can also provide a `.npmignore` file in the root of your package or in subdirectories, which will keep files from being included. +At the root of your package it will not override the "files" field, but in subdirectories it will. +The `.npmignore` file works just like a `.gitignore`. +If there is a `.gitignore` file, and `.npmignore` is missing, `.gitignore`'s contents will be used instead. Certain files are always included, regardless of settings: @@ -319,14 +301,13 @@ Some files are always ignored by default: * `config.gypi` * `node_modules` * `npm-debug.log` -* `package-lock.json` (use - [`npm-shrinkwrap.json`](/configuring-npm/npm-shrinkwrap-json) - if you wish it to be published) +* `package-lock.json` * `pnpm-lock.yaml` * `yarn.lock` +* `bun.lockb` -Most of these ignored files can be included specifically if included in -the `files` globs. Exceptions to this are: +Most of these ignored files can be included specifically if included in the `files` globs. +Exceptions to this are: * `.git` * `.npmrc` @@ -334,45 +315,45 @@ the `files` globs. Exceptions to this are: * `package-lock.json` * `pnpm-lock.yaml` * `yarn.lock` +* `bun.lockb` + +These cannot be included. -These can not be included. +### exports + +The "exports" provides a modern alternative to "main" allowing multiple entry points to be defined, conditional entry resolution support between environments, and preventing any other entry points besides those defined in "exports". This encapsulation allows module authors to clearly define the public interface for their package. +For more details see the [node.js documentation on package entry points](https://nodejs.org/api/packages.html#package-entry-points) ### main -The main field is a module ID that is the primary entry point to your -program. That is, if your package is named `foo`, and a user installs it, -and then does `require("foo")`, then your main module's exports object will -be returned. +The main field is a module ID that is the primary entry point to your program. +That is, if your package is named `foo`, and a user installs it, and then does `require("foo")`, then your main module's exports object will be returned. This should be a module relative to the root of your package folder. -For most modules, it makes the most sense to have a main script and often -not much else. +For most modules, it makes the most sense to have a main script and often not much else. If `main` is not set, it defaults to `index.js` in the package's root folder. +### type + +The `type` field defines how Node.js should interpret `.js` files in your package. This field is not used by npm. + +See the [Node.js documentation on the type field](https://nodejs.org/api/packages.html#type) for more information. + ### browser -If your module is meant to be used client-side the browser field should be -used instead of the main field. This is helpful to hint users that it might -rely on primitives that aren't available in Node.js modules. (e.g. -`window`) +If your module is meant to be used client-side the browser field should be used instead of the main field. +This is helpful to hint users that it might rely on primitives that aren't available in Node.js modules. +(e.g. `window`) ### bin -A lot of packages have one or more executable files that they'd like to -install into the PATH. npm makes this pretty easy (in fact, it uses this -feature to install the "npm" executable.) +A lot of packages have one or more executable files that they'd like to install into the PATH. npm makes this pretty easy (in fact, it uses this feature to install the "npm" executable.) -To use this, supply a `bin` field in your package.json which is a map of -command name to local file name. When this package is installed globally, -that file will be either linked inside the global bins directory or -a cmd (Windows Command File) will be created which executes the specified -file in the `bin` field, so it is available to run by `name` or `name.cmd` (on -Windows PowerShell). When this package is installed as a dependency in another -package, the file will be linked where it will be available to that package -either directly by `npm exec` or by name in other scripts when invoking them -via `npm run-script`. +To use this, supply a `bin` field in your package.json which is a map of command name to local file name. +When this package is installed globally, that file will be either linked inside the global bins directory or a cmd (Windows Command File) will be created which executes the specified file in the `bin` field, so it is available to run by `name` or `name.cmd` (on Windows PowerShell). +When this package is installed as a dependency in another package, the file will be linked where it will be available to that package either directly by `npm exec` or by name in other scripts when invoking them via `npm run`. For example, myapp could have this: @@ -385,13 +366,10 @@ For example, myapp could have this: } ``` -So, when you install myapp, in case of unix-like OS it'll create a symlink -from the `cli.js` script to `/usr/local/bin/myapp` and in case of windows it -will create a cmd file usually at `C:\Users\{Username}\AppData\Roaming\npm\myapp.cmd` -which runs the `cli.js` script. +So, when you install myapp, in case of unix-like OS it'll create a symlink from the `cli.js` script to `/usr/local/bin/myapp` and in case of windows it will create a cmd file usually at `C:\Users\{Username}\AppData\Roaming\npm\myapp.cmd` which runs the `cli.js` script. -If you have a single executable, and its name should be the name of the -package, then you can just supply it as a string. For example: +If you have a single executable, and its name should be the name of the package, then you can just supply it as a string. +For example: ```json { @@ -413,23 +391,20 @@ would be the same as this: } ``` -Please make sure that your file(s) referenced in `bin` starts with -`#!/usr/bin/env node`, otherwise the scripts are started without the node -executable! +Please make sure that your file(s) referenced in `bin` starts with `#!/usr/bin/env node`; otherwise, the scripts are started without the node executable! Note that you can also set the executable files using [directories.bin](#directoriesbin). -See [folders](/configuring-npm/folders#executables) for more info on -executables. +See [folders](/configuring-npm/folders#executables) for more info on executables. ### man -Specify either a single file or an array of filenames to put in place for -the `man` program to find. +> **Note:** As of npm v12, man pages are no longer registered with the system `man` program. This field is retained for backward compatibility with package metadata and tools that consume it, but `man ` will not work after a global install. Use `npm help ` instead where supported. + +Specify either a single file or an array of filenames to include as man pages. -If only a single file is provided, then it's installed such that it is the -result from `man `, regardless of its actual filename. For -example: +If only a single file is provided, then it corresponds to `man `, regardless of its actual filename. +For example: ```json { @@ -441,8 +416,7 @@ example: } ``` -would link the `./man/doc.1` file in such that it is the target for `man -foo` +would associate the `./man/doc.1` file such that it is the target for `man foo` If the filename doesn't start with the package name, then it's prefixed. So, this: @@ -460,11 +434,10 @@ So, this: } ``` -will create files to do `man foo` and `man foo-bar`. +will correspond to `man foo` and `man foo-bar`. -Man files must end with a number, and optionally a `.gz` suffix if they are -compressed. The number dictates which man section the file is installed -into. +Man files must end with a number, and optionally a `.gz` suffix if they are compressed. +The number dictates which man section the file belongs to. ```json { @@ -483,34 +456,28 @@ will create entries for `man foo` and `man 2 foo` ### directories -The CommonJS [Packages](http://wiki.commonjs.org/wiki/Packages/1.0) spec -details a few ways that you can indicate the structure of your package -using a `directories` object. If you look at [npm's -package.json](https://registry.npmjs.org/npm/latest), you'll see that it -has directories for doc, lib, and man. +The CommonJS [Packages](http://wiki.commonjs.org/wiki/Packages/1.0) spec details a few ways that you can indicate the structure of your package using a `directories` object. +If you look at [npm's package.json](https://registry.npmjs.org/npm/latest), you'll see that it has directories for doc, lib, and man. In the future, this information may be used in other creative ways. #### directories.bin -If you specify a `bin` directory in `directories.bin`, all the files in -that folder will be added. +If you specify a `bin` directory in `directories.bin`, all the files in that folder will be added. -Because of the way the `bin` directive works, specifying both a `bin` path -and setting `directories.bin` is an error. If you want to specify -individual files, use `bin`, and for all the files in an existing `bin` -directory, use `directories.bin`. +Because of the way the `bin` directive works, specifying both a `bin` path and setting `directories.bin` is an error. +If you want to specify individual files, use `bin`, and for all the files in an existing `bin` directory, use `directories.bin`. #### directories.man -A folder that is full of man pages. Sugar to generate a "man" array by -walking the folder. +A folder that is full of man pages. +Sugar to generate a "man" array by walking the folder. See the note on [`man`](#man) above: as of npm v12, these are no longer installed into the system `man` path. ### repository -Specify the place where your code lives. This is helpful for people who -want to contribute. If the git repo is on GitHub, then the `npm repo` -command will be able to find you. +Specify the place where your code lives. +This is helpful for people who want to contribute. +If the git repo is on GitHub, then the `npm repo` command will be able to find you. Do it like this: @@ -523,19 +490,17 @@ Do it like this: } ``` -The URL should be a publicly available (perhaps read-only) URL that can be -handed directly to a VCS program without any modification. It should not -be a URL to an html project page that you put in your browser. It's for -computers. +The URL should be a publicly available (perhaps read-only) URL that can be handed directly to a VCS program without any modification. +It should not be a URL to an html project page that you put in your browser. +It's for computers. -For GitHub, GitHub gist, Bitbucket, or GitLab repositories you can use the -same shortcut syntax you use for `npm install`: +For GitHub, GitHub gist, Bitbucket, or GitLab repositories you can use the same shortcut syntax you use for `npm install`: ```json { - "repository": "npm/npm", + "repository": "npm/example", - "repository": "github:user/repo", + "repository": "github:npm/example", "repository": "gist:11081aaa281", @@ -545,9 +510,20 @@ same shortcut syntax you use for `npm install`: } ``` -If the `package.json` for your package is not in the root directory (for -example if it is part of a monorepo), you can specify the directory in -which it lives: +**Note on normalization:** When you publish a package, npm normalizes the `repository` field to the full object format with a `url` property. If you use a shorthand format (like `"npm/example"`), you'll see a warning during `npm publish` indicating that the field was auto-corrected. While the shorthand format currently works, it's recommended to use the full object format in your `package.json` to avoid warnings and ensure future compatibility: + +```json +{ + "repository": { + "type": "git", + "url": "git+https://github.com/npm/example.git" + } +} +``` + +You can run `npm pkg fix` to automatically convert shorthand formats to the normalized object format. + +If the `package.json` for your package is not in the root directory (for example if it is part of a monorepo), you can specify the directory in which it lives: ```json { @@ -561,18 +537,29 @@ which it lives: ### scripts -The "scripts" property is a dictionary containing script commands that are -run at various times in the lifecycle of your package. The key is the -lifecycle event, and the value is the command to run at that point. +The "scripts" property is a dictionary containing script commands that are run at various times in the lifecycle of your package. +The key is the lifecycle event, and the value is the command to run at that point. + +See [`scripts`](/using-npm/scripts) to find out more about writing package scripts. + +### gypfile -See [`scripts`](/using-npm/scripts) to find out more about writing package -scripts. +If you have a binding.gyp file in the root of your package and you have not defined your own `install` or `preinstall` scripts, npm will default to building your module using node-gyp. + +To prevent npm from automatically building your module with node-gyp, set `gypfile` to `false`: + +```json +{ + "gypfile": false +} +``` + +This is useful for packages that include native addons but want to handle the build process differently, or packages that have a binding.gyp file but should not be built as a native addon. ### config -A "config" object can be used to set configuration parameters used in -package scripts that persist across upgrades. For instance, if a package -had the following: +A "config" object can be used to set configuration parameters used in package scripts that persist across upgrades. +For instance, if a package had the following: ```json { @@ -583,18 +570,16 @@ had the following: } ``` -It could also have a "start" command that referenced the -`npm_package_config_port` environment variable. +It could also have a "start" script that referenced the `npm_package_config_port` environment variable. ### dependencies -Dependencies are specified in a simple object that maps a package name to a -version range. The version range is a string which has one or more -space-separated descriptors. Dependencies can also be identified with a -tarball or git URL. +Dependencies are specified in a simple object that maps a package name to a version range. +The version range is a string which has one or more space-separated descriptors. +Dependencies can also be identified with a tarball or git URL. -**Please do not put test harnesses or transpilers or other "development" -time tools in your `dependencies` object.** See `devDependencies`, below. +**Please do not put test harnesses or transpilers or other "development" time tools in your `dependencies` object.** +See `devDependencies`, below. See [semver](https://github.com/npm/node-semver#versions) for more details about specifying version ranges. @@ -603,8 +588,7 @@ See [semver](https://github.com/npm/node-semver#versions) for more details about * `>=version` etc * `1.0.2 <=2.3.4", "boo": "2.0.1", "qux": "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0", - "asd": "http://asdf.com/asdf.tar.gz", + "asd": "http://npmjs.com/example.tar.gz", "til": "~1.2", "elf": "~1.2.3", "two": "2.x", "thr": "3.3.x", "lat": "latest", - "dyl": "file:../dyl" + "dyl": "file:../dyl", + "kpg": "npm:pkg@1.0.0" } } ``` @@ -643,8 +628,7 @@ For example, these are all valid: You may specify a tarball URL in place of a version range. -This tarball will be downloaded and installed locally to your package at -install time. +This tarball will be downloaded and installed locally to your package at install time. #### Git URLs as Dependencies @@ -654,15 +638,11 @@ Git URLs are of the form: ://[[:]@][:][:][/][# | #semver:] ``` -`` is one of `git`, `git+ssh`, `git+http`, `git+https`, or -`git+file`. +`` is one of `git`, `git+ssh`, `git+http`, `git+https`, or `git+file`. -If `#` is provided, it will be used to clone exactly that -commit. If the commit-ish has the format `#semver:`, `` can -be any valid semver range or exact version, and npm will look for any tags -or refs matching that range in the remote repository, much as it would for -a registry dependency. If neither `#` or `#semver:` is -specified, then the default branch is used. +If `#` is provided, it will be used to clone exactly that commit. +If the commit-ish has the format `#semver:`, `` can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. +If neither `#` or `#semver:` is specified, then the default branch is used. Examples: @@ -673,14 +653,10 @@ git+https://isaacs@github.com/npm/cli.git git://github.com/npm/cli.git#v1.0.27 ``` -When installing from a `git` repository, the presence of certain fields in the -`package.json` will cause npm to believe it needs to perform a build. To do so -your repository will be cloned into a temporary directory, all of its deps -installed, relevant scripts run, and the resulting directory packed and -installed. +When installing from a `git` repository, the presence of certain fields in the `package.json` will cause npm to believe it needs to perform a build. +To do so your repository will be cloned into a temporary directory, all of its deps installed, relevant scripts run, and the resulting directory packed and installed. -This flow will occur if your git dependency uses `workspaces`, or if any of the -following scripts are present: +This flow will occur if your git dependency uses `workspaces`, or if any of the following scripts are present: * `build` * `prepare` @@ -689,15 +665,13 @@ following scripts are present: * `install` * `postinstall` -If your git repository includes pre-built artifacts, you will likely want to -make sure that none of the above scripts are defined, or your dependency -will be rebuilt for every installation. +If your git repository includes pre-built artifacts, you will likely want to make sure that none of the above scripts are defined, or your dependency will be rebuilt for every installation. #### GitHub URLs As of version 1.1.65, you can refer to GitHub URLs as just "foo": -"user/foo-project". Just as with git URLs, a `commit-ish` suffix can be -included. For example: +"user/foo-project". Just as with git URLs, a `commit-ish` suffix can be included. +For example: ```json { @@ -706,16 +680,15 @@ included. For example: "dependencies": { "express": "expressjs/express", "mocha": "mochajs/mocha#4727d357ea", - "module": "user/repo#feature\/branch" + "module": "npm/example-github-repo#feature\/branch" } } ``` #### Local Paths -As of version 2.0.0 you can provide a path to a local directory that -contains a package. Local paths can be saved using `npm install -S` or `npm -install --save`, using any of these forms: +As of version 2.0.0 you can provide a path to a local directory that contains a package. +Local paths can be saved using `npm install -S` or `npm install --save`, using any of these forms: ```bash ../foo/bar @@ -724,8 +697,8 @@ install --save`, using any of these forms: /foo/bar ``` -in which case they will be normalized to a relative path and added to your -`package.json`. For example: +in which case they will be normalized to a relative path and added to your `package.json`. +For example: ```json { @@ -736,36 +709,27 @@ in which case they will be normalized to a relative path and added to your } ``` -This feature is helpful for local offline development and creating tests -that require npm installing where you don't want to hit an external server, -but should not be used when publishing your package to the public registry. +This feature is helpful for local offline development and creating tests that require npm installing where you don't want to hit an external server, but should not be used when publishing your package to the public registry. -*note*: Packages linked by local path will not have their own -dependencies installed when `npm install` is ran in this case. You must -run `npm install` from inside the local path itself. +*note*: Packages linked by local path will not have their own dependencies installed when `npm install` is run. +You must run `npm install` from inside the local path itself. ### devDependencies -If someone is planning on downloading and using your module in their -program, then they probably don't want or need to download and build the -external test or documentation framework that you use. +If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use. -In this case, it's best to map these additional items in a -`devDependencies` object. +In this case, it's best to map these additional items in a `devDependencies` object. -These things will be installed when doing `npm link` or `npm install` from -the root of a package, and can be managed like any other npm configuration -param. See [`config`](/using-npm/config) for more on the topic. +These things will be installed when doing `npm link` or `npm install` from the root of a package, and can be managed like any other npm configuration param. +See [`config`](/using-npm/config) for more on the topic. -For build steps that are not platform-specific, such as compiling -CoffeeScript or other languages to JavaScript, use the `prepare` script to -do this, and make the required package a devDependency. +For build steps that are not platform-specific, such as compiling CoffeeScript or other languages to JavaScript, use the `prepare` script to do this, and make the required package a devDependency. For example: ```json { - "name": "ethopia-waza", + "name": "@npm/ethopia-waza", "description": "a delightfully fruity coffee varietal", "version": "1.2.3", "devDependencies": { @@ -778,77 +742,63 @@ For example: } ``` -The `prepare` script will be run before publishing, so that users can -consume the functionality without requiring them to compile it themselves. -In dev mode (ie, locally running `npm install`), it'll run this script as -well, so that you can test it easily. +The `prepare` script will be run before publishing, so that users can consume the functionality without requiring them to compile it themselves. +In dev mode (ie, locally running `npm install`), it'll run this script as well, so that you can test it easily. ### peerDependencies -In some cases, you want to express the compatibility of your package with a -host tool or library, while not necessarily doing a `require` of this host. -This is usually referred to as a *plugin*. Notably, your module may be -exposing a specific interface, expected and specified by the host -documentation. +In some cases, you want to express the compatibility of your package with a host tool or library, while not necessarily doing a `require` of this host. +This is usually referred to as a *plugin*. Notably, your module may be exposing a specific interface, expected and specified by the host documentation. For example: ```json { - "name": "tea-latte", + "name": "@npm/tea-latte", "version": "1.3.5", "peerDependencies": { - "tea": "2.x" + "@npm/tea": "2.x" } } ``` -This ensures your package `tea-latte` can be installed *along* with the -second major version of the host package `tea` only. `npm install -tea-latte` could possibly yield the following dependency graph: +This ensures your package `@npm/tea-latte` can be installed *along* with the second major version of the host package `@npm/tea` only. +`npm install tea-latte` could possibly yield the following dependency graph: ```bash -├── tea-latte@1.3.5 -└── tea@2.2.0 +├── @npm/tea-latte@1.3.5 +└── @npm/tea@2.2.0 ``` -In npm versions 3 through 6, `peerDependencies` were not automatically -installed, and would raise a warning if an invalid version of the peer -dependency was found in the tree. As of npm v7, peerDependencies _are_ -installed by default. +In npm versions 3 through 6, `peerDependencies` were not automatically installed, and would raise a warning if an invalid version of the peer dependency was found in the tree. +As of npm v7, peerDependencies _are_ installed by default. -Trying to install another plugin with a conflicting requirement may cause -an error if the tree cannot be resolved correctly. For this reason, make -sure your plugin requirement is as broad as possible, and not to lock it -down to specific patch versions. +Trying to install another plugin with a conflicting requirement may cause an error if the tree cannot be resolved correctly. +For this reason, make sure your plugin requirement is as broad as possible, and not to lock it down to specific patch versions. -Assuming the host complies with [semver](https://semver.org/), only changes -in the host package's major version will break your plugin. Thus, if you've -worked with every 1.x version of the host package, use `"^1.0"` or `"1.x"` -to express this. If you depend on features introduced in 1.5.2, use -`"^1.5.2"`. +Assuming the host complies with [semver](https://semver.org/), only changes in the host package's major version will break your plugin. +Thus, if you've worked with every 1.x version of the host package, use `"^1.0"` or `"1.x"` to express this. +If you depend on features introduced in 1.5.2, use `"^1.5.2"`. ### peerDependenciesMeta -The `peerDependenciesMeta` field serves to provide npm more information on how -your peer dependencies are to be used. Specifically, it allows peer -dependencies to be marked as optional. Npm will not automatically install -optional peer dependencies. This allows you to -integrate and interact with a variety of host packages without requiring -all of them to be installed. +The `peerDependenciesMeta` field serves to provide npm more information on how your peer dependencies are to be used. +Specifically, it allows peer dependencies to be marked as optional. +Npm will not automatically install optional peer dependencies. +This allows you to integrate and interact with a variety of host packages without requiring all of them to be installed. For example: ```json { - "name": "tea-latte", + "name": "@npm/tea-latte", "version": "1.3.5", "peerDependencies": { - "tea": "2.x", - "soy-milk": "1.2" + "@npm/tea": "2.x", + "@npm/soy-milk": "1.2" }, "peerDependenciesMeta": { - "soy-milk": { + "@npm/soy-milk": { "optional": true } } @@ -857,13 +807,9 @@ For example: ### bundleDependencies -This defines an array of package names that will be bundled when publishing -the package. +This defines an array of package names that will be bundled when publishing the package. -In cases where you need to preserve npm packages locally or have them -available through a single file download, you can bundle the packages in a -tarball file by specifying the package names in the `bundleDependencies` -array and executing `npm pack`. +In cases where you need to preserve npm packages locally or have them available through a single file download, you can bundle the packages in a tarball file by specifying the package names in the `bundleDependencies` array and executing `npm pack`. For example: @@ -871,43 +817,48 @@ If we define a package.json like this: ```json { - "name": "awesome-web-framework", + "name": "@npm/awesome-web-framework", "version": "1.0.0", "bundleDependencies": [ - "renderized", - "super-streams" + "@npm/renderized", + "@npm/super-streams" ] } ``` -we can obtain `awesome-web-framework-1.0.0.tgz` file by running `npm pack`. -This file contains the dependencies `renderized` and `super-streams` which -can be installed in a new project by executing `npm install -awesome-web-framework-1.0.0.tgz`. Note that the package names do not -include any versions, as that information is specified in `dependencies`. +we can obtain `@npm/awesome-web-framework-1.0.0.tgz` file by running `npm pack`. +This file contains the dependencies `@npm/renderized` and `@npm/super-streams` which can be installed in a new project by executing `npm install awesome-web-framework-1.0.0.tgz`. +Note that the package names do not include any versions, as that information is specified in `dependencies`. If this is spelled `"bundledDependencies"`, then that is also honored. -Alternatively, `"bundleDependencies"` can be defined as a boolean value. A -value of `true` will bundle all dependencies, a value of `false` will bundle -none. +Alternatively, `"bundleDependencies"` can be defined as a boolean value. +A value of `true` will bundle all dependencies, a value of `false` will bundle none. ### optionalDependencies -If a dependency can be used, but you would like npm to proceed if it cannot -be found or fails to install, then you may put it in the -`optionalDependencies` object. This is a map of package name to version or -URL, just like the `dependencies` object. The difference is that build -failures do not cause installation to fail. Running `npm install ---omit=optional` will prevent these dependencies from being installed. +If a dependency can be used, but you would like npm to proceed if it cannot be found or fails to install, then you may put it in the `optionalDependencies` object. +This is a map of package name to version or URL, just like the `dependencies` object. +The difference is that build failures do not cause installation to fail. +Running `npm install --omit=optional` will prevent these dependencies from being installed. + +For example: + +```json +{ + "optionalDependencies": { + "@npm/foo": "^1.0.0" + } +} +``` -It is still your program's responsibility to handle the lack of the -dependency. For example, something like this: +It is still your program's responsibility to handle the lack of the dependency. +For example, something like this: ```js try { - var foo = require('foo') - var fooVersion = require('foo/package.json').version + var foo = require('@npm/foo') + var fooVersion = require('@npm/foo/package.json').version } catch (er) { foo = null } @@ -922,76 +873,79 @@ if (foo) { } ``` -Entries in `optionalDependencies` will override entries of the same name in -`dependencies`, so it's usually best to only put in one place. +Entries in `optionalDependencies` will override entries of the same name in `dependencies`, so it's usually best to only put in one place. ### overrides -If you need to make specific changes to dependencies of your dependencies, for -example replacing the version of a dependency with a known security issue, -replacing an existing dependency with a fork, or making sure that the same -version of a package is used everywhere, then you may add an override. +If you need to make specific changes to dependencies of your dependencies, for example replacing the version of a dependency with a known security issue, replacing an existing dependency with a fork, or making sure that the same version of a package is used everywhere, then you may add an override. -Overrides provide a way to replace a package in your dependency tree with -another version, or another package entirely. These changes can be scoped as -specific or as vague as desired. +Overrides provide a way to replace a package in your dependency tree with another version, or another package entirely. +These changes can be scoped as specific or as vague as desired. Overrides are only considered in the root `package.json` file for a project. -Overrides in installed dependencies (including -[workspaces](/using-npm/workspaces)) are not considered in dependency tree -resolution. Published packages may dictate their resolutions by pinning -dependencies or using an -[`npm-shrinkwrap.json`](/configuring-npm/npm-shrinkwrap-json) file. +Overrides in installed dependencies (including [workspaces](/using-npm/workspaces)) are not considered in dependency tree resolution. +Published packages may dictate their resolutions by pinning dependencies or using [`bundleDependencies`](#bundledependencies). -To make sure the package `foo` is always installed as version `1.0.0` no matter -what version your dependencies rely on: +To make sure the package `@npm/foo` is always installed as version `1.0.0` no matter what version your dependencies rely on: ```json { "overrides": { - "foo": "1.0.0" + "@npm/foo": "1.0.0" } } ``` -The above is a short hand notation, the full object form can be used to allow -overriding a package itself as well as a child of the package. This will cause -`foo` to always be `1.0.0` while also making `bar` at any depth beyond `foo` -also `1.0.0`: +Override values can use any specifier that npm accepts for dependencies, including +an exact version, a semver range, a dist-tag, or a replacement specifier such as +`npm:`, `file:`, or a Git URL. + +For example, if you only need to enforce a minimum patched release instead of one +exact version, you can use a semver range: ```json { "overrides": { - "foo": { + "@npm/foo": "^1.0.0" + } +} +``` + +The above is a short hand notation, the full object form can be used to allow overriding a package itself as well as a child of the package. +This will cause `@npm/foo` to always be `1.0.0` while also making `@npm/bar` at any depth beyond `@npm/foo` also `1.0.0`: + +```json +{ + "overrides": { + "@npm/foo": { ".": "1.0.0", - "bar": "1.0.0" + "@npm/bar": "1.0.0" } } } ``` -To only override `foo` to be `1.0.0` when it's a child (or grandchild, or great -grandchild, etc) of the package `bar`: +To only override `@npm/foo` to be `1.0.0` when it's a child (or grandchild, or great grandchild, etc) of the package `@npm/bar`: ```json { "overrides": { - "bar": { - "foo": "1.0.0" + "@npm/bar": { + "@npm/foo": "1.0.0" } } } ``` -Keys can be nested to any arbitrary length. To override `foo` only when it's a -child of `bar` and only when `bar` is a child of `baz`: +Keys can be nested to any arbitrary length. +To override `@npm/foo` only when it's a child of `@npm/bar` and only when `@npm/bar` is a child of `@npm/baz`: ```json { "overrides": { - "baz": { - "bar": { - "foo": "1.0.0" + "@npm/baz": { + "@npm/bar": { + "@npm/foo": "1.0.0" } } } @@ -999,28 +953,25 @@ child of `bar` and only when `bar` is a child of `baz`: ``` The key of an override can also include a version, or range of versions. -To override `foo` to `1.0.0`, but only when it's a child of `bar@2.0.0`: +To override `@npm/foo` to `1.0.0`, but only when it's a child of `@npm/bar@2.0.0`: ```json { "overrides": { - "bar@2.0.0": { - "foo": "1.0.0" + "@npm/bar@2.0.0": { + "@npm/foo": "1.0.0" } } } ``` -You may not set an override for a package that you directly depend on unless -both the dependency and the override itself share the exact same spec. To make -this limitation easier to deal with, overrides may also be defined as a -reference to a spec for a direct dependency by prefixing the name of the -package you wish the version to match with a `$`. +You may not set an override for a package that you directly depend on unless both the dependency and the override itself share the exact same spec. +To make this limitation easier to deal with, overrides may also be defined as a reference to a spec for a direct dependency by prefixing the name of the package you wish the version to match with a `$`. ```json { "dependencies": { - "foo": "^1.0.0" + "@npm/foo": "^1.0.0" }, "overrides": { // BAD, will throw an EOVERRIDE error @@ -1028,13 +979,120 @@ package you wish the version to match with a `$`. // GOOD, specs match so override is allowed // "foo": "^1.0.0" // BEST, the override is defined as a reference to the dependency - "foo": "$foo", + "@npm/foo": "$foo", // the referenced package does not need to match the overridden one - "bar": "$foo" + "@npm/bar": "$foo" + } +} +``` + +#### Replacing a dependency with a fork + +You can replace a package with a different package or fork using several methods: + +**Using the `npm:` prefix to replace with a different package name:** + +```json +{ + "overrides": { + "package-name": "npm:@scope/forked-package@1.0.0" } } ``` +**Using a GitHub repository (supports branches, tags, or commit hashes):** + +```json +{ + "overrides": { + "package-name": "github:username/repo#branch-name" + } +} +``` + +**Using a local file path:** + +```json +{ + "overrides": { + "package-name": "file:../local-fork" + } +} +``` + +These replacement methods work for both top-level overrides and nested overrides. +For example, to replace a transitive dependency with a fork: + +```json +{ + "overrides": { + "parent-package": { + "vulnerable-dep": "github:username/patched-fork#v2.0.1" + } + } +} +``` + +### packageExtensions + +`packageExtensions` lets a project apply small, declarative repairs to the manifests of third-party dependencies before npm resolves the dependency tree. +Use it to add a missing `dependencies`, `optionalDependencies`, or `peerDependencies` entry, or to correct `peerDependencies` and `peerDependenciesMeta`, while you wait for the upstream package to publish a fix. + +This is especially useful with [`install-strategy=linked`](/using-npm/config#install-strategy), where dependencies are fully isolated and a package only sees what it actually declared. +A package that worked under a hoisted layout because a dependency happened to be hoisted above it can fail under `linked`; `packageExtensions` records the missing edge as explicit, reviewable, root-owned policy. + +`packageExtensions` complements [`overrides`](#overrides): `overrides` changes what an existing dependency edge resolves to, while `packageExtensions` adds or corrects the dependency metadata that creates the edge in the first place. +For changing the resolved version of a dependency that is already declared, use `overrides`. + +Like `overrides`, `packageExtensions` is only honored in the root `package.json` of a project (the workspace root in a workspace). +The field in installed dependencies and in non-root workspace packages is ignored. +Because it is root-only project policy, npm refuses to publish a non-private package that contains `packageExtensions`; it remains available to private packages and unpublished local projects. + +Each key is a package selector: a package name with an optional semver range. + +```json +{ + "packageExtensions": { + "broken-package@1": { + "dependencies": { + "missing-runtime-dep": "^2.0.0" + } + }, + "typescript-plugin@4.3.0": { + "peerDependencies": { + "typescript": ">=5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "@scope/uses-types@2": { + "dependencies": { + "@types/node": "^22.0.0" + } + } + } +} +``` + +- `"foo"` matches all versions of `foo`. +- `"foo@1"` matches versions satisfying `1`. +- `"@scope/foo@^2.3.0"` matches versions satisfying `^2.3.0`. + +Selectors match a candidate package's own `name` and `version`. They do not accept dist-tags, git, file, directory, URL, or `npm:` alias specs. For aliases, the selector matches the underlying package name. At most one selector may match a given package; overlapping selectors that both match the same package fail the install. + +Only `dependencies`, `optionalDependencies`, `peerDependencies`, and `peerDependenciesMeta` may be extended. The merge rules are: + +- `dependencies` and `optionalDependencies` entries add a missing dependency only. Adding a name that the package already declares in either field is an error; use `overrides` to change a version. +- `peerDependencies` entries are merged by name, replacing an existing range. +- `peerDependenciesMeta` entries are merged by name and then by key, so you can add `optional: true` without dropping other metadata. Every `peerDependenciesMeta` entry must correspond to a `peerDependencies` entry. + +Deletion is not supported; a `null`, `false`, or `"-"` value is an error. + +`packageExtensions` does not rewrite the installed package's `package.json` on disk and does not modify `bundleDependencies`. Affected packages are recorded in `package-lock.json` and surfaced by [`npm explain`](/commands/npm-explain) and [`npm ls`](/commands/npm-ls), so each repair is easy to audit and to remove once upstream is fixed. + ### engines You can specify the version of node that your stuff works on: @@ -1047,11 +1105,10 @@ You can specify the version of node that your stuff works on: } ``` -And, like with dependencies, if you don't specify the version (or if you -specify "\*" as the version), then any version of node will do. +And, like with dependencies, if you don't specify the version (or if you specify "\*" as the version), then any version of node will do. -You can also use the "engines" field to specify which versions of npm are -capable of properly installing your program. For example: +You can also use the "engines" field to specify which versions of npm are capable of properly installing your program. +For example: ```json { @@ -1061,15 +1118,11 @@ capable of properly installing your program. For example: } ``` -Unless the user has set the -[`engine-strict` config](/using-npm/config#engine-strict) flag, this field is -advisory only and will only produce warnings when your package is installed as a -dependency. +Unless the user has set the [`engine-strict` config](/using-npm/config#engine-strict) flag, this field is advisory only and will only produce warnings when your package is installed as a dependency. ### os -You can specify which operating systems your -module will run on: +You can specify which operating systems your module will run on: ```json { @@ -1080,8 +1133,7 @@ module will run on: } ``` -You can also block instead of allowing operating systems, just prepend the -blocked os with a '!': +You can also block instead of allowing operating systems, just prepend the blocked os with a '!': ```json { @@ -1093,13 +1145,11 @@ blocked os with a '!': The host operating system is determined by `process.platform` -It is allowed to both block and allow an item, although there isn't any -good reason to do this. +It is allowed to both block and allow an item, although there isn't any good reason to do this. ### cpu -If your code only runs on certain cpu architectures, -you can specify which ones. +If your code only runs on certain cpu architectures, you can specify which ones. ```json { @@ -1123,41 +1173,73 @@ Like the `os` option, you can also block architectures: The host architecture is determined by `process.arch` +### libc + +If your code only runs or builds in certain versions of libc, you can specify which ones. +This field only applies if `os` is `linux`. + +```json +{ + "os": "linux", + "libc": "glibc" +} +``` + +### devEngines + +The `devEngines` field aids engineers working on a codebase to all be using the same tooling. + +You can specify a `devEngines` property in your `package.json` which will run before `install`, `ci`, and `run` commands. + + +> Note: `engines` and `devEngines` differ in object shape. +They also function very differently. +`engines` is designed to alert the user when a dependency uses a different npm or node version than the project it's being used in, whereas `devEngines` is used to alert people interacting with the source code of a project. + +The supported keys under the `devEngines` property are `cpu`, `os`, `libc`, `runtime`, and `packageManager`. +Each property can be an object or an array of objects. +Objects must contain `name`, and optionally can specify `version`, and `onFail`. +`onFail` can be `warn`, `error`, or `ignore`, and if left undefined is of the same value as `error`. +`npm` will assume that you're running with `node`. +Here's an example of a project that will fail if the environment is not `node` and `npm`. +If you set `runtime.name` or `packageManager.name` to any other string, it will fail within the npm CLI. + +```json +{ + "devEngines": { + "runtime": { + "name": "node", + "onFail": "error" + }, + "packageManager": { + "name": "npm", + "onFail": "error" + } + } +} +``` + ### private -If you set `"private": true` in your package.json, then npm will refuse to -publish it. +If you set `"private": true` in your package.json, then npm will refuse to publish it. This is a way to prevent accidental publication of private repositories. -If you would like to ensure that a given package is only ever published to -a specific registry (for example, an internal registry), then use the -`publishConfig` dictionary described below to override the `registry` -config param at publish-time. +If you would like to ensure that a given package is only ever published to a specific registry (for example, an internal registry), then use the `publishConfig` dictionary described below to override the `registry` config param at publish-time. ### publishConfig -This is a set of config values that will be used at publish-time. It's -especially handy if you want to set the tag, registry or access, so that -you can ensure that a given package is not tagged with "latest", published -to the global public registry or that a scoped module is private by -default. +This is a set of config values that will be used at publish-time. +It's especially handy if you want to set the tag, registry or access, so that you can ensure that a given package is not tagged with "latest", published to the global public registry or that a scoped module is private by default. -See [`config`](/using-npm/config) to see the list of config options that -can be overridden. +See [`config`](/using-npm/config) to see the list of config options that can be overridden. ### workspaces -The optional `workspaces` field is an array of file patterns that describes -locations within the local file system that the install client should look -up to find each [workspace](/using-npm/workspaces) that needs to be -symlinked to the top level `node_modules` folder. +The optional `workspaces` field is an array of file patterns that describes locations within the local file system that the install client should look up to find each [workspace](/using-npm/workspaces) that needs to be symlinked to the top level `node_modules` folder. -It can describe either the direct paths of the folders to be used as -workspaces or it can define globs that will resolve to these same folders. +It can describe either the direct paths of the folders to be used as workspaces or it can define globs that will resolve to these same folders. -In the following example, all folders located inside the folder -`./packages` will be treated as workspaces as long as they have valid -`package.json` files inside them: +In the following example, all folders located inside the folder `./packages` will be treated as workspaces as long as they have valid `package.json` files inside them: ```json { @@ -1176,20 +1258,16 @@ npm will default some values based on package contents. * `"scripts": {"start": "node server.js"}` - If there is a `server.js` file in the root of your package, then npm will - default the `start` command to `node server.js`. + If there is a `server.js` file in the root of your package, then npm will default the `start` command to `node server.js`. * `"scripts":{"install": "node-gyp rebuild"}` - If there is a `binding.gyp` file in the root of your package and you have - not defined an `install` or `preinstall` script, npm will default the - `install` command to compile using node-gyp. + If there is a `binding.gyp` file in the root of your package and you have not defined an `install` or `preinstall` script, npm will default the `install` command to compile using node-gyp. * `"contributors": [...]` - If there is an `AUTHORS` file in the root of your package, npm will treat - each line as a `Name (url)` format, where email and url are - optional. Lines which start with a `#` or are blank, will be ignored. + If there is an `AUTHORS` file in the root of your package, npm will treat each line as a `Name (url)` format, where email and url are optional. + Lines which start with a `#` or are blank, will be ignored. ### SEE ALSO diff --git a/docs/lib/content/configuring-npm/package-lock-json.md b/docs/lib/content/configuring-npm/package-lock-json.md index f3b012175fa0e..227c6449e39df 100644 --- a/docs/lib/content/configuring-npm/package-lock-json.md +++ b/docs/lib/content/configuring-npm/package-lock-json.md @@ -6,232 +6,173 @@ description: A manifestation of the manifest ### Description -`package-lock.json` is automatically generated for any operations where npm -modifies either the `node_modules` tree, or `package.json`. It describes the -exact tree that was generated, such that subsequent installs are able to -generate identical trees, regardless of intermediate dependency updates. +`package-lock.json` is automatically generated for any operations where npm modifies either the `node_modules` tree, or `package.json`. +It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates. -This file is intended to be committed into source repositories, and serves -various purposes: +This file is intended to be committed into source repositories, and serves various purposes: -* Describe a single representation of a dependency tree such that - teammates, deployments, and continuous integration are guaranteed to - install exactly the same dependencies. +* Describe a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies. -* Provide a facility for users to "time-travel" to previous states of - `node_modules` without having to commit the directory itself. +* Provide a facility for users to "time-travel" to previous states of `node_modules` without having to commit the directory itself. -* Facilitate greater visibility of tree changes through readable source - control diffs. +* Facilitate greater visibility of tree changes through readable source control diffs. -* Optimize the installation process by allowing npm to skip repeated - metadata resolutions for previously-installed packages. +* Optimize the installation process by allowing npm to skip repeated metadata resolutions for previously-installed packages. -* As of npm v7, lockfiles include enough information to gain a complete - picture of the package tree, reducing the need to read `package.json` - files, and allowing for significant performance improvements. +* As of npm v7, lockfiles include enough information to gain a complete picture of the package tree, reducing the need to read `package.json` files, and allowing for significant performance improvements. When `npm` creates or updates `package-lock.json`, it will infer line endings and indentation from `package.json` so that the formatting of both files matches. -### `package-lock.json` vs `npm-shrinkwrap.json` +### `npm-shrinkwrap.json` -Both of these files have the same format, and perform similar functions in -the root of a project. +As of npm v12, `npm-shrinkwrap.json` is no longer read or written by +npm. Projects that previously committed `npm-shrinkwrap.json` should +rename it to `package-lock.json`; the file format is identical. When +npm v12 encounters a dependency that ships an `npm-shrinkwrap.json` +inside its tarball, the file is ignored — publishers who need to ship +a locked tree should use +[`bundleDependencies`](/configuring-npm/package-json#bundledependencies) +instead. -The difference is that `package-lock.json` cannot be published, and it will -be ignored if found in any place other than the root project. +### Hidden Lockfiles -In contrast, [npm-shrinkwrap.json](/configuring-npm/npm-shrinkwrap-json) allows -publication, and defines the dependency tree from the point encountered. -This is not recommended unless deploying a CLI tool or otherwise using the -publication process for producing production packages. +In order to avoid processing the `node_modules` folder repeatedly, npm as of v7 uses a "hidden" lockfile present in `node_modules/.package-lock.json`. +This contains information about the tree, and is used in lieu of reading the entire `node_modules` hierarchy provided that the following conditions are met: -If both `package-lock.json` and `npm-shrinkwrap.json` are present in the -root of a project, `npm-shrinkwrap.json` will take precedence and -`package-lock.json` will be ignored. +- All package folders it references exist in the `node_modules` hierarchy. +- No package folders exist in the `node_modules` hierarchy that are not listed in the lockfile. +- The modified time of the file is at least as recent as all of the package folders it references. -### Hidden Lockfiles +That is, the hidden lockfile will only be relevant if it was created as part of the most recent update to the package tree. +If another CLI mutates the tree in any way, this will be detected, and the hidden lockfile will be ignored. -In order to avoid processing the `node_modules` folder repeatedly, npm as -of v7 uses a "hidden" lockfile present in -`node_modules/.package-lock.json`. This contains information about the -tree, and is used in lieu of reading the entire `node_modules` hierarchy -provided that the following conditions are met: +Note that it _is_ possible to manually change the _contents_ of a package in such a way that the modified time of the package folder is unaffected. +For example, if you add a file to `node_modules/foo/lib/bar.js`, then the modified time on `node_modules/foo` will not reflect this change. +If you are manually editing files in `node_modules`, it is generally best to delete the file at `node_modules/.package-lock.json`. -- All package folders it references exist in the `node_modules` hierarchy. -- No package folders exist in the `node_modules` hierarchy that are not - listed in the lockfile. -- The modified time of the file is at least as recent as all of the package - folders it references. - -That is, the hidden lockfile will only be relevant if it was created as -part of the most recent update to the package tree. If another CLI mutates -the tree in any way, this will be detected, and the hidden lockfile will be -ignored. - -Note that it _is_ possible to manually change the _contents_ of a package -in such a way that the modified time of the package folder is unaffected. -For example, if you add a file to `node_modules/foo/lib/bar.js`, then the -modified time on `node_modules/foo` will not reflect this change. If you -are manually editing files in `node_modules`, it is generally best to -delete the file at `node_modules/.package-lock.json`. - -As the hidden lockfile is ignored by older npm versions, it does not -contain the backwards compatibility affordances present in "normal" -lockfiles. That is, it is `lockfileVersion: 3`, rather than -`lockfileVersion: 2`. +As the hidden lockfile is ignored by older npm versions, it does not contain the backwards compatibility affordances present in "normal" lockfiles. +That is, it is `lockfileVersion: 3`, rather than `lockfileVersion: 2`. ### Handling Old Lockfiles -When npm detects a lockfile from npm v6 or before during the package -installation process, it is automatically updated to fetch missing -information from either the `node_modules` tree or (in the case of empty -`node_modules` trees or very old lockfile formats) the npm registry. +When npm detects a lockfile from npm v6 or before during the package installation process, it is automatically updated to fetch missing information from either the `node_modules` tree or (in the case of empty `node_modules` trees or very old lockfile formats) the npm registry. ### File Format #### `name` -The name of the package this is a package-lock for. This will match what's -in `package.json`. +The name of the package this is a package-lock for. +This will match what's in `package.json`. #### `version` -The version of the package this is a package-lock for. This will match -what's in `package.json`. +The version of the package this is a package-lock for. +This will match what's in `package.json`. #### `lockfileVersion` -An integer version, starting at `1` with the version number of this -document whose semantics were used when generating this -`package-lock.json`. +An integer version, starting at `1` with the version number of this document whose semantics were used when generating this `package-lock.json`. -Note that the file format changed significantly in npm v7 to track -information that would have otherwise required looking in `node_modules` or -the npm registry. Lockfiles generated by npm v7 will contain -`lockfileVersion: 2`. +Note that the file format changed significantly in npm v7 to track information that would have otherwise required looking in `node_modules` or the npm registry. +Lockfiles generated by npm v7 will contain `lockfileVersion: 2`. -* No version provided: an "ancient" shrinkwrap file from a version of npm - prior to npm v5. +* No version provided: an "ancient" lockfile from a version of npm prior to npm v5. * `1`: The lockfile version used by npm v5 and v6. -* `2`: The lockfile version used by npm v7 and v8. Backwards compatible to v1 - lockfiles. -* `3`: The lockfile version used by npm v9 and above. Backwards compatible to npm v7. +* `2`: The lockfile version used by npm v7 and v8. Backwards compatible to v1 lockfiles. +* `3`: The lockfile version used by npm v9 and above. + Backwards compatible to npm v7. -npm will always attempt to get whatever data it can out of a lockfile, even -if it is not a version that it was designed to support. +npm will always attempt to get whatever data it can out of a lockfile, even if it is not a version that it was designed to support. #### `packages` -This is an object that maps package locations to an object containing the -information about that package. +This is an object that maps package locations to an object containing the information about that package. -The root project is typically listed with a key of `""`, and all other -packages are listed with their relative paths from the root project folder. +The root project is typically listed with a key of `""`, and all other packages are listed with their relative paths from the root project folder. Package descriptors have the following fields: * version: The version found in `package.json` -* resolved: The place where the package was actually resolved from. In - the case of packages fetched from the registry, this will be a url to a - tarball. In the case of git dependencies, this will be the full git url - with commit sha. In the case of link dependencies, this will be the - location of the link target. `registry.npmjs.org` is a magic value meaning - "the currently configured registry". +* resolved: The place where the package was actually resolved from. + In the case of packages fetched from the registry, this will be a url to a tarball. + In the case of git dependencies, this will be the full git url with commit sha. + In the case of link dependencies, this will be the location of the link target. + `registry.npmjs.org` is a magic value meaning "the currently configured registry". -* integrity: A `sha512` or `sha1` [Standard Subresource - Integrity](https://w3c.github.io/webappsec/specs/subresourceintegrity/) - string for the artifact that was unpacked in this location. +* integrity: A `sha512` or `sha1` [Standard Subresource Integrity](https://w3c.github.io/webappsec/specs/subresourceintegrity/) string for the artifact that was unpacked in this location. -* link: A flag to indicate that this is a symbolic link. If this is - present, no other fields are specified, since the link target will also - be included in the lockfile. +* link: A flag to indicate that this is a symbolic link. + If this is present, no other fields are specified, since the link target will also be included in the lockfile. * dev, optional, devOptional: If the package is strictly part of the - `devDependencies` tree, then `dev` will be true. If it is strictly part - of the `optionalDependencies` tree, then `optional` will be set. If it - is both a `dev` dependency _and_ an `optional` dependency of a non-dev - dependency, then `devOptional` will be set. (An `optional` dependency of - a `dev` dependency will have both `dev` and `optional` set.) + `devDependencies` tree, then `dev` will be true. + If it is strictly part of the `optionalDependencies` tree, then `optional` will be set. + If it is both a `dev` dependency _and_ an `optional` dependency of a non-dev dependency, then `devOptional` will be set. + (An `optional` dependency of a `dev` dependency will have both `dev` and `optional` set.) * inBundle: A flag to indicate that the package is a bundled dependency. -* hasInstallScript: A flag to indicate that the package has a `preinstall`, - `install`, or `postinstall` script. +* hasInstallScript: A flag to indicate that the package has a `preinstall`, `install`, or `postinstall` script. -* hasShrinkwrap: A flag to indicate that the package has an - `npm-shrinkwrap.json` file. +* bin, license, engines, dependencies, optionalDependencies: fields from `package.json` -* bin, license, engines, dependencies, optionalDependencies: fields from - `package.json` +* os: An array of operating systems this package is compatible with, as specified in `package.json`. This field is included when the package specifies OS restrictions. + +* cpu: An array of CPU architectures this package is compatible with, as specified in `package.json`. This field is included when the package specifies CPU restrictions. + +* funding: Funding information for the package, as specified in `package.json`. This field contains details about how to support the package maintainers. #### dependencies Legacy data for supporting versions of npm that use `lockfileVersion: 1`. -This is a mapping of package names to dependency objects. Because the -object structure is strictly hierarchical, symbolic link dependencies are -somewhat challenging to represent in some cases. +This is a mapping of package names to dependency objects. +Because the object structure is strictly hierarchical, symbolic link dependencies are somewhat challenging to represent in some cases. -npm v7 ignores this section entirely if a `packages` section is present, -but does keep it up to date in order to support switching between npm v6 -and npm v7. +npm v7 ignores this section entirely if a `packages` section is present, but does keep it up to date in order to support switching between npm v6 and npm v7. Dependency objects have the following fields: -* version: a specifier that varies depending on the nature of the package, - and is usable in fetching a new copy of it. - - * bundled dependencies: Regardless of source, this is a version number - that is purely for informational purposes. - * registry sources: This is a version number. (eg, `1.2.3`) - * git sources: This is a git specifier with resolved committish. (eg, - `git+https://example.com/foo/bar#115311855adb0789a0466714ed48a1499ffea97e`) - * http tarball sources: This is the URL of the tarball. (eg, - `https://example.com/example-1.3.0.tgz`) - * local tarball sources: This is the file URL of the tarball. (eg - `file:///opt/storage/example-1.3.0.tgz`) - * local link sources: This is the file URL of the link. (eg - `file:libs/our-module`) - -* integrity: A `sha512` or `sha1` [Standard Subresource - Integrity](https://w3c.github.io/webappsec/specs/subresourceintegrity/) - string for the artifact that was unpacked in this location. For git - dependencies, this is the commit sha. - -* resolved: For registry sources this is path of the tarball relative to - the registry URL. If the tarball URL isn't on the same server as the - registry URL then this is a complete URL. `registry.npmjs.org` is a magic - value meaning "the currently configured registry". - -* bundled: If true, this is the bundled dependency and will be installed - by the parent module. When installing, this module will be extracted - from the parent module during the extract phase, not installed as a - separate dependency. - -* dev: If true then this dependency is either a development dependency ONLY - of the top level module or a transitive dependency of one. This is false - for dependencies that are both a development dependency of the top level - and a transitive dependency of a non-development dependency of the top - level. - -* optional: If true then this dependency is either an optional dependency - ONLY of the top level module or a transitive dependency of one. This is - false for dependencies that are both an optional dependency of the top - level and a transitive dependency of a non-optional dependency of the top - level. - -* requires: This is a mapping of module name to version. This is a list of - everything this module requires, regardless of where it will be - installed. The version should match via normal matching rules a - dependency either in our `dependencies` or in a level higher than us. - -* dependencies: The dependencies of this dependency, exactly as at the top - level. +* version: a specifier that varies depending on the nature of the package, and is usable in fetching a new copy of it. + Note that for peer dependencies that are not installed, or optional dependencies that are not installed, this field may be omitted. + + * bundled dependencies: Regardless of source, this is a version number that is purely for informational purposes. + * registry sources: This is a version number. + (eg, `1.2.3`) + * git sources: This is a git specifier with resolved committish. + (eg, `git+https://example.com/foo/bar#115311855adb0789a0466714ed48a1499ffea97e`) + * http tarball sources: This is the URL of the tarball. + (eg, `https://example.com/example-1.3.0.tgz`) + * local tarball sources: This is the file URL of the tarball. + (eg `file:///opt/storage/example-1.3.0.tgz`) + * local link sources: This is the file URL of the link. + (eg `file:libs/our-module`) + + **Note:** The `version` field may be omitted for certain types of dependencies, such as optional peer dependencies that are not installed. In these cases, only metadata fields like `dev`, `optional`, and `peer` will be present. + +* integrity: A `sha512` or `sha1` [Standard Subresource Integrity](https://w3c.github.io/webappsec/specs/subresourceintegrity/) string for the artifact that was unpacked in this location. + For git dependencies, this is the commit sha. + +* resolved: For registry sources this is path of the tarball relative to the registry URL. + If the tarball URL isn't on the same server as the registry URL then this is a complete URL. + `registry.npmjs.org` is a magic value meaning "the currently configured registry". + +* bundled: If true, this is the bundled dependency and will be installed by the parent module. + When installing, this module will be extracted from the parent module during the extract phase, not installed as a separate dependency. + +* dev: If true then this dependency is either a development dependency ONLY of the top level module or a transitive dependency of one. + This is false for dependencies that are both a development dependency of the top level and a transitive dependency of a non-development dependency of the top level. + +* optional: If true then this dependency is either an optional dependency ONLY of the top level module or a transitive dependency of one. + This is false for dependencies that are both an optional dependency of the top level and a transitive dependency of a non-optional dependency of the top level. + +* requires: This is a mapping of module name to version. + This is a list of everything this module requires, regardless of where it will be installed. + The version should match via normal matching rules a dependency either in our `dependencies` or in a level higher than us. + +* dependencies: The dependencies of this dependency, exactly as at the top level. ### See also -* [npm shrinkwrap](/commands/npm-shrinkwrap) -* [npm-shrinkwrap.json](/configuring-npm/npm-shrinkwrap-json) * [package.json](/configuring-npm/package-json) * [npm install](/commands/npm-install) diff --git a/docs/lib/content/nav.yml b/docs/lib/content/nav.yml index 6b7325fec5f12..cc6463d67301f 100644 --- a/docs/lib/content/nav.yml +++ b/docs/lib/content/nav.yml @@ -8,34 +8,37 @@ children: - title: npm url: /commands/npm - description: JavaScript package manager + description: javascript package manager - title: npm access url: /commands/npm-access description: Set access level on published packages - - title: npm adduser - url: /commands/npm-adduser - description: Add a registry user account + - title: npm approve-scripts + url: /commands/npm-approve-scripts + description: Approve install scripts for specific dependencies - title: npm audit url: /commands/npm-audit description: Run a security audit - title: npm bugs url: /commands/npm-bugs - description: Bugs for a package in a web browser maybe + description: Report bugs for a package in a web browser - title: npm cache url: /commands/npm-cache description: Manipulates packages cache - title: npm ci url: /commands/npm-ci - description: Install a project with a clean slate + description: Clean install a project - title: npm completion url: /commands/npm-completion - description: Tab completion for npm + description: Tab Completion for npm - title: npm config url: /commands/npm-config description: Manage the npm configuration files - title: npm dedupe url: /commands/npm-dedupe - description: Reduce duplication + description: Reduce duplication in the package tree + - title: npm deny-scripts + url: /commands/npm-deny-scripts + description: Deny install scripts for specific dependencies - title: npm deprecate url: /commands/npm-deprecate description: Deprecate a version of a package @@ -47,16 +50,16 @@ description: Modify package distribution tags - title: npm docs url: /commands/npm-docs - description: Docs for a package in a web browser maybe + description: Open documentation for a package in a web browser - title: npm doctor url: /commands/npm-doctor - description: Check your environments + description: Check the health of your npm environment - title: npm edit url: /commands/npm-edit description: Edit an installed package - title: npm exec url: /commands/npm-exec - description: Run a command from an npm package + description: Run a command from a local or remote npm package - title: npm explain url: /commands/npm-explain description: Explain installed packages @@ -69,15 +72,15 @@ - title: npm fund url: /commands/npm-fund description: Retrieve funding information + - title: npm get + url: /commands/npm-get + description: Get a value from the npm configuration - title: npm help url: /commands/npm-help - description: Search npm help documentation + description: Get help on npm - title: npm help-search url: /commands/npm-help-search - description: Get help on npm - - title: npm hook - url: /commands/npm-hook - description: Manage registry hooks + description: Search npm help documentation - title: npm init url: /commands/npm-init description: Create a package.json file @@ -93,6 +96,9 @@ - title: npm link url: /commands/npm-link description: Symlink a package folder + - title: npm ll + url: /commands/npm-ll + description: List installed packages - title: npm login url: /commands/npm-login description: Login to a registry user account @@ -114,6 +120,9 @@ - title: npm pack url: /commands/npm-pack description: Create a tarball from a package + - title: npm patch + url: /commands/npm-patch + description: Apply local patches to installed dependencies - title: npm ping url: /commands/npm-ping description: Ping npm registry @@ -134,7 +143,7 @@ description: Publish a package - title: npm query url: /commands/npm-query - description: Retrieve a filtered list of packages + description: Dependency selector query - title: npm rebuild url: /commands/npm-rebuild description: Rebuild a package @@ -147,8 +156,8 @@ - title: npm root url: /commands/npm-root description: Display npm root - - title: npm run-script - url: /commands/npm-run-script + - title: npm run + url: /commands/npm-run description: Run arbitrary package scripts - title: npm sbom url: /commands/npm-sbom @@ -156,15 +165,12 @@ - title: npm search url: /commands/npm-search description: Search for packages - - title: npm shrinkwrap - url: /commands/npm-shrinkwrap - description: Lock down dependency versions for publication - - title: npm star - url: /commands/npm-star - description: Mark your favorite packages - - title: npm stars - url: /commands/npm-stars - description: View packages marked as favorites + - title: npm set + url: /commands/npm-set + description: Set a value in the npm configuration + - title: npm stage + url: /commands/npm-stage + description: Stage packages for publishing - title: npm start url: /commands/npm-start description: Start a package @@ -180,18 +186,21 @@ - title: npm token url: /commands/npm-token description: Manage your authentication tokens + - title: npm trust + url: /commands/npm-trust + description: Manage trusted publishing relationships between packages and CI/CD providers + - title: npm undeprecate + url: /commands/npm-undeprecate + description: Undeprecate a version of a package - title: npm uninstall url: /commands/npm-uninstall description: Remove a package - title: npm unpublish url: /commands/npm-unpublish description: Remove a package from the registry - - title: npm unstar - url: /commands/npm-unstar - description: Remove an item from your favorite packages - title: npm update url: /commands/npm-update - description: Update a package + description: Update packages - title: npm version url: /commands/npm-version description: Bump a package version @@ -203,8 +212,7 @@ description: Display npm username - title: npx url: /commands/npx - description: Run a command from an npm package - + description: Run a command from a local or remote npm package - title: Configuring npm shortName: Configuring url: /configuring-npm @@ -218,16 +226,15 @@ - title: .npmrc url: /configuring-npm/npmrc description: The npm config files - - title: npm-shrinkwrap.json - url: /configuring-npm/npm-shrinkwrap-json - description: A publishable lockfile - title: package.json url: /configuring-npm/package-json description: Specifics of npm's package.json handling - title: package-lock.json url: /configuring-npm/package-lock-json description: A manifestation of the manifest - + - title: .npm-extension + url: /configuring-npm/npm-extension + description: Imperative, root-owned manifest repairs - title: Using npm shortName: Using url: /using-npm diff --git a/docs/lib/content/using-npm/config.md b/docs/lib/content/using-npm/config.md index ba0e54d8da9f9..7f788375bae6c 100644 --- a/docs/lib/content/using-npm/config.md +++ b/docs/lib/content/using-npm/config.md @@ -1,62 +1,60 @@ --- -title: config +title: Config section: 7 -description: More than you probably want to know about npm configuration +description: About npm configuration --- ### Description -This article details npm configuration in general. To learn about the `config` command, -see [`npm config`](/commands/npm-config). +This article details npm configuration in general. +To learn about the `config` command, see [`npm config`](/commands/npm-config). npm gets its configuration values from the following sources, sorted by priority: #### Command Line Flags -Putting `--foo bar` on the command line sets the `foo` configuration -parameter to `"bar"`. A `--` argument tells the cli parser to stop -reading flags. Using `--flag` without specifying any value will set -the value to `true`. +Putting `--foo bar` on the command line sets the `foo` configuration parameter to `"bar"`. +A `--` argument tells the cli parser to stop reading flags. +Using `--flag` without specifying any value will set the value to `true`. -Example: `--flag1 --flag2` will set both configuration parameters -to `true`, while `--flag1 --flag2 bar` will set `flag1` to `true`, -and `flag2` to `bar`. Finally, `--flag1 --flag2 -- bar` will set -both configuration parameters to `true`, and the `bar` is taken -as a command argument. +Example: `--flag1 --flag2` will set both configuration parameters to `true`, while `--flag1 --flag2 bar` will set `flag1` to `true`, and `flag2` to `bar`. +Finally, `--flag1 --flag2 -- bar` will set both configuration parameters to `true`, and the `bar` is taken as a command argument. + +**Common examples:** + +* `npm install --prefix /path/to/dir` - Runs npm commands in a different directory without changing the current working directory +* `npm install --global` - Installs packages globally (shorthand: `-g`) +* `npm install --save-dev` - Saves to devDependencies (shorthand: `-D`) + +Any configuration option documented in the [Config Settings](#config-settings) section below can be set via command line flags using `--option-name value` syntax. #### Environment Variables -Any environment variables that start with `npm_config_` will be -interpreted as a configuration parameter. For example, putting -`npm_config_foo=bar` in your environment will set the `foo` -configuration parameter to `bar`. Any environment configurations that -are not given a value will be given the value of `true`. Config -values are case-insensitive, so `NPM_CONFIG_FOO=bar` will work the -same. However, please note that inside [`scripts`](/using-npm/scripts) -npm will set its own environment variables and Node will prefer -those lowercase versions over any uppercase ones that you might set. +Any environment variables that start with `npm_config_` will be interpreted as a configuration parameter. +For example, putting `npm_config_foo=bar` in your environment will set the `foo` configuration parameter to `bar`. +Any environment configurations that are not given a value will be given the value of `true`. +Config values are case-insensitive, so `NPM_CONFIG_FOO=bar` will work the same. +However, please note that inside [`scripts`](/using-npm/scripts) npm will set its own environment variables and Node will prefer those lowercase versions over any uppercase ones that you might set. For details see [this issue](https://github.com/npm/npm/issues/14528). -Notice that you need to use underscores instead of dashes, so `--allow-same-version` -would become `npm_config_allow_same_version=true`. +Notice that you need to use underscores instead of dashes, so `--allow-same-version` would become `npm_config_allow_same_version=true`. + +**Important:** When defining custom configuration keys in `.npmrc` files, use hyphens instead of underscores (e.g., `custom-key=value`). This ensures they can be overridden by environment variables, since npm automatically converts underscores to hyphens when reading environment variables. Keys with underscores in `.npmrc` files cannot be overridden via environment variables. #### npmrc Files The four relevant files are: * per-project configuration file (`/path/to/my/project/.npmrc`) -* per-user configuration file (defaults to `$HOME/.npmrc`; configurable via CLI - option `--userconfig` or environment variable `$NPM_CONFIG_USERCONFIG`) -* global configuration file (defaults to `$PREFIX/etc/npmrc`; configurable via - CLI option `--globalconfig` or environment variable `$NPM_CONFIG_GLOBALCONFIG`) +* per-user configuration file (defaults to `$HOME/.npmrc`; configurable via CLI option `--userconfig` or environment variable `$NPM_CONFIG_USERCONFIG`) +* global configuration file (defaults to `$PREFIX/etc/npmrc`; configurable via CLI option `--globalconfig` or environment variable `$NPM_CONFIG_GLOBALCONFIG`) * npm's built-in configuration file (`/path/to/npm/npmrc`) See [npmrc](/configuring-npm/npmrc) for more details. #### Default Configs -Run `npm config ls -l` to see a set of configuration parameters that are -internal to npm, and are defaults if nothing else is specified. +Run `npm config ls -l` to see a set of configuration parameters that are internal to npm, and are defaults if nothing else is specified. ### Shorthands and Other CLI Niceties @@ -64,9 +62,8 @@ The following shorthands are parsed on the command-line: -If the specified configuration param resolves unambiguously to a known -configuration parameter, then it is expanded to that configuration -parameter. For example: +If the specified configuration param resolves unambiguously to a known configuration parameter, then it is expanded to that configuration parameter. +For example: ```bash npm ls --par @@ -74,10 +71,8 @@ npm ls --par npm ls --parseable ``` -If multiple single-character shorthands are strung together, and the -resulting combination is unambiguously not some other configuration -param, then it is expanded to its various component pieces. For -example: +If multiple single-character shorthands are strung together, and the resulting combination is unambiguously not some other configuration param, then it is expanded to its various component pieces. +For example: ```bash npm ls -gpld diff --git a/docs/lib/content/using-npm/dependency-selectors.md b/docs/lib/content/using-npm/dependency-selectors.md index 5f7e27ad21848..ea4a231467636 100644 --- a/docs/lib/content/using-npm/dependency-selectors.md +++ b/docs/lib/content/using-npm/dependency-selectors.md @@ -1,5 +1,5 @@ --- -title: Dependency Selector Syntax & Querying +title: Dependency Selectors section: 7 description: Dependency Selector Syntax & Querying --- @@ -11,13 +11,15 @@ The [`npm query`](/commands/npm-query) command exposes a new dependency selector - Standardizes the shape of, & querying of, dependency graphs with a robust object model, metadata & selector syntax - Leverages existing, known language syntax & operators from CSS to make disparate package information broadly accessible - Unlocks the ability to answer complex, multi-faceted questions about dependencies, their relationships & associative metadata -- Consolidates redundant logic of similar query commands in `npm` (ex. `npm fund`, `npm ls`, `npm outdated`, `npm audit` ...) +- Consolidates redundant logic of similar query commands in `npm` (ex. +`npm fund`, `npm ls`, `npm outdated`, `npm audit` ...) ### Dependency Selector Syntax #### Overview: -- there is no "type" or "tag" selectors (ex. `div, h1, a`) as a dependency/target is the only type of `Node` that can be queried +- there is no "type" or "tag" selectors (ex. +`div, h1, a`) as a dependency/target is the only type of `Node` that can be queried - the term "dependencies" is in reference to any `Node` found in a `tree` returned by `Arborist` #### Combinators @@ -60,19 +62,23 @@ The [`npm query`](/commands/npm-query) command exposes a new dependency selector - `:missing` when a dependency is not found on disk - `:semver(, [selector], [function])` match a valid [`node-semver`](https://github.com/npm/node-semver) version or range to a selector - `:path()` [glob](https://www.npmjs.com/package/glob) matching based on dependencies path relative to the project -- `:type()` [based on currently recognized types](https://github.com/npm/npm-package-arg#result-object) +- `:type()` [based on currently recognized types](https://github.com/npm/npm-package-arg#result-object). You can also use the aggregate type of `registry` for any registry dependency (e.g. tag, version, range, alias) - `:outdated()` when a dependency is outdated - `:vuln()` when a dependency has a known vulnerability ##### `:semver(, [selector], [function])` -The `:semver()` pseudo selector allows comparing fields from each node's `package.json` using [semver](https://github.com/npm/node-semver#readme) methods. It accepts up to 3 parameters, all but the first of which are optional. +The `:semver()` pseudo selector allows comparing fields from each node's `package.json` using [semver](https://github.com/npm/node-semver#readme) methods. +It accepts up to 3 parameters, all but the first of which are optional. - `spec` a semver version or range - `selector` an attribute selector for each node (default `[version]`) - `function` a semver method to apply, one of: `satisfies`, `intersects`, `subset`, `gt`, `gte`, `gtr`, `lt`, `lte`, `ltr`, `eq`, `neq` or the special function `infer` (default `infer`) -When the special `infer` function is used the `spec` and the actual value from the node are compared. If both are versions, according to `semver.valid()`, `eq` is used. If both values are ranges, according to `!semver.valid()`, `intersects` is used. If the values are mixed types `satisfies` is used. +When the special `infer` function is used the `spec` and the actual value from the node are compared. +If both are versions, according to `semver.valid()`, `eq` is used. +If both values are ranges, according to `!semver.valid()`, `intersects` is used. +If the values are mixed types `satisfies` is used. Some examples: @@ -82,7 +88,8 @@ Some examples: ##### `:outdated()` -The `:outdated` pseudo selector retrieves data from the registry and returns information about which of your dependencies are outdated. The type parameter may be one of the following: +The `:outdated` pseudo selector retrieves data from the registry and returns information about which of your dependencies are outdated. +The type parameter may be one of the following: - `any` (default) a version exists that is greater than the current one - `in-range` a version exists that is greater than the current one, and satisfies at least one if its parent's dependencies @@ -91,11 +98,14 @@ The `:outdated` pseudo selector retrieves data from the registry and returns inf - `minor` a version exists that is a semver minor greater than the current one - `patch` a version exists that is a semver patch greater than the current one -In addition to the filtering performed by the pseudo selector, some extra data is added to the resulting objects. The following data can be found under the `queryContext` property of each node. +In addition to the filtering performed by the pseudo selector, some extra data is added to the resulting objects. +The following data can be found under the `queryContext` property of each node. - `versions` an array of every available version of the given node -- `outdated.inRange` an array of objects, each with a `from` and `versions`, where `from` is the on-disk location of the node that depends on the current node and `versions` is an array of all available versions that satisfies that dependency. This is only populated if `:outdated(in-range)` is used. -- `outdated.outOfRange` an array of objects, identical in shape to `inRange`, but where the `versions` array is every available version that does not satisfy the dependency. This is only populated if `:outdated(out-of-range)` is used. +- `outdated.inRange` an array of objects, each with a `from` and `versions`, where `from` is the on-disk location of the node that depends on the current node and `versions` is an array of all available versions that satisfies that dependency. +This is only populated if `:outdated(in-range)` is used. +- `outdated.outOfRange` an array of objects, identical in shape to `inRange`, but where the `versions` array is every available version that does not satisfy the dependency. +This is only populated if `:outdated(out-of-range)` is used. Some examples: @@ -104,9 +114,13 @@ Some examples: ##### `:vuln` -The `:vuln` pseudo selector retrieves data from the registry and returns information about which if your dependencies has a known vulnerability. Only dependencies whose current version matches a vulnerability will be returned. For example if you have `semver@7.6.0` in your tree, a vulnerability for `semver` which affects versions `<=6.3.1` will not match. +The `:vuln` pseudo selector retrieves data from the registry and returns information about which if your dependencies has a known vulnerability. +Only dependencies whose current version matches a vulnerability will be returned. +For example if you have `semver@7.6.0` in your tree, a vulnerability for `semver` which affects versions `<=6.3.1` will not match. -You can also filter results by certain attributes in advisories. Currently that includes `severity` and `cwe`. Note that severity filtering is done per severity, it does not include severities "higher" or "lower" than the one specified. +You can also filter results by certain attributes in advisories. +Currently that includes `severity` and `cwe`. +Note that severity filtering is done per severity, it does not include severities "higher" or "lower" than the one specified. In addition to the filtering performed by the pseudo selector, info about each relevant advisory will be added to the `queryContext` attribute of each node under the `advisories` attribute. @@ -121,7 +135,8 @@ Some examples: The attribute selector evaluates the key/value pairs in `package.json` if they are `String`s. -- `[]` attribute selector (ie. existence of attribute) +- `[]` attribute selector (ie. +existence of attribute) - `[attribute=value]` attribute value is equivalent... - `[attribute~=value]` attribute value contains word... - `[attribute*=value]` attribute value contains string... @@ -131,7 +146,10 @@ The attribute selector evaluates the key/value pairs in `package.json` if they a #### `Array` & `Object` Attribute Selectors -The generic `:attr()` pseudo selector standardizes a pattern which can be used for attribute selection of `Object`s, `Array`s or `Arrays` of `Object`s accessible via `Arborist`'s `Node.package` metadata. This allows for iterative attribute selection beyond top-level `String` evaluation. The last argument passed to `:attr()` must be an `attribute` selector or a nested `:attr()`. See examples below: +The generic `:attr()` pseudo selector standardizes a pattern which can be used for attribute selection of `Object`s, `Array`s or `Arrays` of `Object`s accessible via `Arborist`'s `Node.package` metadata. +This allows for iterative attribute selection beyond top-level `String` evaluation. +The last argument passed to `:attr()` must be an `attribute` selector or a nested `:attr()`. +See examples below: #### `Objects` @@ -145,13 +163,14 @@ The generic `:attr()` pseudo selector standardizes a pattern which can be used f Nested objects are expressed as sequential arguments to `:attr()`. ```css -/* return dependencies that have a testling config for opera browsers */ +/* return dependencies that have a [testling config](https://ci.testling.com/guide/advanced_configuration) for opera browsers */ *:attr(testling, browsers, [~=opera]) ``` #### `Arrays` -`Array`s specifically uses a special/reserved `.` character in place of a typical attribute name. `Arrays` also support exact `value` matching when a `String` is passed to the selector. +`Array`s specifically uses a special/reserved `.` character in place of a typical attribute name. +`Arrays` also support exact `value` matching when a `String` is passed to the selector. ##### Example of an `Array` Attribute Selection: ```css @@ -176,7 +195,11 @@ Nested objects are expressed as sequential arguments to `:attr()`. ### Groups -Dependency groups are defined by the package relationships to their ancestors (ie. the dependency types that are defined in `package.json`). This approach is user-centric as the ecosystem has been taught to think about dependencies in these groups first-and-foremost. Dependencies are allowed to be included in multiple groups (ex. a `prod` dependency may also be a `dev` dependency (in that it's also required by another `dev` dependency) & may also be `bundled` - a selector for that type of dependency would look like: `*.prod.dev.bundled`). +Dependency groups are defined by the package relationships to their ancestors (ie. +the dependency types that are defined in `package.json`). +This approach is user-centric as the ecosystem has been taught to think about dependencies in these groups first-and-foremost. +Dependencies are allowed to be included in multiple groups (ex. +a `prod` dependency may also be a `dev` dependency (in that it's also required by another `dev` dependency) & may also be `bundled` - a selector for that type of dependency would look like: `*.prod.dev.bundled`). - `.prod` - `.dev` @@ -185,7 +208,8 @@ Dependency groups are defined by the package relationships to their ancestors (i - `.bundled` - `.workspace` -Please note that currently `workspace` deps are always `prod` dependencies. Additionally the `.root` dependency is also considered a `prod` dependency. +Please note that currently `workspace` deps are always `prod` dependencies. +Additionally the `.root` dependency is also considered a `prod` dependency. ### Programmatic Usage diff --git a/docs/lib/content/using-npm/developers.md b/docs/lib/content/using-npm/developers.md index 5fc2e5876e3dd..7f86dc123db6c 100644 --- a/docs/lib/content/using-npm/developers.md +++ b/docs/lib/content/using-npm/developers.md @@ -1,24 +1,21 @@ --- -title: developers +title: Developers section: 7 -description: Developer Guide +description: Developer guide --- ### Description -So, you've decided to use npm to develop (and maybe publish/deploy) -your project. +So, you've decided to use npm to develop (and maybe publish/deploy) your project. Fantastic! -There are a few things that you need to do above the simple steps -that your users will do to install your program. +There are a few things that you need to do above the simple steps that your users will do to install your program. ### About These Documents -These are man pages. If you install npm, you should be able to -then do `man npm-thing` to get the documentation on a particular -topic, or `npm help thing` to see the same information. +These are man pages. +If you install npm, you should be able to then do `man npm-thing` to get the documentation on a particular topic, or `npm help thing` to see the same information. ### What is a Package @@ -32,10 +29,7 @@ A package is: * f) a `` that has a "latest" tag satisfying (e) * g) a `git` url that, when cloned, results in (a). -Even if you never publish your package, you can still get a lot of -benefits of using npm if you just want to write a node program (a), and -perhaps if you also want to be able to easily install it elsewhere -after packing it up into a tarball (b). +Even if you never publish your package, you can still get a lot of benefits of using npm if you just want to write a node program (a), and perhaps if you also want to be able to easily install it elsewhere after packing it up into a tarball (b). Git urls can be of the form: @@ -46,74 +40,62 @@ git+http://user@hostname/project/blah.git#commit-ish git+https://user@hostname/project/blah.git#commit-ish ``` -The `commit-ish` can be any tag, sha, or branch which can be supplied as -an argument to `git checkout`. The default is whatever the repository uses -as its default branch. +The `commit-ish` can be any tag, sha, or branch which can be supplied as an argument to `git checkout`. +The default is whatever the repository uses as its default branch. ### The package.json File -You need to have a `package.json` file in the root of your project to do -much of anything with npm. That is basically the whole interface. +You need to have a `package.json` file in the root of your project to do much of anything with npm. +That is basically the whole interface. -See [`package.json`](/configuring-npm/package-json) for details about what -goes in that file. At the very least, you need: +See [`package.json`](/configuring-npm/package-json) for details about what goes in that file. +At the very least, you need: -* name: This should be a string that identifies your project. Please do - not use the name to specify that it runs on node, or is in JavaScript. - You can use the "engines" field to explicitly state the versions of node - (or whatever else) that your program requires, and it's pretty well - assumed that it's JavaScript. +* name: This should be a string that identifies your project. + Please do not use the name to specify that it runs on node, or is in JavaScript. + You can use the "engines" field to explicitly state the versions of node (or whatever else) that your program requires, and it's pretty well assumed that it's JavaScript. It does not necessarily need to match your github repository name. - So, `node-foo` and `bar-js` are bad names. `foo` or `bar` are better. + So, `node-foo` and `bar-js` are bad names. + `foo` or `bar` are better. * version: A semver-compatible version. -* engines: Specify the versions of node (or whatever else) that your - program runs on. The node API changes a lot, and there may be bugs or - new functionality that you depend on. Be explicit. +* engines: Specify the versions of node (or whatever else) that your program runs on. + The node API changes a lot, and there may be bugs or new functionality that you depend on. + Be explicit. * author: Take some credit. -* scripts: If you have a special compilation or installation script, then - you should put it in the `scripts` object. You should definitely have at - least a basic smoke-test command as the "scripts.test" field. See - [scripts](/using-npm/scripts). +* scripts: If you have a special compilation or installation script, then you should put it in the `scripts` object. + You should definitely have at least a basic smoke-test command as the "scripts.test" field. + See [scripts](/using-npm/scripts). -* main: If you have a single module that serves as the entry point to your - program (like what the "foo" package gives you at require("foo")), then - you need to specify that in the "main" field. +* main: If you have a single module that serves as the entry point to your program (like what the "foo" package gives you at require("foo")), then you need to specify that in the "main" field. -* directories: This is an object mapping names to folders. The best ones - to include are "lib" and "doc", but if you use "man" to specify a folder - full of man pages, they'll get installed just like these ones. +* directories: This is an object mapping names to folders. + The best ones to include are "lib" and "doc", but if you use "man" to specify a folder full of man pages, they'll get installed just like these ones. -You can use `npm init` in the root of your package in order to get you -started with a pretty basic package.json file. See [`npm -init`](/commands/npm-init) for more info. +You can use `npm init` in the root of your package in order to get you started with a pretty basic package.json file. +See [`npm init`](/commands/npm-init) for more info. ### Keeping files *out* of your Package -Use a `.npmignore` file to keep stuff out of your package. If there's no -`.npmignore` file, but there *is* a `.gitignore` file, then npm will ignore -the stuff matched by the `.gitignore` file. If you *want* to include -something that is excluded by your `.gitignore` file, you can create an -empty `.npmignore` file to override it. Like `git`, `npm` looks for -`.npmignore` and `.gitignore` files in all subdirectories of your package, -not only the root directory. +Use a `.npmignore` file to keep stuff out of your package. +If there's no `.npmignore` file, but there *is* a `.gitignore` file, then npm will ignore the stuff matched by the `.gitignore` file. +If you *want* to include something that is excluded by your `.gitignore` file, you can create an empty `.npmignore` file to override it. +Like `git`, `npm` looks for `.npmignore` and `.gitignore` files in all subdirectories of your package, not only the root directory. -`.npmignore` files follow the [same pattern -rules](https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository#_ignoring) -as `.gitignore` files: +`.npmignore` files follow the [same pattern rules](https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository#_ignoring) as `.gitignore` files: * Blank lines or lines starting with `#` are ignored. * Standard glob patterns work. * You can end patterns with a forward slash `/` to specify a directory. * You can negate a pattern by starting it with an exclamation point `!`. -By default, the following paths and files are ignored, so there's no -need to add them to `.npmignore` explicitly: +By default, some paths and files are ignored, so there's no need to add them to `.npmignore` explicitly. +Some examples are: * `.*.swp` * `._*` @@ -130,37 +112,28 @@ need to add them to `.npmignore` explicitly: * `CVS` * `npm-debug.log` -Additionally, everything in `node_modules` is ignored, except for -bundled dependencies. npm automatically handles this for you, so don't -bother adding `node_modules` to `.npmignore`. +Additionally, everything in `node_modules` is ignored, except for bundled dependencies. +npm automatically handles this for you, so don't bother adding `node_modules` to `.npmignore`. -The following paths and files are never ignored, so adding them to -`.npmignore` is pointless: +The following paths and files are never ignored, so adding them to `.npmignore` is pointless: * `package.json` * `README` (and its variants) -* `CHANGELOG` (and its variants) * `LICENSE` / `LICENCE` -If, given the structure of your project, you find `.npmignore` to be a -maintenance headache, you might instead try populating the `files` -property of `package.json`, which is an array of file or directory names -that should be included in your package. Sometimes manually picking -which items to allow is easier to manage than building a block list. +If, given the structure of your project, you find `.npmignore` to be a maintenance headache, you might instead try populating the `files` property of `package.json`, which is an array of file or directory names that should be included in your package. +Sometimes manually picking which items to allow is easier to manage than building a block list. + +See [`package.json`](/configuring-npm/package-json) for more info on what can and can't be ignored. #### Testing whether your `.npmignore` or `files` config works -If you want to double check that your package will include only the files -you intend it to when published, you can run the `npm pack` command locally -which will generate a tarball in the working directory, the same way it -does for publishing. +If you want to double check that your package will include only the files you intend it to when published, you can run the `npm pack` command locally which will generate a tarball in the working directory, the same way it does for publishing. ### Link Packages -`npm link` is designed to install a development package and see the -changes in real time without having to keep re-installing it. (You do -need to either re-link or `npm rebuild -g` to update compiled packages, -of course.) +`npm link` is designed to install a development package and see the changes in real time without having to keep re-installing it. +(You do need to either re-link or `npm rebuild -g` to update compiled packages, of course.) More info at [`npm link`](/commands/npm-link). @@ -168,9 +141,8 @@ More info at [`npm link`](/commands/npm-link). **This is important.** -If you can not install it locally, you'll have -problems trying to publish it. Or, worse yet, you'll be able to -publish it, but you'll be publishing a broken or pointless package. +If you cannot install it locally, you'll have problems trying to publish it. +Or, worse yet, you'll be able to publish it, but you'll be publishing a broken or pointless package. So don't do that. In the root of your package, do this: @@ -179,8 +151,8 @@ In the root of your package, do this: npm install . -g ``` -That'll show you that it's working. If you'd rather just create a symlink -package that points to your working directory, then do this: +That'll show you that it's working. +If you'd rather just create a symlink package that points to your working directory, then do this: ```bash npm link @@ -197,36 +169,25 @@ npm install ../my-package to install it locally into the node_modules folder in that other place. -Then go into the node-repl, and try using require("my-thing") to -bring in your module's main module. +Then go into the node-repl, and try using require("my-thing") to bring in your module's main module. ### Create a User Account -Create a user with the adduser command. It works like this: - -```bash -npm adduser -``` - -and then follow the prompts. - -This is documented better in [npm adduser](/commands/npm-adduser). +Create a user account on the [npm website](https://www.npmjs.com/signup). ### Publish your Package -This part's easy. In the root of your folder, do this: +This part's easy. +In the root of your folder, do this: ```bash npm publish ``` -You can give publish a url to a tarball, or a filename of a tarball, -or a path to a folder. +You can give publish a url to a tarball, or a filename of a tarball, or a path to a folder. -Note that pretty much **everything in that folder will be exposed** -by default. So, if you have secret stuff in there, use a -`.npmignore` file to list out the globs to ignore, or publish -from a fresh checkout. +Note that pretty much **everything in that folder will be exposed** by default. +So, if you have secret stuff in there, use a `.npmignore` file to list out the globs to ignore, or publish from a fresh checkout. ### Brag about it @@ -241,5 +202,5 @@ Tell the world how easy it is to install your program! * [package.json](/configuring-npm/package-json) * [npm scripts](/using-npm/scripts) * [npm publish](/commands/npm-publish) -* [npm adduser](/commands/npm-adduser) +* [npm login](/commands/npm-login) * [npm registry](/using-npm/registry) diff --git a/docs/lib/content/using-npm/logging.md b/docs/lib/content/using-npm/logging.md index 4470d5d155acd..6f1a2be102a1a 100644 --- a/docs/lib/content/using-npm/logging.md +++ b/docs/lib/content/using-npm/logging.md @@ -1,7 +1,7 @@ --- title: Logging section: 7 -description: Why, What & How We Log +description: Why, What & How we Log --- ### Description @@ -12,10 +12,11 @@ The `npm` CLI has various mechanisms for showing different levels of information All logs are written to a debug log, with the path to that file printed if the execution of a command fails. -The default location of the logs directory is a directory named `_logs` inside the npm cache. This can be changed with the `logs-dir` config option. +The default location of the logs directory is a directory named `_logs` inside the npm cache. +This can be changed with the `logs-dir` config option. -For example, if you wanted to write all your logs to the current working directory, you could run: `npm install --logs-dir=.`. This is especially helpful in debugging a specific `npm` issue as you can run -a command multiple times with different config values and then diff all the log files. +For example, if you wanted to write all your logs to the current working directory, you could run: `npm install --logs-dir=.`. +This is especially helpful in debugging a specific `npm` issue as you can run a command multiple times with different config values and then diff all the log files. Log files will be removed from the `logs-dir` when the number of log files exceeds `logs-max`, with the oldest logs being deleted first. @@ -38,7 +39,7 @@ The default value of `loglevel` is `"notice"` but there are several levels/types - `"verbose"` - `"silly"` -All logs pertaining to a level proceeding the current setting will be shown. +All logs pertaining to a level preceding the current setting will be shown. ##### Aliases @@ -55,30 +56,31 @@ The log levels listed above have various corresponding aliases, including: #### `foreground-scripts` -The `npm` CLI began hiding the output of lifecycle scripts for `npm install` as of `v7`. Notably, this means you will not see logs/output from packages that may be using "install scripts" to display information back to you or from your own project's scripts defined in `package.json`. If you'd like to change this behavior & log this output you can set `foreground-scripts` to `true`. +The `npm` CLI began hiding the output of lifecycle scripts for `npm install` as of `v7`. +Notably, this means you will not see logs/output from packages that may be using "install scripts" to display information back to you or from your own project's scripts defined in `package.json`. +If you'd like to change this behavior & log this output you can set `foreground-scripts` to `true`. ### Timing Information -The [`--timing` config](/using-npm/config#timing) can be set which does a few -things: +The [`--timing` config](/using-npm/config#timing) can be set which does a few things: 1. Always shows the full path to the debug log regardless of command exit status 1. Write timing information to a process specific timing file in the cache or `logs-dir` 1. Output timing information to the terminal -This file contains a `timers` object where the keys are an identifier for the -portion of the process being timed and the value is the number of milliseconds it took to complete. +This file contains a `timers` object where the keys are an identifier for the portion of the process being timed and the value is the number of milliseconds it took to complete. -Sometimes it is helpful to get timing information without outputting anything to the terminal. For -example, the performance might be affected by writing to the terminal. In this case you can use -`--timing --silent` which will still write the timing file, but not output anything to the terminal -while running. +Sometimes it is helpful to get timing information without outputting anything to the terminal. +For example, the performance might be affected by writing to the terminal. +In this case you can use +`--timing --silent` which will still write the timing file, but not output anything to the terminal while running. ### Registry Response Headers #### `npm-notice` -The `npm` CLI reads from & logs any `npm-notice` headers that are returned from the configured registry. This mechanism can be used by third-party registries to provide useful information when network-dependent requests occur. +The `npm` CLI reads from & logs any `npm-notice` headers that are returned from the configured registry. +This mechanism can be used by third-party registries to provide useful information when network-dependent requests occur. This header is not cached, and will not be logged if the request is served from the cache. @@ -89,7 +91,8 @@ The `npm` CLI makes a best effort to redact the following from terminal output a - Passwords inside basic auth URLs - npm tokens -However, this behavior should not be relied on to keep all possible sensitive information redacted. If you are concerned about secrets in your log file or terminal output, you can use `--loglevel=silent` and `--logs-max=0` to ensure no logs are written to your terminal or filesystem. +However, this behavior should not be relied on to keep all possible sensitive information redacted. +If you are concerned about secrets in your log file or terminal output, you can use `--loglevel=silent` and `--logs-max=0` to ensure no logs are written to your terminal or filesystem. ### See also diff --git a/docs/lib/content/using-npm/orgs.md b/docs/lib/content/using-npm/orgs.md index 5fe9ac6de377f..ea1173a852acc 100644 --- a/docs/lib/content/using-npm/orgs.md +++ b/docs/lib/content/using-npm/orgs.md @@ -1,7 +1,7 @@ --- -title: orgs +title: Organizations section: 7 -description: Working with Teams & Orgs +description: Working with teams & organizations --- ### Description @@ -10,13 +10,17 @@ There are three levels of org users: 1. Super admin, controls billing & adding people to the org. 2. Team admin, manages team membership & package access. -3. Developer, works on packages they are given access to. +3. Developer, works on packages they are given access to. -The super admin is the only person who can add users to the org because it impacts the monthly bill. The super admin will use the website to manage membership. Every org has a `developers` team that all users are automatically added to. +The super admin is the only person who can add users to the org because it impacts the monthly bill. +The super admin will use the website to manage membership. +Every org has a `developers` team that all users are automatically added to. -The team admin is the person who manages team creation, team membership, and package access for teams. The team admin grants package access to teams, not individuals. +The team admin is the person who manages team creation, team membership, and package access for teams. +The team admin grants package access to teams, not individuals. -The developer will be able to access packages based on the teams they are on. Access is either read-write or read-only. +The developer will be able to access packages based on the teams they are on. +Access is either read-write or read-only. There are two main commands: @@ -31,7 +35,8 @@ There are two main commands: npm team ls :developers ``` -* Each org is automatically given a `developers` team, so you can see the whole list of team members in your org. This team automatically gets read-write access to all packages, but you can change that with the `access` command. +* Each org is automatically given a `developers` team, so you can see the whole list of team members in your org. +This team automatically gets read-write access to all packages, but you can change that with the `access` command. * Create a new team: @@ -71,19 +76,19 @@ npm access revoke [] * See what org packages a team member can access: ```bash -npm access ls-packages +npm access list packages ``` * See packages available to a specific team: ```bash -npm access ls-packages +npm access list packages ``` * Check which teams are collaborating on a package: ```bash -npm access ls-collaborators +npm access list collaborators ``` ### See also diff --git a/docs/lib/content/using-npm/package-spec.md b/docs/lib/content/using-npm/package-spec.md index 1ace780019fb3..7318ca29a4899 100644 --- a/docs/lib/content/using-npm/package-spec.md +++ b/docs/lib/content/using-npm/package-spec.md @@ -1,5 +1,5 @@ --- -title: package-spec +title: Package spec section: 7 description: Package name specifier --- @@ -7,12 +7,9 @@ description: Package name specifier ### Description -Commands like `npm install` and the dependency sections in the -`package.json` use a package name specifier. This can be many different -things that all refer to a "package". Examples include a package name, -git url, tarball, or local directory. These will generally be referred -to as `` in the help output for the npm commands that use -this package name specifier. +Commands like `npm install` and the dependency sections in the `package.json` use a package name specifier. +This can be many different things that all refer to a "package". Examples include a package name, git url, tarball, or local directory. +These will generally be referred to as `` in the help output for the npm commands that use this package name specifier. ### Package name @@ -21,10 +18,8 @@ this package name specifier. * `[<@scope>/]@` * `[<@scope>/]@` -Refers to a package by name, with or without a scope, and optionally -tag, version, or version range. This is typically used in combination -with the [registry](/using-npm/config#registry) config to refer to a -package in a registry. +Refers to a package by name, with or without a scope, and optionally tag, version, or version range. +This is typically used in combination with the [registry](/using-npm/config#registry) config to refer to a package in a registry. Examples: * `npm` @@ -37,31 +32,24 @@ Examples: * `@npm:` -Primarily used by commands like `npm install` and in the dependency -sections in the `package.json`, this refers to a package by an alias. -The `` is the name of the package as it is reified in the -`node_modules` folder, and the `` refers to a package name as -found in the configured registry. +Primarily used by commands like `npm install` and in the dependency sections in the `package.json`, this refers to a package by an alias. +The `` is the name of the package as it is reified in the `node_modules` folder, and the `` refers to a package name as found in the configured registry. -See `Package name` above for more info on referring to a package by -name, and [registry](/using-npm/config#registry) for configuring which -registry is used when referring to a package by name. +See `Package name` above for more info on referring to a package by name, and [registry](/using-npm/config#registry) for configuring which registry is used when referring to a package by name. Examples: -* `semver:@npm:@npmcli/semver-with-patch` -* `semver:@npm:semver@7.2.2` -* `semver:@npm:semver@legacy` +* `semver@npm:@npmcli/semver-with-patch` +* `semver@npm:semver@7.2.2` +* `semver@npm:semver@legacy` ### Folders * `` -This refers to a package on the local filesystem. Specifically this is -a folder with a `package.json` file in it. This *should* always be -prefixed with a `/` or `./` (or your OS equivalent) to reduce confusion. -npm currently will parse a string with more than one `/` in it as a -folder, but this is legacy behavior that may be removed in a future -version. +This refers to a package on the local filesystem. +Specifically this is a folder with a `package.json` file in it. +This *should* always be prefixed with a `/` or `./` (or your OS equivalent) to reduce confusion. +npm currently will parse a string with more than one `/` in it as a folder, but this is legacy behavior that may be removed in a future version. Examples: @@ -78,18 +66,17 @@ Examples: * `./my-package.tgz` * `https://registry.npmjs.org/semver/-/semver-1.0.0.tgz` -Refers to a package in a tarball format, either on the local filesystem -or remotely via url. This is the format that packages exist in when -uploaded to a registry. +Refers to a package in a tarball format, either on the local filesystem or remotely via url. +This is the format that packages exist in when uploaded to a registry. ### git urls * `` * `/` -Refers to a package in a git repo. This can be a full git url, git -shorthand, or a username/package on GitHub. You can specify a -git tag, branch, or other git ref by appending `#ref`. +Refers to a package in a git repo. +This can be a full git url, git shorthand, or a username/package on GitHub. +You can specify a git tag, branch, or other git ref by appending `#ref`. Examples: diff --git a/docs/lib/content/using-npm/registry.md b/docs/lib/content/using-npm/registry.md index 035ede5b32a3a..2af6edcd7520a 100644 --- a/docs/lib/content/using-npm/registry.md +++ b/docs/lib/content/using-npm/registry.md @@ -1,74 +1,49 @@ --- -title: registry +title: Registry section: 7 description: The JavaScript Package Registry --- ### Description -To resolve packages by name and version, npm talks to a registry website -that implements the CommonJS Package Registry specification for reading -package info. +To resolve packages by name and version, npm talks to a registry website that implements the CommonJS Package Registry specification for reading package info. npm is configured to use the **npm public registry** at - by default. Use of the npm public registry is -subject to terms of use available at . - -You can configure npm to use any compatible registry you like, and even run -your own registry. Use of someone else's registry may be governed by their -terms of use. - -npm's package registry implementation supports several -write APIs as well, to allow for publishing packages and managing user -account information. - -The npm public registry is powered by a CouchDB database, -of which there is a public mirror at . - -The registry URL used is determined by the scope of the package (see -[`scope`](/using-npm/scope). If no scope is specified, the default registry is -used, which is supplied by the [`registry` config](/using-npm/config#registry) -parameter. See [`npm config`](/commands/npm-config), -[`npmrc`](/configuring-npm/npmrc), and [`config`](/using-npm/config) for more on -managing npm's configuration. -Authentication configuration such as auth tokens and certificates are configured -specifically scoped to an individual registry. See -[Auth Related Configuration](/configuring-npm/npmrc#auth-related-configuration) - -When the default registry is used in a package-lock or shrinkwrap it has the -special meaning of "the currently configured registry". If you create a lock -file while using the default registry you can switch to another registry and -npm will install packages from the new registry, but if you create a lock -file while using a custom registry packages will be installed from that -registry even after you change to another registry. + by default. +Use of the npm public registry is subject to terms of use available at . + +You can configure npm to use any compatible registry you like, and even run your own registry. +Use of someone else's registry may be governed by their terms of use. + +npm's package registry implementation supports several write APIs as well, to allow for publishing packages and managing user account information. + +The registry URL used is determined by the scope of the package (see [`scope`](/using-npm/scope). +If no scope is specified, the default registry is used, which is supplied by the [`registry` config](/using-npm/config#registry) parameter. +See [`npm config`](/commands/npm-config), [`npmrc`](/configuring-npm/npmrc), and [`config`](/using-npm/config) for more on managing npm's configuration. +Authentication configuration such as auth tokens and certificates are configured specifically scoped to an individual registry. +See [Auth Related Configuration](/configuring-npm/npmrc#auth-related-configuration) + +When the default registry is used in a package-lock it has the special meaning of "the currently configured registry". If you create a lock file while using the default registry you can switch to another registry and npm will install packages from the new registry, but if you create a lock file while using a custom registry packages will be installed from that registry even after you change to another registry. ### Does npm send any information about me back to the registry? Yes. -When making requests of the registry npm adds two headers with information -about your environment: - -* `Npm-Scope` – If your project is scoped, this header will contain its - scope. In the future npm hopes to build registry features that use this - information to allow you to customize your experience for your - organization. -* `Npm-In-CI` – Set to "true" if npm believes this install is running in a - continuous integration environment, "false" otherwise. This is detected by - looking for the following environment variables: `CI`, `TDDIUM`, - `JENKINS_URL`, `bamboo.buildKey`. If you'd like to learn more you may find - the [original PR](https://github.com/npm/npm-registry-client/pull/129) - interesting. - This is used to gather better metrics on how npm is used by humans, versus - build farms. - -The npm registry does not try to correlate the information in these headers -with any authenticated accounts that may be used in the same requests. +When making requests of the registry npm adds two headers with information about your environment: + +* `Npm-Scope` – If your project is scoped, this header will contain its scope. +In the future npm hopes to build registry features that use this information to allow you to customize your experience for your organization. +* `Npm-In-CI` – Set to "true" if npm believes this install is running in a continuous integration environment, "false" otherwise. +This is detected by looking for the following environment variables: `CI`, `TDDIUM`, + `JENKINS_URL`, `bamboo.buildKey`. +If you'd like to learn more you may find the [original PR](https://github.com/npm/npm-registry-client/pull/129) interesting. + This is used to gather better metrics on how npm is used by humans, versus build farms. + +The npm registry does not try to correlate the information in these headers with any authenticated accounts that may be used in the same requests. ### How can I prevent my package from being published in the official registry? -Set `"private": true` in your `package.json` to prevent it from being -published at all, or +Set `"private": true` in your `package.json` to prevent it from being published at all, or `"publishConfig":{"registry":"http://my-internal-registry.local"}` to force it to be published only to your internal/private registry. diff --git a/docs/lib/content/using-npm/removal.md b/docs/lib/content/using-npm/removal.md index 3b94a7d18f9d7..4cf3b64c6d4cf 100644 --- a/docs/lib/content/using-npm/removal.md +++ b/docs/lib/content/using-npm/removal.md @@ -1,7 +1,7 @@ --- -title: removal +title: Removal section: 7 -description: Cleaning the Slate +description: Cleaning the slate --- ### Synopsis @@ -16,20 +16,17 @@ Or, if that fails, please proceed to more severe uninstalling methods. ### More Severe Uninstalling -Usually, the above instructions are sufficient. That will remove -npm, but leave behind anything you've installed. +Usually, the above instructions are sufficient. +That will remove npm, but leave behind anything you've installed. -If that doesn't work, or if you require more drastic measures, -continue reading. +If that doesn't work, or if you require more drastic measures, continue reading. -Note that this is only necessary for globally-installed packages. Local -installs are completely contained within a project's `node_modules` -folder. Delete that folder, and everything is gone unless a package's -install script is particularly ill-behaved. +Note that this is only necessary for globally-installed packages. +Local installs are completely contained within a project's `node_modules` folder. +Delete that folder, and everything is gone unless a package's install script is particularly ill-behaved. -This assumes that you installed node and npm in the default place. If -you configured node with a different `--prefix`, or installed npm with a -different prefix setting, then adjust the paths accordingly, replacing +This assumes that you installed node and npm in the default place. +If you configured node with a different `--prefix`, or installed npm with a different prefix setting, then adjust the paths accordingly, replacing `/usr/local` with your install prefix. To remove everything npm-related manually: @@ -38,17 +35,15 @@ To remove everything npm-related manually: rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/npm* ``` -If you installed things *with* npm, then your best bet is to uninstall -them with npm first, and then install them again once you have a -proper install. This can help find any symlinks that are lying -around: +If you installed things *with* npm, then your best bet is to uninstall them with npm first, and then install them again once you have a proper install. +This can help find any symlinks that are lying around: ```bash ls -laF /usr/local/{lib/node{,/.npm},bin,share/man} | grep npm ``` -Prior to version 0.3, npm used shim files for executables and node -modules. To track those down, you can do the following: +Prior to version 0.3, npm used shim files for executables and node modules. +To track those down, you can do the following: ```bash find /usr/local/{lib/node,bin} -exec grep -l npm \{\} \; ; diff --git a/docs/lib/content/using-npm/scope.md b/docs/lib/content/using-npm/scope.md index b43fa2e9ff381..f9fc14075c4a3 100644 --- a/docs/lib/content/using-npm/scope.md +++ b/docs/lib/content/using-npm/scope.md @@ -1,40 +1,34 @@ --- -title: scope +title: Scope section: 7 description: Scoped packages --- ### Description -All npm packages have a name. Some package names also have a scope. A scope -follows the usual rules for package names (URL-safe characters, no leading dots -or underscores). When used in package names, scopes are preceded by an `@` symbol -and followed by a slash, e.g. +All npm packages have a name. +Some package names also have a scope. +A scope follows the usual rules for package names (URL-safe characters, no leading dots or underscores). +When used in package names, scopes are preceded by an `@` symbol and followed by a slash, e.g. ```bash @somescope/somepackagename ``` -Scopes are a way of grouping related packages together, and also affect a few -things about the way npm treats the package. +Scopes are a way of grouping related packages together, and also affect a few things about the way npm treats the package. -Each npm user/organization has their own scope, and only you can add packages -in your scope. This means you don't have to worry about someone taking your -package name ahead of you. Thus it is also a good way to signal official packages -for organizations. +Each npm user/organization has their own scope, and only you can add packages in your scope. +This means you don't have to worry about someone taking your package name ahead of you. +Thus it is also a good way to signal official packages for organizations. -Scoped packages can be published and installed as of `npm@2` and are supported -by the primary npm registry. Unscoped packages can depend on scoped packages and -vice versa. The npm client is backwards-compatible with unscoped registries, -so it can be used to work with scoped and unscoped registries at the same time. +Scoped packages can be published and installed as of `npm@2` and are supported by the primary npm registry. +Unscoped packages can depend on scoped packages and vice versa. +The npm client is backwards-compatible with unscoped registries, so it can be used to work with scoped and unscoped registries at the same time. ### Installing scoped packages -Scoped packages are installed to a sub-folder of the regular installation -folder, e.g. if your other packages are installed in `node_modules/packagename`, -scoped modules will be installed in `node_modules/@myorg/packagename`. The scope -folder (`@myorg`) is simply the name of the scope preceded by an `@` symbol, and can -contain any number of scoped packages. +Scoped packages are installed to a sub-folder of the regular installation folder, e.g. if your other packages are installed in `node_modules/packagename`, scoped modules will be installed in `node_modules/@myorg/packagename`. +The scope folder (`@myorg`) is simply the name of the scope preceded by an `@` symbol, and can contain any number of scoped packages. A scoped package is installed by referencing it by name, preceded by an `@` symbol, in `npm install`: @@ -51,26 +45,22 @@ Or in `package.json`: } ``` -Note that if the `@` symbol is omitted, in either case, npm will instead attempt to -install from GitHub; see [`npm install`](/commands/npm-install). +Note that if the `@` symbol is omitted, in either case, npm will instead attempt to install from GitHub; see [`npm install`](/commands/npm-install). ### Requiring scoped packages -Because scoped packages are installed into a scope folder, you have to -include the name of the scope when requiring them in your code, e.g. +Because scoped packages are installed into a scope folder, you have to include the name of the scope when requiring them in your code, e.g. ```javascript require('@myorg/mypackage') ``` -There is nothing special about the way Node treats scope folders. This -simply requires the `mypackage` module in the folder named `@myorg`. +There is nothing special about the way Node treats scope folders. +This simply requires the `mypackage` module in the folder named `@myorg`. ### Publishing scoped packages -Scoped packages can be published from the CLI as of `npm@2` and can be -published to any registry that supports them, including the primary npm -registry. +Scoped packages can be published from the CLI as of `npm@2` and can be published to any registry that supports them, including the primary npm registry. (As of 2015-04-19, and with npm 2.0 or better, the primary npm registry **does** support scoped packages.) @@ -84,36 +74,27 @@ Publishing to a scope, you have two options: - Publishing to your user scope (example: `@username/module`) - Publishing to an organization scope (example: `@org/module`) -If publishing a public module to an organization scope, you must -first either create an organization with the name of the scope -that you'd like to publish to or be added to an existing organization -with the appropriate permissions. For example, if you'd like to -publish to `@org`, you would need to create the `org` organization -on npmjs.com prior to trying to publish. +If publishing a public module to an organization scope, you must first either create an organization with the name of the scope that you'd like to publish to or be added to an existing organization with the appropriate permissions. +For example, if you'd like to publish to `@org`, you would need to create the `org` organization on npmjs.com prior to trying to publish. -Scoped packages are not public by default. You will need to specify -`--access public` with the initial `npm publish` command. This will publish -the package and set access to `public` as if you had run `npm access public` -after publishing. You do not need to do this when publishing new versions of -an existing scoped package. +Scoped packages are not public by default. +You will need to specify +`--access public` with the initial `npm publish` command. +This will publish the package and set access to `public` as if you had run `npm access public` after publishing. +You do not need to do this when publishing new versions of an existing scoped package. #### Publishing private scoped packages to the npm registry -To publish a private scoped package to the npm registry, you must have -an [npm Private Modules](https://docs.npmjs.com/private-modules/intro) -account. +To publish a private scoped package to the npm registry, you must have an [npm Private Modules](https://docs.npmjs.com/private-modules/intro) account. You can then publish the module with `npm publish` or `npm publish ---access restricted`, and it will be present in the npm registry, with -restricted access. You can then change the access permissions, if -desired, with `npm access` or on the npmjs.com website. +--access restricted`, and it will be present in the npm registry, with restricted access. +You can then change the access permissions, if desired, with `npm access` or on the npmjs.com website. ### Associating a scope with a registry -Scopes can be associated with a separate registry. This allows you to -seamlessly use a mix of packages from the primary npm registry and one or more -private registries, such as [GitHub Packages](https://github.com/features/packages) or the open source [Verdaccio](https://verdaccio.org) -project. +Scopes can be associated with a separate registry. +This allows you to seamlessly use a mix of packages from the primary npm registry and one or more private registries, such as [GitHub Packages](https://github.com/features/packages) or the open source [Verdaccio](https://verdaccio.org) project. You can associate a scope with a registry at login, e.g. @@ -121,8 +102,7 @@ You can associate a scope with a registry at login, e.g. npm login --registry=http://reg.example.com --scope=@myco ``` -Scopes have a many-to-one relationship with registries: one registry can -host multiple scopes, but a scope only ever points to one registry. +Scopes have a many-to-one relationship with registries: one registry can host multiple scopes, but a scope only ever points to one registry. You can also associate a scope with a registry using `npm config`: @@ -130,8 +110,8 @@ You can also associate a scope with a registry using `npm config`: npm config set @myco:registry=http://reg.example.com ``` -Once a scope is associated with a registry, any `npm install` for a package -with that scope will request packages from that registry instead. Any +Once a scope is associated with a registry, any `npm install` for a package with that scope will request packages from that registry instead. +Any `npm publish` for a package name that contains the scope will be published to that registry instead. diff --git a/docs/lib/content/using-npm/scripts.md b/docs/lib/content/using-npm/scripts.md index 75f8929bd99fe..4db79686c2e19 100644 --- a/docs/lib/content/using-npm/scripts.md +++ b/docs/lib/content/using-npm/scripts.md @@ -1,18 +1,17 @@ --- -title: scripts +title: Scripts section: 7 description: How npm handles the "scripts" field --- ### Description -The `"scripts"` property of your `package.json` file supports a number -of built-in scripts and their preset life cycle events as well as -arbitrary scripts. These all can be executed by running -`npm run-script ` or `npm run ` for short. *Pre* and *post* -commands with matching names will be run for those as well (e.g. `premyscript`, -`myscript`, `postmyscript`). Scripts from dependencies can be run with -`npm explore -- npm run `. +The `"scripts"` property of your `package.json` file supports a number of built-in scripts and their preset life cycle events as well as arbitrary scripts. +These all can be executed by running `npm run `. +*Pre* and *post* commands with matching names will be run for those as well (e.g. +`premyscript`, +`myscript`, `postmyscript`). +Scripts from dependencies can be run with `npm explore -- npm run `. ### Pre & Post Scripts @@ -30,41 +29,40 @@ To create "pre" or "post" scripts for any scripts defined in the } ``` -In this example `npm run compress` would execute these scripts as -described. +In this example `npm run compress` would execute these scripts as described. ### Life Cycle Scripts -There are some special life cycle scripts that happen only in certain -situations. These scripts happen in addition to the `pre`, `post`, and +There are some special life cycle scripts that happen only in certain situations. +These scripts happen in addition to the `pre`, `post`, and `` scripts. * `prepare`, `prepublish`, `prepublishOnly`, `prepack`, `postpack`, `dependencies` **prepare** (since `npm@4.0.0`) -* Runs BEFORE the package is packed, i.e. during `npm publish` - and `npm pack` -* Runs on local `npm install` without any arguments -* Runs AFTER `prepublish`, but BEFORE `prepublishOnly` +* Runs BEFORE the package is packed, i.e. +during `npm publish` and `npm pack` +* Runs on local `npm install` without package arguments (runs with flags like `--production` or `--omit=dev`, but does not run when installing specific packages like `npm install express`) +* Runs AFTER `prepublishOnly` and `prepack`, but BEFORE `postpack` +* Runs for a package if it's being installed as a link through `npm install ` -* NOTE: If a package being installed through git contains a `prepare` - script, its `dependencies` and `devDependencies` will be installed, and - the prepare script will be run, before the package is packaged and - installed. +* NOTE: If a package being installed through git contains a `prepare` script, its `dependencies` and `devDependencies` will be installed, and the prepare script will be run, before the package is packaged and installed. * As of `npm@7` these scripts run in the background. To see the output, run with: `--foreground-scripts`. +* **In workspaces, prepare scripts run concurrently** across all packages. If you have interdependent packages where one must build before another, consider using `--foreground-scripts` (which can be set in `.npmrc` with `foreground-scripts=true`) to run scripts sequentially, or structure your build differently. + **prepublish** (DEPRECATED) -* Does not run during `npm publish`, but does run during `npm ci` - and `npm install`. See below for more info. +* Does not run during `npm publish`, but does run during `npm ci` and `npm install`. +See below for more info. **prepublishOnly** * Runs BEFORE the package is prepared and packed, ONLY on `npm publish`. **prepack** * Runs BEFORE a tarball is packed (on "`npm pack`", "`npm publish`", and when installing a git dependency). -* NOTE: "`npm run pack`" is NOT the same as "`npm pack`". "`npm run pack`" is an arbitrary user defined script name, where as, "`npm pack`" is a CLI defined command. +* NOTE: "`npm run pack`" is NOT the same as "`npm pack`". "`npm run pack`" is an arbitrary user defined script name, whereas, "`npm pack`" is a CLI defined command. **postpack** * Runs AFTER the tarball has been generated but before it is moved to its final destination (if at all, publish does not save the tarball locally) @@ -77,30 +75,33 @@ situations. These scripts happen in addition to the `pre`, `post`, **Deprecation Note: prepublish** -Since `npm@1.1.71`, the npm CLI has run the `prepublish` script for both `npm publish` and `npm install`, because it's a convenient way to prepare a package for use (some common use cases are described in the section below). It has also turned out to be, in practice, [very confusing](https://github.com/npm/npm/issues/10074). As of `npm@4.0.0`, a new event has been introduced, `prepare`, that preserves this existing behavior. A _new_ event, `prepublishOnly` has been added as a transitional strategy to allow users to avoid the confusing behavior of existing npm versions and only run on `npm publish` (for instance, running the tests one last time to ensure they're in good shape). +Since `npm@1.1.71`, the npm CLI has run the `prepublish` script for both `npm publish` and `npm install`, because it's a convenient way to prepare a package for use (some common use cases are described in the section below). +It has also turned out to be, in practice, [very confusing](https://github.com/npm/npm/issues/10074). +As of `npm@4.0.0`, a new event has been introduced, `prepare`, that preserves this existing behavior. +A _new_ event, `prepublishOnly` has been added as a transitional strategy to allow users to avoid the confusing behavior of existing npm versions and only run on `npm publish` (for instance, running the tests one last time to ensure they're in good shape). See for a much lengthier justification, with further reading, for this change. **Use Cases** -If you need to perform operations on your package before it is used, in a way that is not dependent on the operating system or architecture of the target system, use a `prepublish` script. This includes tasks such as: +Use a `prepare` script to perform build tasks that are platform-independent and need to run before your package is used. +This includes tasks such as: -* Compiling CoffeeScript source code into JavaScript. +* Compiling TypeScript or other source code into JavaScript. * Creating minified versions of JavaScript source code. * Fetching remote resources that your package will use. -The advantage of doing these things at `prepublish` time is that they can be done once, in a single place, thus reducing complexity and variability. Additionally, this means that: +Running these build tasks in the `prepare` script ensures they happen once, in a single place, reducing complexity and variability. +Additionally, this means that: -* You can depend on `coffee-script` as a `devDependency`, and thus - your users don't need to have it installed. -* You don't need to include minifiers in your package, reducing - the size for your users. -* You don't need to rely on your users having `curl` or `wget` or - other system tools on the target machines. +* You can depend on build tools as `devDependencies`, and thus your users don't need to have them installed. +* You don't need to include minifiers in your package, reducing the size for your users. +* You don't need to rely on your users having `curl` or `wget` or other system tools on the target machines. #### Dependencies -The `dependencies` script is run any time an `npm` command causes changes to the `node_modules` directory. It is run AFTER the changes have been applied and the `package.json` and `package-lock.json` files have been updated. +The `dependencies` script is run any time an `npm` command causes changes to the `node_modules` directory. +It is run AFTER the changes have been applied and the `package.json` and `package-lock.json` files have been updated. ### Life Cycle Operation Order @@ -110,7 +111,7 @@ The `dependencies` script is run any time an `npm` command causes changes to the #### [`npm ci`](/commands/npm-ci) -* `preinstall` +* `preinstall` (before dependencies are installed) * `install` * `postinstall` * `prepublish` @@ -118,8 +119,9 @@ The `dependencies` script is run any time an `npm` command causes changes to the * `prepare` * `postprepare` - These all run after the actual installation of modules into - `node_modules`, in order, with no internal actions happening in between +`preinstall` runs before any dependencies are fetched or unpacked into `node_modules`, so scripts can prepare the environment (for example, setting up authentication for a private registry) before tarballs are fetched. For `npm ci`, `preinstall` fires *after* the lockfile has been validated against `package.json`, so it cannot influence dependency resolution — that remains locked to `package-lock.json`. The remaining scripts run after the installation of modules into `node_modules`, in order, with no internal actions happening in between. + +Because `preinstall` runs before reify, scripts cannot rely on packages from `node_modules`. `npm ci` wipes `node_modules` before `preinstall` fires, so `require()` of a dependency will always fail. Use `install` or `postinstall` for setup that depends on installed packages. #### [`npm diff`](/commands/npm-diff) @@ -127,9 +129,9 @@ The `dependencies` script is run any time an `npm` command causes changes to the #### [`npm install`](/commands/npm-install) -These also run when you run `npm install -g ` +These run on a bare `npm install` in a local project (no package arguments). -* `preinstall` +* `preinstall` (before dependencies are installed) * `install` * `postinstall` * `prepublish` @@ -137,10 +139,11 @@ These also run when you run `npm install -g ` * `prepare` * `postprepare` -If there is a `binding.gyp` file in the root of your package and you -haven't defined your own `install` or `preinstall` scripts, npm will -default the `install` command to compile using node-gyp via `node-gyp -rebuild` +`preinstall` runs before any dependencies are fetched or unpacked into `node_modules`, so scripts can prepare the environment (for example, setting up authentication for a private registry) before resolution begins. The remaining scripts run after installation has completed. + +Because `preinstall` runs before reify, scripts cannot rely on packages from `node_modules`. On a fresh checkout, `require()` of a dependency will fail. On a repeat `npm install` against an existing `node_modules/`, it may incidentally succeed because the previously-installed tree is still on disk, but the version available is whatever was previously installed and may be removed or replaced by the upcoming install. Use `install` or `postinstall` for setup that depends on installed packages. + +If there is a `binding.gyp` file in the root of your package and you haven't defined your own `install` or `preinstall` scripts, npm will default the `install` command to compile using node-gyp via `node-gyp rebuild` These are run from the scripts of `` @@ -166,20 +169,19 @@ These are run from the scripts of `` * `postinstall` * `prepare` -`prepare` is only run if the current directory is a symlink (e.g. with -linked packages) +`prepare` is only run if the current directory is a symlink (e.g. +with linked packages) #### [`npm restart`](/commands/npm-restart) -If there is a `restart` script defined, these events are run, otherwise -`stop` and `start` are both run if present, including their `pre` and -`post` iterations) +If there is a `restart` script defined, these events are run; otherwise, +`stop` and `start` are both run if present, including their `pre` and `post` iterations) * `prerestart` * `restart` * `postrestart` -#### [`npm run `](/commands/npm-run-script) +#### [`npm run `](/commands/npm-run) * `pre` * `` @@ -191,9 +193,8 @@ If there is a `restart` script defined, these events are run, otherwise * `start` * `poststart` -If there is a `server.js` file in the root of your package, then npm -will default the `start` command to `node server.js`. `prestart` and -`poststart` will still run in this case. +If there is a `server.js` file in the root of your package, then npm will default the `start` command to `node server.js`. +`prestart` and `poststart` will still run in this case. #### [`npm stop`](/commands/npm-stop) @@ -215,34 +216,44 @@ will default the `start` command to `node server.js`. `prestart` and #### A Note on a lack of [`npm uninstall`](/commands/npm-uninstall) scripts -While npm v6 had `uninstall` lifecycle scripts, npm v7 does not. Removal of a package can happen for a wide variety of reasons, and there's no clear way to currently give the script enough context to be useful. +While npm v6 had `uninstall` lifecycle scripts, npm v7 does not. +Removal of a package can happen for a wide variety of reasons, and there's no clear way to currently give the script enough context to be useful. + Reasons for a package removal include: * a user directly uninstalled this package -* a user uninstalled a dependant package and so this dependency is being uninstalled -* a user uninstalled a dependant package but another package also depends on this version +* a user uninstalled a dependent package and so this dependency is being uninstalled +* a user uninstalled a dependent package but another package also depends on this version * this version has been merged as a duplicate with another version * etc. Due to the lack of necessary context, `uninstall` lifecycle scripts are not implemented and will not function. -### User +### Working Directory for Scripts + +Scripts are always run from the root of the package folder, regardless of what the current working directory is when `npm` is invoked. +This means your scripts can reliably assume they are running in the package root. + +If you want your script to behave differently based on the directory you were in when you ran `npm`, you can use the `INIT_CWD` environment variable, which holds the full path you were in when you ran `npm run`. + +#### Historical Behavior in Older npm Versions -When npm is run as root, scripts are always run with the effective uid -and gid of the working directory owner. +For npm v6 and earlier, scripts were generally run from the root of the package, but there were rare cases and bugs in older versions where this was not guaranteed. +If your package must support very old npm versions, you may wish to add a safeguard in your scripts (for example, by checking process.cwd()). + +For more details, see: +- [npm v7 release notes](https://github.com/npm/cli/releases/tag/v7.0.0) +- [Discussion about script working directory reliability in npm v6 and earlier](https://github.com/npm/npm/issues/12356) ### Environment -Package scripts run in an environment where many pieces of information -are made available regarding the setup of npm and the current state of -the process. +Package scripts run in an environment where many pieces of information are made available regarding the setup of npm and the current state of the process. #### path -If you depend on modules that define executable scripts, like test -suites, then those executables will be added to the `PATH` for -executing the scripts. So, if your package.json has this: +If you depend on modules that define executable scripts, like test suites, then those executables will be added to the `PATH` for executing the scripts. +So, if your package.json has this: ```json { @@ -256,31 +267,48 @@ executing the scripts. So, if your package.json has this: } ``` -then you could run `npm start` to execute the `bar` script, which is -exported into the `node_modules/.bin` directory on `npm install`. +then you could run `npm start` to execute the `bar` script, which is exported into the `node_modules/.bin` directory on `npm install`. #### package.json vars -The package.json fields are tacked onto the `npm_package_` prefix. So, -for instance, if you had `{"name":"foo", "version":"1.2.5"}` in your -package.json file, then your package scripts would have the -`npm_package_name` environment variable set to "foo", and the -`npm_package_version` set to "1.2.5". You can access these variables -in your code with `process.env.npm_package_name` and -`process.env.npm_package_version`, and so on for other fields. +npm sets the following environment variables from the package.json: + +* `npm_package_name` - The package name +* `npm_package_version` - The package version +* `npm_package_bin_*` - Each executable defined in the bin field +* `npm_package_engines_*` - Each engine defined in the engines field +* `npm_package_config_*` - Each config value defined in the config field +* `npm_package_json` - The full path to the package.json file + +Additionally, for install scripts (`preinstall`, `install`, `postinstall`), npm sets these environment variables: + +* `npm_package_resolved` - The resolved URL for the package +* `npm_package_integrity` - The integrity hash for the package +* `npm_package_optional` - Set to `"true"` if the package is optional +* `npm_package_dev` - Set to `"true"` if the package is a dev dependency +* `npm_package_peer` - Set to `"true"` if the package is a peer dependency +* `npm_package_dev_optional` - Set to `"true"` if the package is both dev and optional + +For example, if you had `{"name":"foo", "version":"1.2.5"}` in your package.json file, then your package scripts would have the `npm_package_name` environment variable set to "foo", and the `npm_package_version` set to "1.2.5". You can access these variables in your code with `process.env.npm_package_name` and `process.env.npm_package_version`. + +**Note:** In npm 7 and later, most package.json fields are no longer provided as environment variables. Scripts that need access to other package.json fields should read the package.json file directly. The `npm_package_json` environment variable provides the path to the file for this purpose. See [`package.json`](/configuring-npm/package-json) for more on package configs. +#### versioning variables + +For versioning scripts (`preversion`, `version`, `postversion`), npm sets these environment variables: + +* `npm_old_version` - The version before being bumped +* `npm_new_version` – The version after being bumped + #### current lifecycle event -Lastly, the `npm_lifecycle_event` environment variable is set to -whichever stage of the cycle is being executed. So, you could have a -single script used for different parts of the process which switches -based on what's currently happening. +Lastly, the `npm_lifecycle_event` environment variable is set to whichever stage of the cycle is being executed. +So, you could have a single script used for different parts of the process which switches based on what's currently happening. Objects are flattened following this format, so if you had -`{"scripts":{"install":"foo.js"}}` in your package.json, then you'd -see this in the script: +`{"scripts":{"install":"foo.js"}}` in your package.json, then you'd see this in the script: ```bash process.env.npm_package_scripts_install === "foo.js" @@ -293,71 +321,58 @@ For example, if your package.json contains this: ```json { "scripts" : { - "install" : "scripts/install.js", - "postinstall" : "scripts/install.js" + "prepare" : "scripts/build.js", + "test" : "scripts/test.js" } } ``` -then `scripts/install.js` will be called for the install and post-install -stages of the lifecycle. Since `scripts/install.js` is running for two -different phases, it would be wise in this case to look at the -`npm_lifecycle_event` environment variable. +then `scripts/build.js` will be called for the prepare stage of the lifecycle, and you can check the +`npm_lifecycle_event` environment variable if your script needs to behave differently in different contexts. -If you want to run a make command, you can do so. This works just -fine: +If you want to run build commands, you can do so. +This works just fine: ```json { "scripts" : { - "preinstall" : "./configure", - "install" : "make && make install", - "test" : "make test" + "prepare" : "npm run build", + "build" : "tsc", + "test" : "jest" } } ``` ### Exiting -Scripts are run by passing the line as a script argument to `sh`. +Scripts are run by passing the line as a script argument to `/bin/sh` on POSIX systems or `cmd.exe` on Windows. +You can control which shell is used by setting the [`script-shell`](/using-npm/config#script-shell) configuration option. -If the script exits with a code other than 0, then this will abort the -process. +If the script exits with a code other than 0, then this will abort the process. -Note that these script files don't have to be Node.js or even -JavaScript programs. They just have to be some kind of executable -file. +Note that these script files don't have to be Node.js or even JavaScript programs. +They just have to be some kind of executable file. ### Best Practices * Don't exit with a non-zero error code unless you *really* mean it. - If the failure is minor or only will prevent some optional features, then - it's better to just print a warning and exit successfully. -* Try not to use scripts to do what npm can do for you. Read through - [`package.json`](/configuring-npm/package-json) to see all the things that you can specify and enable - by simply describing your package appropriately. In general, this - will lead to a more robust and consistent state. -* Inspect the env to determine where to put things. For instance, if - the `npm_config_binroot` environment variable is set to `/home/user/bin`, then - don't try to install executables into `/usr/local/bin`. The user - probably set it up that way for a reason. -* Don't prefix your script commands with "sudo". If root permissions - are required for some reason, then it'll fail with that error, and - the user will sudo the npm command in question. -* Don't use `install`. Use a `.gyp` file for compilation, and `prepare` - for anything else. You should almost never have to explicitly set a - preinstall or install script. If you are doing this, please consider if - there is another option. The only valid use of `install` or `preinstall` - scripts is for compilation which must be done on the target architecture. -* Scripts are run from the root of the package folder, regardless of what the - current working directory is when `npm` is invoked. If you want your - script to use different behavior based on what subdirectory you're in, you - can use the `INIT_CWD` environment variable, which holds the full path you - were in when you ran `npm run`. + If the failure is minor or only will prevent some optional features, then it's better to just print a warning and exit successfully. +* Try not to use scripts to do what npm can do for you. +Read through [`package.json`](/configuring-npm/package-json) to see all the things that you can specify and enable by simply describing your package appropriately. +In general, this will lead to a more robust and consistent state. +* Inspect the env to determine where to put things. +For instance, if the `NPM_CONFIG_BINROOT` environment variable is set to `/home/user/bin`, then don't try to install executables into `/usr/local/bin`. +The user probably set it up that way for a reason. +* Don't prefix your script commands with "sudo". If root permissions are required for some reason, then it'll fail with that error, and the user will sudo the npm command in question. +* Don't use `install`. +Use a `.gyp` file for compilation, and `prepare` for anything else. +You should almost never have to explicitly set a preinstall or install script. +If you are doing this, please consider if there is another option. +The only valid use of `install` or `preinstall` scripts is for compilation which must be done on the target architecture. ### See Also -* [npm run-script](/commands/npm-run-script) +* [npm run](/commands/npm-run) * [package.json](/configuring-npm/package-json) * [npm developers](/using-npm/developers) * [npm install](/commands/npm-install) diff --git a/docs/lib/content/using-npm/workspaces.md b/docs/lib/content/using-npm/workspaces.md index cb545c0b46bf1..09d569748cd23 100644 --- a/docs/lib/content/using-npm/workspaces.md +++ b/docs/lib/content/using-npm/workspaces.md @@ -1,30 +1,22 @@ --- -title: workspaces +title: Workspaces section: 7 description: Working with workspaces --- ### Description -**Workspaces** is a generic term that refers to the set of features in the -npm cli that provides support for managing multiple packages from your local -file system from within a singular top-level, root package. +**Workspaces** is a generic term that refers to the set of features in the npm cli that provides support for managing multiple packages from your local file system from within a singular top-level, root package. -This set of features makes up for a much more streamlined workflow handling -linked packages from the local file system. It automates the linking process -as part of `npm install` and removes the need to manually use `npm link` in -order to add references to packages that should be symlinked into the current -`node_modules` folder. +This set of features makes up for a much more streamlined workflow handling linked packages from the local file system. +It automates the linking process as part of `npm install` and removes the need to manually use `npm link` in order to add references to packages that should be symlinked into the current `node_modules` folder. -We also refer to these packages being auto-symlinked during `npm install` as a -single **workspace**, meaning it's a nested package within the current local -file system that is explicitly defined in the [`package.json`](/configuring-npm/package-json#workspaces) +We also refer to these packages being auto-symlinked during `npm install` as a single **workspace**, meaning it's a nested package within the current local file system that is explicitly defined in the [`package.json`](/configuring-npm/package-json#workspaces) `workspaces` configuration. ### Defining workspaces -Workspaces are usually defined via the `workspaces` property of the -[`package.json`](/configuring-npm/package-json#workspaces) file, e.g: +Workspaces are usually defined via the `workspaces` property of the [`package.json`](/configuring-npm/package-json#workspaces) file, e.g: ```json { @@ -35,9 +27,7 @@ Workspaces are usually defined via the `workspaces` property of the } ``` -Given the above `package.json` example living at a current working -directory `.` that contains a folder named `packages/a` that itself contains -a `package.json` inside it, defining a Node.js package, e.g: +Given the above `package.json` example living at a current working directory `.` that contains a folder named `packages/a` that itself contains a `package.json` inside it, defining a Node.js package, e.g: ``` . @@ -47,12 +37,9 @@ a `package.json` inside it, defining a Node.js package, e.g: | `-- package.json ``` -The expected result once running `npm install` in this current working -directory `.` is that the folder `packages/a` will get symlinked to the -`node_modules` folder of the current working dir. +The expected result once running `npm install` in this current working directory `.` is that the folder `packages/a` will get symlinked to the `node_modules` folder of the current working dir. -Below is a post `npm install` example, given that same previous example -structure of files and folders: +Below is a post `npm install` example, given that same previous example structure of files and folders: ``` . @@ -67,22 +54,19 @@ structure of files and folders: ### Getting started with workspaces -You may automate the required steps to define a new workspace using -[npm init](/commands/npm-init). For example in a project that already has a -`package.json` defined you can run: +You may automate the required steps to define a new workspace using [npm init](/commands/npm-init). +For example in a project that already has a `package.json` defined you can run: ``` npm init -w ./packages/a ``` -This command will create the missing folders and a new `package.json` -file (if needed) while also making sure to properly configure the +This command will create the missing folders and a new `package.json` file (if needed) while also making sure to properly configure the `"workspaces"` property of your root project `package.json`. ### Adding dependencies to a workspace -It's possible to directly add/remove/update dependencies of your workspaces -using the [`workspace` config](/using-npm/config#workspace). +It's possible to directly add/remove/update dependencies of your workspaces using the [`workspace` config](/using-npm/config#workspace). For example, assuming the following structure: @@ -96,24 +80,39 @@ For example, assuming the following structure: `-- package.json ``` -If you want to add a dependency named `abbrev` from the registry as a -dependency of your workspace **a**, you may use the workspace config to tell -the npm installer that package should be added as a dependency of the provided -workspace: +If you want to add a dependency named `abbrev` from the registry as a dependency of your workspace **a**, you may use the workspace config to tell the npm installer that package should be added as a dependency of the provided workspace: ``` npm install abbrev -w a ``` -Note: other installing commands such as `uninstall`, `ci`, etc will also -respect the provided `workspace` configuration. +**Adding a workspace as a dependency of another workspace:** + +The same approach works when adding one workspace as a dependency of another. +If you want to add workspace **b** as a dependency of workspace **a**, run: + +``` +npm install b -w a +``` + +npm will detect that **b** is a workspace and automatically symlink it rather +than fetching it from the registry. The resulting entry in workspace **a**'s +`package.json` will use a standard version range: + +```json +{ + "dependencies": { + "b": "^1.0.0" + } +} +``` + +Note: other installing commands such as `uninstall`, `ci`, etc will also respect the provided `workspace` configuration. ### Using workspaces -Given the [specifics of how Node.js handles module resolution](https://nodejs.org/dist/latest-v14.x/docs/api/modules.html#modules_all_together) it's possible to consume any defined workspace -by its declared `package.json` `name`. Continuing from the example defined -above, let's also create a Node.js script that will require the workspace `a` -example module, e.g: +Given the [specifics of how Node.js handles module resolution](https://nodejs.org/dist/latest-v14.x/docs/api/modules.html#modules_all_together) it's possible to consume any defined workspace by its declared `package.json` `name`. +Continuing from the example defined above, let's also create a Node.js script that will require the workspace `a` example module, e.g: ``` // ./packages/a/index.js @@ -129,19 +128,15 @@ When running it with: `node lib/index.js` This demonstrates how the nature of `node_modules` resolution allows for -**workspaces** to enable a portable workflow for requiring each **workspace** -in such a way that is also easy to [publish](/commands/npm-publish) these -nested workspaces to be consumed elsewhere. +**workspaces** to enable a portable workflow for requiring each **workspace** in such a way that is also easy to [publish](/commands/npm-publish) these nested workspaces to be consumed elsewhere. ### Running commands in the context of workspaces -You can use the `workspace` configuration option to run commands in the context -of a configured workspace. -Additionally, if your current directory is in a workspace, the `workspace` -configuration is implicitly set, and `prefix` is set to the root workspace. +You can use the `workspace` configuration option to run commands in the context of a configured workspace. +Additionally, if your current directory is in a workspace, the `workspace` configuration is implicitly set, and `prefix` is set to the root workspace. -Following is a quick example on how to use the `npm run` command in the context -of nested workspaces. For a project containing multiple workspaces, e.g: +Following is a quick example on how to use the `npm run` command in the context of nested workspaces. +For a project containing multiple workspaces, e.g: ``` . @@ -153,8 +148,8 @@ of nested workspaces. For a project containing multiple workspaces, e.g: `-- package.json ``` -By running a command using the `workspace` option, it's possible to run the -given command in the context of that specific workspace. e.g: +By running a command using the `workspace` option, it's possible to run the given command in the context of that specific workspace. +e.g: ``` npm run test --workspace=a @@ -169,8 +164,7 @@ cd packages/a && npm run test Either will run the `test` script defined within the `./packages/a/package.json` file. -Please note that you can also specify this argument multiple times in the -command-line in order to target multiple workspaces, e.g: +Please note that you can also specify this argument multiple times in the command-line in order to target multiple workspaces, e.g: ``` npm run test --workspace=a --workspace=b @@ -181,9 +175,8 @@ Or run the command for each workspace within the 'packages' folder: npm run test --workspace=packages ``` -It's also possible to use the `workspaces` (plural) configuration option to -enable the same behavior but running that command in the context of **all** -configured workspaces. e.g: +It's also possible to use the `workspaces` (plural) configuration option to enable the same behavior but running that command in the context of **all** configured workspaces. +e.g: ``` npm run test --workspaces @@ -221,6 +214,6 @@ npm run test --workspaces --if-present * [npm install](/commands/npm-install) * [npm publish](/commands/npm-publish) -* [npm run-script](/commands/npm-run-script) +* [npm run](/commands/npm-run) * [config](/using-npm/config) diff --git a/docs/lib/index.js b/docs/lib/index.js index b88d20cca3558..9779d54657293 100644 --- a/docs/lib/index.js +++ b/docs/lib/index.js @@ -22,7 +22,38 @@ const assertPlaceholder = (src, path, placeholder) => { return placeholder } -const getCommandByDoc = (docFile, docExt) => { +// Default command loader - loads commands from lib/commands +const defaultCommandLoader = (name) => { + return require(`../../lib/commands/${name}`) +} + +// Load a command using the provided loader or default +const getCommand = (name, commandLoader = defaultCommandLoader) => { + return commandLoader(name) +} + +// Resolve definitions for a command - use definitions if present, otherwise build from params +const resolveDefinitions = (command) => { + // If command has definitions, use them directly (ignore params) + if (command.definitions && Object.keys(command.definitions).length > 0) { + return command.definitions + } + + // Otherwise build from params using global definitions + if (command.params) { + const resolved = {} + for (const param of command.params) { + if (definitions[param]) { + resolved[param] = definitions[param] + } + } + return resolved + } + + return {} +} + +const getCommandByDoc = (docFile, docExt, commandLoader = defaultCommandLoader) => { // Grab the command name from the *.md filename // NOTE: We cannot use the name property command file because in the case of // `npx` the file being used is `lib/commands/exec.js` @@ -31,24 +62,29 @@ const getCommandByDoc = (docFile, docExt) => { if (name === 'npm') { return { name, - params: null, + definitions: [], usage: 'npm', } } // special case for `npx`: // `npx` is not technically a command in and of itself, - // so it just needs the usage of npm exex + // so it just needs the usage of npm exec const srcName = name === 'npx' ? 'exec' : name - const { params, usage = [''], workspaces } = require(`../../lib/commands/${srcName}`) + const command = getCommand(srcName, commandLoader) + const { usage = [''], workspaces } = command const usagePrefix = name === 'npx' ? 'npx' : `npm ${name}` - if (params) { - for (const param of params) { - if (definitions[param].exclusive) { - for (const e of definitions[param].exclusive) { - if (!params.includes(e)) { - params.splice(params.indexOf(param) + 1, 0, e) - } + + // Resolve definitions - handles exclusive params expansion + const commandDefs = resolveDefinitions(command) + const resolvedDefs = {} + for (const [key, def] of Object.entries(commandDefs)) { + resolvedDefs[key] = def + // Handle exclusive params + if (def.exclusive) { + for (const e of def.exclusive) { + if (!resolvedDefs[e] && definitions[e]) { + resolvedDefs[e] = definitions[e] } } } @@ -57,52 +93,139 @@ const getCommandByDoc = (docFile, docExt) => { return { name, workspaces, - params: name === 'npx' ? null : params, - usage: usage.map(u => `${usagePrefix} ${u}`.trim()).join('\n'), + definitions: name === 'npx' ? {} : resolvedDefs, + usage: usage?.map(u => `${usagePrefix} ${u}`.trim()).join('\n'), } } const replaceVersion = (src) => src.replace(/@VERSION@/g, version) -const replaceUsage = (src, { path }) => { +const replaceUsage = (src, { path, commandLoader }) => { const replacer = assertPlaceholder(src, path, TAGS.USAGE) - const { usage, name, workspaces } = getCommandByDoc(path, DOC_EXT) + const { usage, name, workspaces } = getCommandByDoc(path, DOC_EXT, commandLoader) + + const synopsis = [] - const synopsis = ['```bash', usage] + if (usage) { + synopsis.push('```bash', usage) + + const cmdAliases = Object.keys(aliases).reduce((p, c) => { + if (aliases[c] === name) { + p.push(c) + } + return p + }, []) - const cmdAliases = Object.keys(aliases).reduce((p, c) => { - if (aliases[c] === name) { - p.push(c) + if (cmdAliases.length === 1) { + synopsis.push('', `alias: ${cmdAliases[0]}`) + } else if (cmdAliases.length > 1) { + synopsis.push('', `aliases: ${cmdAliases.join(', ')}`) } - return p - }, []) - if (cmdAliases.length === 1) { - synopsis.push('', `alias: ${cmdAliases[0]}`) - } else if (cmdAliases.length > 1) { - synopsis.push('', `aliases: ${cmdAliases.join(', ')}`) + synopsis.push('```') } - synopsis.push('```') - if (!workspaces) { - synopsis.push('', 'Note: This command is unaware of workspaces.') + if (synopsis.length) { + synopsis.push('') + } + synopsis.push('Note: This command is unaware of workspaces.') } return src.replace(replacer, synopsis.join('\n')) } -const replaceParams = (src, { path }) => { - const { params } = getCommandByDoc(path, DOC_EXT) - const replacer = params && assertPlaceholder(src, path, TAGS.CONFIG) +// Helper to generate a markdown table from definitions +const generateFlagsTable = (definitionPool) => { + const rows = Object.keys(definitionPool).map((n) => { + const def = definitionPool[n] + const flags = [`\`--${def.key}\``] + if (def.alias) { + flags.push(...def.alias.map(a => `\`--${a}\``)) + } + if (def.short) { + flags.push(`\`-${def.short}\``) + } + const flagsStr = flags.join(', ') + let defaultVal = def.defaultDescription + if (!defaultVal) { + defaultVal = String(def.default) + } + defaultVal = defaultVal.replace(/\n/g, ' ').trim() + let typeVal = def.typeDescription || String(def.type) + if (def.required) { + typeVal = `${typeVal} (required)` + } + typeVal = typeVal.replace(/\n/g, ' ').trim() + const desc = (def.description || '').replace(/\n/g, ' ').trim() + return `| ${flagsStr} | ${defaultVal} | ${typeVal} | ${desc} |` + }) + + return [ + '| Flag | Default | Type | Description |', + '| --- | --- | --- | --- |', + ...rows, + ].join('\n') +} + +const replaceDefinitions = (src, { path, commandLoader }) => { + const { definitions: commandDefs, name } = getCommandByDoc(path, DOC_EXT, commandLoader) + + let subcommands = {} + try { + const command = getCommand(name, commandLoader) + subcommands = command.subcommands || {} + } catch { + // Command doesn't exist + } - if (!params) { + // If no definitions and no subcommands, nothing to replace + if (Object.keys(commandDefs).length === 0 && Object.keys(subcommands).length === 0) { return src } - const paramsConfig = params.map((n) => definitions[n].describe()) + // Assert placeholder is present + const replacer = assertPlaceholder(src, path, TAGS.CONFIG) + + // If command has subcommands, generate sections for each subcommand + if (Object.keys(subcommands).length > 0) { + const subcommandSections = Object.entries(subcommands).map(([subName, SubCommand]) => { + const subUsage = SubCommand.usage || [] + const subDefs = resolveDefinitions(SubCommand) + + const parts = [`### \`npm ${name} ${subName}\``, ''] + + if (SubCommand.description) { + parts.push(SubCommand.description, '') + } + + // Add usage/synopsis + if (subUsage.length > 0) { + parts.push('#### Synopsis', '', '```bash') + subUsage.forEach(u => { + parts.push(`npm ${name} ${subName} ${u}`.trim()) + }) + parts.push('```', '') + } + + // Add flags section if definitions exist + if (Object.keys(subDefs).length > 0) { + parts.push('#### Flags', '') + parts.push(generateFlagsTable(subDefs), '') + } + + return parts.join('\n') + }) + + return src.replace(replacer, subcommandSections.join('\n')) + } + + // For commands without subcommands - commandDefs must be non-empty here + // (we would have returned early at line 175 if both were empty) + const paramDescriptions = Object.values(commandDefs) + .map(def => def.describe()) - return src.replace(replacer, paramsConfig.join('\n\n')) + return src.replace(replacer, paramDescriptions.join('\n\n')) } const replaceConfig = (src, { path }) => { @@ -177,7 +300,7 @@ module.exports = { md: resolve(__dirname, '..', 'content'), }, usage: replaceUsage, - params: replaceParams, + definitions: replaceDefinitions, config: replaceConfig, shorthands: replaceShorthands, version: replaceVersion, diff --git a/docs/lib/template.html b/docs/lib/template.html index 622dc327046ee..7736e8f82a115 100644 --- a/docs/lib/template.html +++ b/docs/lib/template.html @@ -125,6 +125,51 @@ margin: 3em 0 4em 0; padding-top: 2em; } + +table { + width: 100%; + margin: 1em 0; + border-radius: 6px; + border: 1px solid #e1e4e8; + overflow: hidden; + border-collapse: separate; + border-spacing: 0; +} + +table thead { + background-color: #f6f8fa; +} + +table tbody { + background-color: #ffffff; +} + +table th, +table td { + padding: 0.75em; + text-align: left; + border-right: 1px solid #e1e4e8; + border-bottom: 1px solid #e1e4e8; +} + +table th:last-child, +table td:last-child { + border-right: none; +} + +table tbody tr:last-child td { + border-bottom: none; +} + +table th { + font-weight: 600; + background-color: #f6f8fa; +} + +table code { + white-space: nowrap; +} + diff --git a/docs/package.json b/docs/package.json index d3f0ecbd26e92..575537c3ce4ab 100644 --- a/docs/package.json +++ b/docs/package.json @@ -5,14 +5,15 @@ "private": true, "main": "lib/index.js", "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", "test": "tap", "posttest": "npm run lint", - "build": "node bin/build.js" + "build": "node bin/build.js", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", @@ -21,19 +22,19 @@ }, "devDependencies": { "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "front-matter": "^4.0.2", - "ignore-walk": "^6.0.5", - "jsdom": "^24.0.0", - "rehype-stringify": "^9.0.3", - "remark-gfm": "^3.0.1", - "remark-man": "^8.0.1", - "remark-parse": "^10.0.1", - "remark-rehype": "^10.1.0", + "ignore-walk": "^8.0.0", + "jsdom": "27.0.0", + "rehype-stringify": "^10.0.1", + "remark-gfm": "^4.0.1", + "remark-man": "^9.0.0", + "remark-parse": "^11.0.0", + "remark-rehype": "^11.1.2", "semver": "^7.3.8", "tap": "^16.3.8", - "unified": "^10.1.2", + "unified": "^11.0.5", "yaml": "^2.2.1" }, "author": "GitHub Inc.", @@ -43,7 +44,7 @@ "lib/" ], "engines": { - "node": "^18.17.0 || >=20.5.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "tap": { "timeout": 600, @@ -55,7 +56,7 @@ "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "ciVersions": "latest", - "version": "4.22.0", + "version": "5.1.1", "content": "../scripts/template-oss/index.js", "workspaceRepo": { "add": { diff --git a/docs/test/index.js b/docs/test/index.js index 8452428212519..5a2a2c2b7d611 100644 --- a/docs/test/index.js +++ b/docs/test/index.js @@ -1,9 +1,31 @@ const t = require('tap') const { join } = require('path') const walk = require('ignore-walk') -const { paths: { content: CONTENT_DIR, nav: NAV, template: TEMPLATE } } = require('../lib/index.js') +const fs = require('fs/promises') +const yaml = require('yaml') +const { + paths: { content: CONTENT_DIR, nav: NAV, template: TEMPLATE }, +} = require('../lib/index.js') -const testBuildDocs = async (t, { verify, ...opts } = {}) => { +// Helper to generate nav entries from content structure +const generateNavFromContent = (content, prefix = '') => { + const entries = [] + for (const [key, value] of Object.entries(content)) { + if (key.endsWith('.md')) { + const name = key.replace('.md', '') + const url = prefix ? `${prefix}/${name}` : `/${name}` + entries.push({ url }) + } else if (typeof value === 'object') { + const children = generateNavFromContent(value, `/${key}`) + if (children.length > 0) { + entries.push(...children) + } + } + } + return entries +} + +const testBuildDocs = async (t, { verify, commandLoader, ...opts } = {}) => { const mockedBuild = require('../lib/build.js') const fixtures = { @@ -13,6 +35,17 @@ const testBuildDocs = async (t, { verify, ...opts } = {}) => { ...opts, } + // Ensure commands directory exists if content is provided + if (fixtures.content && !fixtures.content.commands) { + fixtures.content.commands = {} + } + + // If custom content is provided but not custom nav, auto-generate nav from content + if (fixtures.content && !fixtures.nav) { + const navEntries = generateNavFromContent(fixtures.content) + fixtures.nav = yaml.stringify(navEntries) + } + const root = t.testdir(fixtures) const paths = { @@ -22,6 +55,12 @@ const testBuildDocs = async (t, { verify, ...opts } = {}) => { man: join(root, 'man'), html: join(root, 'html'), md: join(root, 'md'), + // Skip auto-generation of missing docs when using test fixtures + skipAutoGenerate: !!fixtures.content, + // Skip nav generation when using test fixtures with custom content + skipGenerateNav: !!fixtures.content, + // Custom command loader for testing + commandLoader, } return { @@ -31,6 +70,83 @@ const testBuildDocs = async (t, { verify, ...opts } = {}) => { } } +// Helper to create a standard command doc with placeholders +const createCommandDoc = (title, description) => `--- +title: ${title} +section: 1 +description: ${description} +--- + +### Synopsis + + + +### Configuration + + +` + +// Helper to read and return HTML content from a built doc +const readHtmlDoc = async (htmlPath, commandName) => { + const htmlFile = join(htmlPath, `commands/${commandName}.html`) + return await fs.readFile(htmlFile, 'utf-8') +} + +// Helper to test a command doc with common assertions +const testCommandDoc = async (t, commandName, description, assertions = {}) => { + const doc = createCommandDoc(commandName, description) + const { html } = await testBuildDocs(t, { + content: { + commands: { [`${commandName}.md`]: doc }, + }, + nav: `- url: /commands/${commandName}`, + }) + + const htmlContent = await readHtmlDoc(html, commandName) + + // Default assertions + t.ok(htmlContent.length > 0, `generates HTML for ${commandName} command`) + + // Custom assertions + if (assertions.match) { + for (const pattern of assertions.match) { + t.match(htmlContent, pattern, `contains expected pattern: ${pattern}`) + } + } + + return { html, htmlContent } +} + +// Helper to create test directory structure for autoGenerateMissingDocs tests +const createAutoGenTestDir = (t, { existingDocs = {}, navEntries = [], commandFiles = {} }) => { + const navYml = ` +- title: CLI Commands + children: + - title: npm + url: /commands/npm +${navEntries.map(entry => ` - title: ${entry.title}\n url: ${entry.url}\n description: ${entry.description}`).join('\n')} +` + + return t.testdir({ + content: { + commands: existingDocs, + }, + 'nav.yml': navYml, + lib: { + commands: commandFiles, + }, + }) +} + +// Helper to verify nav structure after auto-generation +const verifyNavStructure = async (navPath) => { + const navContent = await fs.readFile(navPath, 'utf-8') + const navData = yaml.parse(navContent) + const commandsSection = navData.find(s => s.title === 'CLI Commands') + + return { navContent, navData, commandsSection } +} + t.test('builds and verifies the real docs', async (t) => { const { man, html, md, results } = await testBuildDocs(t, { verify: true }) @@ -83,7 +199,7 @@ t.test('html', async t => { // but we test for coverage t.test('files can link to root pages', async t => { await testBuildDocs(t, { - content: { 'test.md': '[link](/test)' }, + content: { 'test.md': '[Test](/test)' }, nav: '- url: /test', }) }) @@ -109,3 +225,1272 @@ t.test('html', async t => { }) }) }) + +t.test('command-specific definitions and exclusive parameters', async t => { + // Test through the actual doc building process with real commands + t.test('config command uses params correctly', async t => { + await testCommandDoc(t, 'npm-config', 'Manage the npm configuration files') + }) + + t.test('install command includes exclusive save parameters', async t => { + const { htmlContent } = await testCommandDoc(t, 'npm-install', 'Install a package', { + match: [/save/], + }) + + // The install command should have save-related params due to exclusive expansion + t.match(htmlContent, /save/, 'includes save-related configuration') + }) +}) + +t.test('autoGenerateMissingDocs', async t => { + const { autoGenerateMissingDocs } = require('../lib/build.js') + + t.test('generates docs for missing commands', async t => { + const testDir = createAutoGenTestDir(t, { + existingDocs: { + 'npm-access.md': createCommandDoc('npm-access', 'Set access level on published packages'), + }, + navEntries: [ + { title: 'npm access', url: '/commands/npm-access', description: 'Set access level on published packages' }, + ], + commandFiles: { + 'access.js': ` +class AccessCommand { + static description = 'Set access level on published packages' +} +module.exports = AccessCommand +`, + 'testcmd.js': ` +class TestCommand { + static description = 'A test command' +} +module.exports = TestCommand +`, + }, + }) + + const contentPath = join(testDir, 'content') + const navPath = join(testDir, 'nav.yml') + const commandsPath = join(testDir, 'lib', 'commands') + + await autoGenerateMissingDocs(contentPath, navPath, commandsPath) + + // Verify the doc was created + const testcmdDocPath = join(contentPath, 'commands', 'npm-testcmd.md') + const docExists = await fs.access(testcmdDocPath).then(() => true).catch(() => false) + t.ok(docExists, 'creates documentation file for missing command') + + // Verify the doc has correct content + const docContent = await fs.readFile(testcmdDocPath, 'utf-8') + t.match(docContent, /title: npm-testcmd/, 'doc has correct title') + t.match(docContent, /description: A test command/, 'doc has correct description') + t.match(docContent, //, 'doc has usage placeholder') + t.match(docContent, //, 'doc has config placeholder') + t.match(docContent, /A test command/, 'doc has description in body') + }) + + t.test('updates nav.yml for new commands', async t => { + const testDir = createAutoGenTestDir(t, { + existingDocs: { + 'npm-existing.md': `--- +title: npm-existing +section: 1 +description: Existing command +---`, + }, + navEntries: [ + { title: 'npm existing', url: '/commands/npm-existing', description: 'Existing command' }, + ], + commandFiles: { + 'existing.js': ` +class ExistingCommand { + static description = 'Existing command' +} +module.exports = ExistingCommand +`, + 'newcmd.js': ` +class NewCommand { + static description = 'New command' +} +module.exports = NewCommand +`, + }, + }) + + const contentPath = join(testDir, 'content') + const navPath = join(testDir, 'nav.yml') + const commandsPath = join(testDir, 'lib', 'commands') + + await autoGenerateMissingDocs(contentPath, navPath, commandsPath) + + // Read and verify nav.yml was updated + const { commandsSection } = await verifyNavStructure(navPath) + + t.ok(commandsSection, 'nav has CLI Commands section') + const newCmdEntry = commandsSection.children.find(c => c.url === '/commands/npm-newcmd') + t.ok(newCmdEntry, 'nav has entry for new command') + t.equal(newCmdEntry.title, 'npm newcmd', 'nav entry has correct title') + t.equal(newCmdEntry.description, 'New command', 'nav entry has correct description') + }) + + t.test('sorts nav children alphabetically', async t => { + const testDir = createAutoGenTestDir(t, { + existingDocs: {}, + navEntries: [ + { title: 'npm zebra', url: '/commands/npm-zebra', description: 'Zebra command' }, + { title: 'npm alpha', url: '/commands/npm-alpha', description: 'Alpha command' }, + ], + commandFiles: { + 'zebra.js': `module.exports = { description: 'Zebra command' }`, + 'alpha.js': `module.exports = { description: 'Alpha command' }`, + 'beta.js': `module.exports = { description: 'Beta command' }`, + }, + }) + + const contentPath = join(testDir, 'content') + const navPath = join(testDir, 'nav.yml') + const commandsPath = join(testDir, 'lib', 'commands') + + await autoGenerateMissingDocs(contentPath, navPath, commandsPath) + + // Verify sorting + const { commandsSection } = await verifyNavStructure(navPath) + + const titles = commandsSection.children.map(c => c.title) + + // npm should be first + t.equal(titles[0], 'npm', 'npm command is first') + + // Rest should be alphabetically sorted + const rest = titles.slice(1) + const sorted = [...rest].sort() + t.same(rest, sorted, 'remaining commands are alphabetically sorted') + t.ok(titles.includes('npm alpha'), 'includes alpha') + t.ok(titles.includes('npm beta'), 'includes beta') + t.ok(titles.includes('npm zebra'), 'includes zebra') + }) + + t.test('handles commands without description', async t => { + const testDir = createAutoGenTestDir(t, { + existingDocs: {}, + navEntries: [], + commandFiles: { + 'nodesc.js': `module.exports = {}`, + }, + }) + + const contentPath = join(testDir, 'content') + const navPath = join(testDir, 'nav.yml') + const commandsPath = join(testDir, 'lib', 'commands') + + await autoGenerateMissingDocs(contentPath, navPath, commandsPath) + + // Verify fallback description + const docPath = join(contentPath, 'commands', 'npm-nodesc.md') + const docContent = await fs.readFile(docPath, 'utf-8') + t.match(docContent, /description: The nodesc command/, 'uses fallback description in frontmatter') + t.match(docContent, /The nodesc command/, 'uses fallback description in body') + }) + + t.test('does not add duplicate entries to nav', async t => { + const testDir = createAutoGenTestDir(t, { + existingDocs: {}, + navEntries: [ + { title: 'npm duplicate', url: '/commands/npm-duplicate', description: 'Already exists' }, + ], + commandFiles: { + 'duplicate.js': `module.exports = { description: 'Already exists' }`, + }, + }) + + const contentPath = join(testDir, 'content') + const navPath = join(testDir, 'nav.yml') + const commandsPath = join(testDir, 'lib', 'commands') + + await autoGenerateMissingDocs(contentPath, navPath, commandsPath) + + // Verify no duplicate + const { commandsSection } = await verifyNavStructure(navPath) + + const duplicateEntries = commandsSection.children.filter(c => c.url === '/commands/npm-duplicate') + t.equal(duplicateEntries.length, 1, 'does not create duplicate nav entries') + }) + + t.test('skips update when no missing docs', async t => { + const testDir = createAutoGenTestDir(t, { + existingDocs: { + 'npm-complete.md': `--- +title: npm-complete +section: 1 +description: Complete command +---`, + }, + navEntries: [ + { title: 'npm complete', url: '/commands/npm-complete', description: 'Complete command' }, + ], + commandFiles: { + 'complete.js': `module.exports = { description: 'Complete command' }`, + }, + }) + + const contentPath = join(testDir, 'content') + const navPath = join(testDir, 'nav.yml') + const commandsPath = join(testDir, 'lib', 'commands') + + const navBefore = await fs.readFile(navPath, 'utf-8') + await autoGenerateMissingDocs(contentPath, navPath, commandsPath) + const navAfter = await fs.readFile(navPath, 'utf-8') + + t.equal(navBefore, navAfter, 'does not modify nav when no missing docs') + }) + + t.test('handles nav without CLI Commands section', async t => { + const testDir = t.testdir({ + content: { + commands: {}, + }, + 'nav.yml': ` +- title: Other Section + children: [] +`, + lib: { + commands: { + 'test.js': `module.exports = { description: 'Test command' }`, + }, + }, + }) + + const contentPath = join(testDir, 'content') + const navPath = join(testDir, 'nav.yml') + const commandsPath = join(testDir, 'lib', 'commands') + + // Should not throw, just skip nav update + await autoGenerateMissingDocs(contentPath, navPath, commandsPath) + + // Doc should still be created + const docPath = join(contentPath, 'commands', 'npm-test.md') + const docExists = await fs.access(docPath).then(() => true).catch(() => false) + t.ok(docExists, 'creates doc even when nav section missing') + }) + + t.test('handles nav with CLI Commands but no children', async t => { + const testDir = t.testdir({ + content: { + commands: {}, + }, + 'nav.yml': ` +- title: CLI Commands +`, + lib: { + commands: { + 'test.js': `module.exports = { description: 'Test command' }`, + }, + }, + }) + + const contentPath = join(testDir, 'content') + const navPath = join(testDir, 'nav.yml') + const commandsPath = join(testDir, 'lib', 'commands') + + // Should not throw, just skip nav children update + await autoGenerateMissingDocs(contentPath, navPath, commandsPath) + + // Doc should still be created + const docPath = join(contentPath, 'commands', 'npm-test.md') + const docExists = await fs.access(docPath).then(() => true).catch(() => false) + t.ok(docExists, 'creates doc even when children missing') + }) + + t.test('handles npm command not in first position', async t => { + const testDir = createAutoGenTestDir(t, { + existingDocs: {}, + navEntries: [ + { title: 'npm alpha', url: '/commands/npm-alpha', description: 'Alpha command' }, + ], + commandFiles: { + 'alpha.js': `module.exports = { description: 'Alpha command' }`, + 'beta.js': `module.exports = { description: 'Beta command' }`, + }, + }) + + // Manually adjust nav to put npm not first + const navPath = join(testDir, 'nav.yml') + await fs.writeFile(navPath, ` +- title: CLI Commands + children: + - title: npm alpha + url: /commands/npm-alpha + - title: npm + url: /commands/npm +`) + + const contentPath = join(testDir, 'content') + const commandsPath = join(testDir, 'lib', 'commands') + + await autoGenerateMissingDocs(contentPath, navPath, commandsPath) + + // Verify npm moved to first position + const { commandsSection } = await verifyNavStructure(navPath) + + const titles = commandsSection.children.map(c => c.title) + t.equal(titles[0], 'npm', 'npm command moved to first position') + }) + + t.test('calls autoGenerateMissingDocs via run with default skipAutoGenerate', async t => { + // This test ensures the default parameter path is covered + const build = require('../lib/build.js') + const testDir = t.testdir({ + content: { + commands: { + 'npm-test.md': createCommandDoc('npm-test', 'Test'), + }, + }, + 'nav.yml': ` +- title: CLI Commands + url: /commands/npm-test +`, + lib: { + commands: { + 'test.js': `module.exports = { description: 'Test' }`, + }, + }, + }) + + const template = '{{ content }}' + await fs.writeFile(join(testDir, 'template.html'), template) + + const contentPath = join(testDir, 'content') + const navPath = join(testDir, 'nav.yml') + const templatePath = join(testDir, 'template.html') + const manPath = join(testDir, 'man') + const htmlPath = join(testDir, 'html') + const mdPath = join(testDir, 'md') + + // Call run with skipAutoGenerate set to true to avoid hitting real commands + const results = await build({ + content: contentPath, + template: templatePath, + nav: navPath, + man: manPath, + html: htmlPath, + md: mdPath, + skipAutoGenerate: true, + }) + + t.ok(results.length > 0, 'build runs successfully') + }) +}) + +t.test('command-specific definitions with missing command file', async t => { + // This test targets the catch block in index.js lines 110-113 + // Use a command that exists and has params - the catch block is for safety + // when command-specific definitions can't be loaded + await testCommandDoc(t, 'npm-install', 'Install a package', { + match: [/install/], + }) +}) + +t.test('generateNav', async t => { + const { generateNav } = require('../lib/build.js') + + t.test('commands directory does not exist', async t => { + // Tests line 63: await dirExists(docsCommandsPath) ? await fs.readdir(docsCommandsPath) : [] + // When commands directory doesn't exist, should return empty array + const testDir = t.testdir({ + content: { + // No commands directory + 'configuring-npm': { + 'install.md': `--- +title: Install +section: 5 +description: Download and install node and npm +---`, + }, + }, + 'nav.yml': '', + }) + + const contentPath = join(testDir, 'content') + const navPath = join(testDir, 'nav.yml') + + await generateNav(contentPath, navPath) + + const navContent = await fs.readFile(navPath, 'utf-8') + const navData = yaml.parse(navContent) + + // Should NOT have CLI Commands section since commands dir doesn't exist + const commandsSection = navData.find(s => s.title === 'CLI Commands') + t.notOk(commandsSection, 'no CLI Commands section when commands directory is missing') + + // Should still have configuring-npm section + const configuringSection = navData.find(s => s.title === 'Configuring npm') + t.ok(configuringSection, 'has configuring-npm section') + }) + + t.test('command title fallback to name', async t => { + // Tests line 72: (attributes.title || name).replace(/^npm-/, 'npm ') + // When command doc has no title, should use filename as title + const testDir = t.testdir({ + content: { + commands: { + // Command doc WITHOUT title in frontmatter - should use name + 'npm-test-cmd.md': `--- +section: 1 +description: A test command +--- + +Content here`, + }, + }, + 'nav.yml': '', + }) + + const contentPath = join(testDir, 'content') + const navPath = join(testDir, 'nav.yml') + + await generateNav(contentPath, navPath) + + const navContent = await fs.readFile(navPath, 'utf-8') + const navData = yaml.parse(navContent) + + const commandsSection = navData.find(s => s.title === 'CLI Commands') + t.ok(commandsSection, 'has CLI Commands section') + + const testCmdEntry = commandsSection.children.find(c => c.url === '/commands/npm-test-cmd') + t.ok(testCmdEntry, 'has test-cmd entry') + // Should use name ('npm-test-cmd') and replace 'npm-' with 'npm ' + t.equal(testCmdEntry.title, 'npm test-cmd', 'uses name with npm- replaced to npm space') + }) + + t.test('command description fallback to empty string', async t => { + // Tests line 77: description: attributes.description || '' + // When command doc has no description, should use empty string + const testDir = t.testdir({ + content: { + commands: { + // Command doc WITHOUT description in frontmatter - should use '' + 'npm-no-desc.md': `--- +title: npm-no-desc +section: 1 +--- + +Content here`, + }, + }, + 'nav.yml': '', + }) + + const contentPath = join(testDir, 'content') + const navPath = join(testDir, 'nav.yml') + + await generateNav(contentPath, navPath) + + const navContent = await fs.readFile(navPath, 'utf-8') + const navData = yaml.parse(navContent) + + const commandsSection = navData.find(s => s.title === 'CLI Commands') + t.ok(commandsSection, 'has CLI Commands section') + + const noDescEntry = commandsSection.children.find(c => c.url === '/commands/npm-no-desc') + t.ok(noDescEntry, 'has no-desc entry') + // Should use empty string since no description in frontmatter + t.equal(noDescEntry.description, '', 'uses empty string when no description') + }) +}) + +t.test('replaceParams with name edge cases', async t => { + // Test the conditions around the catch block more explicitly + t.test('npm command (no params)', async t => { + await testCommandDoc(t, 'npm', 'javascript package manager') + }) + + t.test('npx command (special case)', async t => { + await testCommandDoc(t, 'npx', 'Run a command from a local or remote npm package', { + match: [/package/], + }) + }) + + t.test('regular command with params (access)', async t => { + // Tests line 110: name && name !== 'npm' && name !== 'npx' + await testCommandDoc(t, 'npm-access', 'Set access level on published packages', { + match: [/registry/], + }) + }) + + t.test('command with subcommands and aliases (trust)', async t => { + // Tests subcommand code path including line 184 (aliases in subcommand definitions) + // npm trust has subcommands with definitions that include aliases (repo, env) + await testCommandDoc(t, 'npm-trust', 'Create a trusted relationship between a package and a OIDC provider', { + match: [/--repo/, /--env/], + }) + }) +}) + +// Helper to create a command loader from a map of command names to command objects +const createCommandLoader = (commands) => (name) => { + if (commands[name]) { + return commands[name] + } + // Fall back to real commands + return require(`../../lib/commands/${name}`) +} + +// Test harness for custom commands to test edge cases +t.test('custom command loader tests', async t => { + t.test('command without description', async t => { + const commandLoader = createCommandLoader({ + 'testcmd-nodesc': { + usage: [''], + params: ['registry'], + }, + }) + + const doc = createCommandDoc('npm-testcmd-nodesc', 'Test command without description') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-nodesc.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-nodesc') + t.ok(htmlContent.length > 0, 'generates HTML for command without description') + t.match(htmlContent, /registry/, 'includes registry param') + }) + + t.test('command without usage', async t => { + const commandLoader = createCommandLoader({ + 'testcmd-nousage': { + params: ['registry'], + }, + }) + + const doc = createCommandDoc('npm-testcmd-nousage', 'Test command without usage') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-nousage.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-nousage') + t.ok(htmlContent.length > 0, 'generates HTML for command without usage') + t.match(htmlContent, /npm testcmd-nousage/, 'includes command name in usage') + }) + + t.test('command without params (no definitions)', async t => { + const commandLoader = createCommandLoader({ + 'testcmd-noparams': { + usage: [''], + }, + }) + + const doc = `--- +title: npm-testcmd-noparams +section: 1 +description: Test command without params +--- + +### Synopsis + + +` + + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-noparams.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-noparams') + t.ok(htmlContent.length > 0, 'generates HTML for command without params') + t.match(htmlContent, /npm testcmd-noparams/, 'includes command name') + }) + + t.test('command with empty definitions (has config placeholder)', async t => { + const commandLoader = createCommandLoader({ + 'testcmd-empty-defs': { + usage: [''], + definitions: [], + }, + }) + + const doc = createCommandDoc('npm-testcmd-empty-defs', 'Test command with empty definitions') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-empty-defs.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-empty-defs') + t.ok(htmlContent.length > 0, 'generates HTML for command with empty definitions') + t.match(htmlContent, /npm testcmd-empty-defs/, 'includes command name') + }) + + t.test('command with params referencing non-existent global definition', async t => { + const commandLoader = createCommandLoader({ + 'testcmd-missing-param': { + usage: [''], + params: ['non-existent-param', 'registry'], + }, + }) + + const doc = createCommandDoc('npm-testcmd-missing-param', 'Test command with missing param') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-missing-param.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-missing-param') + t.ok(htmlContent.length > 0, 'generates HTML even with missing param definition') + t.match(htmlContent, /registry/, 'includes valid param') + }) + + t.test('command with exclusive param already resolved', async t => { + const commandLoader = createCommandLoader({ + 'testcmd-exclusive-resolved': { + usage: [''], + definitions: { + 'save-dev': { + key: 'save-dev', + default: false, + type: Boolean, + description: 'Save as devDependency', + exclusive: ['save-optional'], + describe: () => '#### `save-dev`\n\n* Default: false\n* Type: Boolean\n\nSave as devDependency', + }, + 'save-optional': { + key: 'save-optional', + default: false, + type: Boolean, + description: 'Save as optionalDependency', + describe: () => '#### `save-optional`\n\n* Default: false\n* Type: Boolean\n\nSave as optionalDependency', + }, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-exclusive-resolved', 'Test command with exclusive already resolved') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-exclusive-resolved.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-exclusive-resolved') + t.ok(htmlContent.length > 0, 'generates HTML with exclusive params') + t.match(htmlContent, /save-dev/, 'includes save-dev') + t.match(htmlContent, /save-optional/, 'includes save-optional') + }) + + t.test('command with exclusive param that does not exist in global definitions', async t => { + const commandLoader = createCommandLoader({ + 'testcmd-exclusive-missing': { + usage: [''], + definitions: { + 'my-flag': { + key: 'my-flag', + default: false, + type: Boolean, + description: 'A flag with non-existent exclusive', + exclusive: ['non-existent-global-param'], + describe: () => '#### `my-flag`\n\n* Default: false\n* Type: Boolean\n\nA flag with non-existent exclusive', + }, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-exclusive-missing', 'Test command with missing exclusive') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-exclusive-missing.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-exclusive-missing') + t.ok(htmlContent.length > 0, 'generates HTML even with missing exclusive param') + t.match(htmlContent, /my-flag/, 'includes the defined flag') + }) + + t.test('command with one definition with short flag', async t => { + const commandLoader = createCommandLoader({ + 'testcmd-short': { + usage: [''], + params: ['custom-flag'], + definitions: { + 'custom-flag': { + key: 'custom-flag', + default: false, + type: Boolean, + short: 'c', + description: 'A custom flag with a short version', + describe: () => '#### `custom-flag`\n\n* Default: false\n* Type: Boolean\n\nA custom flag with a short version', + }, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-short', 'Test command with short flag') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-short.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-short') + t.ok(htmlContent.length > 0, 'generates HTML for command with short flag') + t.match(htmlContent, /custom-flag/, 'includes custom flag') + t.match(htmlContent, /-c/, 'includes short flag') + }) + + t.test('command with definition with aliases', async t => { + const commandLoader = createCommandLoader({ + 'testcmd-alias': { + usage: [''], + definitions: { + 'aliased-flag': { + key: 'aliased-flag', + default: '', + type: String, + alias: ['af', 'alias-flag'], + description: 'A flag with aliases', + describe: () => '#### `aliased-flag`\n\n* Default: ""\n* Type: String\n* Alias: --af, --alias-flag\n\nA flag with aliases', + }, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-alias', 'Test command with aliased flag') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-alias.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-alias') + t.ok(htmlContent.length > 0, 'generates HTML for command with aliases') + t.match(htmlContent, /aliased-flag/, 'includes aliased flag') + t.match(htmlContent, /--af/, 'includes first alias') + t.match(htmlContent, /--alias-flag/, 'includes second alias') + }) + + t.test('command with subcommands', async t => { + class SubA { + static description = 'Subcommand A description' + static usage = [''] + static definitions = { + 'sub-a-flag': { + key: 'sub-a-flag', + default: false, + type: Boolean, + describe: () => '#### `sub-a-flag`\n\n* Default: false\n* Type: Boolean\n\nFlag for subcommand A', + }, + } + } + + class SubB { + static description = 'Subcommand B description' + static usage = ['[options]'] + static params = ['registry'] + } + + const commandLoader = createCommandLoader({ + 'testcmd-subs': { + usage: [''], + params: null, + subcommands: { + 'sub-a': SubA, + 'sub-b': SubB, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-subs', 'Test command with subcommands') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-subs.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-subs') + t.ok(htmlContent.length > 0, 'generates HTML for command with subcommands') + t.match(htmlContent, /npm testcmd-subs sub-a/, 'includes sub-a subcommand') + t.match(htmlContent, /npm testcmd-subs sub-b/, 'includes sub-b subcommand') + t.match(htmlContent, /Subcommand A description/, 'includes sub-a description') + t.match(htmlContent, /sub-a-flag/, 'includes sub-a specific flag') + }) + + t.test('command with exclusive params', async t => { + const commandLoader = createCommandLoader({ + 'testcmd-exclusive': { + usage: [''], + params: ['save'], + }, + }) + + const doc = createCommandDoc('npm-testcmd-exclusive', 'Test command with exclusive params') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-exclusive.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-exclusive') + t.ok(htmlContent.length > 0, 'generates HTML for command with exclusive params') + t.match(htmlContent, /save/, 'includes save param') + }) + + t.test('command without workspaces', async t => { + const commandLoader = createCommandLoader({ + 'testcmd-noworkspaces': { + usage: [''], + params: ['registry'], + workspaces: false, + }, + }) + + const doc = createCommandDoc('npm-testcmd-noworkspaces', 'Test command without workspaces') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-noworkspaces.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-noworkspaces') + t.ok(htmlContent.length > 0, 'generates HTML for command without workspaces') + t.match(htmlContent, /unaware of workspaces/, 'includes workspaces note') + }) + + t.test('command with workspaces enabled', async t => { + const commandLoader = createCommandLoader({ + 'testcmd-workspaces': { + usage: [''], + params: ['registry'], + workspaces: true, + }, + }) + + const doc = createCommandDoc('npm-testcmd-workspaces', 'Test command with workspaces') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-workspaces.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-workspaces') + t.ok(htmlContent.length > 0, 'generates HTML for command with workspaces') + t.notMatch(htmlContent, /unaware of workspaces/, 'does NOT include workspaces note') + }) + + t.test('subcommand without description', async t => { + class SubNoDesc { + static usage = [''] + static definitions = { + flag: { + key: 'flag', + default: false, + type: Boolean, + describe: () => '#### `flag`\n\n* Default: false\n* Type: Boolean\n\nA flag', + }, + } + } + + const commandLoader = createCommandLoader({ + 'testcmd-sub-nodesc': { + usage: [''], + params: null, + subcommands: { + mysub: SubNoDesc, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-sub-nodesc', 'Test command with subcommand without description') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-sub-nodesc.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-sub-nodesc') + t.ok(htmlContent.length > 0, 'generates HTML for subcommand without description') + t.match(htmlContent, /npm testcmd-sub-nodesc mysub/, 'includes subcommand') + }) + + t.test('subcommand without usage', async t => { + class SubNoUsage { + static description = 'Subcommand without usage' + static definitions = { + flag: { + key: 'flag', + default: false, + type: Boolean, + describe: () => '#### `flag`\n\n* Default: false\n* Type: Boolean\n\nA flag', + }, + } + } + + const commandLoader = createCommandLoader({ + 'testcmd-sub-nousage': { + usage: [''], + params: null, + subcommands: { + mysub: SubNoUsage, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-sub-nousage', 'Test command with subcommand without usage') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-sub-nousage.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-sub-nousage') + t.ok(htmlContent.length > 0, 'generates HTML for subcommand without usage') + t.match(htmlContent, /Subcommand without usage/, 'includes subcommand description') + }) + + t.test('subcommand with short flag and alias', async t => { + class SubWithShortAlias { + static description = 'Subcommand with short and alias' + static usage = [''] + static definitions = { + 'complex-flag': { + key: 'complex-flag', + default: '', + type: String, + short: 'x', + alias: ['cf', 'cflag'], + describe: () => '#### `complex-flag`\n\n* Default: ""\n* Type: String\n\nA complex flag', + }, + } + } + + const commandLoader = createCommandLoader({ + 'testcmd-sub-complex': { + usage: [''], + params: null, + subcommands: { + mysub: SubWithShortAlias, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-sub-complex', 'Test command with complex subcommand') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-sub-complex.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-sub-complex') + t.ok(htmlContent.length > 0, 'generates HTML for subcommand with short and alias') + t.match(htmlContent, /complex-flag/, 'includes complex flag') + t.match(htmlContent, /-x/, 'includes short flag') + t.match(htmlContent, /--cf/, 'includes first alias') + t.match(htmlContent, /--cflag/, 'includes second alias') + }) + + t.test('subcommand with explicit params (not derived from definitions)', async t => { + class SubWithParams { + static description = 'Subcommand with explicit params' + static usage = [''] + static params = ['registry', 'tag'] + } + + const commandLoader = createCommandLoader({ + 'testcmd-sub-params': { + usage: [''], + params: null, + subcommands: { + mysub: SubWithParams, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-sub-params', 'Test command with subcommand with explicit params') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-sub-params.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-sub-params') + t.ok(htmlContent.length > 0, 'generates HTML for subcommand with explicit params') + t.match(htmlContent, /registry/, 'includes registry param') + t.match(htmlContent, /tag/, 'includes tag param') + }) + + t.test('command with mixed command-specific and global params', async t => { + const { definitions: globalDefs } = require('@npmcli/config/lib/definitions') + + const commandLoader = createCommandLoader({ + 'testcmd-mixed': { + usage: [''], + definitions: { + 'custom-only': { + key: 'custom-only', + default: false, + type: Boolean, + description: 'A command-specific flag', + describe: () => '#### `custom-only`\n\n* Default: false\n* Type: Boolean\n\nA command-specific flag', + }, + registry: globalDefs.registry, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-mixed', 'Test command with mixed params') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-mixed.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-mixed') + t.ok(htmlContent.length > 0, 'generates HTML for command with mixed params') + t.match(htmlContent, /custom-only/, 'includes command-specific flag') + t.match(htmlContent, /registry/, 'includes global registry param') + }) + + t.test('subcommand with command-specific and global params', async t => { + const { definitions: globalDefs } = require('@npmcli/config/lib/definitions') + + class SubMixed { + static description = 'Subcommand with mixed params' + static usage = [''] + static definitions = { + 'sub-flag': { + key: 'sub-flag', + default: false, + type: Boolean, + description: 'A subcommand-specific flag', + describe: () => '#### `sub-flag`\n\n* Default: false\n* Type: Boolean\n\nA subcommand-specific flag', + }, + registry: globalDefs.registry, + } + } + + const commandLoader = createCommandLoader({ + 'testcmd-sub-mixed': { + usage: [''], + params: null, + subcommands: { + mysub: SubMixed, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-sub-mixed', 'Test command with subcommand with mixed params') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-sub-mixed.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-sub-mixed') + t.ok(htmlContent.length > 0, 'generates HTML for subcommand with mixed params') + t.match(htmlContent, /sub-flag/, 'includes subcommand-specific flag') + t.match(htmlContent, /registry/, 'includes global registry param') + }) + + t.test('subcommand with global config param that has alias in subDefinitions', async t => { + const { definitions: globalDefs } = require('@npmcli/config/lib/definitions') + + class SubWithGlobalAlias { + static description = 'Subcommand using global param with alias override' + static usage = [''] + static params = ['registry'] + static definitions = { + registry: { + ...globalDefs.registry, + alias: ['reg', 'r'], + describe: () => globalDefs.registry.describe(), + }, + } + } + + const commandLoader = createCommandLoader({ + 'testcmd-sub-global-alias': { + usage: [''], + params: null, + subcommands: { + mysub: SubWithGlobalAlias, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-sub-global-alias', 'Test subcommand with global aliased param') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-sub-global-alias.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-sub-global-alias') + t.ok(htmlContent.length > 0, 'generates HTML for subcommand with global aliased param') + t.match(htmlContent, /registry/, 'includes registry param') + t.match(htmlContent, /--reg/, 'includes first alias') + t.match(htmlContent, /--r/, 'includes second alias') + }) + + t.test('subcommand with flags without describe method (fallback table format)', async t => { + class SubWithoutDescribe { + static description = 'Subcommand with simple flags' + static usage = [''] + static definitions = { + 'simple-flag': { + key: 'simple-flag', + default: false, + type: Boolean, + description: 'A simple flag without describe method', + }, + 'aliased-flag': { + key: 'aliased-flag', + default: 'default-val', + type: String, + description: 'A flag with aliases and short form', + alias: ['af', 'alias-f'], + short: 'a', + }, + 'custom-default': { + key: 'custom-default', + default: 'value', + type: String, + defaultDescription: 'custom description of default', + typeDescription: 'Custom Type', + description: 'A flag with custom descriptions', + }, + 'falsy-default-desc': { + key: 'falsy-default-desc', + default: 'another-value', + type: String, + defaultDescription: '', + description: 'A flag with empty defaultDescription', + }, + } + } + + const commandLoader = createCommandLoader({ + 'testcmd-sub-nodescribe': { + usage: [''], + params: null, + subcommands: { + mysub: SubWithoutDescribe, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-sub-nodescribe', 'Test command with subcommand without describe') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-sub-nodescribe.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-sub-nodescribe') + t.ok(htmlContent.length > 0, 'generates HTML for subcommand with simple flags') + t.match(htmlContent, /simple-flag/, 'includes simple flag') + t.match(htmlContent, /aliased-flag/, 'includes aliased flag') + t.match(htmlContent, /-a/, 'includes short form') + t.match(htmlContent, /af/, 'includes alias') + t.match(htmlContent, /custom description of default/, 'includes custom default description') + t.match(htmlContent, /Custom Type/, 'includes custom type description') + t.match(htmlContent, /falsy-default-desc/, 'includes flag with falsy defaultDescription') + }) + + t.test('subcommand with command-specific params and table format (no describe)', async t => { + class SubMixedNoDescribe { + static description = 'Subcommand with command-specific params but no describe' + static usage = [''] + static definitions = { + 'sub-custom': { + key: 'sub-custom', + default: 'default-val', + type: String, + description: 'A command-specific flag without describe', + }, + registry: { + key: 'registry', + default: 'https://registry.npmjs.org/', + type: String, + description: 'The base URL of the npm registry', + }, + } + } + + const commandLoader = createCommandLoader({ + 'testcmd-sub-mixed-nodesc': { + usage: [''], + params: null, + subcommands: { + mysub: SubMixedNoDescribe, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-sub-mixed-nodesc', 'Test command with subcommand with mixed params no describe') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-sub-mixed-nodesc.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-sub-mixed-nodesc') + t.ok(htmlContent.length > 0, 'generates HTML for subcommand with command-specific params no describe') + t.match(htmlContent, /sub-custom/, 'includes command-specific flag') + t.match(htmlContent, /registry/, 'includes global registry param') + }) + + t.test('subcommand with no params', async t => { + class SubNoParams { + static description = 'Subcommand with no params' + static usage = [''] + } + + const commandLoader = createCommandLoader({ + 'testcmd-sub-noparams': { + usage: [''], + params: null, + subcommands: { + mysub: SubNoParams, + }, + }, + }) + + const doc = createCommandDoc('npm-testcmd-sub-noparams', 'Test command with subcommand with no params') + const { html } = await testBuildDocs(t, { + commandLoader, + content: { + commands: { 'npm-testcmd-sub-noparams.md': doc }, + }, + }) + + const htmlContent = await readHtmlDoc(html, 'npm-testcmd-sub-noparams') + t.ok(htmlContent.length > 0, 'generates HTML for subcommand with no params') + t.match(htmlContent, /mysub/, 'includes subcommand') + }) +}) diff --git a/lib/arborist-cmd.js b/lib/arborist-cmd.js index 9d247d02fa181..2206b04379163 100644 --- a/lib/arborist-cmd.js +++ b/lib/arborist-cmd.js @@ -1,9 +1,7 @@ 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. +// 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 @@ -18,14 +16,14 @@ class ArboristCmd extends BaseCommand { 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 + // 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 @@ -34,8 +32,7 @@ class ArboristCmd extends BaseCommand { && 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 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')) { diff --git a/lib/base-cmd.js b/lib/base-cmd.js index 99ae6d7f43c70..f601e5c19d87b 100644 --- a/lib/base-cmd.js +++ b/lib/base-cmd.js @@ -1,46 +1,90 @@ const { log } = require('proc-log') +const { definitions } = require('@npmcli/config/lib/definitions') +const nopt = require('nopt') class BaseCommand { + // these defaults can be overridden by individual commands static workspaces = false static ignoreImplicitWorkspace = true + static checkDevEngines = false - // these are all overridden by individual commands + // these should always be overridden by individual commands static name = null static description = null static params = null + static definitions = null + static subcommands = null + // Number of expected positional arguments (null = unlimited/unchecked) + static positionals = null - // this is a static so that we can read from it without instantiating a command - // which would require loading the config + // 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') + return this.getUsage() + } + + static getUsage (parentName = null, includeDescriptions = true) { const { aliases: cmdAliases } = require('./utils/cmd-list') const seenExclusive = new Set() const wrapWidth = 80 - const { description, usage = [''], name, params } = this + const { description, usage = [''], name } = this + + // Resolve to a definitions array: if the command has its own definitions, use those directly; otherwise resolve params from the global definitions pool. + let cmdDefs + if (this.definitions) { + cmdDefs = this.definitions + } else if (this.params) { + cmdDefs = this.params.map(p => definitions[p]).filter(Boolean) + } + + // If this is a subcommand, prepend parent name + const fullCommandName = parentName ? `${parentName} ${name}` : name const fullUsage = [ `${description}`, '', 'Usage:', - ...usage.map(u => `npm ${name} ${u}`.trim()), ] + if (usage) { + fullUsage.push(...usage.map(u => `npm ${fullCommandName} ${u}`.trim())) + } - if (params) { + if (this.subcommands) { + for (const sub in this.subcommands) { + fullUsage.push(`npm ${fullCommandName} ${sub} ${this.subcommands[sub].usage}`) + } + fullUsage.push('') + fullUsage.push('Subcommands:') + const subcommandEntries = Object.entries(this.subcommands) + for (let i = 0; i < subcommandEntries.length; i++) { + const [subName, SubCommand] = subcommandEntries[i] + fullUsage.push(` ${subName}`) + if (SubCommand.description) { + fullUsage.push(` ${SubCommand.description}`) + } + // Add space between subcommands except after the last one + if (i < subcommandEntries.length - 1) { + fullUsage.push('') + } + } + fullUsage.push('') + fullUsage.push(`Run "npm ${name} --help" for more info on a subcommand.`) + } + + if (cmdDefs) { let results = '' let line = '' - for (const param of params) { + for (const def of cmdDefs) { /* istanbul ignore next */ - if (seenExclusive.has(param)) { + if (seenExclusive.has(def.key)) { continue } - const { exclusive } = definitions[param] - let paramUsage = `${definitions[param].usage}` - if (exclusive) { + let paramUsage = def.usage + if (def.exclusive) { const exclusiveParams = [paramUsage] - seenExclusive.add(param) - for (const e of exclusive) { + for (const e of def.exclusive) { seenExclusive.add(e) - exclusiveParams.push(definitions[e].usage) + const eDef = cmdDefs.find(d => d.key === e) || definitions[e] + exclusiveParams.push(eDef?.usage) } paramUsage = `${exclusiveParams.join('|')}` } @@ -54,6 +98,24 @@ class BaseCommand { fullUsage.push('') fullUsage.push('Options:') fullUsage.push([results, line].filter(Boolean).join('\n')) + + // Add flag descriptions + if (cmdDefs.length > 0 && includeDescriptions) { + fullUsage.push('') + for (const def of cmdDefs) { + if (def.description) { + const desc = def.description.trim().split('\n')[0] + const shortcuts = def.short ? `-${def.short}` : '' + const aliases = (def.alias || []).map(v => `--${v}`).join('|') + const mainFlag = `--${def.key}` + const flagName = [shortcuts, mainFlag, aliases].filter(Boolean).join('|') + const requiredNote = def.required ? ' (required)' : '' + fullUsage.push(` ${flagName}${requiredNote}`) + fullUsage.push(` ${desc}`) + fullUsage.push('') + } + } + } } const aliases = Object.entries(cmdAliases).reduce((p, [k, v]) => { @@ -67,25 +129,33 @@ class BaseCommand { } fullUsage.push('') - fullUsage.push(`Run "npm help ${name}" for more info`) + const helpName = parentName ? parentName.split(' ')[0] : name + fullUsage.push(`Run "npm help ${helpName}" for more info`) return fullUsage.join('\n') } constructor (npm) { this.npm = npm + this.commandArgs = null + this.parentName = null - const { config } = this.npm + const { config } = this 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') + throw new Error('Cannot use --no-workspaces and --workspace at the same time') } } + get config () { + // Return command-specific config if it exists, otherwise use npm's config + return this.npm.config + } + get name () { return this.constructor.name } @@ -99,7 +169,7 @@ class BaseCommand { } get usage () { - return this.constructor.describeUsage + return this.constructor.getUsage(this.parentName) } usageError (prefix = '') { @@ -122,13 +192,69 @@ class BaseCommand { } else if (!this.npm.config.isDefault('expect-result-count')) { const expected = this.npm.config.get('expect-result-count') if (expected !== entries) { - /* eslint-disable-next-line max-len */ 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') @@ -151,6 +277,171 @@ class BaseCommand { this.workspaceNames = [...ws.keys()] this.workspacePaths = [...ws.values()] } + + flags (depth = 1) { + const commandDefinitions = this.constructor.definitions || [] + + // Build types, shorthands, and defaults from definitions + const types = {} + const defaults = {} + const cmdShorthands = {} + const aliasMap = {} // Track which aliases map to which main keys + + for (const def of commandDefinitions) { + defaults[def.key] = def.default + types[def.key] = def.type + + // Handle aliases defined in the definition + if (def.alias && Array.isArray(def.alias)) { + for (const aliasKey of def.alias) { + types[aliasKey] = def.type // Needed for nopt to parse aliases + if (!aliasMap[def.key]) { + aliasMap[def.key] = [] + } + aliasMap[def.key].push(aliasKey) + } + } + + // Handle short options + if (def.short) { + const shorts = Array.isArray(def.short) ? def.short : [def.short] + for (const short of shorts) { + cmdShorthands[short] = [`--${def.key}`] + } + } + } + + // Parse args + let parsed = {} + let remains = [] + const argv = this.config.argv + if (argv && argv.length > 0) { + // config.argv contains the full command line including node, npm, and command names + // Format: ['node', 'npm', 'command', 'subcommand', 'positional', '--flags'] + // depth tells us how many command names to skip (1 for top-level, 2 for subcommand, etc.) + const offset = 2 + depth // Skip 'node', 'npm', and all command/subcommand names + parsed = nopt(types, cmdShorthands, argv, offset) + remains = parsed.argv.remain + delete parsed.argv + } + + // Validate unknown CLI flags/configs and unexpected positionals. + // Runs for every command; command-specific flags are allow-listed here so they don't trip the global unknown-config collection from Config.loadCLI(). + this.validateCli(commandDefinitions, remains) + + // Check for conflicts between main flags and their aliases + // Also map aliases back to their main keys + for (const [mainKey, aliases] of Object.entries(aliasMap)) { + const providedKeys = [] + if (mainKey in parsed) { + providedKeys.push(mainKey) + } + for (const alias of aliases) { + if (alias in parsed) { + providedKeys.push(alias) + } + } + if (providedKeys.length > 1) { + const flagList = providedKeys.map(k => `--${k}`).join(' or ') + throw new Error(`Please provide only one of ${flagList}`) + } + + // If an alias was provided, map it to the main key + if (providedKeys.length === 1 && providedKeys[0] !== mainKey) { + const aliasKey = providedKeys[0] + parsed[mainKey] = parsed[aliasKey] + delete parsed[aliasKey] + } + } + + // Only include keys that are defined in commandDefinitions (main keys only) + const filtered = {} + for (const def of commandDefinitions) { + if (def.key in parsed) { + filtered[def.key] = parsed[def.key] + } + } + return [{ ...defaults, ...filtered }, remains] + } + + // Unified CLI validation — runs for every command (definitions-based and legacy). + // Reads collected unknown configs from Config (they were collected, not thrown, during Config.load()), subtracts any command-specific definitions, and throws a single aggregated error. + // Also enforces extra-positional errors for commands that set a finite `static positionals`. + // Shellout commands (run/exec/lifecycle) leave `static positionals = null` and are unaffected. + // Commands that set `static skipConfigValidation = true` (config, help, doctor, completion, version) bypass both unknown-config checks so they can operate against a broken .npmrc. + validateCli (commandDefinitions = this.constructor.definitions || [], remains = null) { + const allowlist = new Set([ + ...commandDefinitions.map(d => d.key), + ...commandDefinitions.flatMap(d => Array.isArray(d.alias) ? d.alias : []), + ]) + + if (!this.constructor.skipConfigValidation) { + const cliUnknowns = this.npm.config.getUnknownConfigs('cli') + .filter(u => !allowlist.has(u.key) && !allowlist.has(u.baseKey)) + + const fileUnknowns = [] + for (const where of ['builtin', 'project', 'user', 'global']) { + fileUnknowns.push(...this.npm.config.getUnknownConfigs(where)) + } + + if (cliUnknowns.length > 0 || fileUnknowns.length > 0) { + const sections = [] + if (cliUnknowns.length > 0) { + const lines = cliUnknowns.map(u => + u.baseKey ? ` - --${u.baseKey} (${u.key})` : ` - --${u.key}` + ) + sections.push( + `Unknown cli config${cliUnknowns.length > 1 ? 's' : ''}:`, + ...lines, + 'Run `npm help config` for supported options.' + ) + } + if (fileUnknowns.length > 0) { + if (sections.length > 0) { + sections.push('') + } + const lines = fileUnknowns.map(u => { + const display = u.baseKey ? `"${u.baseKey}" (${u.key})` : `"${u.key}"` + return ` - ${u.where} config ${display} from ${u.source}` + }) + sections.push( + `Unknown npm configuration key${fileUnknowns.length > 1 ? 's' : ''}:`, + ...lines, + 'See `npm help npmrc` for supported config options.' + ) + } + throw Object.assign(new Error(sections.join('\n')), { + code: 'EUNKNOWNCONFIG', + unknownConfigs: [...cliUnknowns, ...fileUnknowns], + }) + } + } + + // Positionals consumed as flag values by command-specific definitions were queued as "unknown positional" warnings by Config.unknownHandler; drop those since they're actually flag arguments. + if (Array.isArray(remains)) { + const remainsSet = new Set(remains) + for (const unknownPos of this.npm.config.getUnknownPositionals()) { + if (!remainsSet.has(unknownPos)) { + this.npm.config.removeUnknownPositional(unknownPos) + } + } + } + + const expected = this.constructor.positionals + if (expected !== null && remains !== null && remains.length > expected) { + const extra = remains.slice(expected) + throw this.usageError( + `Unknown positional argument${extra.length > 1 ? 's' : ''}: ${extra.join(', ')}` + ) + } + + this.npm.config.logWarnings() + } + + async exec () { + // This method should be overridden by commands + // Subcommand routing is handled in npm.js #exec + } } module.exports = BaseCommand diff --git a/lib/cli.js b/lib/cli.js index e11729fe3205b..00b4fc0bd7fb7 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -1,3 +1,11 @@ +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') diff --git a/lib/cli/entry.js b/lib/cli/entry.js index ed73eb89e2d36..962c62a5766da 100644 --- a/lib/cli/entry.js +++ b/lib/cli/entry.js @@ -1,16 +1,8 @@ -/* eslint-disable max-len */ - // Separated out for easier unit testing module.exports = async (process, validateEngines) => { - // set it here so that regardless of what happens later, we don't - // leak any private CLI configs to other programs + // set it here so that regardless of what happens later, we don't leak any private CLI configs to other programs process.title = 'npm' - // if npm is called as "npmg" or "npm_g", then run in global mode. - if (process.argv[1][process.argv[1].length - 1] === 'g') { - process.argv.splice(1, 1, 'npm', '-g') - } - // Patch the global fs module here at the app level require('graceful-fs').gracefulify(require('node:fs')) @@ -27,11 +19,13 @@ module.exports = async (process, validateEngines) => { 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. + // At this point we've required a few files and can be pretty sure we don't 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. + // 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) } @@ -64,9 +58,8 @@ module.exports = async (process, validateEngines) => { 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 + // this is async but we don't 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)) diff --git a/lib/cli/exit-handler.js b/lib/cli/exit-handler.js index e76b08c80a635..2c95d0d909a37 100644 --- a/lib/cli/exit-handler.js +++ b/lib/cli/exit-handler.js @@ -37,7 +37,7 @@ class ExitHandler { constructor ({ process }) { this.#process = process - this.#process.on('exit', this.#handleProcesExitAndReset) + this.#process.on('exit', this.#handleProcessExitAndReset) } registerUncaughtHandlers () { @@ -49,12 +49,11 @@ class ExitHandler { this.#handleExit(err) } - #handleProcesExitAndReset = (code) => { + #handleProcessExitAndReset = (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) + // Reset all the state. This is only relevant for tests since in reality the process fully exits here. + this.#process.off('exit', this.#handleProcessExitAndReset) this.#process.off('uncaughtException', this.#handleExit) this.#process.off('unhandledRejection', this.#handleExit) if (this.#loaded) { @@ -115,9 +114,8 @@ class ExitHandler { } #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. + // 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 @@ -147,9 +145,7 @@ class ExitHandler { 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 + // 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. 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) @@ -157,14 +153,12 @@ class ExitHandler { 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 + // 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. + // 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) })) diff --git a/lib/cli/update-notifier.js b/lib/cli/update-notifier.js index 32cac18350be9..893a6f0ccdbe0 100644 --- a/lib/cli/update-notifier.js +++ b/lib/cli/update-notifier.js @@ -1,6 +1,4 @@ -// 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. +// print a banner telling the user to upgrade npm to latest but not in CI, and not if we're doing that already. const ciInfo = require('ci-info') const gt = require('semver/functions/gt') @@ -14,11 +12,9 @@ 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') +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 +// 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') @@ -36,11 +32,9 @@ const updateCheck = async (npm, spec, version, current) => { 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') { + // 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 === '*') { return updateNotifier(npm, `^${version}`) } @@ -51,9 +45,8 @@ const updateCheck = async (npm, spec, version, current) => { 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. + // 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' @@ -62,18 +55,20 @@ const updateCheck = async (npm, spec, version, current) => { 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` + const message = [ + '', + `New ${chalk[typec](type)} version of npm available! ${chalk[typec](current)} -> ${chalk.blue(latest)}`, + `Changelog: ${chalk.blue(`https://github.com/npm/cli/releases/tag/v${latest}`)}`, + `To update run: ${chalk.underline(`npm install -g npm@${latest}`)}`, + '', + ].join('\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 updateNotifier = async (npm, spec = '*') => { + // 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) @@ -83,7 +78,7 @@ const updateNotifier = async (npm, spec = 'latest') => { } // while on a beta train, get updates daily - const duration = spec !== 'latest' ? DAILY : WEEKLY + const duration = current.prerelease.length ? DAILY : WEEKLY const t = new Date(Date.now() - duration) // if we don't have a file, then definitely check it. @@ -94,16 +89,15 @@ const updateNotifier = async (npm, spec = 'latest') => { 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. + // 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 => { +module.exports = async npm => { if ( // opted out !npm.config.get('update-notifier') @@ -114,7 +108,7 @@ module.exports = npm => { // CI || ciInfo.isCI ) { - return Promise.resolve(null) + return null } return updateNotifier(npm) diff --git a/lib/cli/validate-engines.js b/lib/cli/validate-engines.js index cf5315a25dce0..d9d38157564c9 100644 --- a/lib/cli/validate-engines.js +++ b/lib/cli/validate-engines.js @@ -1,9 +1,6 @@ -// 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 +// 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}` @@ -11,14 +8,11 @@ const npm = `v${version}` module.exports = (process, getCli) => { const node = process.version - /* eslint-disable-next-line max-len */ 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/.` - /* eslint-disable-next-line max-len */ 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 + // 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) { diff --git a/lib/commands/access.js b/lib/commands/access.js index 547fa7af01577..d0faf394f0966 100644 --- a/lib/commands/access.js +++ b/lib/commands/access.js @@ -116,11 +116,15 @@ class Access extends BaseCommand { } async #grant (permissions, scope, pkg) { - await libnpmaccess.setPermissions(scope, pkg, permissions, this.npm.flatOptions) + await otplease(this.npm, this.npm.flatOptions, async (opts) => { + await libnpmaccess.setPermissions(scope, pkg, permissions, opts) + }) } async #revoke (scope, pkg) { - await libnpmaccess.removePermissions(scope, pkg, this.npm.flatOptions) + await otplease(this.npm, this.npm.flatOptions, async (opts) => { + await libnpmaccess.removePermissions(scope, pkg, opts) + }) } async #listPackages (owner, pkg) { diff --git a/lib/commands/adduser.js b/lib/commands/adduser.js deleted file mode 100644 index cf64e7a7e7438..0000000000000 --- a/lib/commands/adduser.js +++ /dev/null @@ -1,50 +0,0 @@ -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 diff --git a/lib/commands/approve-scripts.js b/lib/commands/approve-scripts.js new file mode 100644 index 0000000000000..929c692112f16 --- /dev/null +++ b/lib/commands/approve-scripts.js @@ -0,0 +1,10 @@ +const AllowScriptsCmd = require('../utils/allow-scripts-cmd.js') + +class ApproveScripts extends AllowScriptsCmd { + static description = 'Approve install scripts for specific dependencies' + static name = 'approve-scripts' + static usage = [' [ ...]', '--all', '--allow-scripts-pending'] + static verb = 'approve' +} + +module.exports = ApproveScripts diff --git a/lib/commands/audit.js b/lib/commands/audit.js index 486bef1bb5dc1..bc2480c520fe9 100644 --- a/lib/commands/audit.js +++ b/lib/commands/audit.js @@ -3,6 +3,8 @@ 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 resolveAllowScripts = require('../utils/resolve-allow-scripts.js') +const { patchRelaxOpts } = require('../utils/cli-only-flag.js') const VerifySignatures = require('../utils/verify-signatures.js') class Audit extends ArboristWorkspaceCmd { @@ -19,6 +21,7 @@ class Audit extends ArboristWorkspaceCmd { 'include', 'foreground-scripts', 'ignore-scripts', + 'include-attestations', ...super.params, ] @@ -36,7 +39,7 @@ class Audit extends ArboristWorkspaceCmd { case 'signatures': return [] default: - throw Object.assign(new Error(argv[2] + ' not recognized'), { + throw Object.assign(new Error(`${argv[2]} not recognized`), { code: 'EUSAGE', }) } @@ -53,22 +56,39 @@ class Audit extends ArboristWorkspaceCmd { 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') + throw this.usageError('fix cannot be used without a package-lock') } const reporter = this.npm.config.get('json') ? 'json' : 'detail' const Arborist = require('@npmcli/arborist') + const { policy: allowScriptsPolicy } = await resolveAllowScripts(this.npm) const opts = { ...this.npm.flatOptions, + // audit fix reifies, so honor the cli-only patch relax flags + ...patchRelaxOpts(this.npm.config), audit: true, path: this.npm.prefix, reporter, workspaces: this.workspaceNames, + allowScripts: allowScriptsPolicy, } const arb = new Arborist(opts) await arb.audit({ fix }) if (fix) { await reifyFinish(this.npm, arb) + // Report any fix that a `min-release-age`/`before` window blocked from + // installing, and exit non-zero so a blocked fix is not missed. + const report = arb.auditReport + const blocked = report instanceof Map + ? [...report.values()].filter(v => v.fixBlockedByReleaseAge).map(v => v.name) + : [] + if (blocked.length) { + log.warn('audit', `${blocked.length} package(s) left at a vulnerable version because ` + + `a fix is newer than the release-age cutoff: ${blocked.join(', ')}.\n` + + 'Add the package to min-release-age-exclude, or relax min-release-age or before, ' + + 'to install the fix.') + process.exitCode = 1 + } } else { // will throw if there's an error, because this is an audit command auditError(this.npm, arb.auditReport) diff --git a/lib/commands/cache.js b/lib/commands/cache.js index 87c70a57dc0ed..e1d1dcad88df6 100644 --- a/lib/commands/cache.js +++ b/lib/commands/cache.js @@ -1,16 +1,17 @@ -const cacache = require('cacache') -const pacote = require('pacote') const fs = require('node:fs/promises') const { join } = require('node:path') +const cacache = require('cacache') +const pacote = require('pacote') 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 PkgJson = require('@npmcli/package-json') +const abbrev = require('abbrev') +const BaseCommand = require('../base-cmd.js') const searchCachePackage = async (path, parsed, cacheKeys) => { - /* eslint-disable-next-line max-len */ const searchMFH = new RegExp(`^make-fetch-happen:request-cache:.*(? { try { details = await cacache.get(path, key) packument = jsonParse(details.data) - } catch (_) { + } catch { // if we couldn't parse the packument, abort continue } @@ -63,7 +64,7 @@ const searchCachePackage = async (path, parsed, cacheKeys) => { } class Cache extends BaseCommand { - static description = 'Manipulates packages cache' + static description = 'Manipulates packages and npx cache' static name = 'cache' static params = ['cache'] static usage = [ @@ -71,12 +72,15 @@ class Cache extends BaseCommand { 'clean []', 'ls [@]', 'verify', + 'npx ls', + 'npx rm [...]', + 'npx info ...', ] static async completion (opts) { const argv = opts.conf.argv.remain if (argv.length === 2) { - return ['add', 'clean', 'verify', 'ls'] + return ['add', 'clean', 'verify', 'ls', 'npx'] } // TODO - eventually... @@ -100,30 +104,41 @@ class Cache extends BaseCommand { return await this.verify() case 'ls': return await this.ls(args) + case 'npx': + return await this.npx(args) + default: + throw this.usageError() + } + } + + // npm cache npx + async npx ([cmd, ...keys]) { + switch (cmd) { + case 'ls': + return await this.npxLs(keys) + case 'rm': + return await this.npxRm(keys) + case 'info': + return await this.npxInfo(keys) default: throw this.usageError() } } - // npm cache clean [pkg]* + // npm cache clean [spec]* async clean (args) { - const cachePath = join(this.npm.cache, '_cacache') + // this is a derived value + const cachePath = this.npm.flatOptions.cache 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.`) + 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 removing 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 }) } @@ -131,7 +146,7 @@ class Cache extends BaseCommand { let entry try { entry = await cacache.get(cachePath, key) - } catch (err) { + } catch { log.warn('cache', `Not Found: ${key}`) break } @@ -154,34 +169,33 @@ class Cache extends BaseCommand { 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. + // 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 }) + }, { ...this.npm.flatOptions, _isRoot: true }) await pacote.manifest(spec, { ...this.npm.flatOptions, fullMetadata: true, + _isRoot: 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) + // this is a derived value + const cachePath = this.npm.flatOptions.cache + const prefix = cachePath.indexOf(process.env.HOME) === 0 + ? `~${cachePath.slice(process.env.HOME.length)}` + : cachePath + const stats = await cacache.verify(cachePath) 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) { - /* eslint-disable-next-line max-len */ output.standard(`Content garbage-collected: ${stats.reclaimedCount} (${stats.reclaimedSize} bytes)`) } if (stats.missingContent) { @@ -191,9 +205,10 @@ class Cache extends BaseCommand { output.standard(`Finished in ${stats.runTime.total / 1000}s`) } - // npm cache ls [--package ...] + // npm cache ls [ ...] async ls (specs) { - const cachePath = join(this.npm.cache, '_cacache') + // This is a derived value + const { cache: cachePath } = this.npm.flatOptions const cacheKeys = Object.keys(await cacache.ls(cachePath)) if (specs.length > 0) { // get results for each package spec specified @@ -213,6 +228,136 @@ class Cache extends BaseCommand { } cacheKeys.sort(localeCompare).forEach(key => output.standard(key)) } + + async #npxCache (keys = []) { + // This is a derived value + const { npxCache } = this.npm.flatOptions + let dirs + try { + dirs = await fs.readdir(npxCache, { encoding: 'utf-8' }) + } catch { + output.standard('npx cache does not exist') + return + } + const cache = {} + const { default: pMap } = await import('p-map') + await pMap(dirs, async e => { + const pkgPath = join(npxCache, e) + cache[e] = { + hash: e, + path: pkgPath, + valid: false, + } + try { + const pkgJson = await PkgJson.load(pkgPath) + cache[e].package = pkgJson.content + cache[e].valid = true + } catch { + // Defaults to not valid already + } + }, { concurrency: 20 }) + if (!keys.length) { + return cache + } + const result = {} + const abbrevs = abbrev(Object.keys(cache)) + for (const key of keys) { + if (!abbrevs[key]) { + throw this.usageError(`Invalid npx key ${key}`) + } + result[abbrevs[key]] = cache[abbrevs[key]] + } + return result + } + + async npxLs () { + const cache = await this.#npxCache() + for (const key in cache) { + const { hash, valid, package: pkg } = cache[key] + let result = `${hash}:` + if (!valid) { + result = `${result} (empty/invalid)` + } else if (pkg?._npx) { + result = `${result} ${pkg._npx.packages.join(', ')}` + } else { + result = `${result} (unknown)` + } + output.standard(result) + } + } + + async npxRm (keys) { + if (!keys.length) { + if (!this.npm.config.get('force')) { + throw this.usageError('Please use --force to remove entire npx cache') + } + const { npxCache } = this.npm.flatOptions + if (!this.npm.config.get('dry-run')) { + return fs.rm(npxCache, { recursive: true, force: true }) + } + } + + const cache = await this.#npxCache(keys) + for (const key in cache) { + const { path: cachePath } = cache[key] + output.standard(`Removing npx key at ${cachePath}`) + if (!this.npm.config.get('dry-run')) { + await fs.rm(cachePath, { recursive: true }) + } + } + } + + async npxInfo (keys) { + const chalk = this.npm.chalk + if (!keys.length) { + throw this.usageError() + } + const cache = await this.#npxCache(keys) + const Arborist = require('@npmcli/arborist') + for (const key in cache) { + const { hash, path, package: pkg } = cache[key] + let valid = cache[key].valid + const results = [] + try { + if (valid) { + const arb = new Arborist({ path }) + const tree = await arb.loadVirtual() + if (pkg._npx) { + results.push('packages:') + for (const p of pkg._npx.packages) { + const parsed = npa(p) + if (parsed.type === 'directory') { + // in the tree the spec is relative, even if the dependency spec is absolute, so we can't find it by name or spec. + results.push(`- ${chalk.cyan(p)}`) + } else { + results.push(`- ${chalk.cyan(p)} (${chalk.blue(tree.children.get(parsed.name).pkgid)})`) + } + } + } else { + results.push('packages: (unknown)') + results.push(`dependencies:`) + for (const dep in pkg.dependencies) { + const child = tree.children.get(dep) + if (child.isLink) { + results.push(`- ${chalk.cyan(child.realpath)}`) + } else { + results.push(`- ${chalk.cyan(child.pkgid)}`) + } + } + } + } + } catch (ex) { + valid = false + } + const v = valid ? chalk.green('valid') : chalk.red('invalid') + output.standard(`${v} npx cache entry with key ${chalk.blue(hash)}`) + output.standard(`location: ${chalk.blue(path)}`) + if (valid) { + output.standard(results.join('\n')) + } + output.standard() + } + } } module.exports = Cache diff --git a/lib/commands/ci.js b/lib/commands/ci.js index c190de7e3ea7f..17307badede98 100644 --- a/lib/commands/ci.js +++ b/lib/commands/ci.js @@ -1,9 +1,12 @@ const reifyFinish = require('../utils/reify-finish.js') +const resolveAllowScripts = require('../utils/resolve-allow-scripts.js') +const strictAllowScriptsPreflight = require('../utils/strict-allow-scripts-preflight.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 { validatePackageExtensions, validateNpmExtension } = require('../utils/validate-lockfile.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') const getWorkspaces = require('../utils/get-workspaces.js') @@ -21,6 +24,13 @@ class CI extends ArboristWorkspaceCmd { 'strict-peer-deps', 'foreground-scripts', 'ignore-scripts', + 'allow-directory', + 'allow-file', + 'allow-git', + 'allow-remote', + 'allow-scripts', + 'strict-allow-scripts', + 'dangerously-allow-all-scripts', 'audit', 'bin-links', 'fund', @@ -35,56 +45,81 @@ class CI extends ArboristWorkspaceCmd { }) } + // npm ci is always strict about patches; the relax flags are not accepted + for (const flag of ['allow-unused-patches', 'ignore-patch-failures']) { + if (this.npm.config.find(flag) === 'cli') { + throw Object.assign(new Error(`The --${flag} flag is not allowed with \`npm ci\`.`), { + code: 'ECIPATCHFLAG', + }) + } + } + + const dryRun = this.npm.config.get('dry-run') + const ignoreScripts = this.npm.config.get('ignore-scripts') const where = this.npm.prefix const Arborist = require('@npmcli/arborist') + const { policy: allowScriptsPolicy } = await resolveAllowScripts(this.npm) 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, + allowScripts: allowScriptsPolicy, + // npm ci reifies the locked graph, which already carries extension-influenced edges, so it must never import or execute .npm-extension. + // The extension file hash is still validated below, independent of execution. + ignoreExtension: true, } - const arb = new Arborist(opts) - await arb.loadVirtual().catch(er => { - log.verbose('loadVirtual', er.stack) + // generate an inventory from the virtual tree in the lockfile + const virtualArb = new Arborist(opts) + try { + await virtualArb.loadVirtual() + } catch (err) { + log.verbose('loadVirtual', err.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.' + 'The `npm ci` command can only install with an existing\n' + + 'package-lock.json with lockfileVersion >= 1. Run an install with npm@5\n' + + 'or 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) + } + const virtualInventory = new Map(virtualArb.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 + // Now we make our real Arborist. + // We need a new one because the virtual tree from the lockfile can have extraneous dependencies in it that won't install on this platform + const arb = new Arborist(opts) await arb.buildIdealTree() + await strictAllowScriptsPreflight({ arb, npm: this.npm, idealTreeOpts: opts }) - // 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 + // Verifies that the packages from the ideal tree will match the same versions that are present in the virtual tree (lock file). const errors = validateLockfile(virtualInventory, arb.idealTree.inventory) + // Verifies that the root packageExtensions state matches the lockfile and is still consistent with the locked tree. + errors.push(...validatePackageExtensions(virtualArb.virtualTree, arb.idealTree)) + // Verifies that the root .npm-extension file matches the lockfile hash. + // The hash comes from discovering the file (no import or execution), so this holds even under ignore-extension/ignore-scripts. + const { NpmExtension } = require('@npmcli/arborist') + let fileHash = null + try { + fileHash = new NpmExtension({ root: where, extensionFile: opts.extensionFile }).hash + } catch (err) { + errors.push(`Invalid: ${err.message}`) + } + errors.push(...validateNpmExtension(virtualArb.virtualTree, fileHash)) 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' + + '`npm ci` can only install packages when your package.json and package-lock.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 + // 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') @@ -97,13 +132,24 @@ class CI extends ArboristWorkspaceCmd { }) } + // Root lifecycle scripts for `npm ci` mirror those run by `npm install`. `preinstall` runs *before* reify so that scripts can bootstrap the environment (e.g. private-registry auth) before any dependency is fetched or unpacked. The remaining scripts run after reify as they did before. + const scriptShell = this.npm.config.get('script-shell') || undefined + const runRootScript = (event) => runScript({ + path: where, + args: [], + scriptShell, + stdio: 'inherit', + event, + }) + + if (!ignoreScripts) { + await runRootScript('preinstall') + } + 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', + const postReifyScripts = [ 'install', 'postinstall', 'prepublish', // XXX should we remove this finally?? @@ -111,15 +157,8 @@ class CI extends ArboristWorkspaceCmd { '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, - }) + for (const event of postReifyScripts) { + await runRootScript(event) } } await reifyFinish(this.npm, arb) diff --git a/lib/commands/completion.js b/lib/commands/completion.js index f8c2e00c6baee..712cf7358832f 100644 --- a/lib/commands/completion.js +++ b/lib/commands/completion.js @@ -1,32 +1,24 @@ -// 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: +// 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_LINE: the full command line thus far 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: +// 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 +// 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. +// 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. +// 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') @@ -40,13 +32,12 @@ 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 command uses args differently - they represent the command line being completed, not actual arguments to this command, so we use an empty definitions object to prevent flag validation + static definitions = [] + static skipConfigValidation = true // completion for the completion command static async completion (opts) { @@ -85,20 +76,20 @@ class Completion extends BaseCommand { 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. + // 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 + // Use COMP_LINE to get words if args doesn't include flags (e.g., in tests) + const hasFlags = line.includes(' -') && !args.some(arg => arg.startsWith('-')) + const words = (hasFlags ? line.split(/\s+/) : args).map(unescape) + const word = words[w] || '' 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] + const partialWordRaw = args[w] || '' let i = partialWordRaw.length while (partialWordRaw.slice(0, i) !== partialLine.slice(-1 * i) && i > 0) { i-- @@ -121,41 +112,38 @@ class Completion extends BaseCommand { raw: args, } + // try to find the npm command and subcommand early for flag completion this helps with custom command definitions from subcommands + 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) + const cmd = parsed.argv.remain[1] + const subCmd = parsed.argv.remain[2] + if (partialWords.slice(0, -1).indexOf('--') === -1) { - if (word.charAt(0) === '-') { - return this.wrap(opts, configCompl(opts)) + if (word && word.charAt(0) === '-') { + return this.wrap(opts, configCompl(opts, cmd, subCmd, this.npm)) } if (words[w - 1] && words[w - 1].charAt(0) === '-' && - !isFlag(words[w - 1])) { + !isFlag(words[w - 1], cmd, subCmd, this.npm)) { // 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. + // 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) @@ -164,22 +152,15 @@ class Completion extends BaseCommand { return this.wrap(opts, comps) } } catch { - // it wasnt a valid command, so do nothing + // it wasn't 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. + // 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' + // e.g. 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)) } @@ -203,14 +184,10 @@ const dumpScript = async (p) => { // 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. + // 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. + // 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') { @@ -234,16 +211,66 @@ const dumpScript = async (p) => { 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 => { +// Helper to get custom definitions from a command/subcommand +const getCustomDefinitions = (cmd, subCmd) => { + if (!cmd) { + return [] + } + + try { + const command = Npm.cmd(cmd) + + // Check if the command has subcommands + if (subCmd && command.subcommands && command.subcommands[subCmd]) { + const subcommand = command.subcommands[subCmd] + // All subcommands have definitions + return subcommand.definitions + } + + // Check if the command itself has definitions + if (command.definitions) { + return command.definitions + } + } catch { + // Command not found or no definitions + } + + return [] +} + +// Helper to get all config names including aliases from custom definitions +const getCustomConfigNames = (customDefs) => { + const names = new Set() + for (const def of customDefs) { + names.add(def.key) + if (def.alias && Array.isArray(def.alias)) { + def.alias.forEach(a => names.add(a)) + } + } + return [...names] +} + +// the current word has a dash. +// Return the config names with the same number of dashes as the current word has. +const configCompl = (opts, cmd, subCmd, npm) => { 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)) + + // Get custom definitions from the command/subcommand + const customDefs = getCustomDefinitions(cmd, subCmd, npm) + const customNames = getCustomConfigNames(customDefs) + + // If there are custom definitions, return only those (new feature) + // Otherwise, return empty array (historical behavior - no global flag completion) + if (customNames.length > 0) { + const flags = customNames.filter(name => isFlag(name, cmd, subCmd, npm)) + return customNames.map(c => dashes + c) + .concat(flags.map(f => dashes + (no || 'no-') + f)) + } + + return [] } // expand with the valid values of various config values. @@ -251,16 +278,36 @@ const configCompl = opts => { const configValueCompl = () => [] // check if the thing is a flag or not. -const isFlag = word => { +const isFlag = (word, cmd, subCmd, npm) => { // 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] + + // Check custom definitions first + const customDefs = getCustomDefinitions(cmd, subCmd, npm) + + // Check if conf is in custom definitions or is an alias + let customDef = customDefs.find(d => d.key === conf) + if (!customDef) { + // Check if conf is an alias for any of the custom definitions + for (const def of customDefs) { + if (def.alias && Array.isArray(def.alias) && def.alias.includes(conf)) { + customDef = def + break + } + } + } + + if (customDef) { + const { type } = customDef + return no || + type === Boolean || + (Array.isArray(type) && type.includes(Boolean)) + } + + // No custom definitions found, should not reach here in normal flow since configCompl returns empty array when no custom defs exist + return false } // complete against the npm commands diff --git a/lib/commands/config.js b/lib/commands/config.js index 6b1447d7e8426..0a8b84aba2666 100644 --- a/lib/commands/config.js +++ b/lib/commands/config.js @@ -4,31 +4,16 @@ 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 { defaults, definitions, nerfDarts, proxyEnv } = require('@npmcli/config/lib/definitions') +const { log, output, input } = 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" +// 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 cannot "npm config get" them, and they will not display during "npm config list" const protected = [ 'auth', 'authToken', @@ -39,8 +24,7 @@ const protected = [ 'username', ] -// take an array of `[key, value, k2=v2, k3, v3, ...]` and turn into -// { key: value, k2: v2, k3: v3 } +// 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++) { @@ -125,7 +109,7 @@ class Config extends BaseCommand { const action = argv[2] switch (action) { case 'set': - // todo: complete with valid values, if possible. + // TODO: complete with valid values, if possible. if (argv.length > 3) { return [] } @@ -188,7 +172,7 @@ class Config extends BaseCommand { 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}` + `The \`${baseKey}\` option is deprecated, and cannot be set in this way${deprecated}` ) } @@ -215,7 +199,7 @@ class Config extends BaseCommand { 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`) + throw new Error(`The ${key} option is protected, and cannot be retrieved in this way`) } const pref = keys.length > 1 ? `${key}=` : '' @@ -282,7 +266,7 @@ ${defData} `.split('\n').join(EOL) await mkdir(dirname(file), { recursive: true }) await writeFile(file, tmpData, 'utf8') - await new Promise((res, rej) => { + await input.start(() => new Promise((res, rej) => { const [bin, ...args] = e.split(/\s+/) const editor = spawn(bin, [...args, file], { stdio: 'inherit' }) editor.on('exit', (code) => { @@ -291,7 +275,7 @@ ${defData} } return res() }) - }) + })) } async fix () { @@ -362,6 +346,23 @@ ${defData} } if (!long) { + const envVars = [] + + const foundEnvVars = new Set() + for (const key of Object.keys(process.env)) { + const lowerKey = key.toLowerCase() + if (proxyEnv.includes(lowerKey) && !foundEnvVars.has(lowerKey)) { + foundEnvVars.add(lowerKey) + envVars.push(`; ${key} = ${JSON.stringify(process.env[key])}`) + } + } + + if (envVars.length > 0) { + msg.push('; environment-related config', '') + msg.push(...envVars) + msg.push('') + } + msg.push( `; node bin location = ${process.execPath}`, `; node version = ${process.version}`, @@ -378,6 +379,9 @@ ${defData} const { content } = await pkgJson.normalize(this.npm.prefix).catch(() => ({ content: {} })) if (content.publishConfig) { + for (const key in content.publishConfig) { + this.npm.config.checkUnknown('publishConfig', key) + } 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.', '') diff --git a/lib/commands/dedupe.js b/lib/commands/dedupe.js index e07bcd31e894b..0b3fee45bf256 100644 --- a/lib/commands/dedupe.js +++ b/lib/commands/dedupe.js @@ -1,4 +1,6 @@ const reifyFinish = require('../utils/reify-finish.js') +const resolveAllowScripts = require('../utils/resolve-allow-scripts.js') +const { patchRelaxOpts } = require('../utils/cli-only-flag.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') // dedupe duplicated packages, or find them in the tree @@ -14,6 +16,10 @@ class Dedupe extends ArboristWorkspaceCmd { 'omit', 'include', 'ignore-scripts', + 'allow-directory', + 'allow-file', + 'allow-git', + 'allow-remote', 'audit', 'bin-links', 'fund', @@ -31,16 +37,18 @@ class Dedupe extends ArboristWorkspaceCmd { const dryRun = this.npm.config.get('dry-run') const where = this.npm.prefix const Arborist = require('@npmcli/arborist') + const { policy: allowScriptsPolicy } = await resolveAllowScripts(this.npm) 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. + // 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, + allowScripts: allowScriptsPolicy, + ...patchRelaxOpts(this.npm.config), } const arb = new Arborist(opts) await arb.dedupe(opts) diff --git a/lib/commands/deny-scripts.js b/lib/commands/deny-scripts.js new file mode 100644 index 0000000000000..53b0cdd3cc50a --- /dev/null +++ b/lib/commands/deny-scripts.js @@ -0,0 +1,10 @@ +const AllowScriptsCmd = require('../utils/allow-scripts-cmd.js') + +class DenyScripts extends AllowScriptsCmd { + static description = 'Deny install scripts for specific dependencies' + static name = 'deny-scripts' + static usage = [' [ ...]', '--all'] + static verb = 'deny' +} + +module.exports = DenyScripts diff --git a/lib/commands/deprecate.js b/lib/commands/deprecate.js index 977fd9fce11da..d8d33ad9b9d03 100644 --- a/lib/commands/deprecate.js +++ b/lib/commands/deprecate.js @@ -1,4 +1,4 @@ -const fetch = require('npm-registry-fetch') +const npmFetch = require('npm-registry-fetch') const { otplease } = require('../utils/auth.js') const npa = require('npm-package-arg') const { log } = require('proc-log') @@ -14,6 +14,7 @@ class Deprecate extends BaseCommand { static params = [ 'registry', 'otp', + 'dry-run', ] static ignoreImplicitWorkspace = true @@ -47,7 +48,7 @@ class Deprecate extends BaseCommand { } const uri = '/' + p.escapedName - const packument = await fetch.json(uri, { + const packument = await npmFetch.json(uri, { ...this.npm.flatOptions, spec: p, query: { write: true }, @@ -56,17 +57,26 @@ class Deprecate extends BaseCommand { 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, + })) } - return otplease(this.npm, this.npm.flatOptions, opts => fetch(uri, { - ...opts, - spec: p, - method: 'PUT', - body: packument, - ignoreBody: true, - })) } else { log.warn('deprecate', 'No version found for', p.rawSpec) } diff --git a/lib/commands/diff.js b/lib/commands/diff.js index 3fa8090a35046..ecc0e0aa68267 100644 --- a/lib/commands/diff.js +++ b/lib/commands/diff.js @@ -45,11 +45,7 @@ class Diff extends BaseCommand { 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) + // 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 { @@ -83,7 +79,7 @@ class Diff extends BaseCommand { try { const { content: pkg } = await pkgJson.normalize(this.prefix) name = pkg.name - } catch (e) { + } catch { log.verbose('diff', 'could not read project dir package.json') } @@ -100,24 +96,22 @@ class Diff extends BaseCommand { return this.findVersionsByPackageName(specs) } - // no arguments, defaults to comparing cwd - // to its latest published registry version + // 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')}`, + `file:${this.prefix}`, ] } - // single argument, used to compare wanted versions of an - // installed dependency or to compare the cwd to a published version + // 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 (e) { + } catch { log.verbose('diff', 'could not read project dir package.json') noPackageJson = true } @@ -125,22 +119,18 @@ class Diff extends BaseCommand { 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 + // 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')}`, + `file:${this.prefix}`, ] } - // 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 + // 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 @@ -156,7 +146,7 @@ class Diff extends BaseCommand { node = actualTree && actualTree.inventory.query('name', spec.name) .values().next().value - } catch (e) { + } catch { log.verbose('diff', 'failed to load actual install tree') } @@ -166,7 +156,7 @@ class Diff extends BaseCommand { } return [ `${spec.name}@${spec.fetchSpec}`, - `file:${this.prefix.replace(/#/g, '%23')}`, + `file:${this.prefix}`, ] } @@ -179,12 +169,11 @@ class Diff extends BaseCommand { } } - const aSpec = `file:${node.realpath.replace(/#/g, '%23')}` + const aSpec = `file:${node.realpath}` - // 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. + // finds what version of the package to compare against + // if an 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 @@ -193,11 +182,12 @@ class Diff extends BaseCommand { tryRootNodeSpec() || tryAnySpec() - // figure out what to compare against, + // 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, + _isRoot: true, }) bSpec = pickManifest( packument, @@ -212,8 +202,8 @@ class Diff extends BaseCommand { ] } else if (spec.type === 'directory') { return [ - `file:${spec.fetchSpec.replace(/#/g, '%23')}`, - `file:${this.prefix.replace(/#/g, '%23')}`, + `file:${spec.fetchSpec}`, + `file:${this.prefix}`, ] } else { throw this.usageError(`Spec type ${spec.type} not supported.`) @@ -230,7 +220,7 @@ class Diff extends BaseCommand { try { const { content: pkg } = await pkgJson.normalize(this.prefix) pkgName = pkg.name - } catch (e) { + } catch { log.verbose('diff', 'could not read project dir package.json') } @@ -241,8 +231,7 @@ class Diff extends BaseCommand { return [`${pkgName}@${a}`, `${pkgName}@${b}`] } - // otherwise uses the name from the other arg to - // figure out the spec.name of what to compare + // 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}`] } @@ -265,7 +254,7 @@ class Diff extends BaseCommand { } const arb = new Arborist(opts) actualTree = await arb.loadActual(opts) - } catch (e) { + } catch { log.verbose('diff', 'failed to load actual install tree') } @@ -281,7 +270,7 @@ class Diff extends BaseCommand { const res = !node || !node.package || !node.package.version ? spec.fetchSpec - : `file:${node.realpath.replace(/#/g, '%23')}` + : `file:${node.realpath}` return `${spec.name}@${res}` }) diff --git a/lib/commands/dist-tag.js b/lib/commands/dist-tag.js index 663f0eb44a26a..4b51e839d78aa 100644 --- a/lib/commands/dist-tag.js +++ b/lib/commands/dist-tag.js @@ -1,5 +1,5 @@ const npa = require('npm-package-arg') -const regFetch = require('npm-registry-fetch') +const npmFetch = require('npm-registry-fetch') const semver = require('semver') const { log, output } = require('proc-log') const { otplease } = require('../utils/auth.js') @@ -49,8 +49,7 @@ class DistTag extends BaseCommand { } if (!pkg) { - // when only using the pkg name the default behavior - // should be listing the existing tags + // when only using the pkg name the default behavior should be listing the existing tags return this.list(cmdName, opts) } else { throw this.usageError() @@ -77,7 +76,7 @@ class DistTag extends BaseCommand { } // anything else is just a regular dist-tag command - // so we fallback to the non-workspaces implementation + // so we fall back to the non-workspaces implementation log.warn('dist-tag', 'Ignoring workspaces for specified package') return this.exec([cmdName, pkg, tag]) } @@ -119,7 +118,7 @@ class DistTag extends BaseCommand { }, spec, } - await otplease(this.npm, reqOpts, o => regFetch(url, o)) + await otplease(this.npm, reqOpts, o => npmFetch(url, o)) output.standard(`+${t}: ${spec.name}@${version}`) } @@ -145,7 +144,7 @@ class DistTag extends BaseCommand { method: 'DELETE', spec, } - await otplease(this.npm, reqOpts, o => regFetch(url, o)) + await otplease(this.npm, reqOpts, o => npmFetch(url, o)) output.standard(`-${tag}: ${spec.name}@${version}`) } @@ -182,16 +181,15 @@ class DistTag extends BaseCommand { try { output.standard(`${name}:`) await this.list(npa(name), this.npm.flatOptions) - } catch (err) { - // set the exitCode directly, but ignore the error - // since it will have already been logged by this.list() + } 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 regFetch.json( + const data = await npmFetch.json( `/-/package/${spec.escapedName}/dist-tags`, { ...opts, 'prefer-online': true, spec } ) diff --git a/lib/commands/doctor.js b/lib/commands/doctor.js index 8fbd49b7ca8bf..203f6d156c5b8 100644 --- a/lib/commands/doctor.js +++ b/lib/commands/doctor.js @@ -1,6 +1,6 @@ const cacache = require('cacache') const { access, lstat, readdir, constants: { R_OK, W_OK, X_OK } } = require('node:fs/promises') -const fetch = require('make-fetch-happen') +const npmFetch = require('make-fetch-happen') const which = require('which') const pacote = require('pacote') const { resolve } = require('node:path') @@ -27,10 +27,9 @@ const maskLabel = mask => { return label.join(', ') } -const subcommands = [ +const checks = [ { - // Ping is left in as a legacy command but is listed as "connection" to - // make more sense to more people + // 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', @@ -100,12 +99,11 @@ class Doctor extends BaseCommand { static name = 'doctor' static params = ['registry'] static ignoreImplicitWorkspace = false - static usage = [`[${subcommands.flatMap(s => s.groups) + static skipConfigValidation = true + static usage = [`[${checks.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 @@ -128,7 +126,6 @@ class Doctor extends BaseCommand { if (!allOk) { if (this.npm.silent) { - /* eslint-disable-next-line max-len */ 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.') @@ -166,7 +163,7 @@ class Doctor extends BaseCommand { const currentRange = `^${current}` const url = 'https://nodejs.org/dist/index.json' log.info('doctor', 'Getting Node.js release information') - const res = await fetch(url, { method: 'GET', ...this.npm.flatOptions }) + 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' @@ -246,7 +243,7 @@ class Doctor extends BaseCommand { try { await access(f, mask) - } catch (er) { + } catch { ok = false const msg = `Missing permissions on ${f} (expect: ${maskLabel(mask)})` log.error('doctor', 'checkFilesPermission', msg) @@ -332,7 +329,7 @@ class Doctor extends BaseCommand { } actions (params) { - return this.constructor.subcommands.filter(subcmd => { + return checks.filter(subcmd => { if (process.platform === 'win32' && subcmd.windows === false) { return false } diff --git a/lib/commands/edit.js b/lib/commands/edit.js index b2c2ec8d2a39a..0b1a200264d98 100644 --- a/lib/commands/edit.js +++ b/lib/commands/edit.js @@ -1,6 +1,7 @@ const { resolve } = require('node:path') const { lstat } = require('node:fs/promises') const cp = require('node:child_process') +const { input } = require('proc-log') const completion = require('../utils/installed-shallow.js') const BaseCommand = require('../base-cmd.js') @@ -33,8 +34,6 @@ class Edit extends BaseCommand { static params = ['editor'] static ignoreImplicitWorkspace = false - // TODO - /* istanbul ignore next */ static async completion (opts, npm) { return completion(npm, opts) } @@ -48,16 +47,17 @@ class Edit extends BaseCommand { const dir = resolve(this.npm.dir, path) await lstat(dir) - await new Promise((res, rej) => { + await input.start(() => 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) => { + editor.on('exit', (code) => { if (code) { return rej(new Error(`editor process exited with code: ${code}`)) } - await this.npm.exec('rebuild', [dir]).then(res).catch(rej) + res() }) - }) + })) + await this.npm.exec('rebuild', [dir]) } } diff --git a/lib/commands/exec.js b/lib/commands/exec.js index 57ee8efe2c98f..23c47a0cc1ad7 100644 --- a/lib/commands/exec.js +++ b/lib/commands/exec.js @@ -1,5 +1,6 @@ const { resolve } = require('node:path') const libexec = require('libnpmexec') +const resolveAllowScripts = require('../utils/resolve-allow-scripts.js') const BaseCommand = require('../base-cmd.js') class Exec extends BaseCommand { @@ -10,6 +11,9 @@ class Exec extends BaseCommand { 'workspace', 'workspaces', 'include-workspace-root', + 'allow-scripts', + 'strict-allow-scripts', + 'dangerously-allow-all-scripts', ] static name = 'exec' @@ -46,8 +50,7 @@ class Exec extends BaseCommand { 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 + // 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 @@ -65,9 +68,8 @@ class Exec extends BaseCommand { 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. + // --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, '..') } @@ -76,13 +78,20 @@ class Exec extends BaseCommand { throw this.usageError() } + // Resolve the install-script policy from the user/global .npmrc layer + // only. The RFC requires exec/npx to ignore any project + // package.json#allowScripts; CLI flags still apply. + const { policy: allowScriptsPolicy } = await resolveAllowScripts(this.npm, { + skipProjectConfig: true, + }) + 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 + allowScripts: allowScriptsPolicy, + // 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 + args: [...args], // copy args so they don't get mutated // specify a custom command to be run instead of args[0] call, chalk, diff --git a/lib/commands/explain.js b/lib/commands/explain.js index cb0644304d2b5..3b843e3bbff6c 100644 --- a/lib/commands/explain.js +++ b/lib/commands/explain.js @@ -17,8 +17,6 @@ class Explain extends ArboristWorkspaceCmd { static ignoreImplicitWorkspace = false - // TODO - /* istanbul ignore next */ static async completion (opts, npm) { const completion = require('../utils/installed-deep.js') return completion(npm, opts) @@ -92,7 +90,7 @@ class Explain extends ArboristWorkspaceCmd { } // if it's a location, get that node - const maybeLoc = arg.replace(/\\/g, '/').replace(/\/+$/, '') + const maybeLoc = arg.replace(/\\/g, '/').replace(/(? { log.error('explore', `It doesn't look like ${pkgname} is installed.`) diff --git a/lib/commands/find-dupes.js b/lib/commands/find-dupes.js index 735ac7c4a7ed0..15b312e6a7aec 100644 --- a/lib/commands/find-dupes.js +++ b/lib/commands/find-dupes.js @@ -1,6 +1,5 @@ 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' diff --git a/lib/commands/fund.js b/lib/commands/fund.js index 8c194dac80b49..6f5ed8af01505 100644 --- a/lib/commands/fund.js +++ b/lib/commands/fund.js @@ -34,8 +34,6 @@ class Fund extends ArboristWorkspaceCmd { return `${msg}\`` } - // TODO - /* istanbul ignore next */ static async completion (opts, npm) { const completion = require('../utils/installed-deep.js') return completion(npm, opts) @@ -100,8 +98,7 @@ class Fund extends ArboristWorkspaceCmd { const result = depth({ tree: fundingInfo, - // composes human readable package name - // and creates a new archy item for readable output + // 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 || {} @@ -128,8 +125,7 @@ class Fund extends ArboristWorkspaceCmd { return item }, - // puts child nodes back into returned archy - // output while also filtering out missing items + // puts child nodes back into returned archy output while also filtering out missing items leave: (item, children) => { if (item) { item.nodes = children.filter(Boolean) @@ -138,8 +134,7 @@ class Fund extends ArboristWorkspaceCmd { return item }, - // turns tree-like object return by libnpmfund - // into children to be properly read by treeverse + // 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, @@ -168,8 +163,7 @@ class Fund extends ArboristWorkspaceCmd { } } } else { - // tries to retrieve a package from arborist inventory - // by matching resulted package name from the provided spec + // 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)) diff --git a/lib/commands/get.js b/lib/commands/get.js index 4191f2c973e7d..e111d7f2f54c8 100644 --- a/lib/commands/get.js +++ b/lib/commands/get.js @@ -8,8 +8,6 @@ class Get extends BaseCommand { static params = ['long'] static ignoreImplicitWorkspace = false - // TODO - /* istanbul ignore next */ static async completion (opts) { const Config = Npm.cmd('config') return Config.completion(opts) diff --git a/lib/commands/help-search.js b/lib/commands/help-search.js index 72dd03ac7406e..cb8075918dba1 100644 --- a/lib/commands/help-search.js +++ b/lib/commands/help-search.js @@ -53,7 +53,8 @@ class HelpSearch extends BaseCommand { // 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. + // otherwise, set the line to null + // finally, remove the nulls for (let i = 0; i < lines.length; i++) { const line = lines[i] const nextLine = lines[i + 1] @@ -123,11 +124,9 @@ class HelpSearch extends BaseCommand { }) } - // sort results by number of results found, then by number of hits - // then by number of matching lines + // 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 + // 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 @@ -163,18 +162,18 @@ class HelpSearch extends BaseCommand { return } - const hilitLine = [] + const highlightLine = [] 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)) + highlightLine.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)) + highlightLine.push(this.npm.chalk.blue(word)) p += f.length + arg.length } } - out.push(hilitLine.join('') + '\n') + out.push(highlightLine.join('') + '\n') }) return out.join('') diff --git a/lib/commands/help.js b/lib/commands/help.js index 057090da0036c..d520dd1cceb45 100644 --- a/lib/commands/help.js +++ b/lib/commands/help.js @@ -10,12 +10,10 @@ 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 +// 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 +// hardcoded names for man sections +// 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', @@ -27,6 +25,7 @@ class Help extends BaseCommand { static name = 'help' static usage = [' []'] static params = ['viewer'] + static skipConfigValidation = true static async completion (opts, npm) { if (opts.conf.argv.remain.length > 2) { @@ -46,8 +45,7 @@ class Help extends BaseCommand { } 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 + // 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) { @@ -66,8 +64,7 @@ class Help extends BaseCommand { 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. + // 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) { diff --git a/lib/commands/hook.js b/lib/commands/hook.js deleted file mode 100644 index 5793b974197c8..0000000000000 --- a/lib/commands/hook.js +++ /dev/null @@ -1,109 +0,0 @@ -const hookApi = require('libnpmhook') -const { otplease } = require('../utils/auth.js') -const relativeDate = require('tiny-relative-date') -const { output } = require('proc-log') -const BaseCommand = require('../base-cmd.js') - -class Hook extends BaseCommand { - static description = 'Manage registry hooks' - static name = 'hook' - static params = [ - 'registry', - 'otp', - ] - - static usage = [ - 'add [--type=]', - 'ls [pkg]', - 'rm ', - 'update ', - ] - - async exec (args) { - return otplease(this.npm, { ...this.npm.flatOptions }, (opts) => { - switch (args[0]) { - case 'add': - return this.add(args[1], args[2], args[3], opts) - case 'ls': - return this.ls(args[1], opts) - case 'rm': - return this.rm(args[1], opts) - case 'update': - case 'up': - return this.update(args[1], args[2], args[3], opts) - default: - throw this.usageError() - } - }) - } - - async add (pkg, uri, secret, opts) { - const hook = await hookApi.add(pkg, uri, secret, opts) - if (opts.json) { - output.buffer(hook) - } else if (opts.parseable) { - output.standard(Object.keys(hook).join('\t')) - output.standard(Object.keys(hook).map(k => hook[k]).join('\t')) - } else if (!this.npm.silent) { - output.standard(`+ ${this.hookName(hook)} ${opts.unicode ? ' ➜ ' : ' -> '} ${hook.endpoint}`) - } - } - - async ls (pkg, opts) { - const hooks = await hookApi.ls({ ...opts, package: pkg }) - - if (opts.json) { - output.buffer(hooks) - } else if (opts.parseable) { - output.standard(Object.keys(hooks[0]).join('\t')) - hooks.forEach(hook => { - output.standard(Object.keys(hook).map(k => hook[k]).join('\t')) - }) - } else if (!hooks.length) { - output.standard("You don't have any hooks configured yet.") - } else if (!this.npm.silent) { - output.standard(`You have ${hooks.length} hook${hooks.length !== 1 ? 's' : ''} configured.`) - - for (const hook of hooks) { - output.standard(`Hook ${hook.id}: ${this.hookName(hook)}`) - output.standard(`Endpoint: ${hook.endpoint}`) - if (hook.last_delivery) { - /* eslint-disable-next-line max-len */ - output.standard(`Triggered ${relativeDate(hook.last_delivery)}, response code was "${hook.response_code}"\n`) - } else { - output.standard('Never triggered\n') - } - } - } - } - - async rm (id, opts) { - const hook = await hookApi.rm(id, opts) - if (opts.json) { - output.buffer(hook) - } else if (opts.parseable) { - output.standard(Object.keys(hook).join('\t')) - output.standard(Object.keys(hook).map(k => hook[k]).join('\t')) - } else if (!this.npm.silent) { - output.standard(`- ${this.hookName(hook)} ${opts.unicode ? ' ✘ ' : ' X '} ${hook.endpoint}`) - } - } - - async update (id, uri, secret, opts) { - const hook = await hookApi.update(id, uri, secret, opts) - if (opts.json) { - output.buffer(hook) - } else if (opts.parseable) { - output.standard(Object.keys(hook).join('\t')) - output.standard(Object.keys(hook).map(k => hook[k]).join('\t')) - } else if (!this.npm.silent) { - output.standard(`+ ${this.hookName(hook)} ${opts.unicode ? ' ➜ ' : ' -> '} ${hook.endpoint}`) - } - } - - hookName (hook) { - return `${hook.type === 'owner' ? '~' : ''}${hook.name}` - } -} - -module.exports = Hook diff --git a/lib/commands/init.js b/lib/commands/init.js index b8ef3e59ccf29..17ae655223fc7 100644 --- a/lib/commands/init.js +++ b/lib/commands/init.js @@ -19,7 +19,9 @@ class Init extends BaseCommand { 'init-author-url', 'init-license', 'init-module', + 'init-type', 'init-version', + 'init-private', 'yes', 'force', 'scope', @@ -31,7 +33,7 @@ class Init extends BaseCommand { static name = 'init' static usage = [ - ' (same as `npx `)', + ' (same as `npx create-`)', '<@scope> (same as `npx <@scope>/create`)', ] @@ -54,9 +56,8 @@ class Init extends BaseCommand { 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 + // 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`.') @@ -64,8 +65,7 @@ class Init extends BaseCommand { throw err }) - // these are workspaces that are being created, so we cant use - // this.setWorkspaces() + // these are workspaces that are being created, so we can't use this.setWorkspaces() const filters = this.npm.config.get('workspace') const wPath = filterArg => resolve(this.npm.localPrefix, filterArg) @@ -132,8 +132,14 @@ class Init extends BaseCommand { const scriptShell = this.npm.config.get('script-shell') || undefined const yes = this.npm.config.get('yes') + // only send the init-private flag if it is set + const opts = { ...flatOptions } + if (this.npm.config.isDefault('init-private')) { + delete opts.initPrivate + } + await libexec({ - ...flatOptions, + ...opts, args: newArgs, localBin, globalBin, @@ -153,11 +159,9 @@ class Init extends BaseCommand { '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.', + '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.', + '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')) @@ -169,6 +173,7 @@ class Init extends BaseCommand { return data } catch (er) { if (er.message === 'canceled') { + output.flush() log.warn('init', 'canceled') } else { throw er @@ -186,13 +191,10 @@ class Init extends BaseCommand { } } - // 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 + // 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 (err) { + } catch { return } diff --git a/lib/commands/install-ci-test.js b/lib/commands/install-ci-test.js index 4b9dd269f8c74..2503d4ddbf480 100644 --- a/lib/commands/install-ci-test.js +++ b/lib/commands/install-ci-test.js @@ -1,7 +1,5 @@ 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' diff --git a/lib/commands/install-test.js b/lib/commands/install-test.js index e21ca7c929c55..60335ac0d8f65 100644 --- a/lib/commands/install-test.js +++ b/lib/commands/install-test.js @@ -1,7 +1,5 @@ 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' diff --git a/lib/commands/install.js b/lib/commands/install.js index 24e5f6819b314..2fd9bc8d5cd7a 100644 --- a/lib/commands/install.js +++ b/lib/commands/install.js @@ -5,14 +5,16 @@ const runScript = require('@npmcli/run-script') const pacote = require('pacote') const checks = require('npm-install-checks') const reifyFinish = require('../utils/reify-finish.js') +const resolveAllowScripts = require('../utils/resolve-allow-scripts.js') +const strictAllowScriptsPreflight = require('../utils/strict-allow-scripts-preflight.js') +const { patchRelaxOpts } = require('../utils/cli-only-flag.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 + // 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', @@ -28,7 +30,17 @@ class Install extends ArboristWorkspaceCmd { 'package-lock-only', 'foreground-scripts', 'ignore-scripts', + 'allow-directory', + 'allow-file', + 'allow-git', + 'allow-remote', + 'allow-scripts', + 'strict-allow-scripts', + 'dangerously-allow-all-scripts', 'audit', + 'before', + 'min-release-age', + 'min-release-age-exclude', 'bin-links', 'fund', 'dry-run', @@ -51,10 +63,8 @@ class Install extends ArboristWorkspaceCmd { } 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. + // 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) || '/' @@ -68,7 +78,7 @@ class Install extends ArboristWorkspaceCmd { const contents = await readdir(join(partialPath, sibling)) const result = (contents.indexOf('package.json') !== -1) return result - } catch (er) { + } catch { return false } } @@ -86,13 +96,11 @@ class Install extends ArboristWorkspaceCmd { } // no matches return [] - } catch (er) { + } 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 + // Note: there used to be registry completion here, but it stopped making sense somewhere around 50,000 packages on the registry } async exec (args) { @@ -115,7 +123,6 @@ class Install extends ArboristWorkspaceCmd { if (forced) { log.warn( 'install', - /* eslint-disable-next-line max-len */ `Forcing global npm install with incompatible version ${npmManifest.version} into node ${process.version}` ) } else { @@ -128,30 +135,48 @@ class Install extends ArboristWorkspaceCmd { args = args.filter(a => resolve(a) !== this.npm.prefix) // `npm i -g` => "install this package globally" - if (where === globalTop && !args.length) { + if (isGlobalInstall && !args.length) { args = ['.'] } - // throw usage error if trying to install empty package - // name to global space, e.g: `npm i -g ""` + // 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 { policy: allowScriptsPolicy } = await resolveAllowScripts(this.npm) const opts = { ...this.npm.flatOptions, auditLevel: null, path: where, add: args, workspaces: this.workspaceNames, + allowScripts: allowScriptsPolicy, + // patch relax flags are honored only when passed on the command line + ...patchRelaxOpts(this.npm.config), } + + // Root lifecycle scripts only run for a bare `npm install` in a local project. `preinstall` runs *before* Arborist touches the filesystem so that scripts can bootstrap the environment (e.g. set up private-registry auth, generate files consumed during resolution) before dependencies are fetched or unpacked. The remaining scripts run after reify as they did before. + const runRootLifecycle = !args.length && !isGlobalInstall && !ignoreScripts + const runRootScript = (event) => runScript({ + path: where, + args: [], + scriptShell, + stdio: 'inherit', + event, + }) + + if (runRootLifecycle) { + await runRootScript('preinstall') + } + const arb = new Arborist(opts) + await strictAllowScriptsPreflight({ arb, npm: this.npm, idealTreeOpts: opts }) await arb.reify(opts) - if (!args.length && !isGlobalInstall && !ignoreScripts) { - const scripts = [ - 'preinstall', + if (runRootLifecycle) { + const postReifyScripts = [ 'install', 'postinstall', 'prepublish', // XXX(npm9) should we remove this finally?? @@ -159,14 +184,8 @@ class Install extends ArboristWorkspaceCmd { 'prepare', 'postprepare', ] - for (const event of scripts) { - await runScript({ - path: where, - args: [], - scriptShell, - stdio: 'inherit', - event, - }) + for (const event of postReifyScripts) { + await runRootScript(event) } } await reifyFinish(this.npm, arb) diff --git a/lib/commands/link.js b/lib/commands/link.js index 8a41548d7f108..b1169e0233972 100644 --- a/lib/commands/link.js +++ b/lib/commands/link.js @@ -4,6 +4,8 @@ const npa = require('npm-package-arg') const pkgJson = require('@npmcli/package-json') const semver = require('semver') const reifyFinish = require('../utils/reify-finish.js') +const resolveAllowScripts = require('../utils/resolve-allow-scripts.js') +const { patchRelaxOpts } = require('../utils/cli-only-flag.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') class Link extends ArboristWorkspaceCmd { @@ -25,6 +27,10 @@ class Link extends ArboristWorkspaceCmd { 'omit', 'include', 'ignore-scripts', + 'allow-directory', + 'allow-file', + 'allow-git', + 'allow-remote', 'audit', 'bin-links', 'fund', @@ -60,12 +66,12 @@ class Link extends ArboristWorkspaceCmd { } async linkInstall (args) { - // load current packages from the global space, - // and then add symlinks installs locally + // 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, + ...patchRelaxOpts(this.npm.config), Arborist, path: globalTop, global: true, @@ -79,8 +85,7 @@ class Link extends ArboristWorkspaceCmd { !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 + // 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({ @@ -101,8 +106,7 @@ class Link extends ArboristWorkspaceCmd { } } - // npm link should not save=true by default unless you're - // using any of --save-dev or other types + // 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' && @@ -114,19 +118,25 @@ class Link extends ArboristWorkspaceCmd { ) // create a new arborist instance for the local prefix and // reify all the pending names as symlinks there + const { policy: allowScriptsPolicy } = await resolveAllowScripts(this.npm) const localArb = new Arborist({ ...this.npm.flatOptions, + ...patchRelaxOpts(this.npm.config), prune: false, path: this.npm.prefix, save, + // Arborist reads this.options.workspaces (set at construction) to decide which node receives the add, so it must be set here, not only at reify time. + workspaces: this.workspaceNames, + allowScripts: allowScriptsPolicy, }) 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')}`), + add: names.map(l => `file:${resolve(globalTop, 'node_modules', l)}`), save, workspaces: this.workspaceNames, + allowScripts: allowScriptsPolicy, }) await reifyFinish(this.npm, localArb) @@ -135,11 +145,12 @@ class Link extends ArboristWorkspaceCmd { 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 add = paths.map(path => `file:${path}`) const globalTop = resolve(this.npm.globalDir, '..') const Arborist = require('@npmcli/arborist') const arb = new Arborist({ ...this.npm.flatOptions, + ...patchRelaxOpts(this.npm.config), Arborist, path: globalTop, global: true, @@ -150,8 +161,7 @@ class Link extends ArboristWorkspaceCmd { await reifyFinish(this.npm, arb) } - // Returns a list of items that can't be fulfilled by - // things found in the current arborist inventory + // 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) @@ -162,8 +172,8 @@ class Link extends ArboristWorkspaceCmd { 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 + // 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 */ @@ -176,8 +186,7 @@ class Link extends ArboristWorkspaceCmd { return argFound }) - // remote nodes from the loaded tree in order - // to avoid dropping them later when reifying + // remote nodes from the loaded tree in order to avoid dropping them later when reifying for (const node of foundNodes) { node.parent = null } diff --git a/lib/commands/ls.js b/lib/commands/ls.js index 417cb1b40d8c2..e222331d09e3e 100644 --- a/lib/commands/ls.js +++ b/lib/commands/ls.js @@ -39,8 +39,6 @@ class LS extends ArboristWorkspaceCmd { ...super.params, ] - // TODO - /* istanbul ignore next */ static async completion (opts, npm) { const completion = require('../utils/installed-deep.js') return completion(npm, opts) @@ -59,6 +57,7 @@ class LS extends ArboristWorkspaceCmd { const unicode = this.npm.config.get('unicode') const packageLockOnly = this.npm.config.get('package-lock-only') const workspacesEnabled = this.npm.flatOptions.workspacesEnabled + const installStrategy = this.npm.flatOptions.installStrategy const path = global ? resolve(this.npm.globalDir, '..') : this.npm.prefix @@ -73,8 +72,7 @@ class LS extends ArboristWorkspaceCmd { 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. + // 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) @@ -121,9 +119,7 @@ class LS extends ArboristWorkspaceCmd { // 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` + // 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 @@ -138,6 +134,9 @@ class LS extends ArboristWorkspaceCmd { link, omit, }) : () => true) + .filter(installStrategy === 'linked' + ? filterLinkedStrategyEdges({ node, currentDepth }) + : () => true) .map(mapEdgesToNodes({ seenPaths })) .concat(appendExtraneousChildren({ node, seenPaths })) .sort(sortAlphabetically) @@ -148,8 +147,7 @@ class LS extends ArboristWorkspaceCmd { seenNodes, })) }, - // visit each `node` of the `tree`, returning an `item` - these are - // the elements that will be used to build the final output + // 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 }) @@ -233,7 +231,7 @@ const isGitNode = (node) => { try { const { type } = npa(node.resolved) return type === 'git' || type === 'hosted' - } catch (err) { + } catch { return false } } @@ -262,14 +260,12 @@ const getProblems = (node, { global }) => { return problems } -// annotates _parent and _include metadata into the resulting -// item obj allowing for filtering out results during output +// 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 + // 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] @@ -282,6 +278,21 @@ const augmentItemWithIncludeMetadata = (node, item) => { return item } +// Render a manifest-extension provenance object as a short "field.name" list, empty when none. +const formatExtensionApplied = (applied) => { + if (!applied) { + return '' + } + const fields = ['dependencies', 'optionalDependencies', 'peerDependencies', 'peerDependenciesMeta'] + const parts = [] + for (const field of fields) { + for (const name of applied[field] || []) { + parts.push(`${field}.${name}`) + } + } + return parts.join(', ') +} + const getHumanOutputItem = (node, { args, chalk, global, long }) => { const { pkgid, path } = node const workspacePkgId = chalk.blueBright(pkgid) @@ -337,6 +348,21 @@ const getHumanOutputItem = (node, { args, chalk, global, long }) => { ? ' ' + chalk.dim('overridden') : '' ) + + ( + node.patched + ? ' ' + chalk.cyan(`[patched: ${node.patched.path}]`) + : '' + ) + + ( + formatExtensionApplied(node.packageExtensionsApplied) + ? ' ' + chalk.dim(`packageExtensions: ${formatExtensionApplied(node.packageExtensionsApplied)}`) + : '' + ) + + ( + formatExtensionApplied(node.npmExtensionApplied) + ? ' ' + chalk.dim(`.npm-extension: ${formatExtensionApplied(node.npmExtensionApplied)}`) + : '' + ) + (isGitNode(node) ? ` (${node.resolved})` : '') + (node.isLink ? ` -> ${relativePrefix}${targetLocation}` : '') + (long ? `\n${node.package.description || ''}` : '') @@ -355,13 +381,20 @@ const getJsonOutputItem = (node, { global, long }) => { 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 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 } + if (node.packageExtensionsApplied) { + item.packageExtensionsApplied = node.packageExtensionsApplied + } + + if (node.npmExtensionApplied) { + item.npmExtensionApplied = node.npmExtensionApplied + } + item[_name] = node.name // special formatting for top-level package name @@ -394,6 +427,10 @@ const getJsonOutputItem = (node, { global, long }) => { item.invalid = node[_invalid] } + if (node.patched) { + item.patched = node.patched.path + } + if (node[_missing] && !isOptional(node)) { item.required = node[_required] item.missing = true @@ -405,6 +442,34 @@ const getJsonOutputItem = (node, { global, long }) => { return augmentItemWithIncludeMetadata(node, item) } +// In linked strategy, two types of edges produce false UNMET DEPENDENCYs: +// 1. Workspace edges for undeclared workspaces: the lockfile records edges from root to ALL workspaces, but only declared workspaces are hoisted to root/node_modules in linked mode. Undeclared ones are intentionally absent. +// 2. Dev edges on non-root packages: store package link targets have no parent in the node tree, so they are treated as "top" nodes and their devDependencies are loaded as edges. Those devDeps are never installed. +const filterLinkedStrategyEdges = ({ node, currentDepth }) => { + const declaredDeps = new Set(Object.keys(Object.assign({}, + node.target.package.dependencies, + node.target.package.devDependencies, + node.target.package.optionalDependencies, + node.target.package.peerDependencies + ))) + + return (edge) => { + // Skip workspace edges for undeclared workspaces at root level + if (currentDepth === 0 && edge.type === 'workspace' && edge.missing) { + if (!declaredDeps.has(edge.name)) { + return false + } + } + + // Skip dev edges for non-root packages (store packages) + if (currentDepth > 0 && edge.dev) { + return false + } + + return true + } +} + const filterByEdgesTypes = ({ link, omit }) => (edge) => { for (const omitType of omit) { if (edge[omitType]) { @@ -423,18 +488,15 @@ const appendExtraneousChildren = ({ node, seenPaths }) => 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 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 + // 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) } @@ -463,9 +525,7 @@ const augmentNodesWithMetadata = ({ 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 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) @@ -490,18 +550,14 @@ const augmentNodesWithMetadata = ({ 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 + // _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 + // _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` + // _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 @@ -510,9 +566,7 @@ const augmentNodesWithMetadata = ({ 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) + // 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]) { @@ -541,13 +595,10 @@ const jsonOutput = ({ path, problems, result, rootError, seenItems }) => { 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) + // 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 + // 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 = {} diff --git a/lib/commands/org.js b/lib/commands/org.js index 613498056f556..4ece9e19d60bc 100644 --- a/lib/commands/org.js +++ b/lib/commands/org.js @@ -61,7 +61,6 @@ class Org extends BaseCommand { if (!['owner', 'admin', 'developer'].find(x => x === role)) { throw new Error( - /* eslint-disable-next-line max-len */ 'Third argument `role` must be one of `owner`, `admin`, or `developer`, with `developer` being the default value if omitted.' ) } @@ -111,9 +110,7 @@ class Org extends BaseCommand { 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.` + `Successfully removed ${user} from ${org}. You now have ${userCount} member${userCount === 1 ? '' : 's'} in this org.` ) } } diff --git a/lib/commands/outdated.js b/lib/commands/outdated.js index c401c0d50a5cd..714b3ab64da4d 100644 --- a/lib/commands/outdated.js +++ b/lib/commands/outdated.js @@ -4,6 +4,7 @@ const pacote = require('pacote') const table = require('text-table') const npa = require('npm-package-arg') const pickManifest = require('npm-pick-manifest') +const { isReleaseAgeExcluded } = require('@npmcli/arborist/lib/release-age-exclude.js') const { output } = require('proc-log') const localeCompare = require('@isaacs/string-locale-compare')('en') const ArboristWorkspaceCmd = require('../arborist-cmd.js') @@ -30,6 +31,9 @@ class Outdated extends ArboristWorkspaceCmd { 'parseable', 'global', 'workspace', + 'before', + 'min-release-age', + 'min-release-age-exclude', ] #tree @@ -94,8 +98,7 @@ class Outdated extends ArboristWorkspaceCmd { } #getEdges (nodes, type) { - // when no nodes are provided then it should only read direct deps - // from the root node and its workspaces direct dependencies + // 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() @@ -169,8 +172,7 @@ class Outdated extends ArboristWorkspaceCmd { } } - // deps different from prod not currently - // on disk are not included in the output + // deps different from prod not currently on disk are not included in the output if (edge.error === MISSING && type !== 'dependencies') { return } @@ -183,8 +185,14 @@ class Outdated extends ArboristWorkspaceCmd { 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) + const { minReleaseAgeExclude } = this.npm.flatOptions + // Packages matching `min-release-age-exclude` resolve to their newest + // version, so drop the `before` constraint for them. + const pickOpts = isReleaseAgeExcluded(packument.name, minReleaseAgeExclude) + ? { ...this.npm.flatOptions, before: null } + : this.npm.flatOptions + const wanted = pickManifest(packument, expected, pickOpts) + const latest = pickManifest(packument, '*', pickOpts) if (!current || current !== wanted.version || wanted.version !== latest.version) { this.#list.push({ name: alias ? edge.spec.replace('npm', edge.name) : edge.name, @@ -195,14 +203,17 @@ class Outdated extends ArboristWorkspaceCmd { wanted: wanted.version, latest: latest.version, workspaceDependent: edge.from?.isWorkspace ? edge.from.pkgid : null, + dependedByLocation: edge.from?.name + ? edge.from?.location + : 'global', 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)) { + // silently catch and ignore ETARGET, E403 & E404 errors + // deps are just skipped + if (!['ETARGET', 'E403', 'E404'].includes(err.code)) { throw err } } @@ -226,7 +237,7 @@ class Outdated extends ArboristWorkspaceCmd { 'Latest', 'Location', 'Depended by', - ...long ? ['Package Type', 'Homepage'] : [], + ...long ? ['Package Type', 'Homepage', 'Depended By Location'] : [], ].map(h => bold.underline(h)), ...list.map((d) => [ d.current === d.wanted ? yellow(d.name) : red(d.name), @@ -235,7 +246,7 @@ class Outdated extends ArboristWorkspaceCmd { blue(d.latest), d.location ?? '-', d.workspaceDependent ? blue(d.workspaceDependent) : d.dependent, - ...long ? [d.type, blue(d.homepage ?? '')] : [], + ...long ? [d.type, blue(d.homepage ?? ''), d.dependedByLocation] : [], ]), ], { align: ['l', 'r', 'r', 'r', 'l'], @@ -252,15 +263,13 @@ class Outdated extends ArboristWorkspaceCmd { d.current ? `${d.name}@${d.current}` : 'MISSING', `${d.name}@${d.latest}`, d.dependent, - ...this.npm.config.get('long') ? [d.type, d.homepage] : [], + ...this.npm.config.get('long') ? [d.type, d.homepage, d.dependedByLocation] : [], ].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 + // TODO(BREAKING_CHANGE): this should just return an array. + // It's a list and turning 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, @@ -268,10 +277,13 @@ class Outdated extends ArboristWorkspaceCmd { latest: d.latest, dependent: d.dependent, location: d.path, - ...this.npm.config.get('long') ? { type: d.type, homepage: d.homepage } : {}, + ...this.npm.config.get('long') ? { + type: d.type, + homepage: d.homepage, + dependedByLocation: d.dependedByLocation } : {}, } acc[d.name] = acc[d.name] - // If this item alread has an outdated dep then we turn it into an array + // If this item already 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 diff --git a/lib/commands/owner.js b/lib/commands/owner.js index 0f12cf9293c30..d53c1c97b77fc 100644 --- a/lib/commands/owner.js +++ b/lib/commands/owner.js @@ -63,6 +63,7 @@ class Owner extends BaseCommand { const data = await pacote.packument(spec, { ...npm.flatOptions, fullMetadata: true, + _isRoot: true, }) if (data && data.maintainers && data.maintainers.length) { return data.maintainers.map(m => m.name) @@ -112,7 +113,13 @@ class Owner extends BaseCommand { const spec = npa(pkg) try { - const packumentOpts = { ...this.npm.flatOptions, fullMetadata: true, preferOnline: true } + const packumentOpts = { + ...this.npm.flatOptions, + fullMetadata: + true, + preferOnline: true, + _isRoot: true, + } const { maintainers } = await pacote.packument(spec, packumentOpts) if (!maintainers || !maintainers.length) { output.standard('no admin found') @@ -166,6 +173,7 @@ class Owner extends BaseCommand { ...this.npm.flatOptions, fullMetadata: true, preferOnline: true, + _isRoot: true, }) const owners = data.maintainers || [] diff --git a/lib/commands/pack.js b/lib/commands/pack.js index 79e7f49f819ec..8a4d2f0f74382 100644 --- a/lib/commands/pack.js +++ b/lib/commands/pack.js @@ -15,6 +15,7 @@ class Pack extends BaseCommand { 'workspace', 'workspaces', 'include-workspace-root', + 'ignore-scripts', ] static usage = [''] @@ -29,20 +30,24 @@ class Pack extends BaseCommand { const unicode = this.npm.config.get('unicode') const json = this.npm.config.get('json') - // Get the manifests and filenames first so we can bail early on manifest - // errors before making any tarballs + 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) + const manifest = await pacote.manifest(spec, { + ...this.npm.flatOptions, + Arborist, + preferOnline: true, + _isRoot: true, + }) 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 + // 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, { @@ -50,16 +55,15 @@ class Pack extends BaseCommand { foregroundScripts: this.npm.config.isDefault('foreground-scripts') ? true : this.npm.config.get('foreground-scripts'), + preferOnline: true, 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 }) + for (const tar of tarballs) { + logTar(tar, { unicode, json, key: tar.name }) if (!json) { output.standard(tar.filename.replace(/^@/, '').replace(/\//, '-')) } @@ -67,9 +71,7 @@ class Pack extends BaseCommand { } async execWorkspaces (args) { - // If they either ask for nothing, or explicitly include '.' in the args, - // we effectively translate that into each workspace requested - + // 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) { diff --git a/lib/commands/patch.js b/lib/commands/patch.js new file mode 100644 index 0000000000000..67b8bc4555572 --- /dev/null +++ b/lib/commands/patch.js @@ -0,0 +1,740 @@ +const { resolve, relative, join, dirname, basename, isAbsolute, sep } = require('node:path') +const { tmpdir } = require('node:os') +const { cp, mkdir, mkdtemp, readFile, rm, writeFile } = require('node:fs/promises') +const pacote = require('pacote') +const npa = require('npm-package-arg') +const semver = require('semver') +const git = require('@npmcli/git') +const PackageJson = require('@npmcli/package-json') +const { log, output } = require('proc-log') +const { matchSelector, parseSelector } = require('@npmcli/arborist/lib/patched-dependencies.js') +const { applyPatchToDir } = require('@npmcli/arborist/lib/patch.js') +const { patchRelaxOpts } = require('../utils/cli-only-flag.js') +const BaseCommand = require('../base-cmd.js') +const { diffDirs } = require('../utils/patch-diff.js') +const reifyFinish = require('../utils/reify-finish.js') + +const SUBCOMMANDS = ['add', 'commit', 'update', 'ls', 'rm'] + +// Marker left in a conflicted update edit dir so the finalizing commit drops the old exact selector. +const UPDATE_MARKER = '.npm-patch-update.json' + +// fs.cp filter that skips a git working directory. +const notGitDir = src => !src.split(sep).includes('.git') + +// Build the selector key stored in patchedDependencies, e.g. lodash@4.17.21. +const selectorKey = (name, version) => `${name}@${version}` + +// Posix-relative path to a patch file inside patches-dir for name@version. +const patchFilePath = (patchesDir, name, version) => + `${patchesDir}/${name}@${version}.patch`.split('\\').join('/') + +// Recover the exact version a patch file was authored against from its name. +// commit always writes @.patch, so the baseline is encoded there. +const patchFileVersion = patchPath => { + const { spec } = parseSelector(basename(patchPath).replace(/\.patch$/, '')) + return semver.valid(spec) +} + +const patchErr = (message, code, extra = {}) => + Object.assign(new Error(message), { code, ...extra }) + +// The project-root-relative posix path for abs, or null if abs escapes the root. +const containedRelative = (root, abs) => { + const rel = relative(root, abs).split('\\').join('/') + return (!rel || rel.startsWith('..') || isAbsolute(rel)) ? null : rel +} + +class Patch extends BaseCommand { + static description = 'Apply local patches to installed dependencies' + static name = 'patch' + static params = [ + 'patches-dir', + 'allow-unused-patches', + 'ignore-patch-failures', + 'edit-dir', + 'ignore-existing', + 'keep-edit-dir', + 'to', + 'registry', + ] + + static usage = [ + '[@]', + 'add [@] [--edit-dir ] [--ignore-existing]', + 'commit [--patches-dir ] [--keep-edit-dir]', + 'update [@] [--to ] [--patches-dir ]', + 'ls', + 'rm [@]', + ] + + static async completion (opts) { + if (opts.conf.argv.remain.length === 2) { + return SUBCOMMANDS + } + return [] + } + + async exec (args) { + const [sub, ...rest] = args + if (!sub) { + throw this.usageError() + } + // explicit subcommand, else treat the bare arg as `patch add ` + if (SUBCOMMANDS.includes(sub)) { + return this[sub](rest) + } + return this.add(args) + } + + get #root () { + return this.npm.localPrefix + } + + #newArborist (opts = {}) { + const Arborist = require('@npmcli/arborist') + return new Arborist({ + ...this.npm.flatOptions, + ...patchRelaxOpts(this.npm.config), + path: this.#root, + ...opts, + }) + } + + async #loadActual () { + return this.#newArborist().loadActual() + } + + // Resolve a user spec to a concrete registry name@version to patch. + async #resolveTarget (spec) { + const parsed = npa(spec) + if (parsed.type && !parsed.registry) { + throw this.#nonRegistryError(spec) + } + + const { name } = parsed + const tree = await this.#loadActual() + // group every installed node by version so mixed-source duplicates are seen + const installed = new Map() + for (const node of tree.inventory.values()) { + if (node.name === name && !node.isProjectRoot && node.version) { + const nodes = installed.get(node.version) || [] + nodes.push(node) + installed.set(node.version, nodes) + } + } + + // a version cannot be patched if a consumer depends on it through a non-registry spec (file:, git:, http(s)); npm: aliases stay registry. + // checking the edges (not isRegistryDependency) avoids rejecting edgeless store nodes and linked symlinks, which are registry deps. + const ensureRegistry = version => { + const nodes = installed.get(version) || [] + if (nodes.some(n => [...n.edgesIn].some(e => e.spec && !npa(e.spec).registry))) { + throw this.#nonRegistryError(`${name}@${version}`) + } + } + + // an explicit version/range is honored even when not present in the tree + if (parsed.rawSpec && parsed.rawSpec !== '*' && parsed.rawSpec !== 'latest') { + const exact = semver.valid(parsed.fetchSpec) + if (exact) { + ensureRegistry(exact) + return { name, version: exact } + } + const matches = [...installed.keys()].filter(v => semver.satisfies(v, parsed.fetchSpec)) + if (matches.length > 1) { + throw this.#ambiguousError(name, matches, installed) + } + if (matches.length === 1) { + ensureRegistry(matches[0]) + return { name, version: matches[0] } + } + // resolve the range against the registry + const mani = await pacote.manifest(spec, this.npm.flatOptions) + return { name: mani.name, version: mani.version } + } + + if (installed.size === 0) { + throw Object.assign( + new Error(`No installed version of "${name}" found. ` + + `Run "npm install" first, or pass an explicit version.`), + { code: 'EPATCHNOTINSTALLED' } + ) + } + if (installed.size > 1) { + throw this.#ambiguousError(name, [...installed.keys()], installed) + } + const [version] = [...installed.keys()] + ensureRegistry(version) + return { name, version } + } + + #nonRegistryError (label) { + return Object.assign( + new Error(`Cannot patch non-registry dependency "${label}". ` + + `Only registry dependencies can be patched; edit the source directly.`), + { code: 'EPATCHNONREGISTRY' } + ) + } + + #ambiguousError (name, versions, installed) { + const lines = versions.map(version => { + const node = installed.get(version)[0] + const dependant = [...node.edgesIn][0]?.from?.location || '(root)' + return ` ${selectorKey(name, version)} (via ${dependant})` + }) + return Object.assign( + new Error(`Multiple versions of "${name}" are installed:\n${lines.join('\n')}\n` + + `Re-run with an exact selector, e.g. "npm patch add ${selectorKey(name, versions[0])}".`), + { code: 'EPATCHAMBIGUOUS' } + ) + } + + // Create (or reuse, with --edit-dir) the directory a package is extracted into for editing. + async #makeEditDir (name, version) { + let editDir = this.npm.config.get('edit-dir') + if (!editDir) { + const base = join(tmpdir(), 'npm-patch') + await mkdir(base, { recursive: true }) + return mkdtemp(join(base, `${name.replace(/\//g, '+')}@${version}-`)) + } + editDir = resolve(editDir) + if (this.npm.config.get('ignore-existing')) { + await rm(editDir, { recursive: true, force: true }) + } + await mkdir(editDir, { recursive: true }) + return editDir + } + + async add (args) { + if (args.length !== 1) { + throw this.usageError() + } + const { name, version } = await this.#resolveTarget(args[0]) + const editDir = await this.#makeEditDir(name, version) + + await pacote.extract(selectorKey(name, version), editDir, this.npm.flatOptions) + + output.standard(`You can now edit the following directory: ${editDir}`) + output.standard(`When done, run: npm patch commit ${editDir}`) + } + + async commit (args) { + if (args.length !== 1) { + throw this.usageError() + } + const editDir = resolve(args[0]) + const { content: edited } = await PackageJson.normalize(editDir).catch(() => { + throw Object.assign( + new Error(`No package.json found in edit directory: ${editDir}`), + { code: 'EPATCHNOEDITDIR' } + ) + }) + const { name, version } = edited + if (!name || !version) { + throw new Error(`Edit directory package.json is missing name or version: ${editDir}`) + } + + // a conflicted `patch update` leaves a marker so this commit drops the renamed-from selector + // it is kept on disk (and excluded from the diff) so a re-run after a no-op resolution still finalizes the update + const markerPath = join(editDir, UPDATE_MARKER) + const markerRaw = await readFile(markerPath, 'utf8').catch(() => null) + let marker = null + if (markerRaw !== null) { + try { + marker = JSON.parse(markerRaw) + } catch { + throw patchErr(`invalid update marker in ${editDir}`, 'EPATCHBADMARKER') + } + } + + // extract a clean baseline to diff against + const base = await mkdtemp(join(tmpdir(), 'npm-patch-base-')) + let diff, packageJsonChanged + try { + await pacote.extract(selectorKey(name, version), base, this.npm.flatOptions) + ;({ diff, packageJsonChanged } = await diffDirs(base, editDir, new Set([UPDATE_MARKER]))) + } finally { + await rm(base, { recursive: true, force: true }) + } + + if (!diff) { + // package.json is excluded from patches, so an edit limited to it captures nothing + const reason = packageJsonChanged + ? `only package.json changed in ${editDir}, which is not patchable; nothing to commit` + : `no changes detected in ${editDir}; nothing to commit` + log.warn('patch', reason) + return + } + if (packageJsonChanged) { + log.warn('patch', 'changes to package.json are not included in patches and were ignored') + } + + const patchesDir = this.npm.config.get('patches-dir') + const absPatch = resolve(this.#root, patchFilePath(patchesDir, name, version)) + // refuse to write outside the project so the patch set stays in the repo + const relPatch = containedRelative(this.#root, absPatch) + if (!relPatch) { + throw Object.assign( + new Error(`patches-dir "${patchesDir}" resolves outside the project root.`), + { code: 'EPATCHUNSAFE' } + ) + } + await mkdir(dirname(absPatch), { recursive: true }) + await writeFile(absPatch, diff) + + const pkgJson = await PackageJson.load(this.#root) + const patchedDependencies = { ...pkgJson.content.patchedDependencies } + const newKey = selectorKey(name, version) + patchedDependencies[newKey] = relPatch + // a marker left by a conflicted `patch update` for this package means a metadata-only finalize. + // its name is checked so a stray or forged marker can never hijack a normal commit. + const updateFinalize = !!marker && marker.name === name + let orphan = null + // an exact rename drops the renamed-from selector; a fork carries removeKey null and keeps the old entry. + // removeKey must be a real, same-package selector string, so a malformed marker can neither crash nor drop the wrong entry. + if (updateFinalize && typeof marker.removeKey === 'string' && marker.removeKey !== newKey && + patchedDependencies[marker.removeKey] !== undefined && + parseSelector(marker.removeKey).name === name) { + orphan = this.#dropSelector(patchedDependencies, marker.removeKey) + } + pkgJson.update({ patchedDependencies }) + await pkgJson.save() + + // finishing a conflicted update is metadata-only (like update itself): the new version may not be installed yet + const arb = updateFinalize + ? this.#newArborist({ packageLockOnly: true, allowUnusedPatches: true, audit: false }) + : this.#newArborist() + await arb.reify(arb.options) + await reifyFinish(this.npm, arb) + + // remove the renamed-from patch file only after the lockfile is durable + await this.#removePatchFile(orphan) + + if (!this.npm.config.get('keep-edit-dir')) { + await rm(editDir, { recursive: true, force: true }) + } + + output.standard(`Patched ${newKey} -> ${relPatch}`) + } + + // Remove a selector from the map; return its patch file path if nothing else references it. + #dropSelector (patched, key) { + const patchPath = patched[key] + delete patched[key] + /* istanbul ignore next - the shared-file branch only fires when two selectors point at one patch */ + return (patchPath && !Object.values(patched).includes(patchPath)) ? patchPath : null + } + + // Delete an orphaned patch file, but never one that escapes the project root. + async #removePatchFile (patchPath) { + if (!patchPath) { + return + } + const abs = resolve(this.#root, patchPath) + /* istanbul ignore else - defensive: orphaned paths come from the manifest and stay in-project */ + if (containedRelative(this.#root, abs)) { + await rm(abs, { force: true }) + } + } + + async update (args) { + if (args.length !== 1) { + throw this.usageError() + } + + const pkgJson = await PackageJson.load(this.#root) + const patched = { ...pkgJson.content.patchedDependencies } + const entry = this.#resolveUpdateEntry(args[0], patched) + + const baseVersion = patchFileVersion(entry.patchPath) + if (!baseVersion) { + throw patchErr( + `cannot determine the version "${entry.patchPath}" was authored against; rebase by hand`, + 'EPATCHBASE' + ) + } + + const installedVersions = await this.#installedVersions(entry.name) + const newVersion = this.#resolveNewVersion(entry, installedVersions) + if (newVersion === baseVersion) { + throw patchErr(`nothing to update: the patch already targets ${selectorKey(entry.name, newVersion)}`, 'EPATCHNOOP') + } + const newKey = selectorKey(entry.name, newVersion) + if (patched[newKey] && newKey !== entry.key) { + throw patchErr( + `an entry already exists for ${newKey}; use "npm patch rm" first or rebase manually`, + 'EPATCHEXISTS' + ) + } + + const rebase = await this.#rebasePatch({ + name: entry.name, + baseVersion, + newVersion, + patchAbs: resolve(this.#root, entry.patchPath), + }) + try { + if (rebase.conflicted) { + const editDir = await this.#makeEditDir(entry.name, newVersion) + try { + await cp(rebase.repo, editDir, { recursive: true, filter: notGitDir }) + // mark the conflict so the finalizing commit knows this is an update finalize. + // an exact selector is a rename (drop the old key); a range/name-only is a fork (keep it). + const removeKey = entry.spec && semver.valid(entry.spec) ? entry.key : null + await writeFile(join(editDir, UPDATE_MARKER), JSON.stringify({ name: entry.name, removeKey }) + '\n') + } catch (er) { + // discard a temp edit dir we created if the copy or marker write fails; never a user-supplied --edit-dir + /* istanbul ignore next - a failing copy/marker write is not deterministically reproducible */ + if (!this.npm.config.get('edit-dir')) { + await rm(editDir, { recursive: true, force: true }) + } + /* istanbul ignore next */ + throw er + } + output.standard(`Patch did not apply cleanly to ${newKey}.`) + output.standard(`Resolve the conflicts in: ${editDir}`) + output.standard(`When done, run: npm patch commit ${editDir}`) + return + } + + const { diff } = await diffDirs(rebase.newDir, rebase.repo) + if (!diff) { + throw patchErr( + `the patch no longer changes ${newKey}; remove it with "npm patch rm" instead`, + 'EPATCHEMPTY' + ) + } + await this.#finalizeUpdate({ + pkgJson, patched, entry, name: entry.name, newVersion, newKey, diff, installedVersions, + }) + } finally { + await rm(rebase.work, { recursive: true, force: true }) + } + } + + // Identify the single patchedDependencies entry the update targets. + #resolveUpdateEntry (spec, patched) { + const target = npa(spec) + const name = target.name + const oldSpec = target.rawSpec && target.rawSpec !== '*' ? target.fetchSpec : null + const keys = Object.keys(patched) + + if (oldSpec) { + const key = selectorKey(name, oldSpec) + if (!patched[key]) { + throw patchErr(`no patch registered for ${key}`, 'EPATCHNOTFOUND') + } + return { key, name, spec: oldSpec, patchPath: patched[key] } + } + + const matches = keys.filter(k => parseSelector(k).name === name) + if (!matches.length) { + throw patchErr(`no patch to update for "${name}"`, 'EPATCHNOTFOUND') + } + if (matches.length > 1) { + throw patchErr( + `multiple patches match "${name}":\n${matches.map(k => ` ${k}`).join('\n')}\n` + + `Re-run with an explicit selector, e.g. "npm patch update ${matches[0]}".`, + 'EPATCHAMBIGUOUS' + ) + } + const key = matches[0] + return { key, name, spec: parseSelector(key).spec, patchPath: patched[key] } + } + + // Determine the version to rebase onto: --to, else the installed version matching the selector. + #resolveNewVersion (entry, installedVersions) { + const to = this.npm.config.get('to') + if (to) { + const valid = semver.valid(to) + if (!valid) { + throw patchErr(`--to "${to}" is not a valid version`, 'EPATCHBADTO') + } + // update finalizes with allowUnusedPatches, so a --to absent from the tree records an unused patch silently. + // The next plain install then rejects with EPATCHUNUSED, so warn now to surface the mismatch early. + if (installedVersions !== null && !installedVersions.includes(valid)) { + log.warn('patch', + `${selectorKey(entry.name, valid)} is not installed; ` + + `bump the dependency and reinstall, or the next "npm install" will fail with EPATCHUNUSED.`) + } + return valid + } + + if (installedVersions === null) { + throw patchErr( + `could not read the lockfile for "${entry.name}"; ` + + `run "npm install" first or pass --to `, + 'EPATCHSTALE' + ) + } + const { spec } = entry + let matching + if (spec && semver.valid(spec)) { + matching = installedVersions.filter(v => semver.eq(v, spec)) + } else if (spec) { + matching = installedVersions.filter(v => semver.satisfies(v, spec)) + } else { + matching = installedVersions + } + if (!matching.length) { + throw patchErr( + `no installed version matches the patch selector "${entry.key}"; ` + + `pass --to to rebase onto a specific version`, + 'EPATCHSTALE' + ) + } + return matching.sort(semver.rcompare)[0] + } + + // Distinct registry-installed versions of a package from the lockfile, or null when it cannot be loaded. + // Uses loadVirtual so the lockfile's own validity gates staleness and links/workspaces are excluded. + async #installedVersions (name) { + let tree + try { + tree = await this.#newArborist().loadVirtual() + } catch { + return null + } + const versions = new Set() + for (const node of tree.inventory.values()) { + if (node.isProjectRoot || node.isWorkspace || node.isLink || !node.version) { + continue + } + /* istanbul ignore else - other-named nodes are skipped; only exercised with multi-package trees */ + if (node.name === name) { + versions.add(node.version) + } + } + return [...versions] + } + + // 3-way merge the existing patch onto the new version via a throwaway git repo. + // Returns { work, repo, newDir, conflicted }; the caller removes work on success. + async #rebasePatch ({ name, baseVersion, newVersion, patchAbs }) { + const work = await mkdtemp(join(tmpdir(), 'npm-patch-rebase-')) + try { + const baseDir = join(work, 'base') + const newDir = join(work, 'new') + const repo = join(work, 'repo') + await pacote.extract(selectorKey(name, baseVersion), baseDir, this.npm.flatOptions) + await pacote.extract(selectorKey(name, newVersion), newDir, this.npm.flatOptions) + await mkdir(repo, { recursive: true }) + + const id = ['-c', 'user.name=npm', '-c', 'user.email=npm@npmjs.com', '-c', 'commit.gpgsign=false'] + await this.#git(['init', '-q', '-b', 'base'], repo) + // base = the version the patch was authored against + await cp(baseDir, repo, { recursive: true }) + await this.#git(['add', '-Af'], repo) + await this.#git([...id, 'commit', '-qm', 'base', '--allow-empty'], repo) + // theirs = base + the existing patch, applied with the same jsdiff helper installs use + await this.#git(['checkout', '-q', '-b', 'theirs'], repo) + try { + await applyPatchToDir({ patch: await readFile(patchAbs), cwd: repo }) + } catch (er) { + throw patchErr( + `the existing patch no longer applies to its baseline ${selectorKey(name, baseVersion)}; rebase by hand`, + 'EPATCHBASE', + { cause: er } + ) + } + await this.#git(['add', '-Af'], repo) + await this.#git([...id, 'commit', '-qm', 'theirs', '--allow-empty'], repo) + // ours = the new version, branched from base + await this.#git(['checkout', '-q', '-b', 'ours', 'base'], repo) + await this.#git(['rm', '-rqf', '.'], repo) + await cp(newDir, repo, { recursive: true }) + await this.#git(['add', '-Af'], repo) + await this.#git([...id, 'commit', '-qm', 'ours', '--allow-empty'], repo) + // replay the patch's intent onto the new version + let conflicted = false + try { + await this.#git([...id, 'merge', '--no-edit', 'theirs'], repo) + } catch (er) { + // a genuine conflict leaves unmerged paths; any other non-zero exit is a real git failure + const unmerged = await this.#git(['ls-files', '--unmerged'], repo) + /* istanbul ignore else - a non-conflict merge failure is a git/environment fault */ + if (String(unmerged.stdout).trim()) { + conflicted = true + } else { + throw er + } + } + return { work, repo, newDir, conflicted } + } catch (er) { + await rm(work, { recursive: true, force: true }) + throw er + } + } + + #git (args, cwd) { + return git.spawn(args, { + cwd, + env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null' }, + }) + } + + // Apply the selector rules, write the new patch, and sync the lockfile without touching node_modules. + async #finalizeUpdate (opts) { + const { pkgJson, patched, entry, name, newVersion, newKey, diff, installedVersions } = opts + const patchesDir = this.npm.config.get('patches-dir') + const absPatch = resolve(this.#root, patchFilePath(patchesDir, name, newVersion)) + const relPatch = containedRelative(this.#root, absPatch) + if (!relPatch) { + throw patchErr(`patches-dir "${patchesDir}" resolves outside the project root.`, 'EPATCHUNSAFE') + } + // write the new patch first so no selector points at a missing file + await mkdir(dirname(absPatch), { recursive: true }) + await writeFile(absPatch, diff) + + patched[newKey] = relPatch + // drop the old selector only when it no longer wins any installed node, so a still-needed range survives + let orphan = null + if (entry.key !== newKey && this.#selectorUnused(patched, entry.key, name, installedVersions)) { + orphan = this.#dropSelector(patched, entry.key) + } + + pkgJson.update({ patchedDependencies: patched }) + await pkgJson.save() + + // record the new patch integrity in the lockfile only; update never touches node_modules + const arb = this.#newArborist({ packageLockOnly: true, allowUnusedPatches: true, audit: false }) + await arb.reify(arb.options) + await reifyFinish(this.npm, arb) + + // remove the now-orphaned old patch file only after the lockfile is durable + await this.#removePatchFile(orphan) + + output.standard(`Updated ${entry.key} -> ${newKey} (${relPatch})`) + } + + // Whether `key` should be dropped once the new selector is added. + // An exact selector is a straight rename. A range/name-only selector is dropped only when it no longer + // wins any installed node under the installer's exact > range > name-only precedence, so a kept one is still used. + #selectorUnused (patched, key, name, installedVersions) { + const { spec } = parseSelector(key) + if (spec && semver.valid(spec)) { + return true + } + if (installedVersions === null) { + return false + } + const selectors = Object.keys(patched) + .filter(k => parseSelector(k).name === name) + .map(k => ({ ...parseSelector(k), key: k })) + for (const version of installedVersions) { + let winner + try { + winner = matchSelector(selectors, { name, version }) + } catch { + /* istanbul ignore next - ambiguous overlapping ranges: keep the selector to be safe */ + return false + } + /* istanbul ignore if - a still-winning selector is kept; only exercised with multiple installed versions */ + if (winner?.key === key) { + return false + } + } + return true + } + + async ls () { + const pkgJson = await PackageJson.normalize(this.#root).catch(() => ({ content: {} })) + const patched = pkgJson.content.patchedDependencies || {} + const keys = Object.keys(patched) + if (!keys.length) { + return + } + + // count nodes per patch using the same precedence Arborist applies at install + const tree = await this.#loadActual() + const selectors = keys.map(key => ({ ...parseSelector(key), key, patchPath: patched[key] })) + const counts = new Map(keys.map(key => [key, 0])) + // only the overlapping range selectors that actually conflict on a node + const ambiguous = new Set() + for (const node of tree.inventory.values()) { + if (node.isProjectRoot || node.isLink || !node.version) { + continue + } + let winner = null + try { + winner = matchSelector(selectors, node) + } catch { + for (const s of selectors) { + if (s.name === node.name && s.spec && !semver.valid(s.spec) && + semver.satisfies(node.version, s.spec)) { + ambiguous.add(s.key) + } + } + continue + } + if (winner) { + counts.set(winner.key, counts.get(winner.key) + 1) + } + } + for (const key of keys) { + if (ambiguous.has(key)) { + output.standard(`${patched[key]}\t${key}\t(error: ambiguous selectors)`) + continue + } + const n = counts.get(key) + output.standard(`${patched[key]}\t${key}\t(${n} node${n === 1 ? '' : 's'})`) + } + } + + async rm (args) { + if (args.length !== 1) { + throw this.usageError() + } + const target = npa(args[0]) + const targetName = target.name + const targetVersion = target.rawSpec && target.rawSpec !== '*' ? target.fetchSpec : null + + const pkgJson = await PackageJson.load(this.#root) + const patched = { ...pkgJson.content.patchedDependencies } + const removed = [] + for (const key of Object.keys(patched)) { + const { name, spec } = parseSelector(key) + if (name === targetName && (!targetVersion || spec === targetVersion)) { + removed.push(key) + } + } + if (!removed.length) { + throw Object.assign( + new Error(`No registered patch found for "${args[0]}".`), + { code: 'EPATCHNOTFOUND' } + ) + } + + for (const key of removed) { + const patchPath = patched[key] + delete patched[key] + // only delete the file when no remaining selector references it + if (!Object.values(patched).includes(patchPath)) { + const abs = resolve(this.#root, patchPath) + // never delete a path that escapes the project root + if (!containedRelative(this.#root, abs)) { + throw Object.assign( + new Error(`Refusing to delete patch outside the project root: ${patchPath}`), + { code: 'EPATCHUNSAFE' } + ) + } + await rm(abs, { force: true }) + } + } + + if (Object.keys(patched).length) { + pkgJson.update({ patchedDependencies: patched }) + } else { + delete pkgJson.content.patchedDependencies + } + await pkgJson.save() + + const arb = this.#newArborist() + await arb.reify(arb.options) + await reifyFinish(this.npm, arb) + + output.standard(`Removed patch${removed.length === 1 ? '' : 'es'}: ${removed.join(', ')}`) + } +} + +module.exports = Patch diff --git a/lib/commands/pkg.js b/lib/commands/pkg.js index a011fc10be107..a47c7695c3d5e 100644 --- a/lib/commands/pkg.js +++ b/lib/commands/pkg.js @@ -1,3 +1,4 @@ +const { inspect } = require('node:util') const { output } = require('proc-log') const PackageJson = require('@npmcli/package-json') const BaseCommand = require('../base-cmd.js') @@ -56,27 +57,40 @@ class Pkg extends BaseCommand { } async get (args, { path, workspace }) { - this.npm.config.set('json', true) const pkgJson = await PackageJson.load(path) + const json = this.npm.config.get('json') - let result = pkgJson.content + // filter out the newline/indent symbols from the package-json object + let result = JSON.parse(JSON.stringify(pkgJson.content)) if (args.length) { - result = new Queryable(result).query(args) - // in case there's only 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) { - result = result[args] + result = new Queryable(result).query(args, { unwrapSingleItemArrays: false }) + if (args.length === 1 && !json && args[0] in result) { + if (workspace) { + return output.standard(`${workspace} ${result[args[0]]}`) + } + return output.standard(result[args[0]]) } } - // 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) + if (json) { + output.buffer(workspace ? { [workspace]: result } : result) + } else { + for (let [f, d] of Object.entries(result)) { + d = inspect(d, { + showHidden: false, + depth: 5, + colors: this.npm.color, + maxArrayLength: null, + }) + + if (workspace) { + output.standard(`${workspace} ${f} = ${d}`) + } else { + output.standard(`${f} = ${d}`) + } + } + } } async set (args, { path }) { diff --git a/lib/commands/prefix.js b/lib/commands/prefix.js index da8702cf91caa..907ed5af2c179 100644 --- a/lib/commands/prefix.js +++ b/lib/commands/prefix.js @@ -5,7 +5,6 @@ class Prefix extends BaseCommand { static description = 'Display prefix' static name = 'prefix' static params = ['global'] - static usage = ['[-g]'] async exec () { return output.standard(this.npm.prefix) diff --git a/lib/commands/profile.js b/lib/commands/profile.js index 965fcbcb8ce29..9417989cf318c 100644 --- a/lib/commands/profile.js +++ b/lib/commands/profile.js @@ -16,8 +16,6 @@ const knownProfileKeys = [ 'two-factor auth', 'fullname', 'homepage', - 'freenode', - 'twitter', 'github', 'created', 'updated', @@ -28,8 +26,6 @@ const writableProfileKeys = [ 'password', 'fullname', 'homepage', - 'freenode', - 'twitter', 'github', ] @@ -222,6 +218,8 @@ class Profile extends BaseCommand { } async enable2fa (args) { + const conf = { ...this.npm.flatOptions } + if (args.length > 1) { throw new Error('npm profile enable-2fa [auth-and-writes|auth-only]') } @@ -244,14 +242,20 @@ class Profile extends BaseCommand { ) } + const userInfo = await get(conf) + + if (!userInfo?.tfa?.pending && userInfo?.tfa?.mode === mode) { + output.standard('Two factor authentication is already enabled and set to ' + mode) + return + } + const info = { tfa: { - mode: mode, + mode, }, } - // if they're using legacy auth currently then we have to - // update them to a bearer token before continuing. + // 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 = {} @@ -278,11 +282,7 @@ class Profile extends BaseCommand { ) 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' - ) + 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( @@ -296,25 +296,15 @@ class Profile extends BaseCommand { 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) + const challenge = await otplease(this.npm, conf, o => set(info, o)) - if (challenge.tfa === null) { + if (challenge.tfa && challenge.tfa.mode) { output.standard('Two factor authentication mode changed to: ' + mode) return } @@ -322,35 +312,23 @@ class Profile extends BaseCommand { 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) - ) + 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 - ) + 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: ') + 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.' - ) + 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) @@ -358,8 +336,8 @@ class Profile extends BaseCommand { } async disable2fa () { - const conf = { ...this.npm.flatOptions } - const info = await get(conf) + const opts = { ...this.npm.flatOptions } + const info = await get(opts) if (!info.tfa || info.tfa.pending) { output.standard('Two factor authentication not enabled.') @@ -368,14 +346,8 @@ class Profile extends BaseCommand { 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) + await otplease(this.npm, opts, o => set({ tfa: { password: password, mode: 'disable' } }, o)) if (this.npm.config.get('json')) { output.buffer({ tfa: false }) diff --git a/lib/commands/prune.js b/lib/commands/prune.js index 1bcf8a9576316..e1790e4094726 100644 --- a/lib/commands/prune.js +++ b/lib/commands/prune.js @@ -1,7 +1,8 @@ const reifyFinish = require('../utils/reify-finish.js') +const resolveAllowScripts = require('../utils/resolve-allow-scripts.js') +const { patchRelaxOpts } = require('../utils/cli-only-flag.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') -// prune extraneous packages class Prune extends ArboristWorkspaceCmd { static description = 'Remove extraneous packages' static name = 'prune' @@ -20,10 +21,13 @@ class Prune extends ArboristWorkspaceCmd { async exec () { const where = this.npm.prefix const Arborist = require('@npmcli/arborist') + const { policy: allowScriptsPolicy } = await resolveAllowScripts(this.npm) const opts = { ...this.npm.flatOptions, path: where, workspaces: this.workspaceNames, + allowScripts: allowScriptsPolicy, + ...patchRelaxOpts(this.npm.config), } const arb = new Arborist(opts) await arb.prune(opts) diff --git a/lib/commands/publish.js b/lib/commands/publish.js index 3fe337a7b1c43..f13bc026f3295 100644 --- a/lib/commands/publish.js +++ b/lib/commands/publish.js @@ -1,4 +1,4 @@ -const { log, output } = require('proc-log') +const { log, output, META } = require('proc-log') const semver = require('semver') const pack = require('libnpmpack') const libpub = require('libnpmpublish').publish @@ -9,17 +9,22 @@ 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. +// 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') +const { oidc } = require('../utils/oidc.js') class Publish extends BaseCommand { static description = 'Publish a package' static name = 'publish' + static stage = false + + get isStage () { + return this.constructor.stage + } + static params = [ 'tag', 'access', @@ -46,7 +51,12 @@ class Publish extends BaseCommand { await this.#publish(args) } - async execWorkspaces () { + 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()) { @@ -56,20 +66,24 @@ class Publish extends BaseCommand { if (err.code !== 'EPRIVATE') { throw err } - // eslint-disable-next-line max-len - log.warn('publish', `Skipping workspace ${this.npm.chalk.cyan(name)}, marked as ${this.npm.chalk.bold('private')}`) + log.warn(this.#command, `Skipping workspace ${this.npm.chalk.cyan(name)}, marked as ${this.npm.chalk.bold('private')}`) } } } + get #command () { + return this.isStage ? 'stage' : 'publish' + } + async #publish (args, { workspace } = {}) { - log.verbose('publish', replaceInfo(args)) + log.verbose(this.#command, 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 scriptShell = this.npm.config.get('script-shell') || undefined const { silent } = this.npm if (semver.validRange(defaultTag)) { @@ -78,11 +92,13 @@ class Publish extends BaseCommand { const opts = { ...this.npm.flatOptions, progress: false } - // you can publish name@version, ./foo.tgz, etc. - // even though the default is the 'file:.' cwd. + // 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) + // packageExtensions is root-only project policy and must never be published; fail fast so dry-run reports it too + this.#assertNoPackageExtensions(manifest) + // only run scripts for directory type publishes if (spec.type === 'directory' && !ignoreScripts) { await runScript({ @@ -90,6 +106,7 @@ class Publish extends BaseCommand { path: spec.fetchSpec, stdio: 'inherit', pkg: manifest, + scriptShell, }) } @@ -104,15 +121,23 @@ class Publish extends BaseCommand { workspaces: this.workspacePaths, }) const pkgContents = await getContents(manifest, tarballData) - const logPkg = () => logTar(pkgContents, { unicode, json, key: workspace }) + const logPkg = () => logTar(pkgContents, { unicode, json, key: pkgContents.name }) - // 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! + // 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) + // re-check the authoritative manifest in case a lifecycle script introduced packageExtensions + this.#assertNoPackageExtensions(manifest) + 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 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() } @@ -123,11 +148,13 @@ class Publish extends BaseCommand { npa(`${manifest.name}@${defaultTag}`) const registry = npmFetch.pickRegistry(resolved, opts) + + await oidc({ packageName: manifest.name, registry, opts, config: this.npm.config }) + 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 @@ -139,28 +166,57 @@ class Publish extends BaseCommand { if (noCreds) { const msg = `This command requires you to be logged in to ${outputRegistry}` if (dryRun) { - log.warn('', `${msg} (dry-run)`) + log.warn(this.#command, `${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` + const verb = this.isStage ? 'Staging' : 'Publishing' + let msg = `${verb} to ${outputRegistry} with tag ${defaultTag} and ${access} access` if (dryRun) { msg = `${msg} (dry-run)` } log.notice('', msg) + let stageId if (!dryRun) { - await otplease(this.npm, opts, o => libpub(manifest, tarballData, o)) + if (this.isStage) { + // Stage intentionally bypasses otplease — 2FA is deferred to approve/reject + const res = await libpub(manifest, tarballData, { + ...opts, + command: this.#command, + stage: true, + }) + stageId = res.stageId + } else { + 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 + // In json mode we don't log until the publish has completed as this will add it to the output only if completes successfully if (json) { - logPkg() + if (stageId) { + pkgContents.stageId = stageId + } + logTar(pkgContents, { + unicode, json, key: pkgContents.name, redact: stageId ? false : undefined }) } if (spec.type === 'directory' && !ignoreScripts) { @@ -169,6 +225,7 @@ class Publish extends BaseCommand { path: spec.fetchSpec, stdio: 'inherit', pkg: manifest, + scriptShell, }) await runScript({ @@ -176,11 +233,58 @@ class Publish extends BaseCommand { path: spec.fetchSpec, stdio: 'inherit', pkg: manifest, + scriptShell, }) } if (!json && !silent) { - output.standard(`+ ${pkgContents.id}`) + if (this.isStage) { + const stagedMsg = stageId + ? `+ ${pkgContents.id} (staged with id ${stageId})` + : `+ ${pkgContents.id} (staged)` + output.standard(stagedMsg, { [META]: true, redact: false }) + log.notice(this.#command, `package ${pkgContents.id} has been staged with tag ${defaultTag}`) + } else { + output.standard(`+ ${pkgContents.id}`) + } + } + } + + async #registryVersions (spec, registry) { + try { + const packument = await pacote.packument(spec, { + ...this.npm.flatOptions, + preferOnline: true, + registry, + _isRoot: true, + }) + 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 } + } + } + + // packageExtensions is root-only project policy and must never reach the registry; private packages may keep it for local use + #assertNoPackageExtensions (manifest) { + if (!manifest.private && manifest.packageExtensions !== undefined) { + throw Object.assign( + new Error('packageExtensions is only honored at the project root and must not be published.'), + { code: 'EPACKAGEEXTENSIONS' } + ) } } @@ -193,9 +297,8 @@ class Publish extends BaseCommand { const changes = [] const pkg = await pkgJson.fix(spec.fetchSpec, { changes }) if (changes.length && logWarnings) { - /* eslint-disable-next-line max-len */ - 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')}`) + log.warn(this.#command, 'npm auto-corrected some errors in your package.json when publishing. Please run "npm pkg fix" to address these errors.') + log.warn(this.#command, `errors corrected:\n${changes.join('\n')}`) } // Prepare is the special function for publishing, different than normalize const { content } = await pkg.prepare() @@ -203,16 +306,20 @@ class Publish extends BaseCommand { } else { manifest = await pacote.manifest(spec, { ...opts, - fullmetadata: true, + 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 + // 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))) + if (logWarnings) { + for (const key in filteredPublishConfig) { + this.npm.config.checkUnknown('publishConfig', key) + } + } flatten(filteredPublishConfig, opts) } return manifest diff --git a/lib/commands/query.js b/lib/commands/query.js index 74a50fc581d43..4eb2ad5179f99 100644 --- a/lib/commands/query.js +++ b/lib/commands/query.js @@ -49,6 +49,9 @@ class Query extends BaseCommand { 'include-workspace-root', 'package-lock-only', 'expect-results', + 'before', + 'min-release-age', + 'min-release-age-exclude', ] constructor (...args) { @@ -57,22 +60,22 @@ class Query extends BaseCommand { } async exec (args) { - const packageLock = this.npm.config.get('package-lock-only') + const packageLockOnly = 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, + forceActual: !packageLockOnly, }) let tree - if (packageLock) { + if (packageLockOnly) { 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' + 'A package-lock.json file is required in package-lock-only mode' ) } } else { @@ -84,20 +87,33 @@ class Query extends BaseCommand { async execWorkspaces (args) { await this.setWorkspaces() + const packageLockOnly = this.npm.config.get('package-lock-only') const Arborist = require('@npmcli/arborist') const arb = new Arborist({ ...this.npm.flatOptions, path: this.npm.prefix, + forceActual: !packageLockOnly, }) - // 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() + let tree + if (packageLockOnly) { + try { + tree = await arb.loadVirtual() + } catch (err) { + log.verbose('loadVirtual', err.stack) + throw this.usageError( + 'A package-lock.json file is required in package-lock-only mode' + ) + } + } else { + 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]) + : await tree.querySelectorAll(`.workspace:path(${path})`).then(r => r[0]?.target) + if (wsTree) { + await this.#queryTree(wsTree, args[0]) + } } this.#output() } diff --git a/lib/commands/rebuild.js b/lib/commands/rebuild.js index 1c19836106e06..0cb7f532e33ea 100644 --- a/lib/commands/rebuild.js +++ b/lib/commands/rebuild.js @@ -1,8 +1,13 @@ const { resolve } = require('node:path') -const { output } = require('proc-log') +const { log, output } = require('proc-log') const npa = require('npm-package-arg') const semver = require('semver') +const { trustedDisplay } = require('@npmcli/arborist/lib/script-allowed.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') +const checkAllowScripts = require('../utils/check-allow-scripts.js') +const resolveAllowScripts = require('../utils/resolve-allow-scripts.js') +const strictAllowScriptsPreflight = require('../utils/strict-allow-scripts-preflight.js') +const { configSetAllowScripts } = require('../utils/allow-scripts-remediation.js') class Rebuild extends ArboristWorkspaceCmd { static description = 'Rebuild a package' @@ -12,13 +17,14 @@ class Rebuild extends ArboristWorkspaceCmd { 'bin-links', 'foreground-scripts', 'ignore-scripts', + 'allow-scripts', + 'strict-allow-scripts', + 'dangerously-allow-all-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) @@ -28,9 +34,11 @@ class Rebuild extends ArboristWorkspaceCmd { const globalTop = resolve(this.npm.globalDir, '..') const where = this.npm.global ? globalTop : this.npm.prefix const Arborist = require('@npmcli/arborist') + const { policy: allowScriptsPolicy } = await resolveAllowScripts(this.npm) const arb = new Arborist({ ...this.npm.flatOptions, path: where, + allowScripts: allowScriptsPolicy, // TODO when extending ReifyCmd // workspaces: this.workspaceNames, }) @@ -50,17 +58,47 @@ class Rebuild extends ArboristWorkspaceCmd { return spec }) - const nodes = tree.inventory.filter(node => this.isNode(specs, node)) + const nodes = [...tree.inventory.filter(node => this.isNode(specs, node))] + await strictAllowScriptsPreflight({ arb, npm: this.npm }) await arb.rebuild({ nodes }) } else { + await arb.loadActual() + await strictAllowScriptsPreflight({ arb, npm: this.npm }) await arb.rebuild() } + // Rebuild skips reifyFinish, so run the walker here to list any + // packages whose install scripts were blocked. + const unreviewed = await checkAllowScripts({ arb, npm: this.npm }) + if (unreviewed.length > 0) { + const count = unreviewed.length + const noun = count === 1 ? 'package had' : 'packages had' + // `npm approve-scripts` writes to a project package.json, which doesn't + // exist for global rebuilds. Point global users at `npm config set`, + // which writes the `allow-scripts` setting to their user .npmrc. + const names = unreviewed.map(({ node }) => trustedDisplay(node).name) + const remediation = this.npm.global + ? `Run \`${configSetAllowScripts(names)}\` to allow their scripts.` + : 'Run `npm approve-scripts --allow-scripts-pending` to review.' + log.warn( + 'rebuild', + `${count} ${noun} install scripts blocked because they are not covered by allowScripts. ` + + remediation + ) + } + output.standard('rebuilt dependencies successfully') } isNode (specs, node) { + // Bundled dependencies are never selected by name. Their identity comes + // from the bundling parent's tarball (a bundled folder can call itself + // anything), so `npm rebuild bcrypt` must never target a bundled + // `node_modules/bcrypt`. Their install scripts never run regardless. + if (node.inBundle) { + return false + } return specs.some(spec => { if (spec.type === 'directory') { return node.path === spec.fetchSpec diff --git a/lib/commands/repo.js b/lib/commands/repo.js index 3f120c0a3f59f..0bfb2cf962c9b 100644 --- a/lib/commands/repo.js +++ b/lib/commands/repo.js @@ -49,7 +49,7 @@ const unknownHostedUrl = url => { const proto = /(git\+)http:$/.test(protocol) ? 'http:' : 'https:' const path = pathname.replace(/\.git$/, '') return `${proto}//${hostname}${path}` - } catch (e) { + } catch { return null } } diff --git a/lib/commands/restart.js b/lib/commands/restart.js index 7ca2eb323da3c..52b9b20757e29 100644 --- a/lib/commands/restart.js +++ b/lib/commands/restart.js @@ -1,6 +1,6 @@ const LifecycleCmd = require('../lifecycle-cmd.js') -// This ends up calling run-script(['restart', ...args]) +// This ends up calling run(['restart', ...args]) class Restart extends LifecycleCmd { static description = 'Restart a package' static name = 'restart' diff --git a/lib/commands/run-script.js b/lib/commands/run-script.js deleted file mode 100644 index 0a139d08af745..0000000000000 --- a/lib/commands/run-script.js +++ /dev/null @@ -1,217 +0,0 @@ -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 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 diff --git a/lib/commands/run.js b/lib/commands/run.js new file mode 100644 index 0000000000000..ada203f2793af --- /dev/null +++ b/lib/commands/run.js @@ -0,0 +1,221 @@ +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' + 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 workspacePrefixes = npm.config.get('workspace', 'default') + const localPrefix = workspacePrefixes.length + ? workspacePrefixes[0] + : npm.localPrefix + const { content: { scripts = {} } } = await pkgJson.normalize(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) + ) { + 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}`, + '', + '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({ + args: evArgs, + event: ev, + nodeGyp: this.npm.config.get('node-gyp'), + path, + pkg, + // || undefined is because runScript will be unhappy with the default null value + scriptShell: this.npm.config.get('script-shell') || undefined, + stdio: 'inherit', + }) + } + } + + 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')}\`:` + 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 diff --git a/lib/commands/sbom.js b/lib/commands/sbom.js index 278c6d506b42a..38fb383834e66 100644 --- a/lib/commands/sbom.js +++ b/lib/commands/sbom.js @@ -1,6 +1,6 @@ const localeCompare = require('@isaacs/string-locale-compare')('en') const BaseCommand = require('../base-cmd.js') -const { log, output } = require('proc-log') +const { log, output, META } = require('proc-log') const { cyclonedxOutput } = require('../utils/sbom-cyclonedx.js') const { spdxOutput } = require('../utils/sbom-spdx.js') @@ -27,7 +27,6 @@ class SBOM extends BaseCommand { const packageLockOnly = this.npm.config.get('package-lock-only') if (!sbomFormat) { - /* eslint-disable-next-line max-len */ throw this.usageError(`Must specify --sbom-format flag with one of: ${SBOM_FORMATS.join(', ')}.`) } @@ -40,8 +39,7 @@ class SBOM extends BaseCommand { const arb = new Arborist(opts) const tree = packageLockOnly ? await arb.loadVirtual(opts).catch(() => { - /* eslint-disable-next-line max-len */ - throw this.usageError('A package lock or shrinkwrap file is required in package-lock-only mode') + throw this.usageError('A package-lock.json file is required in package-lock-only mode') }) : await arb.loadActual(opts) // Collect the list of selected workspaces in the project @@ -64,10 +62,9 @@ class SBOM extends BaseCommand { // 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. + // 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) + output.standard(JSON.stringify(this.#response, null, 2), { [META]: true, redact: false }) } async execWorkspaces (args) { @@ -81,8 +78,7 @@ class SBOM extends BaseCommand { 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 + // 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) { diff --git a/lib/commands/set.js b/lib/commands/set.js index 2e61762ba9dcd..9a90e2a50ea1e 100644 --- a/lib/commands/set.js +++ b/lib/commands/set.js @@ -8,8 +8,6 @@ class Set extends BaseCommand { static params = ['global', 'location'] static ignoreImplicitWorkspace = false - // TODO - /* istanbul ignore next */ static async completion (opts) { const Config = Npm.cmd('config') return Config.completion(opts) diff --git a/lib/commands/shrinkwrap.js b/lib/commands/shrinkwrap.js deleted file mode 100644 index 86215c18e62dd..0000000000000 --- a/lib/commands/shrinkwrap.js +++ /dev/null @@ -1,73 +0,0 @@ -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 diff --git a/lib/commands/stage/approve.js b/lib/commands/stage/approve.js new file mode 100644 index 0000000000000..619015d0c8a55 --- /dev/null +++ b/lib/commands/stage/approve.js @@ -0,0 +1,35 @@ +const { log, output, META } = require('proc-log') +const npmFetch = require('npm-registry-fetch') +const { otplease } = require('../../utils/auth.js') +const { validateUUID } = require('../../utils/validate-uuid.js') +const BaseCommand = require('../../base-cmd.js') + +class StageApprove extends BaseCommand { + static description = 'Approve a staged package, publishing it to the npm registry' + static name = 'approve' + static usage = [''] + static params = ['otp', 'registry'] + static positionals = 1 + + async exec (args) { + if (!args[0]) { + throw this.usageError('Missing required ') + } + const stageId = args[0] + validateUUID(stageId, 'stage-id') + const opts = { ...this.npm.flatOptions } + + log.notice('', `Approving staged package ${stageId}`) + + await otplease(this.npm, opts, o => + npmFetch.json(`/-/stage/${stageId}/approve`, { + ...o, + method: 'POST', + }) + ) + + output.standard(`Staged package ${stageId} approved and published successfully.`, { [META]: true, redact: false }) + } +} + +module.exports = StageApprove diff --git a/lib/commands/stage/download.js b/lib/commands/stage/download.js new file mode 100644 index 0000000000000..e5b7711aee54d --- /dev/null +++ b/lib/commands/stage/download.js @@ -0,0 +1,70 @@ +const { log, output, META } = require('proc-log') +const { writeFile } = require('node:fs/promises') +const { resolve } = require('node:path') +const tar = require('tar') +const npmFetch = require('npm-registry-fetch') +const { getContents, logTar } = require('../../utils/tar.js') +const { validateUUID } = require('../../utils/validate-uuid.js') +const BaseCommand = require('../../base-cmd.js') + +class StageDownload extends BaseCommand { + static description = 'Download the tarball of a staged package for inspection' + static name = 'download' + static usage = [''] + static params = ['json', 'registry'] + static positionals = 1 + + async exec (args) { + if (!args[0]) { + throw this.usageError('Missing required ') + } + const stageId = args[0] + validateUUID(stageId, 'stage-id') + const opts = { ...this.npm.flatOptions } + const unicode = this.npm.config.get('unicode') + const json = this.npm.config.get('json') + + log.notice('', `Downloading staged package ${stageId}`) + + const res = await npmFetch(`/-/stage/${stageId}/tarball`, opts) + const data = Buffer.from(await res.arrayBuffer()) + + const manifest = await this.#readManifestFromTarball(data) + const pkgContents = await getContents(manifest, data) + logTar(pkgContents, { unicode, json, key: pkgContents.name }) + + const safeName = pkgContents.name.replace('@', '').replace('/', '-') + const filename = `${safeName}-${pkgContents.version}-${stageId}.tgz` + const dest = resolve(process.cwd(), filename) + + await writeFile(dest, data) + if (!json) { + output.standard(filename, { [META]: true, redact: false }) + } + } + + async #readManifestFromTarball (tarballData) { + let manifestJson + const stream = tar.t({ + onentry (entry) { + if (entry.path === 'package/package.json') { + const chunks = [] + entry.on('data', c => chunks.push(c)) + entry.on('end', () => { + manifestJson = JSON.parse(Buffer.concat(chunks).toString()) + }) + } else { + entry.resume() + } + }, + }) + // node-tar uses Minipass which processes synchronously on .end() + stream.end(tarballData) + if (!manifestJson) { + throw new Error('Could not read package.json from tarball') + } + return manifestJson + } +} + +module.exports = StageDownload diff --git a/lib/commands/stage/index.js b/lib/commands/stage/index.js new file mode 100644 index 0000000000000..51b41b4f0249d --- /dev/null +++ b/lib/commands/stage/index.js @@ -0,0 +1,25 @@ +const BaseCommand = require('../../base-cmd.js') + +class Stage extends BaseCommand { + static description = 'Stage packages for publishing, deferring proof-of-presence (2FA) to a later point in time' + static name = 'stage' + + static subcommands = { + publish: require('./publish.js'), + list: require('./list.js'), + view: require('./view.js'), + approve: require('./approve.js'), + reject: require('./reject.js'), + download: require('./download.js'), + } + + static async completion (opts) { + const argv = opts.conf.argv.remain + if (argv.length === 2) { + return Object.keys(Stage.subcommands) + } + return [] + } +} + +module.exports = Stage diff --git a/lib/commands/stage/list.js b/lib/commands/stage/list.js new file mode 100644 index 0000000000000..bcfb45affb00b --- /dev/null +++ b/lib/commands/stage/list.js @@ -0,0 +1,72 @@ +const { output, META } = require('proc-log') +const npa = require('npm-package-arg') +const npmFetch = require('npm-registry-fetch') +const { logStageItem } = require('../../utils/key-values.js') +const BaseCommand = require('../../base-cmd.js') + +class StageList extends BaseCommand { + static description = 'List all staged package versions' + static name = 'list' + static usage = ['[]'] + static params = ['json', 'registry'] + + async exec (args) { + let packageFilter = null + if (args[0]) { + const spec = npa(args[0]) + if (spec.rawSpec !== '*') { + throw this.usageError('Version specifiers are not supported for listing staged packages') + } + packageFilter = spec.name + } + const opts = { ...this.npm.flatOptions } + const json = this.npm.config.get('json') + + const allItems = await this.#fetchAllPages(opts, packageFilter) + + if (json) { + output.standard(JSON.stringify(allItems, null, 2), { [META]: true, redact: false }) + return + } + + if (allItems.length === 0) { + if (packageFilter) { + output.standard(`No staged versions of package name "${packageFilter}".`) + } else { + output.standard('No staged packages found.') + } + return + } + + for (let i = 0; i < allItems.length; i++) { + if (i > 0) { + output.standard('') + } + logStageItem(allItems[i], { chalk: this.npm.chalk }) + } + } + + async #fetchAllPages (opts, packageFilter) { + const items = [] + let page = 0 + const perPage = 100 + while (true) { + const query = { page, perPage } + if (packageFilter) { + query.package = packageFilter + } + const res = await npmFetch.json('/-/stage', { + ...opts, + query, + }) + items.push(...res.items) + if (items.length >= res.total || res.items.length < perPage) { + break + } + page++ + } + return items + } +} + +module.exports = StageList diff --git a/lib/commands/stage/publish.js b/lib/commands/stage/publish.js new file mode 100644 index 0000000000000..ff3fa3ad2b9ca --- /dev/null +++ b/lib/commands/stage/publish.js @@ -0,0 +1,13 @@ +const Publish = require('../publish.js') + +class StagePublish extends Publish { + static description = 'Stage a package for publishing, deferring proof-of-presence (2FA) to a later point in time' + static name = 'publish' + static stage = true + static params = Publish.params + static usage = Publish.usage + static workspaces = true + static ignoreImplicitWorkspace = false +} + +module.exports = StagePublish diff --git a/lib/commands/stage/reject.js b/lib/commands/stage/reject.js new file mode 100644 index 0000000000000..2f29a95ea4e96 --- /dev/null +++ b/lib/commands/stage/reject.js @@ -0,0 +1,37 @@ +const { log, output, META } = require('proc-log') +const npmFetch = require('npm-registry-fetch') +const { otplease } = require('../../utils/auth.js') +const { validateUUID } = require('../../utils/validate-uuid.js') +const BaseCommand = require('../../base-cmd.js') + +class StageReject extends BaseCommand { + static description = 'Reject a staged package, removing it from the registry' + static name = 'reject' + static usage = [''] + static params = ['otp', 'registry'] + static positionals = 1 + + async exec (args) { + if (!args[0]) { + throw this.usageError('Missing required ') + } + const stageId = args[0] + validateUUID(stageId, 'stage-id') + const opts = { ...this.npm.flatOptions } + + log.notice('', `Rejecting staged package ${stageId}`) + log.warn('', 'Rejecting will permanently delete this staged publish record and tarball from the registry.') + + await otplease(this.npm, opts, o => + npmFetch(`/-/stage/${stageId}`, { + ...o, + method: 'DELETE', + ignoreBody: true, + }) + ) + + output.standard(`Staged package ${stageId} has been rejected.`, { [META]: true, redact: false }) + } +} + +module.exports = StageReject diff --git a/lib/commands/stage/view.js b/lib/commands/stage/view.js new file mode 100644 index 0000000000000..7f7f663456870 --- /dev/null +++ b/lib/commands/stage/view.js @@ -0,0 +1,34 @@ +const { output, META } = require('proc-log') +const npmFetch = require('npm-registry-fetch') +const { logStageItem } = require('../../utils/key-values.js') +const { validateUUID } = require('../../utils/validate-uuid.js') +const BaseCommand = require('../../base-cmd.js') + +class StageView extends BaseCommand { + static description = 'View details of a specific staged package' + static name = 'view' + static usage = [''] + static params = ['json', 'registry'] + static positionals = 1 + + async exec (args) { + if (!args[0]) { + throw this.usageError('Missing required ') + } + const stageId = args[0] + validateUUID(stageId, 'stage-id') + const opts = { ...this.npm.flatOptions } + const json = this.npm.config.get('json') + + const item = await npmFetch.json(`/-/stage/${stageId}`, opts) + + if (json) { + output.standard(JSON.stringify(item, null, 2), { [META]: true, redact: false }) + return + } + + logStageItem(item, { chalk: this.npm.chalk }) + } +} + +module.exports = StageView diff --git a/lib/commands/star.js b/lib/commands/star.js deleted file mode 100644 index 1b76955810c72..0000000000000 --- a/lib/commands/star.js +++ /dev/null @@ -1,72 +0,0 @@ -const fetch = 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 fetch.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 fetch.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 diff --git a/lib/commands/stars.js b/lib/commands/stars.js deleted file mode 100644 index 1059569979daf..0000000000000 --- a/lib/commands/stars.js +++ /dev/null @@ -1,39 +0,0 @@ -const fetch = 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 fetch.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 diff --git a/lib/commands/start.js b/lib/commands/start.js index a16eade24d21e..54818c5be4da6 100644 --- a/lib/commands/start.js +++ b/lib/commands/start.js @@ -1,6 +1,6 @@ const LifecycleCmd = require('../lifecycle-cmd.js') -// This ends up calling run-script(['start', ...args]) +// This ends up calling run(['start', ...args]) class Start extends LifecycleCmd { static description = 'Start a package' static name = 'start' diff --git a/lib/commands/stop.js b/lib/commands/stop.js index ae3031f06dd96..e6e9c9afca1dd 100644 --- a/lib/commands/stop.js +++ b/lib/commands/stop.js @@ -1,6 +1,6 @@ const LifecycleCmd = require('../lifecycle-cmd.js') -// This ends up calling run-script(['stop', ...args]) +// This ends up calling run(['stop', ...args]) class Stop extends LifecycleCmd { static description = 'Stop a package' static name = 'stop' diff --git a/lib/commands/team.js b/lib/commands/team.js index 089e917909d10..2cac0fb24660c 100644 --- a/lib/commands/team.js +++ b/lib/commands/team.js @@ -1,4 +1,3 @@ -const columns = require('cli-columns') const libteam = require('libnpmteam') const { output } = require('proc-log') const { otplease } = require('../utils/auth.js') @@ -41,9 +40,9 @@ class Team extends BaseCommand { 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. + // 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) { @@ -131,9 +130,11 @@ class Team extends BaseCommand { 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 })) + const more = users.length === 0 ? '' : ':' + output.standard(`@${entity} has ${users.length} user${plural}${more}`) + for (const user of users) { + output.standard(user) + } } } @@ -145,9 +146,11 @@ class Team extends BaseCommand { 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 })) + const more = teams.length === 0 ? '' : ':' + output.standard(`@${entity} has ${teams.length} team${plural}${more}`) + for (const team of teams) { + output.standard(`@${team}`) + } } } } diff --git a/lib/commands/test.js b/lib/commands/test.js index eccc47fc3341c..7dbff0b0b69c2 100644 --- a/lib/commands/test.js +++ b/lib/commands/test.js @@ -1,6 +1,6 @@ const LifecycleCmd = require('../lifecycle-cmd.js') -// This ends up calling run-script(['test', ...args]) +// This ends up calling run(['test', ...args]) class Test extends LifecycleCmd { static description = 'Test a package' static name = 'test' diff --git a/lib/commands/token.js b/lib/commands/token.js index d2e85ffe5a549..b248d6a789a1f 100644 --- a/lib/commands/token.js +++ b/lib/commands/token.js @@ -1,14 +1,38 @@ -const { log, output } = require('proc-log') -const { listTokens, createToken, removeToken } = require('npm-profile') +const { log, output, META } = require('proc-log') +const fetch = require('npm-registry-fetch') const { otplease } = require('../utils/auth.js') const readUserInfo = require('../utils/read-user-info.js') const BaseCommand = require('../base-cmd.js') +async function paginate (href, opts, items = []) { + while (href) { + const result = await fetch.json(href, opts) + items = items.concat(result.objects) + href = result.urls.next + } + return items +} + 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 usage = ['list', 'revoke ', 'create'] + static params = ['name', + 'token-description', + 'expires', + 'packages', + 'packages-all', + 'scopes', + 'orgs', + 'packages-and-scopes-permission', + 'orgs-permission', + 'cidr', + 'bypass-2fa', + 'password', + 'registry', + 'otp', + 'read-only', + ] static async completion (opts) { const argv = opts.conf.argv.remain @@ -48,7 +72,7 @@ class Token extends BaseCommand { 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) + const tokens = await paginate('/-/npm/v1/tokens', this.npm.flatOptions) if (json) { output.buffer(tokens) return @@ -71,10 +95,8 @@ class Token extends BaseCommand { 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) - /* eslint-disable-next-line max-len */ - output.standard(`${chalk.blue(level)} ${token.token}… with id ${chalk.cyan(token.id)} created ${created}`) + output.standard(`${chalk.blue('Token')} ${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(','))}`) } @@ -90,16 +112,14 @@ class Token extends BaseCommand { 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 tokens = await paginate('/-/npm/v1/tokens', this.npm.flatOptions) + for (const id of args) { 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( - /* eslint-disable-next-line max-len */ `Token ID "${id}" was ambiguous, a new token may have been created since you last ran \`npm token list\`.` ) } else { @@ -110,12 +130,16 @@ class Token extends BaseCommand { toRemove.push(id) } - }) - await Promise.all( - toRemove.map(key => { - return otplease(this.npm, opts, c => removeToken(key, c)) - }) - ) + } + for (const tokenKey of toRemove) { + await otplease(this.npm, this.npm.flatOptions, opts => + fetch(`/-/npm/v1/tokens/token/${tokenKey}`, { + ...opts, + method: 'DELETE', + ignoreBody: true, + }) + ) + } if (json) { output.buffer(toRemove) } else if (parseable) { @@ -129,15 +153,74 @@ class Token extends BaseCommand { 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 name = this.npm.config.get('name') + const tokenDescription = this.npm.config.get('token-description') + const expires = this.npm.config.get('expires') + const packages = this.npm.config.get('packages') + const packagesAll = this.npm.config.get('packages-all') + const scopes = this.npm.config.get('scopes') + const orgs = this.npm.config.get('orgs') + const packagesAndScopesPermission = this.npm.config.get('packages-and-scopes-permission') + const orgsPermission = this.npm.config.get('orgs-permission') + const bypassTwoFactor = this.npm.config.get('bypass-2fa') + let password = this.npm.config.get('password') const validCIDR = await this.validateCIDRList(cidr) - const password = await readUserInfo.password() + + /* istanbul ignore if - skip testing read input */ + if (!password) { + password = await readUserInfo.password() + } + + const tokenData = { + name: name, + password: password, + } + + if (tokenDescription) { + tokenData.description = tokenDescription + } + + if (packages?.length > 0) { + tokenData.packages = packages + } + if (packagesAll) { + tokenData.packages_all = true + } + if (scopes?.length > 0) { + tokenData.scopes = scopes + } + if (orgs?.length > 0) { + tokenData.orgs = orgs + } + + if (packagesAndScopesPermission) { + tokenData.packages_and_scopes_permission = packagesAndScopesPermission + } + if (orgsPermission) { + tokenData.orgs_permission = orgsPermission + } + + // Add expiration in days + if (expires) { + tokenData.expires = parseInt(expires, 10) + } + + // Add optional fields + if (validCIDR?.length > 0) { + tokenData.cidr_whitelist = validCIDR + } + if (bypassTwoFactor) { + tokenData.bypass_2fa = true + } + log.info('token', 'creating') - const result = await otplease( - this.npm, - { ...this.npm.flatOptions }, - c => createToken(password, readonly, validCIDR, c) + const result = await otplease(this.npm, this.npm.flatOptions, opts => + fetch.json('/-/npm/v1/tokens', { + ...opts, + method: 'POST', + body: tokenData, + }) ) delete result.key delete result.updated @@ -147,12 +230,13 @@ class Token extends BaseCommand { 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}`) + output.standard(`Created token ${result.token}`, { [META]: true, redact: false }) if (result.cidr_whitelist?.length) { output.standard(`with IP whitelist: ${chalk.green(result.cidr_whitelist.join(','))}`) } + if (result.expires) { + output.standard(`expires: ${result.expires}`) + } } } @@ -182,7 +266,7 @@ class Token extends BaseCommand { for (const cidr of list) { if (isCidrV6(cidr)) { throw this.invalidCIDRError( - `CIDR whitelist can only contain IPv4 addresses${cidr} is IPv6` + `CIDR whitelist can only contain IPv4 addresses, ${cidr} is IPv6` ) } diff --git a/lib/commands/trust/circleci.js b/lib/commands/trust/circleci.js new file mode 100644 index 0000000000000..5444ccd09ce6e --- /dev/null +++ b/lib/commands/trust/circleci.js @@ -0,0 +1,178 @@ +const Definition = require('@npmcli/config/lib/definitions/definition.js') +const globalDefinitions = require('@npmcli/config/lib/definitions/definitions.js') +const TrustCommand = require('../../trust-cmd.js') +const { trustDefinitions } = require('../../trust-cmd.js') +const { validateUUID } = require('../../utils/validate-uuid.js') + +class TrustCircleCI extends TrustCommand { + static description = 'Create a trusted relationship between a package and CircleCI' + static name = 'circleci' + static positionals = 1 // expects at most 1 positional (package name) + static providerName = 'CircleCI' + static providerEntity = 'CircleCI pipeline' + + static usage = [ + '[package] --org-id --project-id --pipeline-definition-id --vcs-origin [--context-id ...] [--allow-publish] [--allow-stage-publish] [-y|--yes]', + ] + + static definitions = [ + new Definition('org-id', { + default: null, + type: String, + required: true, + description: 'CircleCI organization UUID', + }), + new Definition('project-id', { + default: null, + type: String, + required: true, + description: 'CircleCI project UUID', + }), + new Definition('pipeline-definition-id', { + default: null, + type: String, + required: true, + description: 'CircleCI pipeline definition UUID', + }), + new Definition('vcs-origin', { + default: null, + type: String, + required: true, + description: "CircleCI repository origin in format 'provider/owner/repo'", + }), + new Definition('context-id', { + default: null, + type: [null, String, Array], + description: 'CircleCI context UUID to match', + }), + trustDefinitions['allow-publish'], + trustDefinitions['allow-stage-publish'], + // globals are alphabetical + globalDefinitions['dry-run'], + globalDefinitions.json, + globalDefinitions.registry, + globalDefinitions.yes, + ] + + validateUuid (value, fieldName) { + validateUUID(value, fieldName) + } + + validateVcsOrigin (value) { + // Expected format: provider/owner/repo (e.g., github.com/owner/repo, bitbucket.org/owner/repo) + if (value.includes('://')) { + throw new Error("vcs-origin must not include a scheme (e.g., use 'github.com/owner/repo' not 'https://github.com/owner/repo')") + } + const parts = value.split('/') + if (parts.length < 3) { + throw new Error("vcs-origin must be in format 'provider/owner/repo'") + } + } + + // Generate a URL from vcs-origin (e.g., github.com/npm/repo -> https://github.com/npm/repo) + getVcsOriginUrl (vcsOrigin) { + if (!vcsOrigin) { + return null + } + // vcs-origin format: github.com/owner/repo or bitbucket.org/owner/repo + return `https://${vcsOrigin}` + } + + static optionsToBody (options) { + const { orgId, projectId, pipelineDefinitionId, vcsOrigin, contextIds } = options + const trustConfig = { + type: 'circleci', + claims: { + 'oidc.circleci.com/org-id': orgId, + 'oidc.circleci.com/project-id': projectId, + 'oidc.circleci.com/pipeline-definition-id': pipelineDefinitionId, + 'oidc.circleci.com/vcs-origin': vcsOrigin, + }, + } + if (contextIds && contextIds.length > 0) { + trustConfig.claims['oidc.circleci.com/context-ids'] = contextIds + } + return trustConfig + } + + static bodyToOptions (body) { + return { + ...(body.id) && { id: body.id }, + ...(body.type) && { type: body.type }, + ...(body.claims?.['oidc.circleci.com/org-id']) && { orgId: body.claims['oidc.circleci.com/org-id'] }, + ...(body.claims?.['oidc.circleci.com/project-id']) && { projectId: body.claims['oidc.circleci.com/project-id'] }, + ...(body.claims?.['oidc.circleci.com/pipeline-definition-id']) && { + pipelineDefinitionId: body.claims['oidc.circleci.com/pipeline-definition-id'], + }, + ...(body.claims?.['oidc.circleci.com/vcs-origin']) && { vcsOrigin: body.claims['oidc.circleci.com/vcs-origin'] }, + ...(body.claims?.['oidc.circleci.com/context-ids']) && { contextIds: body.claims['oidc.circleci.com/context-ids'] }, + } + } + + // Override flagsToOptions since CircleCI doesn't use file/entity pattern + async flagsToOptions ({ positionalArgs, flags }) { + const content = await this.optionalPkgJson() + const pkgName = positionalArgs[0] || content.name + + if (!pkgName) { + throw new Error('Package name must be specified either as an argument or in package.json file') + } + + const orgId = flags['org-id'] + const projectId = flags['project-id'] + const pipelineDefinitionId = flags['pipeline-definition-id'] + const vcsOrigin = flags['vcs-origin'] + const contextIds = flags['context-id'] + + // Validate required flags + if (!orgId) { + throw new Error('org-id is required') + } + if (!projectId) { + throw new Error('project-id is required') + } + if (!pipelineDefinitionId) { + throw new Error('pipeline-definition-id is required') + } + if (!vcsOrigin) { + throw new Error('vcs-origin is required') + } + + // Validate formats + this.validateUuid(orgId, 'org-id') + this.validateUuid(projectId, 'project-id') + this.validateUuid(pipelineDefinitionId, 'pipeline-definition-id') + this.validateVcsOrigin(vcsOrigin) + if (contextIds?.length > 0) { + for (const contextId of contextIds) { + this.validateUuid(contextId, 'context-id') + } + } + + return { + values: { + package: pkgName, + orgId, + projectId, + pipelineDefinitionId, + vcsOrigin, + ...(contextIds?.length > 0 && { contextIds }), + }, + fromPackageJson: {}, + warnings: [], + urls: { + package: this.getFrontendUrl({ pkgName }), + vcsOrigin: this.getVcsOriginUrl(vcsOrigin), + }, + } + } + + async exec (positionalArgs, flags) { + await this.createConfigCommand({ + positionalArgs, + flags, + }) + } +} + +module.exports = TrustCircleCI diff --git a/lib/commands/trust/github.js b/lib/commands/trust/github.js new file mode 100644 index 0000000000000..c3434fe40770e --- /dev/null +++ b/lib/commands/trust/github.js @@ -0,0 +1,107 @@ +const Definition = require('@npmcli/config/lib/definitions/definition.js') +const globalDefinitions = require('@npmcli/config/lib/definitions/definitions.js') +const TrustCommand = require('../../trust-cmd.js') +const { trustDefinitions } = require('../../trust-cmd.js') +const path = require('node:path') + +class TrustGitHub extends TrustCommand { + static description = 'Create a trusted relationship between a package and GitHub Actions' + static name = 'github' + static positionals = 1 // expects at most 1 positional (package name) + static providerName = 'GitHub Actions' + static providerEntity = 'GitHub repository' + static providerFile = 'GitHub Actions Workflow' + static providerHostname = 'https://github.com' + + // entity means project / repository + static entityKey = 'repository' + + static usage = [ + '[package] --file [--repo|--repository] [--env|--environment] [--allow-publish] [--allow-stage-publish] [-y|--yes]', + ] + + static definitions = [ + new Definition('file', { + default: null, + type: String, + required: true, + description: 'Name of workflow file within a repositories .GitHub folder (must end in yaml, yml)', + }), + new Definition('repository', { + default: null, + type: String, + description: 'Name of the repository in the format owner/repo', + alias: ['repo'], + }), + new Definition('environment', { + default: null, + type: String, + description: 'CI environment name', + alias: ['env'], + }), + trustDefinitions['allow-publish'], + trustDefinitions['allow-stage-publish'], + // globals are alphabetical + globalDefinitions['dry-run'], + globalDefinitions.json, + globalDefinitions.registry, + globalDefinitions.yes, + ] + + getEntityUrl ({ providerHostname, file, entity }) { + if (file) { + return new URL(`${entity}/blob/HEAD/.github/workflows/${file}`, providerHostname).toString() + } + return new URL(entity, providerHostname).toString() + } + + validateEntity (entity) { + if (entity.split('/').length !== 2) { + throw new Error(`${this.constructor.providerEntity} must be specified in the format owner/repository`) + } + } + + validateFile (file) { + if (file !== path.basename(file)) { + throw new Error('GitHub Actions workflow must be just a file not a path') + } + } + + static optionsToBody (options) { + const { file, repository, environment } = options + const trustConfig = { + type: 'github', + claims: { + repository, + workflow_ref: { + file, + }, + ...(environment) && { environment }, + }, + } + return trustConfig + } + + // Convert API response body to options + static bodyToOptions (body) { + const file = body.claims?.workflow_ref?.file + const repository = body.claims?.repository + const environment = body.claims?.environment + return { + ...(body.id) && { id: body.id }, + ...(body.type) && { type: body.type }, + ...(file) && { file }, + ...(repository) && { repository }, + ...(environment) && { environment }, + } + } + + async exec (positionalArgs, flags) { + await this.createConfigCommand({ + positionalArgs, + flags, + }) + } +} + +module.exports = TrustGitHub diff --git a/lib/commands/trust/gitlab.js b/lib/commands/trust/gitlab.js new file mode 100644 index 0000000000000..809e05ed20020 --- /dev/null +++ b/lib/commands/trust/gitlab.js @@ -0,0 +1,108 @@ +const Definition = require('@npmcli/config/lib/definitions/definition.js') +const globalDefinitions = require('@npmcli/config/lib/definitions/definitions.js') +const TrustCommand = require('../../trust-cmd.js') +const { trustDefinitions } = require('../../trust-cmd.js') +const path = require('node:path') + +class TrustGitLab extends TrustCommand { + static description = 'Create a trusted relationship between a package and GitLab CI/CD' + static name = 'gitlab' + static positionals = 1 // expects at most 1 positional (package name) + static providerName = 'GitLab CI/CD' + static providerEntity = 'GitLab project' + static providerFile = 'GitLab CI/CD Pipeline' + static providerHostname = 'https://gitlab.com' + + // entity means project / repository + static entityKey = 'project' + + static usage = [ + '[package] --file [--project|--repo|--repository] [--env|--environment] [--allow-publish] [--allow-stage-publish] [-y|--yes]', + ] + + static definitions = [ + new Definition('file', { + default: null, + type: String, + required: true, + description: 'Name of pipeline file (e.g., .gitlab-ci.yml)', + }), + new Definition('project', { + default: null, + type: String, + description: 'Name of the project in the format group/project or group/subgroup/project', + }), + new Definition('environment', { + default: null, + type: String, + description: 'CI environment name', + alias: ['env'], + }), + trustDefinitions['allow-publish'], + trustDefinitions['allow-stage-publish'], + // globals are alphabetical + globalDefinitions['dry-run'], + globalDefinitions.json, + globalDefinitions.registry, + globalDefinitions.yes, + ] + + getEntityUrl ({ providerHostname, file, entity }) { + if (file) { + return new URL(`${entity}/-/blob/HEAD/${file}`, providerHostname).toString() + } + return new URL(entity, providerHostname).toString() + } + + validateEntity (entity) { + if (entity.split('/').length < 2) { + throw new Error(`${this.constructor.providerEntity} must be specified in the format group/project or group/subgroup/project`) + } + } + + validateFile (file) { + if (file !== path.basename(file)) { + throw new Error('GitLab CI/CD pipeline file must be just a file not a path') + } + } + + static optionsToBody (options) { + const { file, project, environment } = options + const trustConfig = { + type: 'gitlab', + claims: { + project_path: project, + // this looks off, but this is correct + /** The ref path to the top-level pipeline definition, for example, gitlab.example.com/my-group/my-project//.gitlab-ci.yml@refs/heads/main. Introduced in GitLab 16.2. This claim is null unless the pipeline definition is located in the same project. */ + ci_config_ref_uri: { + file, + }, + ...(environment) && { environment }, + }, + } + return trustConfig + } + + // Convert API response body to options + static bodyToOptions (body) { + const file = body.claims?.ci_config_ref_uri?.file + const project = body.claims?.project_path + const environment = body.claims?.environment + return { + ...(body.id) && { id: body.id }, + ...(body.type) && { type: body.type }, + ...(file) && { file }, + ...(project) && { project }, + ...(environment) && { environment }, + } + } + + async exec (positionalArgs, flags) { + await this.createConfigCommand({ + positionalArgs, + flags, + }) + } +} + +module.exports = TrustGitLab diff --git a/lib/commands/trust/index.js b/lib/commands/trust/index.js new file mode 100644 index 0000000000000..9b866a2cd5e61 --- /dev/null +++ b/lib/commands/trust/index.js @@ -0,0 +1,25 @@ +const BaseCommand = require('../../base-cmd.js') + +class Trust extends BaseCommand { + static description = 'Create a trusted relationship between a package and a OIDC provider' + static name = 'trust' + static usage = null + + static subcommands = { + github: require('./github.js'), + gitlab: require('./gitlab.js'), + circleci: require('./circleci.js'), + list: require('./list.js'), + revoke: require('./revoke.js'), + } + + static async completion (opts) { + const argv = opts.conf.argv.remain + if (argv.length === 2) { + return Object.keys(Trust.subcommands) + } + return [] + } +} + +module.exports = Trust diff --git a/lib/commands/trust/list.js b/lib/commands/trust/list.js new file mode 100644 index 0000000000000..3d5c3aeb0dbc1 --- /dev/null +++ b/lib/commands/trust/list.js @@ -0,0 +1,50 @@ +const { otplease } = require('../../utils/auth.js') +const npmFetch = require('npm-registry-fetch') +const npa = require('npm-package-arg') +const TrustCircleCI = require('./circleci.js') +const TrustGithub = require('./github.js') +const TrustGitlab = require('./gitlab.js') +const TrustCommand = require('../../trust-cmd.js') +const globalDefinitions = require('@npmcli/config/lib/definitions/definitions.js') + +class TrustList extends TrustCommand { + static description = 'List trusted relationships for a package' + static name = 'list' + static positionals = 1 // expects at most 1 positional (package name) + + static usage = [ + '[package]', + ] + + static definitions = [ + globalDefinitions.json, + globalDefinitions.registry, + ] + + static bodyToOptions (body) { + if (body.type === 'circleci') { + return TrustCircleCI.bodyToOptions(body) + } else if (body.type === 'github') { + return TrustGithub.bodyToOptions(body) + } else if (body.type === 'gitlab') { + return TrustGitlab.bodyToOptions(body) + } + return TrustCommand.bodyToOptions(body) + } + + async exec (positionalArgs) { + const packageName = positionalArgs[0] || (await this.optionalPkgJson()).name + if (!packageName) { + throw new Error('Package name must be specified either as an argument or in the package.json file') + } + const spec = npa(packageName) + const uri = `/-/package/${spec.escapedName}/trust` + const body = await otplease(this.npm, this.npm.flatOptions, opts => npmFetch.json(uri, { + ...opts, + method: 'GET', + })) + this.displayResponseBody({ body, packageName }) + } +} + +module.exports = TrustList diff --git a/lib/commands/trust/revoke.js b/lib/commands/trust/revoke.js new file mode 100644 index 0000000000000..0f555c0386bc0 --- /dev/null +++ b/lib/commands/trust/revoke.js @@ -0,0 +1,52 @@ +const globalDefinitions = require('@npmcli/config/lib/definitions/definitions.js') +const Definition = require('@npmcli/config/lib/definitions/definition.js') +const { otplease } = require('../../utils/auth.js') +const npmFetch = require('npm-registry-fetch') +const npa = require('npm-package-arg') +const TrustCommand = require('../../trust-cmd.js') + +class TrustRevoke extends TrustCommand { + static description = 'Revoke a trusted relationship for a package' + static name = 'revoke' + static positionals = 1 // expects at most 1 positional (package name) + + static usage = [ + '[package] --id=', + ] + + static definitions = [ + new Definition('id', { + default: null, + type: String, + description: 'ID of the trusted relationship to revoke', + required: true, + }), + globalDefinitions['dry-run'], + globalDefinitions.registry, + ] + + async exec (positionalArgs, flags) { + const dryRun = this.config.get('dry-run') + const pkgName = positionalArgs[0] || (await this.optionalPkgJson()).name + if (!pkgName) { + throw new Error('Package name must be specified either as an argument or in the package.json file') + } + const { id } = flags + if (!id) { + throw new Error('ID of the trusted relationship to revoke must be specified with the --id option') + } + this.dialogue`Attempting to revoke trusted configuration for package ${pkgName} with id ${id}` + if (dryRun) { + return + } + const spec = npa(pkgName) + const uri = `/-/package/${spec.escapedName}/trust/${encodeURIComponent(id)}` + await otplease(this.npm, this.npm.flatOptions, opts => npmFetch(uri, { + ...opts, + method: 'DELETE', + })) + this.dialogue`Revoked trusted configuration for package ${pkgName} with id ${id}` + } +} + +module.exports = TrustRevoke diff --git a/lib/commands/undeprecate.js b/lib/commands/undeprecate.js new file mode 100644 index 0000000000000..79ce66bbe5600 --- /dev/null +++ b/lib/commands/undeprecate.js @@ -0,0 +1,13 @@ +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 diff --git a/lib/commands/uninstall.js b/lib/commands/uninstall.js index f9baebe3bc2e2..eb595c26a45ba 100644 --- a/lib/commands/uninstall.js +++ b/lib/commands/uninstall.js @@ -1,7 +1,9 @@ const { resolve } = require('node:path') const pkgJson = require('@npmcli/package-json') const reifyFinish = require('../utils/reify-finish.js') +const resolveAllowScripts = require('../utils/resolve-allow-scripts.js') const completion = require('../utils/installed-shallow.js') +const { patchRelaxOpts } = require('../utils/cli-only-flag.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') class Uninstall extends ArboristWorkspaceCmd { @@ -11,8 +13,6 @@ class Uninstall extends ArboristWorkspaceCmd { static usage = ['[<@scope>/]...'] static ignoreImplicitWorkspace = false - // TODO - /* istanbul ignore next */ static async completion (opts, npm) { return completion(npm, opts) } @@ -41,11 +41,14 @@ class Uninstall extends ArboristWorkspaceCmd { : this.npm.localPrefix const Arborist = require('@npmcli/arborist') + const { policy: allowScriptsPolicy } = await resolveAllowScripts(this.npm) const opts = { ...this.npm.flatOptions, path, rm: args, workspaces: this.workspaceNames, + allowScripts: allowScriptsPolicy, + ...patchRelaxOpts(this.npm.config), } const arb = new Arborist(opts) await arb.reify(opts) diff --git a/lib/commands/unpublish.js b/lib/commands/unpublish.js index 4944888fe5aca..fc390a2b9edff 100644 --- a/lib/commands/unpublish.js +++ b/lib/commands/unpublish.js @@ -9,9 +9,7 @@ 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.' +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.\nRun with --force to do this.' class Unpublish extends BaseCommand { static description = 'Remove a package from the registry' @@ -26,6 +24,7 @@ class Unpublish extends BaseCommand { ...opts, spec: name, query: { write: true }, + _isRoot: true, }) return Object.keys(packument.versions) } @@ -44,9 +43,7 @@ class Unpublish extends BaseCommand { } 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 + // 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 @@ -84,10 +81,7 @@ class Unpublish extends BaseCommand { 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.' - ) + throw this.usageError('Can only unpublish a single version, or the entire project.\nTags and ranges are not supported.') } } @@ -95,10 +89,7 @@ class Unpublish extends BaseCommand { log.silly('unpublish', 'spec', spec) if (spec?.rawSpec === '*' && !force) { - throw this.usageError( - 'Refusing to delete entire project.\n' + - 'Run with --force to do this.' - ) + throw this.usageError('Refusing to delete entire project.\nRun with --force to do this.') } const opts = { ...this.npm.flatOptions } @@ -110,14 +101,12 @@ class Unpublish extends BaseCommand { } catch (err) { if (err.code === 'ENOENT' || err.code === 'ENOTDIR') { if (!spec) { - // We needed a local package.json to figure out what package to - // unpublish + // 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. + // They may be relying on `publishConfig` to be loading and we don't want to ignore errors in that case. throw err } } @@ -130,21 +119,19 @@ class Unpublish extends BaseCommand { 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.' - ) + throw this.usageError('Refusing to delete entire project.\nRun 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 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 + // 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))) + for (const key in filteredPublishConfig) { + this.npm.config.checkUnknown('publishConfig', key) + } flatten(filteredPublishConfig, opts) } diff --git a/lib/commands/unstar.js b/lib/commands/unstar.js deleted file mode 100644 index c72966866669a..0000000000000 --- a/lib/commands/unstar.js +++ /dev/null @@ -1,8 +0,0 @@ -const Star = require('./star.js') - -class Unstar extends Star { - static description = 'Remove an item from your favorite packages' - static name = 'unstar' -} - -module.exports = Unstar diff --git a/lib/commands/update.js b/lib/commands/update.js index 235a9a41177df..64c2c5128bb04 100644 --- a/lib/commands/update.js +++ b/lib/commands/update.js @@ -1,6 +1,9 @@ const path = require('node:path') const { log } = require('proc-log') const reifyFinish = require('../utils/reify-finish.js') +const resolveAllowScripts = require('../utils/resolve-allow-scripts.js') +const strictAllowScriptsPreflight = require('../utils/strict-allow-scripts-preflight.js') +const { patchRelaxOpts } = require('../utils/cli-only-flag.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') class Update extends ArboristWorkspaceCmd { @@ -19,7 +22,13 @@ class Update extends ArboristWorkspaceCmd { 'package-lock', 'foreground-scripts', 'ignore-scripts', + 'allow-scripts', + 'strict-allow-scripts', + 'dangerously-allow-all-scripts', 'audit', + 'before', + 'min-release-age', + 'min-release-age-exclude', 'bin-links', 'fund', 'dry-run', @@ -28,8 +37,6 @@ class Update extends ArboristWorkspaceCmd { static usage = ['[...]'] - // TODO - /* istanbul ignore next */ static async completion (opts, npm) { const completion = require('../utils/installed-deep.js') return completion(npm, opts) @@ -40,8 +47,7 @@ class Update extends ArboristWorkspaceCmd { 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` + // 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') @@ -52,15 +58,20 @@ class Update extends ArboristWorkspaceCmd { } const Arborist = require('@npmcli/arborist') + const { policy: allowScriptsPolicy } = await resolveAllowScripts(this.npm) const opts = { ...this.npm.flatOptions, path: where, save, workspaces: this.workspaceNames, + allowScripts: allowScriptsPolicy, + ...patchRelaxOpts(this.npm.config), } const arb = new Arborist(opts) - await arb.reify({ ...opts, update }) + const reifyOpts = { ...opts, update } + await strictAllowScriptsPreflight({ arb, npm: this.npm, idealTreeOpts: reifyOpts }) + await arb.reify(reifyOpts) await reifyFinish(this.npm, arb) } } diff --git a/lib/commands/version.js b/lib/commands/version.js index d6c2dd4caed75..67b17cfbf3967 100644 --- a/lib/commands/version.js +++ b/lib/commands/version.js @@ -13,16 +13,18 @@ class Version extends BaseCommand { 'json', 'preid', 'sign-git-tag', + 'save', 'workspace', 'workspaces', 'workspaces-update', 'include-workspace-root', + 'ignore-scripts', ] static workspaces = true static ignoreImplicitWorkspace = false + static skipConfigValidation = true - /* eslint-disable-next-line max-len */ static usage = ['[ | major | minor | patch | premajor | preminor | prepatch | prerelease | from-git]'] static async completion (opts) { diff --git a/lib/commands/view.js b/lib/commands/view.js index cf7292a2f3b81..9a3d8f29233c4 100644 --- a/lib/commands/view.js +++ b/lib/commands/view.js @@ -1,4 +1,3 @@ -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') @@ -32,8 +31,7 @@ class View extends BaseCommand { 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 + // 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 @@ -41,6 +39,7 @@ class View extends BaseCommand { ...npm.flatOptions, fullMetadata: true, preferOnline: true, + _isRoot: true, } const spec = npa(opts.conf.argv.remain[2]) const pckmnt = await packument(spec, config) @@ -103,8 +102,7 @@ class View extends BaseCommand { 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 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}:`) } @@ -136,6 +134,7 @@ class View extends BaseCommand { ...this.npm.flatOptions, preferOnline: true, fullMetadata: true, + _isRoot: true, }) // get the data about this package @@ -205,6 +204,7 @@ class View extends BaseCommand { const includeVersions = versions.length > 1 let includeFields + // TODO if we ask for two fields but only one existed we treat it as if we only asked for one field, this needs to be fixed const res = versions.flatMap((v) => { const fields = Object.entries(data[v]) @@ -240,19 +240,12 @@ class View extends BaseCommand { }) 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. + // Users can expect an array . 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 } @@ -266,6 +259,20 @@ class View extends BaseCommand { const deps = Object.entries(manifest.dependencies || {}).map(([k, dep]) => `${chalk.blue(k)}: ${dep}` ) + + // Sort dist-tags by publish time when available, then by tag name, keeping `latest` at the top of the list. + const distTags = Object.entries(packu['dist-tags']) + .sort(([aTag, aVer], [bTag, bVer]) => { + const timeMap = packu.time || {} + const aTime = aTag === 'latest' ? Infinity : Date.parse(timeMap[aVer] || 0) + const bTime = bTag === 'latest' ? Infinity : Date.parse(timeMap[bVer] || 0) + 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' @@ -317,7 +324,7 @@ class View extends BaseCommand { if (deps.length) { const maxDeps = 24 res.push('\ndependencies:') - res.push(columns(deps.slice(0, maxDeps), { padding: 1 })) + res.push(deps.slice(0, maxDeps).join(', ')) if (deps.length > maxDeps) { res.push(chalk.dim(`(...and ${deps.length - maxDeps} more.)`)) } @@ -333,9 +340,11 @@ class View extends BaseCommand { } res.push('\ndist-tags:') - res.push(columns(Object.entries(packu['dist-tags']).map(([k, t]) => - `${chalk.blue(k)}: ${t}` - ))) + const maxTags = 5 + res.push(distTags.slice(0, maxTags).join('\n')) + if (distTags.length > maxTags) { + res.push(chalk.dim(`(...and ${distTags.length - maxTags} more.)`)) + } const publisher = manifest._npmUser && unparsePerson({ name: chalk.blue(manifest._npmUser.name), @@ -343,7 +352,7 @@ class View extends BaseCommand { }) if (publisher || packu.time) { let publishInfo = 'published' - if (packu.time) { + if (packu.time?.[manifest.version]) { publishInfo += ` ${chalk.cyan(relativeDate(packu.time[manifest.version]))}` } if (publisher) { @@ -432,10 +441,12 @@ function cleanup (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)) + (keys.length === 2 && (data.email || data.url)) || + data.trustedPublisher )) { data = unparsePerson(data) } diff --git a/lib/lifecycle-cmd.js b/lib/lifecycle-cmd.js index a509a9380f668..e4604b6115131 100644 --- a/lib/lifecycle-cmd.js +++ b/lib/lifecycle-cmd.js @@ -1,7 +1,7 @@ const BaseCommand = require('./base-cmd.js') // The implementation of commands that are just "run a script" -// restart, start, stop, test +// e.g. restart, start, stop, test class LifecycleCmd extends BaseCommand { static usage = ['[-- ]'] static isShellout = true @@ -9,11 +9,11 @@ class LifecycleCmd extends BaseCommand { static ignoreImplicitWorkspace = false async exec (args) { - return this.npm.exec('run-script', [this.constructor.name, ...args]) + return this.npm.exec('run', [this.constructor.name, ...args]) } async execWorkspaces (args) { - return this.npm.exec('run-script', [this.constructor.name, ...args]) + return this.npm.exec('run', [this.constructor.name, ...args]) } } diff --git a/lib/npm.js b/lib/npm.js index 5563cec21ba4d..5c42dbe57f183 100644 --- a/lib/npm.js +++ b/lib/npm.js @@ -1,8 +1,7 @@ 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 { definitions, flatten, nerfDarts, 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') @@ -26,7 +25,7 @@ class Npm { command: c, }) } - return require(`./commands/${command}.js`) + return require(`./commands/${command}`) } unrefPromises = [] @@ -43,18 +42,13 @@ class Npm { #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 + // 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 + // - 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, @@ -68,9 +62,11 @@ class Npm { npmPath: this.#npmRoot, definitions, flatten, + nerfDarts, shorthands, argv: [...process.argv, ...argv], excludeNpmCwd, + warn: false, }) } @@ -85,16 +81,6 @@ class Npm { } 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 @@ -106,17 +92,14 @@ class Npm { } // 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. + // 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 + // 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, @@ -129,53 +112,57 @@ class Npm { process.env.COLOR = this.color ? '1' : '0' // npm -v - // return from here early so we dont create any caches/logfiles/timers etc + // return from here early so we don't 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`) + // extension-file selects root-owned install-time code, so it is only honored from project config or the command line. + // This is checked after #display.load() so the error is surfaced to the user instead of being swallowed during early config loading. + const extensionFile = this.config.get('extension-file') + if (extensionFile != null) { + const where = this.config.find('extension-file') + if (!['cli', 'project', 'default'].includes(where)) { + throw Object.assign( + new Error(`\`extension-file\` may only be set in project config or on the command line, not from ${where} config`), + { code: 'ENPMEXTENSIONCONFIG' } + ) + } + } + + // 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 + // 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. + // 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. + // 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. + // 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. + // 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, @@ -219,15 +206,70 @@ class Npm { 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. + // since 'test', 'start', 'stop', etc. commands re-enter this function to call the run command, we need to only set it one time. if (!this.#command) { this.#command = command process.env.npm_command = this.command } + // Only log warnings for legacy commands without definitions or subcommands + // Commands with definitions will handle warnings in base-cmd flags() + // Commands with subcommands will delegate to the subcommand to handle warnings + if (!Command.definitions && !Command.subcommands) { + this.config.logWarnings() + } + + // this needs to be rest after because some commands run this.npm.config.checkUnknown('publishConfig', key) + this.config.warn = true + + return this.execCommandClass(command, args, [cmd]) + } + + // Unified command execution for both top-level commands and subcommands + // Supports n-depth subcommands, workspaces, and definitions + async execCommandClass (commandInstance, args, commandPath = []) { + const Command = commandInstance.constructor + const commandName = commandPath.join(':') + + // Handle subcommands if present + if (Command.subcommands) { + const subcommandName = args[0] + + // If help is requested without a subcommand, show main command help + if (this.config.get('usage') && !subcommandName) { + return output.standard(commandInstance.usage) + } + + // If no subcommand provided, show usage error + if (!subcommandName) { + throw commandInstance.usageError() + } + + // Check if the subcommand exists + const SubCommand = Command.subcommands[subcommandName] + if (!SubCommand) { + throw commandInstance.usageError(`Unknown subcommand: ${subcommandName}`) + } + + // Check if help is requested for the subcommand + if (this.config.get('usage')) { + const parentName = commandPath.join(' ') + return output.standard(SubCommand.getUsage(parentName)) + } + + // Create subcommand instance and recurse + const subcommandInstance = new SubCommand(this) + subcommandInstance.parentName = commandPath.join(' ') + const subcommandArgs = args.slice(1) // Remove subcommand name from args + const subcommandPath = [...commandPath, subcommandName] + + return time.start(`command:${subcommandPath.join(':')}`, () => + this.execCommandClass(subcommandInstance, subcommandArgs, subcommandPath)) + } + + // No subcommands - execute this command if (this.config.get('usage')) { - return output.standard(command.usage) + return output.standard(commandInstance.usage) } let execWorkspaces = false @@ -247,12 +289,31 @@ class Npm { execWorkspaces = true } - return time.start(`command:${cmd}`, () => - execWorkspaces ? command.execWorkspaces(args) : command.exec(args)) + // Check dev engines if needed + if (commandInstance.checkDevEngines && !this.global) { + await commandInstance.checkDevEngines() + } + + // Execute command with or without definitions + if (Command.definitions) { + // config.argv contains the full argv with flags (set by Config in production, by MockNpm in tests) + // Pass depth so flags() knows how many command names to skip + const [flags, positionalArgs] = commandInstance.flags(commandPath.length) + return time.start(`command:${commandName}`, () => + execWorkspaces + ? commandInstance.execWorkspaces(positionalArgs, flags) + : commandInstance.exec(positionalArgs, flags)) + } else { + // Legacy commands without definitions: still validate unknown CLI configs/flags and (when finite) extra positionals. + if (typeof commandInstance.validateCli === 'function') { + commandInstance.validateCli([], args) + } + return time.start(`command:${commandName}`, () => + execWorkspaces ? commandInstance.execWorkspaces(args) : commandInstance.exec(args)) + } } - // This gets called at the end of the exit handler and - // during any tests to cleanup all of our listeners + // 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() @@ -271,8 +332,7 @@ class Npm { 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 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), }) @@ -361,9 +421,7 @@ class Npm { 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) + // 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 } diff --git a/lib/package-url-cmd.js b/lib/package-url-cmd.js index c7ae32174fcb6..5a45b92057245 100644 --- a/lib/package-url-cmd.js +++ b/lib/package-url-cmd.js @@ -23,12 +23,12 @@ class PackageUrlCommand extends BaseCommand { } for (const arg of args) { - // XXX It is very odd that `where` is how pacote knows to look anywhere - // other than the cwd. + // 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, + _isRoot: true, } const mani = await pacote.manifest(arg, opts) const url = this.getUrl(arg, mani) @@ -45,9 +45,8 @@ class PackageUrlCommand extends BaseCommand { 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 + // 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 diff --git a/lib/trust-cmd.js b/lib/trust-cmd.js new file mode 100644 index 0000000000000..4371cc4488a9b --- /dev/null +++ b/lib/trust-cmd.js @@ -0,0 +1,345 @@ +const BaseCommand = require('./base-cmd.js') +const { otplease } = require('./utils/auth.js') +const npmFetch = require('npm-registry-fetch') +const npa = require('npm-package-arg') +const { read: _read } = require('read') +const { input, output, log, META } = require('proc-log') +const gitinfo = require('hosted-git-info') +const pkgJson = require('@npmcli/package-json') +const Definition = require('@npmcli/config/lib/definitions/definition.js') + +const NPM_FRONTEND = 'https://www.npmjs.com' + +const PERMISSIONS = { + CREATE_PACKAGE: 'createPackage', + CREATE_STAGED_PACKAGE: 'createStagedPackage', +} + +const trustDefinitions = { + 'allow-publish': new Definition('allow-publish', { + default: false, + type: Boolean, + description: 'Allow npm publish for this trusted publisher configuration', + }), + 'allow-stage-publish': new Definition('allow-stage-publish', { + default: false, + type: Boolean, + description: 'Allow npm stage publish for this trusted publisher configuration', + alias: ['allow-staged-publish'], + }), +} + +class TrustCommand extends BaseCommand { + // Helper to format template strings with color + // Blue text with reset color for interpolated values + warnString (strings, ...values) { + const chalk = this.npm.chalk + const message = strings.reduce((result, str, i) => { + return result + chalk.blue(str) + (values[i] ? chalk.reset(values[i]) : '') + }, '') + return message + } + + // Log a warning message with blue formatting + warn (strings, ...values) { + log.warn('trust', this.warnString(strings, ...values)) + } + + // dialogue is non-log text that is different from our usual npm prefix logging + // it should always show to the user unless --json is specified + // it's not controlled by log levels + dialogue (strings, ...values) { + const json = this.config.get('json') + if (!json) { + output.standard(this.warnString(strings, ...values)) + } + } + + createConfig (pkg, body) { + const spec = npa(pkg) + const uri = `/-/package/${spec.escapedName}/trust` + return otplease(this.npm, this.npm.flatOptions, opts => npmFetch(uri, { + ...opts, + method: 'POST', + body: body, + })) + } + + static permissionLabels = { + [PERMISSIONS.CREATE_PACKAGE]: 'publish', + [PERMISSIONS.CREATE_STAGED_PACKAGE]: 'stage publish', + } + + static formatPermissions (permissions) { + if (!Array.isArray(permissions) || permissions.length === 0) { + return null + } + return permissions + .map(p => TrustCommand.permissionLabels[p] || p) + .join(', ') + } + + logOptions (options, pad = true) { + const { values, warnings, fromPackageJson, urls, permissions } = { warnings: [], ...options } + if (warnings && warnings.length > 0) { + for (const warningMsg of warnings) { + log.warn('trust', warningMsg) + } + } + + const json = this.config.get('json') + if (json) { + const jsonValues = { ...options.values } + if (permissions) { + jsonValues.permissions = permissions + } + // Disable redaction: trust config values (e.g. CircleCI UUIDs) are not secrets + output.standard(JSON.stringify(jsonValues, null, 2), { [META]: true, redact: false }) + return + } + + const chalk = this.npm.chalk + const { type, id, ...rest } = values || {} + + if (values) { + const lines = [] + if (type) { + lines.push(`type: ${chalk.green(type)}`) + } + if (id) { + lines.push(`id: ${chalk.green(id)}`) + } + for (const [key, value] of Object.entries(rest)) { + if (value !== null && value !== undefined) { + const parts = [ + `${chalk.reset(key)}: ${chalk.green(value)}`, + ] + if (fromPackageJson && fromPackageJson[key]) { + parts.push(`(${chalk.yellow(`from package.json`)})`) + } + lines.push(parts.join(' ')) + } + } + const formattedPermissions = TrustCommand.formatPermissions(permissions) + if (formattedPermissions) { + lines.push(`${chalk.reset('permissions')}: ${chalk.green(formattedPermissions)}`) + } + if (pad) { + output.standard() + } + output.standard(lines.join('\n'), { [META]: true, redact: false }) + // Print URLs on their own lines after config, following the same order as rest keys + if (urls) { + const urlLines = [] + for (const key of Object.keys(rest)) { + if (urls[key]) { + urlLines.push(chalk.blue(urls[key])) + } + } + if (urlLines.length > 0) { + output.standard() + output.standard(urlLines.join('\n'), { [META]: true, redact: false }) + } + } + if (pad) { + output.standard() + } + } + } + + async confirmOperation (yes) { + // Ask for confirmation unless --yes flag is set + if (yes === true) { + return + } + if (yes === false) { + throw new Error('User cancelled operation') + } + const confirm = await input.read( + () => _read({ prompt: 'Do you want to proceed? (y/N) ', default: 'n' }) + ) + const normalized = confirm.toLowerCase() + if (['y', 'yes'].includes(normalized)) { + return + } + throw new Error('User cancelled operation') + } + + getFrontendUrl ({ pkgName }) { + if (this.registryIsDefault) { + return new URL(`/package/${pkgName}`, NPM_FRONTEND).toString() + } + return null + } + + getRepositoryFromPackageJson (pkg) { + const info = gitinfo.fromUrl(pkg.repository?.url || pkg?.repository) + if (!info) { + return null + } + const repository = info.user + '/' + info.project + const type = info.type + return { repository, type } + } + + async optionalPkgJson () { + try { + const { content } = await pkgJson.normalize(this.npm.prefix) + return content + } catch (err) { + return {} + } + } + + get registryIsDefault () { + return this.npm.config.defaults.registry === this.npm.config.get('registry') + } + + // generic + static bodyToOptions (body) { + return { + ...(body.id) && { id: body.id }, + ...(body.type) && { type: body.type }, + } + } + + async createConfigCommand ({ positionalArgs, flags }) { + const { providerName, providerEntity, providerHostname } = this.constructor + const dryRun = this.config.get('dry-run') + const yes = this.config.get('yes') // deep-lore this allows for --no-yes + + const allowPublish = flags['allow-publish'] + const allowStagePublish = flags['allow-stage-publish'] + + if (!allowPublish && !allowStagePublish) { + throw new Error('At least one permission flag is required (--allow-publish, --allow-stage-publish)') + } + + const permissions = [] + if (allowPublish) { + permissions.push(PERMISSIONS.CREATE_PACKAGE) + } + if (allowStagePublish) { + permissions.push(PERMISSIONS.CREATE_STAGED_PACKAGE) + } + + const options = await this.flagsToOptions({ positionalArgs, flags, providerHostname }) + this.dialogue`Establishing trust between ${options.values.package} package and ${providerName}` + this.dialogue`Anyone with ${providerEntity} write access can publish to ${options.values.package}` + this.dialogue`Two-factor authentication is required for this operation` + if (!this.registryIsDefault) { + this.warn`Registry ${this.npm.config.get('registry')} may not support trusted publishing` + } + this.logOptions({ ...options, permissions }) + if (dryRun) { + return + } + await this.confirmOperation(yes) + const trustConfig = this.constructor.optionsToBody(options.values) + trustConfig.permissions = permissions + const response = await this.createConfig(options.values.package, [trustConfig]) + const body = await response.json() + this.dialogue`Trust configuration created successfully for ${options.values.package} with the following settings:` + this.displayResponseBody({ body, packageName: options.values.package }) + } + + async flagsToOptions ({ positionalArgs, flags, providerHostname }) { + const { entityKey, name, providerEntity, providerFile } = this.constructor + const content = await this.optionalPkgJson() + const pkgPositional = positionalArgs[0] + const pkgJsonName = content.name + const git = this.getRepositoryFromPackageJson(content) + // the provided positional matches package.json name or no positional provided + const matchPkg = (!pkgPositional || pkgPositional === pkgJsonName) + const pkgName = pkgPositional || pkgJsonName + const usedPkgNameFromPkgJson = !pkgPositional && Boolean(pkgJsonName) + const invalidPkgJsonProviderType = matchPkg && git && git?.type !== name + + let entity + let entitySource + + if (flags[entityKey]) { + entity = flags[entityKey] + entitySource = 'flag' + } else if (!invalidPkgJsonProviderType && git?.repository) { + entity = git.repository + entitySource = 'package.json' + } + const mismatchPkgJsonRepository = matchPkg && git && entity !== git.repository + const usedRepositoryInPkgJson = entitySource === 'package.json' + + const warnings = [] + if (!pkgName) { + throw new Error('Package name must be specified either as an argument or in package.json file') + } + + if (!flags.file) { + throw new Error(`${providerFile} must be specified with the file option`) + } + if (!flags.file.endsWith('.yml') && !flags.file.endsWith('.yaml')) { + throw new Error(`${providerFile} must end in .yml or .yaml`) + } + + this.validateFile?.(flags.file) + + if (invalidPkgJsonProviderType) { + const message = this.warnString`Repository in package.json is not a ${providerEntity}` + if (!flags[entityKey]) { + throw new Error(message) + } else { + warnings.push(message) + } + } else { + if (mismatchPkgJsonRepository) { + warnings.push(this.warnString`Repository in package.json (${git.repository}) differs from provided ${providerEntity} (${entity})`) + } + } + + if (!entity && matchPkg) { + throw new Error(`${providerEntity} must be specified with ${entityKey} option or inferred from the package.json repository field`) + } + if (!entity) { + throw new Error(`${providerEntity} must be specified with ${entityKey} option`) + } + + this.validateEntity(entity) + + return { + values: { + package: pkgName, + file: flags.file, + [entityKey]: entity, + ...(flags.environment && { environment: flags.environment }), + }, + fromPackageJson: { + [entityKey]: usedRepositoryInPkgJson, + package: usedPkgNameFromPkgJson, + }, + warnings: warnings, + urls: { + package: this.getFrontendUrl({ pkgName }), + [entityKey]: this.getEntityUrl({ providerHostname, entity }), + file: this.getEntityUrl({ providerHostname, entity, file: flags.file }), + }, + } + } + + displayResponseBody ({ body, packageName }) { + if (!body || body.length === 0) { + this.dialogue`No trust configurations found for package (${packageName})` + return + } + const items = Array.isArray(body) ? body : [body] + for (const config of items) { + const values = this.constructor.bodyToOptions(config) + const permissions = config.permissions + output.standard() + this.logOptions({ values, permissions }, false) + } + output.standard() + } +} + +module.exports = TrustCommand +module.exports.NPM_FRONTEND = NPM_FRONTEND +module.exports.trustDefinitions = trustDefinitions diff --git a/lib/utils/allow-scripts-cmd.js b/lib/utils/allow-scripts-cmd.js new file mode 100644 index 0000000000000..d028936cadf5d --- /dev/null +++ b/lib/utils/allow-scripts-cmd.js @@ -0,0 +1,303 @@ +const { log, output } = require('proc-log') +const npa = require('npm-package-arg') +const semver = require('semver') +const pkgJson = require('@npmcli/package-json') +const { trustedDisplay } = require('@npmcli/arborist/lib/script-allowed.js') +const checkAllowScripts = require('./check-allow-scripts.js') +const resolveAllowScripts = require('./resolve-allow-scripts.js') +const { + applyApprovalForPackage, + applyDenyForPackage, + nameKeyFor, +} = require('./allow-scripts-writer.js') +const BaseCommand = require('../base-cmd.js') + +// Parse a positional arg into a name and an optional version range. A bare +// name matches every installed version; `pkg@1.2.3` or `pkg@^1` narrows by +// semver. npm-package-arg handles dotted and scoped names; fall back to the +// raw string as the name if it can't be parsed. +const parsePositional = (arg) => { + let parsed + try { + parsed = npa(arg) + } catch { + return { name: arg, range: null } + } + const name = parsed.name || arg + if (parsed.type === 'version' || parsed.type === 'range') { + const spec = parsed.fetchSpec + const range = (!spec || spec === '*' || parsed.rawSpec === '' || parsed.rawSpec === '*') + ? null + : spec + return { name, range } + } + return { name, range: null } +} + +// Shared implementation for `npm approve-scripts` and `npm deny-scripts`. +// Subclasses set `verb` to `'approve'` or `'deny'`. +// +// Extends `BaseCommand` rather than `ArboristCmd` on purpose. Per RFC, +// `allowScripts` is read from the workspace root's `package.json` only; +// individual workspaces don't have their own `allowScripts` field, and +// running approve/deny inside a sub-workspace is identical to running +// it at the root. There's no per-workspace targeting to do, so the +// `--workspace` / `--workspaces` / `--include-workspace-root` params +// from `ArboristCmd` would be misleading no-ops. +class AllowScriptsCmd extends BaseCommand { + static params = ['all', 'allow-scripts-pending', 'allow-scripts-pin', 'json'] + static ignoreImplicitWorkspace = false + + // Subclasses set `static verb = 'approve' | 'deny'`. + get verb () { + /* istanbul ignore next: every concrete subclass declares static verb */ + return this.constructor.verb + } + + async exec (args) { + if (this.npm.global) { + throw Object.assign( + new Error(`\`npm ${this.constructor.name}\` does not work for global installs`), + { code: 'EGLOBAL' } + ) + } + + const pending = !!this.npm.config.get('allow-scripts-pending') + const all = !!this.npm.config.get('all') + + if (pending && (args.length > 0 || all)) { + throw this.usageError( + '`--allow-scripts-pending` cannot be combined with positional arguments or `--all`.' + ) + } + if (!pending && !all && args.length === 0) { + throw this.usageError() + } + if (this.verb === 'deny' && pending) { + throw this.usageError('`npm deny-scripts --allow-scripts-pending` is not supported.') + } + + const Arborist = require('@npmcli/arborist') + const { policy } = await resolveAllowScripts(this.npm) + const arb = new Arborist({ + ...this.npm.flatOptions, + path: this.npm.prefix, + allowScripts: policy, + }) + await arb.loadActual() + + // Keep listing unreviewed packages even with ignore-scripts set, so + // you can move from a blanket ignore-scripts to an allowlist. This + // only lists; nothing runs. + const unreviewed = await checkAllowScripts({ arb, npm: this.npm, includeWhenIgnored: true }) + + if (pending) { + return this.runPending(unreviewed) + } + + if (all) { + return this.runAll(unreviewed) + } + + return this.runPositional(args, arb) + } + + runPending (unreviewed) { + if (this.npm.flatOptions.json) { + output.buffer({ allowScripts: this.pendingSummary(unreviewed) }) + return + } + if (unreviewed.length === 0) { + output.standard('No packages with unreviewed install scripts.') + return + } + const count = unreviewed.length + const has = count === 1 ? 'has' : 'have' + const pkg = count === 1 ? 'package' : 'packages' + output.standard( + `${count} ${pkg} ${has} install scripts blocked because they are not covered by allowScripts:` + ) + for (const { node, scripts } of unreviewed) { + const { name, version } = trustedDisplay(node) + /* istanbul ignore next: every test node has a name */ + const display = name || '' + const ver = version ? `@${version}` : '' + const events = Object.entries(scripts) + .map(([event, cmd]) => `${event}: ${cmd}`) + .join('; ') + output.standard(` ${display}${ver} (${events})`) + } + output.standard('') + output.standard( + 'Run `npm approve-scripts ` to allow, or `npm deny-scripts ` to deny.' + ) + } + + // Build the same `{ name, changes }` shape printSummary uses for writes, + // but tag every entry as `pending` since nothing is written. Names and + // versions are derived exactly like the text listing above. + pendingSummary (unreviewed) { + const groups = new Map() + for (const { node } of unreviewed) { + const { name, version } = trustedDisplay(node) + /* istanbul ignore next: every test node has a name */ + const display = name || '' + const key = version ? `${display}@${version}` : display + if (!groups.has(display)) { + groups.set(display, []) + } + groups.get(display).push({ key, change: 'pending' }) + } + return [...groups].map(([name, changes]) => ({ name, changes })) + } + + async runAll (unreviewed) { + if (unreviewed.length === 0) { + if (this.npm.flatOptions.json) { + output.buffer({ allowScripts: [] }) + return + } + output.standard('No packages with unreviewed install scripts.') + return + } + // Bundled dependencies never appear in `unreviewed` (checkAllowScripts + // skips them because they never run their install scripts and cannot + // be allowlisted), so there is nothing extra to filter here. + const groups = this.groupByPackage(unreviewed.map(({ node }) => node)) + await this.writePolicyChanges(groups) + } + + async runPositional (args, arb) { + const { matched, unmatched } = this.findNodesForArgs(args, arb) + if (unmatched.length > 0) { + throw Object.assign( + new Error(`No installed packages match: ${unmatched.join(', ')}`), + { code: 'ENOMATCH' } + ) + } + const groups = this.groupByPackage(matched) + /* istanbul ignore if: matched is non-empty here; groups only empties when a + matched node has no trusted key, which groupByPackage already warns on */ + if (Object.keys(groups).length === 0) { + throw Object.assign( + new Error(`No installed packages match: ${args.join(', ')}`), + { code: 'ENOMATCH' } + ) + } + await this.writePolicyChanges(groups) + } + + findNodesForArgs (args, arb) { + // Match positional args against each node's trusted name. Registry deps + // use the URL-derived name; non-registry deps fall back to the dependency + // edge name. A version or range on the arg narrows the match to installed + // versions that satisfy it. Bundled deps are excluded for the same reason + // as --all. Args that match nothing are returned in `unmatched`. + const matched = [] + const unmatched = [] + for (const arg of args) { + const { name: wantName, range } = parsePositional(arg) + const found = [] + for (const node of arb.actualTree.inventory.values()) { + if (node.isProjectRoot || node.isWorkspace || node.inBundle) { + continue + } + const { name, version } = trustedDisplay(node) + if (!name || name !== wantName) { + continue + } + if (range && (!version || !semver.satisfies(version, range, { loose: true }))) { + continue + } + found.push(node) + } + if (found.length === 0) { + unmatched.push(arg) + } else { + matched.push(...found) + } + } + return { matched, unmatched } + } + + get logTitle () { + return this.constructor.name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() + } + + groupByPackage (nodes) { + const groups = {} + for (const node of nodes) { + const key = nameKeyFor(node) + /* istanbul ignore if: callers prefilter via inBundle and trustedDisplay so untrusted nodes don't reach here */ + if (!key) { + log.warn( + this.logTitle, + `skipping ${node.name || ''}: no trusted identity for policy key` + ) + continue + } + if (!groups[key]) { + groups[key] = [] + } + groups[key].push(node) + } + return groups + } + + async writePolicyChanges (groups) { + const pin = this.npm.config.get('allow-scripts-pin') !== false + + const pkg = await pkgJson.load(this.npm.prefix) + const content = pkg.content + const existing = content.allowScripts && typeof content.allowScripts === 'object' + ? content.allowScripts + : {} + + let updated = existing + const summary = [] + + for (const [name, nodes] of Object.entries(groups)) { + const result = this.verb === 'approve' + ? applyApprovalForPackage(updated, nodes, { pin }) + : applyDenyForPackage(updated, nodes) + + if (result.warning) { + log.warn(this.logTitle, result.warning) + } + updated = result.allowScripts + summary.push({ name, changes: result.changes }) + } + + /* istanbul ignore else: writePolicyChanges only called when changes are expected */ + if (updated !== existing) { + pkg.update({ allowScripts: updated }) + await pkg.save() + } + + this.printSummary(summary) + } + + printSummary (summary) { + if (this.npm.flatOptions.json) { + output.buffer({ allowScripts: summary }) + return + } + const verb = this.verb === 'approve' ? 'Approved' : 'Denied' + let touched = 0 + for (const { name, changes } of summary) { + if (changes.length === 0) { + continue + } + touched++ + output.standard(`${verb} ${name}:`) + for (const { key, change } of changes) { + output.standard(` ${change} ${key}`) + } + } + if (touched === 0) { + output.standard(`Nothing to ${this.verb}; allowScripts unchanged.`) + } + } +} + +module.exports = AllowScriptsCmd diff --git a/lib/utils/allow-scripts-remediation.js b/lib/utils/allow-scripts-remediation.js new file mode 100644 index 0000000000000..ff8c9b75a81fe --- /dev/null +++ b/lib/utils/allow-scripts-remediation.js @@ -0,0 +1,9 @@ +// Builds the `npm config set allow-scripts` command suggested to global +// users, who have no project package.json for `npm approve-scripts` to +// write to. `--location=user` keeps the setting in the user .npmrc instead +// of trying (and, for global installs, failing) to write it to the local +// project config. +const configSetAllowScripts = (names) => + `npm config set allow-scripts=${names.join(',')} --location=user` + +module.exports = { configSetAllowScripts } diff --git a/lib/utils/allow-scripts-writer.js b/lib/utils/allow-scripts-writer.js new file mode 100644 index 0000000000000..310e22412a4a4 --- /dev/null +++ b/lib/utils/allow-scripts-writer.js @@ -0,0 +1,328 @@ +const npa = require('npm-package-arg') +const { log } = require('proc-log') +const { + getTrustedRegistryIdentity, + resolvedSourceSpecs, +} = require('@npmcli/arborist/lib/script-allowed.js') + +// Pure helpers that implement the RFC's pin-mismatch table for +// `npm approve-scripts` and `npm deny-scripts`. +// +// Approving writes either `"": true` or `"": true` to the +// project's `allowScripts` field, depending on `--allow-scripts-pin` and the currently +// installed versions. +// +// Denying always writes `"": false`, regardless of `--allow-scripts-pin`, per the +// RFC's asymmetric-pin rule. + +const primaryResolvedSource = (node) => resolvedSourceSpecs(node)[0] || '' + +// Convert an arborist Node into the spec string used for a versioned policy +// entry. Returns `null` if the node cannot be represented as a versioned key +// derived from trusted sources (lockfile URL for registry, hosted shortcut +// for git, the resolved file path for local installs). Never falls back to +// `node.packageName` / `node.version`, which are tarball-controlled. +const versionedKeyFor = (node) => { + if (!node) { + return null + } + const resolved = primaryResolvedSource(node) + if (resolved.startsWith('git')) { + try { + const parsed = npa(resolved) + if (parsed.hosted) { + const committish = parsed.gitCommittish || parsed.hosted.committish + const base = parsed.hosted.shortcut({ noCommittish: true }) + return committish ? `${base}#${committish}` : base + } + } catch { + /* istanbul ignore next: npa already parsed this string in keyTargetsNode */ + return null + } + return null + } + if (/^https?:\/\//.test(resolved)) { + const trusted = getTrustedRegistryIdentity(node) + if (trusted && trusted.version) { + return `${trusted.name}@${trusted.version}` + } + // Registry node with a resolved URL that versionFromTgz couldn't + // parse (private-registry mirror, alternate CDN URL shape). Leave a + // breadcrumb so users notice when policy keys are silently pruned. + log.silly( + 'allow-scripts', + `unable to derive trusted versioned key for ${node.path || node.name || ''} ` + + `(resolved: ${resolved}); key will be pruned on next save` + ) + return null + } + /* istanbul ignore next: 'file:' and '/' branches are each covered separately */ + if (resolved.startsWith('file:') || resolved.startsWith('/')) { + return resolved + } + // No trusted source. Refuse to compose a key from attacker-controlled + // `node.packageName` / `node.version`. + /* istanbul ignore next: callers filter out non-registry/non-file nodes before reaching this fallback */ + return null +} + +// Convert an arborist Node into the spec string used for a name-only policy +// entry. Same trust rules as versionedKeyFor — returns `null` rather than +// falling back to tarball-controlled fields. +const nameKeyFor = (node) => { + if (!node) { + return null + } + const resolved = primaryResolvedSource(node) + if (resolved.startsWith('git')) { + try { + const parsed = npa(resolved) + if (parsed.hosted) { + return parsed.hosted.shortcut({ noCommittish: true }) + } + } catch { + /* istanbul ignore next: npa already parsed this string in keyTargetsNode */ + return null + } + return null + } + if (resolved.startsWith('file:') || resolved.startsWith('/')) { + return resolved + } + // Registry deps: only the URL-derived (or edges-derived, in the + // omit-lockfile case) trusted name is acceptable. + const trusted = getTrustedRegistryIdentity(node) + return trusted ? trusted.name : null +} + +const isSingleVersionPin = (key) => { + try { + const parsed = npa(key) + return parsed.type === 'version' + } catch { + return false + } +} + +// Build the warning string emitted when an existing deny entry blocks +// an approval. Per RFC, a name-only deny ("pkg": false) is widest and +// the only remediation is to remove the entry. A versioned deny +// ("pkg@1.2.3": false or a disjunction) blocks only specific versions; +// the user can either widen it via `npm deny-scripts ` or remove +// it to approve the currently-installed version only. +const denyWarning = (key, subject, name) => { + if (isNameOnlyKey(key)) { + return `${key} is denied; remove the entry from allowScripts to approve ${subject}.` + } + /* istanbul ignore next: name fallback is defensive; callers pass nameKeyFor(sample) */ + const widenTarget = name || 'this package' + return `${key} is a versioned deny; run \`npm deny-scripts ${widenTarget}\` ` + + `to widen the deny to all versions of ${widenTarget}, or remove the entry ` + + `to approve ${subject}.` +} + +const isNameOnlyKey = (key) => { + try { + const parsed = npa(key) + if (parsed.type === 'tag') { + return true + } + if (parsed.type === 'range') { + return parsed.fetchSpec === '*' + || parsed.rawSpec === '' + || parsed.rawSpec === '*' + } + return false + } catch { + /* istanbul ignore next: keys reaching this helper have already parsed via keyTargetsNode */ + return false + } +} + +// Does this policy key target this node by identity (ignoring the +// allow/deny value)? +// +// Registry keys (`tag`, `range`, `version`) require a trusted identity on +// the node. If the node has no `getTrustedRegistryIdentity` result, the +// key does not match — never fall back to `node.name`, which is the +// install-directory name and is forgeable through aliases / manifest +// confusion. +const keyTargetsNode = (key, node) => { + let parsed + try { + parsed = npa(key) + } catch { + return false + } + switch (parsed.type) { + case 'tag': + case 'range': + case 'version': { + const trusted = getTrustedRegistryIdentity(node) + if (!trusted) { + return false + } + return trusted.name === parsed.name + } + case 'git': { + let resolvedParsed + try { + const resolved = primaryResolvedSource(node) + resolvedParsed = resolved ? npa(resolved) : null + } catch { + /* istanbul ignore next */ + return false + } + const keyHost = parsed.hosted?.ssh({ noCommittish: true }) + const nodeHost = resolvedParsed?.hosted?.ssh({ noCommittish: true }) + return !!(keyHost && nodeHost && keyHost === nodeHost) + } + case 'file': + case 'directory': + case 'remote': + return resolvedSourceSpecs(node) + .some(resolved => resolved === parsed.saveSpec || resolved === parsed.fetchSpec) + default: + return false + } +} + +// Apply approvals for all currently-installed versions of a single package. +// +// `nodes` must all share an identity (same package name for registry deps, +// or same hosted shortcut for git deps, etc.). The caller is responsible +// for grouping nodes correctly. +// +// Returns `{ allowScripts, changes, warning }` where: +// - `allowScripts` is the new object (the input is never mutated) +// - `changes` is a list of `{ key, change }` entries describing edits +// - `warning` is an optional message to surface to the user +const applyApprovalForPackage = (existing, nodes, { pin = true } = {}) => { + const allowScripts = { ...existing } + const changes = [] + + if (!Array.isArray(nodes) || nodes.length === 0) { + return { allowScripts, changes } + } + + const sample = nodes[0] + const name = nameKeyFor(sample) + + // Deny-wins: any existing false that targets any installed version aborts. + for (const node of nodes) { + for (const [key, value] of Object.entries(allowScripts)) { + if (value === false && keyTargetsNode(key, node)) { + /* istanbul ignore next: name fallback covers the empty-name edge case */ + const subject = name || 'this package' + return { + allowScripts, + changes, + warning: denyWarning(key, subject, name), + } + } + } + } + + if (!pin) { + // Name-only mode: collapse any single-version pins for this package + // into a single name-only entry. + for (const key of Object.keys(allowScripts)) { + if ( + keyTargetsNode(key, sample) && + key !== name && + isSingleVersionPin(key) && + allowScripts[key] === true + ) { + delete allowScripts[key] + } + } + + /* istanbul ignore else: name === null is the no-identity path tested separately */ + if (name && allowScripts[name] !== true) { + allowScripts[name] = true + changes.push({ key: name, change: 'added' }) + } + return { allowScripts, changes } + } + + // Pin mode. For each currently installed version, write a single-version + // pin if one is not already in place. Stale single-version pins for this + // package are removed. Per the RFC's pin-mismatch table, an existing + // name-only entry (`pkg: true`) is replaced by `pkg@x.y.z: true` once + // every installed version has a pin. + const installedKeys = new Set(nodes.map(versionedKeyFor).filter(Boolean)) + + for (const key of Object.keys(allowScripts)) { + if ( + keyTargetsNode(key, sample) && + isSingleVersionPin(key) && + allowScripts[key] === true && + !installedKeys.has(key) + ) { + delete allowScripts[key] + changes.push({ key, change: 'removed-stale' }) + } + } + + for (const key of installedKeys) { + if (allowScripts[key] !== true) { + allowScripts[key] = true + changes.push({ key, change: 'added' }) + } + } + + // Upgrade: drop the name-only entry once every installed version has a + // pin. The operation is convergent: running the command twice produces + // the same shape regardless of the starting state. + if ( + installedKeys.size > 0 && + name && + !installedKeys.has(name) && + allowScripts[name] === true + ) { + delete allowScripts[name] + changes.push({ key: name, change: 'replaced-by-pin' }) + } + + return { allowScripts, changes } +} + +// Apply a deny for a single package. Always name-only; ignores `--allow-scripts-pin`. +const applyDenyForPackage = (existing, nodes) => { + const allowScripts = { ...existing } + const changes = [] + + if (!Array.isArray(nodes) || nodes.length === 0) { + return { allowScripts, changes } + } + + const sample = nodes[0] + const name = nameKeyFor(sample) + if (!name) { + return { allowScripts, changes } + } + + // Drop any pinned allow entries for this package: the name-only deny + // overrides them anyway, and leaving them in place is confusing. + for (const key of Object.keys(allowScripts)) { + if (keyTargetsNode(key, sample) && key !== name) { + delete allowScripts[key] + changes.push({ key, change: 'removed-pinned-allow' }) + } + } + + if (allowScripts[name] !== false) { + allowScripts[name] = false + changes.push({ key: name, change: 'added' }) + } + return { allowScripts, changes } +} + +module.exports = { + applyApprovalForPackage, + applyDenyForPackage, + versionedKeyFor, + nameKeyFor, + keyTargetsNode, + isSingleVersionPin, +} diff --git a/lib/utils/audit-error.js b/lib/utils/audit-error.js index c56ec9ba86f18..a93dbb15de780 100644 --- a/lib/utils/audit-error.js +++ b/lib/utils/audit-error.js @@ -1,13 +1,12 @@ 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 +// 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) { + if (!report?.error) { return false } @@ -34,6 +33,7 @@ const auditError = (npm, report) => { output.standard(body) } + // XXX we should throw a real error here throw 'audit endpoint returned an error' } diff --git a/lib/utils/auth.js b/lib/utils/auth.js index 747271169124b..55e40d5c3c269 100644 --- a/lib/utils/auth.js +++ b/lib/utils/auth.js @@ -1,4 +1,4 @@ -const { webAuthOpener, adduserWeb, loginWeb, loginCouch, adduserCouch } = require('npm-profile') +const { webAuthOpener, loginWeb, loginCouch } = require('npm-profile') const { log } = require('proc-log') const { createOpener } = require('../utils/open-url.js') const read = require('../utils/read-user-info.js') @@ -32,43 +32,6 @@ const otplease = async (npm, opts, fn) => { } } -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 @@ -103,7 +66,6 @@ const login = async (npm, { creds, ...opts }) => { } module.exports = { - adduser, login, otplease, } diff --git a/lib/utils/check-allow-scripts.js b/lib/utils/check-allow-scripts.js new file mode 100644 index 0000000000000..47984803cde7b --- /dev/null +++ b/lib/utils/check-allow-scripts.js @@ -0,0 +1,27 @@ +const { collectUnreviewedScripts } = require('@npmcli/arborist/lib/unreviewed-scripts.js') + +// Walks a tree's inventory and returns the list of dep nodes that have +// install-relevant lifecycle scripts and are not yet covered (or explicitly +// denied) by the allowScripts policy. +// +// Thin wrapper around arborist's shared `collectUnreviewedScripts`, mapping +// the CLI's `({ arb, npm, tree })` shape onto the shared walk. Defaults to +// `arb.actualTree` (post-reify) but accepts an explicit tree so callers can +// pre-flight against the idealTree before scripts run. +// +// Returns an array of `{ node, scripts }` entries. `scripts` is an object +// describing the relevant lifecycle scripts that would run. +// +// `includeWhenIgnored` keeps listing unreviewed packages even when +// ignore-scripts is set, so approve/deny can show what you'd move from a +// blanket ignore-scripts to an allowlist. Execution callers leave it false. +const checkAllowScripts = async ({ arb, npm, tree, includeWhenIgnored = false }) => + collectUnreviewedScripts({ + tree: tree || arb.actualTree, + policy: arb.options?.allowScripts || null, + ignoreScripts: !!arb.options?.ignoreScripts, + dangerouslyAllowAllScripts: !!npm?.flatOptions?.dangerouslyAllowAllScripts, + includeWhenIgnored, + }) + +module.exports = checkAllowScripts diff --git a/lib/utils/cli-only-flag.js b/lib/utils/cli-only-flag.js new file mode 100644 index 0000000000000..760c1eabaa95a --- /dev/null +++ b/lib/utils/cli-only-flag.js @@ -0,0 +1,13 @@ +// Read a config value only when it was passed on the command line. +// Values from .npmrc, env, or defaults resolve to undefined, so the flag cannot be set as project policy. +const cliOnlyFlag = (config, key) => + config.find(key) === 'cli' ? config.get(key) : undefined + +// The patch relax flags, honored only from the command line, as Arborist options. +const patchRelaxOpts = config => ({ + allowUnusedPatches: cliOnlyFlag(config, 'allow-unused-patches'), + ignorePatchFailures: cliOnlyFlag(config, 'ignore-patch-failures'), +}) + +module.exports = cliOnlyFlag +module.exports.patchRelaxOpts = patchRelaxOpts diff --git a/lib/utils/cmd-list.js b/lib/utils/cmd-list.js index 9017b2b80ce52..709456913b491 100644 --- a/lib/utils/cmd-list.js +++ b/lib/utils/cmd-list.js @@ -4,7 +4,7 @@ const abbrev = require('abbrev') // Please keep this list sorted alphabetically const commands = [ 'access', - 'adduser', + 'approve-scripts', 'audit', 'bugs', 'cache', @@ -12,6 +12,7 @@ const commands = [ 'completion', 'config', 'dedupe', + 'deny-scripts', 'deprecate', 'diff', 'dist-tag', @@ -26,7 +27,6 @@ const commands = [ 'get', 'help', 'help-search', - 'hook', 'init', 'install', 'install-ci-test', @@ -40,6 +40,7 @@ const commands = [ 'outdated', 'owner', 'pack', + 'patch', 'ping', 'pkg', 'prefix', @@ -51,21 +52,20 @@ const commands = [ 'repo', 'restart', 'root', - 'run-script', + 'run', 'sbom', 'search', 'set', - 'shrinkwrap', - 'star', - 'stars', + 'stage', 'start', 'stop', 'team', 'test', 'token', + 'trust', + 'undeprecate', 'uninstall', 'unpublish', - 'unstar', 'update', 'version', 'view', @@ -97,6 +97,7 @@ const aliases = { i: 'install', it: 'install-test', cit: 'install-ci-test', + u: 'update', up: 'update', c: 'config', s: 'search', @@ -105,7 +106,7 @@ const aliases = { t: 'test', ddp: 'dedupe', v: 'view', - run: 'run-script', + 'run-script': 'run', 'clean-install': 'ci', 'clean-install-test': 'install-ci-test', x: 'exec', @@ -132,11 +133,11 @@ const aliases = { 'dist-tags': 'dist-tag', upgrade: 'update', udpate: 'update', - rum: 'run-script', + rum: 'run', sit: 'install-ci-test', - urn: 'run-script', + urn: 'run', ogr: 'org', - 'add-user': 'adduser', + } const deref = (c) => { @@ -161,9 +162,8 @@ const deref = (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` + // 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] diff --git a/lib/utils/did-you-mean.js b/lib/utils/did-you-mean.js index 7428ed5df85e9..deec803c9b710 100644 --- a/lib/utils/did-you-mean.js +++ b/lib/utils/did-you-mean.js @@ -19,7 +19,6 @@ const didYouMean = (pkg, scmd) => { .map(str => [`run ${str}`, `run the "${str}" package script`]), ...Object.keys(bin) .filter(cmd => isClose(scmd, cmd)) - /* eslint-disable-next-line max-len */ .map(str => [`exec ${str}`, `run the "${str}" command from either this or a remote npm package`]), ] diff --git a/lib/utils/display.js b/lib/utils/display.js index 67a3b98c0417a..4030c8e32b931 100644 --- a/lib/utils/display.js +++ b/lib/utils/display.js @@ -1,6 +1,7 @@ const { log, output, input, META } = require('proc-log') const { explain } = require('./explain-eresolve.js') const { formatWithOptions } = require('./format') +const { redactLog } = require('@npmcli/redact') // This is the general approach to color: // Eventually this will be exposed somewhere we can refer to these by name. @@ -75,11 +76,9 @@ const setBlocking = (stream) => { 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 +// 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) @@ -92,6 +91,8 @@ const getArrayOrObject = (items) => { return foundNonObject } // We use objects with 0,1,2,etc keys to merge array + // We don't currently use this but want to allow for it again + // istanbul ignore next if (items.every((o, i) => Object.hasOwn(o, i))) { return Object.assign([], ...items) } @@ -100,14 +101,16 @@ const getArrayOrObject = (items) => { return Object.assign({}, ...items.filter(o => isPlainObject(o))) } +const redactValue = (obj) => JSON.parse(redactLog(JSON.stringify(obj))) + 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) { + for (const [, { [JSON_ERROR_KEY]: error, redact = true }, obj] of buffer) { if (obj) { - items.push(obj) + items.push(redact ? redactValue(obj) : obj) } if (error) { errors.push(error) @@ -120,15 +123,12 @@ const getJsonBuffer = ({ [JSON_ERROR_KEY]: metaError }, buffer) => { const res = getArrayOrObject(items) - // This skips any error checking since we can only set an error property - // on an object that can be stringified + // 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. + // 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`) @@ -171,7 +171,6 @@ class Display { #progress // options - #command #levelIndex #timing #json @@ -182,6 +181,8 @@ class Display { #stdout #stderr + #seenNotices = new Set() + constructor ({ stdout, stderr }) { this.#stdout = setBlocking(stdout) this.#stderr = setBlocking(stderr) @@ -200,6 +201,7 @@ class Display { this.#outputState.buffer.length = 0 process.off('input', this.#inputHandler) this.#progress.off() + this.#seenNotices.clear() } get chalk () { @@ -211,7 +213,6 @@ class Display { } async load ({ - command, heading, json, loglevel, @@ -221,15 +222,11 @@ class Display { 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. + // 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 @@ -238,7 +235,6 @@ class Display { 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 @@ -265,8 +261,7 @@ class Display { // HANDLERS - // Arrow function assigned to a private class field so it can be passed - // directly as a listener and still reference "this" + // 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: @@ -289,8 +284,7 @@ class Display { } }) - // Arrow function assigned to a private class field so it can be passed - // directly as a listener and still reference "this" + // 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) { @@ -299,7 +293,9 @@ class Display { if (this.#json) { const json = getJsonBuffer(meta, this.#outputState.buffer) if (json) { - this.#writeOutput(output.KEYS.standard, meta, JSON.stringify(json, null, 2)) + // Per-item redaction already applied in getJsonBuffer, skip string-level redaction + const jsonMeta = { ...meta, redact: false } + this.#writeOutput(output.KEYS.standard, jsonMeta, JSON.stringify(json, null, 2)) } } else { this.#outputState.buffer.forEach((item) => this.#writeOutput(...item)) @@ -316,21 +312,6 @@ class Display { 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 @@ -345,22 +326,37 @@ class Display { this.#progress.off() break - case input.KEYS.end: + case input.KEYS.end: { log.resume() + // For silent prompts (like password), add newline to preserve output + if (meta?.silent) { + output.standard() + } 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 + // 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(''))) + + // Use sequential input management to avoid race condition which causes issues with spinner and adding newlines. + input.start() + + return p() + .then((result) => { + // If user hits enter, process end event and return input. + input.end({ [META]: true, silent: meta?.silent }) + res(result) + return result + }) + .catch((error) => { + // If user hits ctrl+c, add newline to preserve output. + output.standard() + input.end() + rej(error) + }) } } }) @@ -370,11 +366,11 @@ class Display { #writeOutput (level, meta, ...args) { switch (level) { case output.KEYS.standard: - this.#write(this.#stdout, {}, ...args) + this.#write(this.#stdout, meta, ...args) break case output.KEYS.error: - this.#write(this.#stderr, {}, ...args) + this.#write(this.#stderr, meta, ...args) break } } @@ -383,10 +379,7 @@ class Display { #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. + // 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') { @@ -400,8 +393,7 @@ class Display { // 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. + // 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) } @@ -421,7 +413,20 @@ class Display { this.#logColors[level](level), title ? this.#logColors.title(title) : null, ] - this.#write(this.#stderr, { prefix }, ...args) + const writeOpts = { prefix } + // notice logs typically come from `npm-notice` headers in responses. Some of them have 2fa login links so we skip redaction. + if (level === 'notice') { + writeOpts.redact = false + // Deduplicate notices within a single command execution, unless in verbose mode + if (this.#levelIndex < LEVEL_OPTIONS.verbose.index) { + const noticeKey = JSON.stringify([title, ...args]) + if (this.#seenNotices.has(noticeKey)) { + return + } + this.#seenNotices.add(noticeKey) + } + } + this.#write(this.#stderr, writeOpts, ...args) } } } @@ -433,16 +438,17 @@ class Progress { static dots = { duration: 80, frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] } static lines = { duration: 130, frames: ['-', '\\', '|', '/'] } - #stream - #spinner #enabled = false - #frameIndex = 0 - #lastUpdate = 0 #interval + #lastUpdate = 0 + #spinner + #stream + // Initial timeout to wait to start rendering #timeout + #rendered = false - // We are rendering is enabled option is set and we are not waiting for the render timeout + // We are rendering if enabled option is set and we are not waiting for the render timeout get #rendering () { return this.#enabled && !this.#timeout } @@ -459,8 +465,13 @@ class Progress { load ({ enabled, unicode }) { this.#enabled = enabled this.#spinner = unicode ? Progress.dots : Progress.lines - // Dont render the spinner for short durations - this.#render(200) + // Wait 200 ms so we don't render the spinner for short durations + this.#timeout = setTimeout(() => { + this.#timeout = null + this.#render() + }, 200) + // Make sure this timeout does not keep the process open + this.#timeout.unref() } off () { @@ -477,12 +488,11 @@ class Progress { } resume () { - this.#render() + this.#render(true) } - // 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 + // If we are currently 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() @@ -493,31 +503,21 @@ class Progress { } } - #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 () { + #render (resuming) { 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) + // 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, resuming) + if (!this.#interval) { + this.#interval = setInterval(() => this.#renderFrame(true), this.#spinner.duration) + // Make sure this timeout does not keep the process open + this.#interval.unref() + } + this.#interval.refresh() } - #renderFrame (next) { + #renderFrame (next, resuming) { if (next) { this.#lastUpdate = Date.now() this.#frameIndex++ @@ -525,14 +525,21 @@ class Progress { this.#frameIndex = 0 } } - this.#clearSpinner() + if (!resuming) { + this.#clearSpinner() + } this.#stream.write(this.#spinner.frames[this.#frameIndex]) + this.#rendered = true } #clearSpinner () { + if (!this.#rendered) { + return + } // Move to the start of the line and clear the rest of the line this.#stream.cursorTo(0) this.#stream.clearLine(1) + this.#rendered = false } } diff --git a/lib/utils/error-message.js b/lib/utils/error-message.js index fc47c909069f0..41e35bd78ac46 100644 --- a/lib/utils/error-message.js +++ b/lib/utils/error-message.js @@ -7,6 +7,7 @@ const errorMessage = (er, npm) => { const summary = [] const detail = [] const files = [] + let json er.message &&= replaceInfo(er.message) er.stack &&= replaceInfo(er.stack) @@ -16,9 +17,8 @@ const errorMessage = (er, npm) => { 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. + // 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]) @@ -41,8 +41,7 @@ const errorMessage = (er, npm) => { 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'", + `If you are behind a proxy, please make sure that the 'proxy' config is set properly. See: 'npm help config'`, ].join('\n')]) break @@ -58,8 +57,7 @@ const errorMessage = (er, npm) => { 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.', + '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')}"`, @@ -70,20 +68,23 @@ const errorMessage = (er, npm) => { '', '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'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.', + '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 'EALLOWGIT': + case 'EALLOWREMOTE': + summary.push(['', er.message]) + detail.push(['', `Refusing to fetch "${er.package}"`]) + break + case 'ENOGIT': summary.push(['', er.message]) detail.push(['', [ @@ -118,12 +119,23 @@ const errorMessage = (er, npm) => { 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')]) + const authUrl = er.body?.authUrl + const doneUrl = er.body?.doneUrl + if (authUrl && doneUrl) { + json = { authUrl, doneUrl } + summary.push(['', 'This operation requires a one-time password.']) + detail.push(['', `Open this URL in your browser to authenticate:`]) + detail.push(['', ` ${authUrl}`]) + detail.push(['', '']) + detail.push(['', `After authenticating, your token can be retrieved from:`]) + detail.push(['', ` ${doneUrl}`]) + } else { + 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 @@ -142,14 +154,12 @@ const errorMessage = (er, npm) => { } 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.', + '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:', + '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 { @@ -165,7 +175,11 @@ const errorMessage = (er, npm) => { const pkg = er.pkgid.replace(/(?!^)@.*$/, '') detail.push(['404', '']) - detail.push(['404', '', `'${replaceInfo(er.pkgid)}' is not in this registry.`]) + detail.push([ + '404', + '', + `The requested resource '${replaceInfo(er.pkgid)}' could not be found or you do not have permission to access it.`, + ]) const nameValidator = require('validate-npm-package-name') const valResult = nameValidator(pkg) @@ -185,7 +199,7 @@ const errorMessage = (er, npm) => { 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', `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']) @@ -195,11 +209,17 @@ const errorMessage = (er, npm) => { 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.', + '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 } @@ -248,7 +268,7 @@ const errorMessage = (er, npm) => { case 'ENEEDAUTH': summary.push(['need auth', er.message]) - detail.push(['need auth', 'You need to authorize this machine using `npm adduser`']) + detail.push(['need auth', 'You need to authorize this machine using `npm login`']) break case 'ECONNRESET': @@ -261,25 +281,21 @@ const errorMessage = (er, npm) => { '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'", + `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.", + `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.', + '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 @@ -290,7 +306,7 @@ const errorMessage = (er, npm) => { 'Not compatible with your version of node/npm: ' + er.pkgid, 'Required: ' + JSON.stringify(er.required), 'Actual: ' + - JSON.stringify({ npm: npm.version, node: process.version }), + JSON.stringify({ node: process.version, npm: npm.version }), ].join('\n')]) break @@ -305,8 +321,7 @@ const errorMessage = (er, npm) => { 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.", + `Often virtualized file systems, or other file systems that don't support symlinks, give this error.`, ].join('\n')]) break @@ -325,7 +340,7 @@ const errorMessage = (er, npm) => { 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', + 'https://github.com/npm/cli/issues', ].join('\n')]) break @@ -353,6 +368,7 @@ const errorMessage = (er, npm) => { summary, detail, files, + json, } } @@ -365,10 +381,8 @@ const getExitCodeFromError = (err) => { } 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 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, @@ -408,13 +422,12 @@ const getError = (err, { npm, command, pkg }) => { } } - // Anything after this is not suppressed and get more logged information + // Anything after this is not suppressed and gets more logged information - // add a code to the error if it doesnt have one and mutate some properties - // so they have redacted 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) + const { summary, detail, files, json } = errorMessage(err, npm) return { err, @@ -424,6 +437,7 @@ const getError = (err, { npm, command, pkg }) => { summary, detail, files, + json, verbose: ['type', 'stack', 'statusCode', 'pkgid'] .filter(k => err[k]) .map(k => [k, replaceInfo(err[k])]), diff --git a/lib/utils/explain-dep.js b/lib/utils/explain-dep.js index 4e9e93454e8a2..06722c627ec41 100644 --- a/lib/utils/explain-dep.js +++ b/lib/utils/explain-dep.js @@ -1,9 +1,9 @@ const { relative } = require('node:path') -const explainNode = (node, depth, chalk) => +const explainNode = (node, depth, chalk, seen = new Set()) => printNode(node, chalk) + - explainDependents(node, depth, chalk) + - explainLinksIn(node, depth, chalk) + explainDependents(node, depth, chalk, seen) + + explainLinksIn(node, depth, chalk, seen) const colorType = (type, chalk) => { const style = type === 'extraneous' ? chalk.red @@ -34,24 +34,24 @@ const printNode = (node, chalk) => { (node.location ? chalk.dim(`\n${node.location}`) : '') } -const explainLinksIn = ({ linksIn }, depth, chalk) => { +const explainLinksIn = ({ linksIn }, depth, chalk, seen) => { if (!linksIn || !linksIn.length || depth <= 0) { return '' } - const messages = linksIn.map(link => explainNode(link, depth - 1, chalk)) + const messages = linksIn.map(link => explainNode(link, depth - 1, chalk, seen)) const str = '\n' + messages.join('\n') return str.split('\n').join('\n ') } -const explainDependents = ({ dependents }, depth, chalk) => { +const explainDependents = ({ dependents }, depth, chalk, seen) => { 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)) + .map(edge => explainEdge(edge, depth, chalk, seen)) // show just the names of the first 5 deps that overflowed the list if (dependents.length > max) { @@ -75,7 +75,10 @@ const explainDependents = ({ dependents }, depth, chalk) => { return str.split('\n').join('\n ') } -const explainEdge = ({ name, type, bundled, from, spec, rawSpec, overridden }, depth, chalk) => { +const explainEdge = ( + { name, type, bundled, from, spec, rawSpec, overridden, packageExtensions, npmExtension }, + depth, chalk, seen = new Set() +) => { let dep = type === 'workspace' ? chalk.bold(relative(from.location, spec.slice('file:'.length))) : `${name}@"${spec}"` @@ -83,21 +86,41 @@ const explainEdge = ({ name, type, bundled, from, spec, rawSpec, overridden }, d dep = `${colorType('overridden', chalk)} ${dep} (was "${rawSpec}")` } - const fromMsg = ` from ${explainFrom(from, depth, chalk)}` + const fromMsg = ` from ${explainFrom(from, depth, chalk, seen)}` + + // note an edge created by a root packageExtensions repair + const extMsg = packageExtensions + ? chalk.dim(` (added by packageExtensions["${packageExtensions.selector}"].${packageExtensions.field}.${name})`) + : '' + + // note an edge created or changed by a root .npm-extension repair + const npmExtMsg = npmExtension + ? chalk.dim(` (changed by .npm-extension ${npmExtension.extensionPoint} ${npmExtension.field}.${name})`) + : '' return (type === 'prod' ? '' : `${colorType(type, chalk)} `) + (bundled ? `${colorType('bundled', chalk)} ` : '') + - `${dep}${fromMsg}` + `${dep}${fromMsg}${extMsg}${npmExtMsg}` } -const explainFrom = (from, depth, chalk) => { +const explainFrom = (from, depth, chalk, seen) => { if (!from.name && !from.version) { return 'the root project' } - return printNode(from, chalk) + - explainDependents(from, depth - 1, chalk) + - explainLinksIn(from, depth - 1, chalk) + // Prevent infinite recursion from cycles in the dependency graph (e.g. linked strategy store nodes). Use stack-based tracking so diamond dependencies (same node reached via different paths) are still explained, but recursive cycles are broken. + const nodeId = `${from.name}@${from.version}:${from.location}` + if (seen.has(nodeId)) { + return printNode(from, chalk) + } + seen.add(nodeId) + + const result = printNode(from, chalk) + + explainDependents(from, depth - 1, chalk, seen) + + explainLinksIn(from, depth - 1, chalk, seen) + + seen.delete(nodeId) + return result } module.exports = { explainNode, printNode, explainEdge } diff --git a/lib/utils/explain-eresolve.js b/lib/utils/explain-eresolve.js index f3c6ae23a479d..41152a8f4a20f 100644 --- a/lib/utils/explain-eresolve.js +++ b/lib/utils/explain-eresolve.js @@ -1,12 +1,9 @@ -// 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. +// 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: +// expl is an explanation object that comes from Arborist. // 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. +// 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 @@ -18,9 +15,7 @@ const explain = (expl, chalk, depth) => { 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. + // 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) { @@ -55,9 +50,7 @@ const report = (expl, chalk, noColorChalk) => { ? 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.` + 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}`, diff --git a/lib/utils/format-bytes.js b/lib/utils/format-bytes.js index d293001df5524..d111c8cab0945 100644 --- a/lib/utils/format-bytes.js +++ b/lib/utils/format-bytes.js @@ -1,6 +1,5 @@ // 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. +// Only supports up to GB because that's way larger than anything the registry supports anyways. const formatBytes = (bytes, space = true) => { let spacer = '' @@ -13,12 +12,12 @@ const formatBytes = (bytes, space = true) => { return `${bytes}${spacer}B` } - if (bytes < 1000000) { + if (bytes < 999950) { // kB return `${(bytes / 1000).toFixed(1)}${spacer}kB` } - if (bytes < 1000000000) { + if (bytes < 999950000) { // MB return `${(bytes / 1000000).toFixed(1)}${spacer}MB` } diff --git a/lib/utils/format-search-stream.js b/lib/utils/format-search-stream.js index b70bd915123da..fd5f6c2385cc3 100644 --- a/lib/utils/format-search-stream.js +++ b/lib/utils/format-search-stream.js @@ -1,4 +1,3 @@ -/* eslint-disable max-len */ const { stripVTControlCharacters: strip } = require('node:util') const { Minipass } = require('minipass') @@ -13,8 +12,7 @@ const { Minipass } = require('minipass') // date: Date // can be null, // } // -// The returned stream will format this package data -// into a byte stream of formatted, displayable output. +// The returned stream will format this package data into a byte stream of formatted, displayable output. function filter (data, exclude) { const words = [data.name] @@ -82,7 +80,14 @@ class TextOutputStream extends Minipass { constructor (opts) { super() - this.#args = opts.args.map(s => s.toLowerCase()).filter(Boolean) + // 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 @@ -124,38 +129,17 @@ class TextOutputStream extends Minipass { } }).join(' ') - let description = [] - for (const arg of this.#args) { - const finder = pkg.description.toLowerCase().split(arg.toLowerCase()) - let p = 0 - for (const f of finder) { - description.push(pkg.description.slice(p, p + f.length)) - const word = pkg.description.slice(p + f.length, p + f.length + arg.length) - description.push(this.#chalk.cyan(word)) - p += f.length + arg.length - } - } - description = description.filter(Boolean) - let name = pkg.name + const description = this.#highlight(pkg.description) + let name if (this.#args.includes(pkg.name)) { name = this.#chalk.cyan(pkg.name) } else { - name = [] - for (const arg of this.#args) { - const finder = pkg.name.toLowerCase().split(arg.toLowerCase()) - let p = 0 - for (const f of finder) { - name.push(pkg.name.slice(p, p + f.length)) - const word = pkg.name.slice(p + f.length, p + f.length + arg.length) - name.push(this.#chalk.cyan(word)) - p += f.length + arg.length - } - } - name = this.#chalk.blue(name.join('')) + name = this.#highlight(pkg.name) + name = this.#chalk.blue(name) } if (description.length) { - output = `${name}\n${description.join('')}\n` + output = `${name}\n${description}\n` } else { output = `${name}\n` } @@ -171,4 +155,21 @@ class TextOutputStream extends Minipass { 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 + } } diff --git a/lib/utils/format.js b/lib/utils/format.js index aaecfe1ba0e7a..3161abd7ea4de 100644 --- a/lib/utils/format.js +++ b/lib/utils/format.js @@ -1,4 +1,7 @@ +// All logging goes through here, both to console and log files + const { formatWithOptions: baseFormatWithOptions } = require('node:util') +const { redactLog } = require('@npmcli/redact') // These are most assuredly not a mistake // https://eslint.org/docs/latest/rules/no-control-regex @@ -38,9 +41,12 @@ function STRIP_C01 (str) { return result } -const formatWithOptions = ({ prefix: prefixes = [], eol = '\n', ...options }, ...args) => { +const formatWithOptions = ({ prefix: prefixes = [], eol = '\n', redact = true, ...options }, ...args) => { const prefix = prefixes.filter(p => p != null).join(' ') - const formatted = STRIP_C01(baseFormatWithOptions(options, ...args)) + let formatted = STRIP_C01(baseFormatWithOptions(options, ...args)) + if (redact) { + formatted = redactLog(formatted) + } // 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/) diff --git a/lib/utils/get-identity.js b/lib/utils/get-identity.js index d8f59da14247a..a523a7c716d36 100644 --- a/lib/utils/get-identity.js +++ b/lib/utils/get-identity.js @@ -17,8 +17,7 @@ module.exports = async (npm, opts) => { } } - // At this point, even if they have a credentials object, it doesn't have a - // valid token. + // 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' } diff --git a/lib/utils/key-values.js b/lib/utils/key-values.js new file mode 100644 index 0000000000000..cf54304da6b4b --- /dev/null +++ b/lib/utils/key-values.js @@ -0,0 +1,42 @@ +const { output, META } = require('proc-log') + +const defaultPredicate = (key, value, chalk) => { + if (value === null || value === undefined) { + return null + } + return chalk.green(value) +} + +function logObject (values, { chalk, json, predicate = defaultPredicate }) { + if (json) { + output.standard(JSON.stringify(values, null, 2), { [META]: true, redact: false }) + return + } + + const lines = [] + for (const [key, value] of Object.entries(values)) { + const formatted = predicate(key, value, chalk) + if (formatted !== null) { + lines.push(`${chalk.cyan(key)}: ${formatted}`) + } + } + if (lines.length) { + output.standard(lines.join('\n'), { [META]: true, redact: false }) + } +} + +function logStageItem (item, { chalk }) { + const { id, packageName, version, tag, createdAt, actor, actorType, shasum, ...rest } = item + logObject({ + id, + 'package name': packageName, + version, + tag, + 'date staged': createdAt, + 'staged by': actorType ? `${actor} (${actorType})` : actor, + shasum, + ...rest, + }, { chalk }) +} + +module.exports = { logObject, logStageItem, defaultPredicate } diff --git a/lib/utils/log-file.js b/lib/utils/log-file.js index 6c9bcd7ff8d86..14b00b180564d 100644 --- a/lib/utils/log-file.js +++ b/lib/utils/log-file.js @@ -13,14 +13,12 @@ class LogFiles { #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 + // 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 + // 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 @@ -53,8 +51,7 @@ class LogFiles { return } - // dir is user configurable and is required to exist so - // this can error if the dir is missing or not configured correctly + // 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 @@ -66,8 +63,7 @@ class LogFiles { 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 + // 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() @@ -106,8 +102,7 @@ class LogFiles { } #logHandler = (level, ...args) => { - // Ignore pause and resume events since we - // write everything to the log file + // Ignore pause and resume events since we write everything to the log file if (level === 'pause' || level === 'resume') { return } @@ -118,8 +113,7 @@ class LogFiles { } if (this.#isBuffered) { - // Cant do anything but buffer the output if we dont - // have a file stream yet + // Cant do anything but buffer the output if we don't have a file stream yet this.#logStream.push([level, ...args]) return } @@ -166,43 +160,35 @@ class LogFiles { 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 + // 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 + // 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 + // 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 + // 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. + // 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 + // 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( diff --git a/lib/utils/npm-usage.js b/lib/utils/npm-usage.js index 1bd790ca601bc..e01a1956e1054 100644 --- a/lib/utils/npm-usage.js +++ b/lib/utils/npm-usage.js @@ -62,7 +62,7 @@ const cmdUsages = (Npm) => { let maxLen = 0 const set = [] for (const c of commands) { - set.push([c, Npm.cmd(c).describeUsage.split('\n')]) + set.push([c, Npm.cmd(c).getUsage(null, false).split('\n')]) maxLen = Math.max(maxLen, c.length) } diff --git a/lib/utils/oidc.js b/lib/utils/oidc.js new file mode 100644 index 0000000000000..00f32c642621c --- /dev/null +++ b/lib/utils/oidc.js @@ -0,0 +1,177 @@ +const { log } = require('proc-log') +const npmFetch = require('npm-registry-fetch') +const ciInfo = require('ci-info') +const fetch = require('make-fetch-happen') +const npa = require('npm-package-arg') +const libaccess = require('libnpmaccess') + +/** + * Handles OpenID Connect (OIDC) token retrieval and exchange for CI environments. + * + * This function is designed to work in Continuous Integration (CI) environments such as GitHub Actions, GitLab, and CircleCI. + * It retrieves an OIDC token from the CI environment, exchanges it for an npm token, and sets the token in the provided configuration for authentication with the npm registry. + * + * This function is intended to never throw, as it mutates the state of the `opts` and `config` objects on success. + * OIDC is always an optional feature, and the function should not throw if OIDC is not configured by the registry. + * + * @see https://github.com/watson/ci-info for CI environment detection. + * @see https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect for GitHub Actions OIDC. + * @see https://circleci.com/docs/openid-connect-tokens/ for CircleCI OIDC. + */ +async function oidc ({ packageName, registry, opts, config }) { + /* + * This code should never run when people try to publish locally on their machines. + * It is designed to execute only in Continuous Integration (CI) environments. + */ + + try { + if (!( + /** @see https://github.com/watson/ci-info/blob/v4.2.0/vendors.json#L152 */ + ciInfo.GITHUB_ACTIONS || + /** @see https://github.com/watson/ci-info/blob/v4.2.0/vendors.json#L161C13-L161C22 */ + ciInfo.GITLAB || + /** @see https://github.com/watson/ci-info/blob/v4.2.0/vendors.json#L78 */ + ciInfo.CIRCLE + )) { + return undefined + } + + /** + * Check if the environment variable `NPM_ID_TOKEN` is set. + * In GitLab CI, the ID token is provided via an environment variable, + * with `NPM_ID_TOKEN` serving as a predefined default. For consistency, + * all supported CI environments are expected to support this variable. + * In contrast, GitHub Actions uses a request-based approach to retrieve the ID token. + * The presence of this token within GitHub Actions will override the request-based approach. + * This variable follows the prefix/suffix convention from sigstore (e.g., `SIGSTORE_ID_TOKEN`). + * @see https://docs.sigstore.dev/cosign/signing/overview/ + */ + let idToken = process.env.NPM_ID_TOKEN + + if (!idToken && ciInfo.GITHUB_ACTIONS) { + /** + * GitHub Actions provides these environment variables: + * - `ACTIONS_ID_TOKEN_REQUEST_URL`: The URL to request the ID token. + * - `ACTIONS_ID_TOKEN_REQUEST_TOKEN`: The token to authenticate the request. + * Only when a workflow has the following permissions: + * ``` + * permissions: + * id-token: write + * ``` + * @see https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-cloud-providers#adding-permissions-settings + */ + if (!( + process.env.ACTIONS_ID_TOKEN_REQUEST_URL && + process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN + )) { + log.silly('oidc', 'Skipped because incorrect permissions for id-token within GitHub workflow') + return undefined + } + + /** + * The specification for an audience is `npm:registry.npmjs.org`, where "registry.npmjs.org" can be any supported registry. + */ + const audience = `npm:${new URL(registry).hostname}` + const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL) + url.searchParams.append('audience', audience) + const startTime = Date.now() + const response = await fetch(url.href, { + retry: opts.retry, + headers: { + Accept: 'application/json', + Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}`, + }, + }) + + const elapsedTime = Date.now() - startTime + + log.http( + 'fetch', + `GET ${url.href} ${response.status} ${elapsedTime}ms` + ) + + const json = await response.json() + + if (!response.ok) { + log.verbose('oidc', `Failed to fetch id_token from GitHub: received an invalid response`) + return undefined + } + + if (!json.value) { + log.verbose('oidc', `Failed to fetch id_token from GitHub: missing value`) + return undefined + } + + idToken = json.value + } + + if (!idToken) { + log.silly('oidc', 'Skipped because no id_token available') + return undefined + } + + const parsedRegistry = new URL(registry) + const regKey = `//${parsedRegistry.host}${parsedRegistry.pathname}` + const authTokenKey = `${regKey}:_authToken` + + const escapedPackageName = npa(packageName).escapedName + let response + try { + response = await npmFetch.json(new URL(`/-/npm/v1/oidc/token/exchange/package/${escapedPackageName}`, registry), { + ...opts, + [authTokenKey]: idToken, // Use the idToken as the auth token for the request + method: 'POST', + }) + } catch (error) { + log.verbose('oidc', `Failed token exchange request with body message: ${error?.body?.message || 'Unknown error'}`) + return undefined + } + + if (!response?.token) { + log.verbose('oidc', 'Failed because token exchange was missing the token in the response body') + return undefined + } + + /* + * The "opts" object is a clone of npm.flatOptions and is passed through the `publish` command, eventually reaching `otplease`. + * To ensure the token is accessible during the publishing process, it must be directly attached to the `opts` object. + * Additionally, the token is required by the "live" configuration or getters within `config`. + */ + opts[authTokenKey] = response.token + config.set(authTokenKey, response.token, 'user') + log.verbose('oidc', `Successfully retrieved and set token`) + + try { + const isDefaultProvenance = config.isDefault('provenance') + // CircleCI doesn't support provenance yet, so skip the auto-enable logic + if (isDefaultProvenance && !ciInfo.CIRCLE) { + const [headerB64, payloadB64] = idToken.split('.') + if (headerB64 && payloadB64) { + const payloadJson = Buffer.from(payloadB64, 'base64').toString('utf8') + const payload = JSON.parse(payloadJson) + if ( + (ciInfo.GITHUB_ACTIONS && payload.repository_visibility === 'public') || + // only set provenance for gitlab if the repo is public and SIGSTORE_ID_TOKEN is available + (ciInfo.GITLAB && payload.project_visibility === 'public' && process.env.SIGSTORE_ID_TOKEN) + ) { + const visibility = await libaccess.getVisibility(packageName, opts) + if (visibility?.public) { + log.verbose('oidc', `Enabling provenance`) + opts.provenance = true + config.set('provenance', true, 'user') + } + } + } + } + } catch (error) { + log.verbose('oidc', `Failed to set provenance with message: ${error?.message || 'Unknown error'}`) + } + } catch (error) { + log.verbose('oidc', `Failure with message: ${error?.message || 'Unknown error'}`) + } + return undefined +} + +module.exports = { + oidc, +} diff --git a/lib/utils/open-url.js b/lib/utils/open-url.js index 632dcc79949d6..7d25a4bef6cc4 100644 --- a/lib/utils/open-url.js +++ b/lib/utils/open-url.js @@ -1,5 +1,5 @@ const { open } = require('@npmcli/promise-spawn') -const { output, input } = require('proc-log') +const { output, input, META } = require('proc-log') const { URL } = require('node:url') const readline = require('node:readline/promises') const { once } = require('node:events') @@ -18,7 +18,8 @@ const outputMsg = (json, title, url) => { if (json) { output.buffer({ title, url }) } else { - output.standard(`${title}:\n${url}`) + // These urls are sometimes specifically login urls so we have to turn off redaction to standard output + output.standard(`${title}:\n${url}`, { [META]: true, redact: false }) } } @@ -33,8 +34,7 @@ const openUrl = async (npm, url, title, isFile) => { return } - // We pass this in as true from the help command so we know we don't have to - // check the protocol + // 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) } @@ -86,8 +86,7 @@ const openUrlPrompt = async (npm, url, title, prompt, { signal }) => { } } -// Rearrange arguments and return a function that takes the two arguments -// returned from the npm-profile methods that take an opener +// 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) diff --git a/lib/utils/output-error.js b/lib/utils/output-error.js index 27128e9f03a8c..07a86c9718b90 100644 --- a/lib/utils/output-error.js +++ b/lib/utils/output-error.js @@ -19,6 +19,7 @@ const jsonError = (error, npm) => { 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(), + ...error.json, } } } diff --git a/lib/utils/patch-diff.js b/lib/utils/patch-diff.js new file mode 100644 index 0000000000000..b0ab9a3aa0bff --- /dev/null +++ b/lib/utils/patch-diff.js @@ -0,0 +1,88 @@ +// Generate a git-compatible unified diff between two directories. +// Used by `npm patch commit` to capture edits against a clean tarball. +// The output is consumed by Arborist's apply step (jsdiff parsePatch). +const { createTwoFilesPatch } = require('diff') +const { readdir, readFile } = require('node:fs/promises') +const { join, sep } = require('node:path') + +const IGNORE = new Set(['node_modules', '.git']) + +// Recursively list file paths under dir, relative and posix-separated. +const listFiles = async dir => { + const out = [] + const walk = async sub => { + const entries = await readdir(join(dir, sub), { withFileTypes: true }) + for (const entry of entries) { + const rel = sub ? `${sub}/${entry.name}` : entry.name + if (entry.isDirectory()) { + if (!IGNORE.has(entry.name)) { + await walk(rel) + } + } else if (entry.isFile()) { + out.push(rel) + } + } + } + await walk('') + return out +} + +const readMaybe = async file => { + try { + return await readFile(file, 'utf8') + } catch { + return null + } +} + +// Diff originalDir against editedDir, returning { diff, packageJsonChanged }. +// Added files use `--- /dev/null`, deleted files use `+++ /dev/null`. +// The root package.json is excluded: Arborist resolves the pre-patch manifest, so a patched manifest would apply to disk without being honored. +// ignore holds extra root-relative filenames the caller keeps out of the diff, e.g. the patch-update marker. +const diffDirs = async (originalDir, editedDir, ignore = new Set()) => { + const [origFiles, editFiles] = await Promise.all([ + listFiles(originalDir), + listFiles(editedDir), + ]) + const all = [...new Set([...origFiles, ...editFiles])].sort() + + let result = '' + let packageJsonChanged = false + for (const file of all) { + const native = file.split('/').join(sep) + const [a, b] = await Promise.all([ + readMaybe(join(originalDir, native)), + readMaybe(join(editedDir, native)), + ]) + if (a === b) { + continue + } + + // the root package.json is never patchable; flag the change so commit can warn + if (file === 'package.json') { + packageJsonChanged = true + continue + } + + // caller-owned control files (e.g. the patch-update marker) never belong in the diff + if (ignore.has(file)) { + continue + } + + let patch = createTwoFilesPatch( + `a/${file}`, `b/${file}`, a || '', b || '', '', '' + ).replace('===================================================================\n', '') + + // mark adds and deletes with /dev/null so the apply step creates/removes files + if (a === null) { + patch = patch.replace(`--- a/${file}\t`, '--- /dev/null\t') + } + if (b === null) { + patch = patch.replace(`+++ b/${file}\t`, '+++ /dev/null\t') + } + result += patch + } + return { diff: result, packageJsonChanged } +} + +module.exports = { diffDirs } diff --git a/lib/utils/ping.js b/lib/utils/ping.js index 00956d0c1630c..92a7a7b6c6867 100644 --- a/lib/utils/ping.js +++ b/lib/utils/ping.js @@ -1,7 +1,6 @@ -// ping the npm registry -// used by the ping and doctor commands -const fetch = require('npm-registry-fetch') +// ping the npm registry used by the ping and doctor commands +const npmFetch = require('npm-registry-fetch') module.exports = async (flatOptions) => { - const res = await fetch('/-/ping?write=true', flatOptions) + const res = await npmFetch('/-/ping', { ...flatOptions, cache: false }) return res.json().catch(() => ({})) } diff --git a/lib/utils/queryable.js b/lib/utils/queryable.js index a5fb25a845eaf..fac7581e6f852 100644 --- a/lib/utils/queryable.js +++ b/lib/utils/queryable.js @@ -2,11 +2,12 @@ const util = require('node:util') const _delete = Symbol('delete') const _append = Symbol('append') +const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']) + 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 +// 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(/^(.*)\[\]\.?(.*)$/) @@ -28,22 +29,17 @@ const parseKeys = key => { 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': {} } } + // 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 + // 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'] + // 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, @@ -51,22 +47,19 @@ const parseKeys = key => { ] } - // 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 + // 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] + // 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 + // 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 { @@ -78,15 +71,12 @@ const parseKeys = key => { } } - // returns an ordered list of strings in which each entry - // represents a key in an object defined by the previous entry + // 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 + // 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 = '' @@ -99,10 +89,8 @@ const getter = ({ data, key }, { unwrapSingleItemArrays = true } = {}) => { }) } - // 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, ... + // extra logic to take into account printing array, along with its special syntax in which using a dot-sep property name after an array 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) => { @@ -120,8 +108,7 @@ const getter = ({ data, key }, { unwrapSingleItemArrays = true } = {}) => { label += k } - // these are some legacy expectations from - // the old API consumed by lib/view.js + // 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] } @@ -132,14 +119,16 @@ const getter = ({ data, key }, { unwrapSingleItemArrays = true } = {}) => { } 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: {} } } + // 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 + if (FORBIDDEN_KEYS.has(String(_key))) { + throw Object.assign(new Error(`Forbidden key: "${_key}"`), { code: 'EFORBIDDENKEY' }) + } + // 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) @@ -150,23 +139,21 @@ const setter = ({ data, key, value, force }) => { _key = maybeIndex } - // creates new array in case key is an index - // and the array obj is not yet defined + // 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 + // 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] + // 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`), { @@ -176,14 +163,12 @@ const setter = ({ data, key, value, force }) => { _key = _data.length } - // retrieves the next data object to recursively iterate on, + // 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 + // 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])) @@ -205,9 +190,8 @@ const setter = ({ data, key, value, force }) => { 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 + // 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 { @@ -246,9 +230,8 @@ class Queryable { } 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 + // 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 } } @@ -270,7 +253,7 @@ class Queryable { } } - // return the value for a single query if found, otherwise returns undefined + // return the value for a single query if found; otherwise, returns undefined get (query) { const obj = this.query(query) if (obj) { @@ -278,8 +261,7 @@ class Queryable { } } - // creates objects along the way for the provided `query` parameter - // and assigns `value` to the last property of the query chain + // 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, diff --git a/lib/utils/read-user-info.js b/lib/utils/read-user-info.js index a9a50f8263ff6..9b89f9e4382b1 100644 --- a/lib/utils/read-user-info.js +++ b/lib/utils/read-user-info.js @@ -1,6 +1,6 @@ const { read: _read } = require('read') const userValidate = require('npm-user-validate') -const { log, input } = require('proc-log') +const { log, input, META } = 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. @@ -9,9 +9,11 @@ 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 emailPrompt = 'email (this will be public): ' -const read = (...args) => input.read(() => _read(...args)) +// Pass options through so we can differentiate between regular and silent prompts +const read = (options) => + input.read(() => _read(options), { [META]: true, silent: options?.silent }) function readOTP (msg = otpPrompt, otp, isRetry) { if (isRetry && otp && /^[\d ]+$|^[A-Fa-f0-9]{64,64}$/.test(otp)) { diff --git a/lib/utils/reify-finish.js b/lib/utils/reify-finish.js index 410c19730cdf4..1041c53fdb935 100644 --- a/lib/utils/reify-finish.js +++ b/lib/utils/reify-finish.js @@ -1,33 +1,25 @@ const reifyOutput = require('./reify-output.js') +const checkAllowScripts = require('./check-allow-scripts.js') +const warnWorkspaceAllowScripts = require('./warn-workspace-allow-scripts.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 + // if we are using a builtin config, and just installed npm as a top-level global package, we have to preserve that config. + if (arb.options.global) { + const npmNode = arb.actualTree.inventory.get('node_modules/npm') + if (npmNode) { + const builtinConf = npm.config.data.get('builtin') + if (!builtinConf.loadError) { + const content = ini.stringify(builtinConf.raw).trim() + '\n' + await writeFile(resolve(npmNode.path, 'npmrc'), content) + } + } } - - 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) + warnWorkspaceAllowScripts(arb.actualTree) + const unreviewedScripts = await checkAllowScripts({ arb, npm }) + reifyOutput(npm, arb, { unreviewedScripts }) } module.exports = reifyFinish diff --git a/lib/utils/reify-output.js b/lib/utils/reify-output.js index 025479f0c8e60..8b3f7546c27fe 100644 --- a/lib/utils/reify-output.js +++ b/lib/utils/reify-output.js @@ -14,30 +14,33 @@ const { depth } = require('treeverse') const ms = require('ms') const npmAuditReport = require('npm-audit-report') const { readTree: getFundingInfo } = require('libnpmfund') +const { trustedDisplay } = require('@npmcli/arborist/lib/script-allowed.js') const auditError = require('./audit-error.js') +const { configSetAllowScripts } = require('./allow-scripts-remediation.js') -// TODO: output JSON if flatOptions.json is true -const reifyOutput = (npm, arb) => { +const reifyOutput = (npm, arb, extras = {}) => { const { diff, actualTree } = arb + const unreviewedScripts = extras.unreviewedScripts || [] - // 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! + // 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. + // 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 = { + add: [], added: 0, - removed: 0, - changed: 0, + // audit gets added later audited: auditReport && !auditReport.error ? actualTree.inventory.size : 0, + change: [], + changed: 0, funding: 0, + remove: [], + removed: 0, } if (diff) { @@ -50,23 +53,45 @@ const reifyOutput = (npm, arb) => { switch (d.action) { case 'REMOVE': if (showDiff) { - /* eslint-disable-next-line max-len */ output.standard(`${chalk.blue('remove')} ${d.actual.name} ${d.actual.package.version}`) } summary.removed++ + summary.remove.push({ + name: d.actual.name, + version: d.actual.package.version, + path: d.actual.path, + }) break case 'ADD': if (showDiff) { output.standard(`${chalk.green('add')} ${d.ideal.name} ${d.ideal.package.version}`) } - actualTree.inventory.has(d.ideal) && summary.added++ + if (actualTree.inventory.has(d.ideal)) { + summary.added++ + summary.add.push({ + name: d.ideal.name, + version: d.ideal.package.version, + path: d.ideal.path, + }) + } break case 'CHANGE': if (showDiff) { - /* eslint-disable-next-line max-len */ output.standard(`${chalk.cyan('change')} ${d.actual.name} ${d.actual.package.version} => ${d.ideal.package.version}`) } summary.changed++ + summary.change.push({ + from: { + name: d.actual.name, + version: d.actual.package.version, + path: d.actual.path, + }, + to: { + name: d.ideal.name, + version: d.ideal.package.version, + path: d.ideal.path, + }, + }) break default: return @@ -90,20 +115,30 @@ const reifyOutput = (npm, arb) => { summary.audit = npm.command === 'audit' ? auditReport : auditReport.toJSON().metadata } + if (unreviewedScripts.length) { + summary.unreviewedScripts = unreviewedScripts.map(({ node, scripts }) => { + const { name, version } = trustedDisplay(node) + return { + name, + version, + path: node.path, + scripts, + } + }) + } output.buffer(summary) } else { packagesChangedMessage(npm, summary) packagesFundingMessage(npm, summary) printAuditReport(npm, auditReport) + unreviewedScriptsMessage(npm, unreviewedScripts) } } -// 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. +// 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) { @@ -117,8 +152,8 @@ const getAuditReport = (npm, report) => { return } - // when in silent mode, we print nothing. the JSON output is - // going to just JSON.stringify() the report object. + // 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' @@ -189,11 +224,68 @@ const packagesFundingMessage = (npm, { funding }) => { return } - output.standard('') + 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') } +const unreviewedScriptsMessage = (npm, unreviewedScripts) => { + if (!unreviewedScripts.length) { + return + } + + // Goes through log.warn so it respects --loglevel / --silent and lands + // on stderr like every other "FYI, here's something to know" message. + // stdout is reserved for things the user explicitly asked to see + // (npm ls, npm view). + const count = unreviewedScripts.length + const pkg = count === 1 ? 'package had' : 'packages had' + const header = + `${count} ${pkg} install scripts blocked because they are not covered by allowScripts:` + + const names = [] + const lines = unreviewedScripts.map(({ node, scripts }) => { + const { name, version } = trustedDisplay(node) + /* istanbul ignore next: every test node has a name */ + const display = name || '' + names.push(display) + const ver = version ? `@${version}` : '' + const events = Object.entries(scripts) + .map(([event, cmd]) => `${event}: ${cmd}`) + .join('; ') + return ` ${display}${ver} (${events})` + }) + + log.warn( + 'allow-scripts', + [ + header, + ...lines, + '', + ...remediationLines(npm, names), + ].join('\n') + ) +} + +// `npm approve-scripts` writes to a project package.json, which doesn't +// exist for global installs (it throws EGLOBAL). For those, point users at +// the mechanism that does work globally: the `--allow-scripts` flag for a +// one-off, or `npm config set allow-scripts` to persist it. +const remediationLines = (npm, names) => { + if (npm.global) { + const list = names.join(',') + return [ + `Run \`npm install -g --allow-scripts=${list}\` to allow these scripts ` + + `once, or \`${configSetAllowScripts(names)}\` to allow them for ` + + 'all global installs.', + ] + } + return [ + 'Run `npm approve-scripts --allow-scripts-pending` to review, ' + + 'or `npm approve-scripts ` to allow.', + ] +} + module.exports = reifyOutput diff --git a/lib/utils/resolve-allow-scripts.js b/lib/utils/resolve-allow-scripts.js new file mode 100644 index 0000000000000..b658e1a68ad0c --- /dev/null +++ b/lib/utils/resolve-allow-scripts.js @@ -0,0 +1,181 @@ +const { log } = require('proc-log') +const npa = require('npm-package-arg') +const pkgJson = require('@npmcli/package-json') +const { isExactVersionDisjunction } = require('@npmcli/arborist/lib/script-allowed.js') +const parseAllowScriptsList = require('@npmcli/config/lib/parse-allow-scripts-list.js') + +const buildPolicyFromNames = (names) => { + /* istanbul ignore if: callers only pass non-empty arrays */ + if (!names.length) { + return null + } + const policy = {} + for (const name of names) { + policy[name] = true + } + return policy +} + +// Read the `allow-scripts` value from one or more named config sources and +// build a policy object. Returns `null` if none of the sources has a value. +const policyFromSources = (npm, sources) => { + for (const where of sources) { + const value = npm.config.get?.('allow-scripts', where) + if (value === undefined) { + continue + } + const names = parseAllowScriptsList(value) + /* istanbul ignore else: parseAllowScriptsList returns non-empty when value is set */ + if (names.length) { + return buildPolicyFromNames(names) + } + } + return null +} + +const validatePolicy = (policy, sourceLabel) => { + // Drop and warn about keys with forbidden semver ranges (^, ~, >=, <, *). + // The RFC only permits exact versions joined by `||`. Bare names like + // `canvas` and explicit name-only wildcards (`canvas@*`) are allowed. + if (!policy) { + return policy + } + const cleaned = {} + for (const [key, value] of Object.entries(policy)) { + let parsed + try { + parsed = npa(key) + } catch { + log.warn('allow-scripts', `${sourceLabel}: ignoring unparseable entry "${key}"`) + continue + } + if (parsed.type === 'tag') { + // `pkg@latest`, `pkg@next`, etc. look like a pin but behave name- + // only — the matcher has no way to verify what the tag points at + // when scripts run. Reject for the same reason as semver ranges. + log.warn( + 'allow-scripts', + `${sourceLabel}: ignoring "${key}" — dist-tag specs (@latest, @next, ...) are not allowed; ` + + 'use exact versions joined by "||", or the bare package name, instead' + ) + continue + } + if (parsed.type === 'range') { + const isNameOnly = parsed.fetchSpec === '*' + || parsed.rawSpec === '' + || parsed.rawSpec === '*' + if (!isNameOnly && !isExactVersionDisjunction(parsed.fetchSpec)) { + log.warn( + 'allow-scripts', + `${sourceLabel}: ignoring "${key}" — semver ranges (^, ~, >=, <) are not allowed; ` + + 'use exact versions joined by "||" instead' + ) + continue + } + } + cleaned[key] = value + } + return Object.keys(cleaned).length > 0 ? cleaned : null +} + +// Resolve the effective allowScripts policy from the layered sources. +// Returns `{ policy, source }` where: +// - `policy` is an object map of `package-spec` -> boolean, or `null` if +// no layer has any configuration +// - `source` is one of `'cli'`, `'package.json'`, `'.npmrc'`, or `null` +// +// Precedence order (highest to lowest), per RFC npm/rfcs#868: +// 1. CLI flags (--allow-scripts) and env vars +// 2. Root `package.json#allowScripts` +// 3. `.npmrc` cascade (project, user, global) +// +// The project `package.json` layer is skipped when: +// - `npm.global` is true (no project context exists for global installs) +// - `skipProjectConfig` is true (e.g. npm exec / npx, which per the RFC +// consult only user/global .npmrc) +// +// In both skipped cases, the CLI and .npmrc layers are still consulted; +// only the project package.json layer is skipped. +// +// The first source with any configuration wins for the entire install; +// lower layers are ignored. A `log.warn` is emitted whenever a setting is +// being suppressed by a higher-priority source. +// +// Reads `package.json` from `npm.prefix` (not `npm.localPrefix`) so an +// install run from a workspace sub-directory still picks up the project +// root's policy. +const resolveAllowScripts = async (npm, { skipProjectConfig = false } = {}) => { + // Independently probe each RFC layer. + const cliPolicy = policyFromSources(npm, ['cli', 'env']) + const npmrcPolicy = policyFromSources(npm, ['project', 'user', 'global', 'builtin']) + + // The --allow-scripts CLI flag is intended for one-off and global + // contexts (npm exec, npx, npm install -g). In a project-scoped install, + // team policy belongs in package.json or .npmrc, so reject the flag + // outright to avoid the "works on my machine" footgun. + if (cliPolicy && !npm.global && !skipProjectConfig) { + throw Object.assign( + new Error( + '--allow-scripts is not allowed in project-scoped installs. ' + + 'Add the entries to the "allowScripts" field in package.json, ' + + 'or to .npmrc, instead.' + ), + { code: 'EALLOWSCRIPTS' } + ) + } + + // Project package.json is consulted only when the caller is operating + // inside a real project (not -g, not npx). + let pkgPolicy = null + if (!npm.global && !skipProjectConfig) { + try { + const { content } = await pkgJson.normalize(npm.prefix) + if (content?.allowScripts && typeof content.allowScripts === 'object') { + const entries = Object.entries(content.allowScripts) + if (entries.length > 0) { + pkgPolicy = Object.fromEntries(entries) + } + } + } catch (err) { + log.silly('allow-scripts', 'no package.json at prefix', err.message) + } + } + + // Validate each candidate layer: drop forbidden ranges, warn the user. + const cli = validatePolicy(cliPolicy, 'CLI flag') + const pkg = validatePolicy(pkgPolicy, 'package.json') + const rc = validatePolicy(npmrcPolicy, '.npmrc') + + // Apply RFC precedence. + if (cli) { + // Note: `pkg` is never set alongside `cli` here. Project package.json is + // only read when `!npm.global && !skipProjectConfig`, but in that same + // case a CLI policy throws above. With `npm.global` or skipProjectConfig + // set, package.json is never consulted. + if (rc) { + log.warn( + 'allow-scripts', + '.npmrc allow-scripts setting is being ignored because --allow-scripts was passed on the command line' + ) + } + return { policy: cli, source: 'cli' } + } + + if (pkg) { + if (rc) { + log.warn( + 'allow-scripts', + '.npmrc allow-scripts setting is being ignored because package.json declares its own allowScripts field' + ) + } + return { policy: pkg, source: 'package.json' } + } + + if (rc) { + return { policy: rc, source: '.npmrc' } + } + + return { policy: null, source: null } +} + +module.exports = resolveAllowScripts diff --git a/lib/utils/sbom-cyclonedx.js b/lib/utils/sbom-cyclonedx.js index 989abea58dae8..6e976f4714e2b 100644 --- a/lib/utils/sbom-cyclonedx.js +++ b/lib/utils/sbom-cyclonedx.js @@ -1,6 +1,6 @@ const crypto = require('node:crypto') -const normalizeData = require('normalize-package-data') const parseLicense = require('spdx-expression-parse') +const PackageJson = require('@npmcli/package-json') const npa = require('npm-package-arg') const ssri = require('ssri') @@ -8,7 +8,6 @@ const CYCLONEDX_SCHEMA = 'http://cyclonedx.org/schema/bom-1.5.schema.json' const CYCLONEDX_FORMAT = 'CycloneDX' const CYCLONEDX_SCHEMA_VERSION = '1.5' -const PROP_PATH = 'cdx:npm:package:path' const PROP_BUNDLED = 'cdx:npm:package:bundled' const PROP_DEVELOPMENT = 'cdx:npm:package:development' const PROP_EXTRANEOUS = 'cdx:npm:package:extraneous' @@ -31,19 +30,18 @@ const cyclonedxOutput = ({ npm, nodes, packageType, packageLockOnly }) => { const childNodes = nodes.filter(node => !node.isRoot && !node.isLink) const uuid = crypto.randomUUID() - const deps = [] - const seen = new Set() - for (let node of nodes) { - if (node.isLink) { - node = node.target + // 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) } - - if (seen.has(node)) { - continue - } - seen.add(node) - deps.push(toCyclonedxDependency(node, nodes)) } + const uniqueChildNodes = Array.from(childNodeMap.values()) + + const deps = [rootNode, ...uniqueChildNodes] + .map(node => toCyclonedxDependency(node, nodes)) const bom = { $schema: CYCLONEDX_SCHEMA, @@ -65,7 +63,7 @@ const cyclonedxOutput = ({ npm, nodes, packageType, packageLockOnly }) => { ], component: toCyclonedxItem(rootNode, { packageType }), }, - components: childNodes.map(toCyclonedxItem), + components: uniqueChildNodes.map(toCyclonedxItem), dependencies: deps, } @@ -81,27 +79,34 @@ const toCyclonedxItem = (node, { packageType }) => { const purl = npa.toPurl(spec) + (isGitNode(node) ? `?vcs_url=${node.resolved}` : '') if (node.package) { - normalizeData(node.package) + const toNormalize = new PackageJson() + toNormalize.fromContent(node.package).normalize({ steps: ['normalizeData'] }) + node.package = toNormalize.content } - let parsedLicense - try { - let license = node.package?.license - if (license) { - if (typeof license === 'object') { - license = license.type - } + let license = node.package?.license + if (license) { + if (typeof license === 'object') { + license = license.type } + } else if (Array.isArray(node.package?.licenses)) { + license = node.package.licenses + .map(l => (typeof l === 'object' ? l.type : l)) + .filter(Boolean) + .join(' OR ') + } + let parsedLicense + try { parsedLicense = parseLicense(license) - } catch (err) { + } catch { parsedLicense = null } const component = { 'bom-ref': toCyclonedxID(node), type: packageType, - name: node.name, + name: node.packageName, version: node.version, scope: (node.optional || node.devOptional) ? 'optional' : 'required', author: (typeof node.package?.author === 'object') @@ -109,10 +114,7 @@ const toCyclonedxItem = (node, { packageType }) => { : (node.package?.author || undefined), description: node.package?.description || undefined, purl: purl, - properties: [{ - name: PROP_PATH, - value: node.location, - }], + properties: [], externalReferences: [], } @@ -161,20 +163,27 @@ const toCyclonedxItem = (node, { packageType }) => { 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 }] + component.licenses = [{ expression: license }] } return component } const toCyclonedxDependency = (node, nodes) => { - return { - ref: toCyclonedxID(node), - dependsOn: [...node.edgesOut.values()] + // A node can have multiple outgoing edges resolving to the same + // `name@version` (e.g. via npm aliases like `foo: npm:bar@1` alongside a + // direct `bar: ^1` dep), which would produce duplicate entries in + // `dependsOn`. CycloneDX 1.5 requires unique items, so dedupe by ref. + const dependsOn = [...new Set( + [...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), + .filter(id => id) + )] + return { + ref: toCyclonedxID(node), + dependsOn, } } @@ -192,7 +201,7 @@ const isGitNode = (node) => { try { const { type } = npa(node.resolved) return type === 'git' || type === 'hosted' - } catch (err) { + } catch { /* istanbul ignore next */ return false } diff --git a/lib/utils/sbom-spdx.js b/lib/utils/sbom-spdx.js index e3af77e10c751..8ea75c688bc86 100644 --- a/lib/utils/sbom-spdx.js +++ b/lib/utils/sbom-spdx.js @@ -1,6 +1,6 @@ const crypto = require('node:crypto') -const normalizeData = require('normalize-package-data') +const PackageJson = require('@npmcli/package-json') const npa = require('npm-package-arg') const ssri = require('ssri') @@ -26,6 +26,16 @@ const spdxOutput = ({ npm, nodes, packageType }) => { 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) { @@ -38,11 +48,23 @@ const spdxOutput = ({ npm, nodes, packageType }) => { } seen.add(node) + // A node can have multiple outgoing edges resolving to the same + // `name@version` of the same edge type (e.g. via npm aliases), which + // would produce identical relationship triples. Dedupe per source node. + const seenRels = new Set() 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) + .filter(rel => { + const key = `${rel.spdxElementId}|${rel.relatedSpdxElement}|${rel.relationshipType}` + if (seenRels.has(key)) { + return false + } + seenRels.add(key) + return true + }) relationships.push(...rels) } @@ -65,7 +87,7 @@ const spdxOutput = ({ npm, nodes, packageType }) => { ], }, documentDescribes: [toSpdxID(rootNode)], - packages: [toSpdxItem(rootNode, { packageType }), ...childNodes.map(toSpdxItem)], + packages: [toSpdxItem(rootNode, { packageType }), ...uniqueChildNodes.map(toSpdxItem)], relationships: [ { spdxElementId: SPDX_IDENTIFER, @@ -80,7 +102,9 @@ const spdxOutput = ({ npm, nodes, packageType }) => { } const toSpdxItem = (node, { packageType }) => { - normalizeData(node.package) + const toNormalize = new PackageJson() + toNormalize.fromContent(node.package).normalize({ steps: ['normalizeData'] }) + node.package = toNormalize.content // Calculate purl from package spec let spec = npa(node.pkgid) @@ -98,6 +122,11 @@ const toSpdxItem = (node, { packageType }) => { if (typeof license === 'object') { license = license.type } + } else if (Array.isArray(node.package?.licenses)) { + license = node.package.licenses + .map(l => (typeof l === 'object' ? l.type : l)) + .filter(Boolean) + .join(' OR ') } const pkg = { @@ -173,7 +202,7 @@ const isGitNode = (node) => { try { const { type } = npa(node.resolved) return type === 'git' || type === 'hosted' - } catch (err) { + } catch { /* istanbul ignore next */ return false } diff --git a/lib/utils/strict-allow-scripts-preflight.js b/lib/utils/strict-allow-scripts-preflight.js new file mode 100644 index 0000000000000..d3575289fa8ed --- /dev/null +++ b/lib/utils/strict-allow-scripts-preflight.js @@ -0,0 +1,76 @@ +const checkAllowScripts = require('./check-allow-scripts.js') +const { trustedDisplay } = require('@npmcli/arborist/lib/script-allowed.js') +const { configSetAllowScripts } = require('./allow-scripts-remediation.js') + +// Pre-flight check for `--strict-allow-scripts`. Call after arborist has +// been constructed but before `arb.reify()` runs, so that install scripts +// never execute when strict mode would block them. +// +// Behaviour: +// - No-op unless `npm.flatOptions.strictAllowScripts` is set. +// - Bypassed by `--dangerously-allow-all-scripts` and `--ignore-scripts` +// (the per-flag short-circuits already live in checkAllowScripts). +// - Builds the ideal tree (idempotent — subsequent reify reuses it), +// walks it for nodes whose install scripts have not been covered by +// the `allowScripts` policy, and throws if any are found. +const strictAllowScriptsPreflight = async ({ arb, npm, idealTreeOpts }) => { + if (!npm?.flatOptions?.strictAllowScripts) { + return + } + + // Prefer the idealTree when reify is about to run; fall back to + // actualTree for npm rebuild (which never builds an ideal tree). + let tree + if (idealTreeOpts !== undefined) { + // `npm ci` builds the ideal tree before calling the preflight, so + // skip the rebuild when one already exists. `npm install` calls the + // preflight before reify and needs us to build. + if (!arb.idealTree) { + await arb.buildIdealTree(idealTreeOpts) + } + tree = arb.idealTree + } else { + tree = arb.actualTree + } + + const unreviewed = await checkAllowScripts({ arb, npm, tree }) + if (unreviewed.length === 0) { + return + } + + const lines = unreviewed.map(({ node, scripts }) => { + const events = Object.entries(scripts) + .map(([event, body]) => `${event}: ${body}`) + .join('; ') + const name = node.package?.name || node.name + const version = node.package?.version || '' + const label = version ? `${name}@${version}` : name + return ` ${label} (${events})` + }).join('\n') + + // `npm approve-scripts` / `npm deny-scripts` write to a project + // package.json, which doesn't exist for global installs. Point global + // users at the `--allow-scripts` flag and `npm config set allow-scripts`, + // which both work for global installs. Use the trusted display identity + // so the suggested `npm config set` value matches what the policy matches + // on, not the tarball's self-reported name. + const names = unreviewed.map(({ node }) => trustedDisplay(node).name) + const remediation = npm.global + ? 'Allow them with `--allow-scripts`, persist them with ' + + `\`${configSetAllowScripts(names)}\`, or bypass this ` + + 'check with `--dangerously-allow-all-scripts`.' + : 'Approve them with `npm approve-scripts`, deny them with ' + + '`npm deny-scripts`, or bypass this check with ' + + '`--dangerously-allow-all-scripts`.' + + throw Object.assign( + new Error( + `--strict-allow-scripts: ${unreviewed.length} package(s) have install ` + + `scripts not covered by allowScripts:\n${lines}\n` + + remediation + ), + { code: 'ESTRICTALLOWSCRIPTS' } + ) +} + +module.exports = strictAllowScriptsPreflight diff --git a/lib/utils/tar.js b/lib/utils/tar.js index 63ef6067acb90..91e424ca127ed 100644 --- a/lib/utils/tar.js +++ b/lib/utils/tar.js @@ -1,15 +1,16 @@ const tar = require('tar') const ssri = require('ssri') -const { log, output } = require('proc-log') +const { log, output, META } = 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 } = {}) => { +const logTar = (tarball, { unicode = false, json, key, redact } = {}) => { if (json) { - output.buffer(key == null ? tarball : { [key]: tarball }) + const meta = redact === false ? { [META]: true, redact: false } : undefined + output.buffer({ [key]: tarball }, meta) return } log.notice('') @@ -36,7 +37,6 @@ const logTar = (tarball, { unicode = false, json, key } = {}) => { log.notice('', `package size: ${formatBytes(tarball.size)}`) log.notice('', `unpacked size: ${formatBytes(tarball.unpackedSize)}`) log.notice('', `shasum: ${tarball.shasum}`) - /* eslint-disable-next-line max-len */ 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}`) diff --git a/lib/utils/update-workspaces.js b/lib/utils/update-workspaces.js index 892f366e9980a..c44abfba7bd10 100644 --- a/lib/utils/update-workspaces.js +++ b/lib/utils/update-workspaces.js @@ -13,16 +13,13 @@ async function updateWorkspaces ({ 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 + // 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 + // runs a minimalistic reify update, targeting only the workspaces that had version updates and skipping fund/audit/save const opts = { ...flatOptions, audit: false, diff --git a/lib/utils/validate-lockfile.js b/lib/utils/validate-lockfile.js index 29161ec55bb79..9039a797c03dd 100644 --- a/lib/utils/validate-lockfile.js +++ b/lib/utils/validate-lockfile.js @@ -22,8 +22,109 @@ function validateLockfile (virtualTree, idealTree) { errors.push(`Invalid: lock file's ${lock.name}@${lock.version} does ` + `not satisfy ${entry.name}@${entry.version}`) } + + // a patch whose on-disk hash or path diverges from the lockfile is out of sync + if ((lock.patched?.integrity || null) !== (entry.patched?.integrity || null) || + (lock.patched?.path || null) !== (entry.patched?.path || null)) { + if (entry.patched && !lock.patched) { + // package.json declares a patch the lockfile lacks: newly added, or skipped via --ignore-patch-failures + errors.push(`Invalid: package.json declares a patch for ${entry.name}@${entry.version} ` + + `that the lock file does not record (it may have been skipped with --ignore-patch-failures). ` + + `Fix the patch and reinstall, or remove its patchedDependencies entry`) + } else if (lock.patched && !entry.patched) { + // describe the lock file's own version, which can differ from the ideal tree's when the version also drifted + errors.push(`Invalid: lock file records a patch for ${lock.name}@${lock.version} ` + + `that package.json no longer declares`) + } else { + errors.push(`Invalid: patch for ${entry.name}@${entry.version} does not ` + + `match the patch recorded in the lock file`) + } + } + } + return errors +} + +// validates that the root packageExtensions state matches what the lockfile recorded, and that the locked tree is still consistent with the rule set. +// Returns an array of human-readable error strings, empty when valid. +function validatePackageExtensions (virtualTree, idealTree) { + const errors = [] + const lockHash = virtualTree.meta?.packageExtensionsHash || null + const idealHash = idealTree.meta?.packageExtensionsHash || null + + if (idealHash !== lockHash) { + if (idealHash && !lockHash) { + errors.push('Missing: packageExtensions state from lock file') + } else if (!idealHash && lockHash) { + errors.push('Invalid: lock file records packageExtensions state but package.json has none') + } else { + errors.push('Invalid: packageExtensions in package.json do not match the lock file') + } + // once the canonical hashes diverge, the deeper per-node checks are moot + return errors + } + + // the hashes match, so validate the locked tree's own consistency against the rules + const { PackageExtensions } = require('@npmcli/arborist') + const root = idealTree.target || idealTree + let pe + try { + pe = new PackageExtensions(root.package?.packageExtensions) + } catch (err) { + return [`Invalid: ${err.message}`] + } + + for (const node of virtualTree.inventory.values()) { + if (node.isProjectRoot || node.isWorkspace) { + continue + } + // selectors match the underlying package identity, which is the alias target for aliased installs + const name = node.packageName || node.name + // a locked package identity must not match more than one selector + try { + pe.match(name, node.version) + } catch (err) { + errors.push(`Invalid: ${err.message}`) + } + // recorded provenance must still correspond to a selector that matches the node + const applied = node.packageExtensionsApplied + if (applied) { + const sel = pe.selectors.find(s => s.key === applied.selector) + if (!sel || !pe.wouldMatch(name, node.version)) { + errors.push( + `Invalid: stale packageExtensions provenance for ${node.name}@${node.version} (selector "${applied.selector}")`) + } + } } return errors } +// validates that the .npm-extension state recorded in the lockfile still matches the selected extension file. +// Validation is hash-based: arbitrary code has no selector to re-check, so a matching hash is trusted and a mismatch fails. +// fileHash is computed from the on-disk file (discovery only, no execution), so this holds even under ignore-extension/ignore-scripts. +// The lockfile carries extension state if it records a root hash or any per-package npmExtensionApplied provenance. +// Returns an array of human-readable error strings, empty when valid. +function validateNpmExtension (virtualTree, fileHash) { + const lockHash = virtualTree?.meta?.npmExtensionHash || null + const hasProvenance = !!virtualTree && + [...virtualTree.inventory.values()].some(node => node.npmExtensionApplied) + fileHash = fileHash || null + + if (fileHash) { + if (!lockHash) { + return ['Missing: .npm-extension state from lock file'] + } + if (lockHash !== fileHash) { + return ['Invalid: .npm-extension file does not match the lock file'] + } + return [] + } + // no extension file present + if (lockHash || hasProvenance) { + return ['Invalid: lock file records .npm-extension state but no .npm-extension file is present'] + } + return [] +} + module.exports = validateLockfile +module.exports.validatePackageExtensions = validatePackageExtensions +module.exports.validateNpmExtension = validateNpmExtension diff --git a/lib/utils/validate-uuid.js b/lib/utils/validate-uuid.js new file mode 100644 index 0000000000000..d5842429303f6 --- /dev/null +++ b/lib/utils/validate-uuid.js @@ -0,0 +1,10 @@ +// UUID validation regex +const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + +const validateUUID = (value, fieldName) => { + if (!UUID_REGEX.test(value)) { + throw new Error(`${fieldName} must be a valid UUID`) + } +} + +module.exports = { UUID_REGEX, validateUUID } diff --git a/lib/utils/verify-signatures.js b/lib/utils/verify-signatures.js index 09711581d11dd..49e1d80df32f8 100644 --- a/lib/utils/verify-signatures.js +++ b/lib/utils/verify-signatures.js @@ -1,8 +1,7 @@ -const fetch = require('npm-registry-fetch') +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 pMap = require('p-map') const tufClient = require('@sigstore/tuf') const { log, output } = require('proc-log') @@ -18,6 +17,7 @@ class VerifySignatures { this.invalid = [] this.missing = [] this.checkedPackages = new Set() + this.verified = [] this.auditedWithKeysCount = 0 this.verifiedSignatureCount = 0 this.verifiedAttestationCount = 0 @@ -26,6 +26,7 @@ class VerifySignatures { 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) @@ -43,9 +44,8 @@ class VerifySignatures { 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) { + // Didn't find any dependencies that could be verified, e.g. only local deps, missing version, not on a registry etc. + if (!this.auditedWithKeysCount && !this.verifiedAttestationCount) { throw new Error('found no dependencies to audit that were installed from ' + 'a supported registry') } @@ -60,7 +60,11 @@ class VerifySignatures { } if (this.npm.config.get('json')) { - output.buffer({ invalid, missing }) + const result = { invalid, missing } + if (this.npm.config.get('include-attestations')) { + result.verified = this.verified + } + output.buffer(result) return } const end = process.hrtime.bigint() @@ -70,41 +74,38 @@ class VerifySignatures { const timing = `audited ${this.auditedWithKeysCount} package${auditedPlural} in ` + `${Math.floor(Number(elapsed) / 1e9)}s` output.standard(timing) - output.standard('') + output.standard() const verifiedBold = this.npm.chalk.bold('verified') if (this.verifiedSignatureCount) { if (this.verifiedSignatureCount === 1) { - /* eslint-disable-next-line max-len */ output.standard(`${this.verifiedSignatureCount} package has a ${verifiedBold} registry signature`) } else { - /* eslint-disable-next-line max-len */ output.standard(`${this.verifiedSignatureCount} packages have ${verifiedBold} registry signatures`) } - output.standard('') + output.standard() } if (this.verifiedAttestationCount) { if (this.verifiedAttestationCount === 1) { - /* eslint-disable-next-line max-len */ output.standard(`${this.verifiedAttestationCount} package has a ${verifiedBold} attestation`) } else { - /* eslint-disable-next-line max-len */ output.standard(`${this.verifiedAttestationCount} packages have ${verifiedBold} attestations`) } - output.standard('') + if (!this.npm.config.get('include-attestations')) { + output.standard('(use --json --include-attestations to view attestation details)') + } + output.standard() } if (missing.length) { const missingClr = this.npm.chalk.redBright('missing') if (missing.length === 1) { - /* eslint-disable-next-line max-len */ output.standard(`1 package has a ${missingClr} registry signature but the registry is providing signing keys:`) } else { - /* eslint-disable-next-line max-len */ output.standard(`${missing.length} packages have ${missingClr} registry signatures but the registry is providing signing keys:`) } - output.standard('') + output.standard() missing.map(m => output.standard(`${this.npm.chalk.red(`${m.name}@${m.version}`)} (${m.registry})`) ) @@ -112,7 +113,7 @@ class VerifySignatures { if (invalid.length) { if (missing.length) { - output.standard('') + output.standard() } const invalidClr = this.npm.chalk.redBright('invalid') // We can have either invalid signatures or invalid provenance @@ -121,14 +122,13 @@ class VerifySignatures { if (invalidSignatures.length === 1) { output.standard(`1 package has an ${invalidClr} registry signature:`) } else { - /* eslint-disable-next-line max-len */ output.standard(`${invalidSignatures.length} packages have ${invalidClr} registry signatures:`) } - output.standard('') + output.standard() invalidSignatures.map(i => output.standard(`${this.npm.chalk.red(`${i.name}@${i.version}`)} (${i.registry})`) ) - output.standard('') + output.standard() } const invalidAttestations = this.invalid.filter(i => i.code === 'EATTESTATIONVERIFY') @@ -136,24 +136,21 @@ class VerifySignatures { if (invalidAttestations.length === 1) { output.standard(`1 package has an ${invalidClr} attestation:`) } else { - /* eslint-disable-next-line max-len */ output.standard(`${invalidAttestations.length} packages have ${invalidClr} attestations:`) } - output.standard('') + output.standard() invalidAttestations.map(i => output.standard(`${this.npm.chalk.red(`${i.name}@${i.version}`)} (${i.registry})`) ) - output.standard('') + output.standard() } if (invalid.length === 1) { - /* eslint-disable-next-line max-len */ output.standard(`Someone might have tampered with this package since it was published on the registry!`) } else { - /* eslint-disable-next-line max-len */ output.standard(`Someone might have tampered with these packages since they were published on the registry!`) } - output.standard('') + output.standard() } } @@ -200,9 +197,10 @@ class VerifySignatures { } }) - // If keys not found in Sigstore TUF repo, fallback to registry keys API + // If keys not found in Sigstore TUF repo, fall back to registry keys API if (!keys) { - keys = await fetch.json('/-/npm/v1/keys', { + log.warn(`Fetching verification keys using TUF failed. Fetching directly from ${registry}.`) + keys = await npmFetch.json('/-/npm/v1/keys', { ...this.npm.flatOptions, registry, }).then(({ keys: ks }) => ks.map((key) => ({ @@ -253,7 +251,7 @@ class VerifySignatures { } getSpecRegistry (spec) { - return fetch.pickRegistry(spec, this.npm.flatOptions) + return npmFetch.pickRegistry(spec, this.npm.flatOptions) } getValidPackageInfo (edge) { @@ -273,7 +271,7 @@ class VerifySignatures { 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 + !version || // Skip packages that don't have an installed version, e.g. optional dependencies !spec.registry) { // Skip if not from registry, e.g. git package return } @@ -298,18 +296,25 @@ class VerifySignatures { _integrity: integrity, _signatures, _attestations, + _attestationBundles, _resolved: resolved, } = await pacote.manifest(`${name}@${version}`, { verifySignatures: true, verifyAttestations: true, ...this.buildRegistryConfig(registry), ...this.npm.flatOptions, + // These versions are already installed, so the before/min-release-age + // filter doesn't apply here. It was already applied at install time, and + // leaving it set makes pacote throw ETARGET for any version newer than + // the cutoff. See npm/cli#9277. + before: null, }) const signatures = _signatures || [] const result = { integrity, signatures, attestations: _attestations, + attestationBundles: _attestationBundles, resolved, } return result @@ -327,17 +332,15 @@ class VerifySignatures { } this.checkedPackages.add(location) - // We only "audit" or verify the signature, or the presence of it, on - // packages whose registry returns signing keys + // 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 - ) + const { integrity, signatures, attestations, attestationBundles, 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 @@ -354,11 +357,19 @@ class VerifySignatures { }) } - // 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. + // 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 + if (this.npm.config.get('include-attestations')) { + this.verified.push({ + name, + version, + location, + registry, + attestations, + attestationBundles, + }) + } } } catch (e) { if (e.code === 'EINTEGRITYSIGNATURE' || e.code === 'EATTESTATIONVERIFY') { diff --git a/lib/utils/warn-workspace-allow-scripts.js b/lib/utils/warn-workspace-allow-scripts.js new file mode 100644 index 0000000000000..e46e6cf4d2a10 --- /dev/null +++ b/lib/utils/warn-workspace-allow-scripts.js @@ -0,0 +1,40 @@ +const { log } = require('proc-log') + +// The allowScripts policy MUST live at the project root (RFC npm/rfcs#868). +// A non-root workspace declaring its own allowScripts is almost always a +// mistake: that policy would be silently ignored at install time. +// +// `findWorkspaceAllowScripts` returns the list of offending workspace nodes. +// `warnWorkspaceAllowScripts` is the side-effecting variant that emits one +// install-time `log.warn` per offender. + +const findWorkspaceAllowScripts = (tree) => { + const offenders = [] + if (!tree?.inventory) { + return offenders + } + for (const node of tree.inventory.values()) { + if (!node.isWorkspace || node.isProjectRoot) { + continue + } + if (node.package?.allowScripts !== undefined) { + offenders.push(node) + } + } + return offenders +} + +const warnWorkspaceAllowScripts = (tree) => { + for (const node of findWorkspaceAllowScripts(tree)) { + const name = node.packageName || node.name + log.warn( + 'allow-scripts', + `allowScripts in workspace ${name} (${node.path}) is ignored. ` + + 'Move the field to the project root package.json.' + ) + } +} + +module.exports = warnWorkspaceAllowScripts +module.exports.warnWorkspaceAllowScripts = warnWorkspaceAllowScripts +module.exports.findWorkspaceAllowScripts = findWorkspaceAllowScripts diff --git a/mock-globals/.gitignore b/mock-globals/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/mock-globals/.gitignore +++ b/mock-globals/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/mock-globals/lib/index.js b/mock-globals/lib/index.js index aec8a83963687..ddbc58c2ed40d 100644 --- a/mock-globals/lib/index.js +++ b/mock-globals/lib/index.js @@ -126,7 +126,7 @@ class DescriptorStack { return () => { const index = this.#stack.indexOf(nextDescriptor) // If the stack doesnt contain the descriptor anymore - // than do nothing. This keeps the reset function indempotent + // than do nothing. This keeps the reset function idempotent if (index > -1) { // Resetting removes a descriptor from the stack this.#stack.splice(index, 1) @@ -174,7 +174,7 @@ class MockGlobals { #descriptors = {} register (globals, { replace = false } = {}) { - // Replace means dont merge in object values but replace them instead + // Replace means don't merge in object values but replace them instead // so we only get top level keys instead of walking the obj const keys = replace ? Object.keys(globals) : getKeys(globals) diff --git a/mock-globals/package.json b/mock-globals/package.json index 83e5388b86186..ad37a06b9c4e6 100644 --- a/mock-globals/package.json +++ b/mock-globals/package.json @@ -6,12 +6,13 @@ "private": true, "scripts": { "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "posttest": "npm run lint" + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", @@ -30,11 +31,11 @@ "lib/" ], "engines": { - "node": "^18.17.0 || >=20.5.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../scripts/template-oss/index.js" }, "tap": { @@ -48,8 +49,8 @@ ] }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.1", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "tap": "^16.3.8" } } diff --git a/mock-globals/test/index.js b/mock-globals/test/index.js index 5480801196301..e926b4d26fa29 100644 --- a/mock-globals/test/index.js +++ b/mock-globals/test/index.js @@ -268,7 +268,7 @@ t.test('multiple mocks and resets', async (t) => { t.equal(process.platform, nextPlatform, 'first reset') reset() reset() - t.equal(process.platform, nextPlatform, 'multiple resets are indempotent') + t.equal(process.platform, nextPlatform, 'multiple resets are idempotent') }) }) @@ -294,10 +294,10 @@ t.test('multiple mocks and resets', async (t) => { const nextPlatform = index === platforms.length - 1 ? initial : lastPlatform t.equal(process.platform, lastPlatform) reset() - t.equal(process.platform, nextPlatform, 'multiple resets are indempotent') + t.equal(process.platform, nextPlatform, 'multiple resets are idempotent') reset() reset() - t.equal(process.platform, nextPlatform, 'multiple resets are indempotent') + t.equal(process.platform, nextPlatform, 'multiple resets are idempotent') }) }) diff --git a/mock-registry/.gitignore b/mock-registry/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/mock-registry/.gitignore +++ b/mock-registry/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/mock-registry/lib/index.js b/mock-registry/lib/index.js index 39bc63504cbe1..a0efca8c697ca 100644 --- a/mock-registry/lib/index.js +++ b/mock-registry/lib/index.js @@ -1,9 +1,15 @@ -const pacote = require('pacote') const Arborist = require('@npmcli/arborist') -const npa = require('npm-package-arg') const Nock = require('nock') +const npa = require('npm-package-arg') +const pacote = require('pacote') +const path = require('node:path') const stringify = require('json-stringify-safe') +const { createReadStream } = require('node:fs') +const fs = require('node:fs/promises') + +const corgiDoc = 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*' + const logReq = (req, ...keys) => { const obj = JSON.parse(stringify(req)) const res = {} @@ -15,6 +21,27 @@ const logReq = (req, ...keys) => { return stringify(res, null, 2) } +// helper to convert old audit results to new bulk results +// TODO eventually convert the fixture files themselves +const auditToBulk = audit => { + const bulk = {} + for (const advisory in audit.advisories) { + const { + id, + url, + title, + severity = 'high', + /* eslint-disable-next-line camelcase */ + vulnerable_versions = '*', + module_name: name, + } = audit.advisories[advisory] + bulk[name] = bulk[name] || [] + /* eslint-disable-next-line camelcase */ + bulk[name].push({ id, url, title, severity, vulnerable_versions }) + } + return bulk +} + class MockRegistry { #tap #nock @@ -53,7 +80,11 @@ class MockRegistry { // XXX: this is opt-in currently because it breaks some existing CLI // tests. We should work towards making this the default for all tests. t.comment(logReq(req, 'interceptors', 'socket', 'response', '_events')) - t.fail(`Unmatched request: ${req.method} ${req.path}`) + const protocol = req?.options?.protocol || 'http:' + const hostname = req?.options?.hostname || req?.hostname || 'localhost' + const p = req?.path || '/' + const url = new URL(p, `${protocol}//${hostname}`).toString() + t.fail(`Unmatched request: ${req.method} ${url}`) } } @@ -66,7 +97,6 @@ class MockRegistry { // find mistakes quicker instead of waiting for the entire test to end t.afterEach((t) => { t.strictSame(server.pendingMocks(), [], 'no pending mocks after each') - t.strictSame(server.activeMocks(), [], 'no active mocks after each') }) } @@ -74,6 +104,7 @@ class MockRegistry { Nock.enableNetConnect() server.done() Nock.emitter.off('no match', noMatch) + Nock.cleanAll() }) return server @@ -197,27 +228,6 @@ class MockRegistry { } } - couchadduser ({ username, email, password, token = 'npm_default-test-token' }) { - this.nock = this.nock.put(this.fullPath(`/-/user/org.couchdb.user:${username}`), body => { - this.#tap.match(body, { - _id: `org.couchdb.user:${username}`, - name: username, - email, // Sole difference from couchlogin - password, - type: 'user', - roles: [], - }) - if (!body.date) { - return false - } - return true - }).reply(201, { - id: 'org.couchdb.user:undefined', - rev: '_we_dont_use_revs_any_more', - token, - }) - } - couchlogin ({ username, password, token = 'npm_default-test-token' }) { this.nock = this.nock.put(this.fullPath(`/-/user/org.couchdb.user:${username}`), body => { this.#tap.match(body, { @@ -251,15 +261,18 @@ class MockRegistry { .reply(200, { token }) } - weblogin ({ token = 'npm_default-test-token' }) { - const doneUrl = new URL('/npm-cli-test/done', this.origin).href - const loginUrl = new URL('/npm-cli-test/login', this.origin).href + weblogin ({ token = 'npm_default-test-token', doneRegistry } = {}) { + const donePath = '/npm-cli-test/done' + // doneRegistry emulates a proxy/mirror that advertises a doneUrl on a different origin than the configured registry. + // The poll itself is always mocked on this registry, since that is where the session lives. + const doneUrl = new URL(donePath, doneRegistry ?? this.origin).href + const loginUrl = new URL('/npm-cli-test/login/cli/00000000-0000-0000-0000-000000000000', this.origin).href this.nock = this.nock .post(this.fullPath('/-/v1/login'), () => { return true }) .reply(200, { doneUrl, loginUrl }) - .get('/npm-cli-test/done') + .get(donePath) .reply(200, { token }) } @@ -320,17 +333,36 @@ class MockRegistry { } ping ({ body = {}, responseCode = 200 } = {}) { - this.nock = this.nock.get(this.fullPath('/-/ping?write=true')).reply(responseCode, body) + this.nock = this.nock.get(this.fullPath('/-/ping')).reply(responseCode, body) } // full unpublish of an entire package - async unpublish ({ manifest }) { + unpublish ({ manifest }) { let nock = this.nock const spec = npa(manifest.name) nock = nock.delete(this.fullPath(`/${spec.escapedName}/-rev/${manifest._rev}`)).reply(201) return nock } + publish (name, { + packageJson, access, noGet, noPut, putCode, manifest, packuments, token, + } = {}) { + if (!noGet) { + // this getPackage call is used to get the latest semver version before publish + if (manifest) { + this.getPackage(name, { code: 200, resp: manifest }) + } else if (packuments) { + this.getPackage(name, { code: 200, resp: this.manifest({ name, packuments }) }) + } else { + // assumes the package does not exist yet and will 404 x2 from pacote.manifest + this.getPackage(name, { times: 2, code: 404 }) + } + } + if (!noPut) { + this.putPackage(name, { code: putCode, packageJson, access, token }) + } + } + getPackage (name, { times = 1, code = 200, query, resp = {} }) { let nock = this.nock nock = nock.get(`/${npa(name).escapedName}`).times(times) @@ -345,8 +377,54 @@ class MockRegistry { this.nock = nock } + putPackage (name, { code = 200, resp = {}, token, ...putPackagePayload }) { + let n = this.nock.put(`/${npa(name).escapedName}`, body => { + return this.#tap.match(body, this.putPackagePayload({ name, ...putPackagePayload })) + }) + if (token) { + n = n.matchHeader('authorization', `Bearer ${token}`) + } + n.reply(code, resp) + } + + putPackagePayload (opts) { + const pkg = opts.packageJson + const name = opts.name || pkg?.name + const registry = opts.registry || pkg?.publishConfig?.registry || 'https://registry.npmjs.org' + const access = opts.access || null + + const nameProperties = !name ? {} : { + _id: name, + name: name, + } + + const packageProperties = !pkg ? {} : { + 'dist-tags': { latest: pkg.version }, + versions: { + [pkg.version]: { + _id: `${pkg.name}@${pkg.version}`, + dist: { + shasum: /\.*/, + tarball: + `http://${new URL(registry).host}/${pkg.name}/-/${pkg.name}-${pkg.version}.tgz`, + }, + ...pkg, + }, + }, + _attachments: { + [`${pkg.name}-${pkg.version}.tgz`]: {}, + }, + } + + return { + access, + ...nameProperties, + ...packageProperties, + } + } + getTokens (tokens) { - return this.nock.get('/-/npm/v1/tokens') + return this.nock.get(this.fullPath('/-/npm/v1/tokens')) .reply(200, { objects: tokens, urls: {}, @@ -355,19 +433,26 @@ class MockRegistry { }) } - createToken ({ password, readonly = false, cidr = [] }) { - return this.nock.post('/-/npm/v1/tokens', { - password, - readonly, - cidr_whitelist: cidr, - }).reply(200, { - key: 'n3wk3y', - token: 'n3wt0k3n', - created: new Date(), - updated: new Date(), - readonly, - cidr_whitelist: cidr, - }) + // The server has rules for what resultData correlates with what tokenData but we don't need to be 100% in sync with that, we just need to be able to pass all of the possible tokenData attributes, and be able to accept all of the possible resultData attributes + createToken (tokenData, resultData = {}) { + return this.nock.post(this.fullPath('/-/npm/v1/tokens'), tokenData) + .reply(201, { + id: `0xdeadbeef`, + key: 'n3wk3y', + token: 'n3wt0k3n', + created: new Date(), + updated: new Date(), + access: 'read-only', + name: tokenData.name, + password: tokenData.password, + ...resultData, + }) + } + + revokeToken (token) { + return this.nock.delete( + this.fullPath(`/-/npm/v1/tokens/token/${token}`) + ).reply(200) } async package ({ manifest, times = 1, query, tarballs }) { @@ -453,8 +538,50 @@ class MockRegistry { } } + // bulk advisory audit endpoint + audit ({ responseCode = 200, results = {}, convert = false, times = 1 } = {}) { + this.nock = this.nock + .post(this.fullPath('/-/npm/v1/security/advisories/bulk')) + .times(times) + .reply( + responseCode, + convert ? auditToBulk(results) : results + ) + } + + // Used in Arborist to mock the registry from fixture data on disk + // Will eat up all GET requests to the entire registry, so it probably doesn't work with the other GET routes very well. + mocks ({ dir }) { + const exists = (p) => fs.stat(p).then((s) => s).catch(() => false) + this.nock = this.nock.get(/.*/).reply(async function () { + const { headers, path: url } = this.req + const isCorgi = headers.accept.includes('application/vnd.npm.install-v1+json') + const encodedUrl = url.replace(/@/g, '').replace(/%2f/gi, '/') + const f = path.join(dir, 'registry-mocks', 'content', encodedUrl) + let file = f + let contentType = 'application/octet-stream' + if (isCorgi && await exists(`${f}.min.json`)) { + file = `${f}.min.json` + contentType = corgiDoc + } else if (await exists(`${f}.json`)) { + file = `${f}.json` + contentType = 'application/json' + } else if (await exists(`${f}/index.json`)) { + file = `${f}index.json` + contentType = 'application/json' + } + const stats = await exists(file) + if (stats) { + const body = createReadStream(file) + body.pause() + return [200, body, { 'content-type': contentType, 'content-length': stats.size }] + } + return [404, { error: 'not found' }] + }).persist() + } + /** - * this is a simpler convience method for creating mockable registry with + * this is a simpler convenience method for creating mockable registry with * tarballs for specific versions */ async setup (packages) { @@ -496,6 +623,33 @@ class MockRegistry { } } } + + mockOidcTokenExchange ({ packageName, idToken, statusCode = 200, body } = {}) { + const encodedPackageName = npa(packageName).escapedName + this.nock.post(this.fullPath(`/-/npm/v1/oidc/token/exchange/package/${encodedPackageName}`)) + .matchHeader('authorization', `Bearer ${idToken}`) + .reply(statusCode, body || {}) + } + + // Trust API methods + trustList ({ packageName, responseCode = 200, body = [] }) { + const spec = npa(packageName) + this.nock = this.nock.get(this.fullPath(`/-/package/${spec.escapedName}/trust`)) + .reply(responseCode, body) + } + + trustCreate ({ packageName, responseCode = 200, body = { ok: true } }) { + const spec = npa(packageName) + this.nock = this.nock.post(this.fullPath(`/-/package/${spec.escapedName}/trust`)) + .reply(responseCode, body) + } + + trustRevoke ({ packageName, id, responseCode = 200, body = { ok: true } }) { + const spec = npa(packageName) + const encodedId = encodeURIComponent(id) + this.nock = this.nock.delete(this.fullPath(`/-/package/${spec.escapedName}/trust/${encodedId}`)) + .reply(responseCode, body) + } } module.exports = MockRegistry diff --git a/mock-registry/lib/provenance.js b/mock-registry/lib/provenance.js new file mode 100644 index 0000000000000..371bd56dcc930 --- /dev/null +++ b/mock-registry/lib/provenance.js @@ -0,0 +1,98 @@ +const mockGlobals = require('@npmcli/mock-globals') +const nock = require('nock') + +const sigstoreIdToken = () => { + return `.${Buffer.from(JSON.stringify({ + iss: 'https://oauth2.sigstore.dev/auth', + email: 'foo@bar.com', + email_verified: true, + })) + .toString('base64')}.` +} + +const mockProvenance = (t, { + oidcURL, + requestToken, + workflowPath, + repository, + serverUrl, + ref, + sha, + runID, + runAttempt, + runnerEnv, +}) => { + const idToken = sigstoreIdToken() + + mockGlobals(t, { + 'process.env': { + CI: true, + GITHUB_ACTIONS: true, + ACTIONS_ID_TOKEN_REQUEST_URL: oidcURL, + ACTIONS_ID_TOKEN_REQUEST_TOKEN: requestToken, + GITHUB_WORKFLOW_REF: `${repository}/${workflowPath}@${ref}`, + GITHUB_REPOSITORY: repository, + GITHUB_SERVER_URL: serverUrl, + GITHUB_REF: ref, + GITHUB_SHA: sha, + GITHUB_RUN_ID: runID, + GITHUB_RUN_ATTEMPT: runAttempt, + RUNNER_ENVIRONMENT: runnerEnv, + }, + }) + + const url = new URL(oidcURL) + nock(url.origin) + .get(url.pathname) + .query({ audience: 'sigstore' }) + .matchHeader('authorization', `Bearer ${requestToken}`) + .matchHeader('accept', 'application/json') + .reply(200, { value: idToken }) + + const leafCertificate = `-----BEGIN CERTIFICATE-----\nabc\n-----END CERTIFICATE-----\n` + + // Mock the Fulcio signing certificate endpoint + nock('https://fulcio.sigstore.dev') + .post('/api/v2/signingCert') + .reply(200, { + signedCertificateEmbeddedSct: { + chain: { + certificates: [ + leafCertificate, + `-----BEGIN CERTIFICATE-----\nxyz\n-----END CERTIFICATE-----\n`, + ], + }, + }, + }) + + nock('https://rekor.sigstore.dev') + .post('/api/v1/log/entries') + .reply(201, { + '69e5a0c1663ee4452674a5c9d5050d866c2ee31e2faaf79913aea7cc27293cf6': { + body: Buffer.from(JSON.stringify({ + kind: 'hashedrekord', + apiVersion: '0.0.1', + spec: { + signature: { + content: 'ABC123', + publicKey: { content: Buffer.from(leafCertificate).toString('base64') }, + }, + }, + })).toString( + 'base64' + ), + integratedTime: 1654015743, + logID: + 'c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d', + logIndex: 2513258, + verification: { + signedEntryTimestamp: 'MEUCIQD6CD7ZNLUipFoxzmSL/L8Ewic4SRkXN77UjfJZ7d/wAAIgatokSuX9Rg0iWxAgSfHMtcsagtDCQalU5IvXdQ+yLEA=', + }, + }, + }) +} + +module.exports = { + mockProvenance, + sigstoreIdToken, +} diff --git a/mock-registry/package.json b/mock-registry/package.json index 8582d113c04f0..7ca2955c9b4f9 100644 --- a/mock-registry/package.json +++ b/mock-registry/package.json @@ -6,12 +6,13 @@ "private": true, "scripts": { "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "posttest": "npm run lint" + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", @@ -30,11 +31,11 @@ "lib/" ], "engines": { - "node": "^18.17.0 || >=20.5.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../scripts/template-oss/index.js" }, "tap": { @@ -45,13 +46,13 @@ ] }, "devDependencies": { - "@npmcli/arborist": "^7.1.0", - "@npmcli/eslint-config": "^4.0.1", - "@npmcli/template-oss": "4.22.0", + "@npmcli/arborist": "^9.1.2", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "json-stringify-safe": "^5.0.1", - "nock": "^13.3.3", - "npm-package-arg": "^11.0.2", - "pacote": "^18.0.6", + "nock": "^14.0.0", + "npm-package-arg": "^14.0.0", + "pacote": "^22.0.0", "tap": "^16.3.8" } } diff --git a/node_modules/.gitignore b/node_modules/.gitignore index 7940f660b3aa4..f162dd5f362ca 100644 --- a/node_modules/.gitignore +++ b/node_modules/.gitignore @@ -3,22 +3,28 @@ /* !/.gitignore # Allow all bundled deps +!/@gar/ +/@gar/* +!/@gar/promise-retry !/@isaacs/ /@isaacs/* -!/@isaacs/cliui -!/@isaacs/cliui/node_modules/ -/@isaacs/cliui/node_modules/* -!/@isaacs/cliui/node_modules/ansi-regex -!/@isaacs/cliui/node_modules/emoji-regex -!/@isaacs/cliui/node_modules/string-width -!/@isaacs/cliui/node_modules/strip-ansi +!/@isaacs/fs-minipass !/@isaacs/string-locale-compare !/@npmcli/ /@npmcli/* !/@npmcli/agent +!/@npmcli/agent/node_modules/ +/@npmcli/agent/node_modules/* +!/@npmcli/agent/node_modules/agent-base +!/@npmcli/agent/node_modules/http-proxy-agent +!/@npmcli/agent/node_modules/https-proxy-agent !/@npmcli/fs !/@npmcli/git !/@npmcli/installed-package-contents +!/@npmcli/installed-package-contents/node_modules/ +/@npmcli/installed-package-contents/node_modules/* +!/@npmcli/installed-package-contents/node_modules/npm-bundled +!/@npmcli/installed-package-contents/node_modules/npm-normalize-package-bin !/@npmcli/map-workspaces !/@npmcli/metavuln-calculator !/@npmcli/name-from-folder @@ -28,30 +34,24 @@ !/@npmcli/query !/@npmcli/redact !/@npmcli/run-script -!/@pkgjs/ -/@pkgjs/* -!/@pkgjs/parseargs !/@sigstore/ /@sigstore/* -!/@sigstore/bundle -!/@sigstore/core !/@sigstore/protobuf-specs -!/@sigstore/sign !/@sigstore/tuf -!/@sigstore/verify !/@tufjs/ /@tufjs/* !/@tufjs/canonical-json -!/@tufjs/models !/abbrev -!/agent-base -!/aggregate-error -!/ansi-regex -!/ansi-styles !/aproba !/archy !/balanced-match !/bin-links +!/bin-links/node_modules/ +/bin-links/node_modules/* +!/bin-links/node_modules/cmd-shim +!/bin-links/node_modules/npm-normalize-package-bin +!/bin-links/node_modules/read-cmd-shim +!/bin-links/node_modules/write-file-atomic !/binary-extensions !/brace-expansion !/cacache @@ -59,51 +59,24 @@ !/chownr !/ci-info !/cidr-regex -!/clean-stack -!/cli-columns -!/cmd-shim -!/color-convert -!/color-name !/common-ancestor-path -!/cross-spawn -!/cross-spawn/node_modules/ -/cross-spawn/node_modules/* -!/cross-spawn/node_modules/which !/cssesc !/debug -!/debug/node_modules/ -/debug/node_modules/* -!/debug/node_modules/ms !/diff -!/eastasianwidth -!/emoji-regex -!/encoding !/env-paths -!/err-code !/exponential-backoff !/fastest-levenshtein -!/foreground-child !/fs-minipass !/glob !/graceful-fs !/hosted-git-info !/http-cache-semantics -!/http-proxy-agent -!/https-proxy-agent !/iconv-lite -!/ignore-walk -!/imurmurhash -!/indent-string !/ini !/init-package-json !/ip-address -!/ip-regex !/is-cidr -!/is-fullwidth-code-point -!/is-lambda !/isexe -!/jackspeak -!/jsbn !/json-parse-even-better-errors !/json-stringify-nice !/jsonparse @@ -111,125 +84,98 @@ !/just-diff !/lru-cache !/make-fetch-happen +!/make-fetch-happen/node_modules/ +/make-fetch-happen/node_modules/* +!/make-fetch-happen/node_modules/minipass-fetch !/minimatch !/minipass-collect -!/minipass-fetch !/minipass-flush -!/minipass-flush/node_modules/ -/minipass-flush/node_modules/* -!/minipass-flush/node_modules/minipass !/minipass-pipeline !/minipass-pipeline/node_modules/ /minipass-pipeline/node_modules/* !/minipass-pipeline/node_modules/minipass +!/minipass-pipeline/node_modules/yallist !/minipass-sized -!/minipass-sized/node_modules/ -/minipass-sized/node_modules/* -!/minipass-sized/node_modules/minipass !/minipass !/minizlib -!/minizlib/node_modules/ -/minizlib/node_modules/* -!/minizlib/node_modules/minipass -!/mkdirp !/ms !/mute-stream !/negotiator !/node-gyp -!/node-gyp/node_modules/ -/node-gyp/node_modules/* -!/node-gyp/node_modules/proc-log !/nopt -!/normalize-package-data !/npm-audit-report -!/npm-bundled !/npm-install-checks -!/npm-normalize-package-bin !/npm-package-arg !/npm-packlist +!/npm-packlist/node_modules/ +/npm-packlist/node_modules/* +!/npm-packlist/node_modules/ignore-walk !/npm-pick-manifest +!/npm-pick-manifest/node_modules/ +/npm-pick-manifest/node_modules/* +!/npm-pick-manifest/node_modules/npm-normalize-package-bin !/npm-profile !/npm-registry-fetch +!/npm-registry-fetch/node_modules/ +/npm-registry-fetch/node_modules/* +!/npm-registry-fetch/node_modules/minipass-fetch !/npm-user-validate !/p-map -!/package-json-from-dist !/pacote +!/pacote/node_modules/ +/pacote/node_modules/* +!/pacote/node_modules/@sigstore/ +/pacote/node_modules/@sigstore/* +!/pacote/node_modules/@sigstore/bundle +!/pacote/node_modules/@sigstore/core +!/pacote/node_modules/@sigstore/sign +!/pacote/node_modules/@sigstore/verify +!/pacote/node_modules/sigstore !/parse-conflict-json -!/path-key !/path-scurry !/postcss-selector-parser !/proc-log !/proggy !/promise-all-reject-late !/promise-call-limit -!/promise-inflight -!/promise-retry !/promzard +!/proxy-agent-negotiate !/qrcode-terminal -!/read-cmd-shim -!/read-package-json-fast !/read -!/retry !/safer-buffer !/semver -!/shebang-command -!/shebang-regex !/signal-exit -!/sigstore !/smart-buffer !/socks-proxy-agent +!/socks-proxy-agent/node_modules/ +/socks-proxy-agent/node_modules/* +!/socks-proxy-agent/node_modules/agent-base !/socks -!/spdx-correct -!/spdx-correct/node_modules/ -/spdx-correct/node_modules/* -!/spdx-correct/node_modules/spdx-expression-parse !/spdx-exceptions !/spdx-expression-parse !/spdx-license-ids -!/sprintf-js !/ssri -!/string-width-cjs -!/string-width -!/strip-ansi-cjs -!/strip-ansi !/supports-color !/tar -!/tar/node_modules/ -/tar/node_modules/* -!/tar/node_modules/fs-minipass -!/tar/node_modules/fs-minipass/node_modules/ -/tar/node_modules/fs-minipass/node_modules/* -!/tar/node_modules/fs-minipass/node_modules/minipass -!/tar/node_modules/minipass !/text-table !/tiny-relative-date +!/tinyglobby +!/tinyglobby/node_modules/ +/tinyglobby/node_modules/* +!/tinyglobby/node_modules/fdir +!/tinyglobby/node_modules/picomatch !/treeverse !/tuf-js -!/unique-filename -!/unique-slug +!/tuf-js/node_modules/ +/tuf-js/node_modules/* +!/tuf-js/node_modules/@tufjs/ +/tuf-js/node_modules/@tufjs/* +!/tuf-js/node_modules/@tufjs/models +!/undici !/util-deprecate -!/validate-npm-package-license -!/validate-npm-package-license/node_modules/ -/validate-npm-package-license/node_modules/* -!/validate-npm-package-license/node_modules/spdx-expression-parse !/validate-npm-package-name !/walk-up-path !/which -!/which/node_modules/ -/which/node_modules/* -!/which/node_modules/isexe -!/wrap-ansi-cjs -!/wrap-ansi-cjs/node_modules/ -/wrap-ansi-cjs/node_modules/* -!/wrap-ansi-cjs/node_modules/ansi-styles -!/wrap-ansi -!/wrap-ansi/node_modules/ -/wrap-ansi/node_modules/* -!/wrap-ansi/node_modules/ansi-regex -!/wrap-ansi/node_modules/emoji-regex -!/wrap-ansi/node_modules/string-width -!/wrap-ansi/node_modules/strip-ansi -!/write-file-atomic !/yallist # Always ignore some specific patterns within any allowed package .bin/ diff --git a/node_modules/@gar/promise-retry/LICENSE b/node_modules/@gar/promise-retry/LICENSE new file mode 100644 index 0000000000000..581fd12567414 --- /dev/null +++ b/node_modules/@gar/promise-retry/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2011 Tim Koschützki (tim@debuggable.com), Felix Geisendörfer (felix@debuggable.com) +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. diff --git a/node_modules/@gar/promise-retry/lib/index.js b/node_modules/@gar/promise-retry/lib/index.js new file mode 100644 index 0000000000000..be4598498e4a0 --- /dev/null +++ b/node_modules/@gar/promise-retry/lib/index.js @@ -0,0 +1,62 @@ +const { RetryOperation } = require('./retry') + +const createTimeout = (attempt, opts) => Math.min(Math.round((1 + (opts.randomize ? Math.random() : 0)) * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)), opts.maxTimeout) +const isRetryError = err => err?.code === 'EPROMISERETRY' && Object.hasOwn(err, 'retried') + +const promiseRetry = async (fn, options = {}) => { + let timeouts = [] + if (options instanceof Array) { + timeouts = [...options] + } else { + if (options.retries === Infinity) { + options.forever = true + delete options.retries + } + const opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1000, + maxTimeout: Infinity, + randomize: false, + ...options + } + if (opts.minTimeout > opts.maxTimeout) { + throw new Error('minTimeout is greater than maxTimeout') + } + if (opts.retries) { + for (let i = 0; i < opts.retries; i++) { + timeouts.push(createTimeout(i, opts)) + } + // sort the array numerically ascending (since the timeouts may be out of order at factor < 1) + timeouts.sort((a, b) => a - b) + } else if (options.forever) { + timeouts.push(createTimeout(0, opts)) + } + } + + const operation = new RetryOperation(timeouts, { + forever: options.forever, + unref: options.unref, + maxRetryTime: options.maxRetryTime + }) + + return new Promise(function (resolve, reject) { + operation.attempt(async number => { + try { + const result = await fn(err => { + throw Object.assign(new Error('Retrying'), { code: 'EPROMISERETRY', retried: err }) + }, number, operation) + return resolve(result) + } catch (err) { + if (!isRetryError(err)) { + return reject(err) + } + if (!operation.retry(err.retried || new Error())) { + return reject(err.retried) + } + } + }) + }) +} + +module.exports = { promiseRetry } diff --git a/node_modules/@gar/promise-retry/lib/retry.js b/node_modules/@gar/promise-retry/lib/retry.js new file mode 100644 index 0000000000000..e2d13dfaee572 --- /dev/null +++ b/node_modules/@gar/promise-retry/lib/retry.js @@ -0,0 +1,109 @@ +class RetryOperation { + #attempts = 1 + #cachedTimeouts = null + #errors = [] + #fn = null + #maxRetryTime + #operationStart = null + #originalTimeouts + #timeouts + #timer = null + #unref + + constructor (timeouts, options = {}) { + this.#originalTimeouts = [...timeouts] + this.#timeouts = [...timeouts] + this.#unref = options.unref + this.#maxRetryTime = options.maxRetryTime || Infinity + if (options.forever) { + this.#cachedTimeouts = [...this.#timeouts] + } + } + + get timeouts () { + return [...this.#timeouts] + } + + get errors () { + return [...this.#errors] + } + + get attempts () { + return this.#attempts + } + + get mainError () { + let mainError = null + if (this.#errors.length) { + let mainErrorCount = 0 + const counts = {} + for (let i = 0; i < this.#errors.length; i++) { + const error = this.#errors[i] + const { message } = error + if (!counts[message]) { + counts[message] = 0 + } + counts[message]++ + + if (counts[message] >= mainErrorCount) { + mainError = error + mainErrorCount = counts[message] + } + } + } + return mainError + } + + reset () { + this.#attempts = 1 + this.#timeouts = [...this.#originalTimeouts] + } + + stop () { + if (this.#timer) { + clearTimeout(this.#timer) + } + + this.#timeouts = [] + this.#cachedTimeouts = null + } + + retry (err) { + this.#errors.push(err) + if (new Date().getTime() - this.#operationStart >= this.#maxRetryTime) { + // XXX This puts the timeout error first, meaning it will never show as mainError, there may be no way to ever see this + this.#errors.unshift(new Error('RetryOperation timeout occurred')) + return false + } + + let timeout = this.#timeouts.shift() + if (timeout === undefined) { + // We're out of timeouts, clear the last error and repeat the final timeout + if (this.#cachedTimeouts) { + this.#errors.pop() + timeout = this.#cachedTimeouts.at(-1) + } else { + return false + } + } + + // TODO what if there already is a timer? + this.#timer = setTimeout(() => { + this.#attempts++ + this.#fn(this.#attempts) + }, timeout) + + if (this.#unref) { + this.#timer.unref() + } + + return true + } + + attempt (fn) { + this.#fn = fn + this.#operationStart = new Date().getTime() + this.#fn(this.#attempts) + } +} +module.exports = { RetryOperation } diff --git a/node_modules/@gar/promise-retry/package.json b/node_modules/@gar/promise-retry/package.json new file mode 100644 index 0000000000000..ab73b70283b31 --- /dev/null +++ b/node_modules/@gar/promise-retry/package.json @@ -0,0 +1,45 @@ +{ + "name": "@gar/promise-retry", + "version": "1.0.3", + "description": "Retries a function that returns a promise, leveraging the power of the retry module.", + "main": "./lib/index.js", + "files": [ + "lib" + ], + "type": "commonjs", + "exports": { + ".": [ + { + "default": "./lib/index.js", + "types": "./lib/index.d.ts" + }, + "./lib/index.js" + ] + }, + "scripts": { + "lint": "npx standard", + "lint:fix": "npx standard --fix", + "test": "node --test --experimental-test-coverage --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100", + "typelint": "npx -p typescript tsc ./lib/index.d.ts", + "posttest": "npm run lint", + "postlint": "npm run typelint" + }, + "bugs": { + "url": "https://github.com/wraithgar/node-promise-retry/issues/" + }, + "repository": { + "type": "git", + "url": "git://github.com/wraithgar/node-promise-retry.git" + }, + "keywords": [ + "retry", + "promise", + "backoff", + "repeat", + "replay" + ], + "license": "MIT", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } +} diff --git a/node_modules/@isaacs/cliui/LICENSE.txt b/node_modules/@isaacs/cliui/LICENSE.txt deleted file mode 100644 index c7e27478a3eff..0000000000000 --- a/node_modules/@isaacs/cliui/LICENSE.txt +++ /dev/null @@ -1,14 +0,0 @@ -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. diff --git a/node_modules/@isaacs/cliui/build/index.cjs b/node_modules/@isaacs/cliui/build/index.cjs deleted file mode 100644 index aca2b8507ac0f..0000000000000 --- a/node_modules/@isaacs/cliui/build/index.cjs +++ /dev/null @@ -1,317 +0,0 @@ -'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; diff --git a/node_modules/@isaacs/cliui/build/index.d.cts b/node_modules/@isaacs/cliui/build/index.d.cts deleted file mode 100644 index 4567f945e81a7..0000000000000 --- a/node_modules/@isaacs/cliui/build/index.d.cts +++ /dev/null @@ -1,43 +0,0 @@ -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 }; diff --git a/node_modules/@isaacs/cliui/build/lib/index.js b/node_modules/@isaacs/cliui/build/lib/index.js deleted file mode 100644 index 587b5ecd3e773..0000000000000 --- a/node_modules/@isaacs/cliui/build/lib/index.js +++ /dev/null @@ -1,302 +0,0 @@ -'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 */ - }); -} diff --git a/node_modules/@isaacs/cliui/index.mjs b/node_modules/@isaacs/cliui/index.mjs deleted file mode 100644 index 5177519af3722..0000000000000 --- a/node_modules/@isaacs/cliui/index.mjs +++ /dev/null @@ -1,14 +0,0 @@ -// 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 - }) -} diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-regex/index.js b/node_modules/@isaacs/cliui/node_modules/ansi-regex/index.js deleted file mode 100644 index 130a0929b8ce8..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/ansi-regex/index.js +++ /dev/null @@ -1,8 +0,0 @@ -export default function ansiRegex({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'); -} diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-regex/license b/node_modules/@isaacs/cliui/node_modules/ansi-regex/license deleted file mode 100644 index fa7ceba3eb4a9..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/ansi-regex/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-regex/package.json b/node_modules/@isaacs/cliui/node_modules/ansi-regex/package.json deleted file mode 100644 index 7bbb563bf2a70..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/ansi-regex/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "ansi-regex", - "version": "6.0.1", - "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", - "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": { - "ava": "^3.15.0", - "tsd": "^0.14.0", - "xo": "^0.38.2" - } -} diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/LICENSE-MIT.txt b/node_modules/@isaacs/cliui/node_modules/emoji-regex/LICENSE-MIT.txt deleted file mode 100644 index a41e0a7ef970e..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/emoji-regex/LICENSE-MIT.txt +++ /dev/null @@ -1,20 +0,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. diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/RGI_Emoji.js b/node_modules/@isaacs/cliui/node_modules/emoji-regex/RGI_Emoji.js deleted file mode 100644 index 3fbe92410063f..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/emoji-regex/RGI_Emoji.js +++ /dev/null @@ -1,6 +0,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]/g; -}; diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/RGI_Emoji.js b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/RGI_Emoji.js deleted file mode 100644 index ecf32f177908c..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/RGI_Emoji.js +++ /dev/null @@ -1,6 +0,0 @@ -"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; -}; diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/index.js b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/index.js deleted file mode 100644 index 1a4fc8d0dcc32..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/index.js +++ /dev/null @@ -1,6 +0,0 @@ -"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; -}; diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/text.js b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/text.js deleted file mode 100644 index 8e9f985758314..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/text.js +++ /dev/null @@ -1,6 +0,0 @@ -"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; -}; diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/index.js b/node_modules/@isaacs/cliui/node_modules/emoji-regex/index.js deleted file mode 100644 index c0490d4c95ac3..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/emoji-regex/index.js +++ /dev/null @@ -1,6 +0,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]|(?:[\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; -}; diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/package.json b/node_modules/@isaacs/cliui/node_modules/emoji-regex/package.json deleted file mode 100644 index eac892a16a253..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/emoji-regex/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/text.js b/node_modules/@isaacs/cliui/node_modules/emoji-regex/text.js deleted file mode 100644 index 9bc63ce74753f..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/emoji-regex/text.js +++ /dev/null @@ -1,6 +0,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; -}; diff --git a/node_modules/@isaacs/cliui/node_modules/string-width/index.js b/node_modules/@isaacs/cliui/node_modules/string-width/index.js deleted file mode 100644 index 9294488f88488..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/string-width/index.js +++ /dev/null @@ -1,54 +0,0 @@ -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; -} diff --git a/node_modules/@isaacs/cliui/node_modules/string-width/license b/node_modules/@isaacs/cliui/node_modules/string-width/license deleted file mode 100644 index fa7ceba3eb4a9..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/string-width/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/@isaacs/cliui/node_modules/string-width/package.json b/node_modules/@isaacs/cliui/node_modules/string-width/package.json deleted file mode 100644 index f46d6770f9ebb..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/string-width/package.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/@isaacs/cliui/node_modules/strip-ansi/index.js b/node_modules/@isaacs/cliui/node_modules/strip-ansi/index.js deleted file mode 100644 index ba19750e64e06..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/strip-ansi/index.js +++ /dev/null @@ -1,14 +0,0 @@ -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, ''); -} diff --git a/node_modules/@isaacs/cliui/node_modules/strip-ansi/license b/node_modules/@isaacs/cliui/node_modules/strip-ansi/license deleted file mode 100644 index fa7ceba3eb4a9..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/strip-ansi/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/@isaacs/cliui/node_modules/strip-ansi/package.json b/node_modules/@isaacs/cliui/node_modules/strip-ansi/package.json deleted file mode 100644 index e1f455c325b00..0000000000000 --- a/node_modules/@isaacs/cliui/node_modules/strip-ansi/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/@isaacs/cliui/package.json b/node_modules/@isaacs/cliui/package.json deleted file mode 100644 index 7a952532def5d..0000000000000 --- a/node_modules/@isaacs/cliui/package.json +++ /dev/null @@ -1,86 +0,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" - } -} diff --git a/node_modules/chownr/LICENSE b/node_modules/@isaacs/fs-minipass/LICENSE similarity index 100% rename from node_modules/chownr/LICENSE rename to node_modules/@isaacs/fs-minipass/LICENSE diff --git a/node_modules/@isaacs/fs-minipass/dist/commonjs/index.js b/node_modules/@isaacs/fs-minipass/dist/commonjs/index.js new file mode 100644 index 0000000000000..2b3178c5263b4 --- /dev/null +++ b/node_modules/@isaacs/fs-minipass/dist/commonjs/index.js @@ -0,0 +1,430 @@ +"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 \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/package.json b/node_modules/@isaacs/fs-minipass/dist/commonjs/package.json similarity index 100% rename from node_modules/foreground-child/dist/commonjs/package.json rename to node_modules/@isaacs/fs-minipass/dist/commonjs/package.json diff --git a/node_modules/@isaacs/fs-minipass/dist/esm/index.js b/node_modules/@isaacs/fs-minipass/dist/esm/index.js new file mode 100644 index 0000000000000..287a0f614dcc6 --- /dev/null +++ b/node_modules/@isaacs/fs-minipass/dist/esm/index.js @@ -0,0 +1,420 @@ +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 \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/package.json b/node_modules/@isaacs/fs-minipass/dist/esm/package.json similarity index 100% rename from node_modules/foreground-child/dist/esm/package.json rename to node_modules/@isaacs/fs-minipass/dist/esm/package.json diff --git a/node_modules/@isaacs/fs-minipass/package.json b/node_modules/@isaacs/fs-minipass/package.json new file mode 100644 index 0000000000000..cc4576c4afe77 --- /dev/null +++ b/node_modules/@isaacs/fs-minipass/package.json @@ -0,0 +1,72 @@ +{ + "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" + } +} diff --git a/node_modules/@npmcli/agent/lib/agents.js b/node_modules/@npmcli/agent/lib/agents.js index c541b93001517..e9624dfeb9009 100644 --- a/node_modules/@npmcli/agent/lib/agents.js +++ b/node_modules/@npmcli/agent/lib/agents.js @@ -203,4 +203,56 @@ module.exports = class Agent extends AgentBase { return super.addRequest(request, options) } + + // When connect() rejects, agent-base removes only its placeholder socket, so Node never drains this.requests[name] and requests queued past maxSockets hang forever. + // On a failure we dispatch the next queued request ourselves. + // See npm/cli#9386 and TooTallNate/proxy-agents#427. + createSocket (req, options, cb) { + super.createSocket(req, options, (err, socket) => { + if (err) { + this.#drainPendingRequests(req, options) + } + cb(err, socket) + }) + } + + // Dispatch the next request queued behind maxSockets, reusing the slot the failed connection freed. + #drainPendingRequests (failedReq, options) { + const name = this.getName(options) + const queue = this.requests[name] + if (!queue || queue.length === 0) { + return + } + + // Node's removeSocket() picks a queued request without shifting it off, so drop the failed one to avoid dispatching it twice. + const failedIndex = queue.indexOf(failedReq) + if (failedIndex !== -1) { + queue.splice(failedIndex, 1) + } + if (queue.length === 0) { + delete this.requests[name] + return + } + + // Safety belt: only dispatch if a socket slot is genuinely free. + const socketCount = this.sockets[name] ? this.sockets[name].length : 0 + if (socketCount >= this.maxSockets || this.totalSocketCount >= this.maxTotalSockets) { + return + } + + const nextReq = queue.shift() + if (queue.length === 0) { + delete this.requests[name] + } + + // All queued requests share this origin, so the failed request's options suit the next one. + // createSocket() recurses here if this connection also fails, draining the whole queue. + this.createSocket(nextReq, options, (err, socket) => { + if (err) { + nextReq.onSocket(null, err) + } else { + nextReq.onSocket(socket) + } + }) + } } diff --git a/node_modules/@npmcli/agent/lib/options.js b/node_modules/@npmcli/agent/lib/options.js index 0bf53f725f084..a6ae490a89c3b 100644 --- a/node_modules/@npmcli/agent/lib/options.js +++ b/node_modules/@npmcli/agent/lib/options.js @@ -37,6 +37,10 @@ const normalizeOptions = (opts) => { // remove timeout since we already used it to set our own idle timeout delete normalized.timeout + // since opts is often passed when initiating requests, it may contain + // headers, which should not be saved in an agent + delete normalized.headers + return normalized } diff --git a/node_modules/agent-base/LICENSE b/node_modules/@npmcli/agent/node_modules/agent-base/LICENSE similarity index 100% rename from node_modules/agent-base/LICENSE rename to node_modules/@npmcli/agent/node_modules/agent-base/LICENSE diff --git a/node_modules/@npmcli/agent/node_modules/agent-base/dist/helpers.js b/node_modules/@npmcli/agent/node_modules/agent-base/dist/helpers.js new file mode 100644 index 0000000000000..42c6ed2a0fed0 --- /dev/null +++ b/node_modules/@npmcli/agent/node_modules/agent-base/dist/helpers.js @@ -0,0 +1,37 @@ +import * as http from 'http'; +import * as https from 'https'; +export 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); +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export 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; + } +} +export 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; +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/@npmcli/agent/node_modules/agent-base/dist/index.js b/node_modules/@npmcli/agent/node_modules/agent-base/dist/index.js new file mode 100644 index 0000000000000..15aa6e9d74593 --- /dev/null +++ b/node_modules/@npmcli/agent/node_modules/agent-base/dist/index.js @@ -0,0 +1,146 @@ +import * as net from 'net'; +import * as http from 'http'; +import { Agent as HttpsAgent } from 'https'; +export * from './helpers.js'; +const INTERNAL = Symbol('AgentBaseInternalState'); +export 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 = this.isSecureEndpoint(options); + if (secureEndpoint) { + return HttpsAgent.prototype.getName.call(this, options); + } + 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 (typeof socket + .addRequest === 'function') { + try { + 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; + } + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@npmcli/agent/node_modules/agent-base/package.json b/node_modules/@npmcli/agent/node_modules/agent-base/package.json new file mode 100644 index 0000000000000..8ef80c2bb094f --- /dev/null +++ b/node_modules/@npmcli/agent/node_modules/agent-base/package.json @@ -0,0 +1,46 @@ +{ + "name": "agent-base", + "version": "9.0.0", + "type": "module", + "description": "Turn a function into an `http.Agent` instance", + "exports": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "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/node": "^22.13.0", + "@types/semver": "^7.3.13", + "@types/ws": "^8.5.4", + "async-listen": "^3.0.0", + "typescript": "^5.1.6", + "ws": "^8.13.0", + "tsconfig": "0.0.0" + }, + "engines": { + "node": ">= 20" + }, + "scripts": { + "build": "tsc", + "test": "vitest", + "lint": "eslint . --ext .ts", + "pack": "node ../../scripts/pack.mjs" + } +} \ No newline at end of file diff --git a/node_modules/http-proxy-agent/LICENSE b/node_modules/@npmcli/agent/node_modules/http-proxy-agent/LICENSE similarity index 100% rename from node_modules/http-proxy-agent/LICENSE rename to node_modules/@npmcli/agent/node_modules/http-proxy-agent/LICENSE diff --git a/node_modules/@npmcli/agent/node_modules/http-proxy-agent/dist/index.js b/node_modules/@npmcli/agent/node_modules/http-proxy-agent/dist/index.js new file mode 100644 index 0000000000000..441f27c99b1e8 --- /dev/null +++ b/node_modules/@npmcli/agent/node_modules/http-proxy-agent/dist/index.js @@ -0,0 +1,132 @@ +import * as net from 'net'; +import * as tls from 'tls'; +import createDebug from 'debug'; +import { once } from 'events'; +import { Agent } from 'agent-base'; +import { URL } from 'url'; +import { createNegotiateAuth, } from 'proxy-agent-negotiate'; +const debug = createDebug('http-proxy-agent'); +/** + * The `HttpProxyAgent` implements an HTTP Agent subclass that connects + * to the specified "HTTP proxy server" in order to proxy HTTP requests. + */ +export class HttpProxyAgent extends Agent { + constructor(proxy, opts) { + super(opts); + this.proxy = typeof proxy === 'string' ? new URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug('Creating new HttpProxyAgent instance: %o', this.proxy.href); + if (opts?.negotiate) { + this.onProxyAuth = createNegotiateAuth(); + } + else if (opts?.onProxyAuth) { + this.onProxyAuth = opts.onProxyAuth; + } + // 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', 'onProxyAuth', 'negotiate') + : 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(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 once(socket, 'connect'); + // Emit the 'proxyConnect' event for parity with https-proxy-agent + const connect = { socket }; + req.emit('proxyConnect', connect); + this.emit('proxyConnect', connect, req); + req.emit('proxy', { proxy: this.proxy.href, socket }); + return socket; + } +} +HttpProxyAgent.protocols = ['http', 'https']; +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 \ No newline at end of file diff --git a/node_modules/@npmcli/agent/node_modules/http-proxy-agent/package.json b/node_modules/@npmcli/agent/node_modules/http-proxy-agent/package.json new file mode 100644 index 0000000000000..c821fe00b5de8 --- /dev/null +++ b/node_modules/@npmcli/agent/node_modules/http-proxy-agent/package.json @@ -0,0 +1,48 @@ +{ + "name": "http-proxy-agent", + "version": "9.1.0", + "type": "module", + "description": "An HTTP(s) proxy `http.Agent` implementation for HTTP", + "exports": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "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": { + "debug": "^4.3.4", + "agent-base": "9.0.0", + "proxy-agent-negotiate": "1.1.0" + }, + "devDependencies": { + "@types/debug": "^4.1.7", + "@types/node": "^22.13.0", + "async-listen": "^3.0.0", + "typescript": "^5.1.6", + "tsconfig": "0.0.0", + "proxy": "4.1.0" + }, + "engines": { + "node": ">= 20" + }, + "scripts": { + "build": "tsc", + "test": "vitest", + "lint": "eslint . --ext .ts", + "pack": "node ../../scripts/pack.mjs" + } +} \ No newline at end of file diff --git a/node_modules/https-proxy-agent/LICENSE b/node_modules/@npmcli/agent/node_modules/https-proxy-agent/LICENSE similarity index 100% rename from node_modules/https-proxy-agent/LICENSE rename to node_modules/@npmcli/agent/node_modules/https-proxy-agent/LICENSE diff --git a/node_modules/@npmcli/agent/node_modules/https-proxy-agent/dist/index.js b/node_modules/@npmcli/agent/node_modules/https-proxy-agent/dist/index.js new file mode 100644 index 0000000000000..207a134b35571 --- /dev/null +++ b/node_modules/@npmcli/agent/node_modules/https-proxy-agent/dist/index.js @@ -0,0 +1,234 @@ +import * as net from 'net'; +import * as tls from 'tls'; +import assert from 'assert'; +import createDebug from 'debug'; +import { Agent } from 'agent-base'; +import { URL } from 'url'; +import { parseProxyResponse } from './parse-proxy-response.js'; +import { createNegotiateAuth, } from 'proxy-agent-negotiate'; +const debug = createDebug('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. + */ +export class HttpsProxyAgent extends Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: undefined }; + this.proxy = typeof proxy === 'string' ? new URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); + if (opts?.negotiate) { + this.onProxyAuth = createNegotiateAuth(); + } + else if (opts?.onProxyAuth) { + this.onProxyAuth = opts.onProxyAuth; + } + // 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', 'onProxyAuth', 'negotiate') + : 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 = parseProxyResponse(socket); + socket.write(`${payload}\r\n`); + const { connect, buffered } = await proxyResponsePromise; + req.emit('proxyConnect', connect); + this.emit('proxyConnect', connect, req); + req.emit('proxy', { proxy: this.proxy.href, socket }); + 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; + } + // Handle 407 Proxy Authentication Required + if (connect.statusCode === 407 && this.onProxyAuth) { + debug('Got 407 response, invoking onProxyAuth callback'); + socket.destroy(); + const proxyAuthenticate = connect.headers['proxy-authenticate'] || ''; + const scheme = Array.isArray(proxyAuthenticate) + ? proxyAuthenticate[0].split(/\s/)[0] + : proxyAuthenticate.split(/\s/)[0]; + const authResponse = await this.onProxyAuth({ + response: connect, + scheme, + }); + // Retry with the auth headers + return this._connectWithAuth(req, opts, authResponse.headers); + } + // 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'); + assert(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; + } + /** + * Retry a CONNECT request with additional auth headers. + */ + async _connectWithAuth(req, opts, authHeaders) { + const { proxy } = this; + let socket; + if (proxy.protocol === 'https:') { + socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + } + else { + 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`; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + } + // Merge auth headers (overrides existing) + Object.assign(headers, authHeaders); + 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 = parseProxyResponse(socket); + socket.write(`${payload}\r\n`); + const { connect } = await proxyResponsePromise; + req.emit('proxyConnect', connect); + this.emit('proxyConnect', connect, req); + if (connect.statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + debug('Upgrading socket connection to TLS'); + return tls.connect({ + ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'), + socket, + }); + } + return socket; + } + // If still not 200, throw + socket.destroy(); + throw new Error(`Proxy authentication failed with status ${connect.statusCode} after retry`); + } +} +HttpsProxyAgent.protocols = ['http', 'https']; +function resume(socket) { + // Defer the resume so that all 'socket' event handlers have a chance + // to attach their listeners (e.g. the HTTP client's 'data' handler) + // before data starts flowing. Without this, buffered proxy-response + // data can be emitted synchronously before listeners are ready. + // See: https://github.com/nicolo-ribaudo/tc39-proposal-await-dictionary/issues/7 + setImmediate(() => { + 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 \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/parse-proxy-response.js b/node_modules/@npmcli/agent/node_modules/https-proxy-agent/dist/parse-proxy-response.js similarity index 87% rename from node_modules/https-proxy-agent/dist/parse-proxy-response.js rename to node_modules/@npmcli/agent/node_modules/https-proxy-agent/dist/parse-proxy-response.js index d3f506f941306..6ecc13a55291d 100644 --- a/node_modules/https-proxy-agent/dist/parse-proxy-response.js +++ b/node_modules/@npmcli/agent/node_modules/https-proxy-agent/dist/parse-proxy-response.js @@ -1,12 +1,6 @@ -"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) { +import createDebug from 'debug'; +const debug = createDebug('https-proxy-agent:parse-proxy-response'); +export 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" @@ -97,5 +91,4 @@ function parseProxyResponse(socket) { read(); }); } -exports.parseProxyResponse = parseProxyResponse; //# sourceMappingURL=parse-proxy-response.js.map \ No newline at end of file diff --git a/node_modules/@npmcli/agent/node_modules/https-proxy-agent/package.json b/node_modules/@npmcli/agent/node_modules/https-proxy-agent/package.json new file mode 100644 index 0000000000000..ae575a2aefa27 --- /dev/null +++ b/node_modules/@npmcli/agent/node_modules/https-proxy-agent/package.json @@ -0,0 +1,51 @@ +{ + "name": "https-proxy-agent", + "version": "9.1.0", + "type": "module", + "description": "An HTTP(s) proxy `http.Agent` implementation for HTTPS", + "exports": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "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": { + "debug": "^4.3.4", + "agent-base": "9.0.0", + "proxy-agent-negotiate": "1.1.0" + }, + "devDependencies": { + "@types/async-retry": "^1.4.5", + "@types/debug": "^4.1.7", + "@types/node": "^22.13.0", + "async-listen": "^3.0.0", + "async-retry": "^1.3.3", + "typescript": "^5.1.6", + "proxy": "4.1.0", + "tsconfig": "0.0.0" + }, + "engines": { + "node": ">= 20" + }, + "scripts": { + "build": "tsc", + "test": "vitest --exclude test/e2e.test.ts", + "test-e2e": "vitest run test/e2e.test.ts", + "lint": "eslint --ext .ts", + "pack": "node ../../scripts/pack.mjs" + } +} \ No newline at end of file diff --git a/node_modules/@npmcli/agent/package.json b/node_modules/@npmcli/agent/package.json index ef5b4e3228cc4..246ed5edade71 100644 --- a/node_modules/@npmcli/agent/package.json +++ b/node_modules/@npmcli/agent/package.json @@ -1,17 +1,18 @@ { "name": "@npmcli/agent", - "version": "2.2.2", + "version": "5.0.1", "description": "the http/https agent used by the npm cli", "main": "lib/index.js", "scripts": { "gencerts": "bash scripts/create-cert.sh", "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "posttest": "npm run lint" + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "author": "GitHub Inc.", "license": "ISC", @@ -24,32 +25,32 @@ "lib/" ], "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.3", - "publish": "true" + "version": "5.1.0", + "publish": "true", + "updateNpm": false }, "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" + "agent-base": "^9.0.0", + "http-proxy-agent": "^9.0.0", + "https-proxy-agent": "^9.0.0", + "lru-cache": "^11.2.1", + "socks-proxy-agent": "^10.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.3", - "minipass-fetch": "^3.0.3", - "nock": "^13.2.7", - "semver": "^7.5.4", - "simple-socks": "^3.1.0", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.0", + "ip-address": "^10.1.0", + "minipass-fetch": "^6.0.0", + "nock": "^14.0.3", "tap": "^16.3.0" }, "repository": { "type": "git", - "url": "https://github.com/npm/agent.git" + "url": "git+https://github.com/npm/agent.git" }, "tap": { "nyc-arg": [ diff --git a/node_modules/@npmcli/fs/lib/move-file.js b/node_modules/@npmcli/fs/lib/move-file.js index d56e06d384659..d7022eee4abf9 100644 --- a/node_modules/@npmcli/fs/lib/move-file.js +++ b/node_modules/@npmcli/fs/lib/move-file.js @@ -56,19 +56,19 @@ const moveFile = async (source, destination, options = {}, root = true, symlinks } // try to determine what the actual file is so we can create the correct // type of symlink in windows - let targetStat = 'file' + let targetType = 'file' try { - targetStat = await fs.stat(resolve(dirname(symSource), target)) + const targetStat = await fs.stat(resolve(dirname(symSource), target)) if (targetStat.isDirectory()) { - targetStat = 'junction' + targetType = 'junction' } } catch { - // targetStat remains 'file' + // targetType remains 'file' } await fs.symlink( target, symDestination, - targetStat + targetType ) })) await fs.rm(source, { recursive: true, force: true }) diff --git a/node_modules/@npmcli/fs/package.json b/node_modules/@npmcli/fs/package.json index 5261a11b78000..4740d1144fbe0 100644 --- a/node_modules/@npmcli/fs/package.json +++ b/node_modules/@npmcli/fs/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/fs", - "version": "3.1.1", + "version": "6.0.0", "description": "filesystem utilities for the npm cli", "main": "lib/index.js", "files": [ @@ -11,12 +11,13 @@ "snap": "tap", "test": "tap", "npmclilint": "npmcli-lint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", @@ -29,19 +30,20 @@ "author": "GitHub Inc.", "license": "ISC", "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.1.0", "tap": "^16.0.1" }, "dependencies": { "semver": "^7.3.5" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0" + "version": "5.1.0", + "publish": true }, "tap": { "nyc-arg": [ diff --git a/node_modules/@npmcli/git/lib/revs.js b/node_modules/@npmcli/git/lib/revs.js index ca14837de1b87..ebcc848fa3458 100644 --- a/node_modules/@npmcli/git/lib/revs.js +++ b/node_modules/@npmcli/git/lib/revs.js @@ -1,14 +1,12 @@ -const pinflight = require('promise-inflight') const spawn = require('./spawn.js') const { LRUCache } = require('lru-cache') +const linesToRevs = require('./lines-to-revs.js') 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) @@ -17,12 +15,8 @@ module.exports = async (repo, opts = {}) => { } } - 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 { stdout } = await spawn(['ls-remote', repo], opts) + const revs = linesToRevs(stdout.trim().split('\n')) + revsCache.set(repo, revs) + return revs } diff --git a/node_modules/@npmcli/git/lib/spawn.js b/node_modules/@npmcli/git/lib/spawn.js index 03c1cbde21547..e4abd420098ee 100644 --- a/node_modules/@npmcli/git/lib/spawn.js +++ b/node_modules/@npmcli/git/lib/spawn.js @@ -1,5 +1,5 @@ const spawn = require('@npmcli/promise-spawn') -const promiseRetry = require('promise-retry') +const { promiseRetry } = require('@gar/promise-retry') const { log } = require('proc-log') const makeError = require('./make-error.js') const makeOpts = require('./opts.js') diff --git a/node_modules/@npmcli/git/package.json b/node_modules/@npmcli/git/package.json index b6aa4a282cc0f..a595184d9151c 100644 --- a/node_modules/@npmcli/git/package.json +++ b/node_modules/@npmcli/git/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/git", - "version": "5.0.8", + "version": "8.0.0", "main": "lib/index.js", "files": [ "bin/", @@ -14,13 +14,14 @@ "author": "GitHub Inc.", "license": "ISC", "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "snap": "tap", "test": "tap", "posttest": "npm run lint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "template-oss-apply": "template-oss-apply --force" + "lintfix": "npm run eslint -- --fix", + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "timeout": 600, @@ -30,29 +31,29 @@ ] }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "npm-package-arg": "^11.0.0", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.0", + "npm-package-arg": "^14.0.0", "slash": "^3.0.0", "tap": "^16.0.1" }, "dependencies": { - "@npmcli/promise-spawn": "^7.0.0", - "ini": "^4.1.3", - "lru-cache": "^10.0.1", - "npm-pick-manifest": "^9.0.0", - "proc-log": "^4.0.0", - "promise-inflight": "^1.0.1", - "promise-retry": "^2.0.1", + "@gar/promise-retry": "^1.0.0", + "@npmcli/promise-spawn": "^10.0.0", + "ini": "^7.0.0", + "lru-cache": "^11.2.1", + "npm-pick-manifest": "^12.0.0", + "proc-log": "^7.0.0", "semver": "^7.3.5", - "which": "^4.0.0" + "which": "^7.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true + "version": "5.1.0", + "publish": true, + "updateNpm": false } } diff --git a/node_modules/cmd-shim/LICENSE b/node_modules/@npmcli/installed-package-contents/node_modules/npm-bundled/LICENSE similarity index 100% rename from node_modules/cmd-shim/LICENSE rename to node_modules/@npmcli/installed-package-contents/node_modules/npm-bundled/LICENSE diff --git a/node_modules/npm-bundled/lib/index.js b/node_modules/@npmcli/installed-package-contents/node_modules/npm-bundled/lib/index.js similarity index 100% rename from node_modules/npm-bundled/lib/index.js rename to node_modules/@npmcli/installed-package-contents/node_modules/npm-bundled/lib/index.js diff --git a/node_modules/@npmcli/installed-package-contents/node_modules/npm-bundled/package.json b/node_modules/@npmcli/installed-package-contents/node_modules/npm-bundled/package.json new file mode 100644 index 0000000000000..559c997a64321 --- /dev/null +++ b/node_modules/@npmcli/installed-package-contents/node_modules/npm-bundled/package.json @@ -0,0 +1,49 @@ +{ + "name": "npm-bundled", + "version": "6.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": "^6.0.0", + "@npmcli/template-oss": "5.1.0", + "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": "^6.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "5.1.0", + "publish": true + }, + "tap": { + "nyc-arg": [ + "--exclude", + "tap-snapshots/**" + ] + } +} diff --git a/node_modules/npm-normalize-package-bin/LICENSE b/node_modules/@npmcli/installed-package-contents/node_modules/npm-normalize-package-bin/LICENSE similarity index 100% rename from node_modules/npm-normalize-package-bin/LICENSE rename to node_modules/@npmcli/installed-package-contents/node_modules/npm-normalize-package-bin/LICENSE diff --git a/node_modules/npm-normalize-package-bin/lib/index.js b/node_modules/@npmcli/installed-package-contents/node_modules/npm-normalize-package-bin/lib/index.js similarity index 100% rename from node_modules/npm-normalize-package-bin/lib/index.js rename to node_modules/@npmcli/installed-package-contents/node_modules/npm-normalize-package-bin/lib/index.js diff --git a/node_modules/@npmcli/installed-package-contents/node_modules/npm-normalize-package-bin/package.json b/node_modules/@npmcli/installed-package-contents/node_modules/npm-normalize-package-bin/package.json new file mode 100644 index 0000000000000..1d0d821b7a2ce --- /dev/null +++ b/node_modules/@npmcli/installed-package-contents/node_modules/npm-normalize-package-bin/package.json @@ -0,0 +1,42 @@ +{ + "name": "npm-normalize-package-bin", + "version": "6.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": "node --test './test/**/*.js'", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "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}\"", + "test:node20": "node --test test", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'" + }, + "devDependencies": { + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0" + }, + "files": [ + "bin/", + "lib/" + ], + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "5.0.0", + "publish": "true", + "testRunner": "node:test", + "latestCiVersion": 24 + } +} diff --git a/node_modules/@npmcli/installed-package-contents/package.json b/node_modules/@npmcli/installed-package-contents/package.json index 132256430a6c1..4111600f4cd9f 100644 --- a/node_modules/@npmcli/installed-package-contents/package.json +++ b/node_modules/@npmcli/installed-package-contents/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/installed-package-contents", - "version": "2.1.0", + "version": "5.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", @@ -11,35 +11,36 @@ "scripts": { "test": "tap", "snap": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint" + "lintfix": "npm run eslint -- --fix", + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.4", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.1.0", "tap": "^16.3.0" }, "dependencies": { - "npm-bundled": "^3.0.0", - "npm-normalize-package-bin": "^3.0.0" + "npm-bundled": "^6.0.0", + "npm-normalize-package-bin": "^6.0.0" }, "repository": { "type": "git", - "url": "https://github.com/npm/installed-package-contents.git" + "url": "git+https://github.com/npm/installed-package-contents.git" }, "files": [ "bin/", "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.4", + "version": "5.1.0", "publish": true }, "tap": { diff --git a/node_modules/@npmcli/map-workspaces/lib/index.js b/node_modules/@npmcli/map-workspaces/lib/index.js index b20bf5de5d631..f38b8cd33b74f 100644 --- a/node_modules/@npmcli/map-workspaces/lib/index.js +++ b/node_modules/@npmcli/map-workspaces/lib/index.js @@ -2,7 +2,7 @@ const path = require('path') const getName = require('@npmcli/name-from-folder') const { minimatch } = require('minimatch') -const rpj = require('read-package-json-fast') +const pkgJson = require('@npmcli/package-json') const { glob } = require('glob') function appendNegatedPatterns (allPatterns) { @@ -67,15 +67,7 @@ function getPatterns (workspaces) { } function getPackageName (pkg, pathname) { - const { name } = pkg - return name || getName(pathname) -} - -function pkgPathmame (opts) { - return (...args) => { - const cwd = opts.cwd ? opts.cwd : process.cwd() - return path.join.apply(null, [cwd, ...args]) - } + return pkg.name || getName(pathname) } // make sure glob pattern only matches folders @@ -101,16 +93,19 @@ async function mapWorkspaces (opts = {}) { code: 'EMAPWORKSPACESPKG', }) } + if (!opts.cwd) { + opts.cwd = process.cwd() + } const { workspaces = [] } = opts.pkg const { patterns, negatedPatterns } = getPatterns(workspaces) const results = new Map() - const seen = new Map() if (!patterns.length && !negatedPatterns.length) { return results } + const seen = new Map() const getGlobOpts = () => ({ ...opts, ignore: [ @@ -121,8 +116,6 @@ async function mapWorkspaces (opts = {}) { ], }) - const getPackagePathname = pkgPathmame(opts) - let matches = await glob(patterns.map((p) => getGlobPattern(p)), getGlobOpts()) // preserves glob@8 behavior matches = matches.sort((a, b) => a.localeCompare(b, 'en')) @@ -138,27 +131,24 @@ async function mapWorkspaces (opts = {}) { for (const match of orderedMatches) { let pkg - const packageJsonPathname = getPackagePathname(match, 'package.json') - try { - pkg = await rpj(packageJsonPathname) + pkg = await pkgJson.normalize(path.join(opts.cwd, match)) } catch (err) { - if (err.code === 'ENOENT') { + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') { continue } else { throw err } } - const packagePathname = path.dirname(packageJsonPathname) - const name = getPackageName(pkg, packagePathname) + const name = getPackageName(pkg.content, pkg.path) let seenPackagePathnames = seen.get(name) if (!seenPackagePathnames) { seenPackagePathnames = new Set() seen.set(name, seenPackagePathnames) } - seenPackagePathnames.add(packagePathname) + seenPackagePathnames.add(pkg.path) } const errorMessageArray = ['must not have multiple workspaces with the same name'] @@ -200,6 +190,9 @@ mapWorkspaces.virtual = function (opts = {}) { code: 'EMAPWORKSPACESLOCKFILE', }) } + if (!opts.cwd) { + opts.cwd = process.cwd() + } const { packages = {} } = opts.lockfile const { workspaces = [] } = packages[''] || {} @@ -218,10 +211,9 @@ mapWorkspaces.virtual = function (opts = {}) { } } - const getPackagePathname = pkgPathmame(opts) for (const pattern of patterns) { for (const packageKey of minimatch.match(packageKeys, pattern)) { - const packagePathname = getPackagePathname(packageKey) + const packagePathname = path.join(opts.cwd, packageKey) const name = getPackageName(packages[packageKey], packagePathname) results.set(packagePathname, name) } diff --git a/node_modules/@npmcli/map-workspaces/package.json b/node_modules/@npmcli/map-workspaces/package.json index e6292b06bd2b4..f16e7f91722be 100644 --- a/node_modules/@npmcli/map-workspaces/package.json +++ b/node_modules/@npmcli/map-workspaces/package.json @@ -1,18 +1,18 @@ { "name": "@npmcli/map-workspaces", - "version": "3.0.6", + "version": "6.0.0", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "description": "Retrieves a name:pathname Map for a given workspaces config", "repository": { "type": "git", - "url": "https://github.com/npm/map-workspaces.git" + "url": "git+https://github.com/npm/map-workspaces.git" }, "keywords": [ "npm", @@ -25,14 +25,15 @@ "author": "GitHub Inc.", "license": "ISC", "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "pretest": "npm run lint", "test": "tap", "snap": "tap", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "check-coverage": true, @@ -42,19 +43,19 @@ ] }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.3", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.0", "tap": "^16.0.1" }, "dependencies": { - "@npmcli/name-from-folder": "^2.0.0", - "glob": "^10.2.2", - "minimatch": "^9.0.0", - "read-package-json-fast": "^3.0.0" + "@npmcli/name-from-folder": "^5.0.0", + "@npmcli/package-json": "^8.0.0", + "glob": "^13.0.0", + "minimatch": "^10.0.3" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.3", + "version": "5.1.0", "publish": "true" } } diff --git a/node_modules/@npmcli/metavuln-calculator/lib/advisory.js b/node_modules/@npmcli/metavuln-calculator/lib/advisory.js index 01f6a66fc2ac4..1f4554963d7e4 100644 --- a/node_modules/@npmcli/metavuln-calculator/lib/advisory.js +++ b/node_modules/@npmcli/metavuln-calculator/lib/advisory.js @@ -292,7 +292,7 @@ class Advisory { [_testSpec] (spec) { for (const v of this.versions) { - const satisfies = semver.satisfies(v, spec) + const satisfies = semver.satisfies(v, spec, semverOpt) if (!satisfies) { continue } diff --git a/node_modules/@npmcli/metavuln-calculator/package.json b/node_modules/@npmcli/metavuln-calculator/package.json index a7ec02d2ee72b..23f539fa95f67 100644 --- a/node_modules/@npmcli/metavuln-calculator/package.json +++ b/node_modules/@npmcli/metavuln-calculator/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/metavuln-calculator", - "version": "7.1.1", + "version": "10.0.0", "main": "lib/index.js", "files": [ "bin/", @@ -18,9 +18,9 @@ "posttest": "npm run lint", "snap": "tap", "postsnap": "npm run lint", - "eslint": "eslint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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" }, @@ -33,30 +33,24 @@ ] }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.0", "require-inject": "^1.4.4", "tap": "^16.0.1" }, "dependencies": { - "cacache": "^18.0.0", - "json-parse-even-better-errors": "^3.0.0", - "pacote": "^18.0.0", - "proc-log": "^4.1.0", + "cacache": "^21.0.1", + "json-parse-even-better-errors": "^6.0.0", + "pacote": "^22.0.0", + "proc-log": "^7.0.0", "semver": "^7.3.5" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": "true", - "ciVersions": [ - "16.14.0", - "16.x", - "18.0.0", - "18.x" - ] + "version": "5.1.0", + "publish": "true" } } diff --git a/node_modules/@npmcli/name-from-folder/package.json b/node_modules/@npmcli/name-from-folder/package.json index f0aa5b16dba1a..60fbc9949d1ea 100644 --- a/node_modules/@npmcli/name-from-folder/package.json +++ b/node_modules/@npmcli/name-from-folder/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/name-from-folder", - "version": "2.0.0", + "version": "5.0.0", "files": [ "bin/", "lib/" @@ -9,35 +9,34 @@ "description": "Get the package name from a folder path", "repository": { "type": "git", - "url": "https://github.com/npm/name-from-folder.git" + "url": "git+https://github.com/npm/name-from-folder.git" }, "author": "GitHub Inc.", "license": "ISC", "scripts": { - "test": "tap", - "snap": "tap", - "lint": "eslint \"**/*.js\"", + "test": "node --test './test/**/*.js'", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint" + "lintfix": "npm run eslint -- --fix", + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test:node20": "node --test test", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.1", - "@npmcli/template-oss": "4.11.0", - "tap": "^16.3.2" + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.11.0" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] + "version": "5.0.0", + "publish": true, + "testRunner": "node:test", + "latestCiVersion": 24 } } diff --git a/node_modules/@npmcli/node-gyp/LICENSE b/node_modules/@npmcli/node-gyp/LICENSE new file mode 100644 index 0000000000000..3609cabca4535 --- /dev/null +++ b/node_modules/@npmcli/node-gyp/LICENSE @@ -0,0 +1,7 @@ +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. diff --git a/node_modules/@npmcli/node-gyp/package.json b/node_modules/@npmcli/node-gyp/package.json index 999572bc5883a..324024de266a5 100644 --- a/node_modules/@npmcli/node-gyp/package.json +++ b/node_modules/@npmcli/node-gyp/package.json @@ -1,19 +1,20 @@ { "name": "@npmcli/node-gyp", - "version": "3.0.0", + "version": "6.0.0", "description": "Tools for dealing with node-gyp packages", "scripts": { "test": "tap", - "lint": "eslint \"**/*.js\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "posttest": "npm run lint" + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", - "url": "https://github.com/npm/node-gyp.git" + "url": "git+https://github.com/npm/node-gyp.git" }, "keywords": [ "npm", @@ -28,16 +29,17 @@ "author": "GitHub Inc.", "license": "ISC", "devDependencies": { - "@npmcli/eslint-config": "^3.0.1", - "@npmcli/template-oss": "4.5.1", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0", "tap": "^16.0.1" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.5.1" + "version": "5.0.0", + "publish": true }, "tap": { "nyc-arg": [ diff --git a/node_modules/@npmcli/package-json/lib/index.js b/node_modules/@npmcli/package-json/lib/index.js index f165ee23b75ab..39cc0980e4659 100644 --- a/node_modules/@npmcli/package-json/lib/index.js +++ b/node_modules/@npmcli/package-json/lib/index.js @@ -5,8 +5,9 @@ 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 { normalize, syncNormalize } = 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 @@ -24,23 +25,11 @@ const knownKeys = new Set([ ]) 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', + 'fixName', 'fixVersionField', 'fixRepositoryField', 'fixDependencies', @@ -48,14 +37,27 @@ class PackageJson { 'scriptpath', ]) + static normalizeSteps = Object.freeze([ + '_id', + '_attributes', + 'bundledDependencies', + 'bundleDependencies', + 'overrides', + 'optionalDedupe', + 'scripts', + 'funding', + 'bin', + 'binDir', + ]) + static prepareSteps = Object.freeze([ '_id', '_attributes', 'bundledDependencies', 'bundleDependencies', 'bundleDependenciesDeleteFalse', + 'overrides', 'gypfile', - 'serverjs', 'scriptpath', 'authors', 'readme', @@ -162,7 +164,11 @@ class PackageJson { return this } + // Manually set data from an existing object fromContent (data) { + if (!data || typeof data !== 'object') { + throw new Error('Content data must be an object') + } this.#manifest = data this.#canSave = false return this @@ -220,7 +226,7 @@ class PackageJson { this.#manifest = step({ content, originalContent: this.content }) } - // unknown properties will just be overwitten + // unknown properties will just be overwritten for (const [key, value] of Object.entries(content)) { if (!knownKeys.has(key)) { this.content[key] = value @@ -230,27 +236,40 @@ class PackageJson { return this } - async save () { + 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(this.content, null, format) + JSON.stringify(content, null, format) }\n` .replace(/\n/g, eol) if (fileContent.trim() !== this.#readFileContent.trim()) { - return await writeFile(this.filename, fileContent) + const written = await writeFile(this.filename, fileContent) + this.#readFileContent = fileContent + return written } } + // steps is NOT overrideable here because this is a legacy function that's not being used in new places + syncNormalize (opts = {}) { + opts.steps = this.constructor.normalizeSteps.filter(s => s !== '_attributes') + syncNormalize(this, opts) + return this + } + async normalize (opts = {}) { if (!opts.steps) { opts.steps = this.constructor.normalizeSteps diff --git a/node_modules/@npmcli/package-json/lib/license.js b/node_modules/@npmcli/package-json/lib/license.js new file mode 100644 index 0000000000000..6428e83730550 --- /dev/null +++ b/node_modules/@npmcli/package-json/lib/license.js @@ -0,0 +1,27 @@ +// This is an implementation of the validForNewPackage flag in validate-npm-package-license, which is no longer maintained + +const parse = require('spdx-expression-parse') + +function usesLicenseRef (ast) { + if (Object.hasOwn(ast, 'license')) { + return ast.license.startsWith('LicenseRef') || ast.license.startsWith('DocumentRef') + } else { + return usesLicenseRef(ast.left) || usesLicenseRef(ast.right) + } +} + +// license should be a valid SPDX license expression (without "LicenseRef"), "UNLICENSED", or "SEE LICENSE IN " +module.exports = function licenseValidForNewPackage (argument) { + if (argument === 'UNLICENSED' || argument === 'UNLICENCED') { + return true + } + if (/^SEE LICEN[CS]E IN ./.test(argument)) { + return true + } + try { + const ast = parse(argument) + return !usesLicenseRef(ast) + } catch { + return false + } +} diff --git a/node_modules/@npmcli/package-json/lib/normalize-data.js b/node_modules/@npmcli/package-json/lib/normalize-data.js new file mode 100644 index 0000000000000..7bd86b5f5bb64 --- /dev/null +++ b/node_modules/@npmcli/package-json/lib/normalize-data.js @@ -0,0 +1,254 @@ +// Originally normalize-package-data + +const { URL } = require('node:url') +const hostedGitInfo = require('hosted-git-info') +const validateLicense = require('./license.js') + +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 } + } else if (URL.canParse(data.bugs)) { + 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) { + if (URL.canParse(oldBugs.url)) { + 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 { + if (!URL.canParse(data.homepage)) { + 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)) { + 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 } diff --git a/node_modules/@npmcli/package-json/lib/normalize.js b/node_modules/@npmcli/package-json/lib/normalize.js index 682d234825de9..2173b321e25c4 100644 --- a/node_modules/@npmcli/package-json/lib/normalize.js +++ b/node_modules/@npmcli/package-json/lib/normalize.js @@ -3,6 +3,7 @@ const clean = require('semver/functions/clean') const fs = require('node:fs/promises') const path = require('node:path') const { log } = require('proc-log') +const moduleBuiltin = require('node:module') /** * @type {import('hosted-git-info')} @@ -66,7 +67,7 @@ function normalizePackageBin (pkg, changes) { changes?.push(`"bin[${binKey}]" was renamed to "bin[${base}]"`) } if (binTarget !== pkg.bin[binKey]) { - changes?.push(`"bin[${base}]" script name was cleaned`) + changes?.push(`"bin[${base}]" script name ${binTarget} was invalid and removed`) } pkg.bin[base] = binTarget } @@ -127,28 +128,18 @@ function unixifyPath (ref) { return ref.replace(/\\|:/g, '/') } -function securePath (ref) { - const secured = path.join('.', path.join('/', unixifyPath(ref))) - return secured.startsWith('.') ? '' : secured -} - function secureAndUnixifyPath (ref) { - return unixifyPath(securePath(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') - } +// Only steps that can be ran synchronously. There are some object constructors (i.e. Aborist Node) that need synchronous normalization so here we are. +function syncSteps (pkg, { strict, steps, changes, allowLegacyCase }) { 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 (steps.includes('fixName') || steps.includes('fixNameField') || steps.includes('normalizeData')) { if (!data.name && !strict) { changes?.push('Missing "name" field was set to an empty string') data.name = '' @@ -174,6 +165,13 @@ const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) } } + if (steps.includes('fixName')) { + // Check for conflicts with builtin modules + if (moduleBuiltin.builtinModules.includes(data.name)) { + log.warn('package-json', pkgId, `Package name "${data.name}" conflicts with a Node.js built-in module 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 @@ -191,6 +189,7 @@ const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) } } } + // remove attributes that start with "_" if (steps.includes('_attributes')) { for (const key in data) { @@ -210,14 +209,14 @@ const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) } // 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"`) } - changes?.push(`Deleted incorrect "bundledDependencies"`) delete data.bundledDependencies } + // expand "bundleDependencies: true or translate from object" if (steps.includes('bundleDependencies')) { const bd = data.bundleDependencies @@ -238,10 +237,23 @@ const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) } } - // 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. + // normalize the shape of the top-level "overrides" field after this step it is either absent or a non-empty object, so consumers do not need to defensively check the type/size + if (steps.includes('overrides')) { + const ov = data.overrides + if (ov !== undefined) { + const isObject = ov && typeof ov === 'object' && !Array.isArray(ov) + if (!isObject) { + changes?.push(`"overrides" was removed (must be an object)`) + delete data.overrides + } else if (Object.keys(ov).length === 0) { + changes?.push(`Empty "overrides" was removed`) + delete data.overrides + } + } + } + + // 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') { @@ -256,32 +268,6 @@ const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) } } - // 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) { @@ -309,6 +295,124 @@ const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) } } + // "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) + } +} + +// Steps that require await, distinct from sync-steps.js +async function asyncSteps (pkg, { steps, root, changes }) { + const data = pkg.content + const scripts = data.scripts || {} + const pkgId = `${data.name ?? ''}@${data.version ?? ''}` + + // 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"`) + } + } + } + // populate "authors" attribute if (steps.includes('authors') && !data.contributors) { try { @@ -352,7 +456,6 @@ const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) changes?.push(`"readmeFilename" was set to ${readmeFile}`) } if (!data.readme) { - // this.warn('missingReadme') data.readme = 'ERROR: No README data found!' } } @@ -370,22 +473,19 @@ const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) 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, securePath(data.directories.bin)) - const bins = await lazyLoadGlob()('**', { cwd: binsDir }) + if (steps.includes('binDir') && data.directories?.bin && !data.bin && pkg.path) { + const binPath = secureAndUnixifyPath(data.directories.bin) + const bins = await lazyLoadGlob()('**', { cwd: path.resolve(pkg.path, binPath) }) data.bin = bins.reduce((acc, binFile) => { if (binFile && !binFile.startsWith('.')) { const binName = path.basename(binFile) - acc[binName] = path.join(data.directories.bin, binFile) + // binPath is already cleaned and unixified, no need to path.join here. + acc[binName] = `${binPath}/${secureAndUnixifyPath(binFile)}` } return acc }, {}) - // *sigh* + } else if (steps.includes('bin') || steps.includes('binDir') || steps.includes('binRefs')) { normalizePackageBin(data, changes) } @@ -483,127 +583,8 @@ const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) } } - // "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) { - /* eslint-disable-next-line max-len */ - 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() - } - } - } - } - } - } - - if (steps.includes('normalizeData')) { - const legacyFixer = require('normalize-package-data/lib/fixer.js') - const legacyMakeWarning = require('normalize-package-data/lib/make_warning.js') - legacyFixer.warn = function () { - changes?.push(legacyMakeWarning.apply(null, arguments)) - } - - const legacySteps = [ - 'fixDescriptionField', - 'fixModulesField', - 'fixFilesField', - 'fixManField', - 'fixBugsField', - 'fixKeywordsField', - 'fixBundleDependenciesField', - 'fixHomepageField', - 'fixReadmeField', - 'fixLicenseField', - 'fixPeople', - 'fixTypos', - ] - for (const legacyStep of legacySteps) { - legacyFixer[legacyStep](data) - } - } - - // 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. + // 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 { @@ -616,4 +597,19 @@ const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) } } -module.exports = normalize +// We don't want the `changes` array in here by default because this is a hot path for parsing packuments during install. +// The calling method passes it in if it wants to track changes. +async function normalize (pkg, opts) { + if (!pkg.content) { + throw new Error('Can not normalize without content') + } + await asyncSteps(pkg, opts) + // the normalizeData part of this needs to be the last thing ran, so sync comes second + syncSteps(pkg, opts) +} + +function syncNormalize (pkg, opts) { + syncSteps(pkg, opts) +} + +module.exports = { normalize, syncNormalize } diff --git a/node_modules/@npmcli/package-json/lib/sort.js b/node_modules/@npmcli/package-json/lib/sort.js new file mode 100644 index 0000000000000..0bd0d5199da58 --- /dev/null +++ b/node_modules/@npmcli/package-json/lib/sort.js @@ -0,0 +1,101 @@ +/** + * 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, +} diff --git a/node_modules/@npmcli/package-json/package.json b/node_modules/@npmcli/package-json/package.json index a5ea22bdbb340..2dd41a3a75a6b 100644 --- a/node_modules/@npmcli/package-json/package.json +++ b/node_modules/@npmcli/package-json/package.json @@ -1,7 +1,17 @@ { "name": "@npmcli/package-json", - "version": "5.2.0", + "version": "8.0.0", "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/", @@ -10,46 +20,36 @@ "scripts": { "snap": "tap", "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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" - }, - "keywords": [ - "npm", - "oss" - ], - "author": "GitHub Inc.", - "license": "ISC", - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "read-package-json": "^7.0.0", - "read-package-json-fast": "^3.0.2", - "tap": "^16.0.1" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "dependencies": { - "@npmcli/git": "^5.0.0", - "glob": "^10.2.2", - "hosted-git-info": "^7.0.0", - "json-parse-even-better-errors": "^3.0.0", - "normalize-package-data": "^6.0.0", - "proc-log": "^4.0.0", - "semver": "^7.5.3" + "@npmcli/git": "^8.0.0", + "glob": "^13.0.0", + "hosted-git-info": "^10.1.1", + "json-parse-even-better-errors": "^6.0.0", + "proc-log": "^7.0.0", + "semver": "^7.5.3", + "spdx-expression-parse": "^4.0.0" }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/package-json.git" + "devDependencies": { + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.0", + "tap": "^16.0.1" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": "true" + "version": "5.1.0", + "publish": "true", + "updateNpm": false }, "tap": { "nyc-arg": [ diff --git a/node_modules/@npmcli/promise-spawn/lib/escape.js b/node_modules/@npmcli/promise-spawn/lib/escape.js index 9aca8bde70a6e..5fab00210f26c 100644 --- a/node_modules/@npmcli/promise-spawn/lib/escape.js +++ b/node_modules/@npmcli/promise-spawn/lib/escape.js @@ -1,6 +1,5 @@ '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) { diff --git a/node_modules/@npmcli/promise-spawn/lib/index.js b/node_modules/@npmcli/promise-spawn/lib/index.js index e147cb8f9c746..1faf62c9157df 100644 --- a/node_modules/@npmcli/promise-spawn/lib/index.js +++ b/node_modules/@npmcli/promise-spawn/lib/index.js @@ -70,7 +70,7 @@ const spawnWithShell = (cmd, args, opts, extra) => { // 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' + command = process.platform === 'win32' ? (process.env.ComSpec || 'cmd.exe') : 'sh' } const options = { ...opts, shell: false } @@ -131,9 +131,19 @@ const open = (_args, opts = {}, extra = {}) => { let platform = process.platform // process.platform === 'linux' may actually indicate WSL, if that's the case - // we want to treat things as win32 anyway so the host can open the argument + // 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 = 'win32' + platform = 'wsl' + if (!process.env.BROWSER) { + return Promise.reject( + new Error('Set the BROWSER environment variable to your desired browser.')) + } } let command = options.command @@ -146,6 +156,8 @@ const open = (_args, opts = {}, extra = {}) => { // 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 { diff --git a/node_modules/@npmcli/promise-spawn/package.json b/node_modules/@npmcli/promise-spawn/package.json index 1b633f84596d2..b227171eebd1f 100644 --- a/node_modules/@npmcli/promise-spawn/package.json +++ b/node_modules/@npmcli/promise-spawn/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/promise-spawn", - "version": "7.0.2", + "version": "10.0.0", "files": [ "bin/", "lib/" @@ -16,12 +16,13 @@ "scripts": { "test": "tap", "snap": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "check-coverage": true, @@ -31,20 +32,20 @@ ] }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.1.0", "spawk": "^1.7.1", "tap": "^16.0.1" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.0", "publish": true }, "dependencies": { - "which": "^4.0.0" + "which": "^7.0.0" } } diff --git a/node_modules/@npmcli/query/package.json b/node_modules/@npmcli/query/package.json index ad45c18c44cd6..0cb533eb819b6 100644 --- a/node_modules/@npmcli/query/package.json +++ b/node_modules/@npmcli/query/package.json @@ -1,16 +1,17 @@ { "name": "@npmcli/query", - "version": "3.1.0", + "version": "5.0.0", "description": "npm query parser and tools", "main": "lib/index.js", "scripts": { "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "posttest": "npm run lint" + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "contributors": [ { @@ -35,24 +36,24 @@ "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "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.21.3", + "version": "4.27.1", "publish": true }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.3", + "@npmcli/eslint-config": "^5.0.0", + "@npmcli/template-oss": "4.27.1", "tap": "^16.2.0" }, "dependencies": { - "postcss-selector-parser": "^6.0.10" + "postcss-selector-parser": "^7.0.0" }, "repository": { "type": "git", - "url": "https://github.com/npm/query.git" + "url": "git+https://github.com/npm/query.git" }, "tap": { "nyc-arg": [ diff --git a/node_modules/@npmcli/redact/lib/deep-map.js b/node_modules/@npmcli/redact/lib/deep-map.js index b555cf9fc4c8b..c14857c2c01b1 100644 --- a/node_modules/@npmcli/redact/lib/deep-map.js +++ b/node_modules/@npmcli/redact/lib/deep-map.js @@ -1,22 +1,15 @@ -function filterError (input) { - return { - errorType: input.name, - message: input.message, - stack: input.stack, - ...(input.code ? { code: input.code } : {}), - ...(input.statusCode ? { statusCode: input.statusCode } : {}), - } -} +const { serializeError } = require('./error') 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) + return deepMap({ err: serializeError(input) }, handler, path, seen) } if (input instanceof Error) { - return deepMap(filterError(input), handler, path, seen) + return deepMap(serializeError(input), handler, path, seen) } - if (input instanceof Buffer) { + // allows for non-node js environments, sush as workers + if (typeof Buffer !== 'undefined' && input instanceof Buffer) { return `[unable to log instanceof buffer]` } if (input instanceof Uint8Array) { diff --git a/node_modules/@npmcli/redact/lib/error.js b/node_modules/@npmcli/redact/lib/error.js new file mode 100644 index 0000000000000..e374b3902a285 --- /dev/null +++ b/node_modules/@npmcli/redact/lib/error.js @@ -0,0 +1,28 @@ +/** takes an error object and serializes it to a plan object */ +function serializeError (input) { + if (!(input instanceof Error)) { + if (typeof input === 'string') { + const error = new Error(`attempted to serialize a non-error, string String, "${input}"`) + return serializeError(error) + } + const error = new Error(`attempted to serialize a non-error, ${typeof input} ${input?.constructor?.name}`) + return serializeError(error) + } + // different error objects store status code differently + // AxiosError uses `status`, other services use `statusCode` + const statusCode = input.statusCode ?? input.status + // CAUTION: what we serialize here gets add to the size of logs + return { + errorType: input.errorType ?? input.constructor.name, + ...(input.message ? { message: input.message } : {}), + ...(input.stack ? { stack: input.stack } : {}), + // think of this as error code + ...(input.code ? { code: input.code } : {}), + // think of this as http status code + ...(statusCode ? { statusCode } : {}), + } +} + +module.exports = { + serializeError, +} diff --git a/node_modules/@npmcli/redact/lib/matchers.js b/node_modules/@npmcli/redact/lib/matchers.js index fe9b9071de8a1..854ba8e1cbda1 100644 --- a/node_modules/@npmcli/redact/lib/matchers.js +++ b/node_modules/@npmcli/redact/lib/matchers.js @@ -44,6 +44,12 @@ const DEEP_HEADER_SET_COOKIE = { replacement: '[REDACTED_HEADER_SET_COOKIE]', } +const DEEP_HEADER_COOKIE = { + type: TYPE_PATH, + predicate: ({ path }) => path.endsWith('.headers.cookie'), + replacement: '[REDACTED_HEADER_COOKIE]', +} + const REWRITE_REQUEST = { type: TYPE_PATH, predicate: ({ path }) => path.endsWith('.request'), @@ -76,6 +82,7 @@ module.exports = { URL_MATCHER, DEEP_HEADER_AUTHORIZATION, DEEP_HEADER_SET_COOKIE, + DEEP_HEADER_COOKIE, REWRITE_REQUEST, REWRITE_RESPONSE, } diff --git a/node_modules/@npmcli/redact/lib/server.js b/node_modules/@npmcli/redact/lib/server.js index 669e834da6131..555e37dcc1f54 100644 --- a/node_modules/@npmcli/redact/lib/server.js +++ b/node_modules/@npmcli/redact/lib/server.js @@ -6,6 +6,7 @@ const { DEEP_HEADER_SET_COOKIE, REWRITE_REQUEST, REWRITE_RESPONSE, + DEEP_HEADER_COOKIE, } = require('./matchers') const { @@ -14,6 +15,8 @@ const { redactMatchers, } = require('./utils') +const { serializeError } = require('./error') + const { deepMap } = require('./deep-map') const _redact = redactMatchers( @@ -22,6 +25,7 @@ const _redact = redactMatchers( JSON_WEB_TOKEN, DEEP_HEADER_AUTHORIZATION, DEEP_HEADER_SET_COOKIE, + DEEP_HEADER_COOKIE, REWRITE_REQUEST, REWRITE_RESPONSE, redactUrlMatcher( @@ -31,4 +35,25 @@ const _redact = redactMatchers( const redact = (input) => deepMap(input, (value, path) => _redact(value, { path })) -module.exports = { redact } +/** takes an error returns new error keeping some custom properties */ +function redactError (input) { + const { message, ...data } = serializeError(input) + const output = new Error(redact(message)) + return Object.assign(output, redact(data)) +} + +/** runs a function within try / catch and throws error wrapped in redactError */ +function redactThrow (func) { + if (typeof func !== 'function') { + throw new Error('redactThrow expects a function') + } + return async (...args) => { + try { + return await func(...args) + } catch (error) { + throw redactError(error) + } + } +} + +module.exports = { redact, redactError, redactThrow } diff --git a/node_modules/@npmcli/redact/package.json b/node_modules/@npmcli/redact/package.json index 831387ca54106..e781e09b16743 100644 --- a/node_modules/@npmcli/redact/package.json +++ b/node_modules/@npmcli/redact/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/redact", - "version": "2.0.1", + "version": "5.0.0", "description": "Redact sensitive npm information from output", "main": "lib/index.js", "exports": { @@ -10,12 +10,13 @@ }, "scripts": { "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "posttest": "npm run lint" + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "keywords": [], "author": "GitHub Inc.", @@ -26,11 +27,11 @@ ], "repository": { "type": "git", - "url": "https://github.com/npm/redact.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.21.3", + "version": "5.0.0", "publish": true }, "tap": { @@ -41,11 +42,11 @@ "timeout": 120 }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.2", - "@npmcli/template-oss": "4.21.3", + "@npmcli/eslint-config": "^5.0.0", + "@npmcli/template-oss": "5.0.0", "tap": "^16.3.10" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } } diff --git a/node_modules/@npmcli/run-script/lib/is-server-package.js b/node_modules/@npmcli/run-script/lib/is-server-package.js deleted file mode 100644 index c36c40d4898d5..0000000000000 --- a/node_modules/@npmcli/run-script/lib/is-server-package.js +++ /dev/null @@ -1,11 +0,0 @@ -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 - } -} diff --git a/node_modules/@npmcli/run-script/lib/make-spawn-args.js b/node_modules/@npmcli/run-script/lib/make-spawn-args.js index 8a32d7198cb2e..e9bc2f0893733 100644 --- a/node_modules/@npmcli/run-script/lib/make-spawn-args.js +++ b/node_modules/@npmcli/run-script/lib/make-spawn-args.js @@ -1,21 +1,33 @@ -/* 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') + +let npmConfigNodeGyp const makeSpawnArgs = options => { const { + args, + binPaths, + cmd, + env, event, + nodeGyp, path, scriptShell = true, - binPaths, - env, stdio, - cmd, - args, stdioString, } = options + if (nodeGyp) { + // npm already pulled this from env and passes it in to options + npmConfigNodeGyp = nodeGyp + } else if (env.npm_config_node_gyp) { + // legacy mode for standalone user + npmConfigNodeGyp = env.npm_config_node_gyp + } else { + // default + npmConfigNodeGyp = require.resolve('node-gyp/bin/node-gyp.js') + } + const spawnEnv = setPATH(path, binPaths, { // we need to at least save the PATH environment var ...process.env, @@ -23,7 +35,7 @@ const makeSpawnArgs = options => { npm_package_json: resolve(path, 'package.json'), npm_lifecycle_event: event, npm_lifecycle_script: cmd, - npm_config_node_gyp, + npm_config_node_gyp: npmConfigNodeGyp, }) const spawnOpts = { diff --git a/node_modules/@npmcli/run-script/lib/run-script-pkg.js b/node_modules/@npmcli/run-script/lib/run-script-pkg.js index 9900c96315f85..e81396cdd280f 100644 --- a/node_modules/@npmcli/run-script/lib/run-script-pkg.js +++ b/node_modules/@npmcli/run-script/lib/run-script-pkg.js @@ -3,22 +3,22 @@ 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, + args = [], binPaths = false, env = {}, - stdio = 'pipe', + event, + nodeGyp, + path, pkg, - args = [], - stdioString, + scriptShell, // 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, + stdio = 'pipe', + stdioString, } = options const { scripts = {}, gypfile } = pkg @@ -36,8 +36,6 @@ const runScriptPkg = async options => { await isNodeGypPackage(path) ) { cmd = defaultGypInstallScript - } else if (event === 'start' && await isServerPackage(path)) { - cmd = 'node server.js' } if (!cmd) { @@ -46,31 +44,26 @@ const runScriptPkg = async options => { let inputEnd = () => {} if (stdio === 'inherit') { - let banner + const { log, input } = require('proc-log') if (pkg._id) { - banner = `\n> ${pkg._id} ${event}\n` + log.notice('run', `${pkg._id} ${event}`) } else { - banner = `\n> ${event}\n` - } - banner += `> ${cmd.trim().replace(/\n/g, '\n> ')}` - if (args.length) { - banner += ` ${args.join(' ')}` + log.notice('run', event) } - banner += '\n' - const { output, input } = require('proc-log') - output.standard(banner) + log.notice('run', `${cmd.trim()} ${args?.join(' ')}`.trim()) inputEnd = input.start() } const [spawnShell, spawnArgs, spawnOpts] = makeSpawnArgs({ + args, + binPaths, + cmd, + env: { ...env, ...packageEnvs(pkg) }, event, + nodeGyp, path, scriptShell, - binPaths, - env: { ...env, ...packageEnvs(pkg) }, stdio, - cmd, - args, stdioString, }) diff --git a/node_modules/@npmcli/run-script/lib/run-script.js b/node_modules/@npmcli/run-script/lib/run-script.js index b00304c8d6e7f..625f2e452ed11 100644 --- a/node_modules/@npmcli/run-script/lib/run-script.js +++ b/node_modules/@npmcli/run-script/lib/run-script.js @@ -1,7 +1,6 @@ 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) @@ -12,4 +11,4 @@ const runScript = async options => { return runScriptPkg({ ...options, pkg }) } -module.exports = Object.assign(runScript, { isServerPackage }) +module.exports = runScript diff --git a/node_modules/@npmcli/run-script/lib/set-path.js b/node_modules/@npmcli/run-script/lib/set-path.js index c59c270d9969a..0344cc0b736f4 100644 --- a/node_modules/@npmcli/run-script/lib/set-path.js +++ b/node_modules/@npmcli/run-script/lib/set-path.js @@ -1,3 +1,4 @@ +const { log } = require('proc-log') 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 @@ -14,6 +15,13 @@ const setPATH = (projectPath, binPaths, env) => { const pathArr = [] if (binPaths) { + for (const bin of binPaths) { + if (bin.includes(delimiter)) { + const event = env.npm_lifecycle_event + const context = event ? `"${event}" script` : 'script execution' + log.warn('run-script', `Path contains delimiter ("${delimiter}"), ${context} may not behave as expected.`) + } + } pathArr.push(...binPaths) } // unshift the ./node_modules/.bin from every folder diff --git a/node_modules/@npmcli/run-script/package.json b/node_modules/@npmcli/run-script/package.json index 8a83e726fbeb2..6dd815a8046a5 100644 --- a/node_modules/@npmcli/run-script/package.json +++ b/node_modules/@npmcli/run-script/package.json @@ -1,32 +1,31 @@ { "name": "@npmcli/run-script", - "version": "8.1.0", + "version": "11.0.0", "description": "Run a lifecycle script for a package (descendant of npm-lifecycle)", "author": "GitHub Inc.", "license": "ISC", "scripts": { "test": "tap", - "eslint": "eslint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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": "^4.0.0", - "@npmcli/template-oss": "4.21.4", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.0", "spawk": "^1.8.1", "tap": "^16.0.1" }, "dependencies": { - "@npmcli/node-gyp": "^3.0.0", - "@npmcli/package-json": "^5.0.0", - "@npmcli/promise-spawn": "^7.0.0", - "node-gyp": "^10.0.0", - "proc-log": "^4.0.0", - "which": "^4.0.0" + "@npmcli/node-gyp": "^6.0.0", + "@npmcli/package-json": "^8.0.0", + "@npmcli/promise-spawn": "^10.0.0", + "node-gyp": "^13.0.0", + "proc-log": "^7.0.0" }, "files": [ "bin/", @@ -35,15 +34,16 @@ "main": "lib/run-script.js", "repository": { "type": "git", - "url": "https://github.com/npm/run-script.git" + "url": "git+https://github.com/npm/run-script.git" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.4", - "publish": "true" + "version": "5.1.0", + "publish": "true", + "updateNpm": false }, "tap": { "nyc-arg": [ diff --git a/node_modules/@pkgjs/parseargs/LICENSE b/node_modules/@pkgjs/parseargs/LICENSE deleted file mode 100644 index 261eeb9e9f8b2..0000000000000 --- a/node_modules/@pkgjs/parseargs/LICENSE +++ /dev/null @@ -1,201 +0,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 [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. diff --git a/node_modules/@pkgjs/parseargs/examples/is-default-value.js b/node_modules/@pkgjs/parseargs/examples/is-default-value.js deleted file mode 100644 index 0a67972b71d13..0000000000000 --- a/node_modules/@pkgjs/parseargs/examples/is-default-value.js +++ /dev/null @@ -1,25 +0,0 @@ -'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 diff --git a/node_modules/@pkgjs/parseargs/examples/limit-long-syntax.js b/node_modules/@pkgjs/parseargs/examples/limit-long-syntax.js deleted file mode 100644 index 943e643ee9553..0000000000000 --- a/node_modules/@pkgjs/parseargs/examples/limit-long-syntax.js +++ /dev/null @@ -1,35 +0,0 @@ -'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 diff --git a/node_modules/@pkgjs/parseargs/examples/negate.js b/node_modules/@pkgjs/parseargs/examples/negate.js deleted file mode 100644 index b6634690a4a0c..0000000000000 --- a/node_modules/@pkgjs/parseargs/examples/negate.js +++ /dev/null @@ -1,43 +0,0 @@ -'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 diff --git a/node_modules/@pkgjs/parseargs/examples/no-repeated-options.js b/node_modules/@pkgjs/parseargs/examples/no-repeated-options.js deleted file mode 100644 index 0c324688af030..0000000000000 --- a/node_modules/@pkgjs/parseargs/examples/no-repeated-options.js +++ /dev/null @@ -1,31 +0,0 @@ -'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 diff --git a/node_modules/@pkgjs/parseargs/examples/ordered-options.mjs b/node_modules/@pkgjs/parseargs/examples/ordered-options.mjs deleted file mode 100644 index 8ab7367b8bbb1..0000000000000 --- a/node_modules/@pkgjs/parseargs/examples/ordered-options.mjs +++ /dev/null @@ -1,41 +0,0 @@ -// 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 diff --git a/node_modules/@pkgjs/parseargs/examples/simple-hard-coded.js b/node_modules/@pkgjs/parseargs/examples/simple-hard-coded.js deleted file mode 100644 index eff04c2a60fa2..0000000000000 --- a/node_modules/@pkgjs/parseargs/examples/simple-hard-coded.js +++ /dev/null @@ -1,26 +0,0 @@ -'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 diff --git a/node_modules/@pkgjs/parseargs/index.js b/node_modules/@pkgjs/parseargs/index.js deleted file mode 100644 index b1004c7b72f27..0000000000000 --- a/node_modules/@pkgjs/parseargs/index.js +++ /dev/null @@ -1,396 +0,0 @@ -'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, -}; diff --git a/node_modules/@pkgjs/parseargs/internal/errors.js b/node_modules/@pkgjs/parseargs/internal/errors.js deleted file mode 100644 index e1b237b5b1639..0000000000000 --- a/node_modules/@pkgjs/parseargs/internal/errors.js +++ /dev/null @@ -1,47 +0,0 @@ -'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, - } -}; diff --git a/node_modules/@pkgjs/parseargs/internal/primordials.js b/node_modules/@pkgjs/parseargs/internal/primordials.js deleted file mode 100644 index 63e23ab117a9c..0000000000000 --- a/node_modules/@pkgjs/parseargs/internal/primordials.js +++ /dev/null @@ -1,393 +0,0 @@ -/* -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; diff --git a/node_modules/@pkgjs/parseargs/internal/util.js b/node_modules/@pkgjs/parseargs/internal/util.js deleted file mode 100644 index b9b8fe5b8d7c0..0000000000000 --- a/node_modules/@pkgjs/parseargs/internal/util.js +++ /dev/null @@ -1,14 +0,0 @@ -'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, -}; diff --git a/node_modules/@pkgjs/parseargs/internal/validators.js b/node_modules/@pkgjs/parseargs/internal/validators.js deleted file mode 100644 index b5ac4fb501eff..0000000000000 --- a/node_modules/@pkgjs/parseargs/internal/validators.js +++ /dev/null @@ -1,89 +0,0 @@ -'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, -}; diff --git a/node_modules/@pkgjs/parseargs/package.json b/node_modules/@pkgjs/parseargs/package.json deleted file mode 100644 index 0bcc05c0d4a3e..0000000000000 --- a/node_modules/@pkgjs/parseargs/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/@pkgjs/parseargs/utils.js b/node_modules/@pkgjs/parseargs/utils.js deleted file mode 100644 index d7f420a233924..0000000000000 --- a/node_modules/@pkgjs/parseargs/utils.js +++ /dev/null @@ -1,198 +0,0 @@ -'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, -}; diff --git a/node_modules/@sigstore/bundle/dist/bundle.js b/node_modules/@sigstore/bundle/dist/bundle.js deleted file mode 100644 index dbd35df2ca2bb..0000000000000 --- a/node_modules/@sigstore/bundle/dist/bundle.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isBundleWithDsseEnvelope = exports.isBundleWithMessageSignature = exports.isBundleWithPublicKey = exports.isBundleWithCertificateChain = exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = void 0; -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'; -} -exports.isBundleWithCertificateChain = isBundleWithCertificateChain; -function isBundleWithPublicKey(b) { - return b.verificationMaterial.content.$case === 'publicKey'; -} -exports.isBundleWithPublicKey = isBundleWithPublicKey; -function isBundleWithMessageSignature(b) { - return b.content.$case === 'messageSignature'; -} -exports.isBundleWithMessageSignature = isBundleWithMessageSignature; -function isBundleWithDsseEnvelope(b) { - return b.content.$case === 'dsseEnvelope'; -} -exports.isBundleWithDsseEnvelope = isBundleWithDsseEnvelope; diff --git a/node_modules/@sigstore/bundle/dist/error.js b/node_modules/@sigstore/bundle/dist/error.js deleted file mode 100644 index f84295323b812..0000000000000 --- a/node_modules/@sigstore/bundle/dist/error.js +++ /dev/null @@ -1,25 +0,0 @@ -"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; diff --git a/node_modules/@sigstore/bundle/package.json b/node_modules/@sigstore/bundle/package.json deleted file mode 100644 index dd853897226d2..0000000000000 --- a/node_modules/@sigstore/bundle/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "@sigstore/bundle", - "version": "2.3.2", - "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": "^16.14.0 || >=18.0.0" - } -} diff --git a/node_modules/@sigstore/core/dist/asn1/parse.js b/node_modules/@sigstore/core/dist/asn1/parse.js deleted file mode 100644 index 482c7239e8316..0000000000000 --- a/node_modules/@sigstore/core/dist/asn1/parse.js +++ /dev/null @@ -1,125 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.parseBitString = exports.parseBoolean = exports.parseOID = exports.parseTime = exports.parseStringASCII = exports.parseInteger = 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 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; -} -exports.parseInteger = parseInteger; -// 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'); -} -exports.parseStringASCII = parseStringASCII; -// 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`); -} -exports.parseTime = parseTime; -// 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; -} -exports.parseOID = parseOID; -// 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; -} -exports.parseBoolean = parseBoolean; -// 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; -} -exports.parseBitString = parseBitString; diff --git a/node_modules/@sigstore/core/dist/dsse.js b/node_modules/@sigstore/core/dist/dsse.js deleted file mode 100644 index a78783c919a25..0000000000000 --- a/node_modules/@sigstore/core/dist/dsse.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.preAuthEncoding = 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 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]); -} -exports.preAuthEncoding = preAuthEncoding; diff --git a/node_modules/@sigstore/core/dist/encoding.js b/node_modules/@sigstore/core/dist/encoding.js deleted file mode 100644 index b020ac4d6ecd4..0000000000000 --- a/node_modules/@sigstore/core/dist/encoding.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.base64Decode = exports.base64Encode = 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 BASE64_ENCODING = 'base64'; -const UTF8_ENCODING = 'utf-8'; -function base64Encode(str) { - return Buffer.from(str, UTF8_ENCODING).toString(BASE64_ENCODING); -} -exports.base64Encode = base64Encode; -function base64Decode(str) { - return Buffer.from(str, BASE64_ENCODING).toString(UTF8_ENCODING); -} -exports.base64Decode = base64Decode; diff --git a/node_modules/@sigstore/core/dist/index.js b/node_modules/@sigstore/core/dist/index.js deleted file mode 100644 index ac35e86a8df7d..0000000000000 --- a/node_modules/@sigstore/core/dist/index.js +++ /dev/null @@ -1,56 +0,0 @@ -"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; } }); diff --git a/node_modules/@sigstore/core/dist/json.js b/node_modules/@sigstore/core/dist/json.js deleted file mode 100644 index a50df7233c7c5..0000000000000 --- a/node_modules/@sigstore/core/dist/json.js +++ /dev/null @@ -1,61 +0,0 @@ -"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 = void 0; -// 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; -} -exports.canonicalize = canonicalize; diff --git a/node_modules/@sigstore/core/dist/oid.js b/node_modules/@sigstore/core/dist/oid.js deleted file mode 100644 index ac7a643067ad0..0000000000000 --- a/node_modules/@sigstore/core/dist/oid.js +++ /dev/null @@ -1,14 +0,0 @@ -"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', -}; diff --git a/node_modules/@sigstore/core/dist/rfc3161/timestamp.js b/node_modules/@sigstore/core/dist/rfc3161/timestamp.js deleted file mode 100644 index 3e61fc1a4e169..0000000000000 --- a/node_modules/@sigstore/core/dist/rfc3161/timestamp.js +++ /dev/null @@ -1,201 +0,0 @@ -"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; diff --git a/node_modules/@sigstore/core/dist/rfc3161/tstinfo.js b/node_modules/@sigstore/core/dist/rfc3161/tstinfo.js deleted file mode 100644 index dc8e4fb339383..0000000000000 --- a/node_modules/@sigstore/core/dist/rfc3161/tstinfo.js +++ /dev/null @@ -1,61 +0,0 @@ -"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; diff --git a/node_modules/@sigstore/core/dist/x509/sct.js b/node_modules/@sigstore/core/dist/x509/sct.js deleted file mode 100644 index 1603059c0d1ac..0000000000000 --- a/node_modules/@sigstore/core/dist/x509/sct.js +++ /dev/null @@ -1,141 +0,0 @@ -"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; diff --git a/node_modules/@sigstore/core/package.json b/node_modules/@sigstore/core/package.json deleted file mode 100644 index 621ff1715bcd1..0000000000000 --- a/node_modules/@sigstore/core/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@sigstore/core", - "version": "1.1.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": "^16.14.0 || >=18.0.0" - } -} diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.js index 0c367a8384454..9ae2847c5e4e0 100644 --- a/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.js +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.js @@ -1,88 +1,58 @@ "use strict"; -/* eslint-disable */ +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: envelope.proto 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)) : [], + payloadType: isSet(object.payloadType) ? globalThis.String(object.payloadType) : "", + signatures: globalThis.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); + if (message.payload.length !== 0) { + obj.payload = base64FromBytes(message.payload); + } + if (message.payloadType !== "") { + obj.payloadType = message.payloadType; } - else { - obj.signatures = []; + if (message.signatures?.length) { + obj.signatures = message.signatures.map((e) => exports.Signature.toJSON(e)); } 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) : "", + keyid: isSet(object.keyid) ? globalThis.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); + if (message.sig.length !== 0) { + obj.sig = base64FromBytes(message.sig); + } + if (message.keyid !== "") { + 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; - } + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); } 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("")); - } + return globalThis.Buffer.from(arr).toString("base64"); } function isSet(value) { return value !== null && value !== undefined; diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.js index 073093b8371a8..e62ac4ad8ebd6 100644 --- a/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.js +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.js @@ -1,21 +1,23 @@ "use strict"; +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: events.proto 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) : "", + id: isSet(object.id) ? globalThis.String(object.id) : "", + source: isSet(object.source) ? globalThis.String(object.source) : "", + specVersion: isSet(object.specVersion) ? globalThis.String(object.specVersion) : "", + type: isSet(object.type) ? globalThis.String(object.type) : "", attributes: isObject(object.attributes) - ? Object.entries(object.attributes).reduce((acc, [key, value]) => { + ? globalThis.Object.entries(object.attributes).reduce((acc, [key, value]) => { acc[key] = exports.CloudEvent_CloudEventAttributeValue.fromJSON(value); return acc; }, {}) @@ -23,7 +25,7 @@ exports.CloudEvent = { data: isSet(object.binaryData) ? { $case: "binaryData", binaryData: Buffer.from(bytesFromBase64(object.binaryData)) } : isSet(object.textData) - ? { $case: "textData", textData: String(object.textData) } + ? { $case: "textData", textData: globalThis.String(object.textData) } : isSet(object.protoData) ? { $case: "protoData", protoData: any_1.Any.fromJSON(object.protoData) } : undefined, @@ -31,60 +33,72 @@ exports.CloudEvent = { }, 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.id !== "") { + obj.id = message.id; + } + if (message.source !== "") { + obj.source = message.source; + } + if (message.specVersion !== "") { + obj.specVersion = message.specVersion; + } + if (message.type !== "") { + obj.type = message.type; + } 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); + const entries = globalThis.Object.entries(message.attributes); + if (entries.length > 0) { + obj.attributes = {}; + entries.forEach(([k, v]) => { + obj.attributes[k] = exports.CloudEvent_CloudEventAttributeValue.toJSON(v); + }); + } + } + if (message.data?.$case === "binaryData") { + obj.binaryData = base64FromBytes(message.data.binaryData); + } + else if (message.data?.$case === "textData") { + obj.textData = message.data.textData; + } + else if (message.data?.$case === "protoData") { + obj.protoData = any_1.Any.toJSON(message.data.protoData); + } return obj; }, }; -function createBaseCloudEvent_AttributesEntry() { - return { key: "", value: undefined }; -} exports.CloudEvent_AttributesEntry = { fromJSON(object) { return { - key: isSet(object.key) ? String(object.key) : "", + key: isSet(object.key) ? globalThis.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); + if (message.key !== "") { + obj.key = message.key; + } + if (message.value !== undefined) { + obj.value = exports.CloudEvent_CloudEventAttributeValue.toJSON(message.value); + } return obj; }, }; -function createBaseCloudEvent_CloudEventAttributeValue() { - return { attr: undefined }; -} exports.CloudEvent_CloudEventAttributeValue = { fromJSON(object) { return { attr: isSet(object.ceBoolean) - ? { $case: "ceBoolean", ceBoolean: Boolean(object.ceBoolean) } + ? { $case: "ceBoolean", ceBoolean: globalThis.Boolean(object.ceBoolean) } : isSet(object.ceInteger) - ? { $case: "ceInteger", ceInteger: Number(object.ceInteger) } + ? { $case: "ceInteger", ceInteger: globalThis.Number(object.ceInteger) } : isSet(object.ceString) - ? { $case: "ceString", ceString: String(object.ceString) } + ? { $case: "ceString", ceString: globalThis.String(object.ceString) } : isSet(object.ceBytes) ? { $case: "ceBytes", ceBytes: Buffer.from(bytesFromBase64(object.ceBytes)) } : isSet(object.ceUri) - ? { $case: "ceUri", ceUri: String(object.ceUri) } + ? { $case: "ceUri", ceUri: globalThis.String(object.ceUri) } : isSet(object.ceUriRef) - ? { $case: "ceUriRef", ceUriRef: String(object.ceUriRef) } + ? { $case: "ceUriRef", ceUriRef: globalThis.String(object.ceUriRef) } : isSet(object.ceTimestamp) ? { $case: "ceTimestamp", ceTimestamp: fromJsonTimestamp(object.ceTimestamp) } : undefined, @@ -92,86 +106,61 @@ exports.CloudEvent_CloudEventAttributeValue = { }, 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()); + if (message.attr?.$case === "ceBoolean") { + obj.ceBoolean = message.attr.ceBoolean; + } + else if (message.attr?.$case === "ceInteger") { + obj.ceInteger = Math.round(message.attr.ceInteger); + } + else if (message.attr?.$case === "ceString") { + obj.ceString = message.attr.ceString; + } + else if (message.attr?.$case === "ceBytes") { + obj.ceBytes = base64FromBytes(message.attr.ceBytes); + } + else if (message.attr?.$case === "ceUri") { + obj.ceUri = message.attr.ceUri; + } + else if (message.attr?.$case === "ceUriRef") { + obj.ceUriRef = message.attr.ceUriRef; + } + else if (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)) : [] }; + return { + events: globalThis.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 = []; + if (message.events?.length) { + obj.events = message.events.map((e) => exports.CloudEvent.toJSON(e)); } 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; - } + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); } 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("")); - } + return globalThis.Buffer.from(arr).toString("base64"); } function fromTimestamp(t) { - let millis = Number(t.seconds) * 1000; - millis += t.nanos / 1000000; - return new Date(millis); + let millis = (globalThis.Number(t.seconds) || 0) * 1_000; + millis += (t.nanos || 0) / 1_000_000; + return new globalThis.Date(millis); } function fromJsonTimestamp(o) { - if (o instanceof Date) { + if (o instanceof globalThis.Date) { return o; } else if (typeof o === "string") { - return new Date(o); + return new globalThis.Date(o); } else { return fromTimestamp(timestamp_1.Timestamp.fromJSON(o)); diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.js index da627499ad765..d267964861fb0 100644 --- a/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.js +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.js @@ -1,7 +1,14 @@ "use strict"; -/* eslint-disable */ +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: google/api/field_behavior.proto Object.defineProperty(exports, "__esModule", { value: true }); -exports.fieldBehaviorToJSON = exports.fieldBehaviorFromJSON = exports.FieldBehavior = void 0; +exports.FieldBehavior = void 0; +exports.fieldBehaviorFromJSON = fieldBehaviorFromJSON; +exports.fieldBehaviorToJSON = fieldBehaviorToJSON; +/* eslint-disable */ /** * 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). @@ -48,11 +55,33 @@ var FieldBehavior; /** * 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 + * 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 || (exports.FieldBehavior = {})); + /** + * NON_EMPTY_DEFAULT - Denotes that this field returns a non-empty default value if not set. + * This indicates that if the user provides the empty value in a request, + * a non-empty value will be returned. The user will not be aware of what + * non-empty value to expect. + */ + FieldBehavior[FieldBehavior["NON_EMPTY_DEFAULT"] = 7] = "NON_EMPTY_DEFAULT"; + /** + * IDENTIFIER - Denotes that the field in a resource (a message annotated with + * google.api.resource) is used in the resource name to uniquely identify the + * resource. For AIP-compliant APIs, this should only be applied to the + * `name` field on the resource. + * + * This behavior should not be applied to references to other resources within + * the message. + * + * The identifier field of resources often have different field behavior + * depending on the request it is embedded in (e.g. for Create methods name + * is optional and unused, while for Update methods it is required). Instead + * of method-specific annotations, only `IDENTIFIER` is required. + */ + FieldBehavior[FieldBehavior["IDENTIFIER"] = 8] = "IDENTIFIER"; +})(FieldBehavior || (exports.FieldBehavior = FieldBehavior = {})); function fieldBehaviorFromJSON(object) { switch (object) { case 0: @@ -76,11 +105,16 @@ function fieldBehaviorFromJSON(object) { case 6: case "UNORDERED_LIST": return FieldBehavior.UNORDERED_LIST; + case 7: + case "NON_EMPTY_DEFAULT": + return FieldBehavior.NON_EMPTY_DEFAULT; + case 8: + case "IDENTIFIER": + return FieldBehavior.IDENTIFIER; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldBehavior"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldBehavior"); } } -exports.fieldBehaviorFromJSON = fieldBehaviorFromJSON; function fieldBehaviorToJSON(object) { switch (object) { case FieldBehavior.FIELD_BEHAVIOR_UNSPECIFIED: @@ -97,23 +131,11 @@ function fieldBehaviorToJSON(object) { return "IMMUTABLE"; case FieldBehavior.UNORDERED_LIST: return "UNORDERED_LIST"; + case FieldBehavior.NON_EMPTY_DEFAULT: + return "NON_EMPTY_DEFAULT"; + case FieldBehavior.IDENTIFIER: + return "IDENTIFIER"; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldBehavior"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldBehavior"); } } -exports.fieldBehaviorToJSON = fieldBehaviorToJSON; -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"; -})(); diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.js index 6b3f3c97a6647..42943d3fbbcad 100644 --- a/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.js +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.js @@ -1,64 +1,34 @@ "use strict"; -/* eslint-disable */ +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: google/protobuf/any.proto 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) : "", + typeUrl: isSet(object.typeUrl) ? globalThis.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))); + if (message.typeUrl !== "") { + obj.typeUrl = message.typeUrl; + } + if (message.value.length !== 0) { + obj.value = base64FromBytes(message.value); + } 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; - } + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); } 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("")); - } + return globalThis.Buffer.from(arr).toString("base64"); } function isSet(value) { return value !== null && value !== undefined; diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.js index d429aac846043..2a70277fe98e7 100644 --- a/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.js +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.js @@ -1,7 +1,242 @@ "use strict"; -/* eslint-disable */ +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: google/protobuf/descriptor.proto 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_IdempotencyLevelToJSON = exports.methodOptions_IdempotencyLevelFromJSON = exports.MethodOptions_IdempotencyLevel = exports.fieldOptions_JSTypeToJSON = exports.fieldOptions_JSTypeFromJSON = exports.FieldOptions_JSType = exports.fieldOptions_CTypeToJSON = exports.fieldOptions_CTypeFromJSON = exports.FieldOptions_CType = exports.fileOptions_OptimizeModeToJSON = exports.fileOptions_OptimizeModeFromJSON = exports.FileOptions_OptimizeMode = exports.fieldDescriptorProto_LabelToJSON = exports.fieldDescriptorProto_LabelFromJSON = exports.FieldDescriptorProto_Label = exports.fieldDescriptorProto_TypeToJSON = exports.fieldDescriptorProto_TypeFromJSON = exports.FieldDescriptorProto_Type = void 0; +exports.FeatureSetDefaults_FeatureSetEditionDefault = exports.FeatureSetDefaults = exports.FeatureSet_VisibilityFeature = exports.FeatureSet = exports.UninterpretedOption_NamePart = exports.UninterpretedOption = exports.MethodOptions = exports.ServiceOptions = exports.EnumValueOptions = exports.EnumOptions = exports.OneofOptions = exports.FieldOptions_FeatureSupport = exports.FieldOptions_EditionDefault = exports.FieldOptions = exports.MessageOptions = exports.FileOptions = exports.MethodDescriptorProto = exports.ServiceDescriptorProto = exports.EnumValueDescriptorProto = exports.EnumDescriptorProto_EnumReservedRange = exports.EnumDescriptorProto = exports.OneofDescriptorProto = exports.FieldDescriptorProto = exports.ExtensionRangeOptions_Declaration = exports.ExtensionRangeOptions = exports.DescriptorProto_ReservedRange = exports.DescriptorProto_ExtensionRange = exports.DescriptorProto = exports.FileDescriptorProto = exports.FileDescriptorSet = exports.GeneratedCodeInfo_Annotation_Semantic = exports.FeatureSet_VisibilityFeature_DefaultSymbolVisibility = exports.FeatureSet_EnforceNamingStyle = exports.FeatureSet_JsonFormat = exports.FeatureSet_MessageEncoding = exports.FeatureSet_Utf8Validation = exports.FeatureSet_RepeatedFieldEncoding = exports.FeatureSet_EnumType = exports.FeatureSet_FieldPresence = exports.MethodOptions_IdempotencyLevel = exports.FieldOptions_OptionTargetType = exports.FieldOptions_OptionRetention = exports.FieldOptions_JSType = exports.FieldOptions_CType = exports.FileOptions_OptimizeMode = exports.FieldDescriptorProto_Label = exports.FieldDescriptorProto_Type = exports.ExtensionRangeOptions_VerificationState = exports.SymbolVisibility = exports.Edition = void 0; +exports.GeneratedCodeInfo_Annotation = exports.GeneratedCodeInfo = exports.SourceCodeInfo_Location = exports.SourceCodeInfo = void 0; +exports.editionFromJSON = editionFromJSON; +exports.editionToJSON = editionToJSON; +exports.symbolVisibilityFromJSON = symbolVisibilityFromJSON; +exports.symbolVisibilityToJSON = symbolVisibilityToJSON; +exports.extensionRangeOptions_VerificationStateFromJSON = extensionRangeOptions_VerificationStateFromJSON; +exports.extensionRangeOptions_VerificationStateToJSON = extensionRangeOptions_VerificationStateToJSON; +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.fieldOptions_OptionRetentionFromJSON = fieldOptions_OptionRetentionFromJSON; +exports.fieldOptions_OptionRetentionToJSON = fieldOptions_OptionRetentionToJSON; +exports.fieldOptions_OptionTargetTypeFromJSON = fieldOptions_OptionTargetTypeFromJSON; +exports.fieldOptions_OptionTargetTypeToJSON = fieldOptions_OptionTargetTypeToJSON; +exports.methodOptions_IdempotencyLevelFromJSON = methodOptions_IdempotencyLevelFromJSON; +exports.methodOptions_IdempotencyLevelToJSON = methodOptions_IdempotencyLevelToJSON; +exports.featureSet_FieldPresenceFromJSON = featureSet_FieldPresenceFromJSON; +exports.featureSet_FieldPresenceToJSON = featureSet_FieldPresenceToJSON; +exports.featureSet_EnumTypeFromJSON = featureSet_EnumTypeFromJSON; +exports.featureSet_EnumTypeToJSON = featureSet_EnumTypeToJSON; +exports.featureSet_RepeatedFieldEncodingFromJSON = featureSet_RepeatedFieldEncodingFromJSON; +exports.featureSet_RepeatedFieldEncodingToJSON = featureSet_RepeatedFieldEncodingToJSON; +exports.featureSet_Utf8ValidationFromJSON = featureSet_Utf8ValidationFromJSON; +exports.featureSet_Utf8ValidationToJSON = featureSet_Utf8ValidationToJSON; +exports.featureSet_MessageEncodingFromJSON = featureSet_MessageEncodingFromJSON; +exports.featureSet_MessageEncodingToJSON = featureSet_MessageEncodingToJSON; +exports.featureSet_JsonFormatFromJSON = featureSet_JsonFormatFromJSON; +exports.featureSet_JsonFormatToJSON = featureSet_JsonFormatToJSON; +exports.featureSet_EnforceNamingStyleFromJSON = featureSet_EnforceNamingStyleFromJSON; +exports.featureSet_EnforceNamingStyleToJSON = featureSet_EnforceNamingStyleToJSON; +exports.featureSet_VisibilityFeature_DefaultSymbolVisibilityFromJSON = featureSet_VisibilityFeature_DefaultSymbolVisibilityFromJSON; +exports.featureSet_VisibilityFeature_DefaultSymbolVisibilityToJSON = featureSet_VisibilityFeature_DefaultSymbolVisibilityToJSON; +exports.generatedCodeInfo_Annotation_SemanticFromJSON = generatedCodeInfo_Annotation_SemanticFromJSON; +exports.generatedCodeInfo_Annotation_SemanticToJSON = generatedCodeInfo_Annotation_SemanticToJSON; +/* eslint-disable */ +/** The full set of known editions. */ +var Edition; +(function (Edition) { + /** EDITION_UNKNOWN - A placeholder for an unknown edition value. */ + Edition[Edition["EDITION_UNKNOWN"] = 0] = "EDITION_UNKNOWN"; + /** + * EDITION_LEGACY - A placeholder edition for specifying default behaviors *before* a feature + * was first introduced. This is effectively an "infinite past". + */ + Edition[Edition["EDITION_LEGACY"] = 900] = "EDITION_LEGACY"; + /** + * EDITION_PROTO2 - Legacy syntax "editions". These pre-date editions, but behave much like + * distinct editions. These can't be used to specify the edition of proto + * files, but feature definitions must supply proto2/proto3 defaults for + * backwards compatibility. + */ + Edition[Edition["EDITION_PROTO2"] = 998] = "EDITION_PROTO2"; + Edition[Edition["EDITION_PROTO3"] = 999] = "EDITION_PROTO3"; + /** + * EDITION_2023 - Editions that have been released. The specific values are arbitrary and + * should not be depended on, but they will always be time-ordered for easy + * comparison. + */ + Edition[Edition["EDITION_2023"] = 1000] = "EDITION_2023"; + Edition[Edition["EDITION_2024"] = 1001] = "EDITION_2024"; + /** EDITION_UNSTABLE - A placeholder edition for developing and testing unscheduled features. */ + Edition[Edition["EDITION_UNSTABLE"] = 9999] = "EDITION_UNSTABLE"; + /** + * EDITION_1_TEST_ONLY - Placeholder editions for testing feature resolution. These should not be + * used or relied on outside of tests. + */ + Edition[Edition["EDITION_1_TEST_ONLY"] = 1] = "EDITION_1_TEST_ONLY"; + Edition[Edition["EDITION_2_TEST_ONLY"] = 2] = "EDITION_2_TEST_ONLY"; + Edition[Edition["EDITION_99997_TEST_ONLY"] = 99997] = "EDITION_99997_TEST_ONLY"; + Edition[Edition["EDITION_99998_TEST_ONLY"] = 99998] = "EDITION_99998_TEST_ONLY"; + Edition[Edition["EDITION_99999_TEST_ONLY"] = 99999] = "EDITION_99999_TEST_ONLY"; + /** + * EDITION_MAX - Placeholder for specifying unbounded edition support. This should only + * ever be used by plugins that can expect to never require any changes to + * support a new edition. + */ + Edition[Edition["EDITION_MAX"] = 2147483647] = "EDITION_MAX"; +})(Edition || (exports.Edition = Edition = {})); +function editionFromJSON(object) { + switch (object) { + case 0: + case "EDITION_UNKNOWN": + return Edition.EDITION_UNKNOWN; + case 900: + case "EDITION_LEGACY": + return Edition.EDITION_LEGACY; + case 998: + case "EDITION_PROTO2": + return Edition.EDITION_PROTO2; + case 999: + case "EDITION_PROTO3": + return Edition.EDITION_PROTO3; + case 1000: + case "EDITION_2023": + return Edition.EDITION_2023; + case 1001: + case "EDITION_2024": + return Edition.EDITION_2024; + case 9999: + case "EDITION_UNSTABLE": + return Edition.EDITION_UNSTABLE; + case 1: + case "EDITION_1_TEST_ONLY": + return Edition.EDITION_1_TEST_ONLY; + case 2: + case "EDITION_2_TEST_ONLY": + return Edition.EDITION_2_TEST_ONLY; + case 99997: + case "EDITION_99997_TEST_ONLY": + return Edition.EDITION_99997_TEST_ONLY; + case 99998: + case "EDITION_99998_TEST_ONLY": + return Edition.EDITION_99998_TEST_ONLY; + case 99999: + case "EDITION_99999_TEST_ONLY": + return Edition.EDITION_99999_TEST_ONLY; + case 2147483647: + case "EDITION_MAX": + return Edition.EDITION_MAX; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum Edition"); + } +} +function editionToJSON(object) { + switch (object) { + case Edition.EDITION_UNKNOWN: + return "EDITION_UNKNOWN"; + case Edition.EDITION_LEGACY: + return "EDITION_LEGACY"; + case Edition.EDITION_PROTO2: + return "EDITION_PROTO2"; + case Edition.EDITION_PROTO3: + return "EDITION_PROTO3"; + case Edition.EDITION_2023: + return "EDITION_2023"; + case Edition.EDITION_2024: + return "EDITION_2024"; + case Edition.EDITION_UNSTABLE: + return "EDITION_UNSTABLE"; + case Edition.EDITION_1_TEST_ONLY: + return "EDITION_1_TEST_ONLY"; + case Edition.EDITION_2_TEST_ONLY: + return "EDITION_2_TEST_ONLY"; + case Edition.EDITION_99997_TEST_ONLY: + return "EDITION_99997_TEST_ONLY"; + case Edition.EDITION_99998_TEST_ONLY: + return "EDITION_99998_TEST_ONLY"; + case Edition.EDITION_99999_TEST_ONLY: + return "EDITION_99999_TEST_ONLY"; + case Edition.EDITION_MAX: + return "EDITION_MAX"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum Edition"); + } +} +/** + * Describes the 'visibility' of a symbol with respect to the proto import + * system. Symbols can only be imported when the visibility rules do not prevent + * it (ex: local symbols cannot be imported). Visibility modifiers can only set + * on `message` and `enum` as they are the only types available to be referenced + * from other files. + */ +var SymbolVisibility; +(function (SymbolVisibility) { + SymbolVisibility[SymbolVisibility["VISIBILITY_UNSET"] = 0] = "VISIBILITY_UNSET"; + SymbolVisibility[SymbolVisibility["VISIBILITY_LOCAL"] = 1] = "VISIBILITY_LOCAL"; + SymbolVisibility[SymbolVisibility["VISIBILITY_EXPORT"] = 2] = "VISIBILITY_EXPORT"; +})(SymbolVisibility || (exports.SymbolVisibility = SymbolVisibility = {})); +function symbolVisibilityFromJSON(object) { + switch (object) { + case 0: + case "VISIBILITY_UNSET": + return SymbolVisibility.VISIBILITY_UNSET; + case 1: + case "VISIBILITY_LOCAL": + return SymbolVisibility.VISIBILITY_LOCAL; + case 2: + case "VISIBILITY_EXPORT": + return SymbolVisibility.VISIBILITY_EXPORT; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum SymbolVisibility"); + } +} +function symbolVisibilityToJSON(object) { + switch (object) { + case SymbolVisibility.VISIBILITY_UNSET: + return "VISIBILITY_UNSET"; + case SymbolVisibility.VISIBILITY_LOCAL: + return "VISIBILITY_LOCAL"; + case SymbolVisibility.VISIBILITY_EXPORT: + return "VISIBILITY_EXPORT"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum SymbolVisibility"); + } +} +/** The verification state of the extension range. */ +var ExtensionRangeOptions_VerificationState; +(function (ExtensionRangeOptions_VerificationState) { + /** DECLARATION - All the extensions of the range must be declared. */ + ExtensionRangeOptions_VerificationState[ExtensionRangeOptions_VerificationState["DECLARATION"] = 0] = "DECLARATION"; + ExtensionRangeOptions_VerificationState[ExtensionRangeOptions_VerificationState["UNVERIFIED"] = 1] = "UNVERIFIED"; +})(ExtensionRangeOptions_VerificationState || (exports.ExtensionRangeOptions_VerificationState = ExtensionRangeOptions_VerificationState = {})); +function extensionRangeOptions_VerificationStateFromJSON(object) { + switch (object) { + case 0: + case "DECLARATION": + return ExtensionRangeOptions_VerificationState.DECLARATION; + case 1: + case "UNVERIFIED": + return ExtensionRangeOptions_VerificationState.UNVERIFIED; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum ExtensionRangeOptions_VerificationState"); + } +} +function extensionRangeOptions_VerificationStateToJSON(object) { + switch (object) { + case ExtensionRangeOptions_VerificationState.DECLARATION: + return "DECLARATION"; + case ExtensionRangeOptions_VerificationState.UNVERIFIED: + return "UNVERIFIED"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum ExtensionRangeOptions_VerificationState"); + } +} var FieldDescriptorProto_Type; (function (FieldDescriptorProto_Type) { /** @@ -27,9 +262,10 @@ var FieldDescriptorProto_Type; 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 + * Group type is deprecated and not supported after google.protobuf. However, Proto3 * implementations should still be able to parse the group wire format and - * treat group fields as unknown fields. + * treat group fields as unknown fields. In Editions, the group wire format + * can be enabled via the `message_encoding` feature. */ FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_GROUP"] = 10] = "TYPE_GROUP"; /** TYPE_MESSAGE - Length-delimited aggregate. */ @@ -44,7 +280,7 @@ var FieldDescriptorProto_Type; 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 || (exports.FieldDescriptorProto_Type = {})); +})(FieldDescriptorProto_Type || (exports.FieldDescriptorProto_Type = FieldDescriptorProto_Type = {})); function fieldDescriptorProto_TypeFromJSON(object) { switch (object) { case 1: @@ -102,10 +338,9 @@ function fieldDescriptorProto_TypeFromJSON(object) { case "TYPE_SINT64": return FieldDescriptorProto_Type.TYPE_SINT64; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Type"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Type"); } } -exports.fieldDescriptorProto_TypeFromJSON = fieldDescriptorProto_TypeFromJSON; function fieldDescriptorProto_TypeToJSON(object) { switch (object) { case FieldDescriptorProto_Type.TYPE_DOUBLE: @@ -145,46 +380,48 @@ function fieldDescriptorProto_TypeToJSON(object) { case FieldDescriptorProto_Type.TYPE_SINT64: return "TYPE_SINT64"; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Type"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Type"); } } -exports.fieldDescriptorProto_TypeToJSON = fieldDescriptorProto_TypeToJSON; 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 || (exports.FieldDescriptorProto_Label = {})); + /** + * LABEL_REQUIRED - The required label is only allowed in google.protobuf. In proto3 and Editions + * it's explicitly prohibited. In Editions, the `field_presence` feature + * can be used to get this behavior. + */ + FieldDescriptorProto_Label[FieldDescriptorProto_Label["LABEL_REQUIRED"] = 2] = "LABEL_REQUIRED"; +})(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; + case 2: + case "LABEL_REQUIRED": + return FieldDescriptorProto_Label.LABEL_REQUIRED; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Label"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Label"); } } -exports.fieldDescriptorProto_LabelFromJSON = fieldDescriptorProto_LabelFromJSON; 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"; + case FieldDescriptorProto_Label.LABEL_REQUIRED: + return "LABEL_REQUIRED"; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Label"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Label"); } } -exports.fieldDescriptorProto_LabelToJSON = fieldDescriptorProto_LabelToJSON; /** Generated classes can be optimized for speed or code size. */ var FileOptions_OptimizeMode; (function (FileOptions_OptimizeMode) { @@ -194,7 +431,7 @@ var FileOptions_OptimizeMode; 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 || (exports.FileOptions_OptimizeMode = {})); +})(FileOptions_OptimizeMode || (exports.FileOptions_OptimizeMode = FileOptions_OptimizeMode = {})); function fileOptions_OptimizeModeFromJSON(object) { switch (object) { case 1: @@ -207,10 +444,9 @@ function fileOptions_OptimizeModeFromJSON(object) { case "LITE_RUNTIME": return FileOptions_OptimizeMode.LITE_RUNTIME; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FileOptions_OptimizeMode"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FileOptions_OptimizeMode"); } } -exports.fileOptions_OptimizeModeFromJSON = fileOptions_OptimizeModeFromJSON; function fileOptions_OptimizeModeToJSON(object) { switch (object) { case FileOptions_OptimizeMode.SPEED: @@ -220,17 +456,24 @@ function fileOptions_OptimizeModeToJSON(object) { case FileOptions_OptimizeMode.LITE_RUNTIME: return "LITE_RUNTIME"; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FileOptions_OptimizeMode"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FileOptions_OptimizeMode"); } } -exports.fileOptions_OptimizeModeToJSON = fileOptions_OptimizeModeToJSON; var FieldOptions_CType; (function (FieldOptions_CType) { /** STRING - Default mode. */ FieldOptions_CType[FieldOptions_CType["STRING"] = 0] = "STRING"; + /** + * CORD - The option [ctype=CORD] may be applied to a non-repeated field of type + * "bytes". It indicates that in C++, the data should be stored in a Cord + * instead of a string. For very large strings, this may reduce memory + * fragmentation. It may also allow better performance when parsing from a + * Cord, or when parsing with aliasing enabled, as the parsed Cord may then + * alias the original buffer. + */ FieldOptions_CType[FieldOptions_CType["CORD"] = 1] = "CORD"; FieldOptions_CType[FieldOptions_CType["STRING_PIECE"] = 2] = "STRING_PIECE"; -})(FieldOptions_CType = exports.FieldOptions_CType || (exports.FieldOptions_CType = {})); +})(FieldOptions_CType || (exports.FieldOptions_CType = FieldOptions_CType = {})); function fieldOptions_CTypeFromJSON(object) { switch (object) { case 0: @@ -243,10 +486,9 @@ function fieldOptions_CTypeFromJSON(object) { case "STRING_PIECE": return FieldOptions_CType.STRING_PIECE; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_CType"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_CType"); } } -exports.fieldOptions_CTypeFromJSON = fieldOptions_CTypeFromJSON; function fieldOptions_CTypeToJSON(object) { switch (object) { case FieldOptions_CType.STRING: @@ -256,10 +498,9 @@ function fieldOptions_CTypeToJSON(object) { case FieldOptions_CType.STRING_PIECE: return "STRING_PIECE"; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_CType"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_CType"); } } -exports.fieldOptions_CTypeToJSON = fieldOptions_CTypeToJSON; var FieldOptions_JSType; (function (FieldOptions_JSType) { /** JS_NORMAL - Use the default type. */ @@ -268,7 +509,7 @@ var FieldOptions_JSType; 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 || (exports.FieldOptions_JSType = {})); +})(FieldOptions_JSType || (exports.FieldOptions_JSType = FieldOptions_JSType = {})); function fieldOptions_JSTypeFromJSON(object) { switch (object) { case 0: @@ -281,10 +522,9 @@ function fieldOptions_JSTypeFromJSON(object) { case "JS_NUMBER": return FieldOptions_JSType.JS_NUMBER; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_JSType"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_JSType"); } } -exports.fieldOptions_JSTypeFromJSON = fieldOptions_JSTypeFromJSON; function fieldOptions_JSTypeToJSON(object) { switch (object) { case FieldOptions_JSType.JS_NORMAL: @@ -294,10 +534,123 @@ function fieldOptions_JSTypeToJSON(object) { case FieldOptions_JSType.JS_NUMBER: return "JS_NUMBER"; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_JSType"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_JSType"); + } +} +/** If set to RETENTION_SOURCE, the option will be omitted from the binary. */ +var FieldOptions_OptionRetention; +(function (FieldOptions_OptionRetention) { + FieldOptions_OptionRetention[FieldOptions_OptionRetention["RETENTION_UNKNOWN"] = 0] = "RETENTION_UNKNOWN"; + FieldOptions_OptionRetention[FieldOptions_OptionRetention["RETENTION_RUNTIME"] = 1] = "RETENTION_RUNTIME"; + FieldOptions_OptionRetention[FieldOptions_OptionRetention["RETENTION_SOURCE"] = 2] = "RETENTION_SOURCE"; +})(FieldOptions_OptionRetention || (exports.FieldOptions_OptionRetention = FieldOptions_OptionRetention = {})); +function fieldOptions_OptionRetentionFromJSON(object) { + switch (object) { + case 0: + case "RETENTION_UNKNOWN": + return FieldOptions_OptionRetention.RETENTION_UNKNOWN; + case 1: + case "RETENTION_RUNTIME": + return FieldOptions_OptionRetention.RETENTION_RUNTIME; + case 2: + case "RETENTION_SOURCE": + return FieldOptions_OptionRetention.RETENTION_SOURCE; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_OptionRetention"); + } +} +function fieldOptions_OptionRetentionToJSON(object) { + switch (object) { + case FieldOptions_OptionRetention.RETENTION_UNKNOWN: + return "RETENTION_UNKNOWN"; + case FieldOptions_OptionRetention.RETENTION_RUNTIME: + return "RETENTION_RUNTIME"; + case FieldOptions_OptionRetention.RETENTION_SOURCE: + return "RETENTION_SOURCE"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_OptionRetention"); + } +} +/** + * This indicates the types of entities that the field may apply to when used + * as an option. If it is unset, then the field may be freely used as an + * option on any kind of entity. + */ +var FieldOptions_OptionTargetType; +(function (FieldOptions_OptionTargetType) { + FieldOptions_OptionTargetType[FieldOptions_OptionTargetType["TARGET_TYPE_UNKNOWN"] = 0] = "TARGET_TYPE_UNKNOWN"; + FieldOptions_OptionTargetType[FieldOptions_OptionTargetType["TARGET_TYPE_FILE"] = 1] = "TARGET_TYPE_FILE"; + FieldOptions_OptionTargetType[FieldOptions_OptionTargetType["TARGET_TYPE_EXTENSION_RANGE"] = 2] = "TARGET_TYPE_EXTENSION_RANGE"; + FieldOptions_OptionTargetType[FieldOptions_OptionTargetType["TARGET_TYPE_MESSAGE"] = 3] = "TARGET_TYPE_MESSAGE"; + FieldOptions_OptionTargetType[FieldOptions_OptionTargetType["TARGET_TYPE_FIELD"] = 4] = "TARGET_TYPE_FIELD"; + FieldOptions_OptionTargetType[FieldOptions_OptionTargetType["TARGET_TYPE_ONEOF"] = 5] = "TARGET_TYPE_ONEOF"; + FieldOptions_OptionTargetType[FieldOptions_OptionTargetType["TARGET_TYPE_ENUM"] = 6] = "TARGET_TYPE_ENUM"; + FieldOptions_OptionTargetType[FieldOptions_OptionTargetType["TARGET_TYPE_ENUM_ENTRY"] = 7] = "TARGET_TYPE_ENUM_ENTRY"; + FieldOptions_OptionTargetType[FieldOptions_OptionTargetType["TARGET_TYPE_SERVICE"] = 8] = "TARGET_TYPE_SERVICE"; + FieldOptions_OptionTargetType[FieldOptions_OptionTargetType["TARGET_TYPE_METHOD"] = 9] = "TARGET_TYPE_METHOD"; +})(FieldOptions_OptionTargetType || (exports.FieldOptions_OptionTargetType = FieldOptions_OptionTargetType = {})); +function fieldOptions_OptionTargetTypeFromJSON(object) { + switch (object) { + case 0: + case "TARGET_TYPE_UNKNOWN": + return FieldOptions_OptionTargetType.TARGET_TYPE_UNKNOWN; + case 1: + case "TARGET_TYPE_FILE": + return FieldOptions_OptionTargetType.TARGET_TYPE_FILE; + case 2: + case "TARGET_TYPE_EXTENSION_RANGE": + return FieldOptions_OptionTargetType.TARGET_TYPE_EXTENSION_RANGE; + case 3: + case "TARGET_TYPE_MESSAGE": + return FieldOptions_OptionTargetType.TARGET_TYPE_MESSAGE; + case 4: + case "TARGET_TYPE_FIELD": + return FieldOptions_OptionTargetType.TARGET_TYPE_FIELD; + case 5: + case "TARGET_TYPE_ONEOF": + return FieldOptions_OptionTargetType.TARGET_TYPE_ONEOF; + case 6: + case "TARGET_TYPE_ENUM": + return FieldOptions_OptionTargetType.TARGET_TYPE_ENUM; + case 7: + case "TARGET_TYPE_ENUM_ENTRY": + return FieldOptions_OptionTargetType.TARGET_TYPE_ENUM_ENTRY; + case 8: + case "TARGET_TYPE_SERVICE": + return FieldOptions_OptionTargetType.TARGET_TYPE_SERVICE; + case 9: + case "TARGET_TYPE_METHOD": + return FieldOptions_OptionTargetType.TARGET_TYPE_METHOD; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_OptionTargetType"); + } +} +function fieldOptions_OptionTargetTypeToJSON(object) { + switch (object) { + case FieldOptions_OptionTargetType.TARGET_TYPE_UNKNOWN: + return "TARGET_TYPE_UNKNOWN"; + case FieldOptions_OptionTargetType.TARGET_TYPE_FILE: + return "TARGET_TYPE_FILE"; + case FieldOptions_OptionTargetType.TARGET_TYPE_EXTENSION_RANGE: + return "TARGET_TYPE_EXTENSION_RANGE"; + case FieldOptions_OptionTargetType.TARGET_TYPE_MESSAGE: + return "TARGET_TYPE_MESSAGE"; + case FieldOptions_OptionTargetType.TARGET_TYPE_FIELD: + return "TARGET_TYPE_FIELD"; + case FieldOptions_OptionTargetType.TARGET_TYPE_ONEOF: + return "TARGET_TYPE_ONEOF"; + case FieldOptions_OptionTargetType.TARGET_TYPE_ENUM: + return "TARGET_TYPE_ENUM"; + case FieldOptions_OptionTargetType.TARGET_TYPE_ENUM_ENTRY: + return "TARGET_TYPE_ENUM_ENTRY"; + case FieldOptions_OptionTargetType.TARGET_TYPE_SERVICE: + return "TARGET_TYPE_SERVICE"; + case FieldOptions_OptionTargetType.TARGET_TYPE_METHOD: + return "TARGET_TYPE_METHOD"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_OptionTargetType"); } } -exports.fieldOptions_JSTypeToJSON = fieldOptions_JSTypeToJSON; /** * 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 @@ -310,7 +663,7 @@ var MethodOptions_IdempotencyLevel; 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 || (exports.MethodOptions_IdempotencyLevel = {})); +})(MethodOptions_IdempotencyLevel || (exports.MethodOptions_IdempotencyLevel = MethodOptions_IdempotencyLevel = {})); function methodOptions_IdempotencyLevelFromJSON(object) { switch (object) { case 0: @@ -323,10 +676,9 @@ function methodOptions_IdempotencyLevelFromJSON(object) { case "IDEMPOTENT": return MethodOptions_IdempotencyLevel.IDEMPOTENT; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum MethodOptions_IdempotencyLevel"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum MethodOptions_IdempotencyLevel"); } } -exports.methodOptions_IdempotencyLevelFromJSON = methodOptions_IdempotencyLevelFromJSON; function methodOptions_IdempotencyLevelToJSON(object) { switch (object) { case MethodOptions_IdempotencyLevel.IDEMPOTENCY_UNKNOWN: @@ -336,972 +688,1491 @@ function methodOptions_IdempotencyLevelToJSON(object) { case MethodOptions_IdempotencyLevel.IDEMPOTENT: return "IDEMPOTENT"; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum MethodOptions_IdempotencyLevel"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum MethodOptions_IdempotencyLevel"); } } -exports.methodOptions_IdempotencyLevelToJSON = methodOptions_IdempotencyLevelToJSON; -function createBaseFileDescriptorSet() { - return { file: [] }; +var FeatureSet_FieldPresence; +(function (FeatureSet_FieldPresence) { + FeatureSet_FieldPresence[FeatureSet_FieldPresence["FIELD_PRESENCE_UNKNOWN"] = 0] = "FIELD_PRESENCE_UNKNOWN"; + FeatureSet_FieldPresence[FeatureSet_FieldPresence["EXPLICIT"] = 1] = "EXPLICIT"; + FeatureSet_FieldPresence[FeatureSet_FieldPresence["IMPLICIT"] = 2] = "IMPLICIT"; + FeatureSet_FieldPresence[FeatureSet_FieldPresence["LEGACY_REQUIRED"] = 3] = "LEGACY_REQUIRED"; +})(FeatureSet_FieldPresence || (exports.FeatureSet_FieldPresence = FeatureSet_FieldPresence = {})); +function featureSet_FieldPresenceFromJSON(object) { + switch (object) { + case 0: + case "FIELD_PRESENCE_UNKNOWN": + return FeatureSet_FieldPresence.FIELD_PRESENCE_UNKNOWN; + case 1: + case "EXPLICIT": + return FeatureSet_FieldPresence.EXPLICIT; + case 2: + case "IMPLICIT": + return FeatureSet_FieldPresence.IMPLICIT; + case 3: + case "LEGACY_REQUIRED": + return FeatureSet_FieldPresence.LEGACY_REQUIRED; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_FieldPresence"); + } +} +function featureSet_FieldPresenceToJSON(object) { + switch (object) { + case FeatureSet_FieldPresence.FIELD_PRESENCE_UNKNOWN: + return "FIELD_PRESENCE_UNKNOWN"; + case FeatureSet_FieldPresence.EXPLICIT: + return "EXPLICIT"; + case FeatureSet_FieldPresence.IMPLICIT: + return "IMPLICIT"; + case FeatureSet_FieldPresence.LEGACY_REQUIRED: + return "LEGACY_REQUIRED"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_FieldPresence"); + } +} +var FeatureSet_EnumType; +(function (FeatureSet_EnumType) { + FeatureSet_EnumType[FeatureSet_EnumType["ENUM_TYPE_UNKNOWN"] = 0] = "ENUM_TYPE_UNKNOWN"; + FeatureSet_EnumType[FeatureSet_EnumType["OPEN"] = 1] = "OPEN"; + FeatureSet_EnumType[FeatureSet_EnumType["CLOSED"] = 2] = "CLOSED"; +})(FeatureSet_EnumType || (exports.FeatureSet_EnumType = FeatureSet_EnumType = {})); +function featureSet_EnumTypeFromJSON(object) { + switch (object) { + case 0: + case "ENUM_TYPE_UNKNOWN": + return FeatureSet_EnumType.ENUM_TYPE_UNKNOWN; + case 1: + case "OPEN": + return FeatureSet_EnumType.OPEN; + case 2: + case "CLOSED": + return FeatureSet_EnumType.CLOSED; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_EnumType"); + } +} +function featureSet_EnumTypeToJSON(object) { + switch (object) { + case FeatureSet_EnumType.ENUM_TYPE_UNKNOWN: + return "ENUM_TYPE_UNKNOWN"; + case FeatureSet_EnumType.OPEN: + return "OPEN"; + case FeatureSet_EnumType.CLOSED: + return "CLOSED"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_EnumType"); + } +} +var FeatureSet_RepeatedFieldEncoding; +(function (FeatureSet_RepeatedFieldEncoding) { + FeatureSet_RepeatedFieldEncoding[FeatureSet_RepeatedFieldEncoding["REPEATED_FIELD_ENCODING_UNKNOWN"] = 0] = "REPEATED_FIELD_ENCODING_UNKNOWN"; + FeatureSet_RepeatedFieldEncoding[FeatureSet_RepeatedFieldEncoding["PACKED"] = 1] = "PACKED"; + FeatureSet_RepeatedFieldEncoding[FeatureSet_RepeatedFieldEncoding["EXPANDED"] = 2] = "EXPANDED"; +})(FeatureSet_RepeatedFieldEncoding || (exports.FeatureSet_RepeatedFieldEncoding = FeatureSet_RepeatedFieldEncoding = {})); +function featureSet_RepeatedFieldEncodingFromJSON(object) { + switch (object) { + case 0: + case "REPEATED_FIELD_ENCODING_UNKNOWN": + return FeatureSet_RepeatedFieldEncoding.REPEATED_FIELD_ENCODING_UNKNOWN; + case 1: + case "PACKED": + return FeatureSet_RepeatedFieldEncoding.PACKED; + case 2: + case "EXPANDED": + return FeatureSet_RepeatedFieldEncoding.EXPANDED; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_RepeatedFieldEncoding"); + } +} +function featureSet_RepeatedFieldEncodingToJSON(object) { + switch (object) { + case FeatureSet_RepeatedFieldEncoding.REPEATED_FIELD_ENCODING_UNKNOWN: + return "REPEATED_FIELD_ENCODING_UNKNOWN"; + case FeatureSet_RepeatedFieldEncoding.PACKED: + return "PACKED"; + case FeatureSet_RepeatedFieldEncoding.EXPANDED: + return "EXPANDED"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_RepeatedFieldEncoding"); + } +} +var FeatureSet_Utf8Validation; +(function (FeatureSet_Utf8Validation) { + FeatureSet_Utf8Validation[FeatureSet_Utf8Validation["UTF8_VALIDATION_UNKNOWN"] = 0] = "UTF8_VALIDATION_UNKNOWN"; + FeatureSet_Utf8Validation[FeatureSet_Utf8Validation["VERIFY"] = 2] = "VERIFY"; + FeatureSet_Utf8Validation[FeatureSet_Utf8Validation["NONE"] = 3] = "NONE"; +})(FeatureSet_Utf8Validation || (exports.FeatureSet_Utf8Validation = FeatureSet_Utf8Validation = {})); +function featureSet_Utf8ValidationFromJSON(object) { + switch (object) { + case 0: + case "UTF8_VALIDATION_UNKNOWN": + return FeatureSet_Utf8Validation.UTF8_VALIDATION_UNKNOWN; + case 2: + case "VERIFY": + return FeatureSet_Utf8Validation.VERIFY; + case 3: + case "NONE": + return FeatureSet_Utf8Validation.NONE; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_Utf8Validation"); + } +} +function featureSet_Utf8ValidationToJSON(object) { + switch (object) { + case FeatureSet_Utf8Validation.UTF8_VALIDATION_UNKNOWN: + return "UTF8_VALIDATION_UNKNOWN"; + case FeatureSet_Utf8Validation.VERIFY: + return "VERIFY"; + case FeatureSet_Utf8Validation.NONE: + return "NONE"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_Utf8Validation"); + } +} +var FeatureSet_MessageEncoding; +(function (FeatureSet_MessageEncoding) { + FeatureSet_MessageEncoding[FeatureSet_MessageEncoding["MESSAGE_ENCODING_UNKNOWN"] = 0] = "MESSAGE_ENCODING_UNKNOWN"; + FeatureSet_MessageEncoding[FeatureSet_MessageEncoding["LENGTH_PREFIXED"] = 1] = "LENGTH_PREFIXED"; + FeatureSet_MessageEncoding[FeatureSet_MessageEncoding["DELIMITED"] = 2] = "DELIMITED"; +})(FeatureSet_MessageEncoding || (exports.FeatureSet_MessageEncoding = FeatureSet_MessageEncoding = {})); +function featureSet_MessageEncodingFromJSON(object) { + switch (object) { + case 0: + case "MESSAGE_ENCODING_UNKNOWN": + return FeatureSet_MessageEncoding.MESSAGE_ENCODING_UNKNOWN; + case 1: + case "LENGTH_PREFIXED": + return FeatureSet_MessageEncoding.LENGTH_PREFIXED; + case 2: + case "DELIMITED": + return FeatureSet_MessageEncoding.DELIMITED; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_MessageEncoding"); + } +} +function featureSet_MessageEncodingToJSON(object) { + switch (object) { + case FeatureSet_MessageEncoding.MESSAGE_ENCODING_UNKNOWN: + return "MESSAGE_ENCODING_UNKNOWN"; + case FeatureSet_MessageEncoding.LENGTH_PREFIXED: + return "LENGTH_PREFIXED"; + case FeatureSet_MessageEncoding.DELIMITED: + return "DELIMITED"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_MessageEncoding"); + } +} +var FeatureSet_JsonFormat; +(function (FeatureSet_JsonFormat) { + FeatureSet_JsonFormat[FeatureSet_JsonFormat["JSON_FORMAT_UNKNOWN"] = 0] = "JSON_FORMAT_UNKNOWN"; + FeatureSet_JsonFormat[FeatureSet_JsonFormat["ALLOW"] = 1] = "ALLOW"; + FeatureSet_JsonFormat[FeatureSet_JsonFormat["LEGACY_BEST_EFFORT"] = 2] = "LEGACY_BEST_EFFORT"; +})(FeatureSet_JsonFormat || (exports.FeatureSet_JsonFormat = FeatureSet_JsonFormat = {})); +function featureSet_JsonFormatFromJSON(object) { + switch (object) { + case 0: + case "JSON_FORMAT_UNKNOWN": + return FeatureSet_JsonFormat.JSON_FORMAT_UNKNOWN; + case 1: + case "ALLOW": + return FeatureSet_JsonFormat.ALLOW; + case 2: + case "LEGACY_BEST_EFFORT": + return FeatureSet_JsonFormat.LEGACY_BEST_EFFORT; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_JsonFormat"); + } +} +function featureSet_JsonFormatToJSON(object) { + switch (object) { + case FeatureSet_JsonFormat.JSON_FORMAT_UNKNOWN: + return "JSON_FORMAT_UNKNOWN"; + case FeatureSet_JsonFormat.ALLOW: + return "ALLOW"; + case FeatureSet_JsonFormat.LEGACY_BEST_EFFORT: + return "LEGACY_BEST_EFFORT"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_JsonFormat"); + } +} +var FeatureSet_EnforceNamingStyle; +(function (FeatureSet_EnforceNamingStyle) { + FeatureSet_EnforceNamingStyle[FeatureSet_EnforceNamingStyle["ENFORCE_NAMING_STYLE_UNKNOWN"] = 0] = "ENFORCE_NAMING_STYLE_UNKNOWN"; + FeatureSet_EnforceNamingStyle[FeatureSet_EnforceNamingStyle["STYLE2024"] = 1] = "STYLE2024"; + FeatureSet_EnforceNamingStyle[FeatureSet_EnforceNamingStyle["STYLE_LEGACY"] = 2] = "STYLE_LEGACY"; +})(FeatureSet_EnforceNamingStyle || (exports.FeatureSet_EnforceNamingStyle = FeatureSet_EnforceNamingStyle = {})); +function featureSet_EnforceNamingStyleFromJSON(object) { + switch (object) { + case 0: + case "ENFORCE_NAMING_STYLE_UNKNOWN": + return FeatureSet_EnforceNamingStyle.ENFORCE_NAMING_STYLE_UNKNOWN; + case 1: + case "STYLE2024": + return FeatureSet_EnforceNamingStyle.STYLE2024; + case 2: + case "STYLE_LEGACY": + return FeatureSet_EnforceNamingStyle.STYLE_LEGACY; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_EnforceNamingStyle"); + } +} +function featureSet_EnforceNamingStyleToJSON(object) { + switch (object) { + case FeatureSet_EnforceNamingStyle.ENFORCE_NAMING_STYLE_UNKNOWN: + return "ENFORCE_NAMING_STYLE_UNKNOWN"; + case FeatureSet_EnforceNamingStyle.STYLE2024: + return "STYLE2024"; + case FeatureSet_EnforceNamingStyle.STYLE_LEGACY: + return "STYLE_LEGACY"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_EnforceNamingStyle"); + } +} +var FeatureSet_VisibilityFeature_DefaultSymbolVisibility; +(function (FeatureSet_VisibilityFeature_DefaultSymbolVisibility) { + FeatureSet_VisibilityFeature_DefaultSymbolVisibility[FeatureSet_VisibilityFeature_DefaultSymbolVisibility["DEFAULT_SYMBOL_VISIBILITY_UNKNOWN"] = 0] = "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN"; + /** EXPORT_ALL - Default pre-EDITION_2024, all UNSET visibility are export. */ + FeatureSet_VisibilityFeature_DefaultSymbolVisibility[FeatureSet_VisibilityFeature_DefaultSymbolVisibility["EXPORT_ALL"] = 1] = "EXPORT_ALL"; + /** EXPORT_TOP_LEVEL - All top-level symbols default to export, nested default to local. */ + FeatureSet_VisibilityFeature_DefaultSymbolVisibility[FeatureSet_VisibilityFeature_DefaultSymbolVisibility["EXPORT_TOP_LEVEL"] = 2] = "EXPORT_TOP_LEVEL"; + /** LOCAL_ALL - All symbols default to local. */ + FeatureSet_VisibilityFeature_DefaultSymbolVisibility[FeatureSet_VisibilityFeature_DefaultSymbolVisibility["LOCAL_ALL"] = 3] = "LOCAL_ALL"; + /** + * STRICT - All symbols local by default. Nested types cannot be exported. + * With special case caveat for message { enum {} reserved 1 to max; } + * This is the recommended setting for new protos. + */ + FeatureSet_VisibilityFeature_DefaultSymbolVisibility[FeatureSet_VisibilityFeature_DefaultSymbolVisibility["STRICT"] = 4] = "STRICT"; +})(FeatureSet_VisibilityFeature_DefaultSymbolVisibility || (exports.FeatureSet_VisibilityFeature_DefaultSymbolVisibility = FeatureSet_VisibilityFeature_DefaultSymbolVisibility = {})); +function featureSet_VisibilityFeature_DefaultSymbolVisibilityFromJSON(object) { + switch (object) { + case 0: + case "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": + return FeatureSet_VisibilityFeature_DefaultSymbolVisibility.DEFAULT_SYMBOL_VISIBILITY_UNKNOWN; + case 1: + case "EXPORT_ALL": + return FeatureSet_VisibilityFeature_DefaultSymbolVisibility.EXPORT_ALL; + case 2: + case "EXPORT_TOP_LEVEL": + return FeatureSet_VisibilityFeature_DefaultSymbolVisibility.EXPORT_TOP_LEVEL; + case 3: + case "LOCAL_ALL": + return FeatureSet_VisibilityFeature_DefaultSymbolVisibility.LOCAL_ALL; + case 4: + case "STRICT": + return FeatureSet_VisibilityFeature_DefaultSymbolVisibility.STRICT; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_VisibilityFeature_DefaultSymbolVisibility"); + } +} +function featureSet_VisibilityFeature_DefaultSymbolVisibilityToJSON(object) { + switch (object) { + case FeatureSet_VisibilityFeature_DefaultSymbolVisibility.DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: + return "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN"; + case FeatureSet_VisibilityFeature_DefaultSymbolVisibility.EXPORT_ALL: + return "EXPORT_ALL"; + case FeatureSet_VisibilityFeature_DefaultSymbolVisibility.EXPORT_TOP_LEVEL: + return "EXPORT_TOP_LEVEL"; + case FeatureSet_VisibilityFeature_DefaultSymbolVisibility.LOCAL_ALL: + return "LOCAL_ALL"; + case FeatureSet_VisibilityFeature_DefaultSymbolVisibility.STRICT: + return "STRICT"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FeatureSet_VisibilityFeature_DefaultSymbolVisibility"); + } +} +/** + * Represents the identified object's effect on the element in the original + * .proto file. + */ +var GeneratedCodeInfo_Annotation_Semantic; +(function (GeneratedCodeInfo_Annotation_Semantic) { + /** NONE - There is no effect or the effect is indescribable. */ + GeneratedCodeInfo_Annotation_Semantic[GeneratedCodeInfo_Annotation_Semantic["NONE"] = 0] = "NONE"; + /** SET - The element is set or otherwise mutated. */ + GeneratedCodeInfo_Annotation_Semantic[GeneratedCodeInfo_Annotation_Semantic["SET"] = 1] = "SET"; + /** ALIAS - An alias to the element is returned. */ + GeneratedCodeInfo_Annotation_Semantic[GeneratedCodeInfo_Annotation_Semantic["ALIAS"] = 2] = "ALIAS"; +})(GeneratedCodeInfo_Annotation_Semantic || (exports.GeneratedCodeInfo_Annotation_Semantic = GeneratedCodeInfo_Annotation_Semantic = {})); +function generatedCodeInfo_Annotation_SemanticFromJSON(object) { + switch (object) { + case 0: + case "NONE": + return GeneratedCodeInfo_Annotation_Semantic.NONE; + case 1: + case "SET": + return GeneratedCodeInfo_Annotation_Semantic.SET; + case 2: + case "ALIAS": + return GeneratedCodeInfo_Annotation_Semantic.ALIAS; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum GeneratedCodeInfo_Annotation_Semantic"); + } +} +function generatedCodeInfo_Annotation_SemanticToJSON(object) { + switch (object) { + case GeneratedCodeInfo_Annotation_Semantic.NONE: + return "NONE"; + case GeneratedCodeInfo_Annotation_Semantic.SET: + return "SET"; + case GeneratedCodeInfo_Annotation_Semantic.ALIAS: + return "ALIAS"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum GeneratedCodeInfo_Annotation_Semantic"); + } } exports.FileDescriptorSet = { fromJSON(object) { - return { file: Array.isArray(object?.file) ? object.file.map((e) => exports.FileDescriptorProto.fromJSON(e)) : [] }; + return { + file: globalThis.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 = []; + if (message.file?.length) { + obj.file = message.file.map((e) => exports.FileDescriptorProto.toJSON(e)); } 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)) + name: isSet(object.name) ? globalThis.String(object.name) : "", + package: isSet(object.package) ? globalThis.String(object.package) : "", + dependency: globalThis.Array.isArray(object?.dependency) + ? object.dependency.map((e) => globalThis.String(e)) + : [], + publicDependency: globalThis.Array.isArray(object?.publicDependency) + ? object.publicDependency.map((e) => globalThis.Number(e)) : [], - weakDependency: Array.isArray(object?.weakDependency) ? object.weakDependency.map((e) => Number(e)) : [], - messageType: Array.isArray(object?.messageType) + weakDependency: globalThis.Array.isArray(object?.weakDependency) + ? object.weakDependency.map((e) => globalThis.Number(e)) + : [], + optionDependency: globalThis.Array.isArray(object?.optionDependency) + ? object.optionDependency.map((e) => globalThis.String(e)) + : [], + messageType: globalThis.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) + enumType: globalThis.Array.isArray(object?.enumType) + ? object.enumType.map((e) => exports.EnumDescriptorProto.fromJSON(e)) + : [], + service: globalThis.Array.isArray(object?.service) + ? object.service.map((e) => exports.ServiceDescriptorProto.fromJSON(e)) + : [], + extension: globalThis.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) : "", + syntax: isSet(object.syntax) ? globalThis.String(object.syntax) : "", + edition: isSet(object.edition) ? editionFromJSON(object.edition) : 0, }; }, 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); + if (message.name !== undefined && message.name !== "") { + obj.name = message.name; } - else { - obj.dependency = []; + if (message.package !== undefined && message.package !== "") { + obj.package = message.package; } - if (message.publicDependency) { - obj.publicDependency = message.publicDependency.map((e) => Math.round(e)); + if (message.dependency?.length) { + obj.dependency = message.dependency; } - else { - obj.publicDependency = []; + if (message.publicDependency?.length) { + obj.publicDependency = message.publicDependency.map((e) => Math.round(e)); } - if (message.weakDependency) { + if (message.weakDependency?.length) { obj.weakDependency = message.weakDependency.map((e) => Math.round(e)); } - else { - obj.weakDependency = []; + if (message.optionDependency?.length) { + obj.optionDependency = message.optionDependency; } - if (message.messageType) { - obj.messageType = message.messageType.map((e) => e ? exports.DescriptorProto.toJSON(e) : undefined); + if (message.messageType?.length) { + obj.messageType = message.messageType.map((e) => exports.DescriptorProto.toJSON(e)); } - else { - obj.messageType = []; + if (message.enumType?.length) { + obj.enumType = message.enumType.map((e) => exports.EnumDescriptorProto.toJSON(e)); } - if (message.enumType) { - obj.enumType = message.enumType.map((e) => e ? exports.EnumDescriptorProto.toJSON(e) : undefined); + if (message.service?.length) { + obj.service = message.service.map((e) => exports.ServiceDescriptorProto.toJSON(e)); } - else { - obj.enumType = []; + if (message.extension?.length) { + obj.extension = message.extension.map((e) => exports.FieldDescriptorProto.toJSON(e)); } - if (message.service) { - obj.service = message.service.map((e) => e ? exports.ServiceDescriptorProto.toJSON(e) : undefined); + if (message.options !== undefined) { + obj.options = exports.FileOptions.toJSON(message.options); } - else { - obj.service = []; + if (message.sourceCodeInfo !== undefined) { + obj.sourceCodeInfo = exports.SourceCodeInfo.toJSON(message.sourceCodeInfo); } - if (message.extension) { - obj.extension = message.extension.map((e) => e ? exports.FieldDescriptorProto.toJSON(e) : undefined); + if (message.syntax !== undefined && message.syntax !== "") { + obj.syntax = message.syntax; } - else { - obj.extension = []; + if (message.edition !== undefined && message.edition !== 0) { + obj.edition = editionToJSON(message.edition); } - 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) + name: isSet(object.name) ? globalThis.String(object.name) : "", + field: globalThis.Array.isArray(object?.field) + ? object.field.map((e) => exports.FieldDescriptorProto.fromJSON(e)) + : [], + extension: globalThis.Array.isArray(object?.extension) ? object.extension.map((e) => exports.FieldDescriptorProto.fromJSON(e)) : [], - nestedType: Array.isArray(object?.nestedType) + nestedType: globalThis.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) + enumType: globalThis.Array.isArray(object?.enumType) + ? object.enumType.map((e) => exports.EnumDescriptorProto.fromJSON(e)) + : [], + extensionRange: globalThis.Array.isArray(object?.extensionRange) ? object.extensionRange.map((e) => exports.DescriptorProto_ExtensionRange.fromJSON(e)) : [], - oneofDecl: Array.isArray(object?.oneofDecl) + oneofDecl: globalThis.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) + reservedRange: globalThis.Array.isArray(object?.reservedRange) ? object.reservedRange.map((e) => exports.DescriptorProto_ReservedRange.fromJSON(e)) : [], - reservedName: Array.isArray(object?.reservedName) ? object.reservedName.map((e) => String(e)) : [], + reservedName: globalThis.Array.isArray(object?.reservedName) + ? object.reservedName.map((e) => globalThis.String(e)) + : [], + visibility: isSet(object.visibility) ? symbolVisibilityFromJSON(object.visibility) : 0, }; }, 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); + if (message.name !== undefined && message.name !== "") { + obj.name = message.name; } - else { - obj.field = []; + if (message.field?.length) { + obj.field = message.field.map((e) => exports.FieldDescriptorProto.toJSON(e)); } - if (message.extension) { - obj.extension = message.extension.map((e) => e ? exports.FieldDescriptorProto.toJSON(e) : undefined); + if (message.extension?.length) { + obj.extension = message.extension.map((e) => exports.FieldDescriptorProto.toJSON(e)); } - else { - obj.extension = []; + if (message.nestedType?.length) { + obj.nestedType = message.nestedType.map((e) => exports.DescriptorProto.toJSON(e)); } - if (message.nestedType) { - obj.nestedType = message.nestedType.map((e) => e ? exports.DescriptorProto.toJSON(e) : undefined); + if (message.enumType?.length) { + obj.enumType = message.enumType.map((e) => exports.EnumDescriptorProto.toJSON(e)); } - else { - obj.nestedType = []; + if (message.extensionRange?.length) { + obj.extensionRange = message.extensionRange.map((e) => exports.DescriptorProto_ExtensionRange.toJSON(e)); } - if (message.enumType) { - obj.enumType = message.enumType.map((e) => e ? exports.EnumDescriptorProto.toJSON(e) : undefined); + if (message.oneofDecl?.length) { + obj.oneofDecl = message.oneofDecl.map((e) => exports.OneofDescriptorProto.toJSON(e)); } - else { - obj.enumType = []; + if (message.options !== undefined) { + obj.options = exports.MessageOptions.toJSON(message.options); } - if (message.extensionRange) { - obj.extensionRange = message.extensionRange.map((e) => e ? exports.DescriptorProto_ExtensionRange.toJSON(e) : undefined); + if (message.reservedRange?.length) { + obj.reservedRange = message.reservedRange.map((e) => exports.DescriptorProto_ReservedRange.toJSON(e)); } - else { - obj.extensionRange = []; + if (message.reservedName?.length) { + obj.reservedName = message.reservedName; } - 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 = []; + if (message.visibility !== undefined && message.visibility !== 0) { + obj.visibility = symbolVisibilityToJSON(message.visibility); } 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, + start: isSet(object.start) ? globalThis.Number(object.start) : 0, + end: isSet(object.end) ? globalThis.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); + if (message.start !== undefined && message.start !== 0) { + obj.start = Math.round(message.start); + } + if (message.end !== undefined && message.end !== 0) { + obj.end = Math.round(message.end); + } + if (message.options !== undefined) { + obj.options = exports.ExtensionRangeOptions.toJSON(message.options); + } 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 }; + return { + start: isSet(object.start) ? globalThis.Number(object.start) : 0, + end: isSet(object.end) ? globalThis.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)); + if (message.start !== undefined && message.start !== 0) { + obj.start = Math.round(message.start); + } + if (message.end !== undefined && message.end !== 0) { + obj.end = Math.round(message.end); + } return obj; }, }; -function createBaseExtensionRangeOptions() { - return { uninterpretedOption: [] }; -} exports.ExtensionRangeOptions = { fromJSON(object) { return { - uninterpretedOption: Array.isArray(object?.uninterpretedOption) + uninterpretedOption: globalThis.Array.isArray(object?.uninterpretedOption) ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) : [], + declaration: globalThis.Array.isArray(object?.declaration) + ? object.declaration.map((e) => exports.ExtensionRangeOptions_Declaration.fromJSON(e)) + : [], + features: isSet(object.features) ? exports.FeatureSet.fromJSON(object.features) : undefined, + verification: isSet(object.verification) + ? extensionRangeOptions_VerificationStateFromJSON(object.verification) + : 1, }; }, toJSON(message) { const obj = {}; - if (message.uninterpretedOption) { - obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); + if (message.uninterpretedOption?.length) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => exports.UninterpretedOption.toJSON(e)); + } + if (message.declaration?.length) { + obj.declaration = message.declaration.map((e) => exports.ExtensionRangeOptions_Declaration.toJSON(e)); } - else { - obj.uninterpretedOption = []; + if (message.features !== undefined) { + obj.features = exports.FeatureSet.toJSON(message.features); + } + if (message.verification !== undefined && message.verification !== 1) { + obj.verification = extensionRangeOptions_VerificationStateToJSON(message.verification); + } + return obj; + }, +}; +exports.ExtensionRangeOptions_Declaration = { + fromJSON(object) { + return { + number: isSet(object.number) ? globalThis.Number(object.number) : 0, + fullName: isSet(object.fullName) ? globalThis.String(object.fullName) : "", + type: isSet(object.type) ? globalThis.String(object.type) : "", + reserved: isSet(object.reserved) ? globalThis.Boolean(object.reserved) : false, + repeated: isSet(object.repeated) ? globalThis.Boolean(object.repeated) : false, + }; + }, + toJSON(message) { + const obj = {}; + if (message.number !== undefined && message.number !== 0) { + obj.number = Math.round(message.number); + } + if (message.fullName !== undefined && message.fullName !== "") { + obj.fullName = message.fullName; + } + if (message.type !== undefined && message.type !== "") { + obj.type = message.type; + } + if (message.reserved !== undefined && message.reserved !== false) { + obj.reserved = message.reserved; + } + if (message.repeated !== undefined && message.repeated !== false) { + obj.repeated = message.repeated; } 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, + name: isSet(object.name) ? globalThis.String(object.name) : "", + number: isSet(object.number) ? globalThis.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) : "", + typeName: isSet(object.typeName) ? globalThis.String(object.typeName) : "", + extendee: isSet(object.extendee) ? globalThis.String(object.extendee) : "", + defaultValue: isSet(object.defaultValue) ? globalThis.String(object.defaultValue) : "", + oneofIndex: isSet(object.oneofIndex) ? globalThis.Number(object.oneofIndex) : 0, + jsonName: isSet(object.jsonName) ? globalThis.String(object.jsonName) : "", options: isSet(object.options) ? exports.FieldOptions.fromJSON(object.options) : undefined, - proto3Optional: isSet(object.proto3Optional) ? Boolean(object.proto3Optional) : false, + proto3Optional: isSet(object.proto3Optional) ? globalThis.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); + if (message.name !== undefined && message.name !== "") { + obj.name = message.name; + } + if (message.number !== undefined && message.number !== 0) { + obj.number = Math.round(message.number); + } + if (message.label !== undefined && message.label !== 1) { + obj.label = fieldDescriptorProto_LabelToJSON(message.label); + } + if (message.type !== undefined && message.type !== 1) { + obj.type = fieldDescriptorProto_TypeToJSON(message.type); + } + if (message.typeName !== undefined && message.typeName !== "") { + obj.typeName = message.typeName; + } + if (message.extendee !== undefined && message.extendee !== "") { + obj.extendee = message.extendee; + } + if (message.defaultValue !== undefined && message.defaultValue !== "") { + obj.defaultValue = message.defaultValue; + } + if (message.oneofIndex !== undefined && message.oneofIndex !== 0) { + obj.oneofIndex = Math.round(message.oneofIndex); + } + if (message.jsonName !== undefined && message.jsonName !== "") { + obj.jsonName = message.jsonName; + } + if (message.options !== undefined) { + obj.options = exports.FieldOptions.toJSON(message.options); + } + if (message.proto3Optional !== undefined && message.proto3Optional !== false) { + obj.proto3Optional = message.proto3Optional; + } return obj; }, }; -function createBaseOneofDescriptorProto() { - return { name: "", options: undefined }; -} exports.OneofDescriptorProto = { fromJSON(object) { return { - name: isSet(object.name) ? String(object.name) : "", + name: isSet(object.name) ? globalThis.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); + if (message.name !== undefined && message.name !== "") { + obj.name = message.name; + } + if (message.options !== undefined) { + obj.options = exports.OneofOptions.toJSON(message.options); + } 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)) : [], + name: isSet(object.name) ? globalThis.String(object.name) : "", + value: globalThis.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) + reservedRange: globalThis.Array.isArray(object?.reservedRange) ? object.reservedRange.map((e) => exports.EnumDescriptorProto_EnumReservedRange.fromJSON(e)) : [], - reservedName: Array.isArray(object?.reservedName) - ? object.reservedName.map((e) => String(e)) + reservedName: globalThis.Array.isArray(object?.reservedName) + ? object.reservedName.map((e) => globalThis.String(e)) : [], + visibility: isSet(object.visibility) ? symbolVisibilityFromJSON(object.visibility) : 0, }; }, 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); + if (message.name !== undefined && message.name !== "") { + obj.name = message.name; } - else { - obj.value = []; + if (message.value?.length) { + obj.value = message.value.map((e) => exports.EnumValueDescriptorProto.toJSON(e)); } - 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); + if (message.options !== undefined) { + obj.options = exports.EnumOptions.toJSON(message.options); } - else { - obj.reservedRange = []; + if (message.reservedRange?.length) { + obj.reservedRange = message.reservedRange.map((e) => exports.EnumDescriptorProto_EnumReservedRange.toJSON(e)); } - if (message.reservedName) { - obj.reservedName = message.reservedName.map((e) => e); + if (message.reservedName?.length) { + obj.reservedName = message.reservedName; } - else { - obj.reservedName = []; + if (message.visibility !== undefined && message.visibility !== 0) { + obj.visibility = symbolVisibilityToJSON(message.visibility); } 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 }; + return { + start: isSet(object.start) ? globalThis.Number(object.start) : 0, + end: isSet(object.end) ? globalThis.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)); + if (message.start !== undefined && message.start !== 0) { + obj.start = Math.round(message.start); + } + if (message.end !== undefined && message.end !== 0) { + 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, + name: isSet(object.name) ? globalThis.String(object.name) : "", + number: isSet(object.number) ? globalThis.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); + if (message.name !== undefined && message.name !== "") { + obj.name = message.name; + } + if (message.number !== undefined && message.number !== 0) { + obj.number = Math.round(message.number); + } + if (message.options !== undefined) { + obj.options = exports.EnumValueOptions.toJSON(message.options); + } 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)) : [], + name: isSet(object.name) ? globalThis.String(object.name) : "", + method: globalThis.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); + if (message.name !== undefined && message.name !== "") { + obj.name = message.name; + } + if (message.method?.length) { + obj.method = message.method.map((e) => exports.MethodDescriptorProto.toJSON(e)); } - else { - obj.method = []; + if (message.options !== undefined) { + obj.options = exports.ServiceOptions.toJSON(message.options); } - 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) : "", + name: isSet(object.name) ? globalThis.String(object.name) : "", + inputType: isSet(object.inputType) ? globalThis.String(object.inputType) : "", + outputType: isSet(object.outputType) ? globalThis.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, + clientStreaming: isSet(object.clientStreaming) ? globalThis.Boolean(object.clientStreaming) : false, + serverStreaming: isSet(object.serverStreaming) ? globalThis.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); + if (message.name !== undefined && message.name !== "") { + obj.name = message.name; + } + if (message.inputType !== undefined && message.inputType !== "") { + obj.inputType = message.inputType; + } + if (message.outputType !== undefined && message.outputType !== "") { + obj.outputType = message.outputType; + } + if (message.options !== undefined) { + obj.options = exports.MethodOptions.toJSON(message.options); + } + if (message.clientStreaming !== undefined && message.clientStreaming !== false) { + obj.clientStreaming = message.clientStreaming; + } + if (message.serverStreaming !== undefined && message.serverStreaming !== false) { + 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, + javaPackage: isSet(object.javaPackage) ? globalThis.String(object.javaPackage) : "", + javaOuterClassname: isSet(object.javaOuterClassname) ? globalThis.String(object.javaOuterClassname) : "", + javaMultipleFiles: isSet(object.javaMultipleFiles) ? globalThis.Boolean(object.javaMultipleFiles) : false, javaGenerateEqualsAndHash: isSet(object.javaGenerateEqualsAndHash) - ? Boolean(object.javaGenerateEqualsAndHash) + ? globalThis.Boolean(object.javaGenerateEqualsAndHash) : false, - javaStringCheckUtf8: isSet(object.javaStringCheckUtf8) ? Boolean(object.javaStringCheckUtf8) : false, + javaStringCheckUtf8: isSet(object.javaStringCheckUtf8) ? globalThis.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) + goPackage: isSet(object.goPackage) ? globalThis.String(object.goPackage) : "", + ccGenericServices: isSet(object.ccGenericServices) ? globalThis.Boolean(object.ccGenericServices) : false, + javaGenericServices: isSet(object.javaGenericServices) ? globalThis.Boolean(object.javaGenericServices) : false, + pyGenericServices: isSet(object.pyGenericServices) ? globalThis.Boolean(object.pyGenericServices) : false, + deprecated: isSet(object.deprecated) ? globalThis.Boolean(object.deprecated) : false, + ccEnableArenas: isSet(object.ccEnableArenas) ? globalThis.Boolean(object.ccEnableArenas) : true, + objcClassPrefix: isSet(object.objcClassPrefix) ? globalThis.String(object.objcClassPrefix) : "", + csharpNamespace: isSet(object.csharpNamespace) ? globalThis.String(object.csharpNamespace) : "", + swiftPrefix: isSet(object.swiftPrefix) ? globalThis.String(object.swiftPrefix) : "", + phpClassPrefix: isSet(object.phpClassPrefix) ? globalThis.String(object.phpClassPrefix) : "", + phpNamespace: isSet(object.phpNamespace) ? globalThis.String(object.phpNamespace) : "", + phpMetadataNamespace: isSet(object.phpMetadataNamespace) ? globalThis.String(object.phpMetadataNamespace) : "", + rubyPackage: isSet(object.rubyPackage) ? globalThis.String(object.rubyPackage) : "", + features: isSet(object.features) ? exports.FeatureSet.fromJSON(object.features) : undefined, + uninterpretedOption: globalThis.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 = []; + if (message.javaPackage !== undefined && message.javaPackage !== "") { + obj.javaPackage = message.javaPackage; + } + if (message.javaOuterClassname !== undefined && message.javaOuterClassname !== "") { + obj.javaOuterClassname = message.javaOuterClassname; + } + if (message.javaMultipleFiles !== undefined && message.javaMultipleFiles !== false) { + obj.javaMultipleFiles = message.javaMultipleFiles; + } + if (message.javaGenerateEqualsAndHash !== undefined && message.javaGenerateEqualsAndHash !== false) { + obj.javaGenerateEqualsAndHash = message.javaGenerateEqualsAndHash; + } + if (message.javaStringCheckUtf8 !== undefined && message.javaStringCheckUtf8 !== false) { + obj.javaStringCheckUtf8 = message.javaStringCheckUtf8; + } + if (message.optimizeFor !== undefined && message.optimizeFor !== 1) { + obj.optimizeFor = fileOptions_OptimizeModeToJSON(message.optimizeFor); + } + if (message.goPackage !== undefined && message.goPackage !== "") { + obj.goPackage = message.goPackage; + } + if (message.ccGenericServices !== undefined && message.ccGenericServices !== false) { + obj.ccGenericServices = message.ccGenericServices; + } + if (message.javaGenericServices !== undefined && message.javaGenericServices !== false) { + obj.javaGenericServices = message.javaGenericServices; + } + if (message.pyGenericServices !== undefined && message.pyGenericServices !== false) { + obj.pyGenericServices = message.pyGenericServices; + } + if (message.deprecated !== undefined && message.deprecated !== false) { + obj.deprecated = message.deprecated; + } + if (message.ccEnableArenas !== undefined && message.ccEnableArenas !== true) { + obj.ccEnableArenas = message.ccEnableArenas; + } + if (message.objcClassPrefix !== undefined && message.objcClassPrefix !== "") { + obj.objcClassPrefix = message.objcClassPrefix; + } + if (message.csharpNamespace !== undefined && message.csharpNamespace !== "") { + obj.csharpNamespace = message.csharpNamespace; + } + if (message.swiftPrefix !== undefined && message.swiftPrefix !== "") { + obj.swiftPrefix = message.swiftPrefix; + } + if (message.phpClassPrefix !== undefined && message.phpClassPrefix !== "") { + obj.phpClassPrefix = message.phpClassPrefix; + } + if (message.phpNamespace !== undefined && message.phpNamespace !== "") { + obj.phpNamespace = message.phpNamespace; + } + if (message.phpMetadataNamespace !== undefined && message.phpMetadataNamespace !== "") { + obj.phpMetadataNamespace = message.phpMetadataNamespace; + } + if (message.rubyPackage !== undefined && message.rubyPackage !== "") { + obj.rubyPackage = message.rubyPackage; + } + if (message.features !== undefined) { + obj.features = exports.FeatureSet.toJSON(message.features); + } + if (message.uninterpretedOption?.length) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => exports.UninterpretedOption.toJSON(e)); } 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, + messageSetWireFormat: isSet(object.messageSetWireFormat) + ? globalThis.Boolean(object.messageSetWireFormat) + : false, noStandardDescriptorAccessor: isSet(object.noStandardDescriptorAccessor) - ? Boolean(object.noStandardDescriptorAccessor) + ? globalThis.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) + deprecated: isSet(object.deprecated) ? globalThis.Boolean(object.deprecated) : false, + mapEntry: isSet(object.mapEntry) ? globalThis.Boolean(object.mapEntry) : false, + deprecatedLegacyJsonFieldConflicts: isSet(object.deprecatedLegacyJsonFieldConflicts) + ? globalThis.Boolean(object.deprecatedLegacyJsonFieldConflicts) + : false, + features: isSet(object.features) ? exports.FeatureSet.fromJSON(object.features) : undefined, + uninterpretedOption: globalThis.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); + if (message.messageSetWireFormat !== undefined && message.messageSetWireFormat !== false) { + obj.messageSetWireFormat = message.messageSetWireFormat; + } + if (message.noStandardDescriptorAccessor !== undefined && message.noStandardDescriptorAccessor !== false) { + obj.noStandardDescriptorAccessor = message.noStandardDescriptorAccessor; + } + if (message.deprecated !== undefined && message.deprecated !== false) { + obj.deprecated = message.deprecated; + } + if (message.mapEntry !== undefined && message.mapEntry !== false) { + obj.mapEntry = message.mapEntry; + } + if (message.deprecatedLegacyJsonFieldConflicts !== undefined && message.deprecatedLegacyJsonFieldConflicts !== false) { + obj.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; + } + if (message.features !== undefined) { + obj.features = exports.FeatureSet.toJSON(message.features); } - else { - obj.uninterpretedOption = []; + if (message.uninterpretedOption?.length) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => exports.UninterpretedOption.toJSON(e)); } 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, + packed: isSet(object.packed) ? globalThis.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) + lazy: isSet(object.lazy) ? globalThis.Boolean(object.lazy) : false, + unverifiedLazy: isSet(object.unverifiedLazy) ? globalThis.Boolean(object.unverifiedLazy) : false, + deprecated: isSet(object.deprecated) ? globalThis.Boolean(object.deprecated) : false, + weak: isSet(object.weak) ? globalThis.Boolean(object.weak) : false, + debugRedact: isSet(object.debugRedact) ? globalThis.Boolean(object.debugRedact) : false, + retention: isSet(object.retention) ? fieldOptions_OptionRetentionFromJSON(object.retention) : 0, + targets: globalThis.Array.isArray(object?.targets) + ? object.targets.map((e) => fieldOptions_OptionTargetTypeFromJSON(e)) + : [], + editionDefaults: globalThis.Array.isArray(object?.editionDefaults) + ? object.editionDefaults.map((e) => exports.FieldOptions_EditionDefault.fromJSON(e)) + : [], + features: isSet(object.features) ? exports.FeatureSet.fromJSON(object.features) : undefined, + featureSupport: isSet(object.featureSupport) + ? exports.FieldOptions_FeatureSupport.fromJSON(object.featureSupport) + : undefined, + uninterpretedOption: globalThis.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 = []; + if (message.ctype !== undefined && message.ctype !== 0) { + obj.ctype = fieldOptions_CTypeToJSON(message.ctype); + } + if (message.packed !== undefined && message.packed !== false) { + obj.packed = message.packed; + } + if (message.jstype !== undefined && message.jstype !== 0) { + obj.jstype = fieldOptions_JSTypeToJSON(message.jstype); + } + if (message.lazy !== undefined && message.lazy !== false) { + obj.lazy = message.lazy; + } + if (message.unverifiedLazy !== undefined && message.unverifiedLazy !== false) { + obj.unverifiedLazy = message.unverifiedLazy; + } + if (message.deprecated !== undefined && message.deprecated !== false) { + obj.deprecated = message.deprecated; + } + if (message.weak !== undefined && message.weak !== false) { + obj.weak = message.weak; + } + if (message.debugRedact !== undefined && message.debugRedact !== false) { + obj.debugRedact = message.debugRedact; + } + if (message.retention !== undefined && message.retention !== 0) { + obj.retention = fieldOptions_OptionRetentionToJSON(message.retention); + } + if (message.targets?.length) { + obj.targets = message.targets.map((e) => fieldOptions_OptionTargetTypeToJSON(e)); + } + if (message.editionDefaults?.length) { + obj.editionDefaults = message.editionDefaults.map((e) => exports.FieldOptions_EditionDefault.toJSON(e)); + } + if (message.features !== undefined) { + obj.features = exports.FeatureSet.toJSON(message.features); + } + if (message.featureSupport !== undefined) { + obj.featureSupport = exports.FieldOptions_FeatureSupport.toJSON(message.featureSupport); + } + if (message.uninterpretedOption?.length) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => exports.UninterpretedOption.toJSON(e)); + } + return obj; + }, +}; +exports.FieldOptions_EditionDefault = { + fromJSON(object) { + return { + edition: isSet(object.edition) ? editionFromJSON(object.edition) : 0, + value: isSet(object.value) ? globalThis.String(object.value) : "", + }; + }, + toJSON(message) { + const obj = {}; + if (message.edition !== undefined && message.edition !== 0) { + obj.edition = editionToJSON(message.edition); + } + if (message.value !== undefined && message.value !== "") { + obj.value = message.value; + } + return obj; + }, +}; +exports.FieldOptions_FeatureSupport = { + fromJSON(object) { + return { + editionIntroduced: isSet(object.editionIntroduced) ? editionFromJSON(object.editionIntroduced) : 0, + editionDeprecated: isSet(object.editionDeprecated) ? editionFromJSON(object.editionDeprecated) : 0, + deprecationWarning: isSet(object.deprecationWarning) ? globalThis.String(object.deprecationWarning) : "", + editionRemoved: isSet(object.editionRemoved) ? editionFromJSON(object.editionRemoved) : 0, + removalError: isSet(object.removalError) ? globalThis.String(object.removalError) : "", + }; + }, + toJSON(message) { + const obj = {}; + if (message.editionIntroduced !== undefined && message.editionIntroduced !== 0) { + obj.editionIntroduced = editionToJSON(message.editionIntroduced); + } + if (message.editionDeprecated !== undefined && message.editionDeprecated !== 0) { + obj.editionDeprecated = editionToJSON(message.editionDeprecated); + } + if (message.deprecationWarning !== undefined && message.deprecationWarning !== "") { + obj.deprecationWarning = message.deprecationWarning; + } + if (message.editionRemoved !== undefined && message.editionRemoved !== 0) { + obj.editionRemoved = editionToJSON(message.editionRemoved); + } + if (message.removalError !== undefined && message.removalError !== "") { + obj.removalError = message.removalError; } return obj; }, }; -function createBaseOneofOptions() { - return { uninterpretedOption: [] }; -} exports.OneofOptions = { fromJSON(object) { return { - uninterpretedOption: Array.isArray(object?.uninterpretedOption) + features: isSet(object.features) ? exports.FeatureSet.fromJSON(object.features) : undefined, + uninterpretedOption: globalThis.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); + if (message.features !== undefined) { + obj.features = exports.FeatureSet.toJSON(message.features); } - else { - obj.uninterpretedOption = []; + if (message.uninterpretedOption?.length) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => exports.UninterpretedOption.toJSON(e)); } 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) + allowAlias: isSet(object.allowAlias) ? globalThis.Boolean(object.allowAlias) : false, + deprecated: isSet(object.deprecated) ? globalThis.Boolean(object.deprecated) : false, + deprecatedLegacyJsonFieldConflicts: isSet(object.deprecatedLegacyJsonFieldConflicts) + ? globalThis.Boolean(object.deprecatedLegacyJsonFieldConflicts) + : false, + features: isSet(object.features) ? exports.FeatureSet.fromJSON(object.features) : undefined, + uninterpretedOption: globalThis.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); + if (message.allowAlias !== undefined && message.allowAlias !== false) { + obj.allowAlias = message.allowAlias; } - else { - obj.uninterpretedOption = []; + if (message.deprecated !== undefined && message.deprecated !== false) { + obj.deprecated = message.deprecated; + } + if (message.deprecatedLegacyJsonFieldConflicts !== undefined && message.deprecatedLegacyJsonFieldConflicts !== false) { + obj.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; + } + if (message.features !== undefined) { + obj.features = exports.FeatureSet.toJSON(message.features); + } + if (message.uninterpretedOption?.length) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => exports.UninterpretedOption.toJSON(e)); } 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) + deprecated: isSet(object.deprecated) ? globalThis.Boolean(object.deprecated) : false, + features: isSet(object.features) ? exports.FeatureSet.fromJSON(object.features) : undefined, + debugRedact: isSet(object.debugRedact) ? globalThis.Boolean(object.debugRedact) : false, + featureSupport: isSet(object.featureSupport) + ? exports.FieldOptions_FeatureSupport.fromJSON(object.featureSupport) + : undefined, + uninterpretedOption: globalThis.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); + if (message.deprecated !== undefined && message.deprecated !== false) { + obj.deprecated = message.deprecated; + } + if (message.features !== undefined) { + obj.features = exports.FeatureSet.toJSON(message.features); + } + if (message.debugRedact !== undefined && message.debugRedact !== false) { + obj.debugRedact = message.debugRedact; + } + if (message.featureSupport !== undefined) { + obj.featureSupport = exports.FieldOptions_FeatureSupport.toJSON(message.featureSupport); } - else { - obj.uninterpretedOption = []; + if (message.uninterpretedOption?.length) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => exports.UninterpretedOption.toJSON(e)); } 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) + features: isSet(object.features) ? exports.FeatureSet.fromJSON(object.features) : undefined, + deprecated: isSet(object.deprecated) ? globalThis.Boolean(object.deprecated) : false, + uninterpretedOption: globalThis.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); + if (message.features !== undefined) { + obj.features = exports.FeatureSet.toJSON(message.features); + } + if (message.deprecated !== undefined && message.deprecated !== false) { + obj.deprecated = message.deprecated; } - else { - obj.uninterpretedOption = []; + if (message.uninterpretedOption?.length) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => exports.UninterpretedOption.toJSON(e)); } return obj; }, }; -function createBaseMethodOptions() { - return { deprecated: false, idempotencyLevel: 0, uninterpretedOption: [] }; -} exports.MethodOptions = { fromJSON(object) { return { - deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, + deprecated: isSet(object.deprecated) ? globalThis.Boolean(object.deprecated) : false, idempotencyLevel: isSet(object.idempotencyLevel) ? methodOptions_IdempotencyLevelFromJSON(object.idempotencyLevel) : 0, - uninterpretedOption: Array.isArray(object?.uninterpretedOption) + features: isSet(object.features) ? exports.FeatureSet.fromJSON(object.features) : undefined, + uninterpretedOption: globalThis.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); + if (message.deprecated !== undefined && message.deprecated !== false) { + obj.deprecated = message.deprecated; + } + if (message.idempotencyLevel !== undefined && message.idempotencyLevel !== 0) { + obj.idempotencyLevel = methodOptions_IdempotencyLevelToJSON(message.idempotencyLevel); } - else { - obj.uninterpretedOption = []; + if (message.features !== undefined) { + obj.features = exports.FeatureSet.toJSON(message.features); + } + if (message.uninterpretedOption?.length) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => exports.UninterpretedOption.toJSON(e)); } 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, + name: globalThis.Array.isArray(object?.name) + ? object.name.map((e) => exports.UninterpretedOption_NamePart.fromJSON(e)) + : [], + identifierValue: isSet(object.identifierValue) ? globalThis.String(object.identifierValue) : "", + positiveIntValue: isSet(object.positiveIntValue) ? globalThis.String(object.positiveIntValue) : "0", + negativeIntValue: isSet(object.negativeIntValue) ? globalThis.String(object.negativeIntValue) : "0", + doubleValue: isSet(object.doubleValue) ? globalThis.Number(object.doubleValue) : 0, stringValue: isSet(object.stringValue) ? Buffer.from(bytesFromBase64(object.stringValue)) : Buffer.alloc(0), - aggregateValue: isSet(object.aggregateValue) ? String(object.aggregateValue) : "", + aggregateValue: isSet(object.aggregateValue) ? globalThis.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); + if (message.name?.length) { + obj.name = message.name.map((e) => exports.UninterpretedOption_NamePart.toJSON(e)); + } + if (message.identifierValue !== undefined && message.identifierValue !== "") { + obj.identifierValue = message.identifierValue; + } + if (message.positiveIntValue !== undefined && message.positiveIntValue !== "0") { + obj.positiveIntValue = message.positiveIntValue; + } + if (message.negativeIntValue !== undefined && message.negativeIntValue !== "0") { + obj.negativeIntValue = message.negativeIntValue; + } + if (message.doubleValue !== undefined && message.doubleValue !== 0) { + obj.doubleValue = message.doubleValue; + } + if (message.stringValue !== undefined && message.stringValue.length !== 0) { + obj.stringValue = base64FromBytes(message.stringValue); + } + if (message.aggregateValue !== undefined && message.aggregateValue !== "") { + 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, + namePart: isSet(object.namePart) ? globalThis.String(object.namePart) : "", + isExtension: isSet(object.isExtension) ? globalThis.Boolean(object.isExtension) : false, }; }, toJSON(message) { const obj = {}; - message.namePart !== undefined && (obj.namePart = message.namePart); - message.isExtension !== undefined && (obj.isExtension = message.isExtension); + if (message.namePart !== "") { + obj.namePart = message.namePart; + } + if (message.isExtension !== false) { + obj.isExtension = message.isExtension; + } + return obj; + }, +}; +exports.FeatureSet = { + fromJSON(object) { + return { + fieldPresence: isSet(object.fieldPresence) ? featureSet_FieldPresenceFromJSON(object.fieldPresence) : 0, + enumType: isSet(object.enumType) ? featureSet_EnumTypeFromJSON(object.enumType) : 0, + repeatedFieldEncoding: isSet(object.repeatedFieldEncoding) + ? featureSet_RepeatedFieldEncodingFromJSON(object.repeatedFieldEncoding) + : 0, + utf8Validation: isSet(object.utf8Validation) ? featureSet_Utf8ValidationFromJSON(object.utf8Validation) : 0, + messageEncoding: isSet(object.messageEncoding) ? featureSet_MessageEncodingFromJSON(object.messageEncoding) : 0, + jsonFormat: isSet(object.jsonFormat) ? featureSet_JsonFormatFromJSON(object.jsonFormat) : 0, + enforceNamingStyle: isSet(object.enforceNamingStyle) + ? featureSet_EnforceNamingStyleFromJSON(object.enforceNamingStyle) + : 0, + defaultSymbolVisibility: isSet(object.defaultSymbolVisibility) + ? featureSet_VisibilityFeature_DefaultSymbolVisibilityFromJSON(object.defaultSymbolVisibility) + : 0, + }; + }, + toJSON(message) { + const obj = {}; + if (message.fieldPresence !== undefined && message.fieldPresence !== 0) { + obj.fieldPresence = featureSet_FieldPresenceToJSON(message.fieldPresence); + } + if (message.enumType !== undefined && message.enumType !== 0) { + obj.enumType = featureSet_EnumTypeToJSON(message.enumType); + } + if (message.repeatedFieldEncoding !== undefined && message.repeatedFieldEncoding !== 0) { + obj.repeatedFieldEncoding = featureSet_RepeatedFieldEncodingToJSON(message.repeatedFieldEncoding); + } + if (message.utf8Validation !== undefined && message.utf8Validation !== 0) { + obj.utf8Validation = featureSet_Utf8ValidationToJSON(message.utf8Validation); + } + if (message.messageEncoding !== undefined && message.messageEncoding !== 0) { + obj.messageEncoding = featureSet_MessageEncodingToJSON(message.messageEncoding); + } + if (message.jsonFormat !== undefined && message.jsonFormat !== 0) { + obj.jsonFormat = featureSet_JsonFormatToJSON(message.jsonFormat); + } + if (message.enforceNamingStyle !== undefined && message.enforceNamingStyle !== 0) { + obj.enforceNamingStyle = featureSet_EnforceNamingStyleToJSON(message.enforceNamingStyle); + } + if (message.defaultSymbolVisibility !== undefined && message.defaultSymbolVisibility !== 0) { + obj.defaultSymbolVisibility = featureSet_VisibilityFeature_DefaultSymbolVisibilityToJSON(message.defaultSymbolVisibility); + } + return obj; + }, +}; +exports.FeatureSet_VisibilityFeature = { + fromJSON(_) { + return {}; + }, + toJSON(_) { + const obj = {}; + return obj; + }, +}; +exports.FeatureSetDefaults = { + fromJSON(object) { + return { + defaults: globalThis.Array.isArray(object?.defaults) + ? object.defaults.map((e) => exports.FeatureSetDefaults_FeatureSetEditionDefault.fromJSON(e)) + : [], + minimumEdition: isSet(object.minimumEdition) ? editionFromJSON(object.minimumEdition) : 0, + maximumEdition: isSet(object.maximumEdition) ? editionFromJSON(object.maximumEdition) : 0, + }; + }, + toJSON(message) { + const obj = {}; + if (message.defaults?.length) { + obj.defaults = message.defaults.map((e) => exports.FeatureSetDefaults_FeatureSetEditionDefault.toJSON(e)); + } + if (message.minimumEdition !== undefined && message.minimumEdition !== 0) { + obj.minimumEdition = editionToJSON(message.minimumEdition); + } + if (message.maximumEdition !== undefined && message.maximumEdition !== 0) { + obj.maximumEdition = editionToJSON(message.maximumEdition); + } + return obj; + }, +}; +exports.FeatureSetDefaults_FeatureSetEditionDefault = { + fromJSON(object) { + return { + edition: isSet(object.edition) ? editionFromJSON(object.edition) : 0, + overridableFeatures: isSet(object.overridableFeatures) + ? exports.FeatureSet.fromJSON(object.overridableFeatures) + : undefined, + fixedFeatures: isSet(object.fixedFeatures) ? exports.FeatureSet.fromJSON(object.fixedFeatures) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + if (message.edition !== undefined && message.edition !== 0) { + obj.edition = editionToJSON(message.edition); + } + if (message.overridableFeatures !== undefined) { + obj.overridableFeatures = exports.FeatureSet.toJSON(message.overridableFeatures); + } + if (message.fixedFeatures !== undefined) { + obj.fixedFeatures = exports.FeatureSet.toJSON(message.fixedFeatures); + } return obj; }, }; -function createBaseSourceCodeInfo() { - return { location: [] }; -} exports.SourceCodeInfo = { fromJSON(object) { return { - location: Array.isArray(object?.location) + location: globalThis.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 = []; + if (message.location?.length) { + obj.location = message.location.map((e) => exports.SourceCodeInfo_Location.toJSON(e)); } 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)) + path: globalThis.Array.isArray(object?.path) + ? object.path.map((e) => globalThis.Number(e)) + : [], + span: globalThis.Array.isArray(object?.span) ? object.span.map((e) => globalThis.Number(e)) : [], + leadingComments: isSet(object.leadingComments) ? globalThis.String(object.leadingComments) : "", + trailingComments: isSet(object.trailingComments) ? globalThis.String(object.trailingComments) : "", + leadingDetachedComments: globalThis.Array.isArray(object?.leadingDetachedComments) + ? object.leadingDetachedComments.map((e) => globalThis.String(e)) : [], }; }, toJSON(message) { const obj = {}; - if (message.path) { + if (message.path?.length) { obj.path = message.path.map((e) => Math.round(e)); } - else { - obj.path = []; - } - if (message.span) { + if (message.span?.length) { obj.span = message.span.map((e) => Math.round(e)); } - else { - obj.span = []; + if (message.leadingComments !== undefined && message.leadingComments !== "") { + obj.leadingComments = message.leadingComments; } - message.leadingComments !== undefined && (obj.leadingComments = message.leadingComments); - message.trailingComments !== undefined && (obj.trailingComments = message.trailingComments); - if (message.leadingDetachedComments) { - obj.leadingDetachedComments = message.leadingDetachedComments.map((e) => e); + if (message.trailingComments !== undefined && message.trailingComments !== "") { + obj.trailingComments = message.trailingComments; } - else { - obj.leadingDetachedComments = []; + if (message.leadingDetachedComments?.length) { + obj.leadingDetachedComments = message.leadingDetachedComments; } return obj; }, }; -function createBaseGeneratedCodeInfo() { - return { annotation: [] }; -} exports.GeneratedCodeInfo = { fromJSON(object) { return { - annotation: Array.isArray(object?.annotation) + annotation: globalThis.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 = []; + if (message.annotation?.length) { + obj.annotation = message.annotation.map((e) => exports.GeneratedCodeInfo_Annotation.toJSON(e)); } 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, + path: globalThis.Array.isArray(object?.path) + ? object.path.map((e) => globalThis.Number(e)) + : [], + sourceFile: isSet(object.sourceFile) ? globalThis.String(object.sourceFile) : "", + begin: isSet(object.begin) ? globalThis.Number(object.begin) : 0, + end: isSet(object.end) ? globalThis.Number(object.end) : 0, + semantic: isSet(object.semantic) ? generatedCodeInfo_Annotation_SemanticFromJSON(object.semantic) : 0, }; }, toJSON(message) { const obj = {}; - if (message.path) { + if (message.path?.length) { obj.path = message.path.map((e) => Math.round(e)); } - else { - obj.path = []; + if (message.sourceFile !== undefined && message.sourceFile !== "") { + obj.sourceFile = message.sourceFile; + } + if (message.begin !== undefined && message.begin !== 0) { + obj.begin = Math.round(message.begin); + } + if (message.end !== undefined && message.end !== 0) { + obj.end = Math.round(message.end); + } + if (message.semantic !== undefined && message.semantic !== 0) { + obj.semantic = generatedCodeInfo_Annotation_SemanticToJSON(message.semantic); } - 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; - } + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); } 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("")); - } + return globalThis.Buffer.from(arr).toString("base64"); } function isSet(value) { return value !== null && value !== undefined; diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.js index 159135fe87172..138ecae8eb4a2 100644 --- a/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.js +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.js @@ -1,21 +1,26 @@ "use strict"; -/* eslint-disable */ +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: google/protobuf/timestamp.proto 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, + seconds: isSet(object.seconds) ? globalThis.String(object.seconds) : "0", + nanos: isSet(object.nanos) ? globalThis.Number(object.nanos) : 0, }; }, toJSON(message) { const obj = {}; - message.seconds !== undefined && (obj.seconds = message.seconds); - message.nanos !== undefined && (obj.nanos = Math.round(message.nanos)); + if (message.seconds !== "0") { + obj.seconds = message.seconds; + } + if (message.nanos !== 0) { + obj.nanos = Math.round(message.nanos); + } return obj; }, }; diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.js new file mode 100644 index 0000000000000..ca878c08c7055 --- /dev/null +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.js @@ -0,0 +1,55 @@ +"use strict"; +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: rekor/v2/dsse.proto +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DSSELogEntryV002 = exports.DSSERequestV002 = void 0; +/* eslint-disable */ +const envelope_1 = require("../../envelope"); +const sigstore_common_1 = require("../../sigstore_common"); +const verifier_1 = require("./verifier"); +exports.DSSERequestV002 = { + fromJSON(object) { + return { + envelope: isSet(object.envelope) ? envelope_1.Envelope.fromJSON(object.envelope) : undefined, + verifiers: globalThis.Array.isArray(object?.verifiers) + ? object.verifiers.map((e) => verifier_1.Verifier.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.envelope !== undefined) { + obj.envelope = envelope_1.Envelope.toJSON(message.envelope); + } + if (message.verifiers?.length) { + obj.verifiers = message.verifiers.map((e) => verifier_1.Verifier.toJSON(e)); + } + return obj; + }, +}; +exports.DSSELogEntryV002 = { + fromJSON(object) { + return { + payloadHash: isSet(object.payloadHash) ? sigstore_common_1.HashOutput.fromJSON(object.payloadHash) : undefined, + signatures: globalThis.Array.isArray(object?.signatures) + ? object.signatures.map((e) => verifier_1.Signature.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.payloadHash !== undefined) { + obj.payloadHash = sigstore_common_1.HashOutput.toJSON(message.payloadHash); + } + if (message.signatures?.length) { + obj.signatures = message.signatures.map((e) => verifier_1.Signature.toJSON(e)); + } + return obj; + }, +}; +function isSet(value) { + return value !== null && value !== undefined; +} diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.js new file mode 100644 index 0000000000000..f54d7d266114c --- /dev/null +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.js @@ -0,0 +1,81 @@ +"use strict"; +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: rekor/v2/entry.proto +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CreateEntryRequest = exports.Spec = exports.Entry = void 0; +/* eslint-disable */ +const dsse_1 = require("./dsse"); +const hashedrekord_1 = require("./hashedrekord"); +exports.Entry = { + fromJSON(object) { + return { + kind: isSet(object.kind) ? globalThis.String(object.kind) : "", + apiVersion: isSet(object.apiVersion) ? globalThis.String(object.apiVersion) : "", + spec: isSet(object.spec) ? exports.Spec.fromJSON(object.spec) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + if (message.kind !== "") { + obj.kind = message.kind; + } + if (message.apiVersion !== "") { + obj.apiVersion = message.apiVersion; + } + if (message.spec !== undefined) { + obj.spec = exports.Spec.toJSON(message.spec); + } + return obj; + }, +}; +exports.Spec = { + fromJSON(object) { + return { + spec: isSet(object.hashedRekordV002) + ? { $case: "hashedRekordV002", hashedRekordV002: hashedrekord_1.HashedRekordLogEntryV002.fromJSON(object.hashedRekordV002) } + : isSet(object.dsseV002) + ? { $case: "dsseV002", dsseV002: dsse_1.DSSELogEntryV002.fromJSON(object.dsseV002) } + : undefined, + }; + }, + toJSON(message) { + const obj = {}; + if (message.spec?.$case === "hashedRekordV002") { + obj.hashedRekordV002 = hashedrekord_1.HashedRekordLogEntryV002.toJSON(message.spec.hashedRekordV002); + } + else if (message.spec?.$case === "dsseV002") { + obj.dsseV002 = dsse_1.DSSELogEntryV002.toJSON(message.spec.dsseV002); + } + return obj; + }, +}; +exports.CreateEntryRequest = { + fromJSON(object) { + return { + spec: isSet(object.hashedRekordRequestV002) + ? { + $case: "hashedRekordRequestV002", + hashedRekordRequestV002: hashedrekord_1.HashedRekordRequestV002.fromJSON(object.hashedRekordRequestV002), + } + : isSet(object.dsseRequestV002) + ? { $case: "dsseRequestV002", dsseRequestV002: dsse_1.DSSERequestV002.fromJSON(object.dsseRequestV002) } + : undefined, + }; + }, + toJSON(message) { + const obj = {}; + if (message.spec?.$case === "hashedRekordRequestV002") { + obj.hashedRekordRequestV002 = hashedrekord_1.HashedRekordRequestV002.toJSON(message.spec.hashedRekordRequestV002); + } + else if (message.spec?.$case === "dsseRequestV002") { + obj.dsseRequestV002 = dsse_1.DSSERequestV002.toJSON(message.spec.dsseRequestV002); + } + return obj; + }, +}; +function isSet(value) { + return value !== null && value !== undefined; +} diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.js new file mode 100644 index 0000000000000..8143a9fc25a77 --- /dev/null +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.js @@ -0,0 +1,56 @@ +"use strict"; +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: rekor/v2/hashedrekord.proto +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HashedRekordLogEntryV002 = exports.HashedRekordRequestV002 = void 0; +/* eslint-disable */ +const sigstore_common_1 = require("../../sigstore_common"); +const verifier_1 = require("./verifier"); +exports.HashedRekordRequestV002 = { + fromJSON(object) { + return { + digest: isSet(object.digest) ? Buffer.from(bytesFromBase64(object.digest)) : Buffer.alloc(0), + signature: isSet(object.signature) ? verifier_1.Signature.fromJSON(object.signature) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + if (message.digest.length !== 0) { + obj.digest = base64FromBytes(message.digest); + } + if (message.signature !== undefined) { + obj.signature = verifier_1.Signature.toJSON(message.signature); + } + return obj; + }, +}; +exports.HashedRekordLogEntryV002 = { + fromJSON(object) { + return { + data: isSet(object.data) ? sigstore_common_1.HashOutput.fromJSON(object.data) : undefined, + signature: isSet(object.signature) ? verifier_1.Signature.fromJSON(object.signature) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + if (message.data !== undefined) { + obj.data = sigstore_common_1.HashOutput.toJSON(message.data); + } + if (message.signature !== undefined) { + obj.signature = verifier_1.Signature.toJSON(message.signature); + } + return obj; + }, +}; +function bytesFromBase64(b64) { + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); +} +function base64FromBytes(arr) { + return globalThis.Buffer.from(arr).toString("base64"); +} +function isSet(value) { + return value !== null && value !== undefined; +} diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.js new file mode 100644 index 0000000000000..1275300b2a3ab --- /dev/null +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.js @@ -0,0 +1,74 @@ +"use strict"; +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: rekor/v2/verifier.proto +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Signature = exports.Verifier = exports.PublicKey = void 0; +/* eslint-disable */ +const sigstore_common_1 = require("../../sigstore_common"); +exports.PublicKey = { + fromJSON(object) { + return { rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : Buffer.alloc(0) }; + }, + toJSON(message) { + const obj = {}; + if (message.rawBytes.length !== 0) { + obj.rawBytes = base64FromBytes(message.rawBytes); + } + return obj; + }, +}; +exports.Verifier = { + fromJSON(object) { + return { + verifier: isSet(object.publicKey) + ? { $case: "publicKey", publicKey: exports.PublicKey.fromJSON(object.publicKey) } + : isSet(object.x509Certificate) + ? { $case: "x509Certificate", x509Certificate: sigstore_common_1.X509Certificate.fromJSON(object.x509Certificate) } + : undefined, + keyDetails: isSet(object.keyDetails) ? (0, sigstore_common_1.publicKeyDetailsFromJSON)(object.keyDetails) : 0, + }; + }, + toJSON(message) { + const obj = {}; + if (message.verifier?.$case === "publicKey") { + obj.publicKey = exports.PublicKey.toJSON(message.verifier.publicKey); + } + else if (message.verifier?.$case === "x509Certificate") { + obj.x509Certificate = sigstore_common_1.X509Certificate.toJSON(message.verifier.x509Certificate); + } + if (message.keyDetails !== 0) { + obj.keyDetails = (0, sigstore_common_1.publicKeyDetailsToJSON)(message.keyDetails); + } + return obj; + }, +}; +exports.Signature = { + fromJSON(object) { + return { + content: isSet(object.content) ? Buffer.from(bytesFromBase64(object.content)) : Buffer.alloc(0), + verifier: isSet(object.verifier) ? exports.Verifier.fromJSON(object.verifier) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + if (message.content.length !== 0) { + obj.content = base64FromBytes(message.content); + } + if (message.verifier !== undefined) { + obj.verifier = exports.Verifier.toJSON(message.verifier); + } + return obj; + }, +}; +function bytesFromBase64(b64) { + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); +} +function base64FromBytes(arr) { + return globalThis.Buffer.from(arr).toString("base64"); +} +function isSet(value) { + return value !== null && value !== undefined; +} diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.js index 3773867f5426a..7052260f04225 100644 --- a/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.js +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.js @@ -1,35 +1,31 @@ "use strict"; +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: sigstore_bundle.proto 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) + rfc3161Timestamps: globalThis.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 = []; + if (message.rfc3161Timestamps?.length) { + obj.rfc3161Timestamps = message.rfc3161Timestamps.map((e) => sigstore_common_1.RFC3161SignedTimestamp.toJSON(e)); } return obj; }, }; -function createBaseVerificationMaterial() { - return { content: undefined, tlogEntries: [], timestampVerificationData: undefined }; -} exports.VerificationMaterial = { fromJSON(object) { return { @@ -43,7 +39,7 @@ exports.VerificationMaterial = { : isSet(object.certificate) ? { $case: "certificate", certificate: sigstore_common_1.X509Certificate.fromJSON(object.certificate) } : undefined, - tlogEntries: Array.isArray(object?.tlogEntries) + tlogEntries: globalThis.Array.isArray(object?.tlogEntries) ? object.tlogEntries.map((e) => sigstore_rekor_1.TransparencyLogEntry.fromJSON(e)) : [], timestampVerificationData: isSet(object.timestampVerificationData) @@ -53,36 +49,28 @@ exports.VerificationMaterial = { }, 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); + if (message.content?.$case === "publicKey") { + obj.publicKey = sigstore_common_1.PublicKeyIdentifier.toJSON(message.content.publicKey); + } + else if (message.content?.$case === "x509CertificateChain") { + obj.x509CertificateChain = sigstore_common_1.X509CertificateChain.toJSON(message.content.x509CertificateChain); + } + else if (message.content?.$case === "certificate") { + obj.certificate = sigstore_common_1.X509Certificate.toJSON(message.content.certificate); + } + if (message.tlogEntries?.length) { + obj.tlogEntries = message.tlogEntries.map((e) => sigstore_rekor_1.TransparencyLogEntry.toJSON(e)); } - else { - obj.tlogEntries = []; + if (message.timestampVerificationData !== undefined) { + obj.timestampVerificationData = exports.TimestampVerificationData.toJSON(message.timestampVerificationData); } - 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) : "", + mediaType: isSet(object.mediaType) ? globalThis.String(object.mediaType) : "", verificationMaterial: isSet(object.verificationMaterial) ? exports.VerificationMaterial.fromJSON(object.verificationMaterial) : undefined, @@ -95,15 +83,18 @@ exports.Bundle = { }, 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); + if (message.mediaType !== "") { + obj.mediaType = message.mediaType; + } + if (message.verificationMaterial !== undefined) { + obj.verificationMaterial = exports.VerificationMaterial.toJSON(message.verificationMaterial); + } + if (message.content?.$case === "messageSignature") { + obj.messageSignature = sigstore_common_1.MessageSignature.toJSON(message.content.messageSignature); + } + else if (message.content?.$case === "dsseEnvelope") { + obj.dsseEnvelope = envelope_1.Envelope.toJSON(message.content.dsseEnvelope); + } return obj; }, }; diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.js index c6f9baa91fff2..23d8ab34d3bb8 100644 --- a/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.js +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.js @@ -1,6 +1,17 @@ "use strict"; +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: sigstore_common.proto 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.subjectAlternativeNameTypeToJSON = exports.subjectAlternativeNameTypeFromJSON = exports.SubjectAlternativeNameType = exports.publicKeyDetailsToJSON = exports.publicKeyDetailsFromJSON = exports.PublicKeyDetails = exports.hashAlgorithmToJSON = exports.hashAlgorithmFromJSON = exports.HashAlgorithm = void 0; +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"); /** @@ -18,9 +29,19 @@ var HashAlgorithm; HashAlgorithm[HashAlgorithm["SHA2_256"] = 1] = "SHA2_256"; HashAlgorithm[HashAlgorithm["SHA2_384"] = 2] = "SHA2_384"; HashAlgorithm[HashAlgorithm["SHA2_512"] = 3] = "SHA2_512"; + /** + * SHA3_256 - Used for LMS + * + * @deprecated + */ HashAlgorithm[HashAlgorithm["SHA3_256"] = 4] = "SHA3_256"; + /** + * SHA3_384 - Used for LMS + * + * @deprecated + */ HashAlgorithm[HashAlgorithm["SHA3_384"] = 5] = "SHA3_384"; -})(HashAlgorithm = exports.HashAlgorithm || (exports.HashAlgorithm = {})); +})(HashAlgorithm || (exports.HashAlgorithm = HashAlgorithm = {})); function hashAlgorithmFromJSON(object) { switch (object) { case 0: @@ -42,10 +63,9 @@ function hashAlgorithmFromJSON(object) { case "SHA3_384": return HashAlgorithm.SHA3_384; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); } } -exports.hashAlgorithmFromJSON = hashAlgorithmFromJSON; function hashAlgorithmToJSON(object) { switch (object) { case HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED: @@ -61,10 +81,9 @@ function hashAlgorithmToJSON(object) { case HashAlgorithm.SHA3_384: return "SHA3_384"; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); } } -exports.hashAlgorithmToJSON = hashAlgorithmToJSON; /** * Details of a specific public key, capturing the the key encoding method, * and signature algorithm. @@ -76,7 +95,8 @@ exports.hashAlgorithmToJSON = hashAlgorithmToJSON; * 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 + * + * See: * * To avoid the possibility of contradicting formats such as PKCS1 with * ED25519 the valid permutations are listed as a linear set instead of a @@ -123,12 +143,20 @@ var PublicKeyDetails; /** PKIX_ED25519 - Ed 25519 */ PublicKeyDetails[PublicKeyDetails["PKIX_ED25519"] = 7] = "PKIX_ED25519"; PublicKeyDetails[PublicKeyDetails["PKIX_ED25519_PH"] = 8] = "PKIX_ED25519_PH"; + /** + * PKIX_ECDSA_P384_SHA_256 - These algorithms are deprecated and should not be used, but they + * were/are being used by most Sigstore clients implementations. + * + * @deprecated + */ + PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P384_SHA_256"] = 19] = "PKIX_ECDSA_P384_SHA_256"; + /** @deprecated */ + PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P521_SHA_256"] = 20] = "PKIX_ECDSA_P521_SHA_256"; /** * 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. + * These algorithms are deprecated and should not be used. + * There are no plans to support SLH-DSA at this time. * * USER WARNING: LMS and LM-OTS are both stateful signature schemes. * Using them correctly requires discretion and careful consideration @@ -137,10 +165,33 @@ var PublicKeyDetails; * 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. + * + * @deprecated */ PublicKeyDetails[PublicKeyDetails["LMS_SHA256"] = 14] = "LMS_SHA256"; + /** @deprecated */ PublicKeyDetails[PublicKeyDetails["LMOTS_SHA256"] = 15] = "LMOTS_SHA256"; -})(PublicKeyDetails = exports.PublicKeyDetails || (exports.PublicKeyDetails = {})); + /** + * ML_DSA_44 - ML-DSA + * + * These ML_DSA_44, ML_DSA_65 and ML-DSA_87 algorithms are the pure variants + * that take data to sign rather than the prehash variants (HashML-DSA), which + * take digests. While considered quantum-resistant, their usage + * involves tradeoffs in that signatures and keys are much larger, and + * this makes deployments more costly. + * + * USER WARNING: ML_DSA_44, ML_DSA_65 and ML_DSA_87 are experimental algorithms. + * In the future they MAY be used by private Sigstore deployments, but + * they are not yet fully functional. This warning will be removed when + * these algorithms are widely supported by Sigstore clients and servers, + * but care should still be taken for production environments. + * + * See NIST FIPS 204, RFC 9881 for algorithm identifiers + */ + PublicKeyDetails[PublicKeyDetails["ML_DSA_44"] = 23] = "ML_DSA_44"; + PublicKeyDetails[PublicKeyDetails["ML_DSA_65"] = 21] = "ML_DSA_65"; + PublicKeyDetails[PublicKeyDetails["ML_DSA_87"] = 22] = "ML_DSA_87"; +})(PublicKeyDetails || (exports.PublicKeyDetails = PublicKeyDetails = {})); function publicKeyDetailsFromJSON(object) { switch (object) { case 0: @@ -194,17 +245,31 @@ function publicKeyDetailsFromJSON(object) { case 8: case "PKIX_ED25519_PH": return PublicKeyDetails.PKIX_ED25519_PH; + case 19: + case "PKIX_ECDSA_P384_SHA_256": + return PublicKeyDetails.PKIX_ECDSA_P384_SHA_256; + case 20: + case "PKIX_ECDSA_P521_SHA_256": + return PublicKeyDetails.PKIX_ECDSA_P521_SHA_256; case 14: case "LMS_SHA256": return PublicKeyDetails.LMS_SHA256; case 15: case "LMOTS_SHA256": return PublicKeyDetails.LMOTS_SHA256; + case 23: + case "ML_DSA_44": + return PublicKeyDetails.ML_DSA_44; + case 21: + case "ML_DSA_65": + return PublicKeyDetails.ML_DSA_65; + case 22: + case "ML_DSA_87": + return PublicKeyDetails.ML_DSA_87; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); } } -exports.publicKeyDetailsFromJSON = publicKeyDetailsFromJSON; function publicKeyDetailsToJSON(object) { switch (object) { case PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED: @@ -241,15 +306,24 @@ function publicKeyDetailsToJSON(object) { return "PKIX_ED25519"; case PublicKeyDetails.PKIX_ED25519_PH: return "PKIX_ED25519_PH"; + case PublicKeyDetails.PKIX_ECDSA_P384_SHA_256: + return "PKIX_ECDSA_P384_SHA_256"; + case PublicKeyDetails.PKIX_ECDSA_P521_SHA_256: + return "PKIX_ECDSA_P521_SHA_256"; case PublicKeyDetails.LMS_SHA256: return "LMS_SHA256"; case PublicKeyDetails.LMOTS_SHA256: return "LMOTS_SHA256"; + case PublicKeyDetails.ML_DSA_44: + return "ML_DSA_44"; + case PublicKeyDetails.ML_DSA_65: + return "ML_DSA_65"; + case PublicKeyDetails.ML_DSA_87: + return "ML_DSA_87"; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); } } -exports.publicKeyDetailsToJSON = publicKeyDetailsToJSON; var SubjectAlternativeNameType; (function (SubjectAlternativeNameType) { SubjectAlternativeNameType[SubjectAlternativeNameType["SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"] = 0] = "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"; @@ -261,7 +335,7 @@ var SubjectAlternativeNameType; * for more details. */ SubjectAlternativeNameType[SubjectAlternativeNameType["OTHER_NAME"] = 3] = "OTHER_NAME"; -})(SubjectAlternativeNameType = exports.SubjectAlternativeNameType || (exports.SubjectAlternativeNameType = {})); +})(SubjectAlternativeNameType || (exports.SubjectAlternativeNameType = SubjectAlternativeNameType = {})); function subjectAlternativeNameTypeFromJSON(object) { switch (object) { case 0: @@ -277,10 +351,9 @@ function subjectAlternativeNameTypeFromJSON(object) { case "OTHER_NAME": return SubjectAlternativeNameType.OTHER_NAME; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); } } -exports.subjectAlternativeNameTypeFromJSON = subjectAlternativeNameTypeFromJSON; function subjectAlternativeNameTypeToJSON(object) { switch (object) { case SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED: @@ -292,13 +365,9 @@ function subjectAlternativeNameTypeToJSON(object) { case SubjectAlternativeNameType.OTHER_NAME: return "OTHER_NAME"; default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); + throw new globalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); } } -exports.subjectAlternativeNameTypeToJSON = subjectAlternativeNameTypeToJSON; -function createBaseHashOutput() { - return { algorithm: 0, digest: Buffer.alloc(0) }; -} exports.HashOutput = { fromJSON(object) { return { @@ -308,15 +377,15 @@ exports.HashOutput = { }, 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))); + if (message.algorithm !== 0) { + obj.algorithm = hashAlgorithmToJSON(message.algorithm); + } + if (message.digest.length !== 0) { + obj.digest = base64FromBytes(message.digest); + } return obj; }, }; -function createBaseMessageSignature() { - return { messageDigest: undefined, signature: Buffer.alloc(0) }; -} exports.MessageSignature = { fromJSON(object) { return { @@ -326,30 +395,27 @@ exports.MessageSignature = { }, 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))); + if (message.messageDigest !== undefined) { + obj.messageDigest = exports.HashOutput.toJSON(message.messageDigest); + } + if (message.signature.length !== 0) { + obj.signature = base64FromBytes(message.signature); + } 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))); + if (message.keyId.length !== 0) { + obj.keyId = base64FromBytes(message.keyId); + } return obj; }, }; -function createBaseRFC3161SignedTimestamp() { - return { signedTimestamp: Buffer.alloc(0) }; -} exports.RFC3161SignedTimestamp = { fromJSON(object) { return { @@ -360,14 +426,12 @@ exports.RFC3161SignedTimestamp = { }, toJSON(message) { const obj = {}; - message.signedTimestamp !== undefined && - (obj.signedTimestamp = base64FromBytes(message.signedTimestamp !== undefined ? message.signedTimestamp : Buffer.alloc(0))); + if (message.signedTimestamp.length !== 0) { + obj.signedTimestamp = base64FromBytes(message.signedTimestamp); + } return obj; }, }; -function createBasePublicKey() { - return { rawBytes: undefined, keyDetails: 0, validFor: undefined }; -} exports.PublicKey = { fromJSON(object) { return { @@ -378,48 +442,42 @@ exports.PublicKey = { }, 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); + if (message.rawBytes !== undefined) { + obj.rawBytes = base64FromBytes(message.rawBytes); + } + if (message.keyDetails !== 0) { + obj.keyDetails = publicKeyDetailsToJSON(message.keyDetails); + } + if (message.validFor !== undefined) { + obj.validFor = exports.TimeRange.toJSON(message.validFor); + } return obj; }, }; -function createBasePublicKeyIdentifier() { - return { hint: "" }; -} exports.PublicKeyIdentifier = { fromJSON(object) { - return { hint: isSet(object.hint) ? String(object.hint) : "" }; + return { hint: isSet(object.hint) ? globalThis.String(object.hint) : "" }; }, toJSON(message) { const obj = {}; - message.hint !== undefined && (obj.hint = message.hint); + if (message.hint !== "") { + 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)) : [] }; + return { id: globalThis.Array.isArray(object?.id) ? object.id.map((e) => globalThis.Number(e)) : [] }; }, toJSON(message) { const obj = {}; - if (message.id) { + if (message.id?.length) { 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 { @@ -429,90 +487,86 @@ exports.ObjectIdentifierValuePair = { }, 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))); + if (message.oid !== undefined) { + obj.oid = exports.ObjectIdentifier.toJSON(message.oid); + } + if (message.value.length !== 0) { + obj.value = base64FromBytes(message.value); + } 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) : "", + organization: isSet(object.organization) ? globalThis.String(object.organization) : "", + commonName: isSet(object.commonName) ? globalThis.String(object.commonName) : "", }; }, toJSON(message) { const obj = {}; - message.organization !== undefined && (obj.organization = message.organization); - message.commonName !== undefined && (obj.commonName = message.commonName); + if (message.organization !== "") { + obj.organization = message.organization; + } + if (message.commonName !== "") { + 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))); + if (message.rawBytes.length !== 0) { + obj.rawBytes = base64FromBytes(message.rawBytes); + } 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) } + ? { $case: "regexp", regexp: globalThis.String(object.regexp) } : isSet(object.value) - ? { $case: "value", value: String(object.value) } + ? { $case: "value", value: globalThis.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); + if (message.type !== 0) { + obj.type = subjectAlternativeNameTypeToJSON(message.type); + } + if (message.identity?.$case === "regexp") { + obj.regexp = message.identity.regexp; + } + else if (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) + certificates: globalThis.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 = []; + if (message.certificates?.length) { + obj.certificates = message.certificates.map((e) => exports.X509Certificate.toJSON(e)); } return obj; }, }; -function createBaseTimeRange() { - return { start: undefined, end: undefined }; -} exports.TimeRange = { fromJSON(object) { return { @@ -522,62 +576,32 @@ exports.TimeRange = { }, toJSON(message) { const obj = {}; - message.start !== undefined && (obj.start = message.start.toISOString()); - message.end !== undefined && (obj.end = message.end.toISOString()); + if (message.start !== undefined) { + obj.start = message.start.toISOString(); + } + if (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; - } + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); } 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("")); - } + return globalThis.Buffer.from(arr).toString("base64"); } function fromTimestamp(t) { - let millis = Number(t.seconds) * 1000; - millis += t.nanos / 1000000; - return new Date(millis); + let millis = (globalThis.Number(t.seconds) || 0) * 1_000; + millis += (t.nanos || 0) / 1_000_000; + return new globalThis.Date(millis); } function fromJsonTimestamp(o) { - if (o instanceof Date) { + if (o instanceof globalThis.Date) { return o; } else if (typeof o === "string") { - return new Date(o); + return new globalThis.Date(o); } else { return fromTimestamp(timestamp_1.Timestamp.fromJSON(o)); diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.js index 398193b2075a7..e5c32d57d37a2 100644 --- a/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.js +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.js @@ -1,71 +1,75 @@ "use strict"; +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: sigstore_rekor.proto 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) : "", + kind: isSet(object.kind) ? globalThis.String(object.kind) : "", + version: isSet(object.version) ? globalThis.String(object.version) : "", }; }, toJSON(message) { const obj = {}; - message.kind !== undefined && (obj.kind = message.kind); - message.version !== undefined && (obj.version = message.version); + if (message.kind !== "") { + obj.kind = message.kind; + } + if (message.version !== "") { + obj.version = message.version; + } return obj; }, }; -function createBaseCheckpoint() { - return { envelope: "" }; -} exports.Checkpoint = { fromJSON(object) { - return { envelope: isSet(object.envelope) ? String(object.envelope) : "" }; + return { envelope: isSet(object.envelope) ? globalThis.String(object.envelope) : "" }; }, toJSON(message) { const obj = {}; - message.envelope !== undefined && (obj.envelope = message.envelope); + if (message.envelope !== "") { + 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", + logIndex: isSet(object.logIndex) ? globalThis.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))) : [], + treeSize: isSet(object.treeSize) ? globalThis.String(object.treeSize) : "0", + hashes: globalThis.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); + if (message.logIndex !== "0") { + obj.logIndex = message.logIndex; + } + if (message.rootHash.length !== 0) { + obj.rootHash = base64FromBytes(message.rootHash); + } + if (message.treeSize !== "0") { + obj.treeSize = message.treeSize; + } + if (message.hashes?.length) { + obj.hashes = message.hashes.map((e) => base64FromBytes(e)); + } + if (message.checkpoint !== undefined) { + obj.checkpoint = exports.Checkpoint.toJSON(message.checkpoint); + } return obj; }, }; -function createBaseInclusionPromise() { - return { signedEntryTimestamp: Buffer.alloc(0) }; -} exports.InclusionPromise = { fromJSON(object) { return { @@ -76,29 +80,19 @@ exports.InclusionPromise = { }, toJSON(message) { const obj = {}; - message.signedEntryTimestamp !== undefined && - (obj.signedEntryTimestamp = base64FromBytes(message.signedEntryTimestamp !== undefined ? message.signedEntryTimestamp : Buffer.alloc(0))); + if (message.signedEntryTimestamp.length !== 0) { + obj.signedEntryTimestamp = base64FromBytes(message.signedEntryTimestamp); + } 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", + logIndex: isSet(object.logIndex) ? globalThis.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", + integratedTime: isSet(object.integratedTime) ? globalThis.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) @@ -108,59 +102,35 @@ exports.TransparencyLogEntry = { }, 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))); + if (message.logIndex !== "0") { + obj.logIndex = message.logIndex; + } + if (message.logId !== undefined) { + obj.logId = sigstore_common_1.LogId.toJSON(message.logId); + } + if (message.kindVersion !== undefined) { + obj.kindVersion = exports.KindVersion.toJSON(message.kindVersion); + } + if (message.integratedTime !== "0") { + obj.integratedTime = message.integratedTime; + } + if (message.inclusionPromise !== undefined) { + obj.inclusionPromise = exports.InclusionPromise.toJSON(message.inclusionPromise); + } + if (message.inclusionProof !== undefined) { + obj.inclusionProof = exports.InclusionProof.toJSON(message.inclusionProof); + } + if (message.canonicalizedBody.length !== 0) { + obj.canonicalizedBody = base64FromBytes(message.canonicalizedBody); + } 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; - } + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); } 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("")); - } + return globalThis.Buffer.from(arr).toString("base64"); } function isSet(value) { return value !== null && value !== undefined; diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.js index 8791aba27044b..978a41cb1162e 100644 --- a/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.js +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.js @@ -1,155 +1,281 @@ "use strict"; +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: sigstore_trustroot.proto Object.defineProperty(exports, "__esModule", { value: true }); -exports.ClientTrustConfig = exports.SigningConfig = exports.TrustedRoot = exports.CertificateAuthority = exports.TransparencyLogInstance = void 0; +exports.ClientTrustConfig = exports.ServiceConfiguration = exports.Service = exports.SigningConfig = exports.TrustedRoot = exports.CertificateAuthority = exports.TransparencyLogInstance = exports.ServiceSelector = void 0; +exports.serviceSelectorFromJSON = serviceSelectorFromJSON; +exports.serviceSelectorToJSON = serviceSelectorToJSON; /* eslint-disable */ const sigstore_common_1 = require("./sigstore_common"); -function createBaseTransparencyLogInstance() { - return { baseUrl: "", hashAlgorithm: 0, publicKey: undefined, logId: undefined, checkpointKeyId: undefined }; +/** + * ServiceSelector specifies how a client SHOULD select a set of + * Services to connect to. A client SHOULD throw an error if + * the value is SERVICE_SELECTOR_UNDEFINED. + */ +var ServiceSelector; +(function (ServiceSelector) { + ServiceSelector[ServiceSelector["SERVICE_SELECTOR_UNDEFINED"] = 0] = "SERVICE_SELECTOR_UNDEFINED"; + /** + * ALL - Clients SHOULD select all Services based on supported API version + * and validity window. + */ + ServiceSelector[ServiceSelector["ALL"] = 1] = "ALL"; + /** + * ANY - Clients SHOULD select one Service based on supported API version + * and validity window. It is up to the client implementation to + * decide how to select the Service, e.g. random or round-robin. + */ + ServiceSelector[ServiceSelector["ANY"] = 2] = "ANY"; + /** + * EXACT - Clients SHOULD select a specific number of Services based on + * supported API version and validity window, using the provided + * `count`. It is up to the client implementation to decide how to + * select the Service, e.g. random or round-robin. + */ + ServiceSelector[ServiceSelector["EXACT"] = 3] = "EXACT"; +})(ServiceSelector || (exports.ServiceSelector = ServiceSelector = {})); +function serviceSelectorFromJSON(object) { + switch (object) { + case 0: + case "SERVICE_SELECTOR_UNDEFINED": + return ServiceSelector.SERVICE_SELECTOR_UNDEFINED; + case 1: + case "ALL": + return ServiceSelector.ALL; + case 2: + case "ANY": + return ServiceSelector.ANY; + case 3: + case "EXACT": + return ServiceSelector.EXACT; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum ServiceSelector"); + } +} +function serviceSelectorToJSON(object) { + switch (object) { + case ServiceSelector.SERVICE_SELECTOR_UNDEFINED: + return "SERVICE_SELECTOR_UNDEFINED"; + case ServiceSelector.ALL: + return "ALL"; + case ServiceSelector.ANY: + return "ANY"; + case ServiceSelector.EXACT: + return "EXACT"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum ServiceSelector"); + } } exports.TransparencyLogInstance = { fromJSON(object) { return { - baseUrl: isSet(object.baseUrl) ? String(object.baseUrl) : "", + baseUrl: isSet(object.baseUrl) ? globalThis.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, + operator: isSet(object.operator) ? globalThis.String(object.operator) : "", }; }, 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); + if (message.baseUrl !== "") { + obj.baseUrl = message.baseUrl; + } + if (message.hashAlgorithm !== 0) { + obj.hashAlgorithm = (0, sigstore_common_1.hashAlgorithmToJSON)(message.hashAlgorithm); + } + if (message.publicKey !== undefined) { + obj.publicKey = sigstore_common_1.PublicKey.toJSON(message.publicKey); + } + if (message.logId !== undefined) { + obj.logId = sigstore_common_1.LogId.toJSON(message.logId); + } + if (message.checkpointKeyId !== undefined) { + obj.checkpointKeyId = sigstore_common_1.LogId.toJSON(message.checkpointKeyId); + } + if (message.operator !== "") { + obj.operator = message.operator; + } 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) : "", + uri: isSet(object.uri) ? globalThis.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, + operator: isSet(object.operator) ? globalThis.String(object.operator) : "", }; }, 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); + if (message.subject !== undefined) { + obj.subject = sigstore_common_1.DistinguishedName.toJSON(message.subject); + } + if (message.uri !== "") { + obj.uri = message.uri; + } + if (message.certChain !== undefined) { + obj.certChain = sigstore_common_1.X509CertificateChain.toJSON(message.certChain); + } + if (message.validFor !== undefined) { + obj.validFor = sigstore_common_1.TimeRange.toJSON(message.validFor); + } + if (message.operator !== "") { + obj.operator = message.operator; + } 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) + mediaType: isSet(object.mediaType) ? globalThis.String(object.mediaType) : "", + tlogs: globalThis.Array.isArray(object?.tlogs) + ? object.tlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) + : [], + certificateAuthorities: globalThis.Array.isArray(object?.certificateAuthorities) ? object.certificateAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e)) : [], - ctlogs: Array.isArray(object?.ctlogs) + ctlogs: globalThis.Array.isArray(object?.ctlogs) ? object.ctlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) : [], - timestampAuthorities: Array.isArray(object?.timestampAuthorities) + timestampAuthorities: globalThis.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); + if (message.mediaType !== "") { + obj.mediaType = message.mediaType; + } + if (message.tlogs?.length) { + obj.tlogs = message.tlogs.map((e) => exports.TransparencyLogInstance.toJSON(e)); + } + if (message.certificateAuthorities?.length) { + obj.certificateAuthorities = message.certificateAuthorities.map((e) => exports.CertificateAuthority.toJSON(e)); + } + if (message.ctlogs?.length) { + obj.ctlogs = message.ctlogs.map((e) => exports.TransparencyLogInstance.toJSON(e)); } - else { - obj.tlogs = []; + if (message.timestampAuthorities?.length) { + obj.timestampAuthorities = message.timestampAuthorities.map((e) => exports.CertificateAuthority.toJSON(e)); + } + return obj; + }, +}; +exports.SigningConfig = { + fromJSON(object) { + return { + mediaType: isSet(object.mediaType) ? globalThis.String(object.mediaType) : "", + caUrls: globalThis.Array.isArray(object?.caUrls) ? object.caUrls.map((e) => exports.Service.fromJSON(e)) : [], + oidcUrls: globalThis.Array.isArray(object?.oidcUrls) ? object.oidcUrls.map((e) => exports.Service.fromJSON(e)) : [], + rekorTlogUrls: globalThis.Array.isArray(object?.rekorTlogUrls) + ? object.rekorTlogUrls.map((e) => exports.Service.fromJSON(e)) + : [], + rekorTlogConfig: isSet(object.rekorTlogConfig) + ? exports.ServiceConfiguration.fromJSON(object.rekorTlogConfig) + : undefined, + tsaUrls: globalThis.Array.isArray(object?.tsaUrls) ? object.tsaUrls.map((e) => exports.Service.fromJSON(e)) : [], + tsaConfig: isSet(object.tsaConfig) ? exports.ServiceConfiguration.fromJSON(object.tsaConfig) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + if (message.mediaType !== "") { + obj.mediaType = message.mediaType; } - if (message.certificateAuthorities) { - obj.certificateAuthorities = message.certificateAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined); + if (message.caUrls?.length) { + obj.caUrls = message.caUrls.map((e) => exports.Service.toJSON(e)); } - else { - obj.certificateAuthorities = []; + if (message.oidcUrls?.length) { + obj.oidcUrls = message.oidcUrls.map((e) => exports.Service.toJSON(e)); } - if (message.ctlogs) { - obj.ctlogs = message.ctlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined); + if (message.rekorTlogUrls?.length) { + obj.rekorTlogUrls = message.rekorTlogUrls.map((e) => exports.Service.toJSON(e)); } - else { - obj.ctlogs = []; + if (message.rekorTlogConfig !== undefined) { + obj.rekorTlogConfig = exports.ServiceConfiguration.toJSON(message.rekorTlogConfig); } - if (message.timestampAuthorities) { - obj.timestampAuthorities = message.timestampAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined); + if (message.tsaUrls?.length) { + obj.tsaUrls = message.tsaUrls.map((e) => exports.Service.toJSON(e)); } - else { - obj.timestampAuthorities = []; + if (message.tsaConfig !== undefined) { + obj.tsaConfig = exports.ServiceConfiguration.toJSON(message.tsaConfig); } return obj; }, }; -function createBaseSigningConfig() { - return { caUrl: "", oidcUrl: "", tlogUrls: [], tsaUrls: [] }; -} -exports.SigningConfig = { +exports.Service = { fromJSON(object) { return { - 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)) : [], + url: isSet(object.url) ? globalThis.String(object.url) : "", + majorApiVersion: isSet(object.majorApiVersion) ? globalThis.Number(object.majorApiVersion) : 0, + validFor: isSet(object.validFor) ? sigstore_common_1.TimeRange.fromJSON(object.validFor) : undefined, + operator: isSet(object.operator) ? globalThis.String(object.operator) : "", }; }, toJSON(message) { const obj = {}; - message.caUrl !== undefined && (obj.caUrl = message.caUrl); - message.oidcUrl !== undefined && (obj.oidcUrl = message.oidcUrl); - if (message.tlogUrls) { - obj.tlogUrls = message.tlogUrls.map((e) => e); + if (message.url !== "") { + obj.url = message.url; } - else { - obj.tlogUrls = []; + if (message.majorApiVersion !== 0) { + obj.majorApiVersion = Math.round(message.majorApiVersion); } - if (message.tsaUrls) { - obj.tsaUrls = message.tsaUrls.map((e) => e); + if (message.validFor !== undefined) { + obj.validFor = sigstore_common_1.TimeRange.toJSON(message.validFor); } - else { - obj.tsaUrls = []; + if (message.operator !== "") { + obj.operator = message.operator; + } + return obj; + }, +}; +exports.ServiceConfiguration = { + fromJSON(object) { + return { + selector: isSet(object.selector) ? serviceSelectorFromJSON(object.selector) : 0, + count: isSet(object.count) ? globalThis.Number(object.count) : 0, + }; + }, + toJSON(message) { + const obj = {}; + if (message.selector !== 0) { + obj.selector = serviceSelectorToJSON(message.selector); + } + if (message.count !== 0) { + obj.count = Math.round(message.count); } return obj; }, }; -function createBaseClientTrustConfig() { - return { mediaType: "", trustedRoot: undefined, signingConfig: undefined }; -} exports.ClientTrustConfig = { fromJSON(object) { return { - mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", + mediaType: isSet(object.mediaType) ? globalThis.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); + if (message.mediaType !== "") { + obj.mediaType = message.mediaType; + } + if (message.trustedRoot !== undefined) { + obj.trustedRoot = exports.TrustedRoot.toJSON(message.trustedRoot); + } + if (message.signingConfig !== undefined) { + obj.signingConfig = exports.SigningConfig.toJSON(message.signingConfig); + } return obj; }, }; diff --git a/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.js b/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.js index 4af83c5a54660..519242c96a9b2 100644 --- a/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.js +++ b/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.js @@ -1,86 +1,71 @@ "use strict"; +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v2.11.5 +// protoc v7.34.1 +// source: sigstore_verification.proto 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) : "", + issuer: isSet(object.issuer) ? globalThis.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)) : [], + oids: globalThis.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); + if (message.issuer !== "") { + obj.issuer = message.issuer; + } + if (message.san !== undefined) { + obj.san = sigstore_common_1.SubjectAlternativeName.toJSON(message.san); } - else { - obj.oids = []; + if (message.oids?.length) { + obj.oids = message.oids.map((e) => sigstore_common_1.ObjectIdentifierValuePair.toJSON(e)); } return obj; }, }; -function createBaseCertificateIdentities() { - return { identities: [] }; -} exports.CertificateIdentities = { fromJSON(object) { return { - identities: Array.isArray(object?.identities) + identities: globalThis.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 = []; + if (message.identities?.length) { + obj.identities = message.identities.map((e) => exports.CertificateIdentity.toJSON(e)); } 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)) : [], + publicKeys: globalThis.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 = []; + if (message.publicKeys?.length) { + obj.publicKeys = message.publicKeys.map((e) => sigstore_common_1.PublicKey.toJSON(e)); } return obj; }, }; -function createBaseArtifactVerificationOptions() { - return { - signers: undefined, - tlogOptions: undefined, - ctlogOptions: undefined, - tsaOptions: undefined, - integratedTsOptions: undefined, - observerOptions: undefined, - }; -} exports.ArtifactVerificationOptions = { fromJSON(object) { return { @@ -111,150 +96,152 @@ exports.ArtifactVerificationOptions = { }, 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); + if (message.signers?.$case === "certificateIdentities") { + obj.certificateIdentities = exports.CertificateIdentities.toJSON(message.signers.certificateIdentities); + } + else if (message.signers?.$case === "publicKeys") { + obj.publicKeys = exports.PublicKeyIdentities.toJSON(message.signers.publicKeys); + } + if (message.tlogOptions !== undefined) { + obj.tlogOptions = exports.ArtifactVerificationOptions_TlogOptions.toJSON(message.tlogOptions); + } + if (message.ctlogOptions !== undefined) { + obj.ctlogOptions = exports.ArtifactVerificationOptions_CtlogOptions.toJSON(message.ctlogOptions); + } + if (message.tsaOptions !== undefined) { + obj.tsaOptions = exports.ArtifactVerificationOptions_TimestampAuthorityOptions.toJSON(message.tsaOptions); + } + if (message.integratedTsOptions !== undefined) { + obj.integratedTsOptions = exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions.toJSON(message.integratedTsOptions); + } + if (message.observerOptions !== undefined) { + obj.observerOptions = exports.ArtifactVerificationOptions_ObserverTimestampOptions.toJSON(message.observerOptions); + } 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, + threshold: isSet(object.threshold) ? globalThis.Number(object.threshold) : 0, performOnlineVerification: isSet(object.performOnlineVerification) - ? Boolean(object.performOnlineVerification) + ? globalThis.Boolean(object.performOnlineVerification) : false, - disable: isSet(object.disable) ? Boolean(object.disable) : false, + disable: isSet(object.disable) ? globalThis.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); + if (message.threshold !== 0) { + obj.threshold = Math.round(message.threshold); + } + if (message.performOnlineVerification !== false) { + obj.performOnlineVerification = message.performOnlineVerification; + } + if (message.disable !== false) { + 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, + threshold: isSet(object.threshold) ? globalThis.Number(object.threshold) : 0, + disable: isSet(object.disable) ? globalThis.Boolean(object.disable) : false, }; }, toJSON(message) { const obj = {}; - message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); - message.disable !== undefined && (obj.disable = message.disable); + if (message.threshold !== 0) { + obj.threshold = Math.round(message.threshold); + } + if (message.disable !== false) { + 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, + threshold: isSet(object.threshold) ? globalThis.Number(object.threshold) : 0, + disable: isSet(object.disable) ? globalThis.Boolean(object.disable) : false, }; }, toJSON(message) { const obj = {}; - message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); - message.disable !== undefined && (obj.disable = message.disable); + if (message.threshold !== 0) { + obj.threshold = Math.round(message.threshold); + } + if (message.disable !== false) { + 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, + threshold: isSet(object.threshold) ? globalThis.Number(object.threshold) : 0, + disable: isSet(object.disable) ? globalThis.Boolean(object.disable) : false, }; }, toJSON(message) { const obj = {}; - message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); - message.disable !== undefined && (obj.disable = message.disable); + if (message.threshold !== 0) { + obj.threshold = Math.round(message.threshold); + } + if (message.disable !== false) { + 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, + threshold: isSet(object.threshold) ? globalThis.Number(object.threshold) : 0, + disable: isSet(object.disable) ? globalThis.Boolean(object.disable) : false, }; }, toJSON(message) { const obj = {}; - message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); - message.disable !== undefined && (obj.disable = message.disable); + if (message.threshold !== 0) { + obj.threshold = Math.round(message.threshold); + } + if (message.disable !== false) { + 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) } + ? { $case: "artifactUri", artifactUri: globalThis.String(object.artifactUri) } : isSet(object.artifact) ? { $case: "artifact", artifact: Buffer.from(bytesFromBase64(object.artifact)) } - : undefined, + : 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); + if (message.data?.$case === "artifactUri") { + obj.artifactUri = message.data.artifactUri; + } + else if (message.data?.$case === "artifact") { + obj.artifact = base64FromBytes(message.data.artifact); + } + else if (message.data?.$case === "artifactDigest") { + obj.artifactDigest = sigstore_common_1.HashOutput.toJSON(message.data.artifactDigest); + } return obj; }, }; -function createBaseInput() { - return { - artifactTrustRoot: undefined, - artifactVerificationOptions: undefined, - bundle: undefined, - artifact: undefined, - }; -} exports.Input = { fromJSON(object) { return { @@ -268,56 +255,26 @@ exports.Input = { }, 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); + if (message.artifactTrustRoot !== undefined) { + obj.artifactTrustRoot = sigstore_trustroot_1.TrustedRoot.toJSON(message.artifactTrustRoot); + } + if (message.artifactVerificationOptions !== undefined) { + obj.artifactVerificationOptions = exports.ArtifactVerificationOptions.toJSON(message.artifactVerificationOptions); + } + if (message.bundle !== undefined) { + obj.bundle = sigstore_bundle_1.Bundle.toJSON(message.bundle); + } + if (message.artifact !== undefined) { + obj.artifact = exports.Artifact.toJSON(message.artifact); + } 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; - } + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); } 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("")); - } + return globalThis.Buffer.from(arr).toString("base64"); } function isSet(value) { return value !== null && value !== undefined; diff --git a/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.js b/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.js new file mode 100644 index 0000000000000..10745efc39a1f --- /dev/null +++ b/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.js @@ -0,0 +1,35 @@ +"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 2025 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__/rekor/v2/dsse"), exports); +__exportStar(require("../../__generated__/rekor/v2/entry"), exports); +__exportStar(require("../../__generated__/rekor/v2/hashedrekord"), exports); +__exportStar(require("../../__generated__/rekor/v2/verifier"), exports); diff --git a/node_modules/@sigstore/protobuf-specs/package.json b/node_modules/@sigstore/protobuf-specs/package.json index 92ae4acbd00ec..bdd434efb8dbd 100644 --- a/node_modules/@sigstore/protobuf-specs/package.json +++ b/node_modules/@sigstore/protobuf-specs/package.json @@ -1,9 +1,13 @@ { "name": "@sigstore/protobuf-specs", - "version": "0.3.2", + "version": "0.5.1", "description": "code-signing for npm packages", "main": "dist/index.js", "types": "dist/index.d.ts", + "exports": { + ".": "./dist/index.js", + "./rekor/v2": "./dist/rekor/v2/index.js" + }, "scripts": { "build": "tsc" }, @@ -21,11 +25,11 @@ }, "homepage": "https://github.com/sigstore/protobuf-specs#readme", "devDependencies": { - "@tsconfig/node16": "^16.1.1", + "@tsconfig/node18": "^18.2.4", "@types/node": "^18.14.0", - "typescript": "^4.9.5" + "typescript": "^5.7.2" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^18.17.0 || >=20.5.0" } } diff --git a/node_modules/@sigstore/sign/dist/bundler/base.js b/node_modules/@sigstore/sign/dist/bundler/base.js deleted file mode 100644 index 61d5eba4568a3..0000000000000 --- a/node_modules/@sigstore/sign/dist/bundler/base.js +++ /dev/null @@ -1,50 +0,0 @@ -"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; - } -} diff --git a/node_modules/@sigstore/sign/dist/bundler/bundle.js b/node_modules/@sigstore/sign/dist/bundler/bundle.js deleted file mode 100644 index 7c2ca9164f0df..0000000000000 --- a/node_modules/@sigstore/sign/dist/bundler/bundle.js +++ /dev/null @@ -1,71 +0,0 @@ -"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.toDSSEBundle = exports.toMessageSignatureBundle = 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 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.hash(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, - }); -} -exports.toMessageSignatureBundle = toMessageSignatureBundle; -// DSSE envelope bundle - $case: 'dsseEnvelope' -function toDSSEBundle(artifact, signature, singleCertificate) { - 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, - singleCertificate, - }); -} -exports.toDSSEBundle = toDSSEBundle; diff --git a/node_modules/@sigstore/sign/dist/bundler/dsse.js b/node_modules/@sigstore/sign/dist/bundler/dsse.js deleted file mode 100644 index 621700df93842..0000000000000 --- a/node_modules/@sigstore/sign/dist/bundler/dsse.js +++ /dev/null @@ -1,46 +0,0 @@ -"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.singleCertificate = options.singleCertificate ?? 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.singleCertificate); - } -} -exports.DSSEBundleBuilder = DSSEBundleBuilder; -// Defaults the artifact type to an empty string if not provided -function artifactDefaults(artifact) { - return { - ...artifact, - type: artifact.type ?? '', - }; -} diff --git a/node_modules/@sigstore/sign/dist/error.js b/node_modules/@sigstore/sign/dist/error.js deleted file mode 100644 index d57e4567fb89e..0000000000000 --- a/node_modules/@sigstore/sign/dist/error.js +++ /dev/null @@ -1,39 +0,0 @@ -"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 = exports.InternalError = void 0; -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, - }); -} -exports.internalError = internalError; diff --git a/node_modules/@sigstore/sign/dist/external/error.js b/node_modules/@sigstore/sign/dist/external/error.js deleted file mode 100644 index a6a65adebb176..0000000000000 --- a/node_modules/@sigstore/sign/dist/external/error.js +++ /dev/null @@ -1,26 +0,0 @@ -"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; diff --git a/node_modules/@sigstore/sign/dist/external/tsa.js b/node_modules/@sigstore/sign/dist/external/tsa.js deleted file mode 100644 index a948ba9cca2c7..0000000000000 --- a/node_modules/@sigstore/sign/dist/external/tsa.js +++ /dev/null @@ -1,38 +0,0 @@ -"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; diff --git a/node_modules/@sigstore/sign/dist/index.js b/node_modules/@sigstore/sign/dist/index.js deleted file mode 100644 index 383b76083361b..0000000000000 --- a/node_modules/@sigstore/sign/dist/index.js +++ /dev/null @@ -1,17 +0,0 @@ -"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; } }); diff --git a/node_modules/@sigstore/sign/dist/signer/fulcio/index.js b/node_modules/@sigstore/sign/dist/signer/fulcio/index.js deleted file mode 100644 index 89a432548d2b4..0000000000000 --- a/node_modules/@sigstore/sign/dist/signer/fulcio/index.js +++ /dev/null @@ -1,87 +0,0 @@ -"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; diff --git a/node_modules/@sigstore/sign/dist/util/index.js b/node_modules/@sigstore/sign/dist/util/index.js deleted file mode 100644 index f467c9150c348..0000000000000 --- a/node_modules/@sigstore/sign/dist/util/index.js +++ /dev/null @@ -1,49 +0,0 @@ -"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")); diff --git a/node_modules/@sigstore/sign/dist/util/oidc.js b/node_modules/@sigstore/sign/dist/util/oidc.js deleted file mode 100644 index 2f5947d7b6b87..0000000000000 --- a/node_modules/@sigstore/sign/dist/util/oidc.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.extractJWTSubject = 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"); -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; - } -} -exports.extractJWTSubject = extractJWTSubject; diff --git a/node_modules/@sigstore/sign/dist/witness/tlog/client.js b/node_modules/@sigstore/sign/dist/witness/tlog/client.js deleted file mode 100644 index 22c895f2ca7ed..0000000000000 --- a/node_modules/@sigstore/sign/dist/witness/tlog/client.js +++ /dev/null @@ -1,61 +0,0 @@ -"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); -} diff --git a/node_modules/@sigstore/sign/dist/witness/tlog/entry.js b/node_modules/@sigstore/sign/dist/witness/tlog/entry.js deleted file mode 100644 index c237523a2c9b2..0000000000000 --- a/node_modules/@sigstore/sign/dist/witness/tlog/entry.js +++ /dev/null @@ -1,136 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toProposedEntry = 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 bundle_1 = require("@sigstore/bundle"); -const util_1 = require("../../util"); -function toProposedEntry(content, publicKey, -// TODO: Remove this parameter once have completely switched to 'dsse' entries -entryType = 'intoto') { - switch (content.$case) { - case 'dsseEnvelope': - // TODO: Remove this conditional once have completely switched to 'dsse' entries - if (entryType === 'dsse') { - return toProposedDSSEEntry(content.dsseEnvelope, publicKey); - } - return toProposedIntotoEntry(content.dsseEnvelope, publicKey); - case 'messageSignature': - return toProposedHashedRekordEntry(content.messageSignature, publicKey); - } -} -exports.toProposedEntry = toProposedEntry; -// 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', - 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.hash(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', value: envelopeHash }, - payloadHash: { algorithm: 'sha256', 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.hash(util_1.json.canonicalize(dsse)).toString('hex'); -} diff --git a/node_modules/@sigstore/sign/dist/witness/tlog/index.js b/node_modules/@sigstore/sign/dist/witness/tlog/index.js deleted file mode 100644 index 6197b09d4cdd9..0000000000000 --- a/node_modules/@sigstore/sign/dist/witness/tlog/index.js +++ /dev/null @@ -1,82 +0,0 @@ -"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, - }, - }; -} diff --git a/node_modules/@sigstore/sign/dist/witness/tsa/client.js b/node_modules/@sigstore/sign/dist/witness/tsa/client.js deleted file mode 100644 index a334deb00b775..0000000000000 --- a/node_modules/@sigstore/sign/dist/witness/tsa/client.js +++ /dev/null @@ -1,43 +0,0 @@ -"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"); -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.hash(signature).toString('base64'), - hashAlgorithm: 'sha256', - }; - try { - return await this.tsa.createTimestamp(request); - } - catch (err) { - (0, error_1.internalError)(err, 'TSA_CREATE_TIMESTAMP_ERROR', 'error creating timestamp'); - } - } -} -exports.TSAClient = TSAClient; diff --git a/node_modules/@sigstore/sign/dist/witness/tsa/index.js b/node_modules/@sigstore/sign/dist/witness/tsa/index.js deleted file mode 100644 index d4f5c7c859d10..0000000000000 --- a/node_modules/@sigstore/sign/dist/witness/tsa/index.js +++ /dev/null @@ -1,44 +0,0 @@ -"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; - } -} diff --git a/node_modules/@sigstore/sign/package.json b/node_modules/@sigstore/sign/package.json deleted file mode 100644 index 4adb3d24c6fa6..0000000000000 --- a/node_modules/@sigstore/sign/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "@sigstore/sign", - "version": "2.3.2", - "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.7.4", - "@sigstore/rekor-types": "^2.0.0", - "@types/make-fetch-happen": "^10.0.4", - "@types/promise-retry": "^1.1.6" - }, - "dependencies": { - "@sigstore/bundle": "^2.3.2", - "@sigstore/core": "^1.0.0", - "@sigstore/protobuf-specs": "^0.3.2", - "make-fetch-happen": "^13.0.1", - "proc-log": "^4.2.0", - "promise-retry": "^2.0.1" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } -} diff --git a/node_modules/@sigstore/tuf/dist/appdata.js b/node_modules/@sigstore/tuf/dist/appdata.js index c9a8ee92b531e..06a8143e70da2 100644 --- a/node_modules/@sigstore/tuf/dist/appdata.js +++ b/node_modules/@sigstore/tuf/dist/appdata.js @@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.appDataPath = void 0; +exports.appDataPath = appDataPath; /* Copyright 2023 The Sigstore Authors. @@ -41,4 +41,3 @@ function appDataPath(name) { } } } -exports.appDataPath = appDataPath; diff --git a/node_modules/@sigstore/tuf/dist/client.js b/node_modules/@sigstore/tuf/dist/client.js index 2019c1fd30f88..a170af40a0a28 100644 --- a/node_modules/@sigstore/tuf/dist/client.js +++ b/node_modules/@sigstore/tuf/dist/client.js @@ -23,9 +23,11 @@ const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const tuf_js_1 = require("tuf-js"); const _1 = require("."); +const package_json_1 = require("../package.json"); const target_1 = require("./target"); const TARGETS_DIR_NAME = 'targets'; class TUFClient { + updater; constructor(options) { const url = new URL(options.mirrorURL); const repoName = encodeURIComponent(url.host + url.pathname.replace(/\/$/, '')); @@ -63,6 +65,7 @@ function initTufCache(cachePath) { if (!fs_1.default.existsSync(cachePath)) { fs_1.default.mkdirSync(cachePath, { recursive: true }); } + /* istanbul ignore else */ if (!fs_1.default.existsSync(targetsPath)) { fs_1.default.mkdirSync(targetsPath); } @@ -74,12 +77,12 @@ 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. + /* istanbul ignore else */ if (!fs_1.default.existsSync(cachedRootPath) || forceInit) { if (tufRootPath) { fs_1.default.copyFileSync(tufRootPath, cachedRootPath); } else { - /* eslint-disable @typescript-eslint/no-var-requires */ const seeds = require('../seeds.json'); const repoSeed = seeds[mirrorURL]; if (!repoSeed) { @@ -100,6 +103,7 @@ function initClient(options) { const config = { fetchTimeout: options.timeout, fetchRetry: options.retry, + userAgent: `${encodeURIComponent(package_json_1.name)}/${package_json_1.version}`, }; return new tuf_js_1.Updater({ metadataBaseUrl: options.mirrorURL, diff --git a/node_modules/@sigstore/tuf/dist/error.js b/node_modules/@sigstore/tuf/dist/error.js index e13971b289ff2..fd1f7100166cf 100644 --- a/node_modules/@sigstore/tuf/dist/error.js +++ b/node_modules/@sigstore/tuf/dist/error.js @@ -2,6 +2,8 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.TUFError = void 0; class TUFError extends Error { + code; + cause; constructor({ code, message, cause, }) { super(message); this.code = code; diff --git a/node_modules/@sigstore/tuf/dist/index.js b/node_modules/@sigstore/tuf/dist/index.js index 678c81d45d21e..2af5de93ec5d2 100644 --- a/node_modules/@sigstore/tuf/dist/index.js +++ b/node_modules/@sigstore/tuf/dist/index.js @@ -1,6 +1,8 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.TUFError = exports.initTUF = exports.getTrustedRoot = exports.DEFAULT_MIRROR_URL = void 0; +exports.TUFError = exports.DEFAULT_MIRROR_URL = void 0; +exports.getTrustedRoot = getTrustedRoot; +exports.initTUF = initTUF; /* Copyright 2023 The Sigstore Authors. @@ -31,14 +33,12 @@ options = {}) { const trustedRoot = await client.getTarget(TRUSTED_ROOT_TARGET); return protobuf_specs_1.TrustedRoot.fromJSON(JSON.parse(trustedRoot)); } -exports.getTrustedRoot = getTrustedRoot; async function initTUF( /* istanbul ignore next */ options = {}) { const client = createClient(options); return client.refresh().then(() => client); } -exports.initTUF = initTUF; // Create a TUF client with default options function createClient(options) { /* istanbul ignore next */ diff --git a/node_modules/@sigstore/tuf/dist/target.js b/node_modules/@sigstore/tuf/dist/target.js index 29eaf99a7e721..5c6675bdfbf5f 100644 --- a/node_modules/@sigstore/tuf/dist/target.js +++ b/node_modules/@sigstore/tuf/dist/target.js @@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.readTarget = void 0; +exports.readTarget = readTarget; /* Copyright 2023 The Sigstore Authors. @@ -39,7 +39,6 @@ async function readTarget(tuf, targetPath) { }); }); } -exports.readTarget = readTarget; // 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. diff --git a/node_modules/@sigstore/tuf/package.json b/node_modules/@sigstore/tuf/package.json index b7fd34ac9674e..16bf7f75a01eb 100644 --- a/node_modules/@sigstore/tuf/package.json +++ b/node_modules/@sigstore/tuf/package.json @@ -1,6 +1,6 @@ { "name": "@sigstore/tuf", - "version": "2.3.4", + "version": "5.0.0", "description": "Client for the Sigstore TUF repository", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -28,14 +28,14 @@ }, "devDependencies": { "@sigstore/jest": "^0.0.0", - "@tufjs/repo-mock": "^2.0.1", + "@tufjs/repo-mock": "^5.0.0", "@types/make-fetch-happen": "^10.0.4" }, "dependencies": { - "@sigstore/protobuf-specs": "^0.3.2", - "tuf-js": "^2.2.1" + "@sigstore/protobuf-specs": "^0.5.0", + "tuf-js": "^6.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } } diff --git a/node_modules/@sigstore/tuf/seeds.json b/node_modules/@sigstore/tuf/seeds.json index e8d97d5fa7a67..47c66e04c775d 100644 --- a/node_modules/@sigstore/tuf/seeds.json +++ b/node_modules/@sigstore/tuf/seeds.json @@ -1 +1 @@ -{"https://tuf-repo-cdn.sigstore.dev":{"root.json":"ewoJInNpZ25lZCI6IHsKCQkiX3R5cGUiOiAicm9vdCIsCgkJInNwZWNfdmVyc2lvbiI6ICIxLjAiLAoJCSJ2ZXJzaW9uIjogOSwKCQkiZXhwaXJlcyI6ICIyMDI0LTA5LTEyVDA2OjUzOjEwWiIsCgkJImtleXMiOiB7CgkJCSIxZTFkNjVjZTk4YjEwYWRkYWQ0NzY0ZmViZjdkZGEyZDA0MzZiM2QzYTM4OTM1NzljMGRkZGFlYTIwZTU0ODQ5IjogewoJCQkJImtleXR5cGUiOiAiZWNkc2EiLAoJCQkJInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKCQkJCSJrZXlpZF9oYXNoX2FsZ29yaXRobXMiOiBbCgkJCQkJInNoYTI1NiIsCgkJCQkJInNoYTUxMiIKCQkJCV0sCgkJCQkia2V5dmFsIjogewoJCQkJCSJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXpCelZPbUhDUG9qTVZMU0kzNjRXaWlWOE5QckRcbjZJZ1J4Vmxpc2t6L3YreTNKRVI1bWNWR2NPTmxpRGNXTUM1SjJsZkhtalBOUGhiNEg3eG04THpmU0E9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCgkJCQl9CgkJCX0sCgkJCSIyMzBlMjEyNjE2Mjc0YTQxOTVjZGMyOGU5ZmNlNzgyYzIwZTZjNzIwZjFhODExYjQwZjk4MjI4Mzc2YmRkM2FjIjogewoJCQkJImtleXR5cGUiOiAiZWNkc2EiLAoJCQkJInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKCQkJCSJrZXlpZF9oYXNoX2FsZ29yaXRobXMiOiBbCgkJCQkJInNoYTI1NiIsCgkJCQkJInNoYTUxMiIKCQkJCV0sCgkJCQkia2V5dmFsIjogewoJCQkJCSJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRUxyV3ZOdDk0djRSMDg1RUxlZUNNeEhwN1BsZEZcbjAvVDFHeHVrVWgyT0R1Z2dMR0pFMHBjMWU4Q1NCZjZDUzkxRndvOUZVT3VSc2pCVWxkK1ZxU3lDZFE9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCgkJCQl9CgkJCX0sCgkJCSIzYzM0NGFhMDY4ZmQ0Y2M0ZTg3ZGM1MGI2MTJjMDI0MzFmYmM3NzFlOTUwMDM5OTM2ODNhMmIwYmYyNjBjZjBlIjogewoJCQkJImtleXR5cGUiOiAiZWNkc2EiLAoJCQkJInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKCQkJCSJrZXlpZF9oYXNoX2FsZ29yaXRobXMiOiBbCgkJCQkJInNoYTI1NiIsCgkJCQkJInNoYTUxMiIKCQkJCV0sCgkJCQkia2V5dmFsIjogewoJCQkJCSJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXk4WEtzbWhCWURJOEpjMEd3ekJ4ZUtheDBjbTVcblNUS0VVNjVIUEZ1blVuNDFzVDhwaTBGak00SWtIei9ZVW13bUxVTzBXdDdseGhqNkJrTElLNHFZQXc9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCgkJCQl9CgkJCX0sCgkJCSI5MjNiYjM5ZTYwZGQ2ZmEyYzMxZTZlYTU1NDczYWE5M2I2NGRkNGU1M2UxNmZiZTQyZjZhMjA3ZDNmOTdkZTJkIjogewoJCQkJImtleXR5cGUiOiAiZWNkc2EiLAoJCQkJInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKCQkJCSJrZXlpZF9oYXNoX2FsZ29yaXRobXMiOiBbCgkJCQkJInNoYTI1NiIsCgkJCQkJInNoYTUxMiIKCQkJCV0sCgkJCQkia2V5dmFsIjogewoJCQkJCSJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRVdSaUdyNStqKzNKNVNzSCtadHI1bkUySDJ3TzdcbkJWK25PM3M5M2dMY2ExOHFUT3pIWTFvV3lBR0R5a01Tc0dUVUJTdDlEK0FuMEtmS3NEMm1mU000MlE9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCgkJCQl9CgkJCX0sCgkJCSJlMmY1OWFjYjk0ODg1MTk0MDdlMThjYmZjOTMyOTUxMGJlMDNjMDRhY2E5OTI5ZDJmMDMwMTM0M2ZlYzg1NTIzIjogewoJCQkJImtleXR5cGUiOiAiZWNkc2EiLAoJCQkJInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKCQkJCSJrZXlpZF9oYXNoX2FsZ29yaXRobXMiOiBbCgkJCQkJInNoYTI1NiIsCgkJCQkJInNoYTUxMiIKCQkJCV0sCgkJCQkia2V5dmFsIjogewoJCQkJCSJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRWluaWtTc0FRbVlrTmVINWVZcS9Dbkl6TGFhY09cbnhsU2Fhd1FET3dxS3kvdENxeHE1eHhQU0pjMjFLNFdJaHM5R3lPa0tmenVlWTNHSUx6Y01KWjRjV3c9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCgkJCQl9CgkJCX0sCgkJCSJlYzgxNjY5NzM0ZTAxNzk5NmM1Yjg1ZjNkMDJjM2RlMWRkNDYzN2ExNTIwMTlmZTFhZjEyNWQyZjkzNjhiOTVlIjogewoJCQkJImtleXR5cGUiOiAiZWNkc2EiLAoJCQkJInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKCQkJCSJrZXlpZF9oYXNoX2FsZ29yaXRobXMiOiBbCgkJCQkJInNoYTI1NiIsCgkJCQkJInNoYTUxMiIKCQkJCV0sCgkJCQkia2V5dmFsIjogewoJCQkJCSJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRUVYc3ozU1pYRmI4ak1WNDJqNnBKbHlqYmpSOEtcbk4zQndvY2V4cTZMTUliNXFzV0tPUXZMTjE2TlVlZkxjNEhzd09vdW1Sc1ZWYWFqU3BRUzZmb2JrUnc9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCgkJCQl9CgkJCX0sCgkJCSJmZGZhODNhMDdiNWE4MzU4OWI4N2RlZDQxZjc3ZjM5ZDIzMmFkOTFmN2NjZTUyODY4ZGFjZDA2YmEwODk4NDlmIjogewoJCQkJImtleXR5cGUiOiAiZWNkc2EiLAoJCQkJInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKCQkJCSJrZXlpZF9oYXNoX2FsZ29yaXRobXMiOiBbCgkJCQkJInNoYTI1NiIsCgkJCQkJInNoYTUxMiIKCQkJCV0sCgkJCQkia2V5dmFsIjogewoJCQkJCSJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTBnaHJoOTJMdzFZcjNpZEdWNVdxQ3RNREI4Q3hcbitEOGhkQzR3MlpMTklwbFZSb1ZHTHNrWWEzZ2hlTXlPamlKOGtQaTE1YVEyLy83UCtvajdVdkpQR3c9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCgkJCQl9CgkJCX0KCQl9LAoJCSJyb2xlcyI6IHsKCQkJInJvb3QiOiB7CgkJCQkia2V5aWRzIjogWwoJCQkJCSIzYzM0NGFhMDY4ZmQ0Y2M0ZTg3ZGM1MGI2MTJjMDI0MzFmYmM3NzFlOTUwMDM5OTM2ODNhMmIwYmYyNjBjZjBlIiwKCQkJCQkiZWM4MTY2OTczNGUwMTc5OTZjNWI4NWYzZDAyYzNkZTFkZDQ2MzdhMTUyMDE5ZmUxYWYxMjVkMmY5MzY4Yjk1ZSIsCgkJCQkJIjFlMWQ2NWNlOThiMTBhZGRhZDQ3NjRmZWJmN2RkYTJkMDQzNmIzZDNhMzg5MzU3OWMwZGRkYWVhMjBlNTQ4NDkiLAoJCQkJCSJlMmY1OWFjYjk0ODg1MTk0MDdlMThjYmZjOTMyOTUxMGJlMDNjMDRhY2E5OTI5ZDJmMDMwMTM0M2ZlYzg1NTIzIiwKCQkJCQkiZmRmYTgzYTA3YjVhODM1ODliODdkZWQ0MWY3N2YzOWQyMzJhZDkxZjdjY2U1Mjg2OGRhY2QwNmJhMDg5ODQ5ZiIKCQkJCV0sCgkJCQkidGhyZXNob2xkIjogMwoJCQl9LAoJCQkic25hcHNob3QiOiB7CgkJCQkia2V5aWRzIjogWwoJCQkJCSIyMzBlMjEyNjE2Mjc0YTQxOTVjZGMyOGU5ZmNlNzgyYzIwZTZjNzIwZjFhODExYjQwZjk4MjI4Mzc2YmRkM2FjIgoJCQkJXSwKCQkJCSJ0aHJlc2hvbGQiOiAxCgkJCX0sCgkJCSJ0YXJnZXRzIjogewoJCQkJImtleWlkcyI6IFsKCQkJCQkiM2MzNDRhYTA2OGZkNGNjNGU4N2RjNTBiNjEyYzAyNDMxZmJjNzcxZTk1MDAzOTkzNjgzYTJiMGJmMjYwY2YwZSIsCgkJCQkJImVjODE2Njk3MzRlMDE3OTk2YzViODVmM2QwMmMzZGUxZGQ0NjM3YTE1MjAxOWZlMWFmMTI1ZDJmOTM2OGI5NWUiLAoJCQkJCSIxZTFkNjVjZTk4YjEwYWRkYWQ0NzY0ZmViZjdkZGEyZDA0MzZiM2QzYTM4OTM1NzljMGRkZGFlYTIwZTU0ODQ5IiwKCQkJCQkiZTJmNTlhY2I5NDg4NTE5NDA3ZTE4Y2JmYzkzMjk1MTBiZTAzYzA0YWNhOTkyOWQyZjAzMDEzNDNmZWM4NTUyMyIsCgkJCQkJImZkZmE4M2EwN2I1YTgzNTg5Yjg3ZGVkNDFmNzdmMzlkMjMyYWQ5MWY3Y2NlNTI4NjhkYWNkMDZiYTA4OTg0OWYiCgkJCQldLAoJCQkJInRocmVzaG9sZCI6IDMKCQkJfSwKCQkJInRpbWVzdGFtcCI6IHsKCQkJCSJrZXlpZHMiOiBbCgkJCQkJIjkyM2JiMzllNjBkZDZmYTJjMzFlNmVhNTU0NzNhYTkzYjY0ZGQ0ZTUzZTE2ZmJlNDJmNmEyMDdkM2Y5N2RlMmQiCgkJCQldLAoJCQkJInRocmVzaG9sZCI6IDEKCQkJfQoJCX0sCgkJImNvbnNpc3RlbnRfc25hcHNob3QiOiB0cnVlCgl9LAoJInNpZ25hdHVyZXMiOiBbCgkJewoJCQkia2V5aWQiOiAiZmY1MWUxN2ZjZjI1MzExOWI3MDMzZjZmNTc1MTI2MzFkYTRhMDk2OTQ0MmFmY2Y5ZmM4YjE0MWM3ZjJiZTk5YyIsCgkJCSJzaWciOiAiMzA0NTAyMjEwMDhiNzhmODk0YzNjZmVkM2JkNDg2Mzc5YzRlMGUwZGZiM2U3ZGQ4Y2JjNGQ1NTk4ZDI4MThlZWExYmEzYzc1NTAwMjIwMjlkM2QwNmU4OWQwNGQzNzg0OTk4NWRjNDZjMGUxMGRjNWIxZmM2OGRjNzBhZjFlYzk5MTAzMDNhMWYzZWUyZiIKCQl9LAoJCXsKCQkJImtleWlkIjogIjI1YTBlYjQ1MGZkM2VlMmJkNzkyMThjOTYzZGNlM2YxY2M2MTE4YmFkZjI1MWJmMTQ5ZjBiZDA3ZDVjYWJlOTkiLAoJCQkic2lnIjogIjMwNDUwMjIxMDA5ZTZiOTBiOTM1ZTA5YjgzN2E5MGQ0NDAyZWFhMjdkNWVhMjZlYjc4OTE5NDhiYTBlZDcwOTA4NDEyNDhmNDM2MDIyMDAzZGMyMjUxYzRkNGE3OTk5YjkxZTlhZDA4Njg3NjVhZTA5YWM3MjY5Mjc5ZjJhNzg5OWJhZmVmN2EyZDkyNjAiCgkJfSwKCQl7CgkJCSJrZXlpZCI6ICJmNTMxMmY1NDJjMjEyNzNkOTQ4NWE0OTM5NDM4NmM0NTc1ODA0NzcwNjY3ZjJkZGI1OWIzYmYwNjY5ZmRkZDJmIiwKCQkJInNpZyI6ICIzMDQ0MDIyMDA5OWU5MDdkY2Y5MGI3YjZlMTA5ZmQxZDZlNDQyMDA2ZmNjYmI0ODg5NGFhYWZmNDdhYjgyNGIwM2ZiMzVkMGQwMjIwMmFhMGEwNmMyMWE0MjMzZjM3OTAwYTQ4YmM4Nzc3ZDNiNDdmNTllM2EzODYxNmNlNjMxYTA0ZGY1N2Y5NjczNiIKCQl9LAoJCXsKCQkJImtleWlkIjogIjNjMzQ0YWEwNjhmZDRjYzRlODdkYzUwYjYxMmMwMjQzMWZiYzc3MWU5NTAwMzk5MzY4M2EyYjBiZjI2MGNmMGUiLAoJCQkic2lnIjogIjMwNDUwMjIxMDA4Yjc4Zjg5NGMzY2ZlZDNiZDQ4NjM3OWM0ZTBlMGRmYjNlN2RkOGNiYzRkNTU5OGQyODE4ZWVhMWJhM2M3NTUwMDIyMDI5ZDNkMDZlODlkMDRkMzc4NDk5ODVkYzQ2YzBlMTBkYzViMWZjNjhkYzcwYWYxZWM5OTEwMzAzYTFmM2VlMmYiCgkJfSwKCQl7CgkJCSJrZXlpZCI6ICJlYzgxNjY5NzM0ZTAxNzk5NmM1Yjg1ZjNkMDJjM2RlMWRkNDYzN2ExNTIwMTlmZTFhZjEyNWQyZjkzNjhiOTVlIiwKCQkJInNpZyI6ICIzMDQ1MDIyMTAwOWU2YjkwYjkzNWUwOWI4MzdhOTBkNDQwMmVhYTI3ZDVlYTI2ZWI3ODkxOTQ4YmEwZWQ3MDkwODQxMjQ4ZjQzNjAyMjAwM2RjMjI1MWM0ZDRhNzk5OWI5MWU5YWQwODY4NzY1YWUwOWFjNzI2OTI3OWYyYTc4OTliYWZlZjdhMmQ5MjYwIgoJCX0sCgkJewoJCQkia2V5aWQiOiAiZTJmNTlhY2I5NDg4NTE5NDA3ZTE4Y2JmYzkzMjk1MTBiZTAzYzA0YWNhOTkyOWQyZjAzMDEzNDNmZWM4NTUyMyIsCgkJCSJzaWciOiAiMzA0NTAyMjAwZTU2MTNiOTAxZTBmM2UwOGVjZWFiZGRjNzNmOThiNTBkZGY4OTJlOTk4ZDBiMzY5YzZlM2Q0NTFhYzQ4ODc1MDIyMTAwOTQwY2Y5MmQxZjQzZWUyZTVjZGJiMjI1NzJiYjUyOTI1ZWQzODYzYTY4OGY3ZmZkZDRiZDJlMmU1NmYwMjhiMyIKCQl9LAoJCXsKCQkJImtleWlkIjogIjJlNjFjZDBjYmY0YThmNDU4MDliZGE5ZjdmNzhjMGQzM2FkMTE4NDJmZjk0YWUzNDA4NzNlMjY2NGRjODQzZGUiLAoJCQkic2lnIjogIjMwNDUwMjIwMmNmZjQ0ZjIyMTVkN2E0N2IyOGI4ZjVmNTgwYzJjZmJiZDFiZmNmY2JiZTc4ZGUzMjMwNDViMmMwYmFkYzVlOTAyMjEwMGM3NDM5NDllYjNmNGVhNWE0YjlhZTI3YWM2ZWRkZWExZjBmZjliZmQwMDRmOGE5YTlkMThjNmU0MTQyYjZlNzUiCgkJfSwKCQl7CgkJCSJrZXlpZCI6ICIxZTFkNjVjZTk4YjEwYWRkYWQ0NzY0ZmViZjdkZGEyZDA0MzZiM2QzYTM4OTM1NzljMGRkZGFlYTIwZTU0ODQ5IiwKCQkJInNpZyI6ICIzMDQ0MDIyMDA5OWU5MDdkY2Y5MGI3YjZlMTA5ZmQxZDZlNDQyMDA2ZmNjYmI0ODg5NGFhYWZmNDdhYjgyNGIwM2ZiMzVkMGQwMjIwMmFhMGEwNmMyMWE0MjMzZjM3OTAwYTQ4YmM4Nzc3ZDNiNDdmNTllM2EzODYxNmNlNjMxYTA0ZGY1N2Y5NjczNiIKCQl9LAoJCXsKCQkJImtleWlkIjogImZkZmE4M2EwN2I1YTgzNTg5Yjg3ZGVkNDFmNzdmMzlkMjMyYWQ5MWY3Y2NlNTI4NjhkYWNkMDZiYTA4OTg0OWYiLAoJCQkic2lnIjogIjMwNDUwMjIwMmNmZjQ0ZjIyMTVkN2E0N2IyOGI4ZjVmNTgwYzJjZmJiZDFiZmNmY2JiZTc4ZGUzMjMwNDViMmMwYmFkYzVlOTAyMjEwMGM3NDM5NDllYjNmNGVhNWE0YjlhZTI3YWM2ZWRkZWExZjBmZjliZmQwMDRmOGE5YTlkMThjNmU0MTQyYjZlNzUiCgkJfSwKCQl7CgkJCSJrZXlpZCI6ICI3Zjc1MTNiMjU0MjlhNjQ0NzNlMTBjZTNhZDJmM2RhMzcyYmJkZDE0YjY1ZDA3YmJhZjU0N2U3YzhiYmJlNjJiIiwKCQkJInNpZyI6ICIzMDQ1MDIyMDBlNTYxM2I5MDFlMGYzZTA4ZWNlYWJkZGM3M2Y5OGI1MGRkZjg5MmU5OThkMGIzNjljNmUzZDQ1MWFjNDg4NzUwMjIxMDA5NDBjZjkyZDFmNDNlZTJlNWNkYmIyMjU3MmJiNTI5MjVlZDM4NjNhNjg4ZjdmZmRkNGJkMmUyZTU2ZjAyOGIzIgoJCX0KCV0KfQ==","targets":{"trusted_root.json":"ewogICJtZWRpYVR5cGUiOiAiYXBwbGljYXRpb24vdm5kLmRldi5zaWdzdG9yZS50cnVzdGVkcm9vdCtqc29uO3ZlcnNpb249MC4xIiwKICAidGxvZ3MiOiBbCiAgICB7CiAgICAgICJiYXNlVXJsIjogImh0dHBzOi8vcmVrb3Iuc2lnc3RvcmUuZGV2IiwKICAgICAgImhhc2hBbGdvcml0aG0iOiAiU0hBMl8yNTYiLAogICAgICAicHVibGljS2V5IjogewogICAgICAgICJyYXdCeXRlcyI6ICJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUUyRzJZKzJ0YWJkVFY1QmNHaUJJeDBhOWZBRndya0JibUxTR3RrczRMM3FYNnlZWTB6dWZCbmhDOFVyL2l5NTVHaFdQLzlBL2JZMkxoQzMwTTkrUll0dz09IiwKICAgICAgICAia2V5RGV0YWlscyI6ICJQS0lYX0VDRFNBX1AyNTZfU0hBXzI1NiIsCiAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgInN0YXJ0IjogIjIwMjEtMDEtMTJUMTE6NTM6MjcuMDAwWiIKICAgICAgICB9CiAgICAgIH0sCiAgICAgICJsb2dJZCI6IHsKICAgICAgICAia2V5SWQiOiAid05JOWF0UUdseitWV2ZPNkxSeWdINFFVZlkvOFc0UkZ3aVQ1aTVXUmdCMD0iCiAgICAgIH0KICAgIH0KICBdLAogICJjZXJ0aWZpY2F0ZUF1dGhvcml0aWVzIjogWwogICAgewogICAgICAic3ViamVjdCI6IHsKICAgICAgICAib3JnYW5pemF0aW9uIjogInNpZ3N0b3JlLmRldiIsCiAgICAgICAgImNvbW1vbk5hbWUiOiAic2lnc3RvcmUiCiAgICAgIH0sCiAgICAgICJ1cmkiOiAiaHR0cHM6Ly9mdWxjaW8uc2lnc3RvcmUuZGV2IiwKICAgICAgImNlcnRDaGFpbiI6IHsKICAgICAgICAiY2VydGlmaWNhdGVzIjogWwogICAgICAgICAgewogICAgICAgICAgICAicmF3Qnl0ZXMiOiAiTUlJQitEQ0NBWDZnQXdJQkFnSVROVmtEWm9DaW9mUERzeTdkZm02Z2VMYnVoekFLQmdncWhrak9QUVFEQXpBcU1SVXdFd1lEVlFRS0V3eHphV2R6ZEc5eVpTNWtaWFl4RVRBUEJnTlZCQU1UQ0hOcFozTjBiM0psTUI0WERUSXhNRE13TnpBek1qQXlPVm9YRFRNeE1ESXlNekF6TWpBeU9Wb3dLakVWTUJNR0ExVUVDaE1NYzJsbmMzUnZjbVV1WkdWMk1SRXdEd1lEVlFRREV3aHphV2R6ZEc5eVpUQjJNQkFHQnlxR1NNNDlBZ0VHQlN1QkJBQWlBMklBQkxTeUE3SWk1aytwTk84WkVXWTB5bGVtV0Rvd09rTmEza0wrR1pFNVo1R1dlaEw5L0E5YlJOQTNSYnJzWjVpMEpjYXN0YVJMN1NwNWZwL2pENWR4cWMvVWRUVm5sdlMxNmFuKzJZZnN3ZS9RdUxvbFJVQ3JjT0UyKzJpQTUrdHpkNk5tTUdRd0RnWURWUjBQQVFIL0JBUURBZ0VHTUJJR0ExVWRFd0VCL3dRSU1BWUJBZjhDQVFFd0hRWURWUjBPQkJZRUZNakZIUUJCbWlRcE1sRWs2dzJ1U3UxS0J0UHNNQjhHQTFVZEl3UVlNQmFBRk1qRkhRQkJtaVFwTWxFazZ3MnVTdTFLQnRQc01Bb0dDQ3FHU000OUJBTURBMmdBTUdVQ01IOGxpV0pmTXVpNnZYWEJoakRnWTRNd3NsbU4vVEp4VmUvODNXckZvbXdtTmYwNTZ5MVg0OEY5YzRtM2Ezb3pYQUl4QUtqUmF5NS9hai9qc0tLR0lrbVFhdGpJOHV1cEhyLytDeEZ2YUpXbXBZcU5rTERHUlUrOW9yemg1aEkyUnJjdWFRPT0iCiAgICAgICAgICB9CiAgICAgICAgXQogICAgICB9LAogICAgICAidmFsaWRGb3IiOiB7CiAgICAgICAgInN0YXJ0IjogIjIwMjEtMDMtMDdUMDM6MjA6MjkuMDAwWiIsCiAgICAgICAgImVuZCI6ICIyMDIyLTEyLTMxVDIzOjU5OjU5Ljk5OVoiCiAgICAgIH0KICAgIH0sCiAgICB7CiAgICAgICJzdWJqZWN0IjogewogICAgICAgICJvcmdhbml6YXRpb24iOiAic2lnc3RvcmUuZGV2IiwKICAgICAgICAiY29tbW9uTmFtZSI6ICJzaWdzdG9yZSIKICAgICAgfSwKICAgICAgInVyaSI6ICJodHRwczovL2Z1bGNpby5zaWdzdG9yZS5kZXYiLAogICAgICAiY2VydENoYWluIjogewogICAgICAgICJjZXJ0aWZpY2F0ZXMiOiBbCiAgICAgICAgICB7CiAgICAgICAgICAgICJyYXdCeXRlcyI6ICJNSUlDR2pDQ0FhR2dBd0lCQWdJVUFMblZpVmZuVTBickphc21Sa0hybi9VbmZhUXdDZ1lJS29aSXpqMEVBd013S2pFVk1CTUdBMVVFQ2hNTWMybG5jM1J2Y21VdVpHVjJNUkV3RHdZRFZRUURFd2h6YVdkemRHOXlaVEFlRncweU1qQTBNVE15TURBMk1UVmFGdzB6TVRFd01EVXhNelUyTlRoYU1EY3hGVEFUQmdOVkJBb1RESE5wWjNOMGIzSmxMbVJsZGpFZU1Cd0dBMVVFQXhNVmMybG5jM1J2Y21VdGFXNTBaWEp0WldScFlYUmxNSFl3RUFZSEtvWkl6ajBDQVFZRks0RUVBQ0lEWWdBRThSVlMveXNIK05PdnVEWnlQSVp0aWxnVUY5TmxhcllwQWQ5SFAxdkJCSDFVNUNWNzdMU1M3czBaaUg0bkU3SHY3cHRTNkx2dlIvU1RrNzk4TFZnTXpMbEo0SGVJZkYzdEhTYWV4TGNZcFNBU3Ixa1MwTi9SZ0JKei85aldDaVhubzNzd2VUQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0V3WURWUjBsQkF3d0NnWUlLd1lCQlFVSEF3TXdFZ1lEVlIwVEFRSC9CQWd3QmdFQi93SUJBREFkQmdOVkhRNEVGZ1FVMzlQcHoxWWtFWmI1cU5qcEtGV2l4aTRZWkQ4d0h3WURWUjBqQkJnd0ZvQVVXTUFlWDVGRnBXYXBlc3lRb1pNaTBDckZ4Zm93Q2dZSUtvWkl6ajBFQXdNRFp3QXdaQUl3UENzUUs0RFlpWllEUElhRGk1SEZLbmZ4WHg2QVNTVm1FUmZzeW5ZQmlYMlg2U0pSblpVODQvOURaZG5GdnZ4bUFqQk90NlFwQmxjNEovMER4dmtUQ3FwY2x2emlMNkJDQ1BuamRsSUIzUHUzQnhzUG15Z1VZN0lpMnpiZENkbGlpb3c9IgogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgInJhd0J5dGVzIjogIk1JSUI5ekNDQVh5Z0F3SUJBZ0lVQUxaTkFQRmR4SFB3amVEbG9Ed3lZQ2hBTy80d0NnWUlLb1pJemowRUF3TXdLakVWTUJNR0ExVUVDaE1NYzJsbmMzUnZjbVV1WkdWMk1SRXdEd1lEVlFRREV3aHphV2R6ZEc5eVpUQWVGdzB5TVRFd01EY3hNelUyTlRsYUZ3MHpNVEV3TURVeE16VTJOVGhhTUNveEZUQVRCZ05WQkFvVERITnBaM04wYjNKbExtUmxkakVSTUE4R0ExVUVBeE1JYzJsbmMzUnZjbVV3ZGpBUUJnY3Foa2pPUFFJQkJnVXJnUVFBSWdOaUFBVDdYZUZUNHJiM1BRR3dTNElhanRMazMvT2xucGdhbmdhQmNsWXBzWUJyNWkrNHluQjA3Y2ViM0xQME9JT1pkeGV4WDY5YzVpVnV5SlJRK0h6MDV5aStVRjN1QldBbEhwaVM1c2gwK0gyR0hFN1NYcmsxRUM1bTFUcjE5TDlnZzkyall6QmhNQTRHQTFVZER3RUIvd1FFQXdJQkJqQVBCZ05WSFJNQkFmOEVCVEFEQVFIL01CMEdBMVVkRGdRV0JCUll3QjVma1VXbFpxbDZ6SkNoa3lMUUtzWEYrakFmQmdOVkhTTUVHREFXZ0JSWXdCNWZrVVdsWnFsNnpKQ2hreUxRS3NYRitqQUtCZ2dxaGtqT1BRUURBd05wQURCbUFqRUFqMW5IZVhacCsxM05XQk5hK0VEc0RQOEcxV1dnMXRDTVdQL1dIUHFwYVZvMGpoc3dlTkZaZ1NzMGVFN3dZSTRxQWpFQTJXQjlvdDk4c0lrb0YzdlpZZGQzL1Z0V0I1YjlUTk1lYTdJeC9zdEo1VGZjTExlQUJMRTRCTkpPc1E0dm5CSEoiCiAgICAgICAgICB9CiAgICAgICAgXQogICAgICB9LAogICAgICAidmFsaWRGb3IiOiB7CiAgICAgICAgInN0YXJ0IjogIjIwMjItMDQtMTNUMjA6MDY6MTUuMDAwWiIKICAgICAgfQogICAgfQogIF0sCiAgImN0bG9ncyI6IFsKICAgIHsKICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly9jdGZlLnNpZ3N0b3JlLmRldi90ZXN0IiwKICAgICAgImhhc2hBbGdvcml0aG0iOiAiU0hBMl8yNTYiLAogICAgICAicHVibGljS2V5IjogewogICAgICAgICJyYXdCeXRlcyI6ICJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUViZndSK1JKdWRYc2NnUkJScEtYMVhGRHkzUHl1ZER4ei9TZm5SaTFmVDhla3BmQmQyTzF1b3o3anIzWjhuS3p4QTY5RVVRK2VGQ0ZJM3pldWJQV1U3dz09IiwKICAgICAgICAia2V5RGV0YWlscyI6ICJQS0lYX0VDRFNBX1AyNTZfU0hBXzI1NiIsCiAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgInN0YXJ0IjogIjIwMjEtMDMtMTRUMDA6MDA6MDAuMDAwWiIsCiAgICAgICAgICAiZW5kIjogIjIwMjItMTAtMzFUMjM6NTk6NTkuOTk5WiIKICAgICAgICB9CiAgICAgIH0sCiAgICAgICJsb2dJZCI6IHsKICAgICAgICAia2V5SWQiOiAiQ0dDUzhDaFMvMmhGMGRGcko0U2NSV2NZckJZOXd6alNiZWE4SWdZMmIzST0iCiAgICAgIH0KICAgIH0sCiAgICB7CiAgICAgICJiYXNlVXJsIjogImh0dHBzOi8vY3RmZS5zaWdzdG9yZS5kZXYvMjAyMiIsCiAgICAgICJoYXNoQWxnb3JpdGhtIjogIlNIQTJfMjU2IiwKICAgICAgInB1YmxpY0tleSI6IHsKICAgICAgICAicmF3Qnl0ZXMiOiAiTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFaVBTbEZpMENtRlRmRWpDVXFGOUh1Q0VjWVhOS0FhWWFsSUptQlo4eXllelBqVHFoeHJLQnBNbmFvY1Z0TEpCSTFlTTN1WG5RelFHQUpkSjRnczlGeXc9PSIsCiAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICJ2YWxpZEZvciI6IHsKICAgICAgICAgICJzdGFydCI6ICIyMDIyLTEwLTIwVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgfQogICAgICB9LAogICAgICAibG9nSWQiOiB7CiAgICAgICAgImtleUlkIjogIjNUMHdhc2JIRVRKakdSNGNtV2MzQXFKS1hyamVQSzMvaDRweWdDOHA3bzQ9IgogICAgICB9CiAgICB9CiAgXSwKICAidGltZXN0YW1wQXV0aG9yaXRpZXMiOiBbCiAgICB7CiAgICAgICJzdWJqZWN0IjogewogICAgICAgICJvcmdhbml6YXRpb24iOiAiR2l0SHViLCBJbmMuIiwKICAgICAgICAiY29tbW9uTmFtZSI6ICJJbnRlcm5hbCBTZXJ2aWNlcyBSb290IgogICAgICB9LAogICAgICAiY2VydENoYWluIjogewogICAgICAgICJjZXJ0aWZpY2F0ZXMiOiBbCiAgICAgICAgICB7CiAgICAgICAgICAgICJyYXdCeXRlcyI6ICJNSUlCM0RDQ0FXS2dBd0lCQWdJVWNoa05zSDM2WGEwNGIxTHFJYytxcjlEVmVjTXdDZ1lJS29aSXpqMEVBd013TWpFVk1CTUdBMVVFQ2hNTVIybDBTSFZpTENCSmJtTXVNUmt3RndZRFZRUURFeEJVVTBFZ2FXNTBaWEp0WldScFlYUmxNQjRYRFRJek1EUXhOREF3TURBd01Gb1hEVEkwTURReE16QXdNREF3TUZvd01qRVZNQk1HQTFVRUNoTU1SMmwwU0hWaUxDQkpibU11TVJrd0Z3WURWUVFERXhCVVUwRWdWR2x0WlhOMFlXMXdhVzVuTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFVUQ1Wk5iU3FZTWQ2cjhxcE9PRVg5aWJHblpUOUdzdVhPaHIvZjhVOUZKdWdCR0V4S1lwNDBPVUxTMGVyalpXN3hWOXhWNTJObkpmNU9lRHE0ZTVaS3FOV01GUXdEZ1lEVlIwUEFRSC9CQVFEQWdlQU1CTUdBMVVkSlFRTU1Bb0dDQ3NHQVFVRkJ3TUlNQXdHQTFVZEV3RUIvd1FDTUFBd0h3WURWUjBqQkJnd0ZvQVVhVzFSdWRPZ1Z0MGxlcVkwV0tZYnVQcjQ3d0F3Q2dZSUtvWkl6ajBFQXdNRGFBQXdaUUl3YlVIOUh2RDRlakNaSk9XUW5xQWxrcVVSbGx2dTlNOCtWcUxiaVJLK3pTZlpDWndzaWxqUm44TVFRUlNrWEVFNUFqRUFnK1Z4cXRvamZWZnU4RGh6emhDeDlHS0VUYkpIYjE5aVY3Mm1NS1ViREFGbXpaNmJROGI1NFpiOHRpZHk1YVdlIgogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgInJhd0J5dGVzIjogIk1JSUNFRENDQVpXZ0F3SUJBZ0lVWDhaTzVRWFA3dk40ZE1RNWU5c1UzbnViOE9nd0NnWUlLb1pJemowRUF3TXdPREVWTUJNR0ExVUVDaE1NUjJsMFNIVmlMQ0JKYm1NdU1SOHdIUVlEVlFRREV4WkpiblJsY201aGJDQlRaWEoyYVdObGN5QlNiMjkwTUI0WERUSXpNRFF4TkRBd01EQXdNRm9YRFRJNE1EUXhNakF3TURBd01Gb3dNakVWTUJNR0ExVUVDaE1NUjJsMFNIVmlMQ0JKYm1NdU1Sa3dGd1lEVlFRREV4QlVVMEVnYVc1MFpYSnRaV1JwWVhSbE1IWXdFQVlIS29aSXpqMENBUVlGSzRFRUFDSURZZ0FFdk1MWS9kVFZidklKWUFOQXVzekV3Sm5RRTFsbGZ0eW55TUtJTWhoNDhIbXFiVnI1eWd5YnpzTFJMVktiQldPZFoyMWFlSnorZ1ppeXRaZXRxY3lGOVdsRVI1TkVNZjZKVjdaTm9qUXB4SHE0UkhHb0dTY2VRdi9xdlRpWnhFREtvMll3WkRBT0JnTlZIUThCQWY4RUJBTUNBUVl3RWdZRFZSMFRBUUgvQkFnd0JnRUIvd0lCQURBZEJnTlZIUTRFRmdRVWFXMVJ1ZE9nVnQwbGVxWTBXS1lidVByNDd3QXdId1lEVlIwakJCZ3dGb0FVOU5ZWWxvYm5BRzRjMC9xanh5SC9scS93eitRd0NnWUlLb1pJemowRUF3TURhUUF3WmdJeEFLMUIxODV5Z0NySVlGbElzM0dqc3dqbndTTUc2TFk4d29MVmRha0tEWnhWYThmOGNxTXMxRGhjeEowKzA5dzk1UUl4QU8rdEJ6Wms3dmpVSjlpSmdENFI2WldUeFFXS3FObTc0ak85OW8rbzlzdjRGSS9TWlRaVEZ5TW4wSUpFSGRObXlBPT0iCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAicmF3Qnl0ZXMiOiAiTUlJQjlEQ0NBWHFnQXdJQkFnSVVhL0pBa2RVaks0SlV3c3F0YWlSSkdXaHFMU293Q2dZSUtvWkl6ajBFQXdNd09ERVZNQk1HQTFVRUNoTU1SMmwwU0hWaUxDQkpibU11TVI4d0hRWURWUVFERXhaSmJuUmxjbTVoYkNCVFpYSjJhV05sY3lCU2IyOTBNQjRYRFRJek1EUXhOREF3TURBd01Gb1hEVE16TURReE1UQXdNREF3TUZvd09ERVZNQk1HQTFVRUNoTU1SMmwwU0hWaUxDQkpibU11TVI4d0hRWURWUVFERXhaSmJuUmxjbTVoYkNCVFpYSjJhV05sY3lCU2IyOTBNSFl3RUFZSEtvWkl6ajBDQVFZRks0RUVBQ0lEWWdBRWY5akZBWHh6NGt4NjhBSFJNT2tGQmhmbERjTVR2emFYejR4L0ZDY1hqSi8xcUVLb24vcVBJR25hVVJza0R0eU5iTkRPcGVKVERERnF0NDhpTVBybnpweDZJWndxZW1mVUpONHhCRVpmemErcFl0L2l5b2QrOXRacjIwUlJXU3YvbzBVd1F6QU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VnWURWUjBUQVFIL0JBZ3dCZ0VCL3dJQkFqQWRCZ05WSFE0RUZnUVU5TllZbG9ibkFHNGMwL3FqeHlIL2xxL3d6K1F3Q2dZSUtvWkl6ajBFQXdNRGFBQXdaUUl4QUxaTFo4QmdSWHpLeExNTU45VklsTytlNGhyQm5OQmdGN3R6N0hucm93djJOZXRaRXJJQUNLRnltQmx2V0R2dE1BSXdaTytraTZzc1ExYnNabzk4TzhtRUFmMk5aN2lpQ2dERFUwVndqZWNvNnp5ZWgwekJUczkvN2dWNkFITlE1M3hEIgogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfSwKICAgICAgInZhbGlkRm9yIjogewogICAgICAgICJzdGFydCI6ICIyMDIzLTA0LTE0VDAwOjAwOjAwLjAwMFoiCiAgICAgIH0KICAgIH0KICBdCn0K","registry.npmjs.org%2Fkeys.json":"ewogICAgImtleXMiOiBbCiAgICAgICAgewogICAgICAgICAgICAia2V5SWQiOiAiU0hBMjU2OmpsM2J3c3d1ODBQampva0NnaDBvMnc1YzJVNExoUUFFNTdnajljejFrekEiLAogICAgICAgICAgICAia2V5VXNhZ2UiOiAibnBtOnNpZ25hdHVyZXMiLAogICAgICAgICAgICAicHVibGljS2V5IjogewogICAgICAgICAgICAgICAgInJhd0J5dGVzIjogIk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTFPbGIzek1BRkZ4WEtIaUlrUU81Y0ozWWhsNWk2VVBwK0lodXRlQkpidUhjQTVVb2dLbzBFV3RsV3dXNktTYUtvVE5FWUw3SmxDUWlWbmtoQmt0VWdnPT0iLAogICAgICAgICAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgICAgICAgICAgICJzdGFydCI6ICIxOTk5LTAxLTAxVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9LAogICAgICAgIHsKICAgICAgICAgICAgImtleUlkIjogIlNIQTI1NjpqbDNid3N3dTgwUGpqb2tDZ2gwbzJ3NWMyVTRMaFFBRTU3Z2o5Y3oxa3pBIiwKICAgICAgICAgICAgImtleVVzYWdlIjogIm5wbTphdHRlc3RhdGlvbnMiLAogICAgICAgICAgICAicHVibGljS2V5IjogewogICAgICAgICAgICAgICAgInJhd0J5dGVzIjogIk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTFPbGIzek1BRkZ4WEtIaUlrUU81Y0ozWWhsNWk2VVBwK0lodXRlQkpidUhjQTVVb2dLbzBFV3RsV3dXNktTYUtvVE5FWUw3SmxDUWlWbmtoQmt0VWdnPT0iLAogICAgICAgICAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgICAgICAgICAgICJzdGFydCI6ICIyMDIyLTEyLTAxVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICBdCn0K"}}} +{"https://tuf-repo-cdn.sigstore.dev":{"root.json":"ewogInNpZ25hdHVyZXMiOiBbCiAgewogICAia2V5aWQiOiAiZTcxYTU0ZDU0MzgzNWJhODZhZGFkOTQ2MDM3OWM3NjQxZmI4NzI2ZDE2NGVhNzY2ODAxYTFjNTIyYWJhN2VhMiIsCiAgICJzaWciOiAiMzA0NTAyMjEwMGVhMmYzNzRmNDA5ODEwZTJkYjk1MDc0OWQ5Y2ZlZDA5YTE1YjZhNWUyNWYzZDVmZmQwNzk5NDU5ZDdiZWUxNjcwMjIwMjhkM2FjZGRlNmRiZDUwMzRjZmFkMjIyZDMxYjQxMDkwZWUyMTg5NGUyYzQ2Y2I4OTc0MTk4YWIwMzc3ZGI0NCIKICB9LAogIHsKICAgImtleWlkIjogIjIyZjRjYWVjNmQ4ZTZmOTU1NWFmNjZiM2Q0YzNjYjA2YTNiYjIzZmRjN2UzOWM5MTZjNjFmNDYyZTZmNTJiMDYiLAogICAic2lnIjogIjMwNDQwMjIwN2ViYjI0ZTMyMzdlNDcwNjkxZDc4NzU5MDNhNzc1NGQwZWYyYWU3ZTdiNTAyNGE3ODg4YzlhMzhhNTJkZWVjZDAyMjA2ZWQ1YWQxYzZmNGZhYjQ2OTk1ODQzYWI2YjIzZjk0MjBjNWE0Y2Y2Y2UxY2IyY2IyYTZmYzJlODdlMmVmM2UxIgogIH0sCiAgewogICAia2V5aWQiOiAiNjE2NDM4MzgxMjViNDQwYjQwZGI2OTQyZjVjYjVhMzFjMGRjMDQzNjgzMTZlYjJhYWE1OGI5NTkwNGE1ODIyMiIsCiAgICJzaWciOiAiMzA0NjAyMjEwMDg5ZDlkZmQ4ZTEwNmNjOTU4MDg4YTRkYTNjOGNmNzI1NGFiNmY2NWE5NjQ3ZDM3YWRhNzMwZWY0NzYzYzUxNjMwMjIxMDBkODgyZWU3NDQ2MTViZTc5ODYxZTIxNGUxZWViOWUxZWRkZjZhMWUyMDNhMjAxYjRjNWQwM2Y1MjI0ZDcxZDE2IgogIH0sCiAgewogICAia2V5aWQiOiAiYTY4N2U1YmY0ZmFiODJiMGVlNThkNDZlMDVjOTUzNTE0NWEyYzlhZmI0NThmNDNkNDJiNDVjYTBmZGNlMmE3MCIsCiAgICJzaWciOiAiMzA0NTAyMjEwMDg4YmQ0Yjg4ZTgzZjU4NmNlNTY4ZDI3ZDA0MjE0YzRhYjNmZDE4OTQxNzhlZjAxNTMwM2Q1NmFmYTkzOTIwNTMwMjIwNTUzOGViYWI5Mzg3NmFiYjkwNzVhZDc3MTE0YmZmMjhhMGQ3OWE3Y2MyMjliNTM0YTBjNWNlZDU1MjZiNDhlNyIKICB9LAogIHsKICAgImtleWlkIjogIjE4M2U2NGYzNzY3MGRjMTNjYTBkMjg5OTVhMzA1M2YzNzQwOTU0ZGRjZTQ0MzIxYTQxZTQ2NTM0Y2Y0NGU2MzIiLAogICAic2lnIjogIjMwNDUwMjIxMDBmMzViMDdlOTM4ZDQ5NDljYWY4MmU2OWU4NmNjOWRiM2I2OWI2ZGJjNjc0MGMxZjM0M2QwNjg5M2Y5OTZmYmViMDIyMDAxZTg0N2Q4MTYyNTlhOTZhNDllNDI3NzlhMjM1MGRhYjk3YjcxYzhhZTdlMjZiMjM4MGM2ZmE3ZjU4MTMxYjMiCiAgfQogXSwKICJzaWduZWQiOiB7CiAgIl90eXBlIjogInJvb3QiLAogICJjb25zaXN0ZW50X3NuYXBzaG90IjogdHJ1ZSwKICAiZXhwaXJlcyI6ICIyMDI2LTExLTIwVDEzOjU4OjE4WiIsCiAgImtleXMiOiB7CiAgICIwYzg3NDMyYzNiZjA5ZmQ5OTE4OWZkYzMyZmE1ZWFlZGY0ZTRhNWZhYzdiYWI3M2ZhMDRhMmUwZmM2NGFmNmY1IjogewogICAgImtleWlkX2hhc2hfYWxnb3JpdGhtcyI6IFsKICAgICAic2hhMjU2IiwKICAgICAic2hhNTEyIgogICAgXSwKICAgICJrZXl0eXBlIjogImVjZHNhIiwKICAgICJrZXl2YWwiOiB7CiAgICAgInB1YmxpYyI6ICItLS0tLUJFR0lOIFBVQkxJQyBLRVktLS0tLVxuTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFV1JpR3I1K2orM0o1U3NIK1p0cjVuRTJIMndPN1xuQlYrbk8zczkzZ0xjYTE4cVRPekhZMW9XeUFHRHlrTVNzR1RVQlN0OUQrQW4wS2ZLc0QybWZTTTQyUT09XG4tLS0tLUVORCBQVUJMSUMgS0VZLS0tLS1cbiIKICAgIH0sCiAgICAic2NoZW1lIjogImVjZHNhLXNoYTItbmlzdHAyNTYiLAogICAgIngtdHVmLW9uLWNpLW9ubGluZS11cmkiOiAiZ2Nwa21zOnByb2plY3RzL3NpZ3N0b3JlLXJvb3Qtc2lnbmluZy9sb2NhdGlvbnMvZ2xvYmFsL2tleVJpbmdzL3Jvb3QvY3J5cHRvS2V5cy90aW1lc3RhbXAvY3J5cHRvS2V5VmVyc2lvbnMvMSIKICAgfSwKICAgIjE4M2U2NGYzNzY3MGRjMTNjYTBkMjg5OTVhMzA1M2YzNzQwOTU0ZGRjZTQ0MzIxYTQxZTQ2NTM0Y2Y0NGU2MzIiOiB7CiAgICAia2V5dHlwZSI6ICJlY2RzYSIsCiAgICAia2V5dmFsIjogewogICAgICJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRU14cFBPSkNJWjVvdEc0MTA2ZkdKc2VFUWkzVjlcbnBrTVlRNHV5VjlUajFNN1dIWEl5TEcramtmdnVHMGdsUTFKWmJSWlpCVjNnQVI0c29qZEdISVNlb3c9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCiAgICB9LAogICAgInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKICAgICJ4LXR1Zi1vbi1jaS1rZXlvd25lciI6ICJAbGFuY2UiCiAgIH0sCiAgICIyMmY0Y2FlYzZkOGU2Zjk1NTVhZjY2YjNkNGMzY2IwNmEzYmIyM2ZkYzdlMzljOTE2YzYxZjQ2MmU2ZjUyYjA2IjogewogICAgImtleWlkX2hhc2hfYWxnb3JpdGhtcyI6IFsKICAgICAic2hhMjU2IiwKICAgICAic2hhNTEyIgogICAgXSwKICAgICJrZXl0eXBlIjogImVjZHNhIiwKICAgICJrZXl2YWwiOiB7CiAgICAgInB1YmxpYyI6ICItLS0tLUJFR0lOIFBVQkxJQyBLRVktLS0tLVxuTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFekJ6Vk9tSENQb2pNVkxTSTM2NFdpaVY4TlByRFxuNklnUnhWbGlza3ovdit5M0pFUjVtY1ZHY09ObGlEY1dNQzVKMmxmSG1qUE5QaGI0SDd4bThMemZTQT09XG4tLS0tLUVORCBQVUJMSUMgS0VZLS0tLS1cbiIKICAgIH0sCiAgICAic2NoZW1lIjogImVjZHNhLXNoYTItbmlzdHAyNTYiLAogICAgIngtdHVmLW9uLWNpLWtleW93bmVyIjogIkBzYW50aWFnb3RvcnJlcyIKICAgfSwKICAgIjYxNjQzODM4MTI1YjQ0MGI0MGRiNjk0MmY1Y2I1YTMxYzBkYzA0MzY4MzE2ZWIyYWFhNThiOTU5MDRhNTgyMjIiOiB7CiAgICAia2V5aWRfaGFzaF9hbGdvcml0aG1zIjogWwogICAgICJzaGEyNTYiLAogICAgICJzaGE1MTIiCiAgICBdLAogICAgImtleXR5cGUiOiAiZWNkc2EiLAogICAgImtleXZhbCI6IHsKICAgICAicHVibGljIjogIi0tLS0tQkVHSU4gUFVCTElDIEtFWS0tLS0tXG5NRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVpbmlrU3NBUW1Za05lSDVlWXEvQ25JekxhYWNPXG54bFNhYXdRRE93cUt5L3RDcXhxNXh4UFNKYzIxSzRXSWhzOUd5T2tLZnp1ZVkzR0lMemNNSlo0Y1d3PT1cbi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLVxuIgogICAgfSwKICAgICJzY2hlbWUiOiAiZWNkc2Etc2hhMi1uaXN0cDI1NiIsCiAgICAieC10dWYtb24tY2kta2V5b3duZXIiOiAiQGJvYmNhbGxhd2F5IgogICB9LAogICAiYTY4N2U1YmY0ZmFiODJiMGVlNThkNDZlMDVjOTUzNTE0NWEyYzlhZmI0NThmNDNkNDJiNDVjYTBmZGNlMmE3MCI6IHsKICAgICJrZXlpZF9oYXNoX2FsZ29yaXRobXMiOiBbCiAgICAgInNoYTI1NiIsCiAgICAgInNoYTUxMiIKICAgIF0sCiAgICAia2V5dHlwZSI6ICJlY2RzYSIsCiAgICAia2V5dmFsIjogewogICAgICJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTBnaHJoOTJMdzFZcjNpZEdWNVdxQ3RNREI4Q3hcbitEOGhkQzR3MlpMTklwbFZSb1ZHTHNrWWEzZ2hlTXlPamlKOGtQaTE1YVEyLy83UCtvajdVdkpQR3c9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCiAgICB9LAogICAgInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKICAgICJ4LXR1Zi1vbi1jaS1rZXlvd25lciI6ICJAam9zaHVhZ2wiCiAgIH0sCiAgICJlNzFhNTRkNTQzODM1YmE4NmFkYWQ5NDYwMzc5Yzc2NDFmYjg3MjZkMTY0ZWE3NjY4MDFhMWM1MjJhYmE3ZWEyIjogewogICAgImtleWlkX2hhc2hfYWxnb3JpdGhtcyI6IFsKICAgICAic2hhMjU2IiwKICAgICAic2hhNTEyIgogICAgXSwKICAgICJrZXl0eXBlIjogImVjZHNhIiwKICAgICJrZXl2YWwiOiB7CiAgICAgInB1YmxpYyI6ICItLS0tLUJFR0lOIFBVQkxJQyBLRVktLS0tLVxuTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFRVhzejNTWlhGYjhqTVY0Mmo2cEpseWpialI4S1xuTjNCd29jZXhxNkxNSWI1cXNXS09RdkxOMTZOVWVmTGM0SHN3T291bVJzVlZhYWpTcFFTNmZvYmtSdz09XG4tLS0tLUVORCBQVUJMSUMgS0VZLS0tLS1cbiIKICAgIH0sCiAgICAic2NoZW1lIjogImVjZHNhLXNoYTItbmlzdHAyNTYiLAogICAgIngtdHVmLW9uLWNpLWtleW93bmVyIjogIkBtbm02NzgiCiAgIH0KICB9LAogICJyb2xlcyI6IHsKICAgInJvb3QiOiB7CiAgICAia2V5aWRzIjogWwogICAgICJlNzFhNTRkNTQzODM1YmE4NmFkYWQ5NDYwMzc5Yzc2NDFmYjg3MjZkMTY0ZWE3NjY4MDFhMWM1MjJhYmE3ZWEyIiwKICAgICAiMjJmNGNhZWM2ZDhlNmY5NTU1YWY2NmIzZDRjM2NiMDZhM2JiMjNmZGM3ZTM5YzkxNmM2MWY0NjJlNmY1MmIwNiIsCiAgICAgIjYxNjQzODM4MTI1YjQ0MGI0MGRiNjk0MmY1Y2I1YTMxYzBkYzA0MzY4MzE2ZWIyYWFhNThiOTU5MDRhNTgyMjIiLAogICAgICJhNjg3ZTViZjRmYWI4MmIwZWU1OGQ0NmUwNWM5NTM1MTQ1YTJjOWFmYjQ1OGY0M2Q0MmI0NWNhMGZkY2UyYTcwIiwKICAgICAiMTgzZTY0ZjM3NjcwZGMxM2NhMGQyODk5NWEzMDUzZjM3NDA5NTRkZGNlNDQzMjFhNDFlNDY1MzRjZjQ0ZTYzMiIKICAgIF0sCiAgICAidGhyZXNob2xkIjogMwogICB9LAogICAic25hcHNob3QiOiB7CiAgICAia2V5aWRzIjogWwogICAgICIwYzg3NDMyYzNiZjA5ZmQ5OTE4OWZkYzMyZmE1ZWFlZGY0ZTRhNWZhYzdiYWI3M2ZhMDRhMmUwZmM2NGFmNmY1IgogICAgXSwKICAgICJ0aHJlc2hvbGQiOiAxLAogICAgIngtdHVmLW9uLWNpLWV4cGlyeS1wZXJpb2QiOiAzNjUwLAogICAgIngtdHVmLW9uLWNpLXNpZ25pbmctcGVyaW9kIjogMzY1CiAgIH0sCiAgICJ0YXJnZXRzIjogewogICAgImtleWlkcyI6IFsKICAgICAiZTcxYTU0ZDU0MzgzNWJhODZhZGFkOTQ2MDM3OWM3NjQxZmI4NzI2ZDE2NGVhNzY2ODAxYTFjNTIyYWJhN2VhMiIsCiAgICAgIjIyZjRjYWVjNmQ4ZTZmOTU1NWFmNjZiM2Q0YzNjYjA2YTNiYjIzZmRjN2UzOWM5MTZjNjFmNDYyZTZmNTJiMDYiLAogICAgICI2MTY0MzgzODEyNWI0NDBiNDBkYjY5NDJmNWNiNWEzMWMwZGMwNDM2ODMxNmViMmFhYTU4Yjk1OTA0YTU4MjIyIiwKICAgICAiYTY4N2U1YmY0ZmFiODJiMGVlNThkNDZlMDVjOTUzNTE0NWEyYzlhZmI0NThmNDNkNDJiNDVjYTBmZGNlMmE3MCIsCiAgICAgIjE4M2U2NGYzNzY3MGRjMTNjYTBkMjg5OTVhMzA1M2YzNzQwOTU0ZGRjZTQ0MzIxYTQxZTQ2NTM0Y2Y0NGU2MzIiCiAgICBdLAogICAgInRocmVzaG9sZCI6IDMKICAgfSwKICAgInRpbWVzdGFtcCI6IHsKICAgICJrZXlpZHMiOiBbCiAgICAgIjBjODc0MzJjM2JmMDlmZDk5MTg5ZmRjMzJmYTVlYWVkZjRlNGE1ZmFjN2JhYjczZmEwNGEyZTBmYzY0YWY2ZjUiCiAgICBdLAogICAgInRocmVzaG9sZCI6IDEsCiAgICAieC10dWYtb24tY2ktZXhwaXJ5LXBlcmlvZCI6IDcsCiAgICAieC10dWYtb24tY2ktc2lnbmluZy1wZXJpb2QiOiA2CiAgIH0KICB9LAogICJzcGVjX3ZlcnNpb24iOiAiMS4wIiwKICAidmVyc2lvbiI6IDE1LAogICJ4LXR1Zi1vbi1jaS1leHBpcnktcGVyaW9kIjogMTk3LAogICJ4LXR1Zi1vbi1jaS1zaWduaW5nLXBlcmlvZCI6IDQ2CiB9Cn0=","targets":{"trusted_root.json":"ewogICJtZWRpYVR5cGUiOiAiYXBwbGljYXRpb24vdm5kLmRldi5zaWdzdG9yZS50cnVzdGVkcm9vdCtqc29uO3ZlcnNpb249MC4xIiwKICAidGxvZ3MiOiBbCiAgICB7CiAgICAgICJiYXNlVXJsIjogImh0dHBzOi8vcmVrb3Iuc2lnc3RvcmUuZGV2IiwKICAgICAgImhhc2hBbGdvcml0aG0iOiAiU0hBMl8yNTYiLAogICAgICAicHVibGljS2V5IjogewogICAgICAgICJyYXdCeXRlcyI6ICJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUUyRzJZKzJ0YWJkVFY1QmNHaUJJeDBhOWZBRndya0JibUxTR3RrczRMM3FYNnlZWTB6dWZCbmhDOFVyL2l5NTVHaFdQLzlBL2JZMkxoQzMwTTkrUll0dz09IiwKICAgICAgICAia2V5RGV0YWlscyI6ICJQS0lYX0VDRFNBX1AyNTZfU0hBXzI1NiIsCiAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgInN0YXJ0IjogIjIwMjEtMDEtMTJUMTE6NTM6MjdaIgogICAgICAgIH0KICAgICAgfSwKICAgICAgImxvZ0lkIjogewogICAgICAgICJrZXlJZCI6ICJ3Tkk5YXRRR2x6K1ZXZk82TFJ5Z0g0UVVmWS84VzRSRndpVDVpNVdSZ0IwPSIKICAgICAgfQogICAgfSwKICAgIHsKICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly9sb2cyMDI1LTEucmVrb3Iuc2lnc3RvcmUuZGV2IiwKICAgICAgImhhc2hBbGdvcml0aG0iOiAiU0hBMl8yNTYiLAogICAgICAicHVibGljS2V5IjogewogICAgICAgICJyYXdCeXRlcyI6ICJNQ293QlFZREsyVndBeUVBdDhybHAxa25Hd2pmYmNYQVlQWUFrbjBYaUx6MXg4TzR0MFlrRWhpZTI0ND0iLAogICAgICAgICJrZXlEZXRhaWxzIjogIlBLSVhfRUQyNTUxOSIsCiAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgInN0YXJ0IjogIjIwMjUtMDktMjNUMDA6MDA6MDBaIgogICAgICAgIH0KICAgICAgfSwKICAgICAgImxvZ0lkIjogewogICAgICAgICJrZXlJZCI6ICJ6eEdaRlZ2ZDBGRW1qUjhXckZ3TWRjQUo5dnRhWS9RWGY0NFkxd1VlUDZBPSIKICAgICAgfQogICAgfQogIF0sCiAgImNlcnRpZmljYXRlQXV0aG9yaXRpZXMiOiBbCiAgICB7CiAgICAgICJzdWJqZWN0IjogewogICAgICAgICJvcmdhbml6YXRpb24iOiAic2lnc3RvcmUuZGV2IiwKICAgICAgICAiY29tbW9uTmFtZSI6ICJzaWdzdG9yZSIKICAgICAgfSwKICAgICAgInVyaSI6ICJodHRwczovL2Z1bGNpby5zaWdzdG9yZS5kZXYiLAogICAgICAiY2VydENoYWluIjogewogICAgICAgICJjZXJ0aWZpY2F0ZXMiOiBbCiAgICAgICAgICB7CiAgICAgICAgICAgICJyYXdCeXRlcyI6ICJNSUlCK0RDQ0FYNmdBd0lCQWdJVE5Wa0Rab0Npb2ZQRHN5N2RmbTZnZUxidWh6QUtCZ2dxaGtqT1BRUURBekFxTVJVd0V3WURWUVFLRXd4emFXZHpkRzl5WlM1a1pYWXhFVEFQQmdOVkJBTVRDSE5wWjNOMGIzSmxNQjRYRFRJeE1ETXdOekF6TWpBeU9Wb1hEVE14TURJeU16QXpNakF5T1Zvd0tqRVZNQk1HQTFVRUNoTU1jMmxuYzNSdmNtVXVaR1YyTVJFd0R3WURWUVFERXdoemFXZHpkRzl5WlRCMk1CQUdCeXFHU000OUFnRUdCU3VCQkFBaUEySUFCTFN5QTdJaTVrK3BOTzhaRVdZMHlsZW1XRG93T2tOYTNrTCtHWkU1WjVHV2VoTDkvQTliUk5BM1JicnNaNWkwSmNhc3RhUkw3U3A1ZnAvakQ1ZHhxYy9VZFRWbmx2UzE2YW4rMllmc3dlL1F1TG9sUlVDcmNPRTIrMmlBNSt0emQ2Tm1NR1F3RGdZRFZSMFBBUUgvQkFRREFnRUdNQklHQTFVZEV3RUIvd1FJTUFZQkFmOENBUUV3SFFZRFZSME9CQllFRk1qRkhRQkJtaVFwTWxFazZ3MnVTdTFLQnRQc01COEdBMVVkSXdRWU1CYUFGTWpGSFFCQm1pUXBNbEVrNncydVN1MUtCdFBzTUFvR0NDcUdTTTQ5QkFNREEyZ0FNR1VDTUg4bGlXSmZNdWk2dlhYQmhqRGdZNE13c2xtTi9USnhWZS84M1dyRm9td21OZjA1NnkxWDQ4RjljNG0zYTNvelhBSXhBS2pSYXk1L2FqL2pzS0tHSWttUWF0akk4dXVwSHIvK0N4RnZhSldtcFlxTmtMREdSVSs5b3J6aDVoSTJScmN1YVE9PSIKICAgICAgICAgIH0KICAgICAgICBdCiAgICAgIH0sCiAgICAgICJ2YWxpZEZvciI6IHsKICAgICAgICAic3RhcnQiOiAiMjAyMS0wMy0wN1QwMzoyMDoyOVoiLAogICAgICAgICJlbmQiOiAiMjAyMi0xMi0zMVQyMzo1OTo1OS45OTlaIgogICAgICB9CiAgICB9LAogICAgewogICAgICAic3ViamVjdCI6IHsKICAgICAgICAib3JnYW5pemF0aW9uIjogInNpZ3N0b3JlLmRldiIsCiAgICAgICAgImNvbW1vbk5hbWUiOiAic2lnc3RvcmUiCiAgICAgIH0sCiAgICAgICJ1cmkiOiAiaHR0cHM6Ly9mdWxjaW8uc2lnc3RvcmUuZGV2IiwKICAgICAgImNlcnRDaGFpbiI6IHsKICAgICAgICAiY2VydGlmaWNhdGVzIjogWwogICAgICAgICAgewogICAgICAgICAgICAicmF3Qnl0ZXMiOiAiTUlJQ0dqQ0NBYUdnQXdJQkFnSVVBTG5WaVZmblUwYnJKYXNtUmtIcm4vVW5mYVF3Q2dZSUtvWkl6ajBFQXdNd0tqRVZNQk1HQTFVRUNoTU1jMmxuYzNSdmNtVXVaR1YyTVJFd0R3WURWUVFERXdoemFXZHpkRzl5WlRBZUZ3MHlNakEwTVRNeU1EQTJNVFZhRncwek1URXdNRFV4TXpVMk5UaGFNRGN4RlRBVEJnTlZCQW9UREhOcFozTjBiM0psTG1SbGRqRWVNQndHQTFVRUF4TVZjMmxuYzNSdmNtVXRhVzUwWlhKdFpXUnBZWFJsTUhZd0VBWUhLb1pJemowQ0FRWUZLNEVFQUNJRFlnQUU4UlZTL3lzSCtOT3Z1RFp5UEladGlsZ1VGOU5sYXJZcEFkOUhQMXZCQkgxVTVDVjc3TFNTN3MwWmlING5FN0h2N3B0UzZMdnZSL1NUazc5OExWZ016TGxKNEhlSWZGM3RIU2FleExjWXBTQVNyMWtTME4vUmdCSnovOWpXQ2lYbm8zc3dlVEFPQmdOVkhROEJBZjhFQkFNQ0FRWXdFd1lEVlIwbEJBd3dDZ1lJS3dZQkJRVUhBd013RWdZRFZSMFRBUUgvQkFnd0JnRUIvd0lCQURBZEJnTlZIUTRFRmdRVTM5UHB6MVlrRVpiNXFOanBLRldpeGk0WVpEOHdId1lEVlIwakJCZ3dGb0FVV01BZVg1RkZwV2FwZXN5UW9aTWkwQ3JGeGZvd0NnWUlLb1pJemowRUF3TURad0F3WkFJd1BDc1FLNERZaVpZRFBJYURpNUhGS25meFh4NkFTU1ZtRVJmc3luWUJpWDJYNlNKUm5aVTg0LzlEWmRuRnZ2eG1BakJPdDZRcEJsYzRKLzBEeHZrVENxcGNsdnppTDZCQ0NQbmpkbElCM1B1M0J4c1BteWdVWTdJaTJ6YmRDZGxpaW93PSIKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJyYXdCeXRlcyI6ICJNSUlCOXpDQ0FYeWdBd0lCQWdJVUFMWk5BUEZkeEhQd2plRGxvRHd5WUNoQU8vNHdDZ1lJS29aSXpqMEVBd013S2pFVk1CTUdBMVVFQ2hNTWMybG5jM1J2Y21VdVpHVjJNUkV3RHdZRFZRUURFd2h6YVdkemRHOXlaVEFlRncweU1URXdNRGN4TXpVMk5UbGFGdzB6TVRFd01EVXhNelUyTlRoYU1Db3hGVEFUQmdOVkJBb1RESE5wWjNOMGIzSmxMbVJsZGpFUk1BOEdBMVVFQXhNSWMybG5jM1J2Y21Vd2RqQVFCZ2NxaGtqT1BRSUJCZ1VyZ1FRQUlnTmlBQVQ3WGVGVDRyYjNQUUd3UzRJYWp0TGszL09sbnBnYW5nYUJjbFlwc1lCcjVpKzR5bkIwN2NlYjNMUDBPSU9aZHhleFg2OWM1aVZ1eUpSUStIejA1eWkrVUYzdUJXQWxIcGlTNXNoMCtIMkdIRTdTWHJrMUVDNW0xVHIxOUw5Z2c5MmpZekJoTUE0R0ExVWREd0VCL3dRRUF3SUJCakFQQmdOVkhSTUJBZjhFQlRBREFRSC9NQjBHQTFVZERnUVdCQlJZd0I1ZmtVV2xacWw2ekpDaGt5TFFLc1hGK2pBZkJnTlZIU01FR0RBV2dCUll3QjVma1VXbFpxbDZ6SkNoa3lMUUtzWEYrakFLQmdncWhrak9QUVFEQXdOcEFEQm1BakVBajFuSGVYWnArMTNOV0JOYStFRHNEUDhHMVdXZzF0Q01XUC9XSFBxcGFWbzBqaHN3ZU5GWmdTczBlRTd3WUk0cUFqRUEyV0I5b3Q5OHNJa29GM3ZaWWRkMy9WdFdCNWI5VE5NZWE3SXgvc3RKNVRmY0xMZUFCTEU0Qk5KT3NRNHZuQkhKIgogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfSwKICAgICAgInZhbGlkRm9yIjogewogICAgICAgICJzdGFydCI6ICIyMDIyLTA0LTEzVDIwOjA2OjE1WiIKICAgICAgfQogICAgfQogIF0sCiAgImN0bG9ncyI6IFsKICAgIHsKICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly9jdGZlLnNpZ3N0b3JlLmRldi90ZXN0IiwKICAgICAgImhhc2hBbGdvcml0aG0iOiAiU0hBMl8yNTYiLAogICAgICAicHVibGljS2V5IjogewogICAgICAgICJyYXdCeXRlcyI6ICJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUViZndSK1JKdWRYc2NnUkJScEtYMVhGRHkzUHl1ZER4ei9TZm5SaTFmVDhla3BmQmQyTzF1b3o3anIzWjhuS3p4QTY5RVVRK2VGQ0ZJM3pldWJQV1U3dz09IiwKICAgICAgICAia2V5RGV0YWlscyI6ICJQS0lYX0VDRFNBX1AyNTZfU0hBXzI1NiIsCiAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgInN0YXJ0IjogIjIwMjEtMDMtMTRUMDA6MDA6MDBaIiwKICAgICAgICAgICJlbmQiOiAiMjAyMi0xMC0zMVQyMzo1OTo1OS45OTlaIgogICAgICAgIH0KICAgICAgfSwKICAgICAgImxvZ0lkIjogewogICAgICAgICJrZXlJZCI6ICJDR0NTOENoUy8yaEYwZEZySjRTY1JXY1lyQlk5d3pqU2JlYThJZ1kyYjNJPSIKICAgICAgfQogICAgfSwKICAgIHsKICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly9jdGZlLnNpZ3N0b3JlLmRldi8yMDIyIiwKICAgICAgImhhc2hBbGdvcml0aG0iOiAiU0hBMl8yNTYiLAogICAgICAicHVibGljS2V5IjogewogICAgICAgICJyYXdCeXRlcyI6ICJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVpUFNsRmkwQ21GVGZFakNVcUY5SHVDRWNZWE5LQWFZYWxJSm1CWjh5eWV6UGpUcWh4cktCcE1uYW9jVnRMSkJJMWVNM3VYblF6UUdBSmRKNGdzOUZ5dz09IiwKICAgICAgICAia2V5RGV0YWlscyI6ICJQS0lYX0VDRFNBX1AyNTZfU0hBXzI1NiIsCiAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgInN0YXJ0IjogIjIwMjItMTAtMjBUMDA6MDA6MDBaIgogICAgICAgIH0KICAgICAgfSwKICAgICAgImxvZ0lkIjogewogICAgICAgICJrZXlJZCI6ICIzVDB3YXNiSEVUSmpHUjRjbVdjM0FxSktYcmplUEszL2g0cHlnQzhwN280PSIKICAgICAgfQogICAgfQogIF0sCiAgInRpbWVzdGFtcEF1dGhvcml0aWVzIjogWwogICAgewogICAgICAic3ViamVjdCI6IHsKICAgICAgICAib3JnYW5pemF0aW9uIjogInNpZ3N0b3JlLmRldiIsCiAgICAgICAgImNvbW1vbk5hbWUiOiAic2lnc3RvcmUtdHNhLXNlbGZzaWduZWQiCiAgICAgIH0sCiAgICAgICJ1cmkiOiAiaHR0cHM6Ly90aW1lc3RhbXAuc2lnc3RvcmUuZGV2L2FwaS92MS90aW1lc3RhbXAiLAogICAgICAiY2VydENoYWluIjogewogICAgICAgICJjZXJ0aWZpY2F0ZXMiOiBbCiAgICAgICAgICB7CiAgICAgICAgICAgICJyYXdCeXRlcyI6ICJNSUlDRURDQ0FaYWdBd0lCQWdJVU9oTlVMd3lRWWU2OHdVTXZ5NHFPaXlvaml3d3dDZ1lJS29aSXpqMEVBd013T1RFVk1CTUdBMVVFQ2hNTWMybG5jM1J2Y21VdVpHVjJNU0F3SGdZRFZRUURFeGR6YVdkemRHOXlaUzEwYzJFdGMyVnNabk5wWjI1bFpEQWVGdzB5TlRBME1EZ3dOalU1TkROYUZ3MHpOVEEwTURZd05qVTVORE5hTUM0eEZUQVRCZ05WQkFvVERITnBaM04wYjNKbExtUmxkakVWTUJNR0ExVUVBeE1NYzJsbmMzUnZjbVV0ZEhOaE1IWXdFQVlIS29aSXpqMENBUVlGSzRFRUFDSURZZ0FFNHJhMlo4aEtOaWcyVDlrRmpDQVRvR0czMGpreStXUXYzQnpMK21LdmgxU0tOUi9Vd3V3c2ZOQ2c0c3J5b1lBZDhFNmlzb3ZWQTNNNGFvTmRtOVFEaTUwWjhuVEV5dnFnZkRQdFRJd1hJdGZpVy9BRmYxVjd1d2tia0FvajB4eGNvMm93YURBT0JnTlZIUThCQWY4RUJBTUNCNEF3SFFZRFZSME9CQllFRkluOWVVT0h6OUJsUnNNQ1JzY3NjMXQ5dE9zRE1COEdBMVVkSXdRWU1CYUFGSmpzQWU5L3UxSC8xSlVlYjRxSW1GTUhpYzYvTUJZR0ExVWRKUUVCL3dRTU1Bb0dDQ3NHQVFVRkJ3TUlNQW9HQ0NxR1NNNDlCQU1EQTJnQU1HVUNNRHRwc1YvNkthTzBxeUYvVU1zWDJhU1VYS1FGZG9HVHB0UUdjMGZ0cTFjc3VsSFBHRzZkc215TU5kM0pCK0czRVFJeEFPYWp2QmNqcEptS2I0TnYrMlRhb2o4VWM1K2I2aWg2RlhDQ0tyYVNxdXBlMDd6cXN3TWNYSlRlMWNFeHZIdnZsdz09IgogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgInJhd0J5dGVzIjogIk1JSUI5ekNDQVh5Z0F3SUJBZ0lVVjdmMEdMRE9vRXpJaDhMWFNXODBPSmlVcDE0d0NnWUlLb1pJemowRUF3TXdPVEVWTUJNR0ExVUVDaE1NYzJsbmMzUnZjbVV1WkdWMk1TQXdIZ1lEVlFRREV4ZHphV2R6ZEc5eVpTMTBjMkV0YzJWc1puTnBaMjVsWkRBZUZ3MHlOVEEwTURnd05qVTVORE5hRncwek5UQTBNRFl3TmpVNU5ETmFNRGt4RlRBVEJnTlZCQW9UREhOcFozTjBiM0psTG1SbGRqRWdNQjRHQTFVRUF4TVhjMmxuYzNSdmNtVXRkSE5oTFhObGJHWnphV2R1WldRd2RqQVFCZ2NxaGtqT1BRSUJCZ1VyZ1FRQUlnTmlBQVFVUU50ZlJUL291M1lBVGE2d0Iva0tUZTcwY2ZKd3lSSUJvdk1udDhSY0pwaC9DT0U4MnV5UzZGbXBwTExMMVZCUEdjUGZwUVBZSk5Yeld3aThpY3doS1E2Vy9RZTJoM29lYkJiMkZIcHdOSkRxbytUTWFDL3RkZmt2L0VsSkI3MmpSVEJETUE0R0ExVWREd0VCL3dRRUF3SUJCakFTQmdOVkhSTUJBZjhFQ0RBR0FRSC9BZ0VBTUIwR0ExVWREZ1FXQkJTWTdBSHZmN3RSLzlTVkhtK0tpSmhUQjRuT3Z6QUtCZ2dxaGtqT1BRUURBd05wQURCbUFqRUF3R0VHcmZHWlIxY2VuMVI4L0RUVk1JOTQzTHNzWm1KUnREcC9pN1NmR0htR1JQNmdSYnVqOXZPSzNiNjdaMFFRQWpFQXVUMkg2NzNMUUVhSFRjeVFTWnJrcDRtWDdXd2ttRitzVmJrWVk1bVhOK1JNSDEzS1VFSEhPcUFTYWVtWVdLL0UiCiAgICAgICAgICB9CiAgICAgICAgXQogICAgICB9LAogICAgICAidmFsaWRGb3IiOiB7CiAgICAgICAgInN0YXJ0IjogIjIwMjUtMDctMDRUMDA6MDA6MDBaIgogICAgICB9CiAgICB9CiAgXQp9Cg==","registry.npmjs.org%2Fkeys.json":"ewogICAgImtleXMiOiBbCiAgICAgICAgewogICAgICAgICAgICAia2V5SWQiOiAiU0hBMjU2OmpsM2J3c3d1ODBQampva0NnaDBvMnc1YzJVNExoUUFFNTdnajljejFrekEiLAogICAgICAgICAgICAia2V5VXNhZ2UiOiAibnBtOnNpZ25hdHVyZXMiLAogICAgICAgICAgICAicHVibGljS2V5IjogewogICAgICAgICAgICAgICAgInJhd0J5dGVzIjogIk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTFPbGIzek1BRkZ4WEtIaUlrUU81Y0ozWWhsNWk2VVBwK0lodXRlQkpidUhjQTVVb2dLbzBFV3RsV3dXNktTYUtvVE5FWUw3SmxDUWlWbmtoQmt0VWdnPT0iLAogICAgICAgICAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgICAgICAgICAgICJzdGFydCI6ICIxOTk5LTAxLTAxVDAwOjAwOjAwLjAwMFoiLAogICAgICAgICAgICAgICAgICAgICJlbmQiOiAiMjAyNS0wMS0yOVQwMDowMDowMC4wMDBaIgogICAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgfSwKICAgICAgICB7CiAgICAgICAgICAgICJrZXlJZCI6ICJTSEEyNTY6amwzYndzd3U4MFBqam9rQ2doMG8ydzVjMlU0TGhRQUU1N2dqOWN6MWt6QSIsCiAgICAgICAgICAgICJrZXlVc2FnZSI6ICJucG06YXR0ZXN0YXRpb25zIiwKICAgICAgICAgICAgInB1YmxpY0tleSI6IHsKICAgICAgICAgICAgICAgICJyYXdCeXRlcyI6ICJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUUxT2xiM3pNQUZGeFhLSGlJa1FPNWNKM1lobDVpNlVQcCtJaHV0ZUJKYnVIY0E1VW9nS28wRVd0bFd3VzZLU2FLb1RORVlMN0psQ1FpVm5raEJrdFVnZz09IiwKICAgICAgICAgICAgICAgICJrZXlEZXRhaWxzIjogIlBLSVhfRUNEU0FfUDI1Nl9TSEFfMjU2IiwKICAgICAgICAgICAgICAgICJ2YWxpZEZvciI6IHsKICAgICAgICAgICAgICAgICAgICAic3RhcnQiOiAiMjAyMi0xMi0wMVQwMDowMDowMC4wMDBaIiwKICAgICAgICAgICAgICAgICAgICAiZW5kIjogIjIwMjUtMDEtMjlUMDA6MDA6MDAuMDAwWiIKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgIH0sCiAgICAgICAgewogICAgICAgICAgICAia2V5SWQiOiAiU0hBMjU2OkRoUTh3UjVBUEJ2RkhMRi8rVGMrQVl2UE9kVHBjSURxT2h4c0JIUndDN1UiLAogICAgICAgICAgICAia2V5VXNhZ2UiOiAibnBtOnNpZ25hdHVyZXMiLAogICAgICAgICAgICAicHVibGljS2V5IjogewogICAgICAgICAgICAgICAgInJhd0J5dGVzIjogIk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRVk2WWE3VysrN2FVUHp2TVRyZXpINlljeDNjK0hPS1lDY05HeWJKWlNDSnEvZmQ3UWE4dXVBS3RkSWtVUXRRaUVLRVJoQW1FNWxNTUpoUDhPa0RPYTJnPT0iLAogICAgICAgICAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgICAgICAgICAgICJzdGFydCI6ICIyMDI1LTAxLTEzVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9LAogICAgICAgIHsKICAgICAgICAgICAgImtleUlkIjogIlNIQTI1NjpEaFE4d1I1QVBCdkZITEYvK1RjK0FZdlBPZFRwY0lEcU9oeHNCSFJ3QzdVIiwKICAgICAgICAgICAgImtleVVzYWdlIjogIm5wbTphdHRlc3RhdGlvbnMiLAogICAgICAgICAgICAicHVibGljS2V5IjogewogICAgICAgICAgICAgICAgInJhd0J5dGVzIjogIk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRVk2WWE3VysrN2FVUHp2TVRyZXpINlljeDNjK0hPS1lDY05HeWJKWlNDSnEvZmQ3UWE4dXVBS3RkSWtVUXRRaUVLRVJoQW1FNWxNTUpoUDhPa0RPYTJnPT0iLAogICAgICAgICAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgICAgICAgICAgICJzdGFydCI6ICIyMDI1LTAxLTEzVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICBdCn0K"}}} diff --git a/node_modules/@sigstore/verify/dist/bundle/dsse.js b/node_modules/@sigstore/verify/dist/bundle/dsse.js deleted file mode 100644 index 193f875fd1014..0000000000000 --- a/node_modules/@sigstore/verify/dist/bundle/dsse.js +++ /dev/null @@ -1,43 +0,0 @@ -"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.hash(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; diff --git a/node_modules/@sigstore/verify/dist/bundle/index.js b/node_modules/@sigstore/verify/dist/bundle/index.js deleted file mode 100644 index 63f8d4c499881..0000000000000 --- a/node_modules/@sigstore/verify/dist/bundle/index.js +++ /dev/null @@ -1,58 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.signatureContent = exports.toSignedEntity = void 0; -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, - }; -} -exports.toSignedEntity = toSignedEntity; -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); - } -} -exports.signatureContent = signatureContent; -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), - }; - } -} diff --git a/node_modules/@sigstore/verify/dist/bundle/message.js b/node_modules/@sigstore/verify/dist/bundle/message.js deleted file mode 100644 index 836148c68a8b6..0000000000000 --- a/node_modules/@sigstore/verify/dist/bundle/message.js +++ /dev/null @@ -1,36 +0,0 @@ -"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; diff --git a/node_modules/@sigstore/verify/dist/error.js b/node_modules/@sigstore/verify/dist/error.js deleted file mode 100644 index 6cb1cd4121343..0000000000000 --- a/node_modules/@sigstore/verify/dist/error.js +++ /dev/null @@ -1,32 +0,0 @@ -"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; diff --git a/node_modules/@sigstore/verify/dist/key/index.js b/node_modules/@sigstore/verify/dist/key/index.js deleted file mode 100644 index 682a306803a99..0000000000000 --- a/node_modules/@sigstore/verify/dist/key/index.js +++ /dev/null @@ -1,72 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.verifyCertificate = exports.verifyPublicKey = 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"); -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 }; -} -exports.verifyPublicKey = verifyPublicKey; -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]), - }; -} -exports.verifyCertificate = verifyCertificate; -function getSigner(cert) { - let issuer; - const issuerExtension = cert.extension(OID_FULCIO_ISSUER_V2); - 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, - }; -} diff --git a/node_modules/@sigstore/verify/dist/key/sct.js b/node_modules/@sigstore/verify/dist/key/sct.js deleted file mode 100644 index aea412840e103..0000000000000 --- a/node_modules/@sigstore/verify/dist/key/sct.js +++ /dev/null @@ -1,79 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.verifySCTs = 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"); -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.hash(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; - }); -} -exports.verifySCTs = verifySCTs; diff --git a/node_modules/@sigstore/verify/dist/policy.js b/node_modules/@sigstore/verify/dist/policy.js deleted file mode 100644 index 731e5c8332847..0000000000000 --- a/node_modules/@sigstore/verify/dist/policy.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.verifyExtensions = exports.verifySubjectAlternativeName = void 0; -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}`, - }); - } -} -exports.verifySubjectAlternativeName = verifySubjectAlternativeName; -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]}`, - }); - } - } -} -exports.verifyExtensions = verifyExtensions; diff --git a/node_modules/@sigstore/verify/dist/timestamp/index.js b/node_modules/@sigstore/verify/dist/timestamp/index.js deleted file mode 100644 index 0da554f648d25..0000000000000 --- a/node_modules/@sigstore/verify/dist/timestamp/index.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.verifyTLogTimestamp = exports.verifyTSATimestamp = void 0; -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, - }; -} -exports.verifyTSATimestamp = verifyTSATimestamp; -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), - }; -} -exports.verifyTLogTimestamp = verifyTLogTimestamp; -function isTLogEntryWithInclusionPromise(entry) { - return entry.inclusionPromise !== undefined; -} -function isTLogEntryWithInclusionProof(entry) { - return entry.inclusionProof !== undefined; -} diff --git a/node_modules/@sigstore/verify/dist/timestamp/tsa.js b/node_modules/@sigstore/verify/dist/timestamp/tsa.js deleted file mode 100644 index 7b095bc3a7f90..0000000000000 --- a/node_modules/@sigstore/verify/dist/timestamp/tsa.js +++ /dev/null @@ -1,74 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.verifyRFC3161Timestamp = void 0; -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', - }); - } -} -exports.verifyRFC3161Timestamp = verifyRFC3161Timestamp; -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)); -} diff --git a/node_modules/@sigstore/verify/dist/tlog/dsse.js b/node_modules/@sigstore/verify/dist/tlog/dsse.js deleted file mode 100644 index bf430e61dde56..0000000000000 --- a/node_modules/@sigstore/verify/dist/tlog/dsse.js +++ /dev/null @@ -1,58 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.verifyDSSETLogBody = 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"); -// 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}`, - }); - } -} -exports.verifyDSSETLogBody = verifyDSSETLogBody; -// 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', - }); - } -} diff --git a/node_modules/@sigstore/verify/dist/tlog/hashedrekord.js b/node_modules/@sigstore/verify/dist/tlog/hashedrekord.js deleted file mode 100644 index d1758858f030d..0000000000000 --- a/node_modules/@sigstore/verify/dist/tlog/hashedrekord.js +++ /dev/null @@ -1,52 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.verifyHashedRekordTLogBody = 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"); -// 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}`, - }); - } -} -exports.verifyHashedRekordTLogBody = verifyHashedRekordTLogBody; -// 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', - }); - } -} diff --git a/node_modules/@sigstore/verify/dist/tlog/index.js b/node_modules/@sigstore/verify/dist/tlog/index.js deleted file mode 100644 index adfc70ed51ad0..0000000000000 --- a/node_modules/@sigstore/verify/dist/tlog/index.js +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.verifyTLogBody = 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 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}`, - }); - } -} -exports.verifyTLogBody = verifyTLogBody; diff --git a/node_modules/@sigstore/verify/dist/trust/index.js b/node_modules/@sigstore/verify/dist/trust/index.js deleted file mode 100644 index 954de55841590..0000000000000 --- a/node_modules/@sigstore/verify/dist/trust/index.js +++ /dev/null @@ -1,84 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toTrustMaterial = exports.filterTLogAuthorities = exports.filterCertAuthorities = 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"); -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, - }; -} -exports.toTrustMaterial = toTrustMaterial; -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) { - 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) => { - return ((key.validFor?.start || BEGINNING_OF_TIME) <= date && - (key.validFor?.end || END_OF_TIME) >= date); - }, - }; - }; -} diff --git a/node_modules/@sigstore/verify/dist/verifier.js b/node_modules/@sigstore/verify/dist/verifier.js deleted file mode 100644 index 829727cd1d40a..0000000000000 --- a/node_modules/@sigstore/verify/dist/verifier.js +++ /dev/null @@ -1,141 +0,0 @@ -"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; -} diff --git a/node_modules/@sigstore/verify/package.json b/node_modules/@sigstore/verify/package.json deleted file mode 100644 index cd0c845a797e4..0000000000000 --- a/node_modules/@sigstore/verify/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "@sigstore/verify", - "version": "1.2.1", - "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": "^2.3.2", - "@sigstore/core": "^1.1.0" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } -} diff --git a/node_modules/@tufjs/models/dist/base.js b/node_modules/@tufjs/models/dist/base.js deleted file mode 100644 index 259f6799c13a0..0000000000000 --- a/node_modules/@tufjs/models/dist/base.js +++ /dev/null @@ -1,83 +0,0 @@ -"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.isMetadataKind = exports.MetadataKind = void 0; -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)); -} -exports.isMetadataKind = isMetadataKind; -/*** - * 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 || new Date().toISOString(); - this.version = options.version || 1; - 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) && !(typeof spec_version === 'string')) { - throw new TypeError('spec_version must be a string'); - } - if (utils_1.guard.isDefined(expires) && !(typeof expires === 'string')) { - throw new TypeError('expires must be a string'); - } - if (utils_1.guard.isDefined(version) && !(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)); -} diff --git a/node_modules/@tufjs/models/dist/file.js b/node_modules/@tufjs/models/dist/file.js deleted file mode 100644 index b35fe5950bbb7..0000000000000 --- a/node_modules/@tufjs/models/dist/file.js +++ /dev/null @@ -1,183 +0,0 @@ -"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'); - } -} diff --git a/node_modules/@tufjs/models/dist/key.js b/node_modules/@tufjs/models/dist/key.js deleted file mode 100644 index 5e55b09d7c6dd..0000000000000 --- a/node_modules/@tufjs/models/dist/key.js +++ /dev/null @@ -1,85 +0,0 @@ -"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; diff --git a/node_modules/@tufjs/models/dist/timestamp.js b/node_modules/@tufjs/models/dist/timestamp.js deleted file mode 100644 index 9880c4c9fc254..0000000000000 --- a/node_modules/@tufjs/models/dist/timestamp.js +++ /dev/null @@ -1,58 +0,0 @@ -"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; -} diff --git a/node_modules/@tufjs/models/dist/utils/index.js b/node_modules/@tufjs/models/dist/utils/index.js deleted file mode 100644 index 872aae28049c9..0000000000000 --- a/node_modules/@tufjs/models/dist/utils/index.js +++ /dev/null @@ -1,28 +0,0 @@ -"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")); diff --git a/node_modules/@tufjs/models/dist/utils/key.js b/node_modules/@tufjs/models/dist/utils/key.js deleted file mode 100644 index 1f795ba1a2733..0000000000000 --- a/node_modules/@tufjs/models/dist/utils/key.js +++ /dev/null @@ -1,143 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getPublicKey = void 0; -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}`); - } -} -exports.getPublicKey = getPublicKey; -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); diff --git a/node_modules/@tufjs/models/dist/utils/oid.js b/node_modules/@tufjs/models/dist/utils/oid.js deleted file mode 100644 index e1bb7af5e54fb..0000000000000 --- a/node_modules/@tufjs/models/dist/utils/oid.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.encodeOIDString = void 0; -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]); -} -exports.encodeOIDString = encodeOIDString; -function encodeVariableLengthInteger(value) { - const bytes = []; - let mask = 0x00; - while (value > 0) { - bytes.unshift((value & 0x7f) | mask); - value >>= 7; - mask = 0x80; - } - return bytes; -} diff --git a/node_modules/@tufjs/models/package.json b/node_modules/@tufjs/models/package.json deleted file mode 100644 index be581591a0f3a..0000000000000 --- a/node_modules/@tufjs/models/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "@tufjs/models", - "version": "2.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.4" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } -} diff --git a/node_modules/abbrev/lib/index.js b/node_modules/abbrev/lib/index.js index 9f48801f049c9..f7bee0c6fc7ad 100644 --- a/node_modules/abbrev/lib/index.js +++ b/node_modules/abbrev/lib/index.js @@ -1,7 +1,10 @@ module.exports = abbrev function abbrev (...args) { - let list = args.length === 1 || Array.isArray(args[0]) ? args[0] : args + let list = args + if (args.length === 1 && (Array.isArray(args[0]) || typeof args[0] === 'string')) { + list = [].concat(args[0]) + } for (let i = 0, l = list.length; i < l; i++) { list[i] = typeof list[i] === 'string' ? list[i] : String(list[i]) diff --git a/node_modules/abbrev/package.json b/node_modules/abbrev/package.json index e26400445631a..47798d9a32fcf 100644 --- a/node_modules/abbrev/package.json +++ b/node_modules/abbrev/package.json @@ -1,43 +1,42 @@ { "name": "abbrev", - "version": "2.0.0", + "version": "5.0.0", "description": "Like ruby's abbrev module, but in js", "author": "GitHub Inc.", "main": "lib/index.js", "scripts": { - "test": "tap", - "lint": "eslint \"**/*.js\"", + "test": "node --test './test/**/*.js'", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" + "lintfix": "npm run eslint -- --fix", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'", + "test:node20": "node --test test" }, "repository": { "type": "git", - "url": "https://github.com/npm/abbrev-js.git" + "url": "git+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/**" - ] + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0" }, "files": [ "bin/", "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.8.0" + "version": "5.0.0", + "publish": true, + "testRunner": "node:test", + "latestCiVersion": 24 } } diff --git a/node_modules/agent-base/dist/helpers.js b/node_modules/agent-base/dist/helpers.js deleted file mode 100644 index ef3f92022d455..0000000000000 --- a/node_modules/agent-base/dist/helpers.js +++ /dev/null @@ -1,66 +0,0 @@ -"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 \ No newline at end of file diff --git a/node_modules/agent-base/dist/index.js b/node_modules/agent-base/dist/index.js deleted file mode 100644 index 69396356e74db..0000000000000 --- a/node_modules/agent-base/dist/index.js +++ /dev/null @@ -1,175 +0,0 @@ -"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) { - // @ts-expect-error `addRequest()` isn't defined in `@types/node` - return socket.addRequest(req, connectOpts); - } - 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 \ No newline at end of file diff --git a/node_modules/agent-base/package.json b/node_modules/agent-base/package.json deleted file mode 100644 index 8e95171707fef..0000000000000 --- a/node_modules/agent-base/package.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "agent-base", - "version": "7.1.1", - "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", - "dependencies": { - "debug": "^4.3.4" - }, - "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": "^3.3.3", - "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" - } -} \ No newline at end of file diff --git a/node_modules/aggregate-error/index.js b/node_modules/aggregate-error/index.js deleted file mode 100644 index ba5bf02211685..0000000000000 --- a/node_modules/aggregate-error/index.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; -const indentString = require('indent-string'); -const cleanStack = require('clean-stack'); - -const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); - -class AggregateError extends Error { - constructor(errors) { - if (!Array.isArray(errors)) { - throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); - } - - errors = [...errors].map(error => { - if (error instanceof Error) { - return error; - } - - if (error !== null && typeof error === 'object') { - // Handle plain error objects with message property and/or possibly other metadata - return Object.assign(new Error(error.message), error); - } - - return new Error(error); - }); - - let message = errors - .map(error => { - // The `stack` property is not standardized, so we can't assume it exists - return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); - }) - .join('\n'); - message = '\n' + indentString(message, 4); - super(message); - - this.name = 'AggregateError'; - - Object.defineProperty(this, '_errors', {value: errors}); - } - - * [Symbol.iterator]() { - for (const error of this._errors) { - yield error; - } - } -} - -module.exports = AggregateError; diff --git a/node_modules/aggregate-error/license b/node_modules/aggregate-error/license deleted file mode 100644 index e7af2f77107d7..0000000000000 --- a/node_modules/aggregate-error/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/aggregate-error/package.json b/node_modules/aggregate-error/package.json deleted file mode 100644 index 74fcc37611e64..0000000000000 --- a/node_modules/aggregate-error/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "aggregate-error", - "version": "3.1.0", - "description": "Create an error from multiple errors", - "license": "MIT", - "repository": "sindresorhus/aggregate-error", - "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": [ - "aggregate", - "error", - "combine", - "multiple", - "many", - "collection", - "iterable", - "iterator" - ], - "dependencies": { - "clean-stack": "^2.0.0", - "indent-string": "^4.0.0" - }, - "devDependencies": { - "ava": "^2.4.0", - "tsd": "^0.7.1", - "xo": "^0.25.3" - } -} diff --git a/node_modules/ansi-regex/index.js b/node_modules/ansi-regex/index.js deleted file mode 100644 index 616ff837d3ff0..0000000000000 --- a/node_modules/ansi-regex/index.js +++ /dev/null @@ -1,10 +0,0 @@ -'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'); -}; diff --git a/node_modules/ansi-regex/license b/node_modules/ansi-regex/license deleted file mode 100644 index e7af2f77107d7..0000000000000 --- a/node_modules/ansi-regex/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/ansi-regex/package.json b/node_modules/ansi-regex/package.json deleted file mode 100644 index 017f53116a9e2..0000000000000 --- a/node_modules/ansi-regex/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/ansi-styles/index.js b/node_modules/ansi-styles/index.js deleted file mode 100644 index d7bede44b7b6b..0000000000000 --- a/node_modules/ansi-styles/index.js +++ /dev/null @@ -1,223 +0,0 @@ -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; diff --git a/node_modules/ansi-styles/license b/node_modules/ansi-styles/license deleted file mode 100644 index fa7ceba3eb4a9..0000000000000 --- a/node_modules/ansi-styles/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/ansi-styles/package.json b/node_modules/ansi-styles/package.json deleted file mode 100644 index 6cd3ca5bf95d0..0000000000000 --- a/node_modules/ansi-styles/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/aproba/index.js b/node_modules/aproba/index.js index fd947481ba557..5a58e8126520c 100644 --- a/node_modules/aproba/index.js +++ b/node_modules/aproba/index.js @@ -97,7 +97,7 @@ function moreThanOneError (schema) { } function newException (code, msg) { - const err = new Error(msg) + const err = new TypeError(msg) err.code = code /* istanbul ignore else */ if (Error.captureStackTrace) Error.captureStackTrace(err, validate) diff --git a/node_modules/aproba/package.json b/node_modules/aproba/package.json index d2212d30d8edd..71c7fca58d3c4 100644 --- a/node_modules/aproba/package.json +++ b/node_modules/aproba/package.json @@ -1,6 +1,6 @@ { "name": "aproba", - "version": "2.0.0", + "version": "2.1.0", "description": "A ridiculously light-weight argument validator (now browser friendly)", "main": "index.js", "directories": { diff --git a/node_modules/balanced-match/LICENSE.md b/node_modules/balanced-match/LICENSE.md index 2cdc8e4148cc0..61ece8cc92afb 100644 --- a/node_modules/balanced-match/LICENSE.md +++ b/node_modules/balanced-match/LICENSE.md @@ -1,6 +1,8 @@ (MIT) -Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> +Original code Copyright Julian Gruber + +Port to TypeScript Copyright Isaac Z. Schlueter 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 diff --git a/node_modules/balanced-match/dist/commonjs/index.js b/node_modules/balanced-match/dist/commonjs/index.js new file mode 100644 index 0000000000000..0c9014bac1531 --- /dev/null +++ b/node_modules/balanced-match/dist/commonjs/index.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.range = exports.balanced = void 0; +const balanced = (a, b, str) => { + const ma = a instanceof RegExp ? maybeMatch(a, str) : a; + const mb = b instanceof RegExp ? maybeMatch(b, str) : b; + const r = ma !== null && mb != null && (0, exports.range)(ma, mb, str); + return (r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + ma.length, r[1]), + post: str.slice(r[1] + mb.length), + }); +}; +exports.balanced = balanced; +const maybeMatch = (reg, str) => { + const m = str.match(reg); + return m ? m[0] : null; +}; +const range = (a, b, str) => { + let begs, beg, left, right = undefined, result; + let ai = str.indexOf(a); + let bi = str.indexOf(b, ai + 1); + let 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) { + const r = begs.pop(); + if (r !== undefined) + result = [r, bi]; + } + else { + beg = begs.pop(); + if (beg !== undefined && beg < left) { + left = beg; + right = bi; + } + bi = str.indexOf(b, i + 1); + } + i = ai < bi && ai >= 0 ? ai : bi; + } + if (begs.length && right !== undefined) { + result = [left, right]; + } + } + return result; +}; +exports.range = range; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/jackspeak/dist/commonjs/package.json b/node_modules/balanced-match/dist/commonjs/package.json similarity index 100% rename from node_modules/jackspeak/dist/commonjs/package.json rename to node_modules/balanced-match/dist/commonjs/package.json diff --git a/node_modules/balanced-match/dist/esm/index.js b/node_modules/balanced-match/dist/esm/index.js new file mode 100644 index 0000000000000..fe81200f9d676 --- /dev/null +++ b/node_modules/balanced-match/dist/esm/index.js @@ -0,0 +1,54 @@ +export const balanced = (a, b, str) => { + const ma = a instanceof RegExp ? maybeMatch(a, str) : a; + const mb = b instanceof RegExp ? maybeMatch(b, str) : b; + const r = ma !== null && mb != null && range(ma, mb, str); + return (r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + ma.length, r[1]), + post: str.slice(r[1] + mb.length), + }); +}; +const maybeMatch = (reg, str) => { + const m = str.match(reg); + return m ? m[0] : null; +}; +export const range = (a, b, str) => { + let begs, beg, left, right = undefined, result; + let ai = str.indexOf(a); + let bi = str.indexOf(b, ai + 1); + let 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) { + const r = begs.pop(); + if (r !== undefined) + result = [r, bi]; + } + else { + beg = begs.pop(); + if (beg !== undefined && beg < left) { + left = beg; + right = bi; + } + bi = str.indexOf(b, i + 1); + } + i = ai < bi && ai >= 0 ? ai : bi; + } + if (begs.length && right !== undefined) { + result = [left, right]; + } + } + return result; +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/jackspeak/dist/esm/package.json b/node_modules/balanced-match/dist/esm/package.json similarity index 100% rename from node_modules/jackspeak/dist/esm/package.json rename to node_modules/balanced-match/dist/esm/package.json diff --git a/node_modules/balanced-match/index.js b/node_modules/balanced-match/index.js deleted file mode 100644 index c67a64608df7f..0000000000000 --- a/node_modules/balanced-match/index.js +++ /dev/null @@ -1,62 +0,0 @@ -'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; -} diff --git a/node_modules/balanced-match/package.json b/node_modules/balanced-match/package.json index ce6073e0403b5..48f1a638d0b67 100644 --- a/node_modules/balanced-match/package.json +++ b/node_modules/balanced-match/package.json @@ -1,20 +1,49 @@ { "name": "balanced-match", "description": "Match balanced character pairs, like \"{\" and \"}\"", - "version": "1.0.2", + "version": "4.0.4", + "files": [ + "dist" + ], "repository": { "type": "git", "url": "git://github.com/juliangruber/balanced-match.git" }, - "homepage": "https://github.com/juliangruber/balanced-match", - "main": "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" + } + } + }, + "type": "module", "scripts": { - "test": "tape test/test.js", - "bench": "matcha test/bench.js" + "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 .", + "benchmark": "node benchmark/index.js", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" }, "devDependencies": { - "matcha": "^0.7.0", - "tape": "^4.6.0" + "@types/brace-expansion": "^1.1.2", + "@types/node": "^25.2.1", + "mkdirp": "^3.0.1", + "prettier": "^3.3.2", + "tap": "^21.6.2", + "tshy": "^3.0.2", + "typedoc": "^0.28.5" }, "keywords": [ "match", @@ -23,26 +52,17 @@ "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" - ] - } + "engines": { + "node": "18 || 20 || >=22" + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js" } diff --git a/node_modules/bin-links/lib/check-bin.js b/node_modules/bin-links/lib/check-bin.js index c5b997bb96355..a7fc8d51b415e 100644 --- a/node_modules/bin-links/lib/check-bin.js +++ b/node_modules/bin-links/lib/check-bin.js @@ -2,7 +2,7 @@ // 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 { resolve, dirname, sep } = require('path') const readCmdShim = require('read-cmd-shim') const { readlink } = require('fs/promises') @@ -34,7 +34,9 @@ const checkLink = async ({ target, path }) => { const resolved = resolve(dirname(target), current) - if (resolved.toLowerCase().indexOf(path.toLowerCase()) !== 0) { + const resolvedLower = resolved.toLowerCase() + const pathLower = path.toLowerCase() + if (resolvedLower !== pathLower && !resolvedLower.startsWith(pathLower + sep)) { return failEEXIST({ target }) } } @@ -65,7 +67,9 @@ const checkShim = async ({ target, path }) => { const resolved = resolve(dirname(shim), current.replace(/\\/g, '/')) - if (resolved.toLowerCase().indexOf(path.toLowerCase()) !== 0) { + const resolvedLower = resolved.toLowerCase() + const pathLower = path.toLowerCase() + if (resolvedLower !== pathLower && !resolvedLower.startsWith(pathLower + sep)) { return failEEXIST({ target: shim }) } })) diff --git a/node_modules/bin-links/lib/fix-bin.js b/node_modules/bin-links/lib/fix-bin.js index 453bd4f3e95b1..cb54e2fda19c2 100644 --- a/node_modules/bin-links/lib/fix-bin.js +++ b/node_modules/bin-links/lib/fix-bin.js @@ -4,6 +4,7 @@ const { chmod, open, readFile, + stat, } = require('fs/promises') const execMode = 0o777 & (~process.umask()) @@ -35,7 +36,8 @@ 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) +const fixBin = (file, mode = execMode) => stat(file) + .then(st => (st.mode & mode) === mode ? null : chmod(file, mode)) .then(() => isWindowsHashbangFile(file)) .then(isWHB => isWHB ? dos2Unix(file) : null) diff --git a/node_modules/bin-links/lib/index.js b/node_modules/bin-links/lib/index.js index ab3bd13c0be6b..b9b03422d2dcc 100644 --- a/node_modules/bin-links/lib/index.js +++ b/node_modules/bin-links/lib/index.js @@ -1,30 +1,22 @@ 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 + // global top pkgs on windows get bins installed in {prefix}. // - // unix global top pkgs get their bins installed in {prefix}/bin, - // and mans in {prefix}/share/man + // unix global top pkgs get their bins installed in {prefix}/bin. // - // non-top pkgs get their bins installed in {prefix}/node_modules/.bin, - // and do not install mans + // non-top pkgs get their bins installed in {prefix}/node_modules/.bin. // - // 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. + // non-global top pkgs don't have any bins 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. + // + // As of v7, bin-links no longer installs man pages into the system man path for any package. `getPaths` still returns legacy man paths so pre-existing installs can be cleaned up on uninstall. 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 }), - ]) + // 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. + return linkBins({ path, pkg, top, force: force || !top }) } const shimBin = require('./shim-bin.js') diff --git a/node_modules/bin-links/lib/link-gently.js b/node_modules/bin-links/lib/link-gently.js index d1e955ec99b02..c4a38f7f54b95 100644 --- a/node_modules/bin-links/lib/link-gently.js +++ b/node_modules/bin-links/lib/link-gently.js @@ -4,12 +4,18 @@ // if there's a symlink already, pointing into our pkg, remove it first // then create the symlink -const { resolve, dirname } = require('path') +const { resolve, dirname, sep } = require('path') const { lstat, mkdir, readlink, rm, symlink } = require('fs/promises') -const throwNonEnoent = er => { - if (er.code !== 'ENOENT') { - throw er +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 = { @@ -37,8 +43,8 @@ const linkGently = async ({ path, to, from, absFrom, force }) => { // 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(throwNonEnoent), - lstat(to).catch(throwNonEnoent), + lstat(absFrom).catch(throwSignificant), + lstat(to).catch(throwSignificant), ]).then(([stFrom, stTo]) => { // not present in package, skip it if (!stFrom) { @@ -57,7 +63,7 @@ const linkGently = async ({ path, to, from, absFrom, force }) => { } // skip it, already set up like we want it. target = resolve(dirname(to), target) - if (target.indexOf(path) === 0 || force) { + if (target === path || target.startsWith(path + sep) || force) { return rm(to, rmOpts).then(() => CLOBBER) } // neither skip nor clobber diff --git a/node_modules/bin-links/lib/link-mans.js b/node_modules/bin-links/lib/link-mans.js deleted file mode 100644 index b6dd214cebdfe..0000000000000 --- a/node_modules/bin-links/lib/link-mans.js +++ /dev/null @@ -1,53 +0,0 @@ -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 diff --git a/node_modules/bin-links/lib/shim-bin.js b/node_modules/bin-links/lib/shim-bin.js index 67e2702702f0a..91a6fcc94153b 100644 --- a/node_modules/bin-links/lib/shim-bin.js +++ b/node_modules/bin-links/lib/shim-bin.js @@ -1,4 +1,4 @@ -const { resolve, dirname } = require('path') +const { resolve, dirname, sep } = require('path') const { lstat } = require('fs/promises') const throwNonEnoent = er => { if (er.code !== 'ENOENT') { @@ -64,7 +64,8 @@ const shimBin = ({ path, to, from, absFrom, force }) => { return readCmdShim(s) .then(target => { target = resolve(dirname(to), target) - if (target.indexOf(resolve(path)) !== 0) { + const base = resolve(path) + if (target !== base && !target.startsWith(base + sep)) { return failEEXIST({ from, to, path }) } return false diff --git a/node_modules/npm-bundled/LICENSE b/node_modules/bin-links/node_modules/cmd-shim/LICENSE similarity index 100% rename from node_modules/npm-bundled/LICENSE rename to node_modules/bin-links/node_modules/cmd-shim/LICENSE diff --git a/node_modules/bin-links/node_modules/cmd-shim/lib/index.js b/node_modules/bin-links/node_modules/cmd-shim/lib/index.js new file mode 100644 index 0000000000000..a1f1548b38d42 --- /dev/null +++ b/node_modules/bin-links/node_modules/cmd-shim/lib/index.js @@ -0,0 +1,283 @@ +// 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) + shTarget = shTarget.split('\\').join('/') + let target = shTarget.split('/').join('\\') + let pwshTarget = shTarget + let longProg + let shProg = prog && prog.split('\\').join('/') + let shLongProg + let pwshProg = shProg && `"${shProg}$exe"` + let pwshLongProg + args = args || '' + variables = variables || '' + if (!prog) { + prog = `"%dp0%\\${target}"` + shProg = `"$basedir/${shTarget}"` + pwshProg = shProg + args = '' + target = '' + shTarget = '' + pwshTarget = '' + } else { + longProg = `"%dp0%\\${prog}.exe"` + shLongProg = `"$basedir/${prog}"` + pwshLongProg = `"$basedir/${prog}$exe"` + target = `"%dp0%\\${target}"` + shTarget = `"$basedir_win/${shTarget}"` + pwshTarget = `"$basedir/${pwshTarget}"` + } + + // 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) { + 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 "$(echo "$0" | sed -e 's,\\,/,g')") + // basedir_win="$basedir" + // + // case `uname -a` in + // *CYGWIN*|*MINGW*|*MSYS*) + // if command -v cygpath > /dev/null 2>&1; then + // basedir_win=`cygpath -w "$basedir"` + // fi + // ;; + // *WSL2*) + // if command -v wslpath > /dev/null 2>&1; then + // basedir_win="$(wslpath -w "$basedir" 2> /dev/null)" + // if [ $? -ne 0 ] || [ -z "$basedir_win" ]; then + // echo "Error: wslpath failed to convert path. WSL environment may be misconfigured." >&2 + // exit 1 + // fi + // fi + // ;; + // esac + // + // PROG_EXE="$basedir/node.exe" + // if ! [ -x "$PROG_EXE" ]; then + // PROG_EXE="$basedir/node" + // if ! [ -x "$PROG_EXE" ]; then + // PROG_EXE=node + // if ! [ -x "$PROG_EXE" ]; then + // PROG_EXE=node.exe + // fi + // fi + // fi + // + // exec "$PROG_EXE" "$basedir_win/node_modules/npm/bin/npm-cli.js" "$@" + + let sh = '#!/bin/sh\n' + + sh = sh + + `basedir=$(dirname "$(echo "$0" | sed -e 's,\\\\,/,g')")\n` + + 'basedir_win="$basedir"\n' + + '\n' + + 'case `uname -a` in\n' + + ' *CYGWIN*|*MINGW*|*MSYS*)\n' + + ' if command -v cygpath > /dev/null 2>&1; then\n' + + ' basedir_win=`cygpath -w "$basedir"`\n' + + ' fi\n' + + ' ;;\n' + + ' *WSL2*)\n' + + ' if command -v wslpath > /dev/null 2>&1; then\n' + + ' basedir_win="$(wslpath -w "$basedir" 2> /dev/null)"\n' + + ' if [ $? -ne 0 ] || [ -z "$basedir_win" ]; then\n' + + ' echo "Error: wslpath failed to convert path. WSL environment may be misconfigured." >&2\n' + + ' exit 1\n' + + ' fi\n' + + ' fi\n' + + ' ;;\n' + + 'esac\n' + + '\n' + + if (shLongProg) { + sh = sh + + `PROG_EXE=${shLongProg.replace(/"$/, '.exe"')}\n` + + 'if ! [ -x "$PROG_EXE" ]; then\n' + + ` PROG_EXE=${shLongProg}\n` + + ' if ! [ -x "$PROG_EXE" ]; then\n' + + ` PROG_EXE=${shProg}\n` + + ' if ! [ -x "$PROG_EXE" ]; then\n' + + ` PROG_EXE=${shProg}.exe\n` + + ' fi\n' + + ' fi\n' + + 'fi\n' + + '\n' + + `exec ${variables}"$PROG_EXE" ${args} ${shTarget} "$@"\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 (pwshLongProg) { + pwsh = pwsh + + '$ret=0\n' + + `if (Test-Path ${pwshLongProg}) {\n` + + ' # Support pipeline input\n' + + ' if ($MyInvocation.ExpectingInput) {\n' + + ` $input | & ${pwshLongProg} ${args} ${pwshTarget} $args\n` + + ' } else {\n' + + ` & ${pwshLongProg} ${args} ${pwshTarget} $args\n` + + ' }\n' + + ' $ret=$LASTEXITCODE\n' + + '} else {\n' + + ' # Support pipeline input\n' + + ' if ($MyInvocation.ExpectingInput) {\n' + + ` $input | & ${pwshProg} ${args} ${pwshTarget} $args\n` + + ' } else {\n' + + ` & ${pwshProg} ${args} ${pwshTarget} $args\n` + + ' }\n' + + ' $ret=$LASTEXITCODE\n' + + '}\n' + + 'exit $ret\n' + } else { + pwsh = pwsh + + '# Support pipeline input\n' + + 'if ($MyInvocation.ExpectingInput) {\n' + + ` $input | & ${pwshProg} ${args} ${pwshTarget} $args\n` + + '} else {\n' + + ` & ${pwshProg} ${args} ${pwshTarget} $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 diff --git a/node_modules/cmd-shim/lib/to-batch-syntax.js b/node_modules/bin-links/node_modules/cmd-shim/lib/to-batch-syntax.js similarity index 100% rename from node_modules/cmd-shim/lib/to-batch-syntax.js rename to node_modules/bin-links/node_modules/cmd-shim/lib/to-batch-syntax.js diff --git a/node_modules/bin-links/node_modules/cmd-shim/package.json b/node_modules/bin-links/node_modules/cmd-shim/package.json new file mode 100644 index 0000000000000..445755b1fdfd4 --- /dev/null +++ b/node_modules/bin-links/node_modules/cmd-shim/package.json @@ -0,0 +1,48 @@ +{ + "name": "cmd-shim", + "version": "9.0.1", + "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": "^7.0.0", + "@npmcli/template-oss": "5.1.0", + "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": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "5.1.0", + "publish": true + } +} diff --git a/node_modules/bin-links/node_modules/npm-normalize-package-bin/LICENSE b/node_modules/bin-links/node_modules/npm-normalize-package-bin/LICENSE new file mode 100644 index 0000000000000..19cec97b18468 --- /dev/null +++ b/node_modules/bin-links/node_modules/npm-normalize-package-bin/LICENSE @@ -0,0 +1,15 @@ +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. diff --git a/node_modules/bin-links/node_modules/npm-normalize-package-bin/lib/index.js b/node_modules/bin-links/node_modules/npm-normalize-package-bin/lib/index.js new file mode 100644 index 0000000000000..3cb8478cf6e2f --- /dev/null +++ b/node_modules/bin-links/node_modules/npm-normalize-package-bin/lib/index.js @@ -0,0 +1,64 @@ +// 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 diff --git a/node_modules/bin-links/node_modules/npm-normalize-package-bin/package.json b/node_modules/bin-links/node_modules/npm-normalize-package-bin/package.json new file mode 100644 index 0000000000000..1d0d821b7a2ce --- /dev/null +++ b/node_modules/bin-links/node_modules/npm-normalize-package-bin/package.json @@ -0,0 +1,42 @@ +{ + "name": "npm-normalize-package-bin", + "version": "6.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": "node --test './test/**/*.js'", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "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}\"", + "test:node20": "node --test test", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'" + }, + "devDependencies": { + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0" + }, + "files": [ + "bin/", + "lib/" + ], + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "5.0.0", + "publish": "true", + "testRunner": "node:test", + "latestCiVersion": 24 + } +} diff --git a/node_modules/read-cmd-shim/LICENSE b/node_modules/bin-links/node_modules/read-cmd-shim/LICENSE similarity index 100% rename from node_modules/read-cmd-shim/LICENSE rename to node_modules/bin-links/node_modules/read-cmd-shim/LICENSE diff --git a/node_modules/read-cmd-shim/lib/index.js b/node_modules/bin-links/node_modules/read-cmd-shim/lib/index.js similarity index 100% rename from node_modules/read-cmd-shim/lib/index.js rename to node_modules/bin-links/node_modules/read-cmd-shim/lib/index.js diff --git a/node_modules/bin-links/node_modules/read-cmd-shim/package.json b/node_modules/bin-links/node_modules/read-cmd-shim/package.json new file mode 100644 index 0000000000000..cfd11bfe148b5 --- /dev/null +++ b/node_modules/bin-links/node_modules/read-cmd-shim/package.json @@ -0,0 +1,44 @@ +{ + "name": "read-cmd-shim", + "version": "7.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": "^6.0.0", + "@npmcli/template-oss": "5.0.0", + "cmd-shim": "^8.0.0" + }, + "scripts": { + "test": "node --test './test/**/*.js'", + "lint": "npm run eslint", + "postlint": "template-oss-check", + "template-oss-apply": "template-oss-apply --force", + "lintfix": "npm run eslint -- --fix", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'", + "test:node20": "node --test test" + }, + "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": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "5.0.0", + "publish": true, + "testRunner": "node:test", + "latestCiVersion": 24 + } +} diff --git a/node_modules/write-file-atomic/LICENSE.md b/node_modules/bin-links/node_modules/write-file-atomic/LICENSE.md similarity index 100% rename from node_modules/write-file-atomic/LICENSE.md rename to node_modules/bin-links/node_modules/write-file-atomic/LICENSE.md diff --git a/node_modules/bin-links/node_modules/write-file-atomic/lib/index.js b/node_modules/bin-links/node_modules/write-file-atomic/lib/index.js new file mode 100644 index 0000000000000..d470cdd18de8c --- /dev/null +++ b/node_modules/bin-links/node_modules/write-file-atomic/lib/index.js @@ -0,0 +1,269 @@ +'use strict' +module.exports = writeFile +module.exports.sync = writeFileSync +module.exports._getTmpname = getTmpname // for testing +module.exports._cleanupOnExit = cleanupOnExit + +const fs = require('fs') +const crypto = require('node:crypto') +const { onExit } = require('signal-exit') +const path = require('path') +const { promisify } = require('util') +const activeFiles = {} + +// if we run inside of a worker_thread, `process.pid` is not unique +/* istanbul ignore next */ +const threadId = (function getId () { + try { + const workerThreads = require('worker_threads') + + /// if we are in main thread, this is set to `0` + return workerThreads.threadId + } catch (e) { + // worker_threads are not available, fallback to 0 + return 0 + } +})() + +let invocations = 0 +function getTmpname (filename) { + return filename + '.' + + crypto.createHash('sha1') + .update(__filename) + .update(String(process.pid)) + .update(String(threadId)) + .update(String(++invocations)) + .digest() + .readUInt32BE(0) +} + +function cleanupOnExit (tmpfile) { + return () => { + try { + fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile) + } catch { + // ignore errors + } + } +} + +function serializeActiveFile (absoluteName) { + return new Promise(resolve => { + // make a queue if it doesn't already exist + if (!activeFiles[absoluteName]) { + activeFiles[absoluteName] = [] + } + + activeFiles[absoluteName].push(resolve) // add this job to the queue + if (activeFiles[absoluteName].length === 1) { + resolve() + } // kick off the first one + }) +} + +// https://github.com/isaacs/node-graceful-fs/blob/master/polyfills.js#L315-L342 +function isChownErrOk (err) { + if (err.code === 'ENOSYS') { + return true + } + + const nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (err.code === 'EINVAL' || err.code === 'EPERM') { + return true + } + } + + return false +} + +async function writeFileAsync (filename, data, options = {}) { + if (typeof options === 'string') { + options = { encoding: options } + } + + let fd + let tmpfile + /* istanbul ignore next -- The closure only gets called when onExit triggers */ + const removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile)) + const absoluteName = path.resolve(filename) + + try { + await serializeActiveFile(absoluteName) + const truename = await promisify(fs.realpath)(filename).catch(() => filename) + tmpfile = getTmpname(truename) + + if (!options.mode || !options.chown) { + // Either mode or chown is not explicitly set + // Default behavior is to copy it from original file + const stats = await promisify(fs.stat)(truename).catch(() => {}) + if (stats) { + if (options.mode == null) { + options.mode = stats.mode + } + + if (options.chown == null && process.getuid) { + options.chown = { uid: stats.uid, gid: stats.gid } + } + } + } + + fd = await promisify(fs.open)(tmpfile, 'w', options.mode) + if (options.tmpfileCreated) { + await options.tmpfileCreated(tmpfile) + } + if (ArrayBuffer.isView(data)) { + await promisify(fs.write)(fd, data, 0, data.length, 0) + } else if (data != null) { + await promisify(fs.write)(fd, String(data), 0, String(options.encoding || 'utf8')) + } + + if (options.fsync !== false) { + await promisify(fs.fsync)(fd) + } + + await promisify(fs.close)(fd) + fd = null + + if (options.chown) { + await promisify(fs.chown)(tmpfile, options.chown.uid, options.chown.gid).catch(err => { + if (!isChownErrOk(err)) { + throw err + } + }) + } + + if (options.mode) { + await promisify(fs.chmod)(tmpfile, options.mode).catch(err => { + if (!isChownErrOk(err)) { + throw err + } + }) + } + + await promisify(fs.rename)(tmpfile, truename) + } finally { + if (fd) { + await promisify(fs.close)(fd).catch( + /* istanbul ignore next */ + () => {} + ) + } + removeOnExitHandler() + await promisify(fs.unlink)(tmpfile).catch(() => {}) + activeFiles[absoluteName].shift() // remove the element added by serializeSameFile + if (activeFiles[absoluteName].length > 0) { + activeFiles[absoluteName][0]() // start next job if one is pending + } else { + delete activeFiles[absoluteName] + } + } +} + +async function writeFile (filename, data, options, callback) { + if (options instanceof Function) { + callback = options + options = {} + } + + const promise = writeFileAsync(filename, data, options) + if (callback) { + try { + const result = await promise + return callback(result) + } catch (err) { + return callback(err) + } + } + + return promise +} + +function writeFileSync (filename, data, options) { + if (typeof options === 'string') { + options = { encoding: options } + } else if (!options) { + options = {} + } + try { + filename = fs.realpathSync(filename) + } catch (ex) { + // it's ok, it'll happen on a not yet existing file + } + const tmpfile = getTmpname(filename) + + if (!options.mode || !options.chown) { + // Either mode or chown is not explicitly set + // Default behavior is to copy it from original file + try { + const stats = fs.statSync(filename) + options = Object.assign({}, options) + if (!options.mode) { + options.mode = stats.mode + } + if (!options.chown && process.getuid) { + options.chown = { uid: stats.uid, gid: stats.gid } + } + } catch (ex) { + // ignore stat errors + } + } + + let fd + const cleanup = cleanupOnExit(tmpfile) + const removeOnExitHandler = onExit(cleanup) + + let threw = true + try { + fd = fs.openSync(tmpfile, 'w', options.mode || 0o666) + if (options.tmpfileCreated) { + options.tmpfileCreated(tmpfile) + } + if (ArrayBuffer.isView(data)) { + fs.writeSync(fd, data, 0, data.length, 0) + } else if (data != null) { + fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8')) + } + if (options.fsync !== false) { + fs.fsyncSync(fd) + } + + fs.closeSync(fd) + fd = null + + if (options.chown) { + try { + fs.chownSync(tmpfile, options.chown.uid, options.chown.gid) + } catch (err) { + if (!isChownErrOk(err)) { + throw err + } + } + } + + if (options.mode) { + try { + fs.chmodSync(tmpfile, options.mode) + } catch (err) { + if (!isChownErrOk(err)) { + throw err + } + } + } + + fs.renameSync(tmpfile, filename) + threw = false + } finally { + if (fd) { + try { + fs.closeSync(fd) + } catch (ex) { + // ignore close errors at this stage, error may have closed fd already. + } + } + removeOnExitHandler() + if (threw) { + cleanup() + } + } +} diff --git a/node_modules/bin-links/node_modules/write-file-atomic/package.json b/node_modules/bin-links/node_modules/write-file-atomic/package.json new file mode 100644 index 0000000000000..200ca040e3d45 --- /dev/null +++ b/node_modules/bin-links/node_modules/write-file-atomic/package.json @@ -0,0 +1,57 @@ +{ + "name": "write-file-atomic", + "version": "8.0.0", + "description": "Write files in an atomic fashion w/configurable ownership", + "main": "./lib/index.js", + "scripts": { + "test": "tap", + "posttest": "npm run lint", + "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}\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/npm/write-file-atomic.git" + }, + "keywords": [ + "writeFile", + "atomic" + ], + "author": "GitHub Inc.", + "license": "ISC", + "bugs": { + "url": "https://github.com/npm/write-file-atomic/issues" + }, + "homepage": "https://github.com/npm/write-file-atomic", + "dependencies": { + "signal-exit": "^4.0.1" + }, + "devDependencies": { + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0", + "tap": "^16.0.1" + }, + "files": [ + "bin/", + "lib/" + ], + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "windowsCI": false, + "version": "5.0.0", + "publish": "true" + }, + "tap": { + "nyc-arg": [ + "--exclude", + "tap-snapshots/**" + ] + } +} diff --git a/node_modules/bin-links/package.json b/node_modules/bin-links/package.json index 1872756bb4b48..a6d8ae822178f 100644 --- a/node_modules/bin-links/package.json +++ b/node_modules/bin-links/package.json @@ -1,16 +1,17 @@ { "name": "bin-links", - "version": "4.0.4", + "version": "7.0.0", "description": "JavaScript package binary linker", "main": "./lib/index.js", "scripts": { "snap": "tap", "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", @@ -23,14 +24,15 @@ ], "license": "ISC", "dependencies": { - "cmd-shim": "^6.0.0", - "npm-normalize-package-bin": "^3.0.0", - "read-cmd-shim": "^4.0.0", - "write-file-atomic": "^5.0.0" + "cmd-shim": "^9.0.0", + "npm-normalize-package-bin": "^6.0.0", + "proc-log": "^7.0.0", + "read-cmd-shim": "^7.0.0", + "write-file-atomic": "^8.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.1.0", "require-inject": "^1.4.4", "tap": "^16.0.1" }, @@ -47,13 +49,14 @@ "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.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.22.0", - "publish": true + "version": "5.1.0", + "publish": true, + "updateNpm": false } } diff --git a/node_modules/binary-extensions/binary-extensions.json b/node_modules/binary-extensions/binary-extensions.json index ac08048e40e2d..9a57d80cd08fb 100644 --- a/node_modules/binary-extensions/binary-extensions.json +++ b/node_modules/binary-extensions/binary-extensions.json @@ -38,6 +38,7 @@ "cmx", "cpio", "cr2", + "cr3", "cur", "dat", "dcm", diff --git a/node_modules/binary-extensions/index.js b/node_modules/binary-extensions/index.js index d46e468867114..6c99c7eb54f17 100644 --- a/node_modules/binary-extensions/index.js +++ b/node_modules/binary-extensions/index.js @@ -1 +1,3 @@ -module.exports = require('./binary-extensions.json'); +import binaryExtensions from './binary-extensions.json' with {type: 'json'}; + +export default binaryExtensions; diff --git a/node_modules/binary-extensions/package.json b/node_modules/binary-extensions/package.json index 4710c339aeb2d..abe49c2e9a34a 100644 --- a/node_modules/binary-extensions/package.json +++ b/node_modules/binary-extensions/package.json @@ -1,6 +1,6 @@ { "name": "binary-extensions", - "version": "2.3.0", + "version": "3.1.0", "description": "List of binary file extensions", "license": "MIT", "repository": "sindresorhus/binary-extensions", @@ -10,18 +10,23 @@ "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, + "type": "module", + "exports": { + "types": "./index.d.ts", + "default": "./index.js" + }, "sideEffects": false, "engines": { - "node": ">=8" + "node": ">=18.20" }, "scripts": { - "test": "xo && ava && tsd" + "//test": "xo && ava && tsd", + "test": "ava && tsd" }, "files": [ "index.js", "index.d.ts", - "binary-extensions.json", - "binary-extensions.json.d.ts" + "binary-extensions.json" ], "keywords": [ "binary", @@ -33,8 +38,8 @@ "array" ], "devDependencies": { - "ava": "^1.4.1", - "tsd": "^0.7.2", - "xo": "^0.24.0" + "ava": "^6.1.2", + "tsd": "^0.31.0", + "xo": "^0.58.0" } } diff --git a/node_modules/brace-expansion/LICENSE b/node_modules/brace-expansion/LICENSE index de3226673c387..46e7b75c91ced 100644 --- a/node_modules/brace-expansion/LICENSE +++ b/node_modules/brace-expansion/LICENSE @@ -1,6 +1,8 @@ MIT License -Copyright (c) 2013 Julian Gruber +Copyright Julian Gruber + +TypeScript port Copyright Isaac Z. Schlueter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/node_modules/brace-expansion/dist/commonjs/index.js b/node_modules/brace-expansion/dist/commonjs/index.js new file mode 100644 index 0000000000000..33063dd3552cd --- /dev/null +++ b/node_modules/brace-expansion/dist/commonjs/index.js @@ -0,0 +1,201 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EXPANSION_MAX = void 0; +exports.expand = expand; +const balanced_match_1 = require("balanced-match"); +const escSlash = '\0SLASH' + Math.random() + '\0'; +const escOpen = '\0OPEN' + Math.random() + '\0'; +const escClose = '\0CLOSE' + Math.random() + '\0'; +const escComma = '\0COMMA' + Math.random() + '\0'; +const escPeriod = '\0PERIOD' + Math.random() + '\0'; +const escSlashPattern = new RegExp(escSlash, 'g'); +const escOpenPattern = new RegExp(escOpen, 'g'); +const escClosePattern = new RegExp(escClose, 'g'); +const escCommaPattern = new RegExp(escComma, 'g'); +const escPeriodPattern = new RegExp(escPeriod, 'g'); +const slashPattern = /\\\\/g; +const openPattern = /\\{/g; +const closePattern = /\\}/g; +const commaPattern = /\\,/g; +const periodPattern = /\\\./g; +exports.EXPANSION_MAX = 100_000; +function numeric(str) { + return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0); +} +function escapeBraces(str) { + return str + .replace(slashPattern, escSlash) + .replace(openPattern, escOpen) + .replace(closePattern, escClose) + .replace(commaPattern, escComma) + .replace(periodPattern, escPeriod); +} +function unescapeBraces(str) { + return str + .replace(escSlashPattern, '\\') + .replace(escOpenPattern, '{') + .replace(escClosePattern, '}') + .replace(escCommaPattern, ',') + .replace(escPeriodPattern, '.'); +} +/** + * 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 ['']; + } + const parts = []; + const m = (0, balanced_match_1.balanced)('{', '}', str); + if (!m) { + return str.split(','); + } + const { pre, body, post } = m; + const p = pre.split(','); + p[p.length - 1] += '{' + body + '}'; + const 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 expand(str, options = {}) { + if (!str) { + return []; + } + const { max = exports.EXPANSION_MAX } = options; + // 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.slice(0, 2) === '{}') { + str = '\\{\\}' + str.slice(2); + } + return expand_(escapeBraces(str), max, 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, max, isTop) { + /** @type {string[]} */ + const expansions = []; + const m = (0, balanced_match_1.balanced)('{', '}', str); + if (!m) + return [str]; + // no need to expand pre, since it is guaranteed to be free of brace-sets + const pre = m.pre; + const post = m.post.length ? expand_(m.post, max, false) : ['']; + if (/\$$/.test(m.pre)) { + for (let k = 0; k < post.length && k < max; k++) { + const expansion = pre + '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } + else { + const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + const isSequence = isNumericSequence || isAlphaSequence; + const 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, max, true); + } + return [str]; + } + let n; + if (isSequence) { + n = m.body.split(/\.\./); + } + else { + n = parseCommaParts(m.body); + if (n.length === 1 && n[0] !== undefined) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand_(n[0], max, false).map(embrace); + //XXX is this necessary? Can't seem to hit it in tests. + /* c8 ignore start */ + if (n.length === 1) { + return post.map(p => m.pre + n[0] + p); + } + /* c8 ignore stop */ + } + } + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + let N; + if (isSequence && n[0] !== undefined && n[1] !== undefined) { + const x = numeric(n[0]); + const y = numeric(n[1]); + const width = Math.max(n[0].length, n[1].length); + let incr = n.length === 3 && n[2] !== undefined ? + Math.max(Math.abs(numeric(n[2])), 1) + : 1; + let test = lte; + const reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + const pad = n.some(isPadded); + N = []; + for (let i = x; test(i, y) && N.length < max; i += incr) { + let c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') { + c = ''; + } + } + else { + c = String(i); + if (pad) { + const need = width - c.length; + if (need > 0) { + const 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 (let j = 0; j < n.length; j++) { + N.push.apply(N, expand_(n[j], max, false)); + } + } + for (let j = 0; j < N.length; j++) { + for (let k = 0; k < post.length && expansions.length < max; k++) { + const expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) { + expansions.push(expansion); + } + } + } + } + return expansions; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/package-json-from-dist/dist/commonjs/package.json b/node_modules/brace-expansion/dist/commonjs/package.json similarity index 100% rename from node_modules/package-json-from-dist/dist/commonjs/package.json rename to node_modules/brace-expansion/dist/commonjs/package.json diff --git a/node_modules/brace-expansion/dist/esm/index.js b/node_modules/brace-expansion/dist/esm/index.js new file mode 100644 index 0000000000000..32399e7b2f5cf --- /dev/null +++ b/node_modules/brace-expansion/dist/esm/index.js @@ -0,0 +1,197 @@ +import { balanced } from 'balanced-match'; +const escSlash = '\0SLASH' + Math.random() + '\0'; +const escOpen = '\0OPEN' + Math.random() + '\0'; +const escClose = '\0CLOSE' + Math.random() + '\0'; +const escComma = '\0COMMA' + Math.random() + '\0'; +const escPeriod = '\0PERIOD' + Math.random() + '\0'; +const escSlashPattern = new RegExp(escSlash, 'g'); +const escOpenPattern = new RegExp(escOpen, 'g'); +const escClosePattern = new RegExp(escClose, 'g'); +const escCommaPattern = new RegExp(escComma, 'g'); +const escPeriodPattern = new RegExp(escPeriod, 'g'); +const slashPattern = /\\\\/g; +const openPattern = /\\{/g; +const closePattern = /\\}/g; +const commaPattern = /\\,/g; +const periodPattern = /\\\./g; +export const EXPANSION_MAX = 100_000; +function numeric(str) { + return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0); +} +function escapeBraces(str) { + return str + .replace(slashPattern, escSlash) + .replace(openPattern, escOpen) + .replace(closePattern, escClose) + .replace(commaPattern, escComma) + .replace(periodPattern, escPeriod); +} +function unescapeBraces(str) { + return str + .replace(escSlashPattern, '\\') + .replace(escOpenPattern, '{') + .replace(escClosePattern, '}') + .replace(escCommaPattern, ',') + .replace(escPeriodPattern, '.'); +} +/** + * 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 ['']; + } + const parts = []; + const m = balanced('{', '}', str); + if (!m) { + return str.split(','); + } + const { pre, body, post } = m; + const p = pre.split(','); + p[p.length - 1] += '{' + body + '}'; + const postParts = parseCommaParts(post); + if (post.length) { + ; + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); + return parts; +} +export function expand(str, options = {}) { + if (!str) { + return []; + } + const { max = EXPANSION_MAX } = options; + // 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.slice(0, 2) === '{}') { + str = '\\{\\}' + str.slice(2); + } + return expand_(escapeBraces(str), max, 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, max, isTop) { + /** @type {string[]} */ + const expansions = []; + const m = balanced('{', '}', str); + if (!m) + return [str]; + // no need to expand pre, since it is guaranteed to be free of brace-sets + const pre = m.pre; + const post = m.post.length ? expand_(m.post, max, false) : ['']; + if (/\$$/.test(m.pre)) { + for (let k = 0; k < post.length && k < max; k++) { + const expansion = pre + '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } + else { + const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + const isSequence = isNumericSequence || isAlphaSequence; + const 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, max, true); + } + return [str]; + } + let n; + if (isSequence) { + n = m.body.split(/\.\./); + } + else { + n = parseCommaParts(m.body); + if (n.length === 1 && n[0] !== undefined) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand_(n[0], max, false).map(embrace); + //XXX is this necessary? Can't seem to hit it in tests. + /* c8 ignore start */ + if (n.length === 1) { + return post.map(p => m.pre + n[0] + p); + } + /* c8 ignore stop */ + } + } + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + let N; + if (isSequence && n[0] !== undefined && n[1] !== undefined) { + const x = numeric(n[0]); + const y = numeric(n[1]); + const width = Math.max(n[0].length, n[1].length); + let incr = n.length === 3 && n[2] !== undefined ? + Math.max(Math.abs(numeric(n[2])), 1) + : 1; + let test = lte; + const reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + const pad = n.some(isPadded); + N = []; + for (let i = x; test(i, y) && N.length < max; i += incr) { + let c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') { + c = ''; + } + } + else { + c = String(i); + if (pad) { + const need = width - c.length; + if (need > 0) { + const 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 (let j = 0; j < n.length; j++) { + N.push.apply(N, expand_(n[j], max, false)); + } + } + for (let j = 0; j < N.length; j++) { + for (let k = 0; k < post.length && expansions.length < max; k++) { + const expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) { + expansions.push(expansion); + } + } + } + } + return expansions; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/package-json-from-dist/dist/esm/package.json b/node_modules/brace-expansion/dist/esm/package.json similarity index 100% rename from node_modules/package-json-from-dist/dist/esm/package.json rename to node_modules/brace-expansion/dist/esm/package.json diff --git a/node_modules/brace-expansion/index.js b/node_modules/brace-expansion/index.js deleted file mode 100644 index 4af9ddee463f4..0000000000000 --- a/node_modules/brace-expansion/index.js +++ /dev/null @@ -1,203 +0,0 @@ -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; -} - diff --git a/node_modules/brace-expansion/package.json b/node_modules/brace-expansion/package.json index 7097d41e39de5..81524809e5861 100644 --- a/node_modules/brace-expansion/package.json +++ b/node_modules/brace-expansion/package.json @@ -1,46 +1,64 @@ { "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" + "version": "5.0.6", + "files": [ + "dist" + ], + "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" + } + } }, - "homepage": "https://github.com/juliangruber/brace-expansion", - "main": "index.js", + "type": "module", "scripts": { - "test": "tape test/*.js", - "gentest": "bash test/generate.sh", - "bench": "matcha test/perf/bench.js" - }, - "dependencies": { - "balanced-match": "^1.0.0" + "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 .", + "benchmark": "node benchmark/index.js", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" }, "devDependencies": { - "@c4312/matcha": "^1.3.1", - "tape": "^4.6.0" + "@types/brace-expansion": "^1.1.2", + "@types/node": "^25.2.1", + "mkdirp": "^3.0.1", + "prettier": "^3.3.2", + "tap": "^21.6.2", + "tshy": "^3.0.2", + "typedoc": "^0.28.5" }, - "keywords": [], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" + "dependencies": { + "balanced-match": "^4.0.2" }, "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" - ] + "engines": { + "node": "18 || 20 || >=22" + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/juliangruber/brace-expansion.git" } } diff --git a/node_modules/cacache/lib/content/write.js b/node_modules/cacache/lib/content/write.js index e7187abca8788..e8d4989981576 100644 --- a/node_modules/cacache/lib/content/write.js +++ b/node_modules/cacache/lib/content/write.js @@ -10,7 +10,8 @@ const Pipeline = require('minipass-pipeline') const Flush = require('minipass-flush') const path = require('path') const ssri = require('ssri') -const uniqueFilename = require('unique-filename') +const cacheDir = require('../util/cache-dir') +const { tmpName } = require('../util/tmp') const fsm = require('fs-minipass') module.exports = write @@ -152,7 +153,8 @@ async function pipeToTmp (inputStream, cache, tmpTarget, opts) { } async function makeTmp (cache, opts) { - const tmpTarget = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) + const tmpTarget = tmpName(cache, opts.tmpPrefix) + await cacheDir.mkdir(cache) await fs.mkdir(path.dirname(tmpTarget), { recursive: true }) return { target: tmpTarget, diff --git a/node_modules/cacache/lib/entry-index.js b/node_modules/cacache/lib/entry-index.js index f73a11ca29ddf..6048a813cb710 100644 --- a/node_modules/cacache/lib/entry-index.js +++ b/node_modules/cacache/lib/entry-index.js @@ -12,17 +12,16 @@ const { const { Minipass } = require('minipass') const path = require('path') const ssri = require('ssri') -const uniqueFilename = require('unique-filename') +const { tmpName } = require('./util/tmp') +const cacheDir = require('./util/cache-dir') 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 pMap = require('p-map') const lsStreamConcurrency = 5 - module.exports.NotFoundError = class NotFoundError extends Error { constructor (cache, key) { super(`No cache entry for ${key} found in ${cache}`) @@ -71,7 +70,8 @@ async function compact (cache, key, matchFn, opts = {}) { }).join('\n') const setup = async () => { - const target = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) + const target = tmpName(cache, opts.tmpPrefix) + await cacheDir.mkdir(cache) await mkdir(path.dirname(target), { recursive: true }) return { target, @@ -123,6 +123,7 @@ async function insert (cache, key, integrity, opts = {}) { metadata, } try { + await cacheDir.mkdir(cache) await mkdir(path.dirname(bucket), { recursive: true }) const stringified = JSON.stringify(entry) // NOTE - Cleverness ahoy! @@ -185,6 +186,7 @@ function lsStream (cache) { // 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) diff --git a/node_modules/cacache/lib/rm.js b/node_modules/cacache/lib/rm.js index a94760c7cf243..897ebccd5eef4 100644 --- a/node_modules/cacache/lib/rm.js +++ b/node_modules/cacache/lib/rm.js @@ -27,5 +27,6 @@ module.exports.all = all async function all (cache) { memo.clearMemoized() const paths = await glob(path.join(cache, '*(content-*|index-*)'), { silent: true, nosort: true }) + paths.push(path.join(cache, 'CACHEDIR.TAG')) return Promise.all(paths.map((p) => rm(p, { recursive: true, force: true }))) } diff --git a/node_modules/cacache/lib/util/cache-dir.js b/node_modules/cacache/lib/util/cache-dir.js new file mode 100644 index 0000000000000..3cc63808f6f29 --- /dev/null +++ b/node_modules/cacache/lib/util/cache-dir.js @@ -0,0 +1,29 @@ +'use strict' + +const fs = require('fs/promises') +const path = require('path') + +const tagContent = `Signature: 8a477f597d28d172789f06886806bc55 +# This file is a cache directory tag created by cacache. +# For information about cache directory tags, see https://bford.info/cachedir/ +` + +async function mkdir (cache) { + await fs.mkdir(cache, { recursive: true, owner: 'inherit' }) + await writeTag(cache) +} + +async function writeTag (cache) { + try { + await fs.writeFile(path.join(cache, 'CACHEDIR.TAG'), tagContent, { flag: 'wx' }) + } catch (err) { + if (err.code !== 'EEXIST') { + throw err + } + } +} + +module.exports = { + mkdir, + tagContent, +} diff --git a/node_modules/cacache/lib/util/tmp.js b/node_modules/cacache/lib/util/tmp.js index 0bf5302136ebe..d274499c71142 100644 --- a/node_modules/cacache/lib/util/tmp.js +++ b/node_modules/cacache/lib/util/tmp.js @@ -1,14 +1,22 @@ 'use strict' +const crypto = require('crypto') const { withTempDir } = require('@npmcli/fs') const fs = require('fs/promises') const path = require('path') +const cacheDir = require('./cache-dir') module.exports.mkdir = mktmpdir +module.exports.tmpName = function tmpName (cache, tmpPrefix) { + const id = crypto.randomUUID() + return path.join(cache, 'tmp', tmpPrefix ? `${tmpPrefix}-${id}` : id) +} + async function mktmpdir (cache, opts = {}) { const { tmpPrefix } = opts const tmpDir = path.join(cache, 'tmp') + await cacheDir.mkdir(cache) 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 || ''}` @@ -22,5 +30,7 @@ function withTmp (cache, opts, cb) { cb = opts opts = {} } - return withTempDir(path.join(cache, 'tmp'), cb, opts) + return cacheDir.mkdir(cache).then(() => + withTempDir(path.join(cache, 'tmp'), cb, opts) + ) } diff --git a/node_modules/cacache/lib/verify.js b/node_modules/cacache/lib/verify.js index d7423da1295b6..8e2226458fded 100644 --- a/node_modules/cacache/lib/verify.js +++ b/node_modules/cacache/lib/verify.js @@ -1,18 +1,17 @@ 'use strict' const { - mkdir, readFile, rm, stat, truncate, writeFile, } = require('fs/promises') -const pMap = require('p-map') const contentPath = require('./content/path') const fsm = require('fs-minipass') const glob = require('./util/glob.js') const index = require('./entry-index') +const cacheDir = require('./util/cache-dir') const path = require('path') const ssri = require('ssri') @@ -78,7 +77,7 @@ async function markEndTime () { async function fixPerms (cache, opts) { opts.log.silly('verify', 'fixing cache permissions') - await mkdir(cache, { recursive: true }) + await cacheDir.mkdir(cache) return null } @@ -93,6 +92,7 @@ async function fixPerms (cache, opts) { // 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) => { @@ -176,6 +176,7 @@ async function verifyContent (filepath, sri) { 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, diff --git a/node_modules/cacache/package.json b/node_modules/cacache/package.json index 0741183efc19b..1dbd6507ad979 100644 --- a/node_modules/cacache/package.json +++ b/node_modules/cacache/package.json @@ -1,6 +1,6 @@ { "name": "cacache", - "version": "18.0.3", + "version": "21.0.1", "cache-version": { "content": "2", "index": "5" @@ -16,13 +16,14 @@ "snap": "tap", "coverage": "tap", "test-docker": "docker run -it --rm --name pacotest -v \"$PWD\":/tmp -w /tmp node:latest npm test", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "npmclilint": "npmcli-lint", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "postsnap": "npm run lintfix --", "postlint": "template-oss-check", "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", @@ -45,31 +46,29 @@ ], "license": "ISC", "dependencies": { - "@npmcli/fs": "^3.1.0", + "@npmcli/fs": "^6.0.0", "fs-minipass": "^3.0.0", - "glob": "^10.2.2", - "lru-cache": "^10.0.1", + "glob": "^13.0.0", + "lru-cache": "^11.1.0", "minipass": "^7.0.3", "minipass-collect": "^2.0.1", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", - "p-map": "^4.0.0", - "ssri": "^10.0.0", - "tar": "^6.1.11", - "unique-filename": "^3.0.0" + "p-map": "^7.0.2", + "ssri": "^14.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.0", "tap": "^16.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "windowsCI": false, - "version": "4.22.0", + "version": "5.1.0", "publish": "true" }, "author": "GitHub Inc.", diff --git a/node_modules/chalk/package.json b/node_modules/chalk/package.json index 3c500105bcbf2..c9e0dc52ba744 100644 --- a/node_modules/chalk/package.json +++ b/node_modules/chalk/package.json @@ -1,6 +1,6 @@ { "name": "chalk", - "version": "5.3.0", + "version": "5.6.2", "description": "Terminal string styling done right", "license": "MIT", "repository": "chalk/chalk", @@ -16,6 +16,7 @@ } }, "types": "./source/index.d.ts", + "sideEffects": false, "engines": { "node": "^12.17.0 || ^14.13 || >=16.0.0" }, @@ -58,10 +59,9 @@ "log-update": "^5.0.0", "matcha": "^0.7.0", "tsd": "^0.19.0", - "xo": "^0.53.0", + "xo": "^0.57.0", "yoctodelay": "^2.0.0" }, - "sideEffects": false, "xo": { "rules": { "unicorn/prefer-string-slice": "off", diff --git a/node_modules/chalk/source/vendor/supports-color/browser.js b/node_modules/chalk/source/vendor/supports-color/browser.js index 9fa6888f10288..fbb6ce0fc9ab9 100644 --- a/node_modules/chalk/source/vendor/supports-color/browser.js +++ b/node_modules/chalk/source/vendor/supports-color/browser.js @@ -1,14 +1,18 @@ /* eslint-env browser */ const level = (() => { - if (navigator.userAgentData) { + 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(navigator.userAgent)) { + if (/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)) { return 1; } diff --git a/node_modules/chalk/source/vendor/supports-color/index.js b/node_modules/chalk/source/vendor/supports-color/index.js index 4ce0a2da8d224..265d7f8581953 100644 --- a/node_modules/chalk/source/vendor/supports-color/index.js +++ b/node_modules/chalk/source/vendor/supports-color/index.js @@ -112,11 +112,11 @@ function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { } if ('CI' in env) { - if ('GITHUB_ACTIONS' in env || 'GITEA_ACTIONS' in env) { + if (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) { return 3; } - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + if (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } @@ -135,6 +135,14 @@ function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { return 3; } + if (env.TERM === 'xterm-ghostty') { + return 3; + } + + if (env.TERM === 'wezterm') { + return 3; + } + if ('TERM_PROGRAM' in env) { const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); diff --git a/node_modules/package-json-from-dist/LICENSE.md b/node_modules/chownr/LICENSE.md similarity index 100% rename from node_modules/package-json-from-dist/LICENSE.md rename to node_modules/chownr/LICENSE.md diff --git a/node_modules/chownr/chownr.js b/node_modules/chownr/chownr.js deleted file mode 100644 index 0d40932169654..0000000000000 --- a/node_modules/chownr/chownr.js +++ /dev/null @@ -1,167 +0,0 @@ -'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 diff --git a/node_modules/chownr/dist/commonjs/index.js b/node_modules/chownr/dist/commonjs/index.js new file mode 100644 index 0000000000000..6a7b68d5eac26 --- /dev/null +++ b/node_modules/chownr/dist/commonjs/index.js @@ -0,0 +1,93 @@ +"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 \ No newline at end of file diff --git a/node_modules/walk-up-path/dist/cjs/package.json b/node_modules/chownr/dist/commonjs/package.json similarity index 100% rename from node_modules/walk-up-path/dist/cjs/package.json rename to node_modules/chownr/dist/commonjs/package.json diff --git a/node_modules/chownr/dist/esm/index.js b/node_modules/chownr/dist/esm/index.js new file mode 100644 index 0000000000000..5c2815297a67c --- /dev/null +++ b/node_modules/chownr/dist/esm/index.js @@ -0,0 +1,85 @@ +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 \ No newline at end of file diff --git a/node_modules/walk-up-path/dist/mjs/package.json b/node_modules/chownr/dist/esm/package.json similarity index 100% rename from node_modules/walk-up-path/dist/mjs/package.json rename to node_modules/chownr/dist/esm/package.json diff --git a/node_modules/chownr/package.json b/node_modules/chownr/package.json index 5b0214ca12e3f..09aa6b2e2e576 100644 --- a/node_modules/chownr/package.json +++ b/node_modules/chownr/package.json @@ -2,31 +2,68 @@ "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "name": "chownr", "description": "like `chown -R`", - "version": "2.0.0", + "version": "3.0.0", "repository": { "type": "git", "url": "git://github.com/isaacs/chownr.git" }, - "main": "chownr.js", "files": [ - "chownr.js" + "dist" ], "devDependencies": { - "mkdirp": "0.3", - "rimraf": "^2.7.1", - "tap": "^14.10.6" - }, - "tap": { - "check-coverage": true + "@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" + "prepublishOnly": "git push origin --follow-tags", + "format": "prettier --write . --loglevel warn", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" }, - "license": "ISC", + "license": "BlueOak-1.0.0", "engines": { - "node": ">=10" + "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" } } diff --git a/node_modules/ci-info/index.js b/node_modules/ci-info/index.js index 47907264581eb..38056d9aa8772 100644 --- a/node_modules/ci-info/index.js +++ b/node_modules/ci-info/index.js @@ -13,59 +13,40 @@ Object.defineProperty(exports, '_vendors', { 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 (env.CI !== 'false') { + vendors.forEach(function (vendor) { + const envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env] + const isCI = envs.every(function (obj) { + return checkEnv(obj) + }) - if (!isCI) { - return - } + exports[vendor.constant] = isCI - exports.name = vendor.name + if (!isCI) { + return + } - switch (typeof vendor.pr) { - case 'string': - // "pr": "CIRRUS_PR" - exports.isPR = !!env[vendor.pr] - break - case 'object': - if ('env' in vendor.pr) { - // "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" } - exports.isPR = vendor.pr.env in env && env[vendor.pr.env] !== vendor.pr.ne - } else if ('any' in vendor.pr) { - // "pr": { "any": ["ghprbPullId", "CHANGE_ID"] } - exports.isPR = vendor.pr.any.some(function (key) { - return !!env[key] - }) - } else { - // "pr": { "DRONE_BUILD_EVENT": "pull_request" } - exports.isPR = checkEnv(vendor.pr) - } - break - default: - // PR detection not supported for this vendor - exports.isPR = null - } -}) + 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) + env.BUILD_NUMBER || // Jenkins, TeamCity + env.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari, Cloudflare Pages/Workers + 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) { @@ -79,12 +60,45 @@ function checkEnv (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 + } +} diff --git a/node_modules/ci-info/package.json b/node_modules/ci-info/package.json index 3c6b9e4adac8e..30b978ab04afa 100644 --- a/node_modules/ci-info/package.json +++ b/node_modules/ci-info/package.json @@ -1,14 +1,27 @@ { "name": "ci-info", - "version": "4.0.0", + "version": "4.4.0", "description": "Get details about the current Continuous Integration environment", "main": "index.js", "typings": "index.d.ts", + "type": "commonjs", "author": "Thomas Watson Steen (https://twitter.com/wa7son)", "license": "MIT", - "repository": "https://github.com/watson/ci-info.git", + "repository": "github:watson/ci-info", "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", @@ -22,22 +35,18 @@ "index.d.ts", "CHANGELOG.md" ], - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], "scripts": { + "build": "node sort-vendors.js && node create-typings.js", "lint:fix": "standard --fix", "test": "standard && node test.js", - "prepare": "husky install" + "prepare": "husky install || true" }, "devDependencies": { "clear-module": "^4.1.2", - "husky": "^8.0.3", - "standard": "^17.1.0", - "tape": "^5.7.0" + "husky": "^9.1.7", + "publint": "^0.3.12", + "standard": "^17.1.2", + "tape": "^5.9.0" }, "engines": { "node": ">=8" diff --git a/node_modules/ci-info/vendors.json b/node_modules/ci-info/vendors.json index 6b65e3f9b541f..d697afa927775 100644 --- a/node_modules/ci-info/vendors.json +++ b/node_modules/ci-info/vendors.json @@ -5,10 +5,19 @@ "env": "AGOLA_GIT_REF", "pr": "AGOLA_PULL_REQUEST_ID" }, + { + "name": "Alpic", + "constant": "ALPIC", + "env": "ALPIC_HOST" + }, { "name": "Appcircle", "constant": "APPCIRCLE", - "env": "AC_APPCIRCLE" + "env": "AC_APPCIRCLE", + "pr": { + "env": "AC_GIT_PR", + "ne": "false" + } }, { "name": "AppVeyor", @@ -19,7 +28,15 @@ { "name": "AWS CodeBuild", "constant": "CODEBUILD", - "env": "CODEBUILD_BUILD_ARN" + "env": "CODEBUILD_BUILD_ARN", + "pr": { + "env": "CODEBUILD_WEBHOOK_EVENT", + "any": [ + "PULL_REQUEST_CREATED", + "PULL_REQUEST_UPDATED", + "PULL_REQUEST_REOPENED" + ] + } }, { "name": "Azure Pipelines", @@ -73,6 +90,16 @@ "env": "CIRRUS_CI", "pr": "CIRRUS_PR" }, + { + "name": "Cloudflare Pages", + "constant": "CLOUDFLARE_PAGES", + "env": "CF_PAGES" + }, + { + "name": "Cloudflare Workers", + "constant": "CLOUDFLARE_WORKERS", + "env": "WORKERS_CI" + }, { "name": "Codefresh", "constant": "CODEFRESH", diff --git a/node_modules/cidr-regex/dist/index.js b/node_modules/cidr-regex/dist/index.js index 2817f65eeb3cb..29bb17cfcbdab 100644 --- a/node_modules/cidr-regex/dist/index.js +++ b/node_modules/cidr-regex/dist/index.js @@ -1,15 +1,21 @@ -import ipRegex from "ip-regex"; +//#region index.ts 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 -}; +const v4src = "(?: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}\\/(3[0-2]|[12]?[0-9])"; +const v6src = "(?:(?:[a-fA-F\\d]{1,4}:){7}(?:[a-fA-F\\d]{1,4}|:)|(?:[a-fA-F\\d]{1,4}:){6}(?:(?: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}|:[a-fA-F\\d]{1,4}|:)|(?:[a-fA-F\\d]{1,4}:){5}(?::(?: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}|(?::[a-fA-F\\d]{1,4}){1,2}|:)|(?:[a-fA-F\\d]{1,4}:){4}(?:(?::[a-fA-F\\d]{1,4})?:(?: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}|(?::[a-fA-F\\d]{1,4}){1,3}|:)|(?:[a-fA-F\\d]{1,4}:){3}(?:(?::[a-fA-F\\d]{1,4}){0,2}:(?: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}|(?::[a-fA-F\\d]{1,4}){1,4}|:)|(?:[a-fA-F\\d]{1,4}:){2}(?:(?::[a-fA-F\\d]{1,4}){0,3}:(?: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}|(?::[a-fA-F\\d]{1,4}){1,5}|:)|[a-fA-F\\d]{1,4}:(?:(?::[a-fA-F\\d]{1,4}){0,4}:(?: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}|(?::[a-fA-F\\d]{1,4}){1,6}|:)|:(?:(?::[a-fA-F\\d]{1,4}){0,5}:(?: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}|(?::[a-fA-F\\d]{1,4}){1,7}|:))(?:%[0-9a-zA-Z]+)?\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])"; +const v46src = `${v4src}|${v6src}`; +const v4exact = new RegExp(`^${v4src}$`); +const v6exact = new RegExp(`^${v6src}$`); +const v46exact = new RegExp(`^${v4src}$|^${v6src}$`); +const v4global = new RegExp(v4src, "g"); +const v6global = new RegExp(v6src, "g"); +const v46global = new RegExp(v46src, "g"); +function resetRegex(re) { + re.lastIndex = 0; + return re; +} +const cidrRegex = ({ exact } = defaultOpts) => exact ? v46exact : resetRegex(v46global); +const v4 = cidrRegex.v4 = ({ exact } = defaultOpts) => exact ? v4exact : resetRegex(v4global); +const v6 = cidrRegex.v6 = ({ exact } = defaultOpts) => exact ? v6exact : resetRegex(v6global); + +//#endregion +export { cidrRegex as default, v4, v6 }; \ No newline at end of file diff --git a/node_modules/cidr-regex/package.json b/node_modules/cidr-regex/package.json index 88b8297b02473..0462dc87dc87f 100644 --- a/node_modules/cidr-regex/package.json +++ b/node_modules/cidr-regex/package.json @@ -1,12 +1,25 @@ { "name": "cidr-regex", - "version": "4.1.1", + "version": "6.0.0", "description": "Regular expression for matching IP addresses in CIDR notation", "author": "silverwind ", "contributors": [ "Felipe Apostol (http://flipjs.io/)" ], "repository": "silverwind/cidr-regex", + "keywords": [ + "cidr", + "regex", + "regexp", + "ip", + "ipv4", + "ipv6", + "address", + "subnet", + "network", + "notation", + "match" + ], "license": "BSD-2-Clause", "type": "module", "sideEffects": false, @@ -17,24 +30,22 @@ "dist" ], "engines": { - "node": ">=14" - }, - "dependencies": { - "ip-regex": "^5.0.0" + "node": ">=22" }, "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" + "@types/node": "25.6.0", + "@typescript/native-preview": "7.0.0-dev.20260427.1", + "eslint": "10.2.1", + "eslint-config-silverwind": "132.0.0", + "jest-extended": "7.0.0", + "tsdown": "0.21.10", + "tsdown-config-silverwind": "3.0.0", + "typescript": "6.0.3", + "typescript-config-silverwind": "18.0.0", + "updates": "17.16.4", + "updates-config-silverwind": "3.0.0", + "versions": "15.0.1", + "vitest": "4.1.5", + "vitest-config-silverwind": "11.3.3" } -} +} \ No newline at end of file diff --git a/node_modules/clean-stack/index.js b/node_modules/clean-stack/index.js deleted file mode 100644 index 8c1dcc4cd02a2..0000000000000 --- a/node_modules/clean-stack/index.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; -const os = require('os'); - -const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; -const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; -const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); - -module.exports = (stack, options) => { - options = Object.assign({pretty: false}, options); - - return stack.replace(/\\/g, '/') - .split('\n') - .filter(line => { - const pathMatches = line.match(extractPathRegex); - if (pathMatches === null || !pathMatches[1]) { - return true; - } - - const match = pathMatches[1]; - - // Electron - if ( - match.includes('.app/Contents/Resources/electron.asar') || - match.includes('.app/Contents/Resources/default_app.asar') - ) { - return false; - } - - return !pathRegex.test(match); - }) - .filter(line => line.trim() !== '') - .map(line => { - if (options.pretty) { - return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); - } - - return line; - }) - .join('\n'); -}; diff --git a/node_modules/clean-stack/license b/node_modules/clean-stack/license deleted file mode 100644 index e7af2f77107d7..0000000000000 --- a/node_modules/clean-stack/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/clean-stack/package.json b/node_modules/clean-stack/package.json deleted file mode 100644 index 719fdff55e7b6..0000000000000 --- a/node_modules/clean-stack/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "clean-stack", - "version": "2.2.0", - "description": "Clean up error stack traces", - "license": "MIT", - "repository": "sindresorhus/clean-stack", - "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": [ - "clean", - "stack", - "trace", - "traces", - "error", - "err", - "electron" - ], - "devDependencies": { - "ava": "^1.4.1", - "tsd": "^0.7.2", - "xo": "^0.24.0" - }, - "browser": { - "os": false - } -} diff --git a/node_modules/cli-columns/color.js b/node_modules/cli-columns/color.js deleted file mode 100644 index 11027047f24fe..0000000000000 --- a/node_modules/cli-columns/color.js +++ /dev/null @@ -1,16 +0,0 @@ -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(''); diff --git a/node_modules/cli-columns/index.js b/node_modules/cli-columns/index.js deleted file mode 100644 index 1090aa21c2bdf..0000000000000 --- a/node_modules/cli-columns/index.js +++ /dev/null @@ -1,82 +0,0 @@ -'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; diff --git a/node_modules/cli-columns/license b/node_modules/cli-columns/license deleted file mode 100644 index 67147a987ea19..0000000000000 --- a/node_modules/cli-columns/license +++ /dev/null @@ -1,20 +0,0 @@ -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. diff --git a/node_modules/cli-columns/package.json b/node_modules/cli-columns/package.json deleted file mode 100644 index 129f2c1316d2f..0000000000000 --- a/node_modules/cli-columns/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 - } -} diff --git a/node_modules/cli-columns/test.js b/node_modules/cli-columns/test.js deleted file mode 100644 index 4d95e7cf07323..0000000000000 --- a/node_modules/cli-columns/test.js +++ /dev/null @@ -1,101 +0,0 @@ -'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); -}); diff --git a/node_modules/cmd-shim/lib/index.js b/node_modules/cmd-shim/lib/index.js deleted file mode 100644 index c13890aed3263..0000000000000 --- a/node_modules/cmd-shim/lib/index.js +++ /dev/null @@ -1,247 +0,0 @@ -// 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 diff --git a/node_modules/cmd-shim/package.json b/node_modules/cmd-shim/package.json deleted file mode 100644 index 094ca2df619d2..0000000000000 --- a/node_modules/cmd-shim/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "cmd-shim", - "version": "6.0.3", - "description": "Used in npm for command line application support", - "scripts": { - "test": "tap", - "snap": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/cmd-shim.git" - }, - "license": "ISC", - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "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": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "author": "GitHub Inc.", - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true - } -} diff --git a/node_modules/color-convert/LICENSE b/node_modules/color-convert/LICENSE deleted file mode 100644 index 5b4c386f9269b..0000000000000 --- a/node_modules/color-convert/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -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. - diff --git a/node_modules/color-convert/conversions.js b/node_modules/color-convert/conversions.js deleted file mode 100644 index 2657f265c9e10..0000000000000 --- a/node_modules/color-convert/conversions.js +++ /dev/null @@ -1,839 +0,0 @@ -/* 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]; -}; diff --git a/node_modules/color-convert/index.js b/node_modules/color-convert/index.js deleted file mode 100644 index b648e5737be61..0000000000000 --- a/node_modules/color-convert/index.js +++ /dev/null @@ -1,81 +0,0 @@ -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; diff --git a/node_modules/color-convert/package.json b/node_modules/color-convert/package.json deleted file mode 100644 index 6e48000c7c98f..0000000000000 --- a/node_modules/color-convert/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/color-convert/route.js b/node_modules/color-convert/route.js deleted file mode 100644 index 1a08521b5a001..0000000000000 --- a/node_modules/color-convert/route.js +++ /dev/null @@ -1,97 +0,0 @@ -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; -}; - diff --git a/node_modules/color-name/LICENSE b/node_modules/color-name/LICENSE deleted file mode 100644 index c6b10012540c2..0000000000000 --- a/node_modules/color-name/LICENSE +++ /dev/null @@ -1,8 +0,0 @@ -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. \ No newline at end of file diff --git a/node_modules/color-name/index.js b/node_modules/color-name/index.js deleted file mode 100644 index b7c198a6f3d7c..0000000000000 --- a/node_modules/color-name/index.js +++ /dev/null @@ -1,152 +0,0 @@ -'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] -}; diff --git a/node_modules/color-name/package.json b/node_modules/color-name/package.json deleted file mode 100644 index 782dd82878030..0000000000000 --- a/node_modules/color-name/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "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" -} diff --git a/node_modules/common-ancestor-path/LICENSE b/node_modules/common-ancestor-path/LICENSE deleted file mode 100644 index 05eeeb88c2ef4..0000000000000 --- a/node_modules/common-ancestor-path/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/common-ancestor-path/LICENSE.md b/node_modules/common-ancestor-path/LICENSE.md new file mode 100644 index 0000000000000..c5402b9577a8c --- /dev/null +++ b/node_modules/common-ancestor-path/LICENSE.md @@ -0,0 +1,55 @@ +# 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.*** diff --git a/node_modules/common-ancestor-path/dist/commonjs/index.js b/node_modules/common-ancestor-path/dist/commonjs/index.js new file mode 100644 index 0000000000000..70a3604fb0f3b --- /dev/null +++ b/node_modules/common-ancestor-path/dist/commonjs/index.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.commonAncestorPath = void 0; +const node_path_1 = require("node: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 cap = (a, b) => a === b ? a + : !a || !b ? null + : (0, node_path_1.parse)(a).root !== (0, node_path_1.parse)(b).root ? null + : [...commonArrayMembers((0, node_path_1.normalize)(a).split(node_path_1.sep), (0, node_path_1.normalize)(b).split(node_path_1.sep))].join(node_path_1.sep); +const commonAncestorPath = (...paths) => paths.reduce(cap); +exports.commonAncestorPath = commonAncestorPath; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/which/node_modules/isexe/dist/cjs/package.json b/node_modules/common-ancestor-path/dist/commonjs/package.json similarity index 100% rename from node_modules/which/node_modules/isexe/dist/cjs/package.json rename to node_modules/common-ancestor-path/dist/commonjs/package.json diff --git a/node_modules/common-ancestor-path/dist/esm/index.js b/node_modules/common-ancestor-path/dist/esm/index.js new file mode 100644 index 0000000000000..abb7c92931a61 --- /dev/null +++ b/node_modules/common-ancestor-path/dist/esm/index.js @@ -0,0 +1,16 @@ +import { parse, sep, normalize as norm } from 'node: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 cap = (a, b) => a === b ? a + : !a || !b ? null + : parse(a).root !== parse(b).root ? null + : [...commonArrayMembers(norm(a).split(sep), norm(b).split(sep))].join(sep); +export const commonAncestorPath = (...paths) => paths.reduce(cap); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/which/node_modules/isexe/dist/mjs/package.json b/node_modules/common-ancestor-path/dist/esm/package.json similarity index 100% rename from node_modules/which/node_modules/isexe/dist/mjs/package.json rename to node_modules/common-ancestor-path/dist/esm/package.json diff --git a/node_modules/common-ancestor-path/index.js b/node_modules/common-ancestor-path/index.js deleted file mode 100644 index 09ae3178295ad..0000000000000 --- a/node_modules/common-ancestor-path/index.js +++ /dev/null @@ -1,17 +0,0 @@ -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) diff --git a/node_modules/common-ancestor-path/package.json b/node_modules/common-ancestor-path/package.json index 4375d1d0818ac..c98b78300d143 100644 --- a/node_modules/common-ancestor-path/package.json +++ b/node_modules/common-ancestor-path/package.json @@ -1,28 +1,60 @@ { "name": "common-ancestor-path", - "version": "1.0.1", + "version": "2.0.0", "files": [ - "index.js" + "dist" ], "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" + "url": "git@github.com:isaacs/common-ancestor-path" }, "author": "Isaac Z. Schlueter (https://izs.me)", - "license": "ISC", + "license": "BlueOak-1.0.0", "scripts": { - "test": "tap", - "snap": "tap", "preversion": "npm test", "postversion": "npm publish", - "prepublishOnly": "git push origin --follow-tags" - }, - "tap": { - "check-coverage": true + "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 --cache", + "typedoc": "typedoc" }, "devDependencies": { + "@types/node": "^24.10.1", + "prettier": "^3.6.2", "require-inject": "^1.4.4", - "tap": "^14.10.7" + "tap": "^21.1.6", + "tshy": "^3.1.0", + "typedoc": "^0.28.14" + }, + "type": "module", + "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", + "module": "./dist/esm/index.js", + "engines": { + "node": ">= 18" } } diff --git a/node_modules/cross-spawn/LICENSE b/node_modules/cross-spawn/LICENSE deleted file mode 100644 index 8407b9a30f51b..0000000000000 --- a/node_modules/cross-spawn/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -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. diff --git a/node_modules/cross-spawn/index.js b/node_modules/cross-spawn/index.js deleted file mode 100644 index 5509742ca9fa8..0000000000000 --- a/node_modules/cross-spawn/index.js +++ /dev/null @@ -1,39 +0,0 @@ -'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; diff --git a/node_modules/cross-spawn/lib/enoent.js b/node_modules/cross-spawn/lib/enoent.js deleted file mode 100644 index 14df9b623d0a2..0000000000000 --- a/node_modules/cross-spawn/lib/enoent.js +++ /dev/null @@ -1,59 +0,0 @@ -'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, 'spawn'); - - 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, -}; diff --git a/node_modules/cross-spawn/lib/parse.js b/node_modules/cross-spawn/lib/parse.js deleted file mode 100644 index 0129d74774a8a..0000000000000 --- a/node_modules/cross-spawn/lib/parse.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/node_modules/cross-spawn/lib/util/escape.js b/node_modules/cross-spawn/lib/util/escape.js deleted file mode 100644 index b0bb84c3a1409..0000000000000 --- a/node_modules/cross-spawn/lib/util/escape.js +++ /dev/null @@ -1,45 +0,0 @@ -'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 - - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - arg = arg.replace(/(\\*)"/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'); - - // 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; diff --git a/node_modules/cross-spawn/lib/util/readShebang.js b/node_modules/cross-spawn/lib/util/readShebang.js deleted file mode 100644 index 5e83733fef260..0000000000000 --- a/node_modules/cross-spawn/lib/util/readShebang.js +++ /dev/null @@ -1,23 +0,0 @@ -'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; diff --git a/node_modules/cross-spawn/lib/util/resolveCommand.js b/node_modules/cross-spawn/lib/util/resolveCommand.js deleted file mode 100644 index 7972455008e91..0000000000000 --- a/node_modules/cross-spawn/lib/util/resolveCommand.js +++ /dev/null @@ -1,52 +0,0 @@ -'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; diff --git a/node_modules/cross-spawn/node_modules/which/bin/node-which b/node_modules/cross-spawn/node_modules/which/bin/node-which deleted file mode 100755 index 7cee3729eebdd..0000000000000 --- a/node_modules/cross-spawn/node_modules/which/bin/node-which +++ /dev/null @@ -1,52 +0,0 @@ -#!/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)) diff --git a/node_modules/cross-spawn/node_modules/which/package.json b/node_modules/cross-spawn/node_modules/which/package.json deleted file mode 100644 index 97ad7fbabc52b..0000000000000 --- a/node_modules/cross-spawn/node_modules/which/package.json +++ /dev/null @@ -1,43 +0,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" - } -} diff --git a/node_modules/cross-spawn/node_modules/which/which.js b/node_modules/cross-spawn/node_modules/which/which.js deleted file mode 100644 index 82afffd214374..0000000000000 --- a/node_modules/cross-spawn/node_modules/which/which.js +++ /dev/null @@ -1,125 +0,0 @@ -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 diff --git a/node_modules/cross-spawn/package.json b/node_modules/cross-spawn/package.json deleted file mode 100644 index 232ff97e04b21..0000000000000 --- a/node_modules/cross-spawn/package.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "name": "cross-spawn", - "version": "7.0.3", - "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": "^7.0.0" - }, - "engines": { - "node": ">= 8" - } -} diff --git a/node_modules/debug/node_modules/ms/index.js b/node_modules/debug/node_modules/ms/index.js deleted file mode 100644 index c4498bcc21258..0000000000000 --- a/node_modules/debug/node_modules/ms/index.js +++ /dev/null @@ -1,162 +0,0 @@ -/** - * 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' : ''); -} diff --git a/node_modules/debug/node_modules/ms/license.md b/node_modules/debug/node_modules/ms/license.md deleted file mode 100644 index 69b61253a3892..0000000000000 --- a/node_modules/debug/node_modules/ms/license.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Zeit, 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. diff --git a/node_modules/debug/node_modules/ms/package.json b/node_modules/debug/node_modules/ms/package.json deleted file mode 100644 index eea666e1fb03d..0000000000000 --- a/node_modules/debug/node_modules/ms/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "ms", - "version": "2.1.2", - "description": "Tiny millisecond conversion utility", - "repository": "zeit/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.12.1", - "expect.js": "0.3.1", - "husky": "0.14.3", - "lint-staged": "5.0.0", - "mocha": "4.0.1" - } -} diff --git a/node_modules/debug/package.json b/node_modules/debug/package.json index cb67103857af1..ee8abb523dbe0 100644 --- a/node_modules/debug/package.json +++ b/node_modules/debug/package.json @@ -1,6 +1,6 @@ { "name": "debug", - "version": "4.3.5", + "version": "4.4.3", "repository": { "type": "git", "url": "git://github.com/debug-js/debug.git" @@ -26,18 +26,17 @@ "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:node": "mocha test.js test.node.js", "test:browser": "karma start --single-run", "test:coverage": "cat ./coverage/lcov.info | coveralls" }, "dependencies": { - "ms": "2.1.2" + "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", @@ -56,5 +55,10 @@ "browser": "./src/browser.js", "engines": { "node": ">=6.0" + }, + "xo": { + "rules": { + "import/extensions": "off" + } } } diff --git a/node_modules/debug/src/browser.js b/node_modules/debug/src/browser.js index cd0fc35d1ee11..5993451b82e6b 100644 --- a/node_modules/debug/src/browser.js +++ b/node_modules/debug/src/browser.js @@ -125,14 +125,17 @@ function useColors() { 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 && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + (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+)/)); } @@ -216,7 +219,7 @@ function save(namespaces) { function load() { let r; try { - r = exports.storage.getItem('debug'); + r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? diff --git a/node_modules/debug/src/common.js b/node_modules/debug/src/common.js index e3291b20faa1a..141cb578b7722 100644 --- a/node_modules/debug/src/common.js +++ b/node_modules/debug/src/common.js @@ -166,24 +166,62 @@ function setup(env) { createDebug.names = []; createDebug.skips = []; - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; + const split = (typeof namespaces === 'string' ? namespaces : '') + .trim() + .replace(/\s+/g, ',') + .split(',') + .filter(Boolean); + + for (const ns of split) { + if (ns[0] === '-') { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); } + } + } - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + /** + * 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 { - createDebug.names.push(new RegExp('^' + namespaces + '$')); + return false; // No match } } + + // Handle trailing '*' in template + while (templateIndex < template.length && template[templateIndex] === '*') { + templateIndex++; + } + + return templateIndex === template.length; } /** @@ -194,8 +232,8 @@ function setup(env) { */ function disable() { const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ...createDebug.names, + ...createDebug.skips.map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; @@ -209,21 +247,14 @@ function setup(env) { * @api public */ function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - let i; - let len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { return false; } } - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { return true; } } @@ -231,19 +262,6 @@ function setup(env) { return false; } - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } - /** * Coerce `val`. * diff --git a/node_modules/diff/CONTRIBUTING.md b/node_modules/diff/CONTRIBUTING.md index c974cf678e2c5..320bd00edf9f7 100644 --- a/node_modules/diff/CONTRIBUTING.md +++ b/node_modules/diff/CONTRIBUTING.md @@ -1,36 +1,28 @@ -# 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 +## Building and testing ``` yarn yarn test ``` -Running `yarn test -- dev` will watch for tests within Node and `karma start` may be used for manual testing in browsers. +To run tests in a *browser* (for instance to test compatibility with Firefox, with Safari, or with old browser versions), run `yarn karma start`, then open http://localhost:9876/ in the browser you want to test in. Results of the test run will appear in the terminal where `yarn karma start` is running. 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 with the following: +Run a test in Firefox via the procedure above before releasing. + +A full release may be completed by first updating the `"version"` property in package.json, then running the following: ``` yarn clean -yarn grunt -yarn grunt uglify -yarn publish +yarn build +yarn npm 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. diff --git a/node_modules/diff/dist/diff.js b/node_modules/diff/dist/diff.js index 76232b293d549..d989cfb5cca4c 100644 --- a/node_modules/diff/dist/diff.js +++ b/node_modules/diff/dist/diff.js @@ -1,1730 +1,1782 @@ (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (global = 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 = {}; - } - - this.options = options; - var self = this; - - function done(value) { - if (callback) { - setTimeout(function () { - callback(undefined, value); - }, 0); - return true; - } else { - return value; - } - } // Allow subclasses to massage the input prior to running - - - oldString = this.castInput(oldString); - newString = this.castInput(newString); - oldString = this.removeEmpty(this.tokenize(oldString)); - newString = this.removeEmpty(this.tokenize(newString)); - var newLen = newString.length, - oldLen = oldString.length; - var editLength = 1; - var maxEditLength = newLen + oldLen; - - if (options.maxEditLength) { - 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); - - if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { - // Identity per the equality and tokenizer - return done([{ - value: this.join(newString), - count: newString.length - }]); - } // 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 - // TODO: Remove the `+ 1` here to make behavior match Myers algorithm - // and prefer to order removals before insertions. - - - if (!canRemove || canAdd && removePath.oldPos + 1 < addPath.oldPos) { - basePath = self.addToPath(addPath, true, undefined, 0); - } else { - basePath = self.addToPath(removePath, undefined, true, 1); - } - - newPos = self.extractCommon(basePath, newString, oldString, diagonalPath); - - 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); + 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'; + + class Diff { + diff(oldStr, newStr, + // Type below is not accurate/complete - see above for full possibilities - but it compiles + options = {}) { + let callback; + if (typeof options === 'function') { + callback = options; + options = {}; } - - if (newPos + 1 >= newLen) { - minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); + else if ('callback' in options) { + callback = options.callback; } - } + // Allow subclasses to massage the input prior to running + const oldString = this.castInput(oldStr, options); + const newString = this.castInput(newStr, options); + const oldTokens = this.removeEmpty(this.tokenize(oldString, options)); + const newTokens = this.removeEmpty(this.tokenize(newString, options)); + return this.diffWithOptionsObj(oldTokens, newTokens, options, callback); } - - 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(); + diffWithOptionsObj(oldTokens, newTokens, options, callback) { + var _a; + const done = (value) => { + value = this.postProcess(value, options); + if (callback) { + setTimeout(function () { callback(value); }, 0); + return undefined; + } + else { + return value; + } + }; + const newLen = newTokens.length, oldLen = oldTokens.length; + let editLength = 1; + let maxEditLength = newLen + oldLen; + if (options.maxEditLength != null) { + maxEditLength = Math.min(maxEditLength, options.maxEditLength); + } + const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity; + const abortAfterTimestamp = Date.now() + maxExecutionTime; + const bestPath = [{ oldPos: -1, lastComponent: undefined }]; + // Seed editLength = 0, i.e. the content starts with the same values + let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options); + if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + // Identity per the equality and tokenizer + return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens)); + } + // 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. + let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; + // Main worker method. checks all permutations of a given edit length for acceptance. + const execEditLength = () => { + for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { + let basePath; + const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; + if (removePath) { + // No one else is going to attempt to use this value, clear it + // @ts-expect-error - perf optimisation. This type-violating value will never be read. + bestPath[diagonalPath - 1] = undefined; + } + let canAdd = false; + if (addPath) { + // what newPos will be after we do an insertion: + const addPathNewPos = addPath.oldPos - diagonalPath; + canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; + } + const canRemove = removePath && removePath.oldPos + 1 < oldLen; + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + // @ts-expect-error - perf optimisation. This type-violating value will never be read. + 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 = this.addToPath(addPath, true, false, 0, options); + } + else { + basePath = this.addToPath(removePath, false, true, 1, options); + } + newPos = this.extractCommon(basePath, newTokens, oldTokens, 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(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true; + } + 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(undefined); + } + if (!execEditLength()) { + exec(); + } + }, 0); + }()); + } + else { + while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { + const ret = execEditLength(); + if (ret) { + return ret; + } + } + } + } + addToPath(path, added, removed, oldPosInc, options) { + const 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(basePath, newTokens, oldTokens, diagonalPath, options) { + const newLen = newTokens.length, oldLen = oldTokens.length; + let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[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(left, right, options) { + if (options.comparator) { + return options.comparator(left, right); + } + else { + return left === right + || (!!options.ignoreCase && left.toLowerCase() === right.toLowerCase()); + } + } + removeEmpty(array) { + const ret = []; + for (let i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } } - - 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) { - var last = path.lastComponent; - - if (last && 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) { - var newLen = newString.length, - oldLen = oldString.length, - oldPos = basePath.oldPos, - newPos = oldPos - diagonalPath, - commonCount = 0; - - while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { - newPos++; - oldPos++; - commonCount++; - } - - if (commonCount) { - basePath.lastComponent = { - count: commonCount, - previousComponent: basePath.lastComponent - }; - } - - basePath.oldPos = oldPos; - return newPos; - }, - equals: function equals(left, right) { - if (this.options.comparator) { - return this.options.comparator(left, right); - } else { - return left === right || this.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]); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + castInput(value, options) { + return value; } - } - - return ret; - }, - castInput: function castInput(value) { - return value; - }, - tokenize: function tokenize(value) { - return value.split(''); - }, - join: function join(chars) { - return chars.join(''); - } - }; - - 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)); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + tokenize(value, options) { + return Array.from(value); + } + join(chars) { + // Assumes ValueT is string, which is the case for most subclasses. + // When it's false, e.g. in diffArrays, this method needs to be overridden (e.g. with a no-op) + // Yes, the casts are verbose and ugly, because this pattern - of having the base class SORT OF + // assume tokens and values are strings, but not completely - is weird and janky. + return chars.join(''); + } + postProcess(changeObjects, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + options) { + return changeObjects; + } + get useLongestToken() { + return false; + } + buildValues(lastComponent, newTokens, oldTokens) { + // First we convert our linked list of components in reverse order to an + // array in the right order: + const components = []; + let nextComponent; + while (lastComponent) { + components.push(lastComponent); + nextComponent = lastComponent.previousComponent; + delete lastComponent.previousComponent; + lastComponent = nextComponent; + } + components.reverse(); + const componentLen = components.length; + let componentPos = 0, newPos = 0, oldPos = 0; + for (; componentPos < componentLen; componentPos++) { + const component = components[componentPos]; + if (!component.removed) { + if (!component.added && this.useLongestToken) { + let value = newTokens.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + const oldValue = oldTokens[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = this.join(value); + } + else { + component.value = this.join(newTokens.slice(newPos, newPos + component.count)); + } + newPos += component.count; + // Common case + if (!component.added) { + oldPos += component.count; + } + } + else { + component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count)); + oldPos += component.count; + } + } + return components; } - - 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; // Reverse add and remove so removes are output first to match common convention - // The diffing algorithm is tied to add then remove output and this is the simplest - // route to get the desired output with minimal overhead. - - if (componentPos && components[componentPos - 1].added) { - var tmp = components[componentPos - 1]; - components[componentPos - 1] = components[componentPos]; - components[componentPos] = tmp; - } - } - } // Special case handle for when one terminal is ignored (i.e. whitespace). - // For this case we merge the terminal into the prior string and drop the change. - // This is only available for string mode. - - - var finalComponent = components[componentLen - 1]; - - if (componentLen > 1 && typeof finalComponent.value === 'string' && (finalComponent.added || finalComponent.removed) && diff.equals('', finalComponent.value)) { - components[componentLen - 2].value += finalComponent.value; - components.pop(); - } - - return components; - } - - var characterDiff = new Diff(); - function diffChars(oldStr, newStr, options) { - return characterDiff.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; - } - - // - // 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-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; - var reWhitespace = /\S/; - var wordDiff = new Diff(); - - wordDiff.equals = function (left, right) { - if (this.options.ignoreCase) { - left = left.toLowerCase(); - right = right.toLowerCase(); + class CharacterDiff extends Diff { } - - return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); - }; - - wordDiff.tokenize = function (value) { - // All whitespace symbols except newline group into one token, each newline - in separate token - var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. - - for (var i = 0; i < tokens.length - 1; i++) { - // If we have an empty string in the next field and we have only word chars before and after, merge - if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { - tokens[i] += tokens[i + 2]; - tokens.splice(i + 1, 2); - i--; - } + const characterDiff = new CharacterDiff(); + function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); } - return tokens; - }; - - function diffWords(oldStr, newStr, options) { - options = generateOptions(options, { - ignoreWhitespace: true - }); - return wordDiff.diff(oldStr, newStr, options); - } - function diffWordsWithSpace(oldStr, newStr, options) { - return wordDiff.diff(oldStr, newStr, options); - } - - var lineDiff = new Diff(); - - lineDiff.tokenize = function (value) { - if (this.options.stripTrailingCr) { - // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior - value = value.replace(/\r\n/g, '\n'); + function longestCommonPrefix(str1, str2) { + let 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); } - - 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 && !this.options.newlineIsToken) { - retLines[retLines.length - 1] += line; - } else { - if (this.options.ignoreWhitespace) { - line = line.trim(); + function longestCommonSuffix(str1, str2) { + let 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 ''; } - - retLines.push(line); - } + 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); } - - return retLines; - }; - - function diffLines(oldStr, newStr, callback) { - return lineDiff.diff(oldStr, newStr, callback); - } - 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 _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; + function replacePrefix(string, oldPrefix, newPrefix) { + if (string.slice(0, oldPrefix.length) != oldPrefix) { + throw Error(`string ${JSON.stringify(string)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`); + } + return newPrefix + string.slice(oldPrefix.length); } - - return _typeof(obj); - } - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; + function replaceSuffix(string, oldSuffix, newSuffix) { + if (!oldSuffix) { + return string + newSuffix; + } + if (string.slice(-oldSuffix.length) != oldSuffix) { + throw Error(`string ${JSON.stringify(string)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`); + } + return string.slice(0, -oldSuffix.length) + newSuffix; } - - return obj; - } - - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); + function removePrefix(string, oldPrefix) { + return replacePrefix(string, oldPrefix, ''); } - - return keys; - } - - function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } + function removeSuffix(string, oldSuffix) { + return replaceSuffix(string, oldSuffix, ''); } - - return target; - } - - 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" && Symbol.iterator in Object(iter)) 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 objectPrototypeToString = Object.prototype.toString; - 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) { - var _this$options = this.options, - undefinedReplacement = _this$options.undefinedReplacement, - _this$options$stringi = _this$options.stringifyReplacer, - stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { - return typeof v === 'undefined' ? undefinedReplacement : v; - } : _this$options$stringi; - return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); - }; - - jsonDiff.equals = function (left, right) { - return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); - }; - - 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); + function maximumOverlap(string1, string2) { + return string2.slice(0, overlapCount(string1, string2)); } - - var i; - - for (i = 0; i < stack.length; i += 1) { - if (stack[i] === obj) { - return replacementStack[i]; - } + // Nicked from https://stackoverflow.com/a/60422853/1709587 + function overlapCount(a, b) { + // Deal with cases where the strings differ in length + let startA = 0; + if (a.length > b.length) { + startA = a.length - b.length; + } + let 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: + const map = Array(endB); + let k = 0; // Index that lags behind j + map[0] = 0; + for (let 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 (let i = startA; i < a.length; i++) { + while (k > 0 && a[i] != b[k]) { + k = map[k]; + } + if (a[i] == b[k]) { + k++; + } + } + return k; } - - var canonicalizedObj; - - if ('[object Array]' === objectPrototypeToString.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; + /** + * 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/); } - - if (obj && obj.toJSON) { - obj = obj.toJSON(); + /** + * Returns true if the string consistently uses Unix line endings. + */ + function hasOnlyUnixLineEndings(string) { + return !string.includes('\r\n') && string.includes('\n'); } - - if (_typeof(obj) === 'object' && obj !== null) { - stack.push(obj); - canonicalizedObj = {}; - replacementStack.push(canonicalizedObj); - - var sortedKeys = [], - _key; - - for (_key in obj) { - /* istanbul ignore else */ - if (obj.hasOwnProperty(_key)) { - sortedKeys.push(_key); + /** + * Split a string into segments using a word segmenter, merging consecutive + * segments if they are both whitespace segments. Whitespace segments can + * appear adjacent to one another for two reasons: + * - newlines always get their own segment + * - where a diacritic is attached to a whitespace character in the text, the + * segment ends after the diacritic, so e.g. " \u0300 " becomes two segments. + * This function therefore runs the segmenter's .segment() method and then + * merges consecutive segments of whitespace into a single part. + */ + function segment(string, segmenter) { + const parts = []; + for (const segmentObj of Array.from(segmenter.segment(string))) { + const segment = segmentObj.segment; + if (parts.length && (/\s/).test(parts[parts.length - 1]) && (/\s/).test(segment)) { + parts[parts.length - 1] += segment; + } + else { + parts.push(segment); + } } - } - - 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 parts; } - - 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 parsePatch(uniDiff) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), - delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], - 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:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { - break; - } else if (/^@@/.test(_line)) { - index.hunks.push(parseHunk()); - } else if (_line && options.strict) { - // Ignore unexpected content unless in strict mode - 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+(.*)$/.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: [], - linedelimiters: [] - }; // 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; i++) { - // Lines starting with '---' could be mistaken for the "remove line" operation - // But they could be the header for the next file. Therefore prune such cases out. - if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { - break; - } - - var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; - - if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { - hunk.lines.push(diffstr[i]); - hunk.linedelimiters.push(delimiters[i] || '\n'); - - if (operation === '+') { - addCount++; - } else if (operation === '-') { - removeCount++; - } else if (operation === ' ') { - addCount++; - removeCount++; - } - } else { - break; - } - } // Handle the empty block count case - - - if (!addCount && hunk.newLines === 1) { - hunk.newLines = 0; - } - - if (!removeCount && hunk.oldLines === 1) { - hunk.oldLines = 0; - } // Perform optional sanity checking - - - if (options.strict) { - if (addCount !== hunk.newLines) { - throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + // The functions below take a `segmenter` argument so that, when called from + // diffWords when it is using a segmenter, they can use a notion of what + // constitutes "whitespace" that is consistent with the segmenter. + // + // USUALLY this will be identical to the result of the non-segmenter-based + // logic, but it differs in at least one case: when whitespace characters are + // modified by diacritics. A word segmenter considers these diacritics to be + // part of the whitespace, whereas our non-segmenter-based logic does not. + // + // Because the segmenter-based approach necessarily requires segmenting the + // entire string, we offer a leadingAndTrailingWs function to allow getting the + // whitespace prefix AND whitespace suffix with a single call to the segmenter, + // for efficiency's sake. + function trailingWs(string, segmenter) { + if (segmenter) { + return leadingAndTrailingWs(string, segmenter)[1]; } - - if (removeCount !== hunk.oldLines) { - throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + // Yes, this looks overcomplicated and dumb - why not replace the whole function with + // return string.match(/\s*$/)[0] + // you ask? Because: + // 1. the trap described at https://markamery.com/blog/quadratic-time-regexes/ would mean doing + // this would cause this function to take O(n²) time in the worst case (specifically when + // there is a massive run of NON-TRAILING whitespace in `string`), and + // 2. the fix proposed in the same blog post, of using a negative lookbehind, is incompatible + // with old Safari versions that we'd like to not break if possible (see + // https://github.com/kpdecker/jsdiff/pull/550) + // It feels absurd to do this with an explicit loop instead of a regex, but I really can't see a + // better way that doesn't result in broken behaviour. + let i; + for (i = string.length - 1; i >= 0; i--) { + if (!string[i].match(/\s/)) { + break; + } } - } - - return hunk; + return string.substring(i + 1); } - - while (i < diffstr.length) { - parseIndex(); + function leadingWs(string, segmenter) { + if (segmenter) { + return leadingAndTrailingWs(string, segmenter)[0]; + } + // Thankfully the annoying considerations described in trailingWs don't apply here: + const match = string.match(/^\s*/); + return match ? match[0] : ''; } - - 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 localOffset; + function leadingAndTrailingWs(string, segmenter) { + if (!segmenter) { + return [leadingWs(string), trailingWs(string)]; } - - 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 -localOffset++; + if (segmenter.resolvedOptions().granularity != 'word') { + throw new Error('The segmenter passed must have a granularity of "word"'); } - - 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); + const segments = segment(string, segmenter); + const firstSeg = segments[0]; + const lastSeg = segments[segments.length - 1]; + const head = (/\s/).test(firstSeg) ? firstSeg : ''; + const tail = (/\s/).test(lastSeg) ? lastSeg : ''; + return [head, tail]; } - if (Array.isArray(uniDiff)) { - if (uniDiff.length > 1) { - throw new Error('applyPatch only works with a single input.'); - } - - uniDiff = uniDiff[0]; - } // Apply the diff to the input - - - var lines = source.split(/\r\n|[\n\v\f\r\x85]/), - delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], - hunks = uniDiff.hunks, - compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { - return line === patchContent; - }, - errorCount = 0, - fuzzFactor = options.fuzzFactor || 0, - minLine = 0, - offset = 0, - removeEOFNL, - addEOFNL; - /** - * Checks if the hunk exactly fits on the provided location - */ - - - function hunkFits(hunk, toPos) { - for (var j = 0; j < hunk.lines.length; j++) { - var line = hunk.lines[j], - operation = line.length > 0 ? line[0] : ' ', - content = line.length > 0 ? line.substr(1) : line; - - if (operation === ' ' || operation === '-') { - // Context sanity check - if (!compareLine(toPos + 1, lines[toPos], operation, content)) { - errorCount++; - - if (errorCount > fuzzFactor) { - return false; + // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode + // + // Chars/ranges counted as "word" characters by this regex are as follows: + // + // + U+00AD Soft hyphen + // + 00C0–00FF (letters with diacritics from the Latin-1 Supplement), except: + // - 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, except: + // - 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 + const extendedWordChars = 'a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\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 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. + const tokenizeIncludingWhitespace = new RegExp(`[${extendedWordChars}]+|\\s+|[^${extendedWordChars}]`, 'ug'); + class WordDiff extends Diff { + equals(left, right, options) { + if (options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); } - } - - toPos++; + return left.trim() === right.trim(); } - } - - return true; - } // Search best fit offsets for each hunk based on the previous ones - - - for (var i = 0; i < hunks.length; i++) { - var hunk = hunks[i], - maxLine = lines.length - hunk.oldLines, - localOffset = 0, - toPos = offset + hunk.oldStart - 1; - var iterator = distanceIterator(toPos, minLine, maxLine); - - for (; localOffset !== undefined; localOffset = iterator()) { - if (hunkFits(hunk, toPos + localOffset)) { - hunk.offset = offset += localOffset; - break; + tokenize(value, options = {}) { + let parts; + if (options.intlSegmenter) { + const segmenter = options.intlSegmenter; + if (segmenter.resolvedOptions().granularity != 'word') { + throw new Error('The segmenter passed must have a granularity of "word"'); + } + // We want `parts` to be an array whose elements alternate between being + // pure whitespace and being pure non-whitespace. This is ALMOST what the + // segments returned by a word-based Intl.Segmenter already look like, + // but not quite - see explanation in the docs of our custom segment() + // function. + parts = segment(value, segmenter); + } + else { + parts = value.match(tokenizeIncludingWhitespace) || []; + } + const tokens = []; + let prevPart = null; + parts.forEach(part => { + if ((/\s/).test(part)) { + if (prevPart == null) { + tokens.push(part); + } + else { + tokens.push(tokens.pop() + part); + } + } + else if (prevPart != null && (/\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; + } + join(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((token, i) => { + if (i == 0) { + return token; + } + else { + return token.replace((/^\s+/), ''); + } + }).join(''); + } + postProcess(changes, options) { + if (!changes || options.oneChangePerToken) { + return changes; + } + let lastKeep = null; + // Change objects representing any insertion or deletion since the last + // "keep" change object. There can be at most one of each. + let insertion = null; + let deletion = null; + changes.forEach(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, options.intlSegmenter); + } + lastKeep = change; + insertion = null; + deletion = null; + } + }); + if (insertion || deletion) { + dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null, options.intlSegmenter); + } + return changes; } - } - - if (localOffset === undefined) { - return false; - } // Set lower text limit to end of the current hunk, so next ones don't try - // to fit over already patched text - - - minLine = hunk.offset + hunk.oldStart + hunk.oldLines; - } // Apply patch hunks - - - var diffOffset = 0; - - for (var _i = 0; _i < hunks.length; _i++) { - var _hunk = hunks[_i], - _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; - - diffOffset += _hunk.newLines - _hunk.oldLines; - - for (var j = 0; j < _hunk.lines.length; j++) { - var line = _hunk.lines[j], - operation = line.length > 0 ? line[0] : ' ', - content = line.length > 0 ? line.substr(1) : line, - delimiter = _hunk.linedelimiters && _hunk.linedelimiters[j] || '\n'; - - if (operation === ' ') { - _toPos++; - } else if (operation === '-') { - lines.splice(_toPos, 1); - delimiters.splice(_toPos, 1); - /* istanbul ignore else */ - } else if (operation === '+') { - lines.splice(_toPos, 0, content); - delimiters.splice(_toPos, 0, delimiter); - _toPos++; - } else if (operation === '\\') { - var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; - - if (previousOperation === '+') { - removeEOFNL = true; - } else if (previousOperation === '-') { - addEOFNL = true; - } - } - } - } // Handle EOFNL insertion/removal - - - if (removeEOFNL) { - while (!lines[lines.length - 1]) { - lines.pop(); - delimiters.pop(); - } - } else if (addEOFNL) { - lines.push(''); - delimiters.push('\n'); - } - - for (var _k = 0; _k < lines.length - 1; _k++) { - lines[_k] = lines[_k] + delimiters[_k]; - } - - return lines.join(''); - } // 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); + const wordDiff = new WordDiff(); + 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); } - - var updatedContent = applyPatch(data, index, options); - options.patched(index, updatedContent, function (err) { - if (err) { - return options.complete(err); - } - - processIndex(); - }); - }); + return wordDiff.diff(oldStr, newStr, options); } - - processIndex(); - } - - function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - if (!options) { - options = {}; + function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep, segmenter) { + // 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) { + const [oldWsPrefix, oldWsSuffix] = leadingAndTrailingWs(deletion.value, segmenter); + const [newWsPrefix, newWsSuffix] = leadingAndTrailingWs(insertion.value, segmenter); + if (startKeep) { + const 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) { + const 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) { + const ws = leadingWs(insertion.value, segmenter); + insertion.value = insertion.value.substring(ws.length); + } + if (endKeep) { + const ws = leadingWs(endKeep.value, segmenter); + endKeep.value = endKeep.value.substring(ws.length); + } + // otherwise we've got a deletion and no insertion + } + else if (startKeep && endKeep) { + const newWsFull = leadingWs(endKeep.value, segmenter), [delWsStart, delWsEnd] = leadingAndTrailingWs(deletion.value, segmenter); + // Any whitespace that comes straight after startKeep in both the old and + // new texts, assign to startKeep and remove from the deletion. + const 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. + const 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. + const endKeepWsPrefix = leadingWs(endKeep.value, segmenter); + const deletionWsSuffix = trailingWs(deletion.value, segmenter); + const 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. + const startKeepWsSuffix = trailingWs(startKeep.value, segmenter); + const deletionWsPrefix = leadingWs(deletion.value, segmenter); + const overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix); + deletion.value = removePrefix(deletion.value, overlap); + } } - - if (typeof options.context === 'undefined') { - options.context = 4; + class WordsWithSpaceDiff extends Diff { + tokenize(value) { + // Slightly different to the tokenizeIncludingWhitespace regex used above in + // that this one treats each individual newline as a distinct token, 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 + const regex = new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`, 'ug'); + return value.match(regex) || []; + } } - - var diff = diffLines(oldStr, newStr, options); - - if (!diff) { - return; + const wordsWithSpaceDiff = new WordsWithSpaceDiff(); + function diffWordsWithSpace(oldStr, newStr, options) { + return wordsWithSpaceDiff.diff(oldStr, newStr, options); } - diff.push({ - value: '', - lines: [] - }); // Append an empty value to make cleanup easier - - function contextLines(lines) { - return lines.map(function (entry) { - return ' ' + entry; - }); + function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } + else if (options) { + for (const name in options) { + /* istanbul ignore else */ + if (Object.prototype.hasOwnProperty.call(options, name)) { + defaults[name] = options[name]; + } + } + } + return defaults; } - var hunks = []; - var oldRangeStart = 0, - newRangeStart = 0, - curRange = [], - oldLine = 1, - newLine = 1; - - var _loop = function _loop(i) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, '').split('\n'); - 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 - }; - - if (i >= diff.length - 2 && lines.length <= options.context) { - // EOF is inside this hunk - var oldEOFNewline = /\n$/.test(oldStr); - var newEOFNewline = /\n$/.test(newStr); - var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; - - if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { - // special case: old has no eol and no trailing context; no-nl can end up before adds - // however, if the old file is empty, do not output the no-nl line - curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); - } - - if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { - curRange.push('\\ No newline at end of file'); - } + class LineDiff extends Diff { + constructor() { + super(...arguments); + this.tokenize = tokenize; + } + equals(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(); + } } - - hunks.push(hunk); - oldRangeStart = 0; - newRangeStart = 0; - curRange = []; - } + 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 super.equals(left, right, options); } - - oldLine += lines.length; - newLine += lines.length; - } - }; - - for (var i = 0; i < diff.length; i++) { - _loop(i); } - - return { - oldFileName: oldFileName, - newFileName: newFileName, - oldHeader: oldHeader, - newHeader: newHeader, - hunks: hunks - }; - } - function formatPatch(diff) { - if (Array.isArray(diff)) { - return diff.map(formatPatch).join('\n'); + const lineDiff = new LineDiff(); + function diffLines(oldStr, newStr, options) { + return lineDiff.diff(oldStr, newStr, options); } - - var ret = []; - - if (diff.oldFileName == diff.newFileName) { - ret.push('Index: ' + diff.oldFileName); + function diffTrimmedLines(oldStr, newStr, options) { + options = generateOptions(options, { ignoreWhitespace: true }); + return lineDiff.diff(oldStr, newStr, options); } - - 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); + // Exported standalone so it can be used from jsonDiff too. + function tokenize(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'); + } + const 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 (let i = 0; i < linesAndNewlines.length; i++) { + const line = linesAndNewlines[i]; + if (i % 2 && !options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } + else { + retLines.push(line); + } + } + return retLines; } - return ret.join('\n') + '\n'; - } - function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); - } - function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { - return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); - } - - function arrayEqual(a, b) { - if (a.length !== b.length) { - return false; + function isSentenceEndPunct(char) { + return char == '.' || char == '!' || char == '?'; } - - return arrayStartsWith(a, b); - } - function arrayStartsWith(array, start) { - if (start.length > array.length) { - return false; + class SentenceDiff extends Diff { + tokenize(value) { + var _a; + // If in future we drop support for environments that don't support lookbehinds, we can replace + // this entire function with: + // return value.split(/(?<=[.!?])(\s+|$)/); + // but until then, for similar reasons to the trailingWs function in string.ts, we are forced + // to do this verbosely "by hand" instead of using a regex. + const result = []; + let tokenStartI = 0; + for (let i = 0; i < value.length; i++) { + if (i == value.length - 1) { + result.push(value.slice(tokenStartI)); + break; + } + if (isSentenceEndPunct(value[i]) && value[i + 1].match(/\s/)) { + // We've hit a sentence break - i.e. a punctuation mark followed by whitespace. + // We now want to push TWO tokens to the result: + // 1. the sentence + result.push(value.slice(tokenStartI, i + 1)); + // 2. the whitespace + i = tokenStartI = i + 1; + while ((_a = value[i + 1]) === null || _a === void 0 ? void 0 : _a.match(/\s/)) { + i++; + } + result.push(value.slice(tokenStartI, i + 1)); + // Then the next token (a sentence) starts on the character after the whitespace. + // (It's okay if this is off the end of the string - then the outer loop will terminate + // here anyway.) + tokenStartI = i + 1; + } + } + return result; + } } - - for (var i = 0; i < start.length; i++) { - if (start[i] !== array[i]) { - return false; - } + const sentenceDiff = new SentenceDiff(); + function diffSentences(oldStr, newStr, options) { + return sentenceDiff.diff(oldStr, newStr, options); } - 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; + class CssDiff extends Diff { + tokenize(value) { + return value.split(/([{}:;,]|\s+)/); + } } - - if (newLines !== undefined) { - hunk.newLines = newLines; - } else { - delete hunk.newLines; + const cssDiff = new CssDiff(); + function diffCss(oldStr, newStr, options) { + return cssDiff.diff(oldStr, newStr, options); } - } - 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; + class JsonDiff extends Diff { + constructor() { + super(...arguments); + this.tokenize = tokenize; + } + get useLongestToken() { + // 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: + return true; + } + castInput(value, options) { + const { undefinedReplacement, stringifyReplacer = (k, v) => typeof v === 'undefined' ? undefinedReplacement : v } = options; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), null, ' '); + } + equals(left, right, options) { + return super.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'), options); + } } - - 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); - } + const jsonDiff = new JsonDiff(); + function diffJson(oldStr, newStr, options) { + return jsonDiff.diff(oldStr, newStr, options); } - - 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); - } + // 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 === undefined ? '' : key, obj); + } + let i; + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + let 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, String(i)); + } + 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); + const sortedKeys = []; + let 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; } - 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); + class ArrayDiff extends Diff { + tokenize(value) { + return value.slice(); + } + join(value) { + return value; + } + removeEmpty(value) { + return value; + } } - - 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 - }; + const arrayDiff = new ArrayDiff(); + function diffArrays(oldArr, newArr, options) { + return arrayDiff.diff(oldArr, newArr, options); } - } - - 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; + function unixToWin(patch) { + if (Array.isArray(patch)) { + // It would be cleaner if instead of the line below we could just write + // return patch.map(unixToWin) + // but mysteriously TypeScript (v5.7.3 at the time of writing) does not like this and it will + // refuse to compile, thinking that unixToWin could then return StructuredPatch[][] and the + // result would be incompatible with the overload signatures. + // See bug report at https://github.com/microsoft/TypeScript/issues/61398. + return patch.map(p => unixToWin(p)); + } + return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map(hunk => (Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line, i) => { + var _a; + return (line.startsWith('\\') || line.endsWith('\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\'))) + ? line + : line + '\r'; + }) }))) }); } - - 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 winToUnix(patch) { + if (Array.isArray(patch)) { + // (See comment above equivalent line in unixToWin) + return patch.map(p => winToUnix(p)); + } + return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map(hunk => (Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map(line => line.endsWith('\r') ? line.substring(0, line.length - 1) : line) }))) }); } - } - - 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++; + /** + * 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(index => index.hunks.some(hunk => hunk.lines.some(line => !line.startsWith('\\') && line.endsWith('\r')))); } - } - - function insertTrailing(hunk, insert) { - while (insert.index < insert.lines.length) { - var line = insert.lines[insert.index++]; - hunk.lines.push(line); + /** + * 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(index => index.hunks.some(hunk => hunk.lines.some(line => line.endsWith('\r')))) + && patch.every(index => index.hunks.every(hunk => hunk.lines.every((line, i) => { var _a; return line.startsWith('\\') || line.endsWith('\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\')); }))); } - } - - 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; - } + /** + * Parses a patch into structured data, in the same structure returned by `structuredPatch`. + * + * @return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. + */ + function parsePatch(uniDiff) { + const diffstr = uniDiff.split(/\n/), list = []; + let i = 0; + function parseIndex() { + const index = {}; + list.push(index); + // Parse diff metadata + while (i < diffstr.length) { + const line = diffstr[i]; + // File header found, end parsing diff metadata + if ((/^(---|\+\+\+|@@)\s/).test(line)) { + break; + } + // Try to parse the line as a diff header, like + // Index: README.md + // or + // diff -r 9117c6561b0b -r 273ce12ad8f1 .hgignore + // or + // Index: something with multiple words + // and extract the filename (or whatever else is used as an index name) + // from the end (i.e. 'README.md', '.hgignore', or + // 'something with multiple words' in the examples above). + // + // TODO: It seems awkward that we indiscriminately trim off trailing + // whitespace here. Theoretically, couldn't that be meaningful - + // e.g. if the patch represents a diff of a file whose name ends + // with a space? Seems wrong to nuke it. + // But this behaviour has been around since v2.2.1 in 2015, so if + // it's going to change, it should be done cautiously and in a new + // major release, for backwards-compat reasons. + // -- ExplodingCabbage + const headerMatch = (/^(?:Index:|diff(?: -r \w+)+)\s+/).exec(line); + if (headerMatch) { + index.index = line.substring(headerMatch[0].length).trim(); + } + 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) { + const 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) { + const fileHeaderMatch = (/^(---|\+\+\+)\s+/).exec(diffstr[i]); + if (fileHeaderMatch) { + const prefix = fileHeaderMatch[1], data = diffstr[i].substring(3).trim().split('\t', 2), header = (data[1] || '').trim(); + let fileName = data[0].replace(/\\\\/g, '\\'); + if (fileName.startsWith('"') && fileName.endsWith('"')) { + fileName = fileName.substr(1, fileName.length - 2); + } + if (prefix === '---') { + index.oldFileName = fileName; + index.oldHeader = header; + } + else { + index.newFileName = fileName; + index.newHeader = header; + } + i++; + } + } + // Parses a hunk + // This assumes that we are at the start of a hunk. + function parseHunk() { + var _a; + const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + const 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; + } + let addCount = 0, removeCount = 0; + for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a = diffstr[i]) === null || _a === void 0 ? void 0 : _a.startsWith('\\'))); i++) { + const 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 ${chunkHeaderIndex + 1} contained invalid line ${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; } - 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; + // 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) { + let 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 + return undefined; + }; + } - while (change[0] === '+') { - changes.push(change); - change = state.lines[++state.index]; + /** + * attempts to apply a unified diff patch. + * + * Hunks are applied first to last. + * `applyPatch` first tries to apply the first hunk at the line number specified in the hunk header, and with all context lines matching exactly. + * If that fails, it tries scanning backwards and forwards, one line at a time, to find a place to apply the hunk where the context lines match exactly. + * If that still fails, and `fuzzFactor` is greater than zero, it increments the maximum number of mismatches (missing, extra, or changed context lines) that there can be between the hunk context and a region where we are trying to apply the patch such that the hunk will still be considered to match. + * Regardless of `fuzzFactor`, lines to be deleted in the hunk *must* be present for a hunk to match, and the context lines *immediately* before and after an insertion must match exactly. + * + * Once a hunk is successfully fitted, the process begins again with the next hunk. + * Regardless of `fuzzFactor`, later hunks must be applied later in the file than earlier hunks. + * + * If a hunk cannot be successfully fitted *anywhere* with fewer than `fuzzFactor` mismatches, `applyPatch` fails and returns `false`. + * + * If a hunk is successfully fitted but not at the line number specified by the hunk header, all subsequent hunks have their target line number adjusted accordingly. + * (e.g. if the first hunk is applied 10 lines below where the hunk header said it should fit, `applyPatch` will *start* looking for somewhere to apply the second hunk 10 lines below where its hunk header says it goes.) + * + * If the patch was applied successfully, returns a string containing the patched text. + * If the patch could not be applied (because some hunks in the patch couldn't be fitted to the text in `source`), `applyPatch` returns false. + * + * @param patch a string diff or the output from the `parsePatch` or `structuredPatch` methods. + */ + function applyPatch(source, patch, options = {}) { + let patches; + if (typeof patch === 'string') { + patches = parsePatch(patch); } - } - - if (match.substr(1) === change.substr(1)) { - changes.push(change); - state.index++; - } else { - conflicted = true; - } + else if (Array.isArray(patch)) { + patches = patch; + } + else { + patches = [patch]; + } + if (patches.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + return applyStructuredPatch(source, patches[0], options); } - - if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { - conflicted = true; + function applyStructuredPatch(source, patch, options = {}) { + if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) { + if (hasOnlyWinLineEndings(source) && isUnix(patch)) { + patch = unixToWin(patch); + } + else if (hasOnlyUnixLineEndings(source) && isWin(patch)) { + patch = winToUnix(patch); + } + } + // Apply the diff to the input + const lines = source.split('\n'), hunks = patch.hunks, compareLine = options.compareLine || ((lineNumber, line, operation, patchContent) => line === patchContent), fuzzFactor = options.fuzzFactor || 0; + let 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: + let prevLine = '', removeEOFNL = false, addEOFNL = false; + for (let i = 0; i < hunks[hunks.length - 1].lines.length; i++) { + const 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, hunkLinesI = 0, lastContextLineMatched = true, patchedLines = [], patchedLinesLength = 0) { + let nConsecutiveOldContextLines = 0; + let nextContextLineMustMatch = false; + for (; hunkLinesI < hunkLines.length; hunkLinesI++) { + const 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, + oldLineLastI: toPos - 1 + }; + } + const resultLines = []; + // Search best fit offsets for each hunk based on the previous ones + let prevHunkOffset = 0; + for (let i = 0; i < hunks.length; i++) { + const hunk = hunks[i]; + let hunkResult; + const maxLine = lines.length - hunk.oldLines + fuzzFactor; + let toPos; + for (let maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) { + toPos = hunk.oldStart + prevHunkOffset - 1; + const 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 (let i = minLine; i < toPos; i++) { + resultLines.push(lines[i]); + } + // Add the lines produced by applying the hunk: + for (let i = 0; i < hunkResult.patchedLines.length; i++) { + const line = hunkResult.patchedLines[i]; + 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 (let i = minLine; i < lines.length; i++) { + resultLines.push(lines[i]); + } + return resultLines.join('\n'); } - - if (conflicted) { - return changes; + /** + * applies one or more patches. + * + * `patch` may be either an array of structured patch objects, or a string representing a patch in unified diff format (which may patch one or more files). + * + * This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is: + * + * - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. + * - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution. + * + * Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. + */ + function applyPatches(uniDiff, options) { + const spDiff = typeof uniDiff === 'string' ? parsePatch(uniDiff) : uniDiff; + let currentIndex = 0; + function processIndex() { + const index = spDiff[currentIndex++]; + if (!index) { + return options.complete(); + } + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + const updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + processIndex(); + }); + }); + } + processIndex(); } - while (matchIndex < matchChanges.length) { - merged.push(matchChanges[matchIndex++]); + function reversePatch(structuredPatch) { + if (Array.isArray(structuredPatch)) { + // (See comment in unixToWin for why we need the pointless-looking anonymous function here) + return structuredPatch.map(patch => reversePatch(patch)).reverse(); + } + return Object.assign(Object.assign({}, structuredPatch), { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(hunk => { + return { + oldLines: hunk.newLines, + oldStart: hunk.newStart, + newLines: hunk.oldLines, + newStart: hunk.oldStart, + lines: hunk.lines.map(l => { + if (l.startsWith('-')) { + return `+${l.slice(1)}`; + } + if (l.startsWith('+')) { + return `-${l.slice(1)}`; + } + return l; + }) + }; + }) }); } - return { - merged: merged, - changes: changes + const INCLUDE_HEADERS = { + includeIndex: true, + includeUnderline: true, + includeFileHeaders: true }; - } - - 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; - } + const FILE_HEADERS_ONLY = { + includeIndex: false, + includeUnderline: false, + includeFileHeaders: true + }; + const OMIT_HEADERS = { + includeIndex: false, + includeUnderline: false, + includeFileHeaders: false + }; + function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + let optionsObj; + if (!options) { + optionsObj = {}; + } + else if (typeof options === 'function') { + optionsObj = { callback: options }; + } + else { + optionsObj = options; + } + if (typeof optionsObj.context === 'undefined') { + optionsObj.context = 4; + } + // We copy this into its own variable to placate TypeScript, which thinks + // optionsObj.context might be undefined in the callbacks below. + const context = optionsObj.context; + // @ts-expect-error (runtime check for something that is correctly a static type error) + if (optionsObj.newlineIsToken) { + throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions'); + } + if (!optionsObj.callback) { + return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj)); + } + else { + const { callback } = optionsObj; + diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => { + const patch = diffLinesResultToPatch(diff); + // TypeScript is unhappy without the cast because it does not understand that `patch` may + // be undefined here only if `callback` is StructuredPatchCallbackAbortable: + 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; }); + } + const hunks = []; + let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; + for (let i = 0; i < diff.length; i++) { + const current = diff[i], lines = current.lines || splitLines(current.value); + current.lines = lines; + if (current.added || current.removed) { + // If we have previous context, start with that + if (!oldRangeStart) { + const prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + if (prev) { + curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + // Output our changes + for (const line of lines) { + curRange.push((current.added ? '+' : '-') + line); + } + // 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 <= context * 2 && i < diff.length - 2) { + // Overlapping + for (const line of contextLines(lines)) { + curRange.push(line); + } + } + else { + // end the range and output + const contextSize = Math.min(lines.length, context); + for (const line of contextLines(lines.slice(0, contextSize))) { + curRange.push(line); + } + const 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; + } + } + // Step 2: eliminate the trailing `\n` from each line of each hunk, and, where needed, add + // "\ No newline at end of file". + for (const hunk of hunks) { + for (let i = 0; i < hunk.lines.length; i++) { + if (hunk.lines[i].endsWith('\n')) { + hunk.lines[i] = hunk.lines[i].slice(0, -1); + } + else { + hunk.lines.splice(i + 1, 0, '\\ No newline at end of file'); + i++; // Skip the line we just added, then continue iterating + } + } + } + return { + oldFileName: oldFileName, newFileName: newFileName, + oldHeader: oldHeader, newHeader: newHeader, + hunks: hunks + }; + } } - - 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; - } + /** + * creates a unified diff patch. + * @param patch either a single structured patch object (as returned by `structuredPatch`) or an array of them (as returned by `parsePatch`) + */ + function formatPatch(patch, headerOptions) { + if (!headerOptions) { + headerOptions = INCLUDE_HEADERS; } - - if (newLines !== undefined) { - if (myCount.newLines === theirCount.newLines) { - newLines += myCount.newLines; - } else { - newLines = undefined; - } + if (Array.isArray(patch)) { + if (patch.length > 1 && !headerOptions.includeFileHeaders) { + throw new Error('Cannot omit file headers on a multi-file patch. ' + + '(The result would be unparseable; how would a tool trying to apply ' + + 'the patch know which changes are to which file?)'); + } + return patch.map(p => formatPatch(p, headerOptions)).join('\n'); } - } else { - if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { - newLines++; + const ret = []; + if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) { + ret.push('Index: ' + patch.oldFileName); } - - 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(); + if (headerOptions.includeUnderline) { + ret.push('==================================================================='); + } + if (headerOptions.includeFileHeaders) { + ret.push('--- ' + patch.oldFileName + (typeof patch.oldHeader === 'undefined' ? '' : '\t' + patch.oldHeader)); + ret.push('+++ ' + patch.newFileName + (typeof patch.newHeader === 'undefined' ? '' : '\t' + patch.newHeader)); + } + for (let i = 0; i < patch.hunks.length; i++) { + const hunk = patch.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 + + ' @@'); + for (const line of hunk.lines) { + ret.push(line); + } + } + return ret.join('\n') + '\n'; } - - 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, - linedelimiters: hunk.linedelimiters, - lines: hunk.lines.map(function (l) { - if (l.startsWith('-')) { - return "+".concat(l.slice(1)); + function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (typeof options === 'function') { + options = { callback: options }; + } + if (!(options === null || options === void 0 ? void 0 : options.callback)) { + const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + if (!patchObj) { + return; } + return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions); + } + else { + const { callback } = options; + structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: patchObj => { + if (!patchObj) { + callback(undefined); + } + else { + callback(formatPatch(patchObj, options.headerOptions)); + } + } })); + } + } + 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) { + const hasTrailingNl = text.endsWith('\n'); + const result = text.split('\n').map(line => line + '\n'); + if (hasTrailingNl) { + result.pop(); + } + else { + result.push(result.pop().slice(0, -1)); + } + return result; + } - if (l.startsWith('+')) { - return "-".concat(l.slice(1)); + /** + * converts a list of change objects to the format returned by Google's [diff-match-patch](https://github.com/google/diff-match-patch) library + */ + function convertChangesToDMP(changes) { + const ret = []; + let change, operation; + for (let i = 0; i < changes.length; i++) { + change = changes[i]; + if (change.added) { + operation = 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]); + else if (change.removed) { + operation = -1; + } + else { + operation = 0; + } + ret.push([operation, change.value]); + } + return ret; } - 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(''); - } + /** + * converts a list of change objects to a serialized XML format + */ + function convertChangesToXML(changes) { + const ret = []; + for (let i = 0; i < changes.length; i++) { + const 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) { + let n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; } - 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; - - Object.defineProperty(exports, '__esModule', { value: true }); - -}))); + exports.Diff = Diff; + exports.FILE_HEADERS_ONLY = FILE_HEADERS_ONLY; + exports.INCLUDE_HEADERS = INCLUDE_HEADERS; + exports.OMIT_HEADERS = OMIT_HEADERS; + exports.applyPatch = applyPatch; + exports.applyPatches = applyPatches; + exports.arrayDiff = arrayDiff; + exports.canonicalize = canonicalize; + exports.characterDiff = characterDiff; + exports.convertChangesToDMP = convertChangesToDMP; + exports.convertChangesToXML = convertChangesToXML; + exports.createPatch = createPatch; + exports.createTwoFilesPatch = createTwoFilesPatch; + exports.cssDiff = cssDiff; + 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.jsonDiff = jsonDiff; + exports.lineDiff = lineDiff; + exports.parsePatch = parsePatch; + exports.reversePatch = reversePatch; + exports.sentenceDiff = sentenceDiff; + exports.structuredPatch = structuredPatch; + exports.wordDiff = wordDiff; + exports.wordsWithSpaceDiff = wordsWithSpaceDiff; + +})); diff --git a/node_modules/diff/dist/diff.min.js b/node_modules/diff/dist/diff.min.js index 078bcc5c2e6a7..663b37595c0d7 100644 --- a/node_modules/diff/dist/diff.min.js +++ b/node_modules/diff/dist/diff.min.js @@ -1 +1 @@ -!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e=e||self).Diff={})}(this,function(e){"use strict";function t(){}t.prototype={diff:function(s,a,e){var n,t=2=c&&f<=v+1)return d([{value:this.join(a),count:a.length}]);var m=-1/0,g=1/0;function w(){for(var e=Math.max(m,-p);e<=Math.min(g,p);e+=2){var n=void 0,t=h[e-1],r=h[e+1];t&&(h[e-1]=void 0);var i,o=!1;r&&(i=r.oldPos-e,o=r&&0<=i&&i=c&&f<=v+1)return d(function(e,n,t,r,i){var o,l=[];for(;n;)l.push(n),o=n.previousComponent,delete n.previousComponent,n=o;l.reverse();for(var s=0,a=l.length,u=0,d=0;se.length?t:e}),p.value=e.join(c)):p.value=e.join(t.slice(u,u+p.count)),u+=p.count,p.added||(d+=p.count))}var h=l[a-1];1=c&&(g=Math.min(g,e-1)),f<=v+1&&(m=Math.max(m,e+1))}else h[e]=void 0}p++}if(r)!function e(){setTimeout(function(){return il?r():void(w()||e())},0)}();else for(;p<=i&&Date.now()<=l;){var y=w();if(y)return y}},addToPath:function(e,n,t,r){var i=e.lastComponent;return i&&i.added===n&&i.removed===t?{oldPos:e.oldPos+r,lastComponent:{count:i.count+1,added:n,removed:t,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:n,removed:t,previousComponent:i}}},extractCommon:function(e,n,t,r){for(var i=n.length,o=t.length,l=e.oldPos,s=l-r,a=0;s+1e.length)&&(n=e.length);for(var t=0,r=new Array(n);t=c.length-2&&a.length<=f.context&&(i=/\n$/.test(u),o=/\n$/.test(d),l=0==a.length&&m.length>r.oldLines,!i&&l&&0e.length)return!1;for(var t=0;t"):i.removed&&t.push(""),t.push((n=i.value,n.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""))),i.added?t.push(""):i.removed&&t.push("")}return t.join("")},e.createPatch=function(e,n,t,r,i,o){return b(e,e,n,t,r,i,o)},e.createTwoFilesPatch=b,e.diffArrays=function(e,n,t){return g.diff(e,n,t)},e.diffChars=function(e,n,t){return r.diff(e,n,t)},e.diffCss=function(e,n,t){return d.diff(e,n,t)},e.diffJson=function(e,n,t){return v.diff(e,n,t)},e.diffLines=L,e.diffSentences=function(e,n,t){return u.diff(e,n,t)},e.diffTrimmedLines=function(e,n,t){var r=i(t,{ignoreWhitespace:!0});return a.diff(e,n,r)},e.diffWords=function(e,n,t){return t=i(t,{ignoreWhitespace:!0}),s.diff(e,n,t)},e.diffWordsWithSpace=function(e,n,t){return s.diff(e,n,t)},e.formatPatch=S,e.merge=function(e,n,t){e=N(e,t),n=N(n,t);var r={};(e.index||n.index)&&(r.index=e.index||n.index),(e.newFileName||n.newFileName)&&(P(e)?P(n)?(r.oldFileName=j(r,e.oldFileName,n.oldFileName),r.newFileName=j(r,e.newFileName,n.newFileName),r.oldHeader=j(r,e.oldHeader,n.oldHeader),r.newHeader=j(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=[];for(var i=0,o=0,l=0,s=0;i{"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).Diff={})})(this,function(exports){class Diff{diff(oldStr,newStr,options={}){let callback;"function"==typeof options?(callback=options,options={}):"callback"in options&&(callback=options.callback);oldStr=this.castInput(oldStr,options),newStr=this.castInput(newStr,options),oldStr=this.removeEmpty(this.tokenize(oldStr,options)),newStr=this.removeEmpty(this.tokenize(newStr,options));return this.diffWithOptionsObj(oldStr,newStr,options,callback)}diffWithOptionsObj(oldTokens,newTokens,options,callback){let _a,done=value=>{if(value=this.postProcess(value,options),!callback)return value;setTimeout(function(){callback(value)},0)},newLen=newTokens.length,oldLen=oldTokens.length,editLength=1,maxEditLength=newLen+oldLen;null!=options.maxEditLength&&(maxEditLength=Math.min(maxEditLength,options.maxEditLength));var maxExecutionTime=null!=(_a=options.timeout)?_a:1/0;let abortAfterTimestamp=Date.now()+maxExecutionTime,bestPath=[{oldPos:-1,lastComponent:void 0}],newPos=this.extractCommon(bestPath[0],newTokens,oldTokens,0,options);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(bestPath[0].lastComponent,newTokens,oldTokens));let minDiagonalToConsider=-1/0,maxDiagonalToConsider=1/0,execEditLength=()=>{for(let diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){let basePath;var removePath=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];removePath&&(bestPath[diagonalPath-1]=void 0);let canAdd=!1;addPath&&(addPathNewPos=addPath.oldPos-diagonalPath,canAdd=addPath&&0<=addPathNewPos&&addPathNewPos=oldLen&&newPos+1>=newLen)return done(this.buildValues(basePath.lastComponent,newTokens,oldTokens))||!0;(bestPath[diagonalPath]=basePath).oldPos+1>=oldLen&&(maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1)),newPos+1>=newLen&&(minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1))}else bestPath[diagonalPath]=void 0}editLength++};if(callback)!function exec(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp)return callback(void 0);execEditLength()||exec()},0)}();else for(;editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp;){var ret=execEditLength();if(ret)return ret}}addToPath(path,added,removed,oldPosInc,options){var last=path.lastComponent;return last&&!options.oneChangePerToken&&last.added===added&&last.removed===removed?{oldPos:path.oldPos+oldPosInc,lastComponent:{count:last.count+1,added:added,removed:removed,previousComponent:last.previousComponent}}:{oldPos:path.oldPos+oldPosInc,lastComponent:{count:1,added:added,removed:removed,previousComponent:last}}}extractCommon(basePath,newTokens,oldTokens,diagonalPath,options){var newLen=newTokens.length,oldLen=oldTokens.length;let oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;for(;newPos+1value.length?i:value}),component.value=this.join(value)}else component.value=this.join(newTokens.slice(newPos,newPos+component.count));newPos+=component.count,component.added||(oldPos+=component.count)}}return components}}class CharacterDiff extends Diff{}let characterDiff=new CharacterDiff;function longestCommonPrefix(str1,str2){let i;for(i=0;i{let startA=0,endB=(a.length>b.length&&(startA=a.length-b.length),b.length),map=(a.length{/\s/.test(part)?null==prevPart?tokens.push(part):tokens.push(tokens.pop()+part):null!=prevPart&&/\s/.test(prevPart)?tokens[tokens.length-1]==prevPart?tokens.push(tokens.pop()+part):tokens.push(prevPart+part):tokens.push(part),prevPart=part}),tokens}join(tokens){return tokens.map((token,i)=>0==i?token:token.replace(/^\s+/,"")).join("")}postProcess(changes,options){if(changes&&!options.oneChangePerToken){let lastKeep=null,insertion=null,deletion=null;changes.forEach(change=>{change.added?insertion=change:deletion=change.removed?change:((insertion||deletion)&&dedupeWhitespaceInChangeObjects(lastKeep,deletion,insertion,change,options.intlSegmenter),lastKeep=change,insertion=null)}),(insertion||deletion)&&dedupeWhitespaceInChangeObjects(lastKeep,deletion,insertion,null,options.intlSegmenter)}return changes}}let wordDiff=new WordDiff;function dedupeWhitespaceInChangeObjects(startKeep,deletion,insertion,endKeep,segmenter){if(deletion&&insertion){var[oldWsPrefix,oldWsSuffix]=leadingAndTrailingWs(deletion.value,segmenter),[newWsPrefix,newWsSuffix]=leadingAndTrailingWs(insertion.value,segmenter);startKeep&&(oldWsPrefix=longestCommonPrefix(oldWsPrefix,newWsPrefix),startKeep.value=replaceSuffix(startKeep.value,newWsPrefix,oldWsPrefix),deletion.value=removePrefix(deletion.value,oldWsPrefix),insertion.value=removePrefix(insertion.value,oldWsPrefix)),endKeep&&(newWsPrefix=longestCommonSuffix(oldWsSuffix,newWsSuffix),endKeep.value=replacePrefix(endKeep.value,newWsSuffix,newWsPrefix),deletion.value=removeSuffix(deletion.value,newWsPrefix),insertion.value=removeSuffix(insertion.value,newWsPrefix))}else if(insertion){if(startKeep&&(oldWsPrefix=leadingWs(insertion.value,segmenter),insertion.value=insertion.value.substring(oldWsPrefix.length)),endKeep){let ws=leadingWs(endKeep.value,segmenter);endKeep.value=endKeep.value.substring(ws.length)}}else if(startKeep&&endKeep){var oldWsSuffix=leadingWs(endKeep.value,segmenter),[newWsSuffix,newWsPrefix]=leadingAndTrailingWs(deletion.value,segmenter),insertion=longestCommonPrefix(oldWsSuffix,newWsSuffix),oldWsPrefix=(deletion.value=removePrefix(deletion.value,insertion),longestCommonSuffix(removePrefix(oldWsSuffix,insertion),newWsPrefix));deletion.value=removeSuffix(deletion.value,oldWsPrefix),endKeep.value=replacePrefix(endKeep.value,oldWsSuffix,oldWsPrefix),startKeep.value=replaceSuffix(startKeep.value,oldWsSuffix,oldWsSuffix.slice(0,oldWsSuffix.length-oldWsPrefix.length))}else if(endKeep){newWsSuffix=leadingWs(endKeep.value,segmenter),insertion=maximumOverlap(trailingWs(deletion.value,segmenter),newWsSuffix);deletion.value=removeSuffix(deletion.value,insertion)}else if(startKeep){let overlap=maximumOverlap(trailingWs(startKeep.value,segmenter),leadingWs(deletion.value,segmenter));deletion.value=removePrefix(deletion.value,overlap)}}class WordsWithSpaceDiff extends Diff{tokenize(value){var regex=new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`,"ug");return value.match(regex)||[]}}let wordsWithSpaceDiff=new WordsWithSpaceDiff;function diffWordsWithSpace(oldStr,newStr,options){return wordsWithSpaceDiff.diff(oldStr,newStr,options)}class LineDiff extends Diff{constructor(){super(...arguments),this.tokenize=tokenize}equals(left,right,options){return options.ignoreWhitespace?(options.newlineIsToken&&left.includes("\n")||(left=left.trim()),options.newlineIsToken&&right.includes("\n")||(right=right.trim())):options.ignoreNewlineAtEof&&!options.newlineIsToken&&(left.endsWith("\n")&&(left=left.slice(0,-1)),right.endsWith("\n"))&&(right=right.slice(0,-1)),super.equals(left,right,options)}}let lineDiff=new LineDiff;function diffLines(oldStr,newStr,options){return lineDiff.diff(oldStr,newStr,options)}function tokenize(value,options){var retLines=[],linesAndNewlines=(value=options.stripTrailingCr?value.replace(/\r\n/g,"\n"):value).split(/(\n|\r\n)/);linesAndNewlines[linesAndNewlines.length-1]||linesAndNewlines.pop();for(let i=0;ivoid 0===v?undefinedReplacement:v}=options;return"string"==typeof value?value:JSON.stringify(canonicalize(value,null,null,stringifyReplacer),null," ")}equals(left,right,options){return super.equals(left.replace(/,([\r\n])/g,"$1"),right.replace(/,([\r\n])/g,"$1"),options)}}let jsonDiff=new JsonDiff;function canonicalize(obj,stack,replacementStack,replacer,key){stack=stack||[],replacementStack=replacementStack||[],replacer&&(obj=replacer(void 0===key?"":key,obj));let i;for(i=0;i{var chunkHeaderIndex=i,chunkHeaderLine=diffstr[i++],hunk={oldStart:+(chunkHeaderLine=chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/))[1],oldLines:void 0===chunkHeaderLine[2]?1:+chunkHeaderLine[2],newStart:+chunkHeaderLine[3],newLines:void 0===chunkHeaderLine[4]?1:+chunkHeaderLine[4],lines:[]};0===hunk.oldLines&&(hunk.oldStart+=1),0===hunk.newLines&&(hunk.newStart+=1);let addCount=0,removeCount=0;for(;i{!options.autoConvertLineEndings&&null!=options.autoConvertLineEndings||((string=>string.includes("\r\n")&&!string.startsWith("\n")&&!string.match(/[^\r]\n/))(source)&&(patch=>!(patch=Array.isArray(patch)?patch:[patch]).some(index=>index.hunks.some(hunk=>hunk.lines.some(line=>!line.startsWith("\\")&&line.endsWith("\r")))))(patch)?patch=function unixToWin(patch){return Array.isArray(patch)?patch.map(p=>unixToWin(p)):Object.assign(Object.assign({},patch),{hunks:patch.hunks.map(hunk=>Object.assign(Object.assign({},hunk),{lines:hunk.lines.map((line,i)=>line.startsWith("\\")||line.endsWith("\r")||null!=(i=hunk.lines[i+1])&&i.startsWith("\\")?line:line+"\r")}))})}(patch):(string=>!string.includes("\r\n")&&string.includes("\n"))(source)&&(patch=>(patch=Array.isArray(patch)?patch:[patch]).some(index=>index.hunks.some(hunk=>hunk.lines.some(line=>line.endsWith("\r"))))&&patch.every(index=>index.hunks.every(hunk=>hunk.lines.every((line,i)=>line.startsWith("\\")||line.endsWith("\r")||(null==(line=hunk.lines[i+1])?void 0:line.startsWith("\\"))))))(patch)&&(patch=function winToUnix(patch){return Array.isArray(patch)?patch.map(p=>winToUnix(p)):Object.assign(Object.assign({},patch),{hunks:patch.hunks.map(hunk=>Object.assign(Object.assign({},hunk),{lines:hunk.lines.map(line=>line.endsWith("\r")?line.substring(0,line.length-1):line)}))})}(patch)));let lines=source.split("\n"),hunks=patch.hunks,compareLine=options.compareLine||((lineNumber,line,operation,patchContent)=>line===patchContent),fuzzFactor=options.fuzzFactor||0,minLine=0;if(fuzzFactor<0||!Number.isInteger(fuzzFactor))throw new Error("fuzzFactor must be a non-negative integer");if(!hunks.length)return source;let prevLine="",removeEOFNL=!1,addEOFNL=!1;for(let i=0;i{let wantForward=!0,backwardExhausted=!1,forwardExhausted=!1,localOffset=1;return function iterator(){if(wantForward&&!forwardExhausted){if(backwardExhausted?localOffset++:wantForward=!1,start+localOffset<=maxLine)return start+localOffset;forwardExhausted=!0}if(!backwardExhausted)return forwardExhausted||(wantForward=!0),minLine<=start-localOffset?start-localOffset++:(backwardExhausted=!0,iterator())}})(toPos=hunk.oldStart+prevHunkOffset-1,minLine,maxLine);void 0!==toPos&&!(hunkResult=function applyHunk(hunkLines,toPos,maxErrors,hunkLinesI=0,lastContextLineMatched=!0,patchedLines=[],patchedLinesLength=0){let nConsecutiveOldContextLines=0,nextContextLineMustMatch=!1;for(;hunkLinesI{diff=diffLinesResultToPatch(diff);callback(diff)}}))}function diffLinesResultToPatch(diff){if(diff){diff.push({value:"",lines:[]});var hunks=[];let oldRangeStart=0,newRangeStart=0,curRange=[],oldLine=1,newLine=1;for(let i=0;i{var hasTrailingNl=text.endsWith("\n"),text=text.split("\n").map(line=>line+"\n");return hasTrailingNl?text.pop():text.push(text.pop().slice(0,-1)),text})(current.value);if(current.lines=lines,current.added||current.removed){oldRangeStart||(prev=diff[i-1],oldRangeStart=oldLine,newRangeStart=newLine,prev&&(curRange=0formatPatch(p,headerOptions)).join("\n")}var ret=[];headerOptions.includeIndex&&patch.oldFileName==patch.newFileName&&ret.push("Index: "+patch.oldFileName),headerOptions.includeUnderline&&ret.push("==================================================================="),headerOptions.includeFileHeaders&&(ret.push("--- "+patch.oldFileName+(void 0===patch.oldHeader?"":"\t"+patch.oldHeader)),ret.push("+++ "+patch.newFileName+(void 0===patch.newHeader?"":"\t"+patch.newHeader)));for(let i=0;i{patchObj?callback(formatPatch(patchObj,options.headerOptions)):callback(void 0)}}))}else{oldFileName=structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options);if(oldFileName)return formatPatch(oldFileName,null==options?void 0:options.headerOptions)}}exports.Diff=Diff,exports.FILE_HEADERS_ONLY={includeIndex:!1,includeUnderline:!1,includeFileHeaders:!0},exports.INCLUDE_HEADERS=INCLUDE_HEADERS,exports.OMIT_HEADERS={includeIndex:!1,includeUnderline:!1,includeFileHeaders:!1},exports.applyPatch=applyPatch,exports.applyPatches=function(uniDiff,options){let spDiff="string"==typeof uniDiff?parsePatch(uniDiff):uniDiff,currentIndex=0;!function processIndex(){let index=spDiff[currentIndex++];if(!index)return options.complete();options.loadFile(index,function(err,data){if(err)return options.complete(err);err=applyPatch(data,index,options),options.patched(index,err,function(err){if(err)return options.complete(err);processIndex()})})}()},exports.arrayDiff=arrayDiff,exports.canonicalize=canonicalize,exports.characterDiff=characterDiff,exports.convertChangesToDMP=function(changes){var ret=[];let change,operation;for(let i=0;i"):change.removed&&ret.push(""),ret.push((s=>{let n=s;return n=(n=(n=(n=n.replace(/&/g,"&")).replace(//g,">")).replace(/"/g,""")})(change.value)),change.added?ret.push(""):change.removed&&ret.push("")}return ret.join("")},exports.createPatch=function(fileName,oldStr,newStr,oldHeader,newHeader,options){return createTwoFilesPatch(fileName,fileName,oldStr,newStr,oldHeader,newHeader,options)},exports.createTwoFilesPatch=createTwoFilesPatch,exports.cssDiff=cssDiff,exports.diffArrays=function(oldArr,newArr,options){return arrayDiff.diff(oldArr,newArr,options)},exports.diffChars=function(oldStr,newStr,options){return characterDiff.diff(oldStr,newStr,options)},exports.diffCss=function(oldStr,newStr,options){return cssDiff.diff(oldStr,newStr,options)},exports.diffJson=function(oldStr,newStr,options){return jsonDiff.diff(oldStr,newStr,options)},exports.diffLines=diffLines,exports.diffSentences=function(oldStr,newStr,options){return sentenceDiff.diff(oldStr,newStr,options)},exports.diffTrimmedLines=function(oldStr,newStr,options){return options=((options,defaults)=>{if("function"==typeof options)defaults.callback=options;else if(options)for(var name in options)Object.prototype.hasOwnProperty.call(options,name)&&(defaults[name]=options[name]);return defaults})(options,{ignoreWhitespace:!0}),lineDiff.diff(oldStr,newStr,options)},exports.diffWords=function(oldStr,newStr,options){return null==(null==options?void 0:options.ignoreWhitespace)||options.ignoreWhitespace?wordDiff.diff(oldStr,newStr,options):diffWordsWithSpace(oldStr,newStr,options)},exports.diffWordsWithSpace=diffWordsWithSpace,exports.formatPatch=formatPatch,exports.jsonDiff=jsonDiff,exports.lineDiff=lineDiff,exports.parsePatch=parsePatch,exports.reversePatch=function reversePatch(structuredPatch){return Array.isArray(structuredPatch)?structuredPatch.map(patch=>reversePatch(patch)).reverse():Object.assign(Object.assign({},structuredPatch),{oldFileName:structuredPatch.newFileName,oldHeader:structuredPatch.newHeader,newFileName:structuredPatch.oldFileName,newHeader:structuredPatch.oldHeader,hunks:structuredPatch.hunks.map(hunk=>({oldLines:hunk.newLines,oldStart:hunk.newStart,newLines:hunk.oldLines,newStart:hunk.oldStart,lines:hunk.lines.map(l=>l.startsWith("-")?"+"+l.slice(1):l.startsWith("+")?"-"+l.slice(1):l)}))})},exports.sentenceDiff=sentenceDiff,exports.structuredPatch=structuredPatch,exports.wordDiff=wordDiff,exports.wordsWithSpaceDiff=wordsWithSpaceDiff}); \ No newline at end of file diff --git a/node_modules/diff/eslint.config.mjs b/node_modules/diff/eslint.config.mjs new file mode 100644 index 0000000000000..ea1c73566ea89 --- /dev/null +++ b/node_modules/diff/eslint.config.mjs @@ -0,0 +1,182 @@ +// @ts-check + +import eslint from '@eslint/js'; +import tseslint from 'typescript-eslint'; +import globals from "globals"; + +export default tseslint.config( + { + ignores: [ + "**/*", // ignore everything... + "!src/**/", "!src/**/*.ts", // ... except our TypeScript source files... + "!test/**/", "!test/**/*.js", // ... and our tests + ], + }, + eslint.configs.recommended, + tseslint.configs.recommended, + { + files: ['src/**/*.ts'], + languageOptions: { + parserOptions: { + projectService: true, + tsconfigRootDir: import.meta.dirname, + }, + }, + extends: [tseslint.configs.recommendedTypeChecked], + rules: { + // Not sure if these actually serve a purpose, but they provide a way to enforce SOME of what + // would be imposed by having "verbatimModuleSyntax": true in our tsconfig.json without + // actually doing that. + "@typescript-eslint/consistent-type-imports": 2, + "@typescript-eslint/consistent-type-exports": 2, + + // Things from the recommendedTypeChecked shared config that are disabled simply because they + // caused lots of errors in our existing code when tried. Plausibly useful to turn on if + // possible and somebody fancies doing the work: + "@typescript-eslint/no-unsafe-argument": 0, + "@typescript-eslint/no-unsafe-assignment": 0, + "@typescript-eslint/no-unsafe-call": 0, + "@typescript-eslint/no-unsafe-member-access": 0, + "@typescript-eslint/no-unsafe-return": 0, + } + }, + { + languageOptions: { + globals: { + ...globals.browser, + }, + }, + + rules: { + // Possible Errors // + //-----------------// + "comma-dangle": [2, "never"], + "no-console": 1, // Allow for debugging + "no-debugger": 1, // Allow for debugging + "no-extra-parens": [2, "functions"], + "no-extra-semi": 2, + "no-negated-in-lhs": 2, + "no-unreachable": 1, // Optimizer and coverage will handle/highlight this and can be useful for debugging + + // Best Practices // + //----------------// + curly: 2, + "default-case": 1, + "dot-notation": [2, { + allowKeywords: false, + }], + "guard-for-in": 1, + "no-alert": 2, + "no-caller": 2, + "no-div-regex": 1, + "no-eval": 2, + "no-extend-native": 2, + "no-extra-bind": 2, + "no-floating-decimal": 2, + "no-implied-eval": 2, + "no-iterator": 2, + "no-labels": 2, + "no-lone-blocks": 2, + "no-multi-spaces": 2, + "no-multi-str": 1, + "no-native-reassign": 2, + "no-new": 2, + "no-new-func": 2, + "no-new-wrappers": 2, + "no-octal-escape": 2, + "no-process-env": 2, + "no-proto": 2, + "no-return-assign": 2, + "no-script-url": 2, + "no-self-compare": 2, + "no-sequences": 2, + "no-throw-literal": 2, + "no-unused-expressions": 2, + "no-warning-comments": 1, + radix: 2, + "wrap-iife": 2, + + // Variables // + //-----------// + "no-catch-shadow": 2, + "no-label-var": 2, + "no-undef-init": 2, + + // Node.js // + //---------// + + // Stylistic // + //-----------// + "brace-style": [2, "1tbs", { + allowSingleLine: true, + }], + camelcase: 2, + "comma-spacing": [2, { + before: false, + after: true, + }], + "comma-style": [2, "last"], + "consistent-this": [1, "self"], + "eol-last": 2, + "func-style": [2, "declaration"], + "key-spacing": [2, { + beforeColon: false, + afterColon: true, + }], + "new-cap": 2, + "new-parens": 2, + "no-array-constructor": 2, + "no-lonely-if": 2, + "no-mixed-spaces-and-tabs": 2, + "no-nested-ternary": 1, + "no-new-object": 2, + "no-spaced-func": 2, + "no-trailing-spaces": 2, + "quote-props": [2, "as-needed", { + keywords: true, + }], + quotes: [2, "single", "avoid-escape"], + semi: 2, + "semi-spacing": [2, { + before: false, + after: true, + }], + "space-before-blocks": [2, "always"], + "space-before-function-paren": [2, { + anonymous: "never", + named: "never", + }], + "space-in-parens": [2, "never"], + "space-infix-ops": 2, + "space-unary-ops": 2, + "spaced-comment": [2, "always"], + "wrap-regex": 1, + "no-var": 2, + + // Typescript // + //------------// + "@typescript-eslint/no-explicit-any": 0, // Very strict rule, incompatible with our code + + // We use these intentionally - e.g. + // export interface DiffCssOptions extends CommonDiffOptions {} + // for the options argument to diffCss which currently takes no options beyond the ones + // common to all diffFoo functions. Doing this allows consistency (one options interface per + // diffFoo function) and future-proofs against the API having to change in future if we add a + // non-common option to one of these functions. + "@typescript-eslint/no-empty-object-type": [2, {allowInterfaces: 'with-single-extends'}], + }, + }, + { + files: ['test/**/*.js'], + languageOptions: { + globals: { + ...globals.node, + ...globals.mocha, + }, + }, + rules: { + "no-unused-expressions": 0, // Needs disabling to support Chai `.to.be.undefined` etc syntax + "@typescript-eslint/no-unused-expressions": 0, // (as above) + }, + } +); diff --git a/node_modules/diff/lib/convert/dmp.js b/node_modules/diff/lib/convert/dmp.js deleted file mode 100644 index 91ff40a9120f7..0000000000000 --- a/node_modules/diff/lib/convert/dmp.js +++ /dev/null @@ -1,32 +0,0 @@ -/*istanbul ignore start*/ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.convertChangesToDMP = convertChangesToDMP; - -/*istanbul ignore end*/ -// 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; -} -//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L2RtcC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvRE1QIiwiY2hhbmdlcyIsInJldCIsImNoYW5nZSIsIm9wZXJhdGlvbiIsImkiLCJsZW5ndGgiLCJhZGRlZCIsInJlbW92ZWQiLCJwdXNoIiwidmFsdWUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztBQUFBO0FBQ08sU0FBU0EsbUJBQVQsQ0FBNkJDLE9BQTdCLEVBQXNDO0FBQzNDLE1BQUlDLEdBQUcsR0FBRyxFQUFWO0FBQUEsTUFDSUMsTUFESjtBQUFBLE1BRUlDLFNBRko7O0FBR0EsT0FBSyxJQUFJQyxDQUFDLEdBQUcsQ0FBYixFQUFnQkEsQ0FBQyxHQUFHSixPQUFPLENBQUNLLE1BQTVCLEVBQW9DRCxDQUFDLEVBQXJDLEVBQXlDO0FBQ3ZDRixJQUFBQSxNQUFNLEdBQUdGLE9BQU8sQ0FBQ0ksQ0FBRCxDQUFoQjs7QUFDQSxRQUFJRixNQUFNLENBQUNJLEtBQVgsRUFBa0I7QUFDaEJILE1BQUFBLFNBQVMsR0FBRyxDQUFaO0FBQ0QsS0FGRCxNQUVPLElBQUlELE1BQU0sQ0FBQ0ssT0FBWCxFQUFvQjtBQUN6QkosTUFBQUEsU0FBUyxHQUFHLENBQUMsQ0FBYjtBQUNELEtBRk0sTUFFQTtBQUNMQSxNQUFBQSxTQUFTLEdBQUcsQ0FBWjtBQUNEOztBQUVERixJQUFBQSxHQUFHLENBQUNPLElBQUosQ0FBUyxDQUFDTCxTQUFELEVBQVlELE1BQU0sQ0FBQ08sS0FBbkIsQ0FBVDtBQUNEOztBQUNELFNBQU9SLEdBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbIi8vIFNlZTogaHR0cDovL2NvZGUuZ29vZ2xlLmNvbS9wL2dvb2dsZS1kaWZmLW1hdGNoLXBhdGNoL3dpa2kvQVBJXG5leHBvcnQgZnVuY3Rpb24gY29udmVydENoYW5nZXNUb0RNUChjaGFuZ2VzKSB7XG4gIGxldCByZXQgPSBbXSxcbiAgICAgIGNoYW5nZSxcbiAgICAgIG9wZXJhdGlvbjtcbiAgZm9yIChsZXQgaSA9IDA7IGkgPCBjaGFuZ2VzLmxlbmd0aDsgaSsrKSB7XG4gICAgY2hhbmdlID0gY2hhbmdlc1tpXTtcbiAgICBpZiAoY2hhbmdlLmFkZGVkKSB7XG4gICAgICBvcGVyYXRpb24gPSAxO1xuICAgIH0gZWxzZSBpZiAoY2hhbmdlLnJlbW92ZWQpIHtcbiAgICAgIG9wZXJhdGlvbiA9IC0xO1xuICAgIH0gZWxzZSB7XG4gICAgICBvcGVyYXRpb24gPSAwO1xuICAgIH1cblxuICAgIHJldC5wdXNoKFtvcGVyYXRpb24sIGNoYW5nZS52YWx1ZV0pO1xuICB9XG4gIHJldHVybiByZXQ7XG59XG4iXX0= diff --git a/node_modules/diff/lib/convert/xml.js b/node_modules/diff/lib/convert/xml.js deleted file mode 100644 index 69ec60c66c81d..0000000000000 --- a/node_modules/diff/lib/convert/xml.js +++ /dev/null @@ -1,42 +0,0 @@ -/*istanbul ignore start*/ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.convertChangesToXML = convertChangesToXML; - -/*istanbul ignore end*/ -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; -} -//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L3htbC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvWE1MIiwiY2hhbmdlcyIsInJldCIsImkiLCJsZW5ndGgiLCJjaGFuZ2UiLCJhZGRlZCIsInB1c2giLCJyZW1vdmVkIiwiZXNjYXBlSFRNTCIsInZhbHVlIiwiam9pbiIsInMiLCJuIiwicmVwbGFjZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQU8sU0FBU0EsbUJBQVQsQ0FBNkJDLE9BQTdCLEVBQXNDO0FBQzNDLE1BQUlDLEdBQUcsR0FBRyxFQUFWOztBQUNBLE9BQUssSUFBSUMsQ0FBQyxHQUFHLENBQWIsRUFBZ0JBLENBQUMsR0FBR0YsT0FBTyxDQUFDRyxNQUE1QixFQUFvQ0QsQ0FBQyxFQUFyQyxFQUF5QztBQUN2QyxRQUFJRSxNQUFNLEdBQUdKLE9BQU8sQ0FBQ0UsQ0FBRCxDQUFwQjs7QUFDQSxRQUFJRSxNQUFNLENBQUNDLEtBQVgsRUFBa0I7QUFDaEJKLE1BQUFBLEdBQUcsQ0FBQ0ssSUFBSixDQUFTLE9BQVQ7QUFDRCxLQUZELE1BRU8sSUFBSUYsTUFBTSxDQUFDRyxPQUFYLEVBQW9CO0FBQ3pCTixNQUFBQSxHQUFHLENBQUNLLElBQUosQ0FBUyxPQUFUO0FBQ0Q7O0FBRURMLElBQUFBLEdBQUcsQ0FBQ0ssSUFBSixDQUFTRSxVQUFVLENBQUNKLE1BQU0sQ0FBQ0ssS0FBUixDQUFuQjs7QUFFQSxRQUFJTCxNQUFNLENBQUNDLEtBQVgsRUFBa0I7QUFDaEJKLE1BQUFBLEdBQUcsQ0FBQ0ssSUFBSixDQUFTLFFBQVQ7QUFDRCxLQUZELE1BRU8sSUFBSUYsTUFBTSxDQUFDRyxPQUFYLEVBQW9CO0FBQ3pCTixNQUFBQSxHQUFHLENBQUNLLElBQUosQ0FBUyxRQUFUO0FBQ0Q7QUFDRjs7QUFDRCxTQUFPTCxHQUFHLENBQUNTLElBQUosQ0FBUyxFQUFULENBQVA7QUFDRDs7QUFFRCxTQUFTRixVQUFULENBQW9CRyxDQUFwQixFQUF1QjtBQUNyQixNQUFJQyxDQUFDLEdBQUdELENBQVI7QUFDQUMsRUFBQUEsQ0FBQyxHQUFHQSxDQUFDLENBQUNDLE9BQUYsQ0FBVSxJQUFWLEVBQWdCLE9BQWhCLENBQUo7QUFDQUQsRUFBQUEsQ0FBQyxHQUFHQSxDQUFDLENBQUNDLE9BQUYsQ0FBVSxJQUFWLEVBQWdCLE1BQWhCLENBQUo7QUFDQUQsRUFBQUEsQ0FBQyxHQUFHQSxDQUFDLENBQUNDLE9BQUYsQ0FBVSxJQUFWLEVBQWdCLE1BQWhCLENBQUo7QUFDQUQsRUFBQUEsQ0FBQyxHQUFHQSxDQUFDLENBQUNDLE9BQUYsQ0FBVSxJQUFWLEVBQWdCLFFBQWhCLENBQUo7QUFFQSxTQUFPRCxDQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gY29udmVydENoYW5nZXNUb1hNTChjaGFuZ2VzKSB7XG4gIGxldCByZXQgPSBbXTtcbiAgZm9yIChsZXQgaSA9IDA7IGkgPCBjaGFuZ2VzLmxlbmd0aDsgaSsrKSB7XG4gICAgbGV0IGNoYW5nZSA9IGNoYW5nZXNbaV07XG4gICAgaWYgKGNoYW5nZS5hZGRlZCkge1xuICAgICAgcmV0LnB1c2goJzxpbnM+Jyk7XG4gICAgfSBlbHNlIGlmIChjaGFuZ2UucmVtb3ZlZCkge1xuICAgICAgcmV0LnB1c2goJzxkZWw+Jyk7XG4gICAgfVxuXG4gICAgcmV0LnB1c2goZXNjYXBlSFRNTChjaGFuZ2UudmFsdWUpKTtcblxuICAgIGlmIChjaGFuZ2UuYWRkZWQpIHtcbiAgICAgIHJldC5wdXNoKCc8L2lucz4nKTtcbiAgICB9IGVsc2UgaWYgKGNoYW5nZS5yZW1vdmVkKSB7XG4gICAgICByZXQucHVzaCgnPC9kZWw+Jyk7XG4gICAgfVxuICB9XG4gIHJldHVybiByZXQuam9pbignJyk7XG59XG5cbmZ1bmN0aW9uIGVzY2FwZUhUTUwocykge1xuICBsZXQgbiA9IHM7XG4gIG4gPSBuLnJlcGxhY2UoLyYvZywgJyZhbXA7Jyk7XG4gIG4gPSBuLnJlcGxhY2UoLzwvZywgJyZsdDsnKTtcbiAgbiA9IG4ucmVwbGFjZSgvPi9nLCAnJmd0OycpO1xuICBuID0gbi5yZXBsYWNlKC9cIi9nLCAnJnF1b3Q7Jyk7XG5cbiAgcmV0dXJuIG47XG59XG4iXX0= diff --git a/node_modules/diff/lib/diff/array.js b/node_modules/diff/lib/diff/array.js deleted file mode 100644 index 19e36809893c1..0000000000000 --- a/node_modules/diff/lib/diff/array.js +++ /dev/null @@ -1,45 +0,0 @@ -/*istanbul ignore start*/ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.diffArrays = diffArrays; -exports.arrayDiff = 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 arrayDiff = new -/*istanbul ignore start*/ -_base -/*istanbul ignore end*/ -[ -/*istanbul ignore start*/ -"default" -/*istanbul ignore end*/ -](); - -/*istanbul ignore start*/ -exports.arrayDiff = arrayDiff; - -/*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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2FycmF5LmpzIl0sIm5hbWVzIjpbImFycmF5RGlmZiIsIkRpZmYiLCJ0b2tlbml6ZSIsInZhbHVlIiwic2xpY2UiLCJqb2luIiwicmVtb3ZlRW1wdHkiLCJkaWZmQXJyYXlzIiwib2xkQXJyIiwibmV3QXJyIiwiY2FsbGJhY2siLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFFTyxJQUFNQSxTQUFTLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSixFQUFsQjs7Ozs7O0FBQ1BELFNBQVMsQ0FBQ0UsUUFBVixHQUFxQixVQUFTQyxLQUFULEVBQWdCO0FBQ25DLFNBQU9BLEtBQUssQ0FBQ0MsS0FBTixFQUFQO0FBQ0QsQ0FGRDs7QUFHQUosU0FBUyxDQUFDSyxJQUFWLEdBQWlCTCxTQUFTLENBQUNNLFdBQVYsR0FBd0IsVUFBU0gsS0FBVCxFQUFnQjtBQUN2RCxTQUFPQSxLQUFQO0FBQ0QsQ0FGRDs7QUFJTyxTQUFTSSxVQUFULENBQW9CQyxNQUFwQixFQUE0QkMsTUFBNUIsRUFBb0NDLFFBQXBDLEVBQThDO0FBQUUsU0FBT1YsU0FBUyxDQUFDVyxJQUFWLENBQWVILE1BQWYsRUFBdUJDLE1BQXZCLEVBQStCQyxRQUEvQixDQUFQO0FBQWtEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcblxuZXhwb3J0IGNvbnN0IGFycmF5RGlmZiA9IG5ldyBEaWZmKCk7XG5hcnJheURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWUuc2xpY2UoKTtcbn07XG5hcnJheURpZmYuam9pbiA9IGFycmF5RGlmZi5yZW1vdmVFbXB0eSA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIHJldHVybiB2YWx1ZTtcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmQXJyYXlzKG9sZEFyciwgbmV3QXJyLCBjYWxsYmFjaykgeyByZXR1cm4gYXJyYXlEaWZmLmRpZmYob2xkQXJyLCBuZXdBcnIsIGNhbGxiYWNrKTsgfVxuIl19 diff --git a/node_modules/diff/lib/diff/base.js b/node_modules/diff/lib/diff/base.js deleted file mode 100644 index 428e7fd97e819..0000000000000 --- a/node_modules/diff/lib/diff/base.js +++ /dev/null @@ -1,358 +0,0 @@ -/*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 = {}; - } - - this.options = options; - var self = this; - - function done(value) { - if (callback) { - setTimeout(function () { - callback(undefined, value); - }, 0); - return true; - } else { - return value; - } - } // Allow subclasses to massage the input prior to running - - - oldString = this.castInput(oldString); - newString = this.castInput(newString); - oldString = this.removeEmpty(this.tokenize(oldString)); - newString = this.removeEmpty(this.tokenize(newString)); - var newLen = newString.length, - oldLen = oldString.length; - var editLength = 1; - var maxEditLength = newLen + oldLen; - - if (options.maxEditLength) { - 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); - - if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { - // Identity per the equality and tokenizer - return done([{ - value: this.join(newString), - count: newString.length - }]); - } // 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 - // TODO: Remove the `+ 1` here to make behavior match Myers algorithm - // and prefer to order removals before insertions. - - - if (!canRemove || canAdd && removePath.oldPos + 1 < addPath.oldPos) { - basePath = self.addToPath(addPath, true, undefined, 0); - } else { - basePath = self.addToPath(removePath, undefined, true, 1); - } - - newPos = self.extractCommon(basePath, newString, oldString, diagonalPath); - - 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) { - var last = path.lastComponent; - - if (last && 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) { - var newLen = newString.length, - oldLen = oldString.length, - oldPos = basePath.oldPos, - newPos = oldPos - diagonalPath, - commonCount = 0; - - while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { - newPos++; - oldPos++; - commonCount++; - } - - if (commonCount) { - basePath.lastComponent = { - count: commonCount, - previousComponent: basePath.lastComponent - }; - } - - basePath.oldPos = oldPos; - return newPos; - }, - - /*istanbul ignore start*/ - - /*istanbul ignore end*/ - equals: function equals(left, right) { - if (this.options.comparator) { - return this.options.comparator(left, right); - } else { - return left === right || this.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 value.split(''); - }, - - /*istanbul ignore start*/ - - /*istanbul ignore end*/ - join: function join(chars) { - return chars.join(''); - } -}; - -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; // Reverse add and remove so removes are output first to match common convention - // The diffing algorithm is tied to add then remove output and this is the simplest - // route to get the desired output with minimal overhead. - - if (componentPos && components[componentPos - 1].added) { - var tmp = components[componentPos - 1]; - components[componentPos - 1] = components[componentPos]; - components[componentPos] = tmp; - } - } - } // Special case handle for when one terminal is ignored (i.e. whitespace). - // For this case we merge the terminal into the prior string and drop the change. - // This is only available for string mode. - - - var finalComponent = components[componentLen - 1]; - - if (componentLen > 1 && typeof finalComponent.value === 'string' && (finalComponent.added || finalComponent.removed) && diff.equals('', finalComponent.value)) { - components[componentLen - 2].value += finalComponent.value; - components.pop(); - } - - return components; -} -//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Jhc2UuanMiXSwibmFtZXMiOlsiRGlmZiIsInByb3RvdHlwZSIsImRpZmYiLCJvbGRTdHJpbmciLCJuZXdTdHJpbmciLCJvcHRpb25zIiwiY2FsbGJhY2siLCJzZWxmIiwiZG9uZSIsInZhbHVlIiwic2V0VGltZW91dCIsInVuZGVmaW5lZCIsImNhc3RJbnB1dCIsInJlbW92ZUVtcHR5IiwidG9rZW5pemUiLCJuZXdMZW4iLCJsZW5ndGgiLCJvbGRMZW4iLCJlZGl0TGVuZ3RoIiwibWF4RWRpdExlbmd0aCIsIk1hdGgiLCJtaW4iLCJtYXhFeGVjdXRpb25UaW1lIiwidGltZW91dCIsIkluZmluaXR5IiwiYWJvcnRBZnRlclRpbWVzdGFtcCIsIkRhdGUiLCJub3ciLCJiZXN0UGF0aCIsIm9sZFBvcyIsImxhc3RDb21wb25lbnQiLCJuZXdQb3MiLCJleHRyYWN0Q29tbW9uIiwiam9pbiIsImNvdW50IiwibWluRGlhZ29uYWxUb0NvbnNpZGVyIiwibWF4RGlhZ29uYWxUb0NvbnNpZGVyIiwiZXhlY0VkaXRMZW5ndGgiLCJkaWFnb25hbFBhdGgiLCJtYXgiLCJiYXNlUGF0aCIsInJlbW92ZVBhdGgiLCJhZGRQYXRoIiwiY2FuQWRkIiwiYWRkUGF0aE5ld1BvcyIsImNhblJlbW92ZSIsImFkZFRvUGF0aCIsImJ1aWxkVmFsdWVzIiwidXNlTG9uZ2VzdFRva2VuIiwiZXhlYyIsInJldCIsInBhdGgiLCJhZGRlZCIsInJlbW92ZWQiLCJvbGRQb3NJbmMiLCJsYXN0IiwicHJldmlvdXNDb21wb25lbnQiLCJjb21tb25Db3VudCIsImVxdWFscyIsImxlZnQiLCJyaWdodCIsImNvbXBhcmF0b3IiLCJpZ25vcmVDYXNlIiwidG9Mb3dlckNhc2UiLCJhcnJheSIsImkiLCJwdXNoIiwic3BsaXQiLCJjaGFycyIsImNvbXBvbmVudHMiLCJuZXh0Q29tcG9uZW50IiwicmV2ZXJzZSIsImNvbXBvbmVudFBvcyIsImNvbXBvbmVudExlbiIsImNvbXBvbmVudCIsInNsaWNlIiwibWFwIiwib2xkVmFsdWUiLCJ0bXAiLCJmaW5hbENvbXBvbmVudCIsInBvcCJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQWUsU0FBU0EsSUFBVCxHQUFnQixDQUFFOztBQUVqQ0EsSUFBSSxDQUFDQyxTQUFMLEdBQWlCO0FBQUE7O0FBQUE7QUFDZkMsRUFBQUEsSUFEZSxnQkFDVkMsU0FEVSxFQUNDQyxTQURELEVBQzBCO0FBQUE7QUFBQTs7QUFBQTtBQUFBO0FBQWRDLElBQUFBLE9BQWMsdUVBQUosRUFBSTtBQUN2QyxRQUFJQyxRQUFRLEdBQUdELE9BQU8sQ0FBQ0MsUUFBdkI7O0FBQ0EsUUFBSSxPQUFPRCxPQUFQLEtBQW1CLFVBQXZCLEVBQW1DO0FBQ2pDQyxNQUFBQSxRQUFRLEdBQUdELE9BQVg7QUFDQUEsTUFBQUEsT0FBTyxHQUFHLEVBQVY7QUFDRDs7QUFDRCxTQUFLQSxPQUFMLEdBQWVBLE9BQWY7QUFFQSxRQUFJRSxJQUFJLEdBQUcsSUFBWDs7QUFFQSxhQUFTQyxJQUFULENBQWNDLEtBQWQsRUFBcUI7QUFDbkIsVUFBSUgsUUFBSixFQUFjO0FBQ1pJLFFBQUFBLFVBQVUsQ0FBQyxZQUFXO0FBQUVKLFVBQUFBLFFBQVEsQ0FBQ0ssU0FBRCxFQUFZRixLQUFaLENBQVI7QUFBNkIsU0FBM0MsRUFBNkMsQ0FBN0MsQ0FBVjtBQUNBLGVBQU8sSUFBUDtBQUNELE9BSEQsTUFHTztBQUNMLGVBQU9BLEtBQVA7QUFDRDtBQUNGLEtBakJzQyxDQW1CdkM7OztBQUNBTixJQUFBQSxTQUFTLEdBQUcsS0FBS1MsU0FBTCxDQUFlVCxTQUFmLENBQVo7QUFDQUMsSUFBQUEsU0FBUyxHQUFHLEtBQUtRLFNBQUwsQ0FBZVIsU0FBZixDQUFaO0FBRUFELElBQUFBLFNBQVMsR0FBRyxLQUFLVSxXQUFMLENBQWlCLEtBQUtDLFFBQUwsQ0FBY1gsU0FBZCxDQUFqQixDQUFaO0FBQ0FDLElBQUFBLFNBQVMsR0FBRyxLQUFLUyxXQUFMLENBQWlCLEtBQUtDLFFBQUwsQ0FBY1YsU0FBZCxDQUFqQixDQUFaO0FBRUEsUUFBSVcsTUFBTSxHQUFHWCxTQUFTLENBQUNZLE1BQXZCO0FBQUEsUUFBK0JDLE1BQU0sR0FBR2QsU0FBUyxDQUFDYSxNQUFsRDtBQUNBLFFBQUlFLFVBQVUsR0FBRyxDQUFqQjtBQUNBLFFBQUlDLGFBQWEsR0FBR0osTUFBTSxHQUFHRSxNQUE3Qjs7QUFDQSxRQUFHWixPQUFPLENBQUNjLGFBQVgsRUFBMEI7QUFDeEJBLE1BQUFBLGFBQWEsR0FBR0MsSUFBSSxDQUFDQyxHQUFMLENBQVNGLGFBQVQsRUFBd0JkLE9BQU8sQ0FBQ2MsYUFBaEMsQ0FBaEI7QUFDRDs7QUFDRCxRQUFNRyxnQkFBZ0I7QUFBQTtBQUFBO0FBQUE7QUFBR2pCLElBQUFBLE9BQU8sQ0FBQ2tCLE9BQVgsK0RBQXNCQyxRQUE1QztBQUNBLFFBQU1DLG1CQUFtQixHQUFHQyxJQUFJLENBQUNDLEdBQUwsS0FBYUwsZ0JBQXpDO0FBRUEsUUFBSU0sUUFBUSxHQUFHLENBQUM7QUFBRUMsTUFBQUEsTUFBTSxFQUFFLENBQUMsQ0FBWDtBQUFjQyxNQUFBQSxhQUFhLEVBQUVuQjtBQUE3QixLQUFELENBQWYsQ0FuQ3VDLENBcUN2Qzs7QUFDQSxRQUFJb0IsTUFBTSxHQUFHLEtBQUtDLGFBQUwsQ0FBbUJKLFFBQVEsQ0FBQyxDQUFELENBQTNCLEVBQWdDeEIsU0FBaEMsRUFBMkNELFNBQTNDLEVBQXNELENBQXRELENBQWI7O0FBQ0EsUUFBSXlCLFFBQVEsQ0FBQyxDQUFELENBQVIsQ0FBWUMsTUFBWixHQUFxQixDQUFyQixJQUEwQlosTUFBMUIsSUFBb0NjLE1BQU0sR0FBRyxDQUFULElBQWNoQixNQUF0RCxFQUE4RDtBQUM1RDtBQUNBLGFBQU9QLElBQUksQ0FBQyxDQUFDO0FBQUNDLFFBQUFBLEtBQUssRUFBRSxLQUFLd0IsSUFBTCxDQUFVN0IsU0FBVixDQUFSO0FBQThCOEIsUUFBQUEsS0FBSyxFQUFFOUIsU0FBUyxDQUFDWTtBQUEvQyxPQUFELENBQUQsQ0FBWDtBQUNELEtBMUNzQyxDQTRDdkM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7O0FBQ0EsUUFBSW1CLHFCQUFxQixHQUFHLENBQUNYLFFBQTdCO0FBQUEsUUFBdUNZLHFCQUFxQixHQUFHWixRQUEvRCxDQTdEdUMsQ0ErRHZDOztBQUNBLGFBQVNhLGNBQVQsR0FBMEI7QUFDeEIsV0FDRSxJQUFJQyxZQUFZLEdBQUdsQixJQUFJLENBQUNtQixHQUFMLENBQVNKLHFCQUFULEVBQWdDLENBQUNqQixVQUFqQyxDQURyQixFQUVFb0IsWUFBWSxJQUFJbEIsSUFBSSxDQUFDQyxHQUFMLENBQVNlLHFCQUFULEVBQWdDbEIsVUFBaEMsQ0FGbEIsRUFHRW9CLFlBQVksSUFBSSxDQUhsQixFQUlFO0FBQ0EsWUFBSUUsUUFBUTtBQUFBO0FBQUE7QUFBWjtBQUFBO0FBQ0EsWUFBSUMsVUFBVSxHQUFHYixRQUFRLENBQUNVLFlBQVksR0FBRyxDQUFoQixDQUF6QjtBQUFBLFlBQ0lJLE9BQU8sR0FBR2QsUUFBUSxDQUFDVSxZQUFZLEdBQUcsQ0FBaEIsQ0FEdEI7O0FBRUEsWUFBSUcsVUFBSixFQUFnQjtBQUNkO0FBQ0FiLFVBQUFBLFFBQVEsQ0FBQ1UsWUFBWSxHQUFHLENBQWhCLENBQVIsR0FBNkIzQixTQUE3QjtBQUNEOztBQUVELFlBQUlnQyxNQUFNLEdBQUcsS0FBYjs7QUFDQSxZQUFJRCxPQUFKLEVBQWE7QUFDWDtBQUNBLGNBQU1FLGFBQWEsR0FBR0YsT0FBTyxDQUFDYixNQUFSLEdBQWlCUyxZQUF2QztBQUNBSyxVQUFBQSxNQUFNLEdBQUdELE9BQU8sSUFBSSxLQUFLRSxhQUFoQixJQUFpQ0EsYUFBYSxHQUFHN0IsTUFBMUQ7QUFDRDs7QUFFRCxZQUFJOEIsU0FBUyxHQUFHSixVQUFVLElBQUlBLFVBQVUsQ0FBQ1osTUFBWCxHQUFvQixDQUFwQixHQUF3QlosTUFBdEQ7O0FBQ0EsWUFBSSxDQUFDMEIsTUFBRCxJQUFXLENBQUNFLFNBQWhCLEVBQTJCO0FBQ3pCO0FBQ0FqQixVQUFBQSxRQUFRLENBQUNVLFlBQUQsQ0FBUixHQUF5QjNCLFNBQXpCO0FBQ0E7QUFDRCxTQXJCRCxDQXVCQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOzs7QUFDQSxZQUFJLENBQUNrQyxTQUFELElBQWVGLE1BQU0sSUFBSUYsVUFBVSxDQUFDWixNQUFYLEdBQW9CLENBQXBCLEdBQXdCYSxPQUFPLENBQUNiLE1BQTdELEVBQXNFO0FBQ3BFVyxVQUFBQSxRQUFRLEdBQUdqQyxJQUFJLENBQUN1QyxTQUFMLENBQWVKLE9BQWYsRUFBd0IsSUFBeEIsRUFBOEIvQixTQUE5QixFQUF5QyxDQUF6QyxDQUFYO0FBQ0QsU0FGRCxNQUVPO0FBQ0w2QixVQUFBQSxRQUFRLEdBQUdqQyxJQUFJLENBQUN1QyxTQUFMLENBQWVMLFVBQWYsRUFBMkI5QixTQUEzQixFQUFzQyxJQUF0QyxFQUE0QyxDQUE1QyxDQUFYO0FBQ0Q7O0FBRURvQixRQUFBQSxNQUFNLEdBQUd4QixJQUFJLENBQUN5QixhQUFMLENBQW1CUSxRQUFuQixFQUE2QnBDLFNBQTdCLEVBQXdDRCxTQUF4QyxFQUFtRG1DLFlBQW5ELENBQVQ7O0FBRUEsWUFBSUUsUUFBUSxDQUFDWCxNQUFULEdBQWtCLENBQWxCLElBQXVCWixNQUF2QixJQUFpQ2MsTUFBTSxHQUFHLENBQVQsSUFBY2hCLE1BQW5ELEVBQTJEO0FBQ3pEO0FBQ0EsaUJBQU9QLElBQUksQ0FBQ3VDLFdBQVcsQ0FBQ3hDLElBQUQsRUFBT2lDLFFBQVEsQ0FBQ1YsYUFBaEIsRUFBK0IxQixTQUEvQixFQUEwQ0QsU0FBMUMsRUFBcURJLElBQUksQ0FBQ3lDLGVBQTFELENBQVosQ0FBWDtBQUNELFNBSEQsTUFHTztBQUNMcEIsVUFBQUEsUUFBUSxDQUFDVSxZQUFELENBQVIsR0FBeUJFLFFBQXpCOztBQUNBLGNBQUlBLFFBQVEsQ0FBQ1gsTUFBVCxHQUFrQixDQUFsQixJQUF1QlosTUFBM0IsRUFBbUM7QUFDakNtQixZQUFBQSxxQkFBcUIsR0FBR2hCLElBQUksQ0FBQ0MsR0FBTCxDQUFTZSxxQkFBVCxFQUFnQ0UsWUFBWSxHQUFHLENBQS9DLENBQXhCO0FBQ0Q7O0FBQ0QsY0FBSVAsTUFBTSxHQUFHLENBQVQsSUFBY2hCLE1BQWxCLEVBQTBCO0FBQ3hCb0IsWUFBQUEscUJBQXFCLEdBQUdmLElBQUksQ0FBQ21CLEdBQUwsQ0FBU0oscUJBQVQsRUFBZ0NHLFlBQVksR0FBRyxDQUEvQyxDQUF4QjtBQUNEO0FBQ0Y7QUFDRjs7QUFFRHBCLE1BQUFBLFVBQVU7QUFDWCxLQXhIc0MsQ0EwSHZDO0FBQ0E7QUFDQTtBQUNBOzs7QUFDQSxRQUFJWixRQUFKLEVBQWM7QUFDWCxnQkFBUzJDLElBQVQsR0FBZ0I7QUFDZnZDLFFBQUFBLFVBQVUsQ0FBQyxZQUFXO0FBQ3BCLGNBQUlRLFVBQVUsR0FBR0MsYUFBYixJQUE4Qk8sSUFBSSxDQUFDQyxHQUFMLEtBQWFGLG1CQUEvQyxFQUFvRTtBQUNsRSxtQkFBT25CLFFBQVEsRUFBZjtBQUNEOztBQUVELGNBQUksQ0FBQytCLGNBQWMsRUFBbkIsRUFBdUI7QUFDckJZLFlBQUFBLElBQUk7QUFDTDtBQUNGLFNBUlMsRUFRUCxDQVJPLENBQVY7QUFTRCxPQVZBLEdBQUQ7QUFXRCxLQVpELE1BWU87QUFDTCxhQUFPL0IsVUFBVSxJQUFJQyxhQUFkLElBQStCTyxJQUFJLENBQUNDLEdBQUwsTUFBY0YsbUJBQXBELEVBQXlFO0FBQ3ZFLFlBQUl5QixHQUFHLEdBQUdiLGNBQWMsRUFBeEI7O0FBQ0EsWUFBSWEsR0FBSixFQUFTO0FBQ1AsaUJBQU9BLEdBQVA7QUFDRDtBQUNGO0FBQ0Y7QUFDRixHQW5KYzs7QUFBQTs7QUFBQTtBQXFKZkosRUFBQUEsU0FySmUscUJBcUpMSyxJQXJKSyxFQXFKQ0MsS0FySkQsRUFxSlFDLE9BckpSLEVBcUppQkMsU0FySmpCLEVBcUo0QjtBQUN6QyxRQUFJQyxJQUFJLEdBQUdKLElBQUksQ0FBQ3JCLGFBQWhCOztBQUNBLFFBQUl5QixJQUFJLElBQUlBLElBQUksQ0FBQ0gsS0FBTCxLQUFlQSxLQUF2QixJQUFnQ0csSUFBSSxDQUFDRixPQUFMLEtBQWlCQSxPQUFyRCxFQUE4RDtBQUM1RCxhQUFPO0FBQ0x4QixRQUFBQSxNQUFNLEVBQUVzQixJQUFJLENBQUN0QixNQUFMLEdBQWN5QixTQURqQjtBQUVMeEIsUUFBQUEsYUFBYSxFQUFFO0FBQUNJLFVBQUFBLEtBQUssRUFBRXFCLElBQUksQ0FBQ3JCLEtBQUwsR0FBYSxDQUFyQjtBQUF3QmtCLFVBQUFBLEtBQUssRUFBRUEsS0FBL0I7QUFBc0NDLFVBQUFBLE9BQU8sRUFBRUEsT0FBL0M7QUFBd0RHLFVBQUFBLGlCQUFpQixFQUFFRCxJQUFJLENBQUNDO0FBQWhGO0FBRlYsT0FBUDtBQUlELEtBTEQsTUFLTztBQUNMLGFBQU87QUFDTDNCLFFBQUFBLE1BQU0sRUFBRXNCLElBQUksQ0FBQ3RCLE1BQUwsR0FBY3lCLFNBRGpCO0FBRUx4QixRQUFBQSxhQUFhLEVBQUU7QUFBQ0ksVUFBQUEsS0FBSyxFQUFFLENBQVI7QUFBV2tCLFVBQUFBLEtBQUssRUFBRUEsS0FBbEI7QUFBeUJDLFVBQUFBLE9BQU8sRUFBRUEsT0FBbEM7QUFBMkNHLFVBQUFBLGlCQUFpQixFQUFFRDtBQUE5RDtBQUZWLE9BQVA7QUFJRDtBQUNGLEdBbEtjOztBQUFBOztBQUFBO0FBbUtmdkIsRUFBQUEsYUFuS2UseUJBbUtEUSxRQW5LQyxFQW1LU3BDLFNBbktULEVBbUtvQkQsU0FuS3BCLEVBbUsrQm1DLFlBbksvQixFQW1LNkM7QUFDMUQsUUFBSXZCLE1BQU0sR0FBR1gsU0FBUyxDQUFDWSxNQUF2QjtBQUFBLFFBQ0lDLE1BQU0sR0FBR2QsU0FBUyxDQUFDYSxNQUR2QjtBQUFBLFFBRUlhLE1BQU0sR0FBR1csUUFBUSxDQUFDWCxNQUZ0QjtBQUFBLFFBR0lFLE1BQU0sR0FBR0YsTUFBTSxHQUFHUyxZQUh0QjtBQUFBLFFBS0ltQixXQUFXLEdBQUcsQ0FMbEI7O0FBTUEsV0FBTzFCLE1BQU0sR0FBRyxDQUFULEdBQWFoQixNQUFiLElBQXVCYyxNQUFNLEdBQUcsQ0FBVCxHQUFhWixNQUFwQyxJQUE4QyxLQUFLeUMsTUFBTCxDQUFZdEQsU0FBUyxDQUFDMkIsTUFBTSxHQUFHLENBQVYsQ0FBckIsRUFBbUM1QixTQUFTLENBQUMwQixNQUFNLEdBQUcsQ0FBVixDQUE1QyxDQUFyRCxFQUFnSDtBQUM5R0UsTUFBQUEsTUFBTTtBQUNORixNQUFBQSxNQUFNO0FBQ040QixNQUFBQSxXQUFXO0FBQ1o7O0FBRUQsUUFBSUEsV0FBSixFQUFpQjtBQUNmakIsTUFBQUEsUUFBUSxDQUFDVixhQUFULEdBQXlCO0FBQUNJLFFBQUFBLEtBQUssRUFBRXVCLFdBQVI7QUFBcUJELFFBQUFBLGlCQUFpQixFQUFFaEIsUUFBUSxDQUFDVjtBQUFqRCxPQUF6QjtBQUNEOztBQUVEVSxJQUFBQSxRQUFRLENBQUNYLE1BQVQsR0FBa0JBLE1BQWxCO0FBQ0EsV0FBT0UsTUFBUDtBQUNELEdBdExjOztBQUFBOztBQUFBO0FBd0xmMkIsRUFBQUEsTUF4TGUsa0JBd0xSQyxJQXhMUSxFQXdMRkMsS0F4TEUsRUF3TEs7QUFDbEIsUUFBSSxLQUFLdkQsT0FBTCxDQUFhd0QsVUFBakIsRUFBNkI7QUFDM0IsYUFBTyxLQUFLeEQsT0FBTCxDQUFhd0QsVUFBYixDQUF3QkYsSUFBeEIsRUFBOEJDLEtBQTlCLENBQVA7QUFDRCxLQUZELE1BRU87QUFDTCxhQUFPRCxJQUFJLEtBQUtDLEtBQVQsSUFDRCxLQUFLdkQsT0FBTCxDQUFheUQsVUFBYixJQUEyQkgsSUFBSSxDQUFDSSxXQUFMLE9BQXVCSCxLQUFLLENBQUNHLFdBQU4sRUFEeEQ7QUFFRDtBQUNGLEdBL0xjOztBQUFBOztBQUFBO0FBZ01mbEQsRUFBQUEsV0FoTWUsdUJBZ01IbUQsS0FoTUcsRUFnTUk7QUFDakIsUUFBSWQsR0FBRyxHQUFHLEVBQVY7O0FBQ0EsU0FBSyxJQUFJZSxDQUFDLEdBQUcsQ0FBYixFQUFnQkEsQ0FBQyxHQUFHRCxLQUFLLENBQUNoRCxNQUExQixFQUFrQ2lELENBQUMsRUFBbkMsRUFBdUM7QUFDckMsVUFBSUQsS0FBSyxDQUFDQyxDQUFELENBQVQsRUFBYztBQUNaZixRQUFBQSxHQUFHLENBQUNnQixJQUFKLENBQVNGLEtBQUssQ0FBQ0MsQ0FBRCxDQUFkO0FBQ0Q7QUFDRjs7QUFDRCxXQUFPZixHQUFQO0FBQ0QsR0F4TWM7O0FBQUE7O0FBQUE7QUF5TWZ0QyxFQUFBQSxTQXpNZSxxQkF5TUxILEtBek1LLEVBeU1FO0FBQ2YsV0FBT0EsS0FBUDtBQUNELEdBM01jOztBQUFBOztBQUFBO0FBNE1mSyxFQUFBQSxRQTVNZSxvQkE0TU5MLEtBNU1NLEVBNE1DO0FBQ2QsV0FBT0EsS0FBSyxDQUFDMEQsS0FBTixDQUFZLEVBQVosQ0FBUDtBQUNELEdBOU1jOztBQUFBOztBQUFBO0FBK01mbEMsRUFBQUEsSUEvTWUsZ0JBK01WbUMsS0EvTVUsRUErTUg7QUFDVixXQUFPQSxLQUFLLENBQUNuQyxJQUFOLENBQVcsRUFBWCxDQUFQO0FBQ0Q7QUFqTmMsQ0FBakI7O0FBb05BLFNBQVNjLFdBQVQsQ0FBcUI3QyxJQUFyQixFQUEyQjRCLGFBQTNCLEVBQTBDMUIsU0FBMUMsRUFBcURELFNBQXJELEVBQWdFNkMsZUFBaEUsRUFBaUY7QUFDL0U7QUFDQTtBQUNBLE1BQU1xQixVQUFVLEdBQUcsRUFBbkI7QUFDQSxNQUFJQyxhQUFKOztBQUNBLFNBQU94QyxhQUFQLEVBQXNCO0FBQ3BCdUMsSUFBQUEsVUFBVSxDQUFDSCxJQUFYLENBQWdCcEMsYUFBaEI7QUFDQXdDLElBQUFBLGFBQWEsR0FBR3hDLGFBQWEsQ0FBQzBCLGlCQUE5QjtBQUNBLFdBQU8xQixhQUFhLENBQUMwQixpQkFBckI7QUFDQTFCLElBQUFBLGFBQWEsR0FBR3dDLGFBQWhCO0FBQ0Q7O0FBQ0RELEVBQUFBLFVBQVUsQ0FBQ0UsT0FBWDtBQUVBLE1BQUlDLFlBQVksR0FBRyxDQUFuQjtBQUFBLE1BQ0lDLFlBQVksR0FBR0osVUFBVSxDQUFDckQsTUFEOUI7QUFBQSxNQUVJZSxNQUFNLEdBQUcsQ0FGYjtBQUFBLE1BR0lGLE1BQU0sR0FBRyxDQUhiOztBQUtBLFNBQU8yQyxZQUFZLEdBQUdDLFlBQXRCLEVBQW9DRCxZQUFZLEVBQWhELEVBQW9EO0FBQ2xELFFBQUlFLFNBQVMsR0FBR0wsVUFBVSxDQUFDRyxZQUFELENBQTFCOztBQUNBLFFBQUksQ0FBQ0UsU0FBUyxDQUFDckIsT0FBZixFQUF3QjtBQUN0QixVQUFJLENBQUNxQixTQUFTLENBQUN0QixLQUFYLElBQW9CSixlQUF4QixFQUF5QztBQUN2QyxZQUFJdkMsS0FBSyxHQUFHTCxTQUFTLENBQUN1RSxLQUFWLENBQWdCNUMsTUFBaEIsRUFBd0JBLE1BQU0sR0FBRzJDLFNBQVMsQ0FBQ3hDLEtBQTNDLENBQVo7QUFDQXpCLFFBQUFBLEtBQUssR0FBR0EsS0FBSyxDQUFDbUUsR0FBTixDQUFVLFVBQVNuRSxLQUFULEVBQWdCd0QsQ0FBaEIsRUFBbUI7QUFDbkMsY0FBSVksUUFBUSxHQUFHMUUsU0FBUyxDQUFDMEIsTUFBTSxHQUFHb0MsQ0FBVixDQUF4QjtBQUNBLGlCQUFPWSxRQUFRLENBQUM3RCxNQUFULEdBQWtCUCxLQUFLLENBQUNPLE1BQXhCLEdBQWlDNkQsUUFBakMsR0FBNENwRSxLQUFuRDtBQUNELFNBSE8sQ0FBUjtBQUtBaUUsUUFBQUEsU0FBUyxDQUFDakUsS0FBVixHQUFrQlAsSUFBSSxDQUFDK0IsSUFBTCxDQUFVeEIsS0FBVixDQUFsQjtBQUNELE9BUkQsTUFRTztBQUNMaUUsUUFBQUEsU0FBUyxDQUFDakUsS0FBVixHQUFrQlAsSUFBSSxDQUFDK0IsSUFBTCxDQUFVN0IsU0FBUyxDQUFDdUUsS0FBVixDQUFnQjVDLE1BQWhCLEVBQXdCQSxNQUFNLEdBQUcyQyxTQUFTLENBQUN4QyxLQUEzQyxDQUFWLENBQWxCO0FBQ0Q7O0FBQ0RILE1BQUFBLE1BQU0sSUFBSTJDLFNBQVMsQ0FBQ3hDLEtBQXBCLENBWnNCLENBY3RCOztBQUNBLFVBQUksQ0FBQ3dDLFNBQVMsQ0FBQ3RCLEtBQWYsRUFBc0I7QUFDcEJ2QixRQUFBQSxNQUFNLElBQUk2QyxTQUFTLENBQUN4QyxLQUFwQjtBQUNEO0FBQ0YsS0FsQkQsTUFrQk87QUFDTHdDLE1BQUFBLFNBQVMsQ0FBQ2pFLEtBQVYsR0FBa0JQLElBQUksQ0FBQytCLElBQUwsQ0FBVTlCLFNBQVMsQ0FBQ3dFLEtBQVYsQ0FBZ0I5QyxNQUFoQixFQUF3QkEsTUFBTSxHQUFHNkMsU0FBUyxDQUFDeEMsS0FBM0MsQ0FBVixDQUFsQjtBQUNBTCxNQUFBQSxNQUFNLElBQUk2QyxTQUFTLENBQUN4QyxLQUFwQixDQUZLLENBSUw7QUFDQTtBQUNBOztBQUNBLFVBQUlzQyxZQUFZLElBQUlILFVBQVUsQ0FBQ0csWUFBWSxHQUFHLENBQWhCLENBQVYsQ0FBNkJwQixLQUFqRCxFQUF3RDtBQUN0RCxZQUFJMEIsR0FBRyxHQUFHVCxVQUFVLENBQUNHLFlBQVksR0FBRyxDQUFoQixDQUFwQjtBQUNBSCxRQUFBQSxVQUFVLENBQUNHLFlBQVksR0FBRyxDQUFoQixDQUFWLEdBQStCSCxVQUFVLENBQUNHLFlBQUQsQ0FBekM7QUFDQUgsUUFBQUEsVUFBVSxDQUFDRyxZQUFELENBQVYsR0FBMkJNLEdBQTNCO0FBQ0Q7QUFDRjtBQUNGLEdBbkQ4RSxDQXFEL0U7QUFDQTtBQUNBOzs7QUFDQSxNQUFJQyxjQUFjLEdBQUdWLFVBQVUsQ0FBQ0ksWUFBWSxHQUFHLENBQWhCLENBQS9COztBQUNBLE1BQUlBLFlBQVksR0FBRyxDQUFmLElBQ0csT0FBT00sY0FBYyxDQUFDdEUsS0FBdEIsS0FBZ0MsUUFEbkMsS0FFSXNFLGNBQWMsQ0FBQzNCLEtBQWYsSUFBd0IyQixjQUFjLENBQUMxQixPQUYzQyxLQUdHbkQsSUFBSSxDQUFDd0QsTUFBTCxDQUFZLEVBQVosRUFBZ0JxQixjQUFjLENBQUN0RSxLQUEvQixDQUhQLEVBRzhDO0FBQzVDNEQsSUFBQUEsVUFBVSxDQUFDSSxZQUFZLEdBQUcsQ0FBaEIsQ0FBVixDQUE2QmhFLEtBQTdCLElBQXNDc0UsY0FBYyxDQUFDdEUsS0FBckQ7QUFDQTRELElBQUFBLFVBQVUsQ0FBQ1csR0FBWDtBQUNEOztBQUVELFNBQU9YLFVBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBkZWZhdWx0IGZ1bmN0aW9uIERpZmYoKSB7fVxuXG5EaWZmLnByb3RvdHlwZSA9IHtcbiAgZGlmZihvbGRTdHJpbmcsIG5ld1N0cmluZywgb3B0aW9ucyA9IHt9KSB7XG4gICAgbGV0IGNhbGxiYWNrID0gb3B0aW9ucy5jYWxsYmFjaztcbiAgICBpZiAodHlwZW9mIG9wdGlvbnMgPT09ICdmdW5jdGlvbicpIHtcbiAgICAgIGNhbGxiYWNrID0gb3B0aW9ucztcbiAgICAgIG9wdGlvbnMgPSB7fTtcbiAgICB9XG4gICAgdGhpcy5vcHRpb25zID0gb3B0aW9ucztcblxuICAgIGxldCBzZWxmID0gdGhpcztcblxuICAgIGZ1bmN0aW9uIGRvbmUodmFsdWUpIHtcbiAgICAgIGlmIChjYWxsYmFjaykge1xuICAgICAgICBzZXRUaW1lb3V0KGZ1bmN0aW9uKCkgeyBjYWxsYmFjayh1bmRlZmluZWQsIHZhbHVlKTsgfSwgMCk7XG4gICAgICAgIHJldHVybiB0cnVlO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgcmV0dXJuIHZhbHVlO1xuICAgICAgfVxuICAgIH1cblxuICAgIC8vIEFsbG93IHN1YmNsYXNzZXMgdG8gbWFzc2FnZSB0aGUgaW5wdXQgcHJpb3IgdG8gcnVubmluZ1xuICAgIG9sZFN0cmluZyA9IHRoaXMuY2FzdElucHV0KG9sZFN0cmluZyk7XG4gICAgbmV3U3RyaW5nID0gdGhpcy5jYXN0SW5wdXQobmV3U3RyaW5nKTtcblxuICAgIG9sZFN0cmluZyA9IHRoaXMucmVtb3ZlRW1wdHkodGhpcy50b2tlbml6ZShvbGRTdHJpbmcpKTtcbiAgICBuZXdTdHJpbmcgPSB0aGlzLnJlbW92ZUVtcHR5KHRoaXMudG9rZW5pemUobmV3U3RyaW5nKSk7XG5cbiAgICBsZXQgbmV3TGVuID0gbmV3U3RyaW5nLmxlbmd0aCwgb2xkTGVuID0gb2xkU3RyaW5nLmxlbmd0aDtcbiAgICBsZXQgZWRpdExlbmd0aCA9IDE7XG4gICAgbGV0IG1heEVkaXRMZW5ndGggPSBuZXdMZW4gKyBvbGRMZW47XG4gICAgaWYob3B0aW9ucy5tYXhFZGl0TGVuZ3RoKSB7XG4gICAgICBtYXhFZGl0TGVuZ3RoID0gTWF0aC5taW4obWF4RWRpdExlbmd0aCwgb3B0aW9ucy5tYXhFZGl0TGVuZ3RoKTtcbiAgICB9XG4gICAgY29uc3QgbWF4RXhlY3V0aW9uVGltZSA9IG9wdGlvbnMudGltZW91dCA/PyBJbmZpbml0eTtcbiAgICBjb25zdCBhYm9ydEFmdGVyVGltZXN0YW1wID0gRGF0ZS5ub3coKSArIG1heEV4ZWN1dGlvblRpbWU7XG5cbiAgICBsZXQgYmVzdFBhdGggPSBbeyBvbGRQb3M6IC0xLCBsYXN0Q29tcG9uZW50OiB1bmRlZmluZWQgfV07XG5cbiAgICAvLyBTZWVkIGVkaXRMZW5ndGggPSAwLCBpLmUuIHRoZSBjb250ZW50IHN0YXJ0cyB3aXRoIHRoZSBzYW1lIHZhbHVlc1xuICAgIGxldCBuZXdQb3MgPSB0aGlzLmV4dHJhY3RDb21tb24oYmVzdFBhdGhbMF0sIG5ld1N0cmluZywgb2xkU3RyaW5nLCAwKTtcbiAgICBpZiAoYmVzdFBhdGhbMF0ub2xkUG9zICsgMSA+PSBvbGRMZW4gJiYgbmV3UG9zICsgMSA+PSBuZXdMZW4pIHtcbiAgICAgIC8vIElkZW50aXR5IHBlciB0aGUgZXF1YWxpdHkgYW5kIHRva2VuaXplclxuICAgICAgcmV0dXJuIGRvbmUoW3t2YWx1ZTogdGhpcy5qb2luKG5ld1N0cmluZyksIGNvdW50OiBuZXdTdHJpbmcubGVuZ3RofV0pO1xuICAgIH1cblxuICAgIC8vIE9uY2Ugd2UgaGl0IHRoZSByaWdodCBlZGdlIG9mIHRoZSBlZGl0IGdyYXBoIG9uIHNvbWUgZGlhZ29uYWwgaywgd2UgY2FuXG4gICAgLy8gZGVmaW5pdGVseSByZWFjaCB0aGUgZW5kIG9mIHRoZSBlZGl0IGdyYXBoIGluIG5vIG1vcmUgdGhhbiBrIGVkaXRzLCBzb1xuICAgIC8vIHRoZXJlJ3Mgbm8gcG9pbnQgaW4gY29uc2lkZXJpbmcgYW55IG1vdmVzIHRvIGRpYWdvbmFsIGsrMSBhbnkgbW9yZSAoZnJvbVxuICAgIC8vIHdoaWNoIHdlJ3JlIGd1YXJhbnRlZWQgdG8gbmVlZCBhdCBsZWFzdCBrKzEgbW9yZSBlZGl0cykuXG4gICAgLy8gU2ltaWxhcmx5LCBvbmNlIHdlJ3ZlIHJlYWNoZWQgdGhlIGJvdHRvbSBvZiB0aGUgZWRpdCBncmFwaCwgdGhlcmUncyBub1xuICAgIC8vIHBvaW50IGNvbnNpZGVyaW5nIG1vdmVzIHRvIGxvd2VyIGRpYWdvbmFscy5cbiAgICAvLyBXZSByZWNvcmQgdGhpcyBmYWN0IGJ5IHNldHRpbmcgbWluRGlhZ29uYWxUb0NvbnNpZGVyIGFuZFxuICAgIC8vIG1heERpYWdvbmFsVG9Db25zaWRlciB0byBzb21lIGZpbml0ZSB2YWx1ZSBvbmNlIHdlJ3ZlIGhpdCB0aGUgZWRnZSBvZlxuICAgIC8vIHRoZSBlZGl0IGdyYXBoLlxuICAgIC8vIFRoaXMgb3B0aW1pemF0aW9uIGlzIG5vdCBmYWl0aGZ1bCB0byB0aGUgb3JpZ2luYWwgYWxnb3JpdGhtIHByZXNlbnRlZCBpblxuICAgIC8vIE15ZXJzJ3MgcGFwZXIsIHdoaWNoIGluc3RlYWQgcG9pbnRsZXNzbHkgZXh0ZW5kcyBELXBhdGhzIG9mZiB0aGUgZW5kIG9mXG4gICAgLy8gdGhlIGVkaXQgZ3JhcGggLSBzZWUgcGFnZSA3IG9mIE15ZXJzJ3MgcGFwZXIgd2hpY2ggbm90ZXMgdGhpcyBwb2ludFxuICAgIC8vIGV4cGxpY2l0bHkgYW5kIGlsbHVzdHJhdGVzIGl0IHdpdGggYSBkaWFncmFtLiBUaGlzIGhhcyBtYWpvciBwZXJmb3JtYW5jZVxuICAgIC8vIGltcGxpY2F0aW9ucyBmb3Igc29tZSBjb21tb24gc2NlbmFyaW9zLiBGb3IgaW5zdGFuY2UsIHRvIGNvbXB1dGUgYSBkaWZmXG4gICAgLy8gd2hlcmUgdGhlIG5ldyB0ZXh0IHNpbXBseSBhcHBlbmRzIGQgY2hhcmFjdGVycyBvbiB0aGUgZW5kIG9mIHRoZVxuICAgIC8vIG9yaWdpbmFsIHRleHQgb2YgbGVuZ3RoIG4sIHRoZSB0cnVlIE15ZXJzIGFsZ29yaXRobSB3aWxsIHRha2UgTyhuK2ReMilcbiAgICAvLyB0aW1lIHdoaWxlIHRoaXMgb3B0aW1pemF0aW9uIG5lZWRzIG9ubHkgTyhuK2QpIHRpbWUuXG4gICAgbGV0IG1pbkRpYWdvbmFsVG9Db25zaWRlciA9IC1JbmZpbml0eSwgbWF4RGlhZ29uYWxUb0NvbnNpZGVyID0gSW5maW5pdHk7XG5cbiAgICAvLyBNYWluIHdvcmtlciBtZXRob2QuIGNoZWNrcyBhbGwgcGVybXV0YXRpb25zIG9mIGEgZ2l2ZW4gZWRpdCBsZW5ndGggZm9yIGFjY2VwdGFuY2UuXG4gICAgZnVuY3Rpb24gZXhlY0VkaXRMZW5ndGgoKSB7XG4gICAgICBmb3IgKFxuICAgICAgICBsZXQgZGlhZ29uYWxQYXRoID0gTWF0aC5tYXgobWluRGlhZ29uYWxUb0NvbnNpZGVyLCAtZWRpdExlbmd0aCk7XG4gICAgICAgIGRpYWdvbmFsUGF0aCA8PSBNYXRoLm1pbihtYXhEaWFnb25hbFRvQ29uc2lkZXIsIGVkaXRMZW5ndGgpO1xuICAgICAgICBkaWFnb25hbFBhdGggKz0gMlxuICAgICAgKSB7XG4gICAgICAgIGxldCBiYXNlUGF0aDtcbiAgICAgICAgbGV0IHJlbW92ZVBhdGggPSBiZXN0UGF0aFtkaWFnb25hbFBhdGggLSAxXSxcbiAgICAgICAgICAgIGFkZFBhdGggPSBiZXN0UGF0aFtkaWFnb25hbFBhdGggKyAxXTtcbiAgICAgICAgaWYgKHJlbW92ZVBhdGgpIHtcbiAgICAgICAgICAvLyBObyBvbmUgZWxzZSBpcyBnb2luZyB0byBhdHRlbXB0IHRvIHVzZSB0aGlzIHZhbHVlLCBjbGVhciBpdFxuICAgICAgICAgIGJlc3RQYXRoW2RpYWdvbmFsUGF0aCAtIDFdID0gdW5kZWZpbmVkO1xuICAgICAgICB9XG5cbiAgICAgICAgbGV0IGNhbkFkZCA9IGZhbHNlO1xuICAgICAgICBpZiAoYWRkUGF0aCkge1xuICAgICAgICAgIC8vIHdoYXQgbmV3UG9zIHdpbGwgYmUgYWZ0ZXIgd2UgZG8gYW4gaW5zZXJ0aW9uOlxuICAgICAgICAgIGNvbnN0IGFkZFBhdGhOZXdQb3MgPSBhZGRQYXRoLm9sZFBvcyAtIGRpYWdvbmFsUGF0aDtcbiAgICAgICAgICBjYW5BZGQgPSBhZGRQYXRoICYmIDAgPD0gYWRkUGF0aE5ld1BvcyAmJiBhZGRQYXRoTmV3UG9zIDwgbmV3TGVuO1xuICAgICAgICB9XG5cbiAgICAgICAgbGV0IGNhblJlbW92ZSA9IHJlbW92ZVBhdGggJiYgcmVtb3ZlUGF0aC5vbGRQb3MgKyAxIDwgb2xkTGVuO1xuICAgICAgICBpZiAoIWNhbkFkZCAmJiAhY2FuUmVtb3ZlKSB7XG4gICAgICAgICAgLy8gSWYgdGhpcyBwYXRoIGlzIGEgdGVybWluYWwgdGhlbiBwcnVuZVxuICAgICAgICAgIGJlc3RQYXRoW2RpYWdvbmFsUGF0aF0gPSB1bmRlZmluZWQ7XG4gICAgICAgICAgY29udGludWU7XG4gICAgICAgIH1cblxuICAgICAgICAvLyBTZWxlY3QgdGhlIGRpYWdvbmFsIHRoYXQgd2Ugd2FudCB0byBicmFuY2ggZnJvbS4gV2Ugc2VsZWN0IHRoZSBwcmlvclxuICAgICAgICAvLyBwYXRoIHdob3NlIHBvc2l0aW9uIGluIHRoZSBvbGQgc3RyaW5nIGlzIHRoZSBmYXJ0aGVzdCBmcm9tIHRoZSBvcmlnaW5cbiAgICAgICAgLy8gYW5kIGRvZXMgbm90IHBhc3MgdGhlIGJvdW5kcyBvZiB0aGUgZGlmZiBncmFwaFxuICAgICAgICAvLyBUT0RPOiBSZW1vdmUgdGhlIGArIDFgIGhlcmUgdG8gbWFrZSBiZWhhdmlvciBtYXRjaCBNeWVycyBhbGdvcml0aG1cbiAgICAgICAgLy8gICAgICAgYW5kIHByZWZlciB0byBvcmRlciByZW1vdmFscyBiZWZvcmUgaW5zZXJ0aW9ucy5cbiAgICAgICAgaWYgKCFjYW5SZW1vdmUgfHwgKGNhbkFkZCAmJiByZW1vdmVQYXRoLm9sZFBvcyArIDEgPCBhZGRQYXRoLm9sZFBvcykpIHtcbiAgICAgICAgICBiYXNlUGF0aCA9IHNlbGYuYWRkVG9QYXRoKGFkZFBhdGgsIHRydWUsIHVuZGVmaW5lZCwgMCk7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgYmFzZVBhdGggPSBzZWxmLmFkZFRvUGF0aChyZW1vdmVQYXRoLCB1bmRlZmluZWQsIHRydWUsIDEpO1xuICAgICAgICB9XG5cbiAgICAgICAgbmV3UG9zID0gc2VsZi5leHRyYWN0Q29tbW9uKGJhc2VQYXRoLCBuZXdTdHJpbmcsIG9sZFN0cmluZywgZGlhZ29uYWxQYXRoKTtcblxuICAgICAgICBpZiAoYmFzZVBhdGgub2xkUG9zICsgMSA+PSBvbGRMZW4gJiYgbmV3UG9zICsgMSA+PSBuZXdMZW4pIHtcbiAgICAgICAgICAvLyBJZiB3ZSBoYXZlIGhpdCB0aGUgZW5kIG9mIGJvdGggc3RyaW5ncywgdGhlbiB3ZSBhcmUgZG9uZVxuICAgICAgICAgIHJldHVybiBkb25lKGJ1aWxkVmFsdWVzKHNlbGYsIGJhc2VQYXRoLmxhc3RDb21wb25lbnQsIG5ld1N0cmluZywgb2xkU3RyaW5nLCBzZWxmLnVzZUxvbmdlc3RUb2tlbikpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIGJlc3RQYXRoW2RpYWdvbmFsUGF0aF0gPSBiYXNlUGF0aDtcbiAgICAgICAgICBpZiAoYmFzZVBhdGgub2xkUG9zICsgMSA+PSBvbGRMZW4pIHtcbiAgICAgICAgICAgIG1heERpYWdvbmFsVG9Db25zaWRlciA9IE1hdGgubWluKG1heERpYWdvbmFsVG9Db25zaWRlciwgZGlhZ29uYWxQYXRoIC0gMSk7XG4gICAgICAgICAgfVxuICAgICAgICAgIGlmIChuZXdQb3MgKyAxID49IG5ld0xlbikge1xuICAgICAgICAgICAgbWluRGlhZ29uYWxUb0NvbnNpZGVyID0gTWF0aC5tYXgobWluRGlhZ29uYWxUb0NvbnNpZGVyLCBkaWFnb25hbFBhdGggKyAxKTtcbiAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgIH1cblxuICAgICAgZWRpdExlbmd0aCsrO1xuICAgIH1cblxuICAgIC8vIFBlcmZvcm1zIHRoZSBsZW5ndGggb2YgZWRpdCBpdGVyYXRpb24uIElzIGEgYml0IGZ1Z2x5IGFzIHRoaXMgaGFzIHRvIHN1cHBvcnQgdGhlXG4gICAgLy8gc3luYyBhbmQgYXN5bmMgbW9kZSB3aGljaCBpcyBuZXZlciBmdW4uIExvb3BzIG92ZXIgZXhlY0VkaXRMZW5ndGggdW50aWwgYSB2YWx1ZVxuICAgIC8vIGlzIHByb2R1Y2VkLCBvciB1bnRpbCB0aGUgZWRpdCBsZW5ndGggZXhjZWVkcyBvcHRpb25zLm1heEVkaXRMZW5ndGggKGlmIGdpdmVuKSxcbiAgICAvLyBpbiB3aGljaCBjYXNlIGl0IHdpbGwgcmV0dXJuIHVuZGVmaW5lZC5cbiAgICBpZiAoY2FsbGJhY2spIHtcbiAgICAgIChmdW5jdGlvbiBleGVjKCkge1xuICAgICAgICBzZXRUaW1lb3V0KGZ1bmN0aW9uKCkge1xuICAgICAgICAgIGlmIChlZGl0TGVuZ3RoID4gbWF4RWRpdExlbmd0aCB8fCBEYXRlLm5vdygpID4gYWJvcnRBZnRlclRpbWVzdGFtcCkge1xuICAgICAgICAgICAgcmV0dXJuIGNhbGxiYWNrKCk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKCFleGVjRWRpdExlbmd0aCgpKSB7XG4gICAgICAgICAgICBleGVjKCk7XG4gICAgICAgICAgfVxuICAgICAgICB9LCAwKTtcbiAgICAgIH0oKSk7XG4gICAgfSBlbHNlIHtcbiAgICAgIHdoaWxlIChlZGl0TGVuZ3RoIDw9IG1heEVkaXRMZW5ndGggJiYgRGF0ZS5ub3coKSA8PSBhYm9ydEFmdGVyVGltZXN0YW1wKSB7XG4gICAgICAgIGxldCByZXQgPSBleGVjRWRpdExlbmd0aCgpO1xuICAgICAgICBpZiAocmV0KSB7XG4gICAgICAgICAgcmV0dXJuIHJldDtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cbiAgfSxcblxuICBhZGRUb1BhdGgocGF0aCwgYWRkZWQsIHJlbW92ZWQsIG9sZFBvc0luYykge1xuICAgIGxldCBsYXN0ID0gcGF0aC5sYXN0Q29tcG9uZW50O1xuICAgIGlmIChsYXN0ICYmIGxhc3QuYWRkZWQgPT09IGFkZGVkICYmIGxhc3QucmVtb3ZlZCA9PT0gcmVtb3ZlZCkge1xuICAgICAgcmV0dXJuIHtcbiAgICAgICAgb2xkUG9zOiBwYXRoLm9sZFBvcyArIG9sZFBvc0luYyxcbiAgICAgICAgbGFzdENvbXBvbmVudDoge2NvdW50OiBsYXN0LmNvdW50ICsgMSwgYWRkZWQ6IGFkZGVkLCByZW1vdmVkOiByZW1vdmVkLCBwcmV2aW91c0NvbXBvbmVudDogbGFzdC5wcmV2aW91c0NvbXBvbmVudCB9XG4gICAgICB9O1xuICAgIH0gZWxzZSB7XG4gICAgICByZXR1cm4ge1xuICAgICAgICBvbGRQb3M6IHBhdGgub2xkUG9zICsgb2xkUG9zSW5jLFxuICAgICAgICBsYXN0Q29tcG9uZW50OiB7Y291bnQ6IDEsIGFkZGVkOiBhZGRlZCwgcmVtb3ZlZDogcmVtb3ZlZCwgcHJldmlvdXNDb21wb25lbnQ6IGxhc3QgfVxuICAgICAgfTtcbiAgICB9XG4gIH0sXG4gIGV4dHJhY3RDb21tb24oYmFzZVBhdGgsIG5ld1N0cmluZywgb2xkU3RyaW5nLCBkaWFnb25hbFBhdGgpIHtcbiAgICBsZXQgbmV3TGVuID0gbmV3U3RyaW5nLmxlbmd0aCxcbiAgICAgICAgb2xkTGVuID0gb2xkU3RyaW5nLmxlbmd0aCxcbiAgICAgICAgb2xkUG9zID0gYmFzZVBhdGgub2xkUG9zLFxuICAgICAgICBuZXdQb3MgPSBvbGRQb3MgLSBkaWFnb25hbFBhdGgsXG5cbiAgICAgICAgY29tbW9uQ291bnQgPSAwO1xuICAgIHdoaWxlIChuZXdQb3MgKyAxIDwgbmV3TGVuICYmIG9sZFBvcyArIDEgPCBvbGRMZW4gJiYgdGhpcy5lcXVhbHMobmV3U3RyaW5nW25ld1BvcyArIDFdLCBvbGRTdHJpbmdbb2xkUG9zICsgMV0pKSB7XG4gICAgICBuZXdQb3MrKztcbiAgICAgIG9sZFBvcysrO1xuICAgICAgY29tbW9uQ291bnQrKztcbiAgICB9XG5cbiAgICBpZiAoY29tbW9uQ291bnQpIHtcbiAgICAgIGJhc2VQYXRoLmxhc3RDb21wb25lbnQgPSB7Y291bnQ6IGNvbW1vbkNvdW50LCBwcmV2aW91c0NvbXBvbmVudDogYmFzZVBhdGgubGFzdENvbXBvbmVudH07XG4gICAgfVxuXG4gICAgYmFzZVBhdGgub2xkUG9zID0gb2xkUG9zO1xuICAgIHJldHVybiBuZXdQb3M7XG4gIH0sXG5cbiAgZXF1YWxzKGxlZnQsIHJpZ2h0KSB7XG4gICAgaWYgKHRoaXMub3B0aW9ucy5jb21wYXJhdG9yKSB7XG4gICAgICByZXR1cm4gdGhpcy5vcHRpb25zLmNvbXBhcmF0b3IobGVmdCwgcmlnaHQpO1xuICAgIH0gZWxzZSB7XG4gICAgICByZXR1cm4gbGVmdCA9PT0gcmlnaHRcbiAgICAgICAgfHwgKHRoaXMub3B0aW9ucy5pZ25vcmVDYXNlICYmIGxlZnQudG9Mb3dlckNhc2UoKSA9PT0gcmlnaHQudG9Mb3dlckNhc2UoKSk7XG4gICAgfVxuICB9LFxuICByZW1vdmVFbXB0eShhcnJheSkge1xuICAgIGxldCByZXQgPSBbXTtcbiAgICBmb3IgKGxldCBpID0gMDsgaSA8IGFycmF5Lmxlbmd0aDsgaSsrKSB7XG4gICAgICBpZiAoYXJyYXlbaV0pIHtcbiAgICAgICAgcmV0LnB1c2goYXJyYXlbaV0pO1xuICAgICAgfVxuICAgIH1cbiAgICByZXR1cm4gcmV0O1xuICB9LFxuICBjYXN0SW5wdXQodmFsdWUpIHtcbiAgICByZXR1cm4gdmFsdWU7XG4gIH0sXG4gIHRva2VuaXplKHZhbHVlKSB7XG4gICAgcmV0dXJuIHZhbHVlLnNwbGl0KCcnKTtcbiAgfSxcbiAgam9pbihjaGFycykge1xuICAgIHJldHVybiBjaGFycy5qb2luKCcnKTtcbiAgfVxufTtcblxuZnVuY3Rpb24gYnVpbGRWYWx1ZXMoZGlmZiwgbGFzdENvbXBvbmVudCwgbmV3U3RyaW5nLCBvbGRTdHJpbmcsIHVzZUxvbmdlc3RUb2tlbikge1xuICAvLyBGaXJzdCB3ZSBjb252ZXJ0IG91ciBsaW5rZWQgbGlzdCBvZiBjb21wb25lbnRzIGluIHJldmVyc2Ugb3JkZXIgdG8gYW5cbiAgLy8gYXJyYXkgaW4gdGhlIHJpZ2h0IG9yZGVyOlxuICBjb25zdCBjb21wb25lbnRzID0gW107XG4gIGxldCBuZXh0Q29tcG9uZW50O1xuICB3aGlsZSAobGFzdENvbXBvbmVudCkge1xuICAgIGNvbXBvbmVudHMucHVzaChsYXN0Q29tcG9uZW50KTtcbiAgICBuZXh0Q29tcG9uZW50ID0gbGFzdENvbXBvbmVudC5wcmV2aW91c0NvbXBvbmVudDtcbiAgICBkZWxldGUgbGFzdENvbXBvbmVudC5wcmV2aW91c0NvbXBvbmVudDtcbiAgICBsYXN0Q29tcG9uZW50ID0gbmV4dENvbXBvbmVudDtcbiAgfVxuICBjb21wb25lbnRzLnJldmVyc2UoKTtcblxuICBsZXQgY29tcG9uZW50UG9zID0gMCxcbiAgICAgIGNvbXBvbmVudExlbiA9IGNvbXBvbmVudHMubGVuZ3RoLFxuICAgICAgbmV3UG9zID0gMCxcbiAgICAgIG9sZFBvcyA9IDA7XG5cbiAgZm9yICg7IGNvbXBvbmVudFBvcyA8IGNvbXBvbmVudExlbjsgY29tcG9uZW50UG9zKyspIHtcbiAgICBsZXQgY29tcG9uZW50ID0gY29tcG9uZW50c1tjb21wb25lbnRQb3NdO1xuICAgIGlmICghY29tcG9uZW50LnJlbW92ZWQpIHtcbiAgICAgIGlmICghY29tcG9uZW50LmFkZGVkICYmIHVzZUxvbmdlc3RUb2tlbikge1xuICAgICAgICBsZXQgdmFsdWUgPSBuZXdTdHJpbmcuc2xpY2UobmV3UG9zLCBuZXdQb3MgKyBjb21wb25lbnQuY291bnQpO1xuICAgICAgICB2YWx1ZSA9IHZhbHVlLm1hcChmdW5jdGlvbih2YWx1ZSwgaSkge1xuICAgICAgICAgIGxldCBvbGRWYWx1ZSA9IG9sZFN0cmluZ1tvbGRQb3MgKyBpXTtcbiAgICAgICAgICByZXR1cm4gb2xkVmFsdWUubGVuZ3RoID4gdmFsdWUubGVuZ3RoID8gb2xkVmFsdWUgOiB2YWx1ZTtcbiAgICAgICAgfSk7XG5cbiAgICAgICAgY29tcG9uZW50LnZhbHVlID0gZGlmZi5qb2luKHZhbHVlKTtcbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIGNvbXBvbmVudC52YWx1ZSA9IGRpZmYuam9pbihuZXdTdHJpbmcuc2xpY2UobmV3UG9zLCBuZXdQb3MgKyBjb21wb25lbnQuY291bnQpKTtcbiAgICAgIH1cbiAgICAgIG5ld1BvcyArPSBjb21wb25lbnQuY291bnQ7XG5cbiAgICAgIC8vIENvbW1vbiBjYXNlXG4gICAgICBpZiAoIWNvbXBvbmVudC5hZGRlZCkge1xuICAgICAgICBvbGRQb3MgKz0gY29tcG9uZW50LmNvdW50O1xuICAgICAgfVxuICAgIH0gZWxzZSB7XG4gICAgICBjb21wb25lbnQudmFsdWUgPSBkaWZmLmpvaW4ob2xkU3RyaW5nLnNsaWNlKG9sZFBvcywgb2xkUG9zICsgY29tcG9uZW50LmNvdW50KSk7XG4gICAgICBvbGRQb3MgKz0gY29tcG9uZW50LmNvdW50O1xuXG4gICAgICAvLyBSZXZlcnNlIGFkZCBhbmQgcmVtb3ZlIHNvIHJlbW92ZXMgYXJlIG91dHB1dCBmaXJzdCB0byBtYXRjaCBjb21tb24gY29udmVudGlvblxuICAgICAgLy8gVGhlIGRpZmZpbmcgYWxnb3JpdGhtIGlzIHRpZWQgdG8gYWRkIHRoZW4gcmVtb3ZlIG91dHB1dCBhbmQgdGhpcyBpcyB0aGUgc2ltcGxlc3RcbiAgICAgIC8vIHJvdXRlIHRvIGdldCB0aGUgZGVzaXJlZCBvdXRwdXQgd2l0aCBtaW5pbWFsIG92ZXJoZWFkLlxuICAgICAgaWYgKGNvbXBvbmVudFBvcyAmJiBjb21wb25lbnRzW2NvbXBvbmVudFBvcyAtIDFdLmFkZGVkKSB7XG4gICAgICAgIGxldCB0bXAgPSBjb21wb25lbnRzW2NvbXBvbmVudFBvcyAtIDFdO1xuICAgICAgICBjb21wb25lbnRzW2NvbXBvbmVudFBvcyAtIDFdID0gY29tcG9uZW50c1tjb21wb25lbnRQb3NdO1xuICAgICAgICBjb21wb25lbnRzW2NvbXBvbmVudFBvc10gPSB0bXA7XG4gICAgICB9XG4gICAgfVxuICB9XG5cbiAgLy8gU3BlY2lhbCBjYXNlIGhhbmRsZSBmb3Igd2hlbiBvbmUgdGVybWluYWwgaXMgaWdub3JlZCAoaS5lLiB3aGl0ZXNwYWNlKS5cbiAgLy8gRm9yIHRoaXMgY2FzZSB3ZSBtZXJnZSB0aGUgdGVybWluYWwgaW50byB0aGUgcHJpb3Igc3RyaW5nIGFuZCBkcm9wIHRoZSBjaGFuZ2UuXG4gIC8vIFRoaXMgaXMgb25seSBhdmFpbGFibGUgZm9yIHN0cmluZyBtb2RlLlxuICBsZXQgZmluYWxDb21wb25lbnQgPSBjb21wb25lbnRzW2NvbXBvbmVudExlbiAtIDFdO1xuICBpZiAoY29tcG9uZW50TGVuID4gMVxuICAgICAgJiYgdHlwZW9mIGZpbmFsQ29tcG9uZW50LnZhbHVlID09PSAnc3RyaW5nJ1xuICAgICAgJiYgKGZpbmFsQ29tcG9uZW50LmFkZGVkIHx8IGZpbmFsQ29tcG9uZW50LnJlbW92ZWQpXG4gICAgICAmJiBkaWZmLmVxdWFscygnJywgZmluYWxDb21wb25lbnQudmFsdWUpKSB7XG4gICAgY29tcG9uZW50c1tjb21wb25lbnRMZW4gLSAyXS52YWx1ZSArPSBmaW5hbENvbXBvbmVudC52YWx1ZTtcbiAgICBjb21wb25lbnRzLnBvcCgpO1xuICB9XG5cbiAgcmV0dXJuIGNvbXBvbmVudHM7XG59XG4iXX0= diff --git a/node_modules/diff/lib/diff/character.js b/node_modules/diff/lib/diff/character.js deleted file mode 100644 index 7ddfa205e394a..0000000000000 --- a/node_modules/diff/lib/diff/character.js +++ /dev/null @@ -1,37 +0,0 @@ -/*istanbul ignore start*/ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.diffChars = diffChars; -exports.characterDiff = 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 characterDiff = new -/*istanbul ignore start*/ -_base -/*istanbul ignore end*/ -[ -/*istanbul ignore start*/ -"default" -/*istanbul ignore end*/ -](); - -/*istanbul ignore start*/ -exports.characterDiff = characterDiff; - -/*istanbul ignore end*/ -function diffChars(oldStr, newStr, options) { - return characterDiff.diff(oldStr, newStr, options); -} -//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2NoYXJhY3Rlci5qcyJdLCJuYW1lcyI6WyJjaGFyYWN0ZXJEaWZmIiwiRGlmZiIsImRpZmZDaGFycyIsIm9sZFN0ciIsIm5ld1N0ciIsIm9wdGlvbnMiLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFFTyxJQUFNQSxhQUFhLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSixFQUF0Qjs7Ozs7O0FBQ0EsU0FBU0MsU0FBVCxDQUFtQkMsTUFBbkIsRUFBMkJDLE1BQTNCLEVBQW1DQyxPQUFuQyxFQUE0QztBQUFFLFNBQU9MLGFBQWEsQ0FBQ00sSUFBZCxDQUFtQkgsTUFBbkIsRUFBMkJDLE1BQTNCLEVBQW1DQyxPQUFuQyxDQUFQO0FBQXFEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcblxuZXhwb3J0IGNvbnN0IGNoYXJhY3RlckRpZmYgPSBuZXcgRGlmZigpO1xuZXhwb3J0IGZ1bmN0aW9uIGRpZmZDaGFycyhvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykgeyByZXR1cm4gY2hhcmFjdGVyRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTsgfVxuIl19 diff --git a/node_modules/diff/lib/diff/css.js b/node_modules/diff/lib/diff/css.js deleted file mode 100644 index e3ad1fcba5f0e..0000000000000 --- a/node_modules/diff/lib/diff/css.js +++ /dev/null @@ -1,41 +0,0 @@ -/*istanbul ignore start*/ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.diffCss = diffCss; -exports.cssDiff = 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 cssDiff = new -/*istanbul ignore start*/ -_base -/*istanbul ignore end*/ -[ -/*istanbul ignore start*/ -"default" -/*istanbul ignore end*/ -](); - -/*istanbul ignore start*/ -exports.cssDiff = cssDiff; - -/*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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Nzcy5qcyJdLCJuYW1lcyI6WyJjc3NEaWZmIiwiRGlmZiIsInRva2VuaXplIiwidmFsdWUiLCJzcGxpdCIsImRpZmZDc3MiLCJvbGRTdHIiLCJuZXdTdHIiLCJjYWxsYmFjayIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBOzs7OztBQUVPLElBQU1BLE9BQU8sR0FBRztBQUFJQztBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQSxDQUFKLEVBQWhCOzs7Ozs7QUFDUEQsT0FBTyxDQUFDRSxRQUFSLEdBQW1CLFVBQVNDLEtBQVQsRUFBZ0I7QUFDakMsU0FBT0EsS0FBSyxDQUFDQyxLQUFOLENBQVksZUFBWixDQUFQO0FBQ0QsQ0FGRDs7QUFJTyxTQUFTQyxPQUFULENBQWlCQyxNQUFqQixFQUF5QkMsTUFBekIsRUFBaUNDLFFBQWpDLEVBQTJDO0FBQUUsU0FBT1IsT0FBTyxDQUFDUyxJQUFSLENBQWFILE1BQWIsRUFBcUJDLE1BQXJCLEVBQTZCQyxRQUE3QixDQUFQO0FBQWdEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcblxuZXhwb3J0IGNvbnN0IGNzc0RpZmYgPSBuZXcgRGlmZigpO1xuY3NzRGlmZi50b2tlbml6ZSA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIHJldHVybiB2YWx1ZS5zcGxpdCgvKFt7fTo7LF18XFxzKykvKTtcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmQ3NzKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjaykgeyByZXR1cm4gY3NzRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7IH1cbiJdfQ== diff --git a/node_modules/diff/lib/diff/json.js b/node_modules/diff/lib/diff/json.js deleted file mode 100644 index 67c2f175f73b4..0000000000000 --- a/node_modules/diff/lib/diff/json.js +++ /dev/null @@ -1,163 +0,0 @@ -/*istanbul ignore start*/ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.diffJson = diffJson; -exports.canonicalize = canonicalize; -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(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -/*istanbul ignore end*/ -var objectPrototypeToString = Object.prototype.toString; -var jsonDiff = 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: - -/*istanbul ignore start*/ -exports.jsonDiff = jsonDiff; - -/*istanbul ignore end*/ -jsonDiff.useLongestToken = true; -jsonDiff.tokenize = -/*istanbul ignore start*/ -_line -/*istanbul ignore end*/ -. -/*istanbul ignore start*/ -lineDiff -/*istanbul ignore end*/ -.tokenize; - -jsonDiff.castInput = function (value) { - /*istanbul ignore start*/ - var _this$options = - /*istanbul ignore end*/ - this.options, - undefinedReplacement = _this$options.undefinedReplacement, - _this$options$stringi = _this$options.stringifyReplacer, - stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) - /*istanbul ignore start*/ - { - return ( - /*istanbul ignore end*/ - typeof v === 'undefined' ? undefinedReplacement : v - ); - } : _this$options$stringi; - return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); -}; - -jsonDiff.equals = function (left, right) { - 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')) - ); -}; - -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]' === objectPrototypeToString.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 (obj.hasOwnProperty(_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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2pzb24uanMiXSwibmFtZXMiOlsib2JqZWN0UHJvdG90eXBlVG9TdHJpbmciLCJPYmplY3QiLCJwcm90b3R5cGUiLCJ0b1N0cmluZyIsImpzb25EaWZmIiwiRGlmZiIsInVzZUxvbmdlc3RUb2tlbiIsInRva2VuaXplIiwibGluZURpZmYiLCJjYXN0SW5wdXQiLCJ2YWx1ZSIsIm9wdGlvbnMiLCJ1bmRlZmluZWRSZXBsYWNlbWVudCIsInN0cmluZ2lmeVJlcGxhY2VyIiwiayIsInYiLCJKU09OIiwic3RyaW5naWZ5IiwiY2Fub25pY2FsaXplIiwiZXF1YWxzIiwibGVmdCIsInJpZ2h0IiwiY2FsbCIsInJlcGxhY2UiLCJkaWZmSnNvbiIsIm9sZE9iaiIsIm5ld09iaiIsImRpZmYiLCJvYmoiLCJzdGFjayIsInJlcGxhY2VtZW50U3RhY2siLCJyZXBsYWNlciIsImtleSIsImkiLCJsZW5ndGgiLCJjYW5vbmljYWxpemVkT2JqIiwicHVzaCIsIkFycmF5IiwicG9wIiwidG9KU09OIiwic29ydGVkS2V5cyIsImhhc093blByb3BlcnR5Iiwic29ydCJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7Ozs7Ozs7QUFFQSxJQUFNQSx1QkFBdUIsR0FBR0MsTUFBTSxDQUFDQyxTQUFQLENBQWlCQyxRQUFqRDtBQUdPLElBQU1DLFFBQVEsR0FBRztBQUFJQztBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQSxDQUFKLEVBQWpCLEMsQ0FDUDtBQUNBOzs7Ozs7QUFDQUQsUUFBUSxDQUFDRSxlQUFULEdBQTJCLElBQTNCO0FBRUFGLFFBQVEsQ0FBQ0csUUFBVDtBQUFvQkM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQTtBQUFBLENBQVNELFFBQTdCOztBQUNBSCxRQUFRLENBQUNLLFNBQVQsR0FBcUIsVUFBU0MsS0FBVCxFQUFnQjtBQUFBO0FBQUE7QUFBQTtBQUMrRSxPQUFLQyxPQURwRjtBQUFBLE1BQzVCQyxvQkFENEIsaUJBQzVCQSxvQkFENEI7QUFBQSw0Q0FDTkMsaUJBRE07QUFBQSxNQUNOQSxpQkFETSxzQ0FDYyxVQUFDQyxDQUFELEVBQUlDLENBQUo7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFVLGFBQU9BLENBQVAsS0FBYSxXQUFiLEdBQTJCSCxvQkFBM0IsR0FBa0RHO0FBQTVEO0FBQUEsR0FEZDtBQUduQyxTQUFPLE9BQU9MLEtBQVAsS0FBaUIsUUFBakIsR0FBNEJBLEtBQTVCLEdBQW9DTSxJQUFJLENBQUNDLFNBQUwsQ0FBZUMsWUFBWSxDQUFDUixLQUFELEVBQVEsSUFBUixFQUFjLElBQWQsRUFBb0JHLGlCQUFwQixDQUEzQixFQUFtRUEsaUJBQW5FLEVBQXNGLElBQXRGLENBQTNDO0FBQ0QsQ0FKRDs7QUFLQVQsUUFBUSxDQUFDZSxNQUFULEdBQWtCLFVBQVNDLElBQVQsRUFBZUMsS0FBZixFQUFzQjtBQUN0QyxTQUFPaEI7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsTUFBS0gsU0FBTCxDQUFlaUIsTUFBZixDQUFzQkcsSUFBdEIsQ0FBMkJsQixRQUEzQixFQUFxQ2dCLElBQUksQ0FBQ0csT0FBTCxDQUFhLFlBQWIsRUFBMkIsSUFBM0IsQ0FBckMsRUFBdUVGLEtBQUssQ0FBQ0UsT0FBTixDQUFjLFlBQWQsRUFBNEIsSUFBNUIsQ0FBdkU7QUFBUDtBQUNELENBRkQ7O0FBSU8sU0FBU0MsUUFBVCxDQUFrQkMsTUFBbEIsRUFBMEJDLE1BQTFCLEVBQWtDZixPQUFsQyxFQUEyQztBQUFFLFNBQU9QLFFBQVEsQ0FBQ3VCLElBQVQsQ0FBY0YsTUFBZCxFQUFzQkMsTUFBdEIsRUFBOEJmLE9BQTlCLENBQVA7QUFBZ0QsQyxDQUVwRztBQUNBOzs7QUFDTyxTQUFTTyxZQUFULENBQXNCVSxHQUF0QixFQUEyQkMsS0FBM0IsRUFBa0NDLGdCQUFsQyxFQUFvREMsUUFBcEQsRUFBOERDLEdBQTlELEVBQW1FO0FBQ3hFSCxFQUFBQSxLQUFLLEdBQUdBLEtBQUssSUFBSSxFQUFqQjtBQUNBQyxFQUFBQSxnQkFBZ0IsR0FBR0EsZ0JBQWdCLElBQUksRUFBdkM7O0FBRUEsTUFBSUMsUUFBSixFQUFjO0FBQ1pILElBQUFBLEdBQUcsR0FBR0csUUFBUSxDQUFDQyxHQUFELEVBQU1KLEdBQU4sQ0FBZDtBQUNEOztBQUVELE1BQUlLLENBQUo7O0FBRUEsT0FBS0EsQ0FBQyxHQUFHLENBQVQsRUFBWUEsQ0FBQyxHQUFHSixLQUFLLENBQUNLLE1BQXRCLEVBQThCRCxDQUFDLElBQUksQ0FBbkMsRUFBc0M7QUFDcEMsUUFBSUosS0FBSyxDQUFDSSxDQUFELENBQUwsS0FBYUwsR0FBakIsRUFBc0I7QUFDcEIsYUFBT0UsZ0JBQWdCLENBQUNHLENBQUQsQ0FBdkI7QUFDRDtBQUNGOztBQUVELE1BQUlFLGdCQUFKOztBQUVBLE1BQUkscUJBQXFCbkMsdUJBQXVCLENBQUNzQixJQUF4QixDQUE2Qk0sR0FBN0IsQ0FBekIsRUFBNEQ7QUFDMURDLElBQUFBLEtBQUssQ0FBQ08sSUFBTixDQUFXUixHQUFYO0FBQ0FPLElBQUFBLGdCQUFnQixHQUFHLElBQUlFLEtBQUosQ0FBVVQsR0FBRyxDQUFDTSxNQUFkLENBQW5CO0FBQ0FKLElBQUFBLGdCQUFnQixDQUFDTSxJQUFqQixDQUFzQkQsZ0JBQXRCOztBQUNBLFNBQUtGLENBQUMsR0FBRyxDQUFULEVBQVlBLENBQUMsR0FBR0wsR0FBRyxDQUFDTSxNQUFwQixFQUE0QkQsQ0FBQyxJQUFJLENBQWpDLEVBQW9DO0FBQ2xDRSxNQUFBQSxnQkFBZ0IsQ0FBQ0YsQ0FBRCxDQUFoQixHQUFzQmYsWUFBWSxDQUFDVSxHQUFHLENBQUNLLENBQUQsQ0FBSixFQUFTSixLQUFULEVBQWdCQyxnQkFBaEIsRUFBa0NDLFFBQWxDLEVBQTRDQyxHQUE1QyxDQUFsQztBQUNEOztBQUNESCxJQUFBQSxLQUFLLENBQUNTLEdBQU47QUFDQVIsSUFBQUEsZ0JBQWdCLENBQUNRLEdBQWpCO0FBQ0EsV0FBT0gsZ0JBQVA7QUFDRDs7QUFFRCxNQUFJUCxHQUFHLElBQUlBLEdBQUcsQ0FBQ1csTUFBZixFQUF1QjtBQUNyQlgsSUFBQUEsR0FBRyxHQUFHQSxHQUFHLENBQUNXLE1BQUosRUFBTjtBQUNEOztBQUVEO0FBQUk7QUFBQTtBQUFBO0FBQU9YLEVBQUFBLEdBQVAsTUFBZSxRQUFmLElBQTJCQSxHQUFHLEtBQUssSUFBdkMsRUFBNkM7QUFDM0NDLElBQUFBLEtBQUssQ0FBQ08sSUFBTixDQUFXUixHQUFYO0FBQ0FPLElBQUFBLGdCQUFnQixHQUFHLEVBQW5CO0FBQ0FMLElBQUFBLGdCQUFnQixDQUFDTSxJQUFqQixDQUFzQkQsZ0JBQXRCOztBQUNBLFFBQUlLLFVBQVUsR0FBRyxFQUFqQjtBQUFBLFFBQ0lSLElBREo7O0FBRUEsU0FBS0EsSUFBTCxJQUFZSixHQUFaLEVBQWlCO0FBQ2Y7QUFDQSxVQUFJQSxHQUFHLENBQUNhLGNBQUosQ0FBbUJULElBQW5CLENBQUosRUFBNkI7QUFDM0JRLFFBQUFBLFVBQVUsQ0FBQ0osSUFBWCxDQUFnQkosSUFBaEI7QUFDRDtBQUNGOztBQUNEUSxJQUFBQSxVQUFVLENBQUNFLElBQVg7O0FBQ0EsU0FBS1QsQ0FBQyxHQUFHLENBQVQsRUFBWUEsQ0FBQyxHQUFHTyxVQUFVLENBQUNOLE1BQTNCLEVBQW1DRCxDQUFDLElBQUksQ0FBeEMsRUFBMkM7QUFDekNELE1BQUFBLElBQUcsR0FBR1EsVUFBVSxDQUFDUCxDQUFELENBQWhCO0FBQ0FFLE1BQUFBLGdCQUFnQixDQUFDSCxJQUFELENBQWhCLEdBQXdCZCxZQUFZLENBQUNVLEdBQUcsQ0FBQ0ksSUFBRCxDQUFKLEVBQVdILEtBQVgsRUFBa0JDLGdCQUFsQixFQUFvQ0MsUUFBcEMsRUFBOENDLElBQTlDLENBQXBDO0FBQ0Q7O0FBQ0RILElBQUFBLEtBQUssQ0FBQ1MsR0FBTjtBQUNBUixJQUFBQSxnQkFBZ0IsQ0FBQ1EsR0FBakI7QUFDRCxHQW5CRCxNQW1CTztBQUNMSCxJQUFBQSxnQkFBZ0IsR0FBR1AsR0FBbkI7QUFDRDs7QUFDRCxTQUFPTyxnQkFBUDtBQUNEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcbmltcG9ydCB7bGluZURpZmZ9IGZyb20gJy4vbGluZSc7XG5cbmNvbnN0IG9iamVjdFByb3RvdHlwZVRvU3RyaW5nID0gT2JqZWN0LnByb3RvdHlwZS50b1N0cmluZztcblxuXG5leHBvcnQgY29uc3QganNvbkRpZmYgPSBuZXcgRGlmZigpO1xuLy8gRGlzY3JpbWluYXRlIGJldHdlZW4gdHdvIGxpbmVzIG9mIHByZXR0eS1wcmludGVkLCBzZXJpYWxpemVkIEpTT04gd2hlcmUgb25lIG9mIHRoZW0gaGFzIGFcbi8vIGRhbmdsaW5nIGNvbW1hIGFuZCB0aGUgb3RoZXIgZG9lc24ndC4gVHVybnMgb3V0IGluY2x1ZGluZyB0aGUgZGFuZ2xpbmcgY29tbWEgeWllbGRzIHRoZSBuaWNlc3Qgb3V0cHV0OlxuanNvbkRpZmYudXNlTG9uZ2VzdFRva2VuID0gdHJ1ZTtcblxuanNvbkRpZmYudG9rZW5pemUgPSBsaW5lRGlmZi50b2tlbml6ZTtcbmpzb25EaWZmLmNhc3RJbnB1dCA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIGNvbnN0IHt1bmRlZmluZWRSZXBsYWNlbWVudCwgc3RyaW5naWZ5UmVwbGFjZXIgPSAoaywgdikgPT4gdHlwZW9mIHYgPT09ICd1bmRlZmluZWQnID8gdW5kZWZpbmVkUmVwbGFjZW1lbnQgOiB2fSA9IHRoaXMub3B0aW9ucztcblxuICByZXR1cm4gdHlwZW9mIHZhbHVlID09PSAnc3RyaW5nJyA/IHZhbHVlIDogSlNPTi5zdHJpbmdpZnkoY2Fub25pY2FsaXplKHZhbHVlLCBudWxsLCBudWxsLCBzdHJpbmdpZnlSZXBsYWNlciksIHN0cmluZ2lmeVJlcGxhY2VyLCAnICAnKTtcbn07XG5qc29uRGlmZi5lcXVhbHMgPSBmdW5jdGlvbihsZWZ0LCByaWdodCkge1xuICByZXR1cm4gRGlmZi5wcm90b3R5cGUuZXF1YWxzLmNhbGwoanNvbkRpZmYsIGxlZnQucmVwbGFjZSgvLChbXFxyXFxuXSkvZywgJyQxJyksIHJpZ2h0LnJlcGxhY2UoLywoW1xcclxcbl0pL2csICckMScpKTtcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmSnNvbihvbGRPYmosIG5ld09iaiwgb3B0aW9ucykgeyByZXR1cm4ganNvbkRpZmYuZGlmZihvbGRPYmosIG5ld09iaiwgb3B0aW9ucyk7IH1cblxuLy8gVGhpcyBmdW5jdGlvbiBoYW5kbGVzIHRoZSBwcmVzZW5jZSBvZiBjaXJjdWxhciByZWZlcmVuY2VzIGJ5IGJhaWxpbmcgb3V0IHdoZW4gZW5jb3VudGVyaW5nIGFuXG4vLyBvYmplY3QgdGhhdCBpcyBhbHJlYWR5IG9uIHRoZSBcInN0YWNrXCIgb2YgaXRlbXMgYmVpbmcgcHJvY2Vzc2VkLiBBY2NlcHRzIGFuIG9wdGlvbmFsIHJlcGxhY2VyXG5leHBvcnQgZnVuY3Rpb24gY2Fub25pY2FsaXplKG9iaiwgc3RhY2ssIHJlcGxhY2VtZW50U3RhY2ssIHJlcGxhY2VyLCBrZXkpIHtcbiAgc3RhY2sgPSBzdGFjayB8fCBbXTtcbiAgcmVwbGFjZW1lbnRTdGFjayA9IHJlcGxhY2VtZW50U3RhY2sgfHwgW107XG5cbiAgaWYgKHJlcGxhY2VyKSB7XG4gICAgb2JqID0gcmVwbGFjZXIoa2V5LCBvYmopO1xuICB9XG5cbiAgbGV0IGk7XG5cbiAgZm9yIChpID0gMDsgaSA8IHN0YWNrLmxlbmd0aDsgaSArPSAxKSB7XG4gICAgaWYgKHN0YWNrW2ldID09PSBvYmopIHtcbiAgICAgIHJldHVybiByZXBsYWNlbWVudFN0YWNrW2ldO1xuICAgIH1cbiAgfVxuXG4gIGxldCBjYW5vbmljYWxpemVkT2JqO1xuXG4gIGlmICgnW29iamVjdCBBcnJheV0nID09PSBvYmplY3RQcm90b3R5cGVUb1N0cmluZy5jYWxsKG9iaikpIHtcbiAgICBzdGFjay5wdXNoKG9iaik7XG4gICAgY2Fub25pY2FsaXplZE9iaiA9IG5ldyBBcnJheShvYmoubGVuZ3RoKTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnB1c2goY2Fub25pY2FsaXplZE9iaik7XG4gICAgZm9yIChpID0gMDsgaSA8IG9iai5sZW5ndGg7IGkgKz0gMSkge1xuICAgICAgY2Fub25pY2FsaXplZE9ialtpXSA9IGNhbm9uaWNhbGl6ZShvYmpbaV0sIHN0YWNrLCByZXBsYWNlbWVudFN0YWNrLCByZXBsYWNlciwga2V5KTtcbiAgICB9XG4gICAgc3RhY2sucG9wKCk7XG4gICAgcmVwbGFjZW1lbnRTdGFjay5wb3AoKTtcbiAgICByZXR1cm4gY2Fub25pY2FsaXplZE9iajtcbiAgfVxuXG4gIGlmIChvYmogJiYgb2JqLnRvSlNPTikge1xuICAgIG9iaiA9IG9iai50b0pTT04oKTtcbiAgfVxuXG4gIGlmICh0eXBlb2Ygb2JqID09PSAnb2JqZWN0JyAmJiBvYmogIT09IG51bGwpIHtcbiAgICBzdGFjay5wdXNoKG9iaik7XG4gICAgY2Fub25pY2FsaXplZE9iaiA9IHt9O1xuICAgIHJlcGxhY2VtZW50U3RhY2sucHVzaChjYW5vbmljYWxpemVkT2JqKTtcbiAgICBsZXQgc29ydGVkS2V5cyA9IFtdLFxuICAgICAgICBrZXk7XG4gICAgZm9yIChrZXkgaW4gb2JqKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9iai5oYXNPd25Qcm9wZXJ0eShrZXkpKSB7XG4gICAgICAgIHNvcnRlZEtleXMucHVzaChrZXkpO1xuICAgICAgfVxuICAgIH1cbiAgICBzb3J0ZWRLZXlzLnNvcnQoKTtcbiAgICBmb3IgKGkgPSAwOyBpIDwgc29ydGVkS2V5cy5sZW5ndGg7IGkgKz0gMSkge1xuICAgICAga2V5ID0gc29ydGVkS2V5c1tpXTtcbiAgICAgIGNhbm9uaWNhbGl6ZWRPYmpba2V5XSA9IGNhbm9uaWNhbGl6ZShvYmpba2V5XSwgc3RhY2ssIHJlcGxhY2VtZW50U3RhY2ssIHJlcGxhY2VyLCBrZXkpO1xuICAgIH1cbiAgICBzdGFjay5wb3AoKTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnBvcCgpO1xuICB9IGVsc2Uge1xuICAgIGNhbm9uaWNhbGl6ZWRPYmogPSBvYmo7XG4gIH1cbiAgcmV0dXJuIGNhbm9uaWNhbGl6ZWRPYmo7XG59XG4iXX0= diff --git a/node_modules/diff/lib/diff/line.js b/node_modules/diff/lib/diff/line.js deleted file mode 100644 index 30bc74d2383d2..0000000000000 --- a/node_modules/diff/lib/diff/line.js +++ /dev/null @@ -1,94 +0,0 @@ -/*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 = new -/*istanbul ignore start*/ -_base -/*istanbul ignore end*/ -[ -/*istanbul ignore start*/ -"default" -/*istanbul ignore end*/ -](); - -/*istanbul ignore start*/ -exports.lineDiff = lineDiff; - -/*istanbul ignore end*/ -lineDiff.tokenize = function (value) { - if (this.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 && !this.options.newlineIsToken) { - retLines[retLines.length - 1] += line; - } else { - if (this.options.ignoreWhitespace) { - line = line.trim(); - } - - retLines.push(line); - } - } - - return retLines; -}; - -function diffLines(oldStr, newStr, callback) { - return lineDiff.diff(oldStr, newStr, callback); -} - -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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2xpbmUuanMiXSwibmFtZXMiOlsibGluZURpZmYiLCJEaWZmIiwidG9rZW5pemUiLCJ2YWx1ZSIsIm9wdGlvbnMiLCJzdHJpcFRyYWlsaW5nQ3IiLCJyZXBsYWNlIiwicmV0TGluZXMiLCJsaW5lc0FuZE5ld2xpbmVzIiwic3BsaXQiLCJsZW5ndGgiLCJwb3AiLCJpIiwibGluZSIsIm5ld2xpbmVJc1Rva2VuIiwiaWdub3JlV2hpdGVzcGFjZSIsInRyaW0iLCJwdXNoIiwiZGlmZkxpbmVzIiwib2xkU3RyIiwibmV3U3RyIiwiY2FsbGJhY2siLCJkaWZmIiwiZGlmZlRyaW1tZWRMaW5lcyIsImdlbmVyYXRlT3B0aW9ucyJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7Ozs7O0FBRU8sSUFBTUEsUUFBUSxHQUFHO0FBQUlDO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBLENBQUosRUFBakI7Ozs7OztBQUNQRCxRQUFRLENBQUNFLFFBQVQsR0FBb0IsVUFBU0MsS0FBVCxFQUFnQjtBQUNsQyxNQUFHLEtBQUtDLE9BQUwsQ0FBYUMsZUFBaEIsRUFBaUM7QUFDL0I7QUFDQUYsSUFBQUEsS0FBSyxHQUFHQSxLQUFLLENBQUNHLE9BQU4sQ0FBYyxPQUFkLEVBQXVCLElBQXZCLENBQVI7QUFDRDs7QUFFRCxNQUFJQyxRQUFRLEdBQUcsRUFBZjtBQUFBLE1BQ0lDLGdCQUFnQixHQUFHTCxLQUFLLENBQUNNLEtBQU4sQ0FBWSxXQUFaLENBRHZCLENBTmtDLENBU2xDOztBQUNBLE1BQUksQ0FBQ0QsZ0JBQWdCLENBQUNBLGdCQUFnQixDQUFDRSxNQUFqQixHQUEwQixDQUEzQixDQUFyQixFQUFvRDtBQUNsREYsSUFBQUEsZ0JBQWdCLENBQUNHLEdBQWpCO0FBQ0QsR0FaaUMsQ0FjbEM7OztBQUNBLE9BQUssSUFBSUMsQ0FBQyxHQUFHLENBQWIsRUFBZ0JBLENBQUMsR0FBR0osZ0JBQWdCLENBQUNFLE1BQXJDLEVBQTZDRSxDQUFDLEVBQTlDLEVBQWtEO0FBQ2hELFFBQUlDLElBQUksR0FBR0wsZ0JBQWdCLENBQUNJLENBQUQsQ0FBM0I7O0FBRUEsUUFBSUEsQ0FBQyxHQUFHLENBQUosSUFBUyxDQUFDLEtBQUtSLE9BQUwsQ0FBYVUsY0FBM0IsRUFBMkM7QUFDekNQLE1BQUFBLFFBQVEsQ0FBQ0EsUUFBUSxDQUFDRyxNQUFULEdBQWtCLENBQW5CLENBQVIsSUFBaUNHLElBQWpDO0FBQ0QsS0FGRCxNQUVPO0FBQ0wsVUFBSSxLQUFLVCxPQUFMLENBQWFXLGdCQUFqQixFQUFtQztBQUNqQ0YsUUFBQUEsSUFBSSxHQUFHQSxJQUFJLENBQUNHLElBQUwsRUFBUDtBQUNEOztBQUNEVCxNQUFBQSxRQUFRLENBQUNVLElBQVQsQ0FBY0osSUFBZDtBQUNEO0FBQ0Y7O0FBRUQsU0FBT04sUUFBUDtBQUNELENBN0JEOztBQStCTyxTQUFTVyxTQUFULENBQW1CQyxNQUFuQixFQUEyQkMsTUFBM0IsRUFBbUNDLFFBQW5DLEVBQTZDO0FBQUUsU0FBT3JCLFFBQVEsQ0FBQ3NCLElBQVQsQ0FBY0gsTUFBZCxFQUFzQkMsTUFBdEIsRUFBOEJDLFFBQTlCLENBQVA7QUFBaUQ7O0FBQ2hHLFNBQVNFLGdCQUFULENBQTBCSixNQUExQixFQUFrQ0MsTUFBbEMsRUFBMENDLFFBQTFDLEVBQW9EO0FBQ3pELE1BQUlqQixPQUFPO0FBQUc7QUFBQTtBQUFBOztBQUFBb0I7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQTtBQUFBLEdBQWdCSCxRQUFoQixFQUEwQjtBQUFDTixJQUFBQSxnQkFBZ0IsRUFBRTtBQUFuQixHQUExQixDQUFkO0FBQ0EsU0FBT2YsUUFBUSxDQUFDc0IsSUFBVCxDQUFjSCxNQUFkLEVBQXNCQyxNQUF0QixFQUE4QmhCLE9BQTlCLENBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5pbXBvcnQge2dlbmVyYXRlT3B0aW9uc30gZnJvbSAnLi4vdXRpbC9wYXJhbXMnO1xuXG5leHBvcnQgY29uc3QgbGluZURpZmYgPSBuZXcgRGlmZigpO1xubGluZURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICBpZih0aGlzLm9wdGlvbnMuc3RyaXBUcmFpbGluZ0NyKSB7XG4gICAgLy8gcmVtb3ZlIG9uZSBcXHIgYmVmb3JlIFxcbiB0byBtYXRjaCBHTlUgZGlmZidzIC0tc3RyaXAtdHJhaWxpbmctY3IgYmVoYXZpb3JcbiAgICB2YWx1ZSA9IHZhbHVlLnJlcGxhY2UoL1xcclxcbi9nLCAnXFxuJyk7XG4gIH1cblxuICBsZXQgcmV0TGluZXMgPSBbXSxcbiAgICAgIGxpbmVzQW5kTmV3bGluZXMgPSB2YWx1ZS5zcGxpdCgvKFxcbnxcXHJcXG4pLyk7XG5cbiAgLy8gSWdub3JlIHRoZSBmaW5hbCBlbXB0eSB0b2tlbiB0aGF0IG9jY3VycyBpZiB0aGUgc3RyaW5nIGVuZHMgd2l0aCBhIG5ldyBsaW5lXG4gIGlmICghbGluZXNBbmROZXdsaW5lc1tsaW5lc0FuZE5ld2xpbmVzLmxlbmd0aCAtIDFdKSB7XG4gICAgbGluZXNBbmROZXdsaW5lcy5wb3AoKTtcbiAgfVxuXG4gIC8vIE1lcmdlIHRoZSBjb250ZW50IGFuZCBsaW5lIHNlcGFyYXRvcnMgaW50byBzaW5nbGUgdG9rZW5zXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgbGluZXNBbmROZXdsaW5lcy5sZW5ndGg7IGkrKykge1xuICAgIGxldCBsaW5lID0gbGluZXNBbmROZXdsaW5lc1tpXTtcblxuICAgIGlmIChpICUgMiAmJiAhdGhpcy5vcHRpb25zLm5ld2xpbmVJc1Rva2VuKSB7XG4gICAgICByZXRMaW5lc1tyZXRMaW5lcy5sZW5ndGggLSAxXSArPSBsaW5lO1xuICAgIH0gZWxzZSB7XG4gICAgICBpZiAodGhpcy5vcHRpb25zLmlnbm9yZVdoaXRlc3BhY2UpIHtcbiAgICAgICAgbGluZSA9IGxpbmUudHJpbSgpO1xuICAgICAgfVxuICAgICAgcmV0TGluZXMucHVzaChsaW5lKTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gcmV0TGluZXM7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZkxpbmVzKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjaykgeyByZXR1cm4gbGluZURpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spOyB9XG5leHBvcnQgZnVuY3Rpb24gZGlmZlRyaW1tZWRMaW5lcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHtcbiAgbGV0IG9wdGlvbnMgPSBnZW5lcmF0ZU9wdGlvbnMoY2FsbGJhY2ssIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiBsaW5lRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cbiJdfQ== diff --git a/node_modules/diff/lib/diff/sentence.js b/node_modules/diff/lib/diff/sentence.js deleted file mode 100644 index 95158d6f58f9f..0000000000000 --- a/node_modules/diff/lib/diff/sentence.js +++ /dev/null @@ -1,41 +0,0 @@ -/*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 = new -/*istanbul ignore start*/ -_base -/*istanbul ignore end*/ -[ -/*istanbul ignore start*/ -"default" -/*istanbul ignore end*/ -](); - -/*istanbul ignore start*/ -exports.sentenceDiff = sentenceDiff; - -/*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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3NlbnRlbmNlLmpzIl0sIm5hbWVzIjpbInNlbnRlbmNlRGlmZiIsIkRpZmYiLCJ0b2tlbml6ZSIsInZhbHVlIiwic3BsaXQiLCJkaWZmU2VudGVuY2VzIiwib2xkU3RyIiwibmV3U3RyIiwiY2FsbGJhY2siLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFHTyxJQUFNQSxZQUFZLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSixFQUFyQjs7Ozs7O0FBQ1BELFlBQVksQ0FBQ0UsUUFBYixHQUF3QixVQUFTQyxLQUFULEVBQWdCO0FBQ3RDLFNBQU9BLEtBQUssQ0FBQ0MsS0FBTixDQUFZLHVCQUFaLENBQVA7QUFDRCxDQUZEOztBQUlPLFNBQVNDLGFBQVQsQ0FBdUJDLE1BQXZCLEVBQStCQyxNQUEvQixFQUF1Q0MsUUFBdkMsRUFBaUQ7QUFBRSxTQUFPUixZQUFZLENBQUNTLElBQWIsQ0FBa0JILE1BQWxCLEVBQTBCQyxNQUExQixFQUFrQ0MsUUFBbEMsQ0FBUDtBQUFxRCIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cblxuZXhwb3J0IGNvbnN0IHNlbnRlbmNlRGlmZiA9IG5ldyBEaWZmKCk7XG5zZW50ZW5jZURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWUuc3BsaXQoLyhcXFMuKz9bLiE/XSkoPz1cXHMrfCQpLyk7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZlNlbnRlbmNlcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHsgcmV0dXJuIHNlbnRlbmNlRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7IH1cbiJdfQ== diff --git a/node_modules/diff/lib/diff/word.js b/node_modules/diff/lib/diff/word.js deleted file mode 100644 index cef7fe17befe6..0000000000000 --- a/node_modules/diff/lib/diff/word.js +++ /dev/null @@ -1,108 +0,0 @@ -/*istanbul ignore start*/ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.diffWords = diffWords; -exports.diffWordsWithSpace = diffWordsWithSpace; -exports.wordDiff = 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*/ -// 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-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; -var reWhitespace = /\S/; -var wordDiff = new -/*istanbul ignore start*/ -_base -/*istanbul ignore end*/ -[ -/*istanbul ignore start*/ -"default" -/*istanbul ignore end*/ -](); - -/*istanbul ignore start*/ -exports.wordDiff = wordDiff; - -/*istanbul ignore end*/ -wordDiff.equals = function (left, right) { - if (this.options.ignoreCase) { - left = left.toLowerCase(); - right = right.toLowerCase(); - } - - return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); -}; - -wordDiff.tokenize = function (value) { - // All whitespace symbols except newline group into one token, each newline - in separate token - var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. - - for (var i = 0; i < tokens.length - 1; i++) { - // If we have an empty string in the next field and we have only word chars before and after, merge - if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { - tokens[i] += tokens[i + 2]; - tokens.splice(i + 1, 2); - i--; - } - } - - return tokens; -}; - -function diffWords(oldStr, newStr, options) { - options = - /*istanbul ignore start*/ - (0, - /*istanbul ignore end*/ - - /*istanbul ignore start*/ - _params - /*istanbul ignore end*/ - . - /*istanbul ignore start*/ - generateOptions) - /*istanbul ignore end*/ - (options, { - ignoreWhitespace: true - }); - return wordDiff.diff(oldStr, newStr, options); -} - -function diffWordsWithSpace(oldStr, newStr, options) { - return wordDiff.diff(oldStr, newStr, options); -} -//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3dvcmQuanMiXSwibmFtZXMiOlsiZXh0ZW5kZWRXb3JkQ2hhcnMiLCJyZVdoaXRlc3BhY2UiLCJ3b3JkRGlmZiIsIkRpZmYiLCJlcXVhbHMiLCJsZWZ0IiwicmlnaHQiLCJvcHRpb25zIiwiaWdub3JlQ2FzZSIsInRvTG93ZXJDYXNlIiwiaWdub3JlV2hpdGVzcGFjZSIsInRlc3QiLCJ0b2tlbml6ZSIsInZhbHVlIiwidG9rZW5zIiwic3BsaXQiLCJpIiwibGVuZ3RoIiwic3BsaWNlIiwiZGlmZldvcmRzIiwib2xkU3RyIiwibmV3U3RyIiwiZ2VuZXJhdGVPcHRpb25zIiwiZGlmZiIsImRpZmZXb3Jkc1dpdGhTcGFjZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7Ozs7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBTUEsaUJBQWlCLEdBQUcsK0RBQTFCO0FBRUEsSUFBTUMsWUFBWSxHQUFHLElBQXJCO0FBRU8sSUFBTUMsUUFBUSxHQUFHO0FBQUlDO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBLENBQUosRUFBakI7Ozs7OztBQUNQRCxRQUFRLENBQUNFLE1BQVQsR0FBa0IsVUFBU0MsSUFBVCxFQUFlQyxLQUFmLEVBQXNCO0FBQ3RDLE1BQUksS0FBS0MsT0FBTCxDQUFhQyxVQUFqQixFQUE2QjtBQUMzQkgsSUFBQUEsSUFBSSxHQUFHQSxJQUFJLENBQUNJLFdBQUwsRUFBUDtBQUNBSCxJQUFBQSxLQUFLLEdBQUdBLEtBQUssQ0FBQ0csV0FBTixFQUFSO0FBQ0Q7O0FBQ0QsU0FBT0osSUFBSSxLQUFLQyxLQUFULElBQW1CLEtBQUtDLE9BQUwsQ0FBYUcsZ0JBQWIsSUFBaUMsQ0FBQ1QsWUFBWSxDQUFDVSxJQUFiLENBQWtCTixJQUFsQixDQUFsQyxJQUE2RCxDQUFDSixZQUFZLENBQUNVLElBQWIsQ0FBa0JMLEtBQWxCLENBQXhGO0FBQ0QsQ0FORDs7QUFPQUosUUFBUSxDQUFDVSxRQUFULEdBQW9CLFVBQVNDLEtBQVQsRUFBZ0I7QUFDbEM7QUFDQSxNQUFJQyxNQUFNLEdBQUdELEtBQUssQ0FBQ0UsS0FBTixDQUFZLGlDQUFaLENBQWIsQ0FGa0MsQ0FJbEM7O0FBQ0EsT0FBSyxJQUFJQyxDQUFDLEdBQUcsQ0FBYixFQUFnQkEsQ0FBQyxHQUFHRixNQUFNLENBQUNHLE1BQVAsR0FBZ0IsQ0FBcEMsRUFBdUNELENBQUMsRUFBeEMsRUFBNEM7QUFDMUM7QUFDQSxRQUFJLENBQUNGLE1BQU0sQ0FBQ0UsQ0FBQyxHQUFHLENBQUwsQ0FBUCxJQUFrQkYsTUFBTSxDQUFDRSxDQUFDLEdBQUcsQ0FBTCxDQUF4QixJQUNLaEIsaUJBQWlCLENBQUNXLElBQWxCLENBQXVCRyxNQUFNLENBQUNFLENBQUQsQ0FBN0IsQ0FETCxJQUVLaEIsaUJBQWlCLENBQUNXLElBQWxCLENBQXVCRyxNQUFNLENBQUNFLENBQUMsR0FBRyxDQUFMLENBQTdCLENBRlQsRUFFZ0Q7QUFDOUNGLE1BQUFBLE1BQU0sQ0FBQ0UsQ0FBRCxDQUFOLElBQWFGLE1BQU0sQ0FBQ0UsQ0FBQyxHQUFHLENBQUwsQ0FBbkI7QUFDQUYsTUFBQUEsTUFBTSxDQUFDSSxNQUFQLENBQWNGLENBQUMsR0FBRyxDQUFsQixFQUFxQixDQUFyQjtBQUNBQSxNQUFBQSxDQUFDO0FBQ0Y7QUFDRjs7QUFFRCxTQUFPRixNQUFQO0FBQ0QsQ0FqQkQ7O0FBbUJPLFNBQVNLLFNBQVQsQ0FBbUJDLE1BQW5CLEVBQTJCQyxNQUEzQixFQUFtQ2QsT0FBbkMsRUFBNEM7QUFDakRBLEVBQUFBLE9BQU87QUFBRztBQUFBO0FBQUE7O0FBQUFlO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUE7QUFBQSxHQUFnQmYsT0FBaEIsRUFBeUI7QUFBQ0csSUFBQUEsZ0JBQWdCLEVBQUU7QUFBbkIsR0FBekIsQ0FBVjtBQUNBLFNBQU9SLFFBQVEsQ0FBQ3FCLElBQVQsQ0FBY0gsTUFBZCxFQUFzQkMsTUFBdEIsRUFBOEJkLE9BQTlCLENBQVA7QUFDRDs7QUFFTSxTQUFTaUIsa0JBQVQsQ0FBNEJKLE1BQTVCLEVBQW9DQyxNQUFwQyxFQUE0Q2QsT0FBNUMsRUFBcUQ7QUFDMUQsU0FBT0wsUUFBUSxDQUFDcUIsSUFBVCxDQUFjSCxNQUFkLEVBQXNCQyxNQUF0QixFQUE4QmQsT0FBOUIsQ0FBUDtBQUNEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcbmltcG9ydCB7Z2VuZXJhdGVPcHRpb25zfSBmcm9tICcuLi91dGlsL3BhcmFtcyc7XG5cbi8vIEJhc2VkIG9uIGh0dHBzOi8vZW4ud2lraXBlZGlhLm9yZy93aWtpL0xhdGluX3NjcmlwdF9pbl9Vbmljb2RlXG4vL1xuLy8gUmFuZ2VzIGFuZCBleGNlcHRpb25zOlxuLy8gTGF0aW4tMSBTdXBwbGVtZW50LCAwMDgw4oCTMDBGRlxuLy8gIC0gVSswMEQ3ICDDlyBNdWx0aXBsaWNhdGlvbiBzaWduXG4vLyAgLSBVKzAwRjcgIMO3IERpdmlzaW9uIHNpZ25cbi8vIExhdGluIEV4dGVuZGVkLUEsIDAxMDDigJMwMTdGXG4vLyBMYXRpbiBFeHRlbmRlZC1CLCAwMTgw4oCTMDI0RlxuLy8gSVBBIEV4dGVuc2lvbnMsIDAyNTDigJMwMkFGXG4vLyBTcGFjaW5nIE1vZGlmaWVyIExldHRlcnMsIDAyQjDigJMwMkZGXG4vLyAgLSBVKzAyQzcgIMuHICYjNzExOyAgQ2Fyb25cbi8vICAtIFUrMDJEOCAgy5ggJiM3Mjg7ICBCcmV2ZVxuLy8gIC0gVSswMkQ5ICDLmSAmIzcyOTsgIERvdCBBYm92ZVxuLy8gIC0gVSswMkRBICDLmiAmIzczMDsgIFJpbmcgQWJvdmVcbi8vICAtIFUrMDJEQiAgy5sgJiM3MzE7ICBPZ29uZWtcbi8vICAtIFUrMDJEQyAgy5wgJiM3MzI7ICBTbWFsbCBUaWxkZVxuLy8gIC0gVSswMkREICDLnSAmIzczMzsgIERvdWJsZSBBY3V0ZSBBY2NlbnRcbi8vIExhdGluIEV4dGVuZGVkIEFkZGl0aW9uYWwsIDFFMDDigJMxRUZGXG5jb25zdCBleHRlbmRlZFdvcmRDaGFycyA9IC9eW2EtekEtWlxcdXtDMH0tXFx1e0ZGfVxcdXtEOH0tXFx1e0Y2fVxcdXtGOH0tXFx1ezJDNn1cXHV7MkM4fS1cXHV7MkQ3fVxcdXsyREV9LVxcdXsyRkZ9XFx1ezFFMDB9LVxcdXsxRUZGfV0rJC91O1xuXG5jb25zdCByZVdoaXRlc3BhY2UgPSAvXFxTLztcblxuZXhwb3J0IGNvbnN0IHdvcmREaWZmID0gbmV3IERpZmYoKTtcbndvcmREaWZmLmVxdWFscyA9IGZ1bmN0aW9uKGxlZnQsIHJpZ2h0KSB7XG4gIGlmICh0aGlzLm9wdGlvbnMuaWdub3JlQ2FzZSkge1xuICAgIGxlZnQgPSBsZWZ0LnRvTG93ZXJDYXNlKCk7XG4gICAgcmlnaHQgPSByaWdodC50b0xvd2VyQ2FzZSgpO1xuICB9XG4gIHJldHVybiBsZWZ0ID09PSByaWdodCB8fCAodGhpcy5vcHRpb25zLmlnbm9yZVdoaXRlc3BhY2UgJiYgIXJlV2hpdGVzcGFjZS50ZXN0KGxlZnQpICYmICFyZVdoaXRlc3BhY2UudGVzdChyaWdodCkpO1xufTtcbndvcmREaWZmLnRva2VuaXplID0gZnVuY3Rpb24odmFsdWUpIHtcbiAgLy8gQWxsIHdoaXRlc3BhY2Ugc3ltYm9scyBleGNlcHQgbmV3bGluZSBncm91cCBpbnRvIG9uZSB0b2tlbiwgZWFjaCBuZXdsaW5lIC0gaW4gc2VwYXJhdGUgdG9rZW5cbiAgbGV0IHRva2VucyA9IHZhbHVlLnNwbGl0KC8oW15cXFNcXHJcXG5dK3xbKClbXFxde30nXCJcXHJcXG5dfFxcYikvKTtcblxuICAvLyBKb2luIHRoZSBib3VuZGFyeSBzcGxpdHMgdGhhdCB3ZSBkbyBub3QgY29uc2lkZXIgdG8gYmUgYm91bmRhcmllcy4gVGhpcyBpcyBwcmltYXJpbHkgdGhlIGV4dGVuZGVkIExhdGluIGNoYXJhY3RlciBzZXQuXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgdG9rZW5zLmxlbmd0aCAtIDE7IGkrKykge1xuICAgIC8vIElmIHdlIGhhdmUgYW4gZW1wdHkgc3RyaW5nIGluIHRoZSBuZXh0IGZpZWxkIGFuZCB3ZSBoYXZlIG9ubHkgd29yZCBjaGFycyBiZWZvcmUgYW5kIGFmdGVyLCBtZXJnZVxuICAgIGlmICghdG9rZW5zW2kgKyAxXSAmJiB0b2tlbnNbaSArIDJdXG4gICAgICAgICAgJiYgZXh0ZW5kZWRXb3JkQ2hhcnMudGVzdCh0b2tlbnNbaV0pXG4gICAgICAgICAgJiYgZXh0ZW5kZWRXb3JkQ2hhcnMudGVzdCh0b2tlbnNbaSArIDJdKSkge1xuICAgICAgdG9rZW5zW2ldICs9IHRva2Vuc1tpICsgMl07XG4gICAgICB0b2tlbnMuc3BsaWNlKGkgKyAxLCAyKTtcbiAgICAgIGktLTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gdG9rZW5zO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3JkcyhvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICBvcHRpb25zID0gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiB3b3JkRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3Jkc1dpdGhTcGFjZShvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICByZXR1cm4gd29yZERpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucyk7XG59XG4iXX0= diff --git a/node_modules/diff/lib/index.es6.js b/node_modules/diff/lib/index.es6.js deleted file mode 100644 index a0ace0182ab14..0000000000000 --- a/node_modules/diff/lib/index.es6.js +++ /dev/null @@ -1,1699 +0,0 @@ -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 = {}; - } - - this.options = options; - var self = this; - - function done(value) { - if (callback) { - setTimeout(function () { - callback(undefined, value); - }, 0); - return true; - } else { - return value; - } - } // Allow subclasses to massage the input prior to running - - - oldString = this.castInput(oldString); - newString = this.castInput(newString); - oldString = this.removeEmpty(this.tokenize(oldString)); - newString = this.removeEmpty(this.tokenize(newString)); - var newLen = newString.length, - oldLen = oldString.length; - var editLength = 1; - var maxEditLength = newLen + oldLen; - - if (options.maxEditLength) { - 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); - - if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { - // Identity per the equality and tokenizer - return done([{ - value: this.join(newString), - count: newString.length - }]); - } // 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 - // TODO: Remove the `+ 1` here to make behavior match Myers algorithm - // and prefer to order removals before insertions. - - - if (!canRemove || canAdd && removePath.oldPos + 1 < addPath.oldPos) { - basePath = self.addToPath(addPath, true, undefined, 0); - } else { - basePath = self.addToPath(removePath, undefined, true, 1); - } - - newPos = self.extractCommon(basePath, newString, oldString, diagonalPath); - - 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) { - var last = path.lastComponent; - - if (last && 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) { - var newLen = newString.length, - oldLen = oldString.length, - oldPos = basePath.oldPos, - newPos = oldPos - diagonalPath, - commonCount = 0; - - while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { - newPos++; - oldPos++; - commonCount++; - } - - if (commonCount) { - basePath.lastComponent = { - count: commonCount, - previousComponent: basePath.lastComponent - }; - } - - basePath.oldPos = oldPos; - return newPos; - }, - equals: function equals(left, right) { - if (this.options.comparator) { - return this.options.comparator(left, right); - } else { - return left === right || this.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 value.split(''); - }, - join: function join(chars) { - return chars.join(''); - } -}; - -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; // Reverse add and remove so removes are output first to match common convention - // The diffing algorithm is tied to add then remove output and this is the simplest - // route to get the desired output with minimal overhead. - - if (componentPos && components[componentPos - 1].added) { - var tmp = components[componentPos - 1]; - components[componentPos - 1] = components[componentPos]; - components[componentPos] = tmp; - } - } - } // Special case handle for when one terminal is ignored (i.e. whitespace). - // For this case we merge the terminal into the prior string and drop the change. - // This is only available for string mode. - - - var finalComponent = components[componentLen - 1]; - - if (componentLen > 1 && typeof finalComponent.value === 'string' && (finalComponent.added || finalComponent.removed) && diff.equals('', finalComponent.value)) { - components[componentLen - 2].value += finalComponent.value; - components.pop(); - } - - return components; -} - -var characterDiff = new Diff(); -function diffChars(oldStr, newStr, options) { - return characterDiff.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; -} - -// -// 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-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; -var reWhitespace = /\S/; -var wordDiff = new Diff(); - -wordDiff.equals = function (left, right) { - if (this.options.ignoreCase) { - left = left.toLowerCase(); - right = right.toLowerCase(); - } - - return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); -}; - -wordDiff.tokenize = function (value) { - // All whitespace symbols except newline group into one token, each newline - in separate token - var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. - - for (var i = 0; i < tokens.length - 1; i++) { - // If we have an empty string in the next field and we have only word chars before and after, merge - if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { - tokens[i] += tokens[i + 2]; - tokens.splice(i + 1, 2); - i--; - } - } - - return tokens; -}; - -function diffWords(oldStr, newStr, options) { - options = generateOptions(options, { - ignoreWhitespace: true - }); - return wordDiff.diff(oldStr, newStr, options); -} -function diffWordsWithSpace(oldStr, newStr, options) { - return wordDiff.diff(oldStr, newStr, options); -} - -var lineDiff = new Diff(); - -lineDiff.tokenize = function (value) { - if (this.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 && !this.options.newlineIsToken) { - retLines[retLines.length - 1] += line; - } else { - if (this.options.ignoreWhitespace) { - line = line.trim(); - } - - retLines.push(line); - } - } - - return retLines; -}; - -function diffLines(oldStr, newStr, callback) { - return lineDiff.diff(oldStr, newStr, callback); -} -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 _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -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" && Symbol.iterator in Object(iter)) 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 objectPrototypeToString = Object.prototype.toString; -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) { - var _this$options = this.options, - undefinedReplacement = _this$options.undefinedReplacement, - _this$options$stringi = _this$options.stringifyReplacer, - stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { - return typeof v === 'undefined' ? undefinedReplacement : v; - } : _this$options$stringi; - return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); -}; - -jsonDiff.equals = function (left, right) { - return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); -}; - -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]' === objectPrototypeToString.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 (obj.hasOwnProperty(_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 parsePatch(uniDiff) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), - delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], - 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:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { - break; - } else if (/^@@/.test(_line)) { - index.hunks.push(parseHunk()); - } else if (_line && options.strict) { - // Ignore unexpected content unless in strict mode - 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+(.*)$/.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: [], - linedelimiters: [] - }; // 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; i++) { - // Lines starting with '---' could be mistaken for the "remove line" operation - // But they could be the header for the next file. Therefore prune such cases out. - if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { - break; - } - - var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; - - if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { - hunk.lines.push(diffstr[i]); - hunk.linedelimiters.push(delimiters[i] || '\n'); - - if (operation === '+') { - addCount++; - } else if (operation === '-') { - removeCount++; - } else if (operation === ' ') { - addCount++; - removeCount++; - } - } else { - break; - } - } // Handle the empty block count case - - - if (!addCount && hunk.newLines === 1) { - hunk.newLines = 0; - } - - if (!removeCount && hunk.oldLines === 1) { - hunk.oldLines = 0; - } // Perform optional sanity checking - - - if (options.strict) { - 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 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 -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]; - } // Apply the diff to the input - - - var lines = source.split(/\r\n|[\n\v\f\r\x85]/), - delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], - hunks = uniDiff.hunks, - compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { - return line === patchContent; - }, - errorCount = 0, - fuzzFactor = options.fuzzFactor || 0, - minLine = 0, - offset = 0, - removeEOFNL, - addEOFNL; - /** - * Checks if the hunk exactly fits on the provided location - */ - - - function hunkFits(hunk, toPos) { - for (var j = 0; j < hunk.lines.length; j++) { - var line = hunk.lines[j], - operation = line.length > 0 ? line[0] : ' ', - content = line.length > 0 ? line.substr(1) : line; - - if (operation === ' ' || operation === '-') { - // Context sanity check - if (!compareLine(toPos + 1, lines[toPos], operation, content)) { - errorCount++; - - if (errorCount > fuzzFactor) { - return false; - } - } - - toPos++; - } - } - - return true; - } // Search best fit offsets for each hunk based on the previous ones - - - for (var i = 0; i < hunks.length; i++) { - var hunk = hunks[i], - maxLine = lines.length - hunk.oldLines, - localOffset = 0, - toPos = offset + hunk.oldStart - 1; - var iterator = distanceIterator(toPos, minLine, maxLine); - - for (; localOffset !== undefined; localOffset = iterator()) { - if (hunkFits(hunk, toPos + localOffset)) { - hunk.offset = offset += localOffset; - break; - } - } - - if (localOffset === undefined) { - return false; - } // Set lower text limit to end of the current hunk, so next ones don't try - // to fit over already patched text - - - minLine = hunk.offset + hunk.oldStart + hunk.oldLines; - } // Apply patch hunks - - - var diffOffset = 0; - - for (var _i = 0; _i < hunks.length; _i++) { - var _hunk = hunks[_i], - _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; - - diffOffset += _hunk.newLines - _hunk.oldLines; - - for (var j = 0; j < _hunk.lines.length; j++) { - var line = _hunk.lines[j], - operation = line.length > 0 ? line[0] : ' ', - content = line.length > 0 ? line.substr(1) : line, - delimiter = _hunk.linedelimiters && _hunk.linedelimiters[j] || '\n'; - - if (operation === ' ') { - _toPos++; - } else if (operation === '-') { - lines.splice(_toPos, 1); - delimiters.splice(_toPos, 1); - /* istanbul ignore else */ - } else if (operation === '+') { - lines.splice(_toPos, 0, content); - delimiters.splice(_toPos, 0, delimiter); - _toPos++; - } else if (operation === '\\') { - var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; - - if (previousOperation === '+') { - removeEOFNL = true; - } else if (previousOperation === '-') { - addEOFNL = true; - } - } - } - } // Handle EOFNL insertion/removal - - - if (removeEOFNL) { - while (!lines[lines.length - 1]) { - lines.pop(); - delimiters.pop(); - } - } else if (addEOFNL) { - lines.push(''); - delimiters.push('\n'); - } - - for (var _k = 0; _k < lines.length - 1; _k++) { - lines[_k] = lines[_k] + delimiters[_k]; - } - - return lines.join(''); -} // 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.context === 'undefined') { - options.context = 4; - } - - var diff = diffLines(oldStr, newStr, options); - - 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(i) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, '').split('\n'); - 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 - }; - - if (i >= diff.length - 2 && lines.length <= options.context) { - // EOF is inside this hunk - var oldEOFNewline = /\n$/.test(oldStr); - var newEOFNewline = /\n$/.test(newStr); - var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; - - if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { - // special case: old has no eol and no trailing context; no-nl can end up before adds - // however, if the old file is empty, do not output the no-nl line - curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); - } - - if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { - curRange.push('\\ No newline at end of file'); - } - } - - hunks.push(hunk); - oldRangeStart = 0; - newRangeStart = 0; - curRange = []; - } - } - - oldLine += lines.length; - newLine += lines.length; - } - }; - - for (var i = 0; i < diff.length; i++) { - _loop(i); - } - - 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) { - return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); -} -function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { - return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); -} - -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, - linedelimiters: hunk.linedelimiters, - 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 }; diff --git a/node_modules/diff/lib/index.js b/node_modules/diff/lib/index.js deleted file mode 100644 index 09d885e118292..0000000000000 --- a/node_modules/diff/lib/index.js +++ /dev/null @@ -1,234 +0,0 @@ -/*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, "diffChars", { - enumerable: true, - get: function get() { - return _character.diffChars; - } -}); -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, "diffLines", { - enumerable: true, - get: function get() { - return _line.diffLines; - } -}); -Object.defineProperty(exports, "diffTrimmedLines", { - enumerable: true, - get: function get() { - return _line.diffTrimmedLines; - } -}); -Object.defineProperty(exports, "diffSentences", { - enumerable: true, - get: function get() { - return _sentence.diffSentences; - } -}); -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, "canonicalize", { - enumerable: true, - get: function get() { - return _json.canonicalize; - } -}); -Object.defineProperty(exports, "diffArrays", { - enumerable: true, - get: function get() { - return _array.diffArrays; - } -}); -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, "parsePatch", { - enumerable: true, - get: function get() { - return _parse.parsePatch; - } -}); -Object.defineProperty(exports, "merge", { - enumerable: true, - get: function get() { - return _merge.merge; - } -}); -Object.defineProperty(exports, "reversePatch", { - enumerable: true, - get: function get() { - return _reverse.reversePatch; - } -}); -Object.defineProperty(exports, "structuredPatch", { - enumerable: true, - get: function get() { - return _create.structuredPatch; - } -}); -Object.defineProperty(exports, "createTwoFilesPatch", { - enumerable: true, - get: function get() { - return _create.createTwoFilesPatch; - } -}); -Object.defineProperty(exports, "createPatch", { - enumerable: true, - get: function get() { - return _create.createPatch; - } -}); -Object.defineProperty(exports, "formatPatch", { - enumerable: true, - get: function get() { - return _create.formatPatch; - } -}); -Object.defineProperty(exports, "convertChangesToDMP", { - enumerable: true, - get: function get() { - return _dmp.convertChangesToDMP; - } -}); -Object.defineProperty(exports, "convertChangesToXML", { - enumerable: true, - get: function get() { - return _xml.convertChangesToXML; - } -}); - -/*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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9pbmRleC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQWdCQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQTs7QUFDQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBRUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7QUFDQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUVBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBRUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7QUFDQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQTs7QUFDQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUVBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQSIsInNvdXJjZXNDb250ZW50IjpbIi8qIFNlZSBMSUNFTlNFIGZpbGUgZm9yIHRlcm1zIG9mIHVzZSAqL1xuXG4vKlxuICogVGV4dCBkaWZmIGltcGxlbWVudGF0aW9uLlxuICpcbiAqIFRoaXMgbGlicmFyeSBzdXBwb3J0cyB0aGUgZm9sbG93aW5nIEFQSXM6XG4gKiBEaWZmLmRpZmZDaGFyczogQ2hhcmFjdGVyIGJ5IGNoYXJhY3RlciBkaWZmXG4gKiBEaWZmLmRpZmZXb3JkczogV29yZCAoYXMgZGVmaW5lZCBieSBcXGIgcmVnZXgpIGRpZmYgd2hpY2ggaWdub3JlcyB3aGl0ZXNwYWNlXG4gKiBEaWZmLmRpZmZMaW5lczogTGluZSBiYXNlZCBkaWZmXG4gKlxuICogRGlmZi5kaWZmQ3NzOiBEaWZmIHRhcmdldGVkIGF0IENTUyBjb250ZW50XG4gKlxuICogVGhlc2UgbWV0aG9kcyBhcmUgYmFzZWQgb24gdGhlIGltcGxlbWVudGF0aW9uIHByb3Bvc2VkIGluXG4gKiBcIkFuIE8oTkQpIERpZmZlcmVuY2UgQWxnb3JpdGhtIGFuZCBpdHMgVmFyaWF0aW9uc1wiIChNeWVycywgMTk4NikuXG4gKiBodHRwOi8vY2l0ZXNlZXJ4LmlzdC5wc3UuZWR1L3ZpZXdkb2Mvc3VtbWFyeT9kb2k9MTAuMS4xLjQuNjkyN1xuICovXG5pbXBvcnQgRGlmZiBmcm9tICcuL2RpZmYvYmFzZSc7XG5pbXBvcnQge2RpZmZDaGFyc30gZnJvbSAnLi9kaWZmL2NoYXJhY3Rlcic7XG5pbXBvcnQge2RpZmZXb3JkcywgZGlmZldvcmRzV2l0aFNwYWNlfSBmcm9tICcuL2RpZmYvd29yZCc7XG5pbXBvcnQge2RpZmZMaW5lcywgZGlmZlRyaW1tZWRMaW5lc30gZnJvbSAnLi9kaWZmL2xpbmUnO1xuaW1wb3J0IHtkaWZmU2VudGVuY2VzfSBmcm9tICcuL2RpZmYvc2VudGVuY2UnO1xuXG5pbXBvcnQge2RpZmZDc3N9IGZyb20gJy4vZGlmZi9jc3MnO1xuaW1wb3J0IHtkaWZmSnNvbiwgY2Fub25pY2FsaXplfSBmcm9tICcuL2RpZmYvanNvbic7XG5cbmltcG9ydCB7ZGlmZkFycmF5c30gZnJvbSAnLi9kaWZmL2FycmF5JztcblxuaW1wb3J0IHthcHBseVBhdGNoLCBhcHBseVBhdGNoZXN9IGZyb20gJy4vcGF0Y2gvYXBwbHknO1xuaW1wb3J0IHtwYXJzZVBhdGNofSBmcm9tICcuL3BhdGNoL3BhcnNlJztcbmltcG9ydCB7bWVyZ2V9IGZyb20gJy4vcGF0Y2gvbWVyZ2UnO1xuaW1wb3J0IHtyZXZlcnNlUGF0Y2h9IGZyb20gJy4vcGF0Y2gvcmV2ZXJzZSc7XG5pbXBvcnQge3N0cnVjdHVyZWRQYXRjaCwgY3JlYXRlVHdvRmlsZXNQYXRjaCwgY3JlYXRlUGF0Y2gsIGZvcm1hdFBhdGNofSBmcm9tICcuL3BhdGNoL2NyZWF0ZSc7XG5cbmltcG9ydCB7Y29udmVydENoYW5nZXNUb0RNUH0gZnJvbSAnLi9jb252ZXJ0L2RtcCc7XG5pbXBvcnQge2NvbnZlcnRDaGFuZ2VzVG9YTUx9IGZyb20gJy4vY29udmVydC94bWwnO1xuXG5leHBvcnQge1xuICBEaWZmLFxuXG4gIGRpZmZDaGFycyxcbiAgZGlmZldvcmRzLFxuICBkaWZmV29yZHNXaXRoU3BhY2UsXG4gIGRpZmZMaW5lcyxcbiAgZGlmZlRyaW1tZWRMaW5lcyxcbiAgZGlmZlNlbnRlbmNlcyxcblxuICBkaWZmQ3NzLFxuICBkaWZmSnNvbixcblxuICBkaWZmQXJyYXlzLFxuXG4gIHN0cnVjdHVyZWRQYXRjaCxcbiAgY3JlYXRlVHdvRmlsZXNQYXRjaCxcbiAgY3JlYXRlUGF0Y2gsXG4gIGZvcm1hdFBhdGNoLFxuICBhcHBseVBhdGNoLFxuICBhcHBseVBhdGNoZXMsXG4gIHBhcnNlUGF0Y2gsXG4gIG1lcmdlLFxuICByZXZlcnNlUGF0Y2gsXG4gIGNvbnZlcnRDaGFuZ2VzVG9ETVAsXG4gIGNvbnZlcnRDaGFuZ2VzVG9YTUwsXG4gIGNhbm9uaWNhbGl6ZVxufTtcbiJdfQ== diff --git a/node_modules/diff/lib/index.mjs b/node_modules/diff/lib/index.mjs deleted file mode 100644 index a0ace0182ab14..0000000000000 --- a/node_modules/diff/lib/index.mjs +++ /dev/null @@ -1,1699 +0,0 @@ -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 = {}; - } - - this.options = options; - var self = this; - - function done(value) { - if (callback) { - setTimeout(function () { - callback(undefined, value); - }, 0); - return true; - } else { - return value; - } - } // Allow subclasses to massage the input prior to running - - - oldString = this.castInput(oldString); - newString = this.castInput(newString); - oldString = this.removeEmpty(this.tokenize(oldString)); - newString = this.removeEmpty(this.tokenize(newString)); - var newLen = newString.length, - oldLen = oldString.length; - var editLength = 1; - var maxEditLength = newLen + oldLen; - - if (options.maxEditLength) { - 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); - - if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { - // Identity per the equality and tokenizer - return done([{ - value: this.join(newString), - count: newString.length - }]); - } // 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 - // TODO: Remove the `+ 1` here to make behavior match Myers algorithm - // and prefer to order removals before insertions. - - - if (!canRemove || canAdd && removePath.oldPos + 1 < addPath.oldPos) { - basePath = self.addToPath(addPath, true, undefined, 0); - } else { - basePath = self.addToPath(removePath, undefined, true, 1); - } - - newPos = self.extractCommon(basePath, newString, oldString, diagonalPath); - - 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) { - var last = path.lastComponent; - - if (last && 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) { - var newLen = newString.length, - oldLen = oldString.length, - oldPos = basePath.oldPos, - newPos = oldPos - diagonalPath, - commonCount = 0; - - while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { - newPos++; - oldPos++; - commonCount++; - } - - if (commonCount) { - basePath.lastComponent = { - count: commonCount, - previousComponent: basePath.lastComponent - }; - } - - basePath.oldPos = oldPos; - return newPos; - }, - equals: function equals(left, right) { - if (this.options.comparator) { - return this.options.comparator(left, right); - } else { - return left === right || this.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 value.split(''); - }, - join: function join(chars) { - return chars.join(''); - } -}; - -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; // Reverse add and remove so removes are output first to match common convention - // The diffing algorithm is tied to add then remove output and this is the simplest - // route to get the desired output with minimal overhead. - - if (componentPos && components[componentPos - 1].added) { - var tmp = components[componentPos - 1]; - components[componentPos - 1] = components[componentPos]; - components[componentPos] = tmp; - } - } - } // Special case handle for when one terminal is ignored (i.e. whitespace). - // For this case we merge the terminal into the prior string and drop the change. - // This is only available for string mode. - - - var finalComponent = components[componentLen - 1]; - - if (componentLen > 1 && typeof finalComponent.value === 'string' && (finalComponent.added || finalComponent.removed) && diff.equals('', finalComponent.value)) { - components[componentLen - 2].value += finalComponent.value; - components.pop(); - } - - return components; -} - -var characterDiff = new Diff(); -function diffChars(oldStr, newStr, options) { - return characterDiff.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; -} - -// -// 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-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; -var reWhitespace = /\S/; -var wordDiff = new Diff(); - -wordDiff.equals = function (left, right) { - if (this.options.ignoreCase) { - left = left.toLowerCase(); - right = right.toLowerCase(); - } - - return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); -}; - -wordDiff.tokenize = function (value) { - // All whitespace symbols except newline group into one token, each newline - in separate token - var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. - - for (var i = 0; i < tokens.length - 1; i++) { - // If we have an empty string in the next field and we have only word chars before and after, merge - if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { - tokens[i] += tokens[i + 2]; - tokens.splice(i + 1, 2); - i--; - } - } - - return tokens; -}; - -function diffWords(oldStr, newStr, options) { - options = generateOptions(options, { - ignoreWhitespace: true - }); - return wordDiff.diff(oldStr, newStr, options); -} -function diffWordsWithSpace(oldStr, newStr, options) { - return wordDiff.diff(oldStr, newStr, options); -} - -var lineDiff = new Diff(); - -lineDiff.tokenize = function (value) { - if (this.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 && !this.options.newlineIsToken) { - retLines[retLines.length - 1] += line; - } else { - if (this.options.ignoreWhitespace) { - line = line.trim(); - } - - retLines.push(line); - } - } - - return retLines; -}; - -function diffLines(oldStr, newStr, callback) { - return lineDiff.diff(oldStr, newStr, callback); -} -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 _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -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" && Symbol.iterator in Object(iter)) 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 objectPrototypeToString = Object.prototype.toString; -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) { - var _this$options = this.options, - undefinedReplacement = _this$options.undefinedReplacement, - _this$options$stringi = _this$options.stringifyReplacer, - stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { - return typeof v === 'undefined' ? undefinedReplacement : v; - } : _this$options$stringi; - return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); -}; - -jsonDiff.equals = function (left, right) { - return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); -}; - -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]' === objectPrototypeToString.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 (obj.hasOwnProperty(_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 parsePatch(uniDiff) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), - delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], - 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:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { - break; - } else if (/^@@/.test(_line)) { - index.hunks.push(parseHunk()); - } else if (_line && options.strict) { - // Ignore unexpected content unless in strict mode - 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+(.*)$/.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: [], - linedelimiters: [] - }; // 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; i++) { - // Lines starting with '---' could be mistaken for the "remove line" operation - // But they could be the header for the next file. Therefore prune such cases out. - if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { - break; - } - - var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; - - if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { - hunk.lines.push(diffstr[i]); - hunk.linedelimiters.push(delimiters[i] || '\n'); - - if (operation === '+') { - addCount++; - } else if (operation === '-') { - removeCount++; - } else if (operation === ' ') { - addCount++; - removeCount++; - } - } else { - break; - } - } // Handle the empty block count case - - - if (!addCount && hunk.newLines === 1) { - hunk.newLines = 0; - } - - if (!removeCount && hunk.oldLines === 1) { - hunk.oldLines = 0; - } // Perform optional sanity checking - - - if (options.strict) { - 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 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 -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]; - } // Apply the diff to the input - - - var lines = source.split(/\r\n|[\n\v\f\r\x85]/), - delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], - hunks = uniDiff.hunks, - compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { - return line === patchContent; - }, - errorCount = 0, - fuzzFactor = options.fuzzFactor || 0, - minLine = 0, - offset = 0, - removeEOFNL, - addEOFNL; - /** - * Checks if the hunk exactly fits on the provided location - */ - - - function hunkFits(hunk, toPos) { - for (var j = 0; j < hunk.lines.length; j++) { - var line = hunk.lines[j], - operation = line.length > 0 ? line[0] : ' ', - content = line.length > 0 ? line.substr(1) : line; - - if (operation === ' ' || operation === '-') { - // Context sanity check - if (!compareLine(toPos + 1, lines[toPos], operation, content)) { - errorCount++; - - if (errorCount > fuzzFactor) { - return false; - } - } - - toPos++; - } - } - - return true; - } // Search best fit offsets for each hunk based on the previous ones - - - for (var i = 0; i < hunks.length; i++) { - var hunk = hunks[i], - maxLine = lines.length - hunk.oldLines, - localOffset = 0, - toPos = offset + hunk.oldStart - 1; - var iterator = distanceIterator(toPos, minLine, maxLine); - - for (; localOffset !== undefined; localOffset = iterator()) { - if (hunkFits(hunk, toPos + localOffset)) { - hunk.offset = offset += localOffset; - break; - } - } - - if (localOffset === undefined) { - return false; - } // Set lower text limit to end of the current hunk, so next ones don't try - // to fit over already patched text - - - minLine = hunk.offset + hunk.oldStart + hunk.oldLines; - } // Apply patch hunks - - - var diffOffset = 0; - - for (var _i = 0; _i < hunks.length; _i++) { - var _hunk = hunks[_i], - _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; - - diffOffset += _hunk.newLines - _hunk.oldLines; - - for (var j = 0; j < _hunk.lines.length; j++) { - var line = _hunk.lines[j], - operation = line.length > 0 ? line[0] : ' ', - content = line.length > 0 ? line.substr(1) : line, - delimiter = _hunk.linedelimiters && _hunk.linedelimiters[j] || '\n'; - - if (operation === ' ') { - _toPos++; - } else if (operation === '-') { - lines.splice(_toPos, 1); - delimiters.splice(_toPos, 1); - /* istanbul ignore else */ - } else if (operation === '+') { - lines.splice(_toPos, 0, content); - delimiters.splice(_toPos, 0, delimiter); - _toPos++; - } else if (operation === '\\') { - var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; - - if (previousOperation === '+') { - removeEOFNL = true; - } else if (previousOperation === '-') { - addEOFNL = true; - } - } - } - } // Handle EOFNL insertion/removal - - - if (removeEOFNL) { - while (!lines[lines.length - 1]) { - lines.pop(); - delimiters.pop(); - } - } else if (addEOFNL) { - lines.push(''); - delimiters.push('\n'); - } - - for (var _k = 0; _k < lines.length - 1; _k++) { - lines[_k] = lines[_k] + delimiters[_k]; - } - - return lines.join(''); -} // 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.context === 'undefined') { - options.context = 4; - } - - var diff = diffLines(oldStr, newStr, options); - - 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(i) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, '').split('\n'); - 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 - }; - - if (i >= diff.length - 2 && lines.length <= options.context) { - // EOF is inside this hunk - var oldEOFNewline = /\n$/.test(oldStr); - var newEOFNewline = /\n$/.test(newStr); - var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; - - if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { - // special case: old has no eol and no trailing context; no-nl can end up before adds - // however, if the old file is empty, do not output the no-nl line - curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); - } - - if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { - curRange.push('\\ No newline at end of file'); - } - } - - hunks.push(hunk); - oldRangeStart = 0; - newRangeStart = 0; - curRange = []; - } - } - - oldLine += lines.length; - newLine += lines.length; - } - }; - - for (var i = 0; i < diff.length; i++) { - _loop(i); - } - - 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) { - return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); -} -function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { - return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); -} - -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, - linedelimiters: hunk.linedelimiters, - 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 }; diff --git a/node_modules/diff/lib/patch/apply.js b/node_modules/diff/lib/patch/apply.js deleted file mode 100644 index cefea04dae73b..0000000000000 --- a/node_modules/diff/lib/patch/apply.js +++ /dev/null @@ -1,238 +0,0 @@ -/*istanbul ignore start*/ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.applyPatch = applyPatch; -exports.applyPatches = applyPatches; - -/*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]; - } // Apply the diff to the input - - - var lines = source.split(/\r\n|[\n\v\f\r\x85]/), - delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], - hunks = uniDiff.hunks, - compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) - /*istanbul ignore start*/ - { - return ( - /*istanbul ignore end*/ - line === patchContent - ); - }, - errorCount = 0, - fuzzFactor = options.fuzzFactor || 0, - minLine = 0, - offset = 0, - removeEOFNL, - addEOFNL; - /** - * Checks if the hunk exactly fits on the provided location - */ - - - function hunkFits(hunk, toPos) { - for (var j = 0; j < hunk.lines.length; j++) { - var line = hunk.lines[j], - operation = line.length > 0 ? line[0] : ' ', - content = line.length > 0 ? line.substr(1) : line; - - if (operation === ' ' || operation === '-') { - // Context sanity check - if (!compareLine(toPos + 1, lines[toPos], operation, content)) { - errorCount++; - - if (errorCount > fuzzFactor) { - return false; - } - } - - toPos++; - } - } - - return true; - } // Search best fit offsets for each hunk based on the previous ones - - - for (var i = 0; i < hunks.length; i++) { - var hunk = hunks[i], - maxLine = lines.length - hunk.oldLines, - localOffset = 0, - toPos = offset + hunk.oldStart - 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 (; localOffset !== undefined; localOffset = iterator()) { - if (hunkFits(hunk, toPos + localOffset)) { - hunk.offset = offset += localOffset; - break; - } - } - - if (localOffset === undefined) { - return false; - } // Set lower text limit to end of the current hunk, so next ones don't try - // to fit over already patched text - - - minLine = hunk.offset + hunk.oldStart + hunk.oldLines; - } // Apply patch hunks - - - var diffOffset = 0; - - for (var _i = 0; _i < hunks.length; _i++) { - var _hunk = hunks[_i], - _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; - - diffOffset += _hunk.newLines - _hunk.oldLines; - - for (var j = 0; j < _hunk.lines.length; j++) { - var line = _hunk.lines[j], - operation = line.length > 0 ? line[0] : ' ', - content = line.length > 0 ? line.substr(1) : line, - delimiter = _hunk.linedelimiters && _hunk.linedelimiters[j] || '\n'; - - if (operation === ' ') { - _toPos++; - } else if (operation === '-') { - lines.splice(_toPos, 1); - delimiters.splice(_toPos, 1); - /* istanbul ignore else */ - } else if (operation === '+') { - lines.splice(_toPos, 0, content); - delimiters.splice(_toPos, 0, delimiter); - _toPos++; - } else if (operation === '\\') { - var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; - - if (previousOperation === '+') { - removeEOFNL = true; - } else if (previousOperation === '-') { - addEOFNL = true; - } - } - } - } // Handle EOFNL insertion/removal - - - if (removeEOFNL) { - while (!lines[lines.length - 1]) { - lines.pop(); - delimiters.pop(); - } - } else if (addEOFNL) { - lines.push(''); - delimiters.push('\n'); - } - - for (var _k = 0; _k < lines.length - 1; _k++) { - lines[_k] = lines[_k] + delimiters[_k]; - } - - return lines.join(''); -} // 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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9hcHBseS5qcyJdLCJuYW1lcyI6WyJhcHBseVBhdGNoIiwic291cmNlIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJwYXJzZVBhdGNoIiwiQXJyYXkiLCJpc0FycmF5IiwibGVuZ3RoIiwiRXJyb3IiLCJsaW5lcyIsInNwbGl0IiwiZGVsaW1pdGVycyIsIm1hdGNoIiwiaHVua3MiLCJjb21wYXJlTGluZSIsImxpbmVOdW1iZXIiLCJsaW5lIiwib3BlcmF0aW9uIiwicGF0Y2hDb250ZW50IiwiZXJyb3JDb3VudCIsImZ1enpGYWN0b3IiLCJtaW5MaW5lIiwib2Zmc2V0IiwicmVtb3ZlRU9GTkwiLCJhZGRFT0ZOTCIsImh1bmtGaXRzIiwiaHVuayIsInRvUG9zIiwiaiIsImNvbnRlbnQiLCJzdWJzdHIiLCJpIiwibWF4TGluZSIsIm9sZExpbmVzIiwibG9jYWxPZmZzZXQiLCJvbGRTdGFydCIsIml0ZXJhdG9yIiwiZGlzdGFuY2VJdGVyYXRvciIsInVuZGVmaW5lZCIsImRpZmZPZmZzZXQiLCJuZXdMaW5lcyIsImRlbGltaXRlciIsImxpbmVkZWxpbWl0ZXJzIiwic3BsaWNlIiwicHJldmlvdXNPcGVyYXRpb24iLCJwb3AiLCJwdXNoIiwiX2siLCJqb2luIiwiYXBwbHlQYXRjaGVzIiwiY3VycmVudEluZGV4IiwicHJvY2Vzc0luZGV4IiwiaW5kZXgiLCJjb21wbGV0ZSIsImxvYWRGaWxlIiwiZXJyIiwiZGF0YSIsInVwZGF0ZWRDb250ZW50IiwicGF0Y2hlZCJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7OztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFFTyxTQUFTQSxVQUFULENBQW9CQyxNQUFwQixFQUE0QkMsT0FBNUIsRUFBbUQ7QUFBQTtBQUFBO0FBQUE7QUFBZEMsRUFBQUEsT0FBYyx1RUFBSixFQUFJOztBQUN4RCxNQUFJLE9BQU9ELE9BQVAsS0FBbUIsUUFBdkIsRUFBaUM7QUFDL0JBLElBQUFBLE9BQU87QUFBRztBQUFBO0FBQUE7O0FBQUFFO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUE7QUFBQSxLQUFXRixPQUFYLENBQVY7QUFDRDs7QUFFRCxNQUFJRyxLQUFLLENBQUNDLE9BQU4sQ0FBY0osT0FBZCxDQUFKLEVBQTRCO0FBQzFCLFFBQUlBLE9BQU8sQ0FBQ0ssTUFBUixHQUFpQixDQUFyQixFQUF3QjtBQUN0QixZQUFNLElBQUlDLEtBQUosQ0FBVSw0Q0FBVixDQUFOO0FBQ0Q7O0FBRUROLElBQUFBLE9BQU8sR0FBR0EsT0FBTyxDQUFDLENBQUQsQ0FBakI7QUFDRCxHQVh1RCxDQWF4RDs7O0FBQ0EsTUFBSU8sS0FBSyxHQUFHUixNQUFNLENBQUNTLEtBQVAsQ0FBYSxxQkFBYixDQUFaO0FBQUEsTUFDSUMsVUFBVSxHQUFHVixNQUFNLENBQUNXLEtBQVAsQ0FBYSxzQkFBYixLQUF3QyxFQUR6RDtBQUFBLE1BRUlDLEtBQUssR0FBR1gsT0FBTyxDQUFDVyxLQUZwQjtBQUFBLE1BSUlDLFdBQVcsR0FBR1gsT0FBTyxDQUFDVyxXQUFSLElBQXdCLFVBQUNDLFVBQUQsRUFBYUMsSUFBYixFQUFtQkMsU0FBbkIsRUFBOEJDLFlBQTlCO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBK0NGLE1BQUFBLElBQUksS0FBS0U7QUFBeEQ7QUFBQSxHQUoxQztBQUFBLE1BS0lDLFVBQVUsR0FBRyxDQUxqQjtBQUFBLE1BTUlDLFVBQVUsR0FBR2pCLE9BQU8sQ0FBQ2lCLFVBQVIsSUFBc0IsQ0FOdkM7QUFBQSxNQU9JQyxPQUFPLEdBQUcsQ0FQZDtBQUFBLE1BUUlDLE1BQU0sR0FBRyxDQVJiO0FBQUEsTUFVSUMsV0FWSjtBQUFBLE1BV0lDLFFBWEo7QUFhQTs7Ozs7QUFHQSxXQUFTQyxRQUFULENBQWtCQyxJQUFsQixFQUF3QkMsS0FBeEIsRUFBK0I7QUFDN0IsU0FBSyxJQUFJQyxDQUFDLEdBQUcsQ0FBYixFQUFnQkEsQ0FBQyxHQUFHRixJQUFJLENBQUNqQixLQUFMLENBQVdGLE1BQS9CLEVBQXVDcUIsQ0FBQyxFQUF4QyxFQUE0QztBQUMxQyxVQUFJWixJQUFJLEdBQUdVLElBQUksQ0FBQ2pCLEtBQUwsQ0FBV21CLENBQVgsQ0FBWDtBQUFBLFVBQ0lYLFNBQVMsR0FBSUQsSUFBSSxDQUFDVCxNQUFMLEdBQWMsQ0FBZCxHQUFrQlMsSUFBSSxDQUFDLENBQUQsQ0FBdEIsR0FBNEIsR0FEN0M7QUFBQSxVQUVJYSxPQUFPLEdBQUliLElBQUksQ0FBQ1QsTUFBTCxHQUFjLENBQWQsR0FBa0JTLElBQUksQ0FBQ2MsTUFBTCxDQUFZLENBQVosQ0FBbEIsR0FBbUNkLElBRmxEOztBQUlBLFVBQUlDLFNBQVMsS0FBSyxHQUFkLElBQXFCQSxTQUFTLEtBQUssR0FBdkMsRUFBNEM7QUFDMUM7QUFDQSxZQUFJLENBQUNILFdBQVcsQ0FBQ2EsS0FBSyxHQUFHLENBQVQsRUFBWWxCLEtBQUssQ0FBQ2tCLEtBQUQsQ0FBakIsRUFBMEJWLFNBQTFCLEVBQXFDWSxPQUFyQyxDQUFoQixFQUErRDtBQUM3RFYsVUFBQUEsVUFBVTs7QUFFVixjQUFJQSxVQUFVLEdBQUdDLFVBQWpCLEVBQTZCO0FBQzNCLG1CQUFPLEtBQVA7QUFDRDtBQUNGOztBQUNETyxRQUFBQSxLQUFLO0FBQ047QUFDRjs7QUFFRCxXQUFPLElBQVA7QUFDRCxHQWxEdUQsQ0FvRHhEOzs7QUFDQSxPQUFLLElBQUlJLENBQUMsR0FBRyxDQUFiLEVBQWdCQSxDQUFDLEdBQUdsQixLQUFLLENBQUNOLE1BQTFCLEVBQWtDd0IsQ0FBQyxFQUFuQyxFQUF1QztBQUNyQyxRQUFJTCxJQUFJLEdBQUdiLEtBQUssQ0FBQ2tCLENBQUQsQ0FBaEI7QUFBQSxRQUNJQyxPQUFPLEdBQUd2QixLQUFLLENBQUNGLE1BQU4sR0FBZW1CLElBQUksQ0FBQ08sUUFEbEM7QUFBQSxRQUVJQyxXQUFXLEdBQUcsQ0FGbEI7QUFBQSxRQUdJUCxLQUFLLEdBQUdMLE1BQU0sR0FBR0ksSUFBSSxDQUFDUyxRQUFkLEdBQXlCLENBSHJDO0FBS0EsUUFBSUMsUUFBUTtBQUFHO0FBQUE7QUFBQTs7QUFBQUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsT0FBaUJWLEtBQWpCLEVBQXdCTixPQUF4QixFQUFpQ1csT0FBakMsQ0FBZjs7QUFFQSxXQUFPRSxXQUFXLEtBQUtJLFNBQXZCLEVBQWtDSixXQUFXLEdBQUdFLFFBQVEsRUFBeEQsRUFBNEQ7QUFDMUQsVUFBSVgsUUFBUSxDQUFDQyxJQUFELEVBQU9DLEtBQUssR0FBR08sV0FBZixDQUFaLEVBQXlDO0FBQ3ZDUixRQUFBQSxJQUFJLENBQUNKLE1BQUwsR0FBY0EsTUFBTSxJQUFJWSxXQUF4QjtBQUNBO0FBQ0Q7QUFDRjs7QUFFRCxRQUFJQSxXQUFXLEtBQUtJLFNBQXBCLEVBQStCO0FBQzdCLGFBQU8sS0FBUDtBQUNELEtBakJvQyxDQW1CckM7QUFDQTs7O0FBQ0FqQixJQUFBQSxPQUFPLEdBQUdLLElBQUksQ0FBQ0osTUFBTCxHQUFjSSxJQUFJLENBQUNTLFFBQW5CLEdBQThCVCxJQUFJLENBQUNPLFFBQTdDO0FBQ0QsR0EzRXVELENBNkV4RDs7O0FBQ0EsTUFBSU0sVUFBVSxHQUFHLENBQWpCOztBQUNBLE9BQUssSUFBSVIsRUFBQyxHQUFHLENBQWIsRUFBZ0JBLEVBQUMsR0FBR2xCLEtBQUssQ0FBQ04sTUFBMUIsRUFBa0N3QixFQUFDLEVBQW5DLEVBQXVDO0FBQ3JDLFFBQUlMLEtBQUksR0FBR2IsS0FBSyxDQUFDa0IsRUFBRCxDQUFoQjtBQUFBLFFBQ0lKLE1BQUssR0FBR0QsS0FBSSxDQUFDUyxRQUFMLEdBQWdCVCxLQUFJLENBQUNKLE1BQXJCLEdBQThCaUIsVUFBOUIsR0FBMkMsQ0FEdkQ7O0FBRUFBLElBQUFBLFVBQVUsSUFBSWIsS0FBSSxDQUFDYyxRQUFMLEdBQWdCZCxLQUFJLENBQUNPLFFBQW5DOztBQUVBLFNBQUssSUFBSUwsQ0FBQyxHQUFHLENBQWIsRUFBZ0JBLENBQUMsR0FBR0YsS0FBSSxDQUFDakIsS0FBTCxDQUFXRixNQUEvQixFQUF1Q3FCLENBQUMsRUFBeEMsRUFBNEM7QUFDMUMsVUFBSVosSUFBSSxHQUFHVSxLQUFJLENBQUNqQixLQUFMLENBQVdtQixDQUFYLENBQVg7QUFBQSxVQUNJWCxTQUFTLEdBQUlELElBQUksQ0FBQ1QsTUFBTCxHQUFjLENBQWQsR0FBa0JTLElBQUksQ0FBQyxDQUFELENBQXRCLEdBQTRCLEdBRDdDO0FBQUEsVUFFSWEsT0FBTyxHQUFJYixJQUFJLENBQUNULE1BQUwsR0FBYyxDQUFkLEdBQWtCUyxJQUFJLENBQUNjLE1BQUwsQ0FBWSxDQUFaLENBQWxCLEdBQW1DZCxJQUZsRDtBQUFBLFVBR0l5QixTQUFTLEdBQUdmLEtBQUksQ0FBQ2dCLGNBQUwsSUFBdUJoQixLQUFJLENBQUNnQixjQUFMLENBQW9CZCxDQUFwQixDQUF2QixJQUFpRCxJQUhqRTs7QUFLQSxVQUFJWCxTQUFTLEtBQUssR0FBbEIsRUFBdUI7QUFDckJVLFFBQUFBLE1BQUs7QUFDTixPQUZELE1BRU8sSUFBSVYsU0FBUyxLQUFLLEdBQWxCLEVBQXVCO0FBQzVCUixRQUFBQSxLQUFLLENBQUNrQyxNQUFOLENBQWFoQixNQUFiLEVBQW9CLENBQXBCO0FBQ0FoQixRQUFBQSxVQUFVLENBQUNnQyxNQUFYLENBQWtCaEIsTUFBbEIsRUFBeUIsQ0FBekI7QUFDRjtBQUNDLE9BSk0sTUFJQSxJQUFJVixTQUFTLEtBQUssR0FBbEIsRUFBdUI7QUFDNUJSLFFBQUFBLEtBQUssQ0FBQ2tDLE1BQU4sQ0FBYWhCLE1BQWIsRUFBb0IsQ0FBcEIsRUFBdUJFLE9BQXZCO0FBQ0FsQixRQUFBQSxVQUFVLENBQUNnQyxNQUFYLENBQWtCaEIsTUFBbEIsRUFBeUIsQ0FBekIsRUFBNEJjLFNBQTVCO0FBQ0FkLFFBQUFBLE1BQUs7QUFDTixPQUpNLE1BSUEsSUFBSVYsU0FBUyxLQUFLLElBQWxCLEVBQXdCO0FBQzdCLFlBQUkyQixpQkFBaUIsR0FBR2xCLEtBQUksQ0FBQ2pCLEtBQUwsQ0FBV21CLENBQUMsR0FBRyxDQUFmLElBQW9CRixLQUFJLENBQUNqQixLQUFMLENBQVdtQixDQUFDLEdBQUcsQ0FBZixFQUFrQixDQUFsQixDQUFwQixHQUEyQyxJQUFuRTs7QUFDQSxZQUFJZ0IsaUJBQWlCLEtBQUssR0FBMUIsRUFBK0I7QUFDN0JyQixVQUFBQSxXQUFXLEdBQUcsSUFBZDtBQUNELFNBRkQsTUFFTyxJQUFJcUIsaUJBQWlCLEtBQUssR0FBMUIsRUFBK0I7QUFDcENwQixVQUFBQSxRQUFRLEdBQUcsSUFBWDtBQUNEO0FBQ0Y7QUFDRjtBQUNGLEdBN0d1RCxDQStHeEQ7OztBQUNBLE1BQUlELFdBQUosRUFBaUI7QUFDZixXQUFPLENBQUNkLEtBQUssQ0FBQ0EsS0FBSyxDQUFDRixNQUFOLEdBQWUsQ0FBaEIsQ0FBYixFQUFpQztBQUMvQkUsTUFBQUEsS0FBSyxDQUFDb0MsR0FBTjtBQUNBbEMsTUFBQUEsVUFBVSxDQUFDa0MsR0FBWDtBQUNEO0FBQ0YsR0FMRCxNQUtPLElBQUlyQixRQUFKLEVBQWM7QUFDbkJmLElBQUFBLEtBQUssQ0FBQ3FDLElBQU4sQ0FBVyxFQUFYO0FBQ0FuQyxJQUFBQSxVQUFVLENBQUNtQyxJQUFYLENBQWdCLElBQWhCO0FBQ0Q7O0FBQ0QsT0FBSyxJQUFJQyxFQUFFLEdBQUcsQ0FBZCxFQUFpQkEsRUFBRSxHQUFHdEMsS0FBSyxDQUFDRixNQUFOLEdBQWUsQ0FBckMsRUFBd0N3QyxFQUFFLEVBQTFDLEVBQThDO0FBQzVDdEMsSUFBQUEsS0FBSyxDQUFDc0MsRUFBRCxDQUFMLEdBQVl0QyxLQUFLLENBQUNzQyxFQUFELENBQUwsR0FBWXBDLFVBQVUsQ0FBQ29DLEVBQUQsQ0FBbEM7QUFDRDs7QUFDRCxTQUFPdEMsS0FBSyxDQUFDdUMsSUFBTixDQUFXLEVBQVgsQ0FBUDtBQUNELEMsQ0FFRDs7O0FBQ08sU0FBU0MsWUFBVCxDQUFzQi9DLE9BQXRCLEVBQStCQyxPQUEvQixFQUF3QztBQUM3QyxNQUFJLE9BQU9ELE9BQVAsS0FBbUIsUUFBdkIsRUFBaUM7QUFDL0JBLElBQUFBLE9BQU87QUFBRztBQUFBO0FBQUE7O0FBQUFFO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUE7QUFBQSxLQUFXRixPQUFYLENBQVY7QUFDRDs7QUFFRCxNQUFJZ0QsWUFBWSxHQUFHLENBQW5COztBQUNBLFdBQVNDLFlBQVQsR0FBd0I7QUFDdEIsUUFBSUMsS0FBSyxHQUFHbEQsT0FBTyxDQUFDZ0QsWUFBWSxFQUFiLENBQW5COztBQUNBLFFBQUksQ0FBQ0UsS0FBTCxFQUFZO0FBQ1YsYUFBT2pELE9BQU8sQ0FBQ2tELFFBQVIsRUFBUDtBQUNEOztBQUVEbEQsSUFBQUEsT0FBTyxDQUFDbUQsUUFBUixDQUFpQkYsS0FBakIsRUFBd0IsVUFBU0csR0FBVCxFQUFjQyxJQUFkLEVBQW9CO0FBQzFDLFVBQUlELEdBQUosRUFBUztBQUNQLGVBQU9wRCxPQUFPLENBQUNrRCxRQUFSLENBQWlCRSxHQUFqQixDQUFQO0FBQ0Q7O0FBRUQsVUFBSUUsY0FBYyxHQUFHekQsVUFBVSxDQUFDd0QsSUFBRCxFQUFPSixLQUFQLEVBQWNqRCxPQUFkLENBQS9CO0FBQ0FBLE1BQUFBLE9BQU8sQ0FBQ3VELE9BQVIsQ0FBZ0JOLEtBQWhCLEVBQXVCSyxjQUF2QixFQUF1QyxVQUFTRixHQUFULEVBQWM7QUFDbkQsWUFBSUEsR0FBSixFQUFTO0FBQ1AsaUJBQU9wRCxPQUFPLENBQUNrRCxRQUFSLENBQWlCRSxHQUFqQixDQUFQO0FBQ0Q7O0FBRURKLFFBQUFBLFlBQVk7QUFDYixPQU5EO0FBT0QsS0FiRDtBQWNEOztBQUNEQSxFQUFBQSxZQUFZO0FBQ2IiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQge3BhcnNlUGF0Y2h9IGZyb20gJy4vcGFyc2UnO1xuaW1wb3J0IGRpc3RhbmNlSXRlcmF0b3IgZnJvbSAnLi4vdXRpbC9kaXN0YW5jZS1pdGVyYXRvcic7XG5cbmV4cG9ydCBmdW5jdGlvbiBhcHBseVBhdGNoKHNvdXJjZSwgdW5pRGlmZiwgb3B0aW9ucyA9IHt9KSB7XG4gIGlmICh0eXBlb2YgdW5pRGlmZiA9PT0gJ3N0cmluZycpIHtcbiAgICB1bmlEaWZmID0gcGFyc2VQYXRjaCh1bmlEaWZmKTtcbiAgfVxuXG4gIGlmIChBcnJheS5pc0FycmF5KHVuaURpZmYpKSB7XG4gICAgaWYgKHVuaURpZmYubGVuZ3RoID4gMSkge1xuICAgICAgdGhyb3cgbmV3IEVycm9yKCdhcHBseVBhdGNoIG9ubHkgd29ya3Mgd2l0aCBhIHNpbmdsZSBpbnB1dC4nKTtcbiAgICB9XG5cbiAgICB1bmlEaWZmID0gdW5pRGlmZlswXTtcbiAgfVxuXG4gIC8vIEFwcGx5IHRoZSBkaWZmIHRvIHRoZSBpbnB1dFxuICBsZXQgbGluZXMgPSBzb3VyY2Uuc3BsaXQoL1xcclxcbnxbXFxuXFx2XFxmXFxyXFx4ODVdLyksXG4gICAgICBkZWxpbWl0ZXJzID0gc291cmNlLm1hdGNoKC9cXHJcXG58W1xcblxcdlxcZlxcclxceDg1XS9nKSB8fCBbXSxcbiAgICAgIGh1bmtzID0gdW5pRGlmZi5odW5rcyxcblxuICAgICAgY29tcGFyZUxpbmUgPSBvcHRpb25zLmNvbXBhcmVMaW5lIHx8ICgobGluZU51bWJlciwgbGluZSwgb3BlcmF0aW9uLCBwYXRjaENvbnRlbnQpID0+IGxpbmUgPT09IHBhdGNoQ29udGVudCksXG4gICAgICBlcnJvckNvdW50ID0gMCxcbiAgICAgIGZ1enpGYWN0b3IgPSBvcHRpb25zLmZ1enpGYWN0b3IgfHwgMCxcbiAgICAgIG1pbkxpbmUgPSAwLFxuICAgICAgb2Zmc2V0ID0gMCxcblxuICAgICAgcmVtb3ZlRU9GTkwsXG4gICAgICBhZGRFT0ZOTDtcblxuICAvKipcbiAgICogQ2hlY2tzIGlmIHRoZSBodW5rIGV4YWN0bHkgZml0cyBvbiB0aGUgcHJvdmlkZWQgbG9jYXRpb25cbiAgICovXG4gIGZ1bmN0aW9uIGh1bmtGaXRzKGh1bmssIHRvUG9zKSB7XG4gICAgZm9yIChsZXQgaiA9IDA7IGogPCBodW5rLmxpbmVzLmxlbmd0aDsgaisrKSB7XG4gICAgICBsZXQgbGluZSA9IGh1bmsubGluZXNbal0sXG4gICAgICAgICAgb3BlcmF0aW9uID0gKGxpbmUubGVuZ3RoID4gMCA/IGxpbmVbMF0gOiAnICcpLFxuICAgICAgICAgIGNvbnRlbnQgPSAobGluZS5sZW5ndGggPiAwID8gbGluZS5zdWJzdHIoMSkgOiBsaW5lKTtcblxuICAgICAgaWYgKG9wZXJhdGlvbiA9PT0gJyAnIHx8IG9wZXJhdGlvbiA9PT0gJy0nKSB7XG4gICAgICAgIC8vIENvbnRleHQgc2FuaXR5IGNoZWNrXG4gICAgICAgIGlmICghY29tcGFyZUxpbmUodG9Qb3MgKyAxLCBsaW5lc1t0b1Bvc10sIG9wZXJhdGlvbiwgY29udGVudCkpIHtcbiAgICAgICAgICBlcnJvckNvdW50Kys7XG5cbiAgICAgICAgICBpZiAoZXJyb3JDb3VudCA+IGZ1enpGYWN0b3IpIHtcbiAgICAgICAgICAgIHJldHVybiBmYWxzZTtcbiAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgICAgdG9Qb3MrKztcbiAgICAgIH1cbiAgICB9XG5cbiAgICByZXR1cm4gdHJ1ZTtcbiAgfVxuXG4gIC8vIFNlYXJjaCBiZXN0IGZpdCBvZmZzZXRzIGZvciBlYWNoIGh1bmsgYmFzZWQgb24gdGhlIHByZXZpb3VzIG9uZXNcbiAgZm9yIChsZXQgaSA9IDA7IGkgPCBodW5rcy5sZW5ndGg7IGkrKykge1xuICAgIGxldCBodW5rID0gaHVua3NbaV0sXG4gICAgICAgIG1heExpbmUgPSBsaW5lcy5sZW5ndGggLSBodW5rLm9sZExpbmVzLFxuICAgICAgICBsb2NhbE9mZnNldCA9IDAsXG4gICAgICAgIHRvUG9zID0gb2Zmc2V0ICsgaHVuay5vbGRTdGFydCAtIDE7XG5cbiAgICBsZXQgaXRlcmF0b3IgPSBkaXN0YW5jZUl0ZXJhdG9yKHRvUG9zLCBtaW5MaW5lLCBtYXhMaW5lKTtcblxuICAgIGZvciAoOyBsb2NhbE9mZnNldCAhPT0gdW5kZWZpbmVkOyBsb2NhbE9mZnNldCA9IGl0ZXJhdG9yKCkpIHtcbiAgICAgIGlmIChodW5rRml0cyhodW5rLCB0b1BvcyArIGxvY2FsT2Zmc2V0KSkge1xuICAgICAgICBodW5rLm9mZnNldCA9IG9mZnNldCArPSBsb2NhbE9mZnNldDtcbiAgICAgICAgYnJlYWs7XG4gICAgICB9XG4gICAgfVxuXG4gICAgaWYgKGxvY2FsT2Zmc2V0ID09PSB1bmRlZmluZWQpIHtcbiAgICAgIHJldHVybiBmYWxzZTtcbiAgICB9XG5cbiAgICAvLyBTZXQgbG93ZXIgdGV4dCBsaW1pdCB0byBlbmQgb2YgdGhlIGN1cnJlbnQgaHVuaywgc28gbmV4dCBvbmVzIGRvbid0IHRyeVxuICAgIC8vIHRvIGZpdCBvdmVyIGFscmVhZHkgcGF0Y2hlZCB0ZXh0XG4gICAgbWluTGluZSA9IGh1bmsub2Zmc2V0ICsgaHVuay5vbGRTdGFydCArIGh1bmsub2xkTGluZXM7XG4gIH1cblxuICAvLyBBcHBseSBwYXRjaCBodW5rc1xuICBsZXQgZGlmZk9mZnNldCA9IDA7XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgaHVua3MubGVuZ3RoOyBpKyspIHtcbiAgICBsZXQgaHVuayA9IGh1bmtzW2ldLFxuICAgICAgICB0b1BvcyA9IGh1bmsub2xkU3RhcnQgKyBodW5rLm9mZnNldCArIGRpZmZPZmZzZXQgLSAxO1xuICAgIGRpZmZPZmZzZXQgKz0gaHVuay5uZXdMaW5lcyAtIGh1bmsub2xkTGluZXM7XG5cbiAgICBmb3IgKGxldCBqID0gMDsgaiA8IGh1bmsubGluZXMubGVuZ3RoOyBqKyspIHtcbiAgICAgIGxldCBsaW5lID0gaHVuay5saW5lc1tqXSxcbiAgICAgICAgICBvcGVyYXRpb24gPSAobGluZS5sZW5ndGggPiAwID8gbGluZVswXSA6ICcgJyksXG4gICAgICAgICAgY29udGVudCA9IChsaW5lLmxlbmd0aCA+IDAgPyBsaW5lLnN1YnN0cigxKSA6IGxpbmUpLFxuICAgICAgICAgIGRlbGltaXRlciA9IGh1bmsubGluZWRlbGltaXRlcnMgJiYgaHVuay5saW5lZGVsaW1pdGVyc1tqXSB8fCAnXFxuJztcblxuICAgICAgaWYgKG9wZXJhdGlvbiA9PT0gJyAnKSB7XG4gICAgICAgIHRvUG9zKys7XG4gICAgICB9IGVsc2UgaWYgKG9wZXJhdGlvbiA9PT0gJy0nKSB7XG4gICAgICAgIGxpbmVzLnNwbGljZSh0b1BvcywgMSk7XG4gICAgICAgIGRlbGltaXRlcnMuc3BsaWNlKHRvUG9zLCAxKTtcbiAgICAgIC8qIGlzdGFuYnVsIGlnbm9yZSBlbHNlICovXG4gICAgICB9IGVsc2UgaWYgKG9wZXJhdGlvbiA9PT0gJysnKSB7XG4gICAgICAgIGxpbmVzLnNwbGljZSh0b1BvcywgMCwgY29udGVudCk7XG4gICAgICAgIGRlbGltaXRlcnMuc3BsaWNlKHRvUG9zLCAwLCBkZWxpbWl0ZXIpO1xuICAgICAgICB0b1BvcysrO1xuICAgICAgfSBlbHNlIGlmIChvcGVyYXRpb24gPT09ICdcXFxcJykge1xuICAgICAgICBsZXQgcHJldmlvdXNPcGVyYXRpb24gPSBodW5rLmxpbmVzW2ogLSAxXSA/IGh1bmsubGluZXNbaiAtIDFdWzBdIDogbnVsbDtcbiAgICAgICAgaWYgKHByZXZpb3VzT3BlcmF0aW9uID09PSAnKycpIHtcbiAgICAgICAgICByZW1vdmVFT0ZOTCA9IHRydWU7XG4gICAgICAgIH0gZWxzZSBpZiAocHJldmlvdXNPcGVyYXRpb24gPT09ICctJykge1xuICAgICAgICAgIGFkZEVPRk5MID0gdHJ1ZTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cbiAgfVxuXG4gIC8vIEhhbmRsZSBFT0ZOTCBpbnNlcnRpb24vcmVtb3ZhbFxuICBpZiAocmVtb3ZlRU9GTkwpIHtcbiAgICB3aGlsZSAoIWxpbmVzW2xpbmVzLmxlbmd0aCAtIDFdKSB7XG4gICAgICBsaW5lcy5wb3AoKTtcbiAgICAgIGRlbGltaXRlcnMucG9wKCk7XG4gICAgfVxuICB9IGVsc2UgaWYgKGFkZEVPRk5MKSB7XG4gICAgbGluZXMucHVzaCgnJyk7XG4gICAgZGVsaW1pdGVycy5wdXNoKCdcXG4nKTtcbiAgfVxuICBmb3IgKGxldCBfayA9IDA7IF9rIDwgbGluZXMubGVuZ3RoIC0gMTsgX2srKykge1xuICAgIGxpbmVzW19rXSA9IGxpbmVzW19rXSArIGRlbGltaXRlcnNbX2tdO1xuICB9XG4gIHJldHVybiBsaW5lcy5qb2luKCcnKTtcbn1cblxuLy8gV3JhcHBlciB0aGF0IHN1cHBvcnRzIG11bHRpcGxlIGZpbGUgcGF0Y2hlcyB2aWEgY2FsbGJhY2tzLlxuZXhwb3J0IGZ1bmN0aW9uIGFwcGx5UGF0Y2hlcyh1bmlEaWZmLCBvcHRpb25zKSB7XG4gIGlmICh0eXBlb2YgdW5pRGlmZiA9PT0gJ3N0cmluZycpIHtcbiAgICB1bmlEaWZmID0gcGFyc2VQYXRjaCh1bmlEaWZmKTtcbiAgfVxuXG4gIGxldCBjdXJyZW50SW5kZXggPSAwO1xuICBmdW5jdGlvbiBwcm9jZXNzSW5kZXgoKSB7XG4gICAgbGV0IGluZGV4ID0gdW5pRGlmZltjdXJyZW50SW5kZXgrK107XG4gICAgaWYgKCFpbmRleCkge1xuICAgICAgcmV0dXJuIG9wdGlvbnMuY29tcGxldGUoKTtcbiAgICB9XG5cbiAgICBvcHRpb25zLmxvYWRGaWxlKGluZGV4LCBmdW5jdGlvbihlcnIsIGRhdGEpIHtcbiAgICAgIGlmIChlcnIpIHtcbiAgICAgICAgcmV0dXJuIG9wdGlvbnMuY29tcGxldGUoZXJyKTtcbiAgICAgIH1cblxuICAgICAgbGV0IHVwZGF0ZWRDb250ZW50ID0gYXBwbHlQYXRjaChkYXRhLCBpbmRleCwgb3B0aW9ucyk7XG4gICAgICBvcHRpb25zLnBhdGNoZWQoaW5kZXgsIHVwZGF0ZWRDb250ZW50LCBmdW5jdGlvbihlcnIpIHtcbiAgICAgICAgaWYgKGVycikge1xuICAgICAgICAgIHJldHVybiBvcHRpb25zLmNvbXBsZXRlKGVycik7XG4gICAgICAgIH1cblxuICAgICAgICBwcm9jZXNzSW5kZXgoKTtcbiAgICAgIH0pO1xuICAgIH0pO1xuICB9XG4gIHByb2Nlc3NJbmRleCgpO1xufVxuIl19 diff --git a/node_modules/diff/lib/patch/create.js b/node_modules/diff/lib/patch/create.js deleted file mode 100644 index 45be1512a5a08..0000000000000 --- a/node_modules/diff/lib/patch/create.js +++ /dev/null @@ -1,276 +0,0 @@ -/*istanbul ignore start*/ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.structuredPatch = structuredPatch; -exports.formatPatch = formatPatch; -exports.createTwoFilesPatch = createTwoFilesPatch; -exports.createPatch = createPatch; - -/*istanbul ignore end*/ -var -/*istanbul ignore start*/ -_line = require("../diff/line") -/*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" && Symbol.iterator in Object(iter)) 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 structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - if (!options) { - options = {}; - } - - if (typeof options.context === 'undefined') { - options.context = 4; - } - - var diff = - /*istanbul ignore start*/ - (0, - /*istanbul ignore end*/ - - /*istanbul ignore start*/ - _line - /*istanbul ignore end*/ - . - /*istanbul ignore start*/ - diffLines) - /*istanbul ignore end*/ - (oldStr, newStr, options); - - 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*/ - i) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, '').split('\n'); - 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 - }; - - if (i >= diff.length - 2 && lines.length <= options.context) { - // EOF is inside this hunk - var oldEOFNewline = /\n$/.test(oldStr); - var newEOFNewline = /\n$/.test(newStr); - var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; - - if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { - // special case: old has no eol and no trailing context; no-nl can end up before adds - // however, if the old file is empty, do not output the no-nl line - curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); - } - - if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { - curRange.push('\\ No newline at end of file'); - } - } - - 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( - /*istanbul ignore end*/ - i); - } - - 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) { - return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); -} - -function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { - return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); -} -//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9jcmVhdGUuanMiXSwibmFtZXMiOlsic3RydWN0dXJlZFBhdGNoIiwib2xkRmlsZU5hbWUiLCJuZXdGaWxlTmFtZSIsIm9sZFN0ciIsIm5ld1N0ciIsIm9sZEhlYWRlciIsIm5ld0hlYWRlciIsIm9wdGlvbnMiLCJjb250ZXh0IiwiZGlmZiIsImRpZmZMaW5lcyIsInB1c2giLCJ2YWx1ZSIsImxpbmVzIiwiY29udGV4dExpbmVzIiwibWFwIiwiZW50cnkiLCJodW5rcyIsIm9sZFJhbmdlU3RhcnQiLCJuZXdSYW5nZVN0YXJ0IiwiY3VyUmFuZ2UiLCJvbGRMaW5lIiwibmV3TGluZSIsImkiLCJjdXJyZW50IiwicmVwbGFjZSIsInNwbGl0IiwiYWRkZWQiLCJyZW1vdmVkIiwicHJldiIsInNsaWNlIiwibGVuZ3RoIiwiY29udGV4dFNpemUiLCJNYXRoIiwibWluIiwiaHVuayIsIm9sZFN0YXJ0Iiwib2xkTGluZXMiLCJuZXdTdGFydCIsIm5ld0xpbmVzIiwib2xkRU9GTmV3bGluZSIsInRlc3QiLCJuZXdFT0ZOZXdsaW5lIiwibm9ObEJlZm9yZUFkZHMiLCJzcGxpY2UiLCJmb3JtYXRQYXRjaCIsIkFycmF5IiwiaXNBcnJheSIsImpvaW4iLCJyZXQiLCJhcHBseSIsImNyZWF0ZVR3b0ZpbGVzUGF0Y2giLCJjcmVhdGVQYXRjaCIsImZpbGVOYW1lIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBOzs7Ozs7Ozs7Ozs7Ozs7QUFFTyxTQUFTQSxlQUFULENBQXlCQyxXQUF6QixFQUFzQ0MsV0FBdEMsRUFBbURDLE1BQW5ELEVBQTJEQyxNQUEzRCxFQUFtRUMsU0FBbkUsRUFBOEVDLFNBQTlFLEVBQXlGQyxPQUF6RixFQUFrRztBQUN2RyxNQUFJLENBQUNBLE9BQUwsRUFBYztBQUNaQSxJQUFBQSxPQUFPLEdBQUcsRUFBVjtBQUNEOztBQUNELE1BQUksT0FBT0EsT0FBTyxDQUFDQyxPQUFmLEtBQTJCLFdBQS9CLEVBQTRDO0FBQzFDRCxJQUFBQSxPQUFPLENBQUNDLE9BQVIsR0FBa0IsQ0FBbEI7QUFDRDs7QUFFRCxNQUFNQyxJQUFJO0FBQUc7QUFBQTtBQUFBOztBQUFBQztBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBO0FBQUEsR0FBVVAsTUFBVixFQUFrQkMsTUFBbEIsRUFBMEJHLE9BQTFCLENBQWI7O0FBQ0EsTUFBRyxDQUFDRSxJQUFKLEVBQVU7QUFDUjtBQUNEOztBQUVEQSxFQUFBQSxJQUFJLENBQUNFLElBQUwsQ0FBVTtBQUFDQyxJQUFBQSxLQUFLLEVBQUUsRUFBUjtBQUFZQyxJQUFBQSxLQUFLLEVBQUU7QUFBbkIsR0FBVixFQWJ1RyxDQWFwRTs7QUFFbkMsV0FBU0MsWUFBVCxDQUFzQkQsS0FBdEIsRUFBNkI7QUFDM0IsV0FBT0EsS0FBSyxDQUFDRSxHQUFOLENBQVUsVUFBU0MsS0FBVCxFQUFnQjtBQUFFLGFBQU8sTUFBTUEsS0FBYjtBQUFxQixLQUFqRCxDQUFQO0FBQ0Q7O0FBRUQsTUFBSUMsS0FBSyxHQUFHLEVBQVo7QUFDQSxNQUFJQyxhQUFhLEdBQUcsQ0FBcEI7QUFBQSxNQUF1QkMsYUFBYSxHQUFHLENBQXZDO0FBQUEsTUFBMENDLFFBQVEsR0FBRyxFQUFyRDtBQUFBLE1BQ0lDLE9BQU8sR0FBRyxDQURkO0FBQUEsTUFDaUJDLE9BQU8sR0FBRyxDQUQzQjs7QUFwQnVHO0FBQUE7QUFBQTtBQXNCOUZDLEVBQUFBLENBdEI4RjtBQXVCckcsUUFBTUMsT0FBTyxHQUFHZixJQUFJLENBQUNjLENBQUQsQ0FBcEI7QUFBQSxRQUNNVixLQUFLLEdBQUdXLE9BQU8sQ0FBQ1gsS0FBUixJQUFpQlcsT0FBTyxDQUFDWixLQUFSLENBQWNhLE9BQWQsQ0FBc0IsS0FBdEIsRUFBNkIsRUFBN0IsRUFBaUNDLEtBQWpDLENBQXVDLElBQXZDLENBRC9CO0FBRUFGLElBQUFBLE9BQU8sQ0FBQ1gsS0FBUixHQUFnQkEsS0FBaEI7O0FBRUEsUUFBSVcsT0FBTyxDQUFDRyxLQUFSLElBQWlCSCxPQUFPLENBQUNJLE9BQTdCLEVBQXNDO0FBQUE7QUFBQTs7QUFBQTtBQUNwQztBQUNBLFVBQUksQ0FBQ1YsYUFBTCxFQUFvQjtBQUNsQixZQUFNVyxJQUFJLEdBQUdwQixJQUFJLENBQUNjLENBQUMsR0FBRyxDQUFMLENBQWpCO0FBQ0FMLFFBQUFBLGFBQWEsR0FBR0csT0FBaEI7QUFDQUYsUUFBQUEsYUFBYSxHQUFHRyxPQUFoQjs7QUFFQSxZQUFJTyxJQUFKLEVBQVU7QUFDUlQsVUFBQUEsUUFBUSxHQUFHYixPQUFPLENBQUNDLE9BQVIsR0FBa0IsQ0FBbEIsR0FBc0JNLFlBQVksQ0FBQ2UsSUFBSSxDQUFDaEIsS0FBTCxDQUFXaUIsS0FBWCxDQUFpQixDQUFDdkIsT0FBTyxDQUFDQyxPQUExQixDQUFELENBQWxDLEdBQXlFLEVBQXBGO0FBQ0FVLFVBQUFBLGFBQWEsSUFBSUUsUUFBUSxDQUFDVyxNQUExQjtBQUNBWixVQUFBQSxhQUFhLElBQUlDLFFBQVEsQ0FBQ1csTUFBMUI7QUFDRDtBQUNGLE9BWm1DLENBY3BDOzs7QUFDQTs7QUFBQTs7QUFBQTtBQUFBO0FBQUE7QUFBQVgsTUFBQUEsUUFBUSxFQUFDVCxJQUFUO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBa0JFLE1BQUFBLEtBQUssQ0FBQ0UsR0FBTixDQUFVLFVBQVNDLEtBQVQsRUFBZ0I7QUFDMUMsZUFBTyxDQUFDUSxPQUFPLENBQUNHLEtBQVIsR0FBZ0IsR0FBaEIsR0FBc0IsR0FBdkIsSUFBOEJYLEtBQXJDO0FBQ0QsT0FGaUIsQ0FBbEIsR0Fmb0MsQ0FtQnBDOzs7QUFDQSxVQUFJUSxPQUFPLENBQUNHLEtBQVosRUFBbUI7QUFDakJMLFFBQUFBLE9BQU8sSUFBSVQsS0FBSyxDQUFDa0IsTUFBakI7QUFDRCxPQUZELE1BRU87QUFDTFYsUUFBQUEsT0FBTyxJQUFJUixLQUFLLENBQUNrQixNQUFqQjtBQUNEO0FBQ0YsS0F6QkQsTUF5Qk87QUFDTDtBQUNBLFVBQUliLGFBQUosRUFBbUI7QUFDakI7QUFDQSxZQUFJTCxLQUFLLENBQUNrQixNQUFOLElBQWdCeEIsT0FBTyxDQUFDQyxPQUFSLEdBQWtCLENBQWxDLElBQXVDZSxDQUFDLEdBQUdkLElBQUksQ0FBQ3NCLE1BQUwsR0FBYyxDQUE3RCxFQUFnRTtBQUFBO0FBQUE7O0FBQUE7QUFDOUQ7O0FBQ0E7O0FBQUE7O0FBQUE7QUFBQTtBQUFBO0FBQUFYLFVBQUFBLFFBQVEsRUFBQ1QsSUFBVDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQWtCRyxVQUFBQSxZQUFZLENBQUNELEtBQUQsQ0FBOUI7QUFDRCxTQUhELE1BR087QUFBQTtBQUFBOztBQUFBO0FBQ0w7QUFDQSxjQUFJbUIsV0FBVyxHQUFHQyxJQUFJLENBQUNDLEdBQUwsQ0FBU3JCLEtBQUssQ0FBQ2tCLE1BQWYsRUFBdUJ4QixPQUFPLENBQUNDLE9BQS9CLENBQWxCOztBQUNBOztBQUFBOztBQUFBO0FBQUE7QUFBQTtBQUFBWSxVQUFBQSxRQUFRLEVBQUNULElBQVQ7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFrQkcsVUFBQUEsWUFBWSxDQUFDRCxLQUFLLENBQUNpQixLQUFOLENBQVksQ0FBWixFQUFlRSxXQUFmLENBQUQsQ0FBOUI7O0FBRUEsY0FBSUcsSUFBSSxHQUFHO0FBQ1RDLFlBQUFBLFFBQVEsRUFBRWxCLGFBREQ7QUFFVG1CLFlBQUFBLFFBQVEsRUFBR2hCLE9BQU8sR0FBR0gsYUFBVixHQUEwQmMsV0FGNUI7QUFHVE0sWUFBQUEsUUFBUSxFQUFFbkIsYUFIRDtBQUlUb0IsWUFBQUEsUUFBUSxFQUFHakIsT0FBTyxHQUFHSCxhQUFWLEdBQTBCYSxXQUo1QjtBQUtUbkIsWUFBQUEsS0FBSyxFQUFFTztBQUxFLFdBQVg7O0FBT0EsY0FBSUcsQ0FBQyxJQUFJZCxJQUFJLENBQUNzQixNQUFMLEdBQWMsQ0FBbkIsSUFBd0JsQixLQUFLLENBQUNrQixNQUFOLElBQWdCeEIsT0FBTyxDQUFDQyxPQUFwRCxFQUE2RDtBQUMzRDtBQUNBLGdCQUFJZ0MsYUFBYSxHQUFLLEtBQUQsQ0FBUUMsSUFBUixDQUFhdEMsTUFBYixDQUFyQjtBQUNBLGdCQUFJdUMsYUFBYSxHQUFLLEtBQUQsQ0FBUUQsSUFBUixDQUFhckMsTUFBYixDQUFyQjtBQUNBLGdCQUFJdUMsY0FBYyxHQUFHOUIsS0FBSyxDQUFDa0IsTUFBTixJQUFnQixDQUFoQixJQUFxQlgsUUFBUSxDQUFDVyxNQUFULEdBQWtCSSxJQUFJLENBQUNFLFFBQWpFOztBQUNBLGdCQUFJLENBQUNHLGFBQUQsSUFBa0JHLGNBQWxCLElBQW9DeEMsTUFBTSxDQUFDNEIsTUFBUCxHQUFnQixDQUF4RCxFQUEyRDtBQUN6RDtBQUNBO0FBQ0FYLGNBQUFBLFFBQVEsQ0FBQ3dCLE1BQVQsQ0FBZ0JULElBQUksQ0FBQ0UsUUFBckIsRUFBK0IsQ0FBL0IsRUFBa0MsOEJBQWxDO0FBQ0Q7O0FBQ0QsZ0JBQUssQ0FBQ0csYUFBRCxJQUFrQixDQUFDRyxjQUFwQixJQUF1QyxDQUFDRCxhQUE1QyxFQUEyRDtBQUN6RHRCLGNBQUFBLFFBQVEsQ0FBQ1QsSUFBVCxDQUFjLDhCQUFkO0FBQ0Q7QUFDRjs7QUFDRE0sVUFBQUEsS0FBSyxDQUFDTixJQUFOLENBQVd3QixJQUFYO0FBRUFqQixVQUFBQSxhQUFhLEdBQUcsQ0FBaEI7QUFDQUMsVUFBQUEsYUFBYSxHQUFHLENBQWhCO0FBQ0FDLFVBQUFBLFFBQVEsR0FBRyxFQUFYO0FBQ0Q7QUFDRjs7QUFDREMsTUFBQUEsT0FBTyxJQUFJUixLQUFLLENBQUNrQixNQUFqQjtBQUNBVCxNQUFBQSxPQUFPLElBQUlULEtBQUssQ0FBQ2tCLE1BQWpCO0FBQ0Q7QUE5Rm9HOztBQXNCdkcsT0FBSyxJQUFJUixDQUFDLEdBQUcsQ0FBYixFQUFnQkEsQ0FBQyxHQUFHZCxJQUFJLENBQUNzQixNQUF6QixFQUFpQ1IsQ0FBQyxFQUFsQyxFQUFzQztBQUFBO0FBQUE7QUFBQTtBQUE3QkEsSUFBQUEsQ0FBNkI7QUF5RXJDOztBQUVELFNBQU87QUFDTHRCLElBQUFBLFdBQVcsRUFBRUEsV0FEUjtBQUNxQkMsSUFBQUEsV0FBVyxFQUFFQSxXQURsQztBQUVMRyxJQUFBQSxTQUFTLEVBQUVBLFNBRk47QUFFaUJDLElBQUFBLFNBQVMsRUFBRUEsU0FGNUI7QUFHTFcsSUFBQUEsS0FBSyxFQUFFQTtBQUhGLEdBQVA7QUFLRDs7QUFFTSxTQUFTNEIsV0FBVCxDQUFxQnBDLElBQXJCLEVBQTJCO0FBQ2hDLE1BQUlxQyxLQUFLLENBQUNDLE9BQU4sQ0FBY3RDLElBQWQsQ0FBSixFQUF5QjtBQUN2QixXQUFPQSxJQUFJLENBQUNNLEdBQUwsQ0FBUzhCLFdBQVQsRUFBc0JHLElBQXRCLENBQTJCLElBQTNCLENBQVA7QUFDRDs7QUFFRCxNQUFNQyxHQUFHLEdBQUcsRUFBWjs7QUFDQSxNQUFJeEMsSUFBSSxDQUFDUixXQUFMLElBQW9CUSxJQUFJLENBQUNQLFdBQTdCLEVBQTBDO0FBQ3hDK0MsSUFBQUEsR0FBRyxDQUFDdEMsSUFBSixDQUFTLFlBQVlGLElBQUksQ0FBQ1IsV0FBMUI7QUFDRDs7QUFDRGdELEVBQUFBLEdBQUcsQ0FBQ3RDLElBQUosQ0FBUyxxRUFBVDtBQUNBc0MsRUFBQUEsR0FBRyxDQUFDdEMsSUFBSixDQUFTLFNBQVNGLElBQUksQ0FBQ1IsV0FBZCxJQUE2QixPQUFPUSxJQUFJLENBQUNKLFNBQVosS0FBMEIsV0FBMUIsR0FBd0MsRUFBeEMsR0FBNkMsT0FBT0ksSUFBSSxDQUFDSixTQUF0RixDQUFUO0FBQ0E0QyxFQUFBQSxHQUFHLENBQUN0QyxJQUFKLENBQVMsU0FBU0YsSUFBSSxDQUFDUCxXQUFkLElBQTZCLE9BQU9PLElBQUksQ0FBQ0gsU0FBWixLQUEwQixXQUExQixHQUF3QyxFQUF4QyxHQUE2QyxPQUFPRyxJQUFJLENBQUNILFNBQXRGLENBQVQ7O0FBRUEsT0FBSyxJQUFJaUIsQ0FBQyxHQUFHLENBQWIsRUFBZ0JBLENBQUMsR0FBR2QsSUFBSSxDQUFDUSxLQUFMLENBQVdjLE1BQS9CLEVBQXVDUixDQUFDLEVBQXhDLEVBQTRDO0FBQzFDLFFBQU1ZLElBQUksR0FBRzFCLElBQUksQ0FBQ1EsS0FBTCxDQUFXTSxDQUFYLENBQWIsQ0FEMEMsQ0FFMUM7QUFDQTtBQUNBOztBQUNBLFFBQUlZLElBQUksQ0FBQ0UsUUFBTCxLQUFrQixDQUF0QixFQUF5QjtBQUN2QkYsTUFBQUEsSUFBSSxDQUFDQyxRQUFMLElBQWlCLENBQWpCO0FBQ0Q7O0FBQ0QsUUFBSUQsSUFBSSxDQUFDSSxRQUFMLEtBQWtCLENBQXRCLEVBQXlCO0FBQ3ZCSixNQUFBQSxJQUFJLENBQUNHLFFBQUwsSUFBaUIsQ0FBakI7QUFDRDs7QUFDRFcsSUFBQUEsR0FBRyxDQUFDdEMsSUFBSixDQUNFLFNBQVN3QixJQUFJLENBQUNDLFFBQWQsR0FBeUIsR0FBekIsR0FBK0JELElBQUksQ0FBQ0UsUUFBcEMsR0FDRSxJQURGLEdBQ1NGLElBQUksQ0FBQ0csUUFEZCxHQUN5QixHQUR6QixHQUMrQkgsSUFBSSxDQUFDSSxRQURwQyxHQUVFLEtBSEo7QUFLQVUsSUFBQUEsR0FBRyxDQUFDdEMsSUFBSixDQUFTdUMsS0FBVCxDQUFlRCxHQUFmLEVBQW9CZCxJQUFJLENBQUN0QixLQUF6QjtBQUNEOztBQUVELFNBQU9vQyxHQUFHLENBQUNELElBQUosQ0FBUyxJQUFULElBQWlCLElBQXhCO0FBQ0Q7O0FBRU0sU0FBU0csbUJBQVQsQ0FBNkJsRCxXQUE3QixFQUEwQ0MsV0FBMUMsRUFBdURDLE1BQXZELEVBQStEQyxNQUEvRCxFQUF1RUMsU0FBdkUsRUFBa0ZDLFNBQWxGLEVBQTZGQyxPQUE3RixFQUFzRztBQUMzRyxTQUFPc0MsV0FBVyxDQUFDN0MsZUFBZSxDQUFDQyxXQUFELEVBQWNDLFdBQWQsRUFBMkJDLE1BQTNCLEVBQW1DQyxNQUFuQyxFQUEyQ0MsU0FBM0MsRUFBc0RDLFNBQXRELEVBQWlFQyxPQUFqRSxDQUFoQixDQUFsQjtBQUNEOztBQUVNLFNBQVM2QyxXQUFULENBQXFCQyxRQUFyQixFQUErQmxELE1BQS9CLEVBQXVDQyxNQUF2QyxFQUErQ0MsU0FBL0MsRUFBMERDLFNBQTFELEVBQXFFQyxPQUFyRSxFQUE4RTtBQUNuRixTQUFPNEMsbUJBQW1CLENBQUNFLFFBQUQsRUFBV0EsUUFBWCxFQUFxQmxELE1BQXJCLEVBQTZCQyxNQUE3QixFQUFxQ0MsU0FBckMsRUFBZ0RDLFNBQWhELEVBQTJEQyxPQUEzRCxDQUExQjtBQUNEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHtkaWZmTGluZXN9IGZyb20gJy4uL2RpZmYvbGluZSc7XG5cbmV4cG9ydCBmdW5jdGlvbiBzdHJ1Y3R1cmVkUGF0Y2gob2xkRmlsZU5hbWUsIG5ld0ZpbGVOYW1lLCBvbGRTdHIsIG5ld1N0ciwgb2xkSGVhZGVyLCBuZXdIZWFkZXIsIG9wdGlvbnMpIHtcbiAgaWYgKCFvcHRpb25zKSB7XG4gICAgb3B0aW9ucyA9IHt9O1xuICB9XG4gIGlmICh0eXBlb2Ygb3B0aW9ucy5jb250ZXh0ID09PSAndW5kZWZpbmVkJykge1xuICAgIG9wdGlvbnMuY29udGV4dCA9IDQ7XG4gIH1cblxuICBjb25zdCBkaWZmID0gZGlmZkxpbmVzKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbiAgaWYoIWRpZmYpIHtcbiAgICByZXR1cm47XG4gIH1cblxuICBkaWZmLnB1c2goe3ZhbHVlOiAnJywgbGluZXM6IFtdfSk7IC8vIEFwcGVuZCBhbiBlbXB0eSB2YWx1ZSB0byBtYWtlIGNsZWFudXAgZWFzaWVyXG5cbiAgZnVuY3Rpb24gY29udGV4dExpbmVzKGxpbmVzKSB7XG4gICAgcmV0dXJuIGxpbmVzLm1hcChmdW5jdGlvbihlbnRyeSkgeyByZXR1cm4gJyAnICsgZW50cnk7IH0pO1xuICB9XG5cbiAgbGV0IGh1bmtzID0gW107XG4gIGxldCBvbGRSYW5nZVN0YXJ0ID0gMCwgbmV3UmFuZ2VTdGFydCA9IDAsIGN1clJhbmdlID0gW10sXG4gICAgICBvbGRMaW5lID0gMSwgbmV3TGluZSA9IDE7XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgZGlmZi5sZW5ndGg7IGkrKykge1xuICAgIGNvbnN0IGN1cnJlbnQgPSBkaWZmW2ldLFxuICAgICAgICAgIGxpbmVzID0gY3VycmVudC5saW5lcyB8fCBjdXJyZW50LnZhbHVlLnJlcGxhY2UoL1xcbiQvLCAnJykuc3BsaXQoJ1xcbicpO1xuICAgIGN1cnJlbnQubGluZXMgPSBsaW5lcztcblxuICAgIGlmIChjdXJyZW50LmFkZGVkIHx8IGN1cnJlbnQucmVtb3ZlZCkge1xuICAgICAgLy8gSWYgd2UgaGF2ZSBwcmV2aW91cyBjb250ZXh0LCBzdGFydCB3aXRoIHRoYXRcbiAgICAgIGlmICghb2xkUmFuZ2VTdGFydCkge1xuICAgICAgICBjb25zdCBwcmV2ID0gZGlmZltpIC0gMV07XG4gICAgICAgIG9sZFJhbmdlU3RhcnQgPSBvbGRMaW5lO1xuICAgICAgICBuZXdSYW5nZVN0YXJ0ID0gbmV3TGluZTtcblxuICAgICAgICBpZiAocHJldikge1xuICAgICAgICAgIGN1clJhbmdlID0gb3B0aW9ucy5jb250ZXh0ID4gMCA/IGNvbnRleHRMaW5lcyhwcmV2LmxpbmVzLnNsaWNlKC1vcHRpb25zLmNvbnRleHQpKSA6IFtdO1xuICAgICAgICAgIG9sZFJhbmdlU3RhcnQgLT0gY3VyUmFuZ2UubGVuZ3RoO1xuICAgICAgICAgIG5ld1JhbmdlU3RhcnQgLT0gY3VyUmFuZ2UubGVuZ3RoO1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIC8vIE91dHB1dCBvdXIgY2hhbmdlc1xuICAgICAgY3VyUmFuZ2UucHVzaCguLi4gbGluZXMubWFwKGZ1bmN0aW9uKGVudHJ5KSB7XG4gICAgICAgIHJldHVybiAoY3VycmVudC5hZGRlZCA/ICcrJyA6ICctJykgKyBlbnRyeTtcbiAgICAgIH0pKTtcblxuICAgICAgLy8gVHJhY2sgdGhlIHVwZGF0ZWQgZmlsZSBwb3NpdGlvblxuICAgICAgaWYgKGN1cnJlbnQuYWRkZWQpIHtcbiAgICAgICAgbmV3TGluZSArPSBsaW5lcy5sZW5ndGg7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBvbGRMaW5lICs9IGxpbmVzLmxlbmd0aDtcbiAgICAgIH1cbiAgICB9IGVsc2Uge1xuICAgICAgLy8gSWRlbnRpY2FsIGNvbnRleHQgbGluZXMuIFRyYWNrIGxpbmUgY2hhbmdlc1xuICAgICAgaWYgKG9sZFJhbmdlU3RhcnQpIHtcbiAgICAgICAgLy8gQ2xvc2Ugb3V0IGFueSBjaGFuZ2VzIHRoYXQgaGF2ZSBiZWVuIG91dHB1dCAob3Igam9pbiBvdmVybGFwcGluZylcbiAgICAgICAgaWYgKGxpbmVzLmxlbmd0aCA8PSBvcHRpb25zLmNvbnRleHQgKiAyICYmIGkgPCBkaWZmLmxlbmd0aCAtIDIpIHtcbiAgICAgICAgICAvLyBPdmVybGFwcGluZ1xuICAgICAgICAgIGN1clJhbmdlLnB1c2goLi4uIGNvbnRleHRMaW5lcyhsaW5lcykpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIC8vIGVuZCB0aGUgcmFuZ2UgYW5kIG91dHB1dFxuICAgICAgICAgIGxldCBjb250ZXh0U2l6ZSA9IE1hdGgubWluKGxpbmVzLmxlbmd0aCwgb3B0aW9ucy5jb250ZXh0KTtcbiAgICAgICAgICBjdXJSYW5nZS5wdXNoKC4uLiBjb250ZXh0TGluZXMobGluZXMuc2xpY2UoMCwgY29udGV4dFNpemUpKSk7XG5cbiAgICAgICAgICBsZXQgaHVuayA9IHtcbiAgICAgICAgICAgIG9sZFN0YXJ0OiBvbGRSYW5nZVN0YXJ0LFxuICAgICAgICAgICAgb2xkTGluZXM6IChvbGRMaW5lIC0gb2xkUmFuZ2VTdGFydCArIGNvbnRleHRTaXplKSxcbiAgICAgICAgICAgIG5ld1N0YXJ0OiBuZXdSYW5nZVN0YXJ0LFxuICAgICAgICAgICAgbmV3TGluZXM6IChuZXdMaW5lIC0gbmV3UmFuZ2VTdGFydCArIGNvbnRleHRTaXplKSxcbiAgICAgICAgICAgIGxpbmVzOiBjdXJSYW5nZVxuICAgICAgICAgIH07XG4gICAgICAgICAgaWYgKGkgPj0gZGlmZi5sZW5ndGggLSAyICYmIGxpbmVzLmxlbmd0aCA8PSBvcHRpb25zLmNvbnRleHQpIHtcbiAgICAgICAgICAgIC8vIEVPRiBpcyBpbnNpZGUgdGhpcyBodW5rXG4gICAgICAgICAgICBsZXQgb2xkRU9GTmV3bGluZSA9ICgoL1xcbiQvKS50ZXN0KG9sZFN0cikpO1xuICAgICAgICAgICAgbGV0IG5ld0VPRk5ld2xpbmUgPSAoKC9cXG4kLykudGVzdChuZXdTdHIpKTtcbiAgICAgICAgICAgIGxldCBub05sQmVmb3JlQWRkcyA9IGxpbmVzLmxlbmd0aCA9PSAwICYmIGN1clJhbmdlLmxlbmd0aCA+IGh1bmsub2xkTGluZXM7XG4gICAgICAgICAgICBpZiAoIW9sZEVPRk5ld2xpbmUgJiYgbm9ObEJlZm9yZUFkZHMgJiYgb2xkU3RyLmxlbmd0aCA+IDApIHtcbiAgICAgICAgICAgICAgLy8gc3BlY2lhbCBjYXNlOiBvbGQgaGFzIG5vIGVvbCBhbmQgbm8gdHJhaWxpbmcgY29udGV4dDsgbm8tbmwgY2FuIGVuZCB1cCBiZWZvcmUgYWRkc1xuICAgICAgICAgICAgICAvLyBob3dldmVyLCBpZiB0aGUgb2xkIGZpbGUgaXMgZW1wdHksIGRvIG5vdCBvdXRwdXQgdGhlIG5vLW5sIGxpbmVcbiAgICAgICAgICAgICAgY3VyUmFuZ2Uuc3BsaWNlKGh1bmsub2xkTGluZXMsIDAsICdcXFxcIE5vIG5ld2xpbmUgYXQgZW5kIG9mIGZpbGUnKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGlmICgoIW9sZEVPRk5ld2xpbmUgJiYgIW5vTmxCZWZvcmVBZGRzKSB8fCAhbmV3RU9GTmV3bGluZSkge1xuICAgICAgICAgICAgICBjdXJSYW5nZS5wdXNoKCdcXFxcIE5vIG5ld2xpbmUgYXQgZW5kIG9mIGZpbGUnKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICB9XG4gICAgICAgICAgaHVua3MucHVzaChodW5rKTtcblxuICAgICAgICAgIG9sZFJhbmdlU3RhcnQgPSAwO1xuICAgICAgICAgIG5ld1JhbmdlU3RhcnQgPSAwO1xuICAgICAgICAgIGN1clJhbmdlID0gW107XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICAgIG9sZExpbmUgKz0gbGluZXMubGVuZ3RoO1xuICAgICAgbmV3TGluZSArPSBsaW5lcy5sZW5ndGg7XG4gICAgfVxuICB9XG5cbiAgcmV0dXJuIHtcbiAgICBvbGRGaWxlTmFtZTogb2xkRmlsZU5hbWUsIG5ld0ZpbGVOYW1lOiBuZXdGaWxlTmFtZSxcbiAgICBvbGRIZWFkZXI6IG9sZEhlYWRlciwgbmV3SGVhZGVyOiBuZXdIZWFkZXIsXG4gICAgaHVua3M6IGh1bmtzXG4gIH07XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBmb3JtYXRQYXRjaChkaWZmKSB7XG4gIGlmIChBcnJheS5pc0FycmF5KGRpZmYpKSB7XG4gICAgcmV0dXJuIGRpZmYubWFwKGZvcm1hdFBhdGNoKS5qb2luKCdcXG4nKTtcbiAgfVxuXG4gIGNvbnN0IHJldCA9IFtdO1xuICBpZiAoZGlmZi5vbGRGaWxlTmFtZSA9PSBkaWZmLm5ld0ZpbGVOYW1lKSB7XG4gICAgcmV0LnB1c2goJ0luZGV4OiAnICsgZGlmZi5vbGRGaWxlTmFtZSk7XG4gIH1cbiAgcmV0LnB1c2goJz09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0nKTtcbiAgcmV0LnB1c2goJy0tLSAnICsgZGlmZi5vbGRGaWxlTmFtZSArICh0eXBlb2YgZGlmZi5vbGRIZWFkZXIgPT09ICd1bmRlZmluZWQnID8gJycgOiAnXFx0JyArIGRpZmYub2xkSGVhZGVyKSk7XG4gIHJldC5wdXNoKCcrKysgJyArIGRpZmYubmV3RmlsZU5hbWUgKyAodHlwZW9mIGRpZmYubmV3SGVhZGVyID09PSAndW5kZWZpbmVkJyA/ICcnIDogJ1xcdCcgKyBkaWZmLm5ld0hlYWRlcikpO1xuXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgZGlmZi5odW5rcy5sZW5ndGg7IGkrKykge1xuICAgIGNvbnN0IGh1bmsgPSBkaWZmLmh1bmtzW2ldO1xuICAgIC8vIFVuaWZpZWQgRGlmZiBGb3JtYXQgcXVpcms6IElmIHRoZSBjaHVuayBzaXplIGlzIDAsXG4gICAgLy8gdGhlIGZpcnN0IG51bWJlciBpcyBvbmUgbG93ZXIgdGhhbiBvbmUgd291bGQgZXhwZWN0LlxuICAgIC8vIGh0dHBzOi8vd3d3LmFydGltYS5jb20vd2VibG9ncy92aWV3cG9zdC5qc3A/dGhyZWFkPTE2NDI5M1xuICAgIGlmIChodW5rLm9sZExpbmVzID09PSAwKSB7XG4gICAgICBodW5rLm9sZFN0YXJ0IC09IDE7XG4gICAgfVxuICAgIGlmIChodW5rLm5ld0xpbmVzID09PSAwKSB7XG4gICAgICBodW5rLm5ld1N0YXJ0IC09IDE7XG4gICAgfVxuICAgIHJldC5wdXNoKFxuICAgICAgJ0BAIC0nICsgaHVuay5vbGRTdGFydCArICcsJyArIGh1bmsub2xkTGluZXNcbiAgICAgICsgJyArJyArIGh1bmsubmV3U3RhcnQgKyAnLCcgKyBodW5rLm5ld0xpbmVzXG4gICAgICArICcgQEAnXG4gICAgKTtcbiAgICByZXQucHVzaC5hcHBseShyZXQsIGh1bmsubGluZXMpO1xuICB9XG5cbiAgcmV0dXJuIHJldC5qb2luKCdcXG4nKSArICdcXG4nO1xufVxuXG5leHBvcnQgZnVuY3Rpb24gY3JlYXRlVHdvRmlsZXNQYXRjaChvbGRGaWxlTmFtZSwgbmV3RmlsZU5hbWUsIG9sZFN0ciwgbmV3U3RyLCBvbGRIZWFkZXIsIG5ld0hlYWRlciwgb3B0aW9ucykge1xuICByZXR1cm4gZm9ybWF0UGF0Y2goc3RydWN0dXJlZFBhdGNoKG9sZEZpbGVOYW1lLCBuZXdGaWxlTmFtZSwgb2xkU3RyLCBuZXdTdHIsIG9sZEhlYWRlciwgbmV3SGVhZGVyLCBvcHRpb25zKSk7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBjcmVhdGVQYXRjaChmaWxlTmFtZSwgb2xkU3RyLCBuZXdTdHIsIG9sZEhlYWRlciwgbmV3SGVhZGVyLCBvcHRpb25zKSB7XG4gIHJldHVybiBjcmVhdGVUd29GaWxlc1BhdGNoKGZpbGVOYW1lLCBmaWxlTmFtZSwgb2xkU3RyLCBuZXdTdHIsIG9sZEhlYWRlciwgbmV3SGVhZGVyLCBvcHRpb25zKTtcbn1cbiJdfQ== diff --git a/node_modules/diff/lib/patch/merge.js b/node_modules/diff/lib/patch/merge.js deleted file mode 100644 index b46faaaba8e8b..0000000000000 --- a/node_modules/diff/lib/patch/merge.js +++ /dev/null @@ -1,613 +0,0 @@ -/*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" && Symbol.iterator in Object(iter)) 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) { - /*istanbul ignore start*/ - var _calcOldNewLineCount = - /*istanbul ignore end*/ - 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 ( - /*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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9tZXJnZS5qcyJdLCJuYW1lcyI6WyJjYWxjTGluZUNvdW50IiwiaHVuayIsImNhbGNPbGROZXdMaW5lQ291bnQiLCJsaW5lcyIsIm9sZExpbmVzIiwibmV3TGluZXMiLCJ1bmRlZmluZWQiLCJtZXJnZSIsIm1pbmUiLCJ0aGVpcnMiLCJiYXNlIiwibG9hZFBhdGNoIiwicmV0IiwiaW5kZXgiLCJuZXdGaWxlTmFtZSIsImZpbGVOYW1lQ2hhbmdlZCIsIm9sZEZpbGVOYW1lIiwib2xkSGVhZGVyIiwibmV3SGVhZGVyIiwic2VsZWN0RmllbGQiLCJodW5rcyIsIm1pbmVJbmRleCIsInRoZWlyc0luZGV4IiwibWluZU9mZnNldCIsInRoZWlyc09mZnNldCIsImxlbmd0aCIsIm1pbmVDdXJyZW50Iiwib2xkU3RhcnQiLCJJbmZpbml0eSIsInRoZWlyc0N1cnJlbnQiLCJodW5rQmVmb3JlIiwicHVzaCIsImNsb25lSHVuayIsIm1lcmdlZEh1bmsiLCJNYXRoIiwibWluIiwibmV3U3RhcnQiLCJtZXJnZUxpbmVzIiwicGFyYW0iLCJ0ZXN0IiwicGFyc2VQYXRjaCIsIkVycm9yIiwic3RydWN0dXJlZFBhdGNoIiwicGF0Y2giLCJjb25mbGljdCIsImNoZWNrIiwib2Zmc2V0IiwibWluZUxpbmVzIiwidGhlaXJPZmZzZXQiLCJ0aGVpckxpbmVzIiwidGhlaXIiLCJpbnNlcnRMZWFkaW5nIiwidGhlaXJDdXJyZW50IiwibXV0dWFsQ2hhbmdlIiwiY29sbGVjdENoYW5nZSIsInJlbW92YWwiLCJpbnNlcnRUcmFpbGluZyIsIm15Q2hhbmdlcyIsInRoZWlyQ2hhbmdlcyIsImFsbFJlbW92ZXMiLCJhcnJheVN0YXJ0c1dpdGgiLCJza2lwUmVtb3ZlU3VwZXJzZXQiLCJhcnJheUVxdWFsIiwic3dhcCIsImNvbGxlY3RDb250ZXh0IiwibWVyZ2VkIiwiaW5zZXJ0IiwibGluZSIsInN0YXRlIiwib3BlcmF0aW9uIiwibWF0Y2hDaGFuZ2VzIiwiY2hhbmdlcyIsIm1hdGNoSW5kZXgiLCJjb250ZXh0Q2hhbmdlcyIsImNvbmZsaWN0ZWQiLCJjaGFuZ2UiLCJtYXRjaCIsInN1YnN0ciIsInJlZHVjZSIsInByZXYiLCJyZW1vdmVDaGFuZ2VzIiwiZGVsdGEiLCJpIiwiY2hhbmdlQ29udGVudCIsImZvckVhY2giLCJteUNvdW50IiwidGhlaXJDb3VudCJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7OztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQTs7QUFFQTtBQUFBO0FBQUE7QUFBQTtBQUFBOzs7Ozs7Ozs7Ozs7Ozs7QUFFTyxTQUFTQSxhQUFULENBQXVCQyxJQUF2QixFQUE2QjtBQUFBO0FBQUE7QUFBQTtBQUNMQyxFQUFBQSxtQkFBbUIsQ0FBQ0QsSUFBSSxDQUFDRSxLQUFOLENBRGQ7QUFBQSxNQUMzQkMsUUFEMkIsd0JBQzNCQSxRQUQyQjtBQUFBLE1BQ2pCQyxRQURpQix3QkFDakJBLFFBRGlCOztBQUdsQyxNQUFJRCxRQUFRLEtBQUtFLFNBQWpCLEVBQTRCO0FBQzFCTCxJQUFBQSxJQUFJLENBQUNHLFFBQUwsR0FBZ0JBLFFBQWhCO0FBQ0QsR0FGRCxNQUVPO0FBQ0wsV0FBT0gsSUFBSSxDQUFDRyxRQUFaO0FBQ0Q7O0FBRUQsTUFBSUMsUUFBUSxLQUFLQyxTQUFqQixFQUE0QjtBQUMxQkwsSUFBQUEsSUFBSSxDQUFDSSxRQUFMLEdBQWdCQSxRQUFoQjtBQUNELEdBRkQsTUFFTztBQUNMLFdBQU9KLElBQUksQ0FBQ0ksUUFBWjtBQUNEO0FBQ0Y7O0FBRU0sU0FBU0UsS0FBVCxDQUFlQyxJQUFmLEVBQXFCQyxNQUFyQixFQUE2QkMsSUFBN0IsRUFBbUM7QUFDeENGLEVBQUFBLElBQUksR0FBR0csU0FBUyxDQUFDSCxJQUFELEVBQU9FLElBQVAsQ0FBaEI7QUFDQUQsRUFBQUEsTUFBTSxHQUFHRSxTQUFTLENBQUNGLE1BQUQsRUFBU0MsSUFBVCxDQUFsQjtBQUVBLE1BQUlFLEdBQUcsR0FBRyxFQUFWLENBSndDLENBTXhDO0FBQ0E7QUFDQTs7QUFDQSxNQUFJSixJQUFJLENBQUNLLEtBQUwsSUFBY0osTUFBTSxDQUFDSSxLQUF6QixFQUFnQztBQUM5QkQsSUFBQUEsR0FBRyxDQUFDQyxLQUFKLEdBQVlMLElBQUksQ0FBQ0ssS0FBTCxJQUFjSixNQUFNLENBQUNJLEtBQWpDO0FBQ0Q7O0FBRUQsTUFBSUwsSUFBSSxDQUFDTSxXQUFMLElBQW9CTCxNQUFNLENBQUNLLFdBQS9CLEVBQTRDO0FBQzFDLFFBQUksQ0FBQ0MsZUFBZSxDQUFDUCxJQUFELENBQXBCLEVBQTRCO0FBQzFCO0FBQ0FJLE1BQUFBLEdBQUcsQ0FBQ0ksV0FBSixHQUFrQlAsTUFBTSxDQUFDTyxXQUFQLElBQXNCUixJQUFJLENBQUNRLFdBQTdDO0FBQ0FKLE1BQUFBLEdBQUcsQ0FBQ0UsV0FBSixHQUFrQkwsTUFBTSxDQUFDSyxXQUFQLElBQXNCTixJQUFJLENBQUNNLFdBQTdDO0FBQ0FGLE1BQUFBLEdBQUcsQ0FBQ0ssU0FBSixHQUFnQlIsTUFBTSxDQUFDUSxTQUFQLElBQW9CVCxJQUFJLENBQUNTLFNBQXpDO0FBQ0FMLE1BQUFBLEdBQUcsQ0FBQ00sU0FBSixHQUFnQlQsTUFBTSxDQUFDUyxTQUFQLElBQW9CVixJQUFJLENBQUNVLFNBQXpDO0FBQ0QsS0FORCxNQU1PLElBQUksQ0FBQ0gsZUFBZSxDQUFDTixNQUFELENBQXBCLEVBQThCO0FBQ25DO0FBQ0FHLE1BQUFBLEdBQUcsQ0FBQ0ksV0FBSixHQUFrQlIsSUFBSSxDQUFDUSxXQUF2QjtBQUNBSixNQUFBQSxHQUFHLENBQUNFLFdBQUosR0FBa0JOLElBQUksQ0FBQ00sV0FBdkI7QUFDQUYsTUFBQUEsR0FBRyxDQUFDSyxTQUFKLEdBQWdCVCxJQUFJLENBQUNTLFNBQXJCO0FBQ0FMLE1BQUFBLEdBQUcsQ0FBQ00sU0FBSixHQUFnQlYsSUFBSSxDQUFDVSxTQUFyQjtBQUNELEtBTk0sTUFNQTtBQUNMO0FBQ0FOLE1BQUFBLEdBQUcsQ0FBQ0ksV0FBSixHQUFrQkcsV0FBVyxDQUFDUCxHQUFELEVBQU1KLElBQUksQ0FBQ1EsV0FBWCxFQUF3QlAsTUFBTSxDQUFDTyxXQUEvQixDQUE3QjtBQUNBSixNQUFBQSxHQUFHLENBQUNFLFdBQUosR0FBa0JLLFdBQVcsQ0FBQ1AsR0FBRCxFQUFNSixJQUFJLENBQUNNLFdBQVgsRUFBd0JMLE1BQU0sQ0FBQ0ssV0FBL0IsQ0FBN0I7QUFDQUYsTUFBQUEsR0FBRyxDQUFDSyxTQUFKLEdBQWdCRSxXQUFXLENBQUNQLEdBQUQsRUFBTUosSUFBSSxDQUFDUyxTQUFYLEVBQXNCUixNQUFNLENBQUNRLFNBQTdCLENBQTNCO0FBQ0FMLE1BQUFBLEdBQUcsQ0FBQ00sU0FBSixHQUFnQkMsV0FBVyxDQUFDUCxHQUFELEVBQU1KLElBQUksQ0FBQ1UsU0FBWCxFQUFzQlQsTUFBTSxDQUFDUyxTQUE3QixDQUEzQjtBQUNEO0FBQ0Y7O0FBRUROLEVBQUFBLEdBQUcsQ0FBQ1EsS0FBSixHQUFZLEVBQVo7QUFFQSxNQUFJQyxTQUFTLEdBQUcsQ0FBaEI7QUFBQSxNQUNJQyxXQUFXLEdBQUcsQ0FEbEI7QUFBQSxNQUVJQyxVQUFVLEdBQUcsQ0FGakI7QUFBQSxNQUdJQyxZQUFZLEdBQUcsQ0FIbkI7O0FBS0EsU0FBT0gsU0FBUyxHQUFHYixJQUFJLENBQUNZLEtBQUwsQ0FBV0ssTUFBdkIsSUFBaUNILFdBQVcsR0FBR2IsTUFBTSxDQUFDVyxLQUFQLENBQWFLLE1BQW5FLEVBQTJFO0FBQ3pFLFFBQUlDLFdBQVcsR0FBR2xCLElBQUksQ0FBQ1ksS0FBTCxDQUFXQyxTQUFYLEtBQXlCO0FBQUNNLE1BQUFBLFFBQVEsRUFBRUM7QUFBWCxLQUEzQztBQUFBLFFBQ0lDLGFBQWEsR0FBR3BCLE1BQU0sQ0FBQ1csS0FBUCxDQUFhRSxXQUFiLEtBQTZCO0FBQUNLLE1BQUFBLFFBQVEsRUFBRUM7QUFBWCxLQURqRDs7QUFHQSxRQUFJRSxVQUFVLENBQUNKLFdBQUQsRUFBY0csYUFBZCxDQUFkLEVBQTRDO0FBQzFDO0FBQ0FqQixNQUFBQSxHQUFHLENBQUNRLEtBQUosQ0FBVVcsSUFBVixDQUFlQyxTQUFTLENBQUNOLFdBQUQsRUFBY0gsVUFBZCxDQUF4QjtBQUNBRixNQUFBQSxTQUFTO0FBQ1RHLE1BQUFBLFlBQVksSUFBSUUsV0FBVyxDQUFDckIsUUFBWixHQUF1QnFCLFdBQVcsQ0FBQ3RCLFFBQW5EO0FBQ0QsS0FMRCxNQUtPLElBQUkwQixVQUFVLENBQUNELGFBQUQsRUFBZ0JILFdBQWhCLENBQWQsRUFBNEM7QUFDakQ7QUFDQWQsTUFBQUEsR0FBRyxDQUFDUSxLQUFKLENBQVVXLElBQVYsQ0FBZUMsU0FBUyxDQUFDSCxhQUFELEVBQWdCTCxZQUFoQixDQUF4QjtBQUNBRixNQUFBQSxXQUFXO0FBQ1hDLE1BQUFBLFVBQVUsSUFBSU0sYUFBYSxDQUFDeEIsUUFBZCxHQUF5QndCLGFBQWEsQ0FBQ3pCLFFBQXJEO0FBQ0QsS0FMTSxNQUtBO0FBQ0w7QUFDQSxVQUFJNkIsVUFBVSxHQUFHO0FBQ2ZOLFFBQUFBLFFBQVEsRUFBRU8sSUFBSSxDQUFDQyxHQUFMLENBQVNULFdBQVcsQ0FBQ0MsUUFBckIsRUFBK0JFLGFBQWEsQ0FBQ0YsUUFBN0MsQ0FESztBQUVmdkIsUUFBQUEsUUFBUSxFQUFFLENBRks7QUFHZmdDLFFBQUFBLFFBQVEsRUFBRUYsSUFBSSxDQUFDQyxHQUFMLENBQVNULFdBQVcsQ0FBQ1UsUUFBWixHQUF1QmIsVUFBaEMsRUFBNENNLGFBQWEsQ0FBQ0YsUUFBZCxHQUF5QkgsWUFBckUsQ0FISztBQUlmbkIsUUFBQUEsUUFBUSxFQUFFLENBSks7QUFLZkYsUUFBQUEsS0FBSyxFQUFFO0FBTFEsT0FBakI7QUFPQWtDLE1BQUFBLFVBQVUsQ0FBQ0osVUFBRCxFQUFhUCxXQUFXLENBQUNDLFFBQXpCLEVBQW1DRCxXQUFXLENBQUN2QixLQUEvQyxFQUFzRDBCLGFBQWEsQ0FBQ0YsUUFBcEUsRUFBOEVFLGFBQWEsQ0FBQzFCLEtBQTVGLENBQVY7QUFDQW1CLE1BQUFBLFdBQVc7QUFDWEQsTUFBQUEsU0FBUztBQUVUVCxNQUFBQSxHQUFHLENBQUNRLEtBQUosQ0FBVVcsSUFBVixDQUFlRSxVQUFmO0FBQ0Q7QUFDRjs7QUFFRCxTQUFPckIsR0FBUDtBQUNEOztBQUVELFNBQVNELFNBQVQsQ0FBbUIyQixLQUFuQixFQUEwQjVCLElBQTFCLEVBQWdDO0FBQzlCLE1BQUksT0FBTzRCLEtBQVAsS0FBaUIsUUFBckIsRUFBK0I7QUFDN0IsUUFBSyxNQUFELENBQVNDLElBQVQsQ0FBY0QsS0FBZCxLQUEwQixVQUFELENBQWFDLElBQWIsQ0FBa0JELEtBQWxCLENBQTdCLEVBQXdEO0FBQ3RELGFBQU87QUFBQTtBQUFBO0FBQUE7O0FBQUFFO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUE7QUFBQSxTQUFXRixLQUFYLEVBQWtCLENBQWxCO0FBQVA7QUFDRDs7QUFFRCxRQUFJLENBQUM1QixJQUFMLEVBQVc7QUFDVCxZQUFNLElBQUkrQixLQUFKLENBQVUsa0RBQVYsQ0FBTjtBQUNEOztBQUNELFdBQU87QUFBQTtBQUFBO0FBQUE7O0FBQUFDO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUE7QUFBQSxPQUFnQnBDLFNBQWhCLEVBQTJCQSxTQUEzQixFQUFzQ0ksSUFBdEMsRUFBNEM0QixLQUE1QztBQUFQO0FBQ0Q7O0FBRUQsU0FBT0EsS0FBUDtBQUNEOztBQUVELFNBQVN2QixlQUFULENBQXlCNEIsS0FBekIsRUFBZ0M7QUFDOUIsU0FBT0EsS0FBSyxDQUFDN0IsV0FBTixJQUFxQjZCLEtBQUssQ0FBQzdCLFdBQU4sS0FBc0I2QixLQUFLLENBQUMzQixXQUF4RDtBQUNEOztBQUVELFNBQVNHLFdBQVQsQ0FBcUJOLEtBQXJCLEVBQTRCTCxJQUE1QixFQUFrQ0MsTUFBbEMsRUFBMEM7QUFDeEMsTUFBSUQsSUFBSSxLQUFLQyxNQUFiLEVBQXFCO0FBQ25CLFdBQU9ELElBQVA7QUFDRCxHQUZELE1BRU87QUFDTEssSUFBQUEsS0FBSyxDQUFDK0IsUUFBTixHQUFpQixJQUFqQjtBQUNBLFdBQU87QUFBQ3BDLE1BQUFBLElBQUksRUFBSkEsSUFBRDtBQUFPQyxNQUFBQSxNQUFNLEVBQU5BO0FBQVAsS0FBUDtBQUNEO0FBQ0Y7O0FBRUQsU0FBU3FCLFVBQVQsQ0FBb0JTLElBQXBCLEVBQTBCTSxLQUExQixFQUFpQztBQUMvQixTQUFPTixJQUFJLENBQUNaLFFBQUwsR0FBZ0JrQixLQUFLLENBQUNsQixRQUF0QixJQUNEWSxJQUFJLENBQUNaLFFBQUwsR0FBZ0JZLElBQUksQ0FBQ25DLFFBQXRCLEdBQWtDeUMsS0FBSyxDQUFDbEIsUUFEN0M7QUFFRDs7QUFFRCxTQUFTSyxTQUFULENBQW1CL0IsSUFBbkIsRUFBeUI2QyxNQUF6QixFQUFpQztBQUMvQixTQUFPO0FBQ0xuQixJQUFBQSxRQUFRLEVBQUUxQixJQUFJLENBQUMwQixRQURWO0FBQ29CdkIsSUFBQUEsUUFBUSxFQUFFSCxJQUFJLENBQUNHLFFBRG5DO0FBRUxnQyxJQUFBQSxRQUFRLEVBQUVuQyxJQUFJLENBQUNtQyxRQUFMLEdBQWdCVSxNQUZyQjtBQUU2QnpDLElBQUFBLFFBQVEsRUFBRUosSUFBSSxDQUFDSSxRQUY1QztBQUdMRixJQUFBQSxLQUFLLEVBQUVGLElBQUksQ0FBQ0U7QUFIUCxHQUFQO0FBS0Q7O0FBRUQsU0FBU2tDLFVBQVQsQ0FBb0JwQyxJQUFwQixFQUEwQnNCLFVBQTFCLEVBQXNDd0IsU0FBdEMsRUFBaURDLFdBQWpELEVBQThEQyxVQUE5RCxFQUEwRTtBQUN4RTtBQUNBO0FBQ0EsTUFBSXpDLElBQUksR0FBRztBQUFDc0MsSUFBQUEsTUFBTSxFQUFFdkIsVUFBVDtBQUFxQnBCLElBQUFBLEtBQUssRUFBRTRDLFNBQTVCO0FBQXVDbEMsSUFBQUEsS0FBSyxFQUFFO0FBQTlDLEdBQVg7QUFBQSxNQUNJcUMsS0FBSyxHQUFHO0FBQUNKLElBQUFBLE1BQU0sRUFBRUUsV0FBVDtBQUFzQjdDLElBQUFBLEtBQUssRUFBRThDLFVBQTdCO0FBQXlDcEMsSUFBQUEsS0FBSyxFQUFFO0FBQWhELEdBRFosQ0FId0UsQ0FNeEU7O0FBQ0FzQyxFQUFBQSxhQUFhLENBQUNsRCxJQUFELEVBQU9PLElBQVAsRUFBYTBDLEtBQWIsQ0FBYjtBQUNBQyxFQUFBQSxhQUFhLENBQUNsRCxJQUFELEVBQU9pRCxLQUFQLEVBQWMxQyxJQUFkLENBQWIsQ0FSd0UsQ0FVeEU7O0FBQ0EsU0FBT0EsSUFBSSxDQUFDSyxLQUFMLEdBQWFMLElBQUksQ0FBQ0wsS0FBTCxDQUFXc0IsTUFBeEIsSUFBa0N5QixLQUFLLENBQUNyQyxLQUFOLEdBQWNxQyxLQUFLLENBQUMvQyxLQUFOLENBQVlzQixNQUFuRSxFQUEyRTtBQUN6RSxRQUFJQyxXQUFXLEdBQUdsQixJQUFJLENBQUNMLEtBQUwsQ0FBV0ssSUFBSSxDQUFDSyxLQUFoQixDQUFsQjtBQUFBLFFBQ0l1QyxZQUFZLEdBQUdGLEtBQUssQ0FBQy9DLEtBQU4sQ0FBWStDLEtBQUssQ0FBQ3JDLEtBQWxCLENBRG5COztBQUdBLFFBQUksQ0FBQ2EsV0FBVyxDQUFDLENBQUQsQ0FBWCxLQUFtQixHQUFuQixJQUEwQkEsV0FBVyxDQUFDLENBQUQsQ0FBWCxLQUFtQixHQUE5QyxNQUNJMEIsWUFBWSxDQUFDLENBQUQsQ0FBWixLQUFvQixHQUFwQixJQUEyQkEsWUFBWSxDQUFDLENBQUQsQ0FBWixLQUFvQixHQURuRCxDQUFKLEVBQzZEO0FBQzNEO0FBQ0FDLE1BQUFBLFlBQVksQ0FBQ3BELElBQUQsRUFBT08sSUFBUCxFQUFhMEMsS0FBYixDQUFaO0FBQ0QsS0FKRCxNQUlPLElBQUl4QixXQUFXLENBQUMsQ0FBRCxDQUFYLEtBQW1CLEdBQW5CLElBQTBCMEIsWUFBWSxDQUFDLENBQUQsQ0FBWixLQUFvQixHQUFsRCxFQUF1RDtBQUFBO0FBQUE7O0FBQUE7QUFDNUQ7O0FBQ0E7O0FBQUE7O0FBQUE7QUFBQTtBQUFBO0FBQUFuRCxNQUFBQSxJQUFJLENBQUNFLEtBQUwsRUFBVzRCLElBQVg7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFvQnVCLE1BQUFBLGFBQWEsQ0FBQzlDLElBQUQsQ0FBakM7QUFDRCxLQUhNLE1BR0EsSUFBSTRDLFlBQVksQ0FBQyxDQUFELENBQVosS0FBb0IsR0FBcEIsSUFBMkIxQixXQUFXLENBQUMsQ0FBRCxDQUFYLEtBQW1CLEdBQWxELEVBQXVEO0FBQUE7QUFBQTs7QUFBQTtBQUM1RDs7QUFDQTs7QUFBQTs7QUFBQTtBQUFBO0FBQUE7QUFBQXpCLE1BQUFBLElBQUksQ0FBQ0UsS0FBTCxFQUFXNEIsSUFBWDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQW9CdUIsTUFBQUEsYUFBYSxDQUFDSixLQUFELENBQWpDO0FBQ0QsS0FITSxNQUdBLElBQUl4QixXQUFXLENBQUMsQ0FBRCxDQUFYLEtBQW1CLEdBQW5CLElBQTBCMEIsWUFBWSxDQUFDLENBQUQsQ0FBWixLQUFvQixHQUFsRCxFQUF1RDtBQUM1RDtBQUNBRyxNQUFBQSxPQUFPLENBQUN0RCxJQUFELEVBQU9PLElBQVAsRUFBYTBDLEtBQWIsQ0FBUDtBQUNELEtBSE0sTUFHQSxJQUFJRSxZQUFZLENBQUMsQ0FBRCxDQUFaLEtBQW9CLEdBQXBCLElBQTJCMUIsV0FBVyxDQUFDLENBQUQsQ0FBWCxLQUFtQixHQUFsRCxFQUF1RDtBQUM1RDtBQUNBNkIsTUFBQUEsT0FBTyxDQUFDdEQsSUFBRCxFQUFPaUQsS0FBUCxFQUFjMUMsSUFBZCxFQUFvQixJQUFwQixDQUFQO0FBQ0QsS0FITSxNQUdBLElBQUlrQixXQUFXLEtBQUswQixZQUFwQixFQUFrQztBQUN2QztBQUNBbkQsTUFBQUEsSUFBSSxDQUFDRSxLQUFMLENBQVc0QixJQUFYLENBQWdCTCxXQUFoQjtBQUNBbEIsTUFBQUEsSUFBSSxDQUFDSyxLQUFMO0FBQ0FxQyxNQUFBQSxLQUFLLENBQUNyQyxLQUFOO0FBQ0QsS0FMTSxNQUtBO0FBQ0w7QUFDQStCLE1BQUFBLFFBQVEsQ0FBQzNDLElBQUQsRUFBT3FELGFBQWEsQ0FBQzlDLElBQUQsQ0FBcEIsRUFBNEI4QyxhQUFhLENBQUNKLEtBQUQsQ0FBekMsQ0FBUjtBQUNEO0FBQ0YsR0F4Q3VFLENBMEN4RTs7O0FBQ0FNLEVBQUFBLGNBQWMsQ0FBQ3ZELElBQUQsRUFBT08sSUFBUCxDQUFkO0FBQ0FnRCxFQUFBQSxjQUFjLENBQUN2RCxJQUFELEVBQU9pRCxLQUFQLENBQWQ7QUFFQWxELEVBQUFBLGFBQWEsQ0FBQ0MsSUFBRCxDQUFiO0FBQ0Q7O0FBRUQsU0FBU29ELFlBQVQsQ0FBc0JwRCxJQUF0QixFQUE0Qk8sSUFBNUIsRUFBa0MwQyxLQUFsQyxFQUF5QztBQUN2QyxNQUFJTyxTQUFTLEdBQUdILGFBQWEsQ0FBQzlDLElBQUQsQ0FBN0I7QUFBQSxNQUNJa0QsWUFBWSxHQUFHSixhQUFhLENBQUNKLEtBQUQsQ0FEaEM7O0FBR0EsTUFBSVMsVUFBVSxDQUFDRixTQUFELENBQVYsSUFBeUJFLFVBQVUsQ0FBQ0QsWUFBRCxDQUF2QyxFQUF1RDtBQUNyRDtBQUNBO0FBQUk7QUFBQTtBQUFBOztBQUFBRTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBO0FBQUEsS0FBZ0JILFNBQWhCLEVBQTJCQyxZQUEzQixLQUNHRyxrQkFBa0IsQ0FBQ1gsS0FBRCxFQUFRTyxTQUFSLEVBQW1CQSxTQUFTLENBQUNoQyxNQUFWLEdBQW1CaUMsWUFBWSxDQUFDakMsTUFBbkQsQ0FEekIsRUFDcUY7QUFBQTtBQUFBOztBQUFBOztBQUNuRjs7QUFBQTs7QUFBQTtBQUFBO0FBQUE7QUFBQXhCLE1BQUFBLElBQUksQ0FBQ0UsS0FBTCxFQUFXNEIsSUFBWDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQW9CMEIsTUFBQUEsU0FBcEI7O0FBQ0E7QUFDRCxLQUpELE1BSU87QUFBSTtBQUFBO0FBQUE7O0FBQUFHO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUE7QUFBQSxLQUFnQkYsWUFBaEIsRUFBOEJELFNBQTlCLEtBQ0pJLGtCQUFrQixDQUFDckQsSUFBRCxFQUFPa0QsWUFBUCxFQUFxQkEsWUFBWSxDQUFDakMsTUFBYixHQUFzQmdDLFNBQVMsQ0FBQ2hDLE1BQXJELENBRGxCLEVBQ2dGO0FBQUE7QUFBQTs7QUFBQTs7QUFDckY7O0FBQUE7O0FBQUE7QUFBQTtBQUFBO0FBQUF4QixNQUFBQSxJQUFJLENBQUNFLEtBQUwsRUFBVzRCLElBQVg7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFvQjJCLE1BQUFBLFlBQXBCOztBQUNBO0FBQ0Q7QUFDRixHQVhELE1BV087QUFBSTtBQUFBO0FBQUE7O0FBQUFJO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUE7QUFBQSxHQUFXTCxTQUFYLEVBQXNCQyxZQUF0QixDQUFKLEVBQXlDO0FBQUE7QUFBQTs7QUFBQTs7QUFDOUM7O0FBQUE7O0FBQUE7QUFBQTtBQUFBO0FBQUF6RCxJQUFBQSxJQUFJLENBQUNFLEtBQUwsRUFBVzRCLElBQVg7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFvQjBCLElBQUFBLFNBQXBCOztBQUNBO0FBQ0Q7O0FBRURiLEVBQUFBLFFBQVEsQ0FBQzNDLElBQUQsRUFBT3dELFNBQVAsRUFBa0JDLFlBQWxCLENBQVI7QUFDRDs7QUFFRCxTQUFTSCxPQUFULENBQWlCdEQsSUFBakIsRUFBdUJPLElBQXZCLEVBQTZCMEMsS0FBN0IsRUFBb0NhLElBQXBDLEVBQTBDO0FBQ3hDLE1BQUlOLFNBQVMsR0FBR0gsYUFBYSxDQUFDOUMsSUFBRCxDQUE3QjtBQUFBLE1BQ0lrRCxZQUFZLEdBQUdNLGNBQWMsQ0FBQ2QsS0FBRCxFQUFRTyxTQUFSLENBRGpDOztBQUVBLE1BQUlDLFlBQVksQ0FBQ08sTUFBakIsRUFBeUI7QUFBQTtBQUFBOztBQUFBOztBQUN2Qjs7QUFBQTs7QUFBQTtBQUFBO0FBQUE7QUFBQWhFLElBQUFBLElBQUksQ0FBQ0UsS0FBTCxFQUFXNEIsSUFBWDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQW9CMkIsSUFBQUEsWUFBWSxDQUFDTyxNQUFqQztBQUNELEdBRkQsTUFFTztBQUNMckIsSUFBQUEsUUFBUSxDQUFDM0MsSUFBRCxFQUFPOEQsSUFBSSxHQUFHTCxZQUFILEdBQWtCRCxTQUE3QixFQUF3Q00sSUFBSSxHQUFHTixTQUFILEdBQWVDLFlBQTNELENBQVI7QUFDRDtBQUNGOztBQUVELFNBQVNkLFFBQVQsQ0FBa0IzQyxJQUFsQixFQUF3Qk8sSUFBeEIsRUFBOEIwQyxLQUE5QixFQUFxQztBQUNuQ2pELEVBQUFBLElBQUksQ0FBQzJDLFFBQUwsR0FBZ0IsSUFBaEI7QUFDQTNDLEVBQUFBLElBQUksQ0FBQ0UsS0FBTCxDQUFXNEIsSUFBWCxDQUFnQjtBQUNkYSxJQUFBQSxRQUFRLEVBQUUsSUFESTtBQUVkcEMsSUFBQUEsSUFBSSxFQUFFQSxJQUZRO0FBR2RDLElBQUFBLE1BQU0sRUFBRXlDO0FBSE0sR0FBaEI7QUFLRDs7QUFFRCxTQUFTQyxhQUFULENBQXVCbEQsSUFBdkIsRUFBNkJpRSxNQUE3QixFQUFxQ2hCLEtBQXJDLEVBQTRDO0FBQzFDLFNBQU9nQixNQUFNLENBQUNwQixNQUFQLEdBQWdCSSxLQUFLLENBQUNKLE1BQXRCLElBQWdDb0IsTUFBTSxDQUFDckQsS0FBUCxHQUFlcUQsTUFBTSxDQUFDL0QsS0FBUCxDQUFhc0IsTUFBbkUsRUFBMkU7QUFDekUsUUFBSTBDLElBQUksR0FBR0QsTUFBTSxDQUFDL0QsS0FBUCxDQUFhK0QsTUFBTSxDQUFDckQsS0FBUCxFQUFiLENBQVg7QUFDQVosSUFBQUEsSUFBSSxDQUFDRSxLQUFMLENBQVc0QixJQUFYLENBQWdCb0MsSUFBaEI7QUFDQUQsSUFBQUEsTUFBTSxDQUFDcEIsTUFBUDtBQUNEO0FBQ0Y7O0FBQ0QsU0FBU1UsY0FBVCxDQUF3QnZELElBQXhCLEVBQThCaUUsTUFBOUIsRUFBc0M7QUFDcEMsU0FBT0EsTUFBTSxDQUFDckQsS0FBUCxHQUFlcUQsTUFBTSxDQUFDL0QsS0FBUCxDQUFhc0IsTUFBbkMsRUFBMkM7QUFDekMsUUFBSTBDLElBQUksR0FBR0QsTUFBTSxDQUFDL0QsS0FBUCxDQUFhK0QsTUFBTSxDQUFDckQsS0FBUCxFQUFiLENBQVg7QUFDQVosSUFBQUEsSUFBSSxDQUFDRSxLQUFMLENBQVc0QixJQUFYLENBQWdCb0MsSUFBaEI7QUFDRDtBQUNGOztBQUVELFNBQVNiLGFBQVQsQ0FBdUJjLEtBQXZCLEVBQThCO0FBQzVCLE1BQUl4RCxHQUFHLEdBQUcsRUFBVjtBQUFBLE1BQ0l5RCxTQUFTLEdBQUdELEtBQUssQ0FBQ2pFLEtBQU4sQ0FBWWlFLEtBQUssQ0FBQ3ZELEtBQWxCLEVBQXlCLENBQXpCLENBRGhCOztBQUVBLFNBQU91RCxLQUFLLENBQUN2RCxLQUFOLEdBQWN1RCxLQUFLLENBQUNqRSxLQUFOLENBQVlzQixNQUFqQyxFQUF5QztBQUN2QyxRQUFJMEMsSUFBSSxHQUFHQyxLQUFLLENBQUNqRSxLQUFOLENBQVlpRSxLQUFLLENBQUN2RCxLQUFsQixDQUFYLENBRHVDLENBR3ZDOztBQUNBLFFBQUl3RCxTQUFTLEtBQUssR0FBZCxJQUFxQkYsSUFBSSxDQUFDLENBQUQsQ0FBSixLQUFZLEdBQXJDLEVBQTBDO0FBQ3hDRSxNQUFBQSxTQUFTLEdBQUcsR0FBWjtBQUNEOztBQUVELFFBQUlBLFNBQVMsS0FBS0YsSUFBSSxDQUFDLENBQUQsQ0FBdEIsRUFBMkI7QUFDekJ2RCxNQUFBQSxHQUFHLENBQUNtQixJQUFKLENBQVNvQyxJQUFUO0FBQ0FDLE1BQUFBLEtBQUssQ0FBQ3ZELEtBQU47QUFDRCxLQUhELE1BR087QUFDTDtBQUNEO0FBQ0Y7O0FBRUQsU0FBT0QsR0FBUDtBQUNEOztBQUNELFNBQVNvRCxjQUFULENBQXdCSSxLQUF4QixFQUErQkUsWUFBL0IsRUFBNkM7QUFDM0MsTUFBSUMsT0FBTyxHQUFHLEVBQWQ7QUFBQSxNQUNJTixNQUFNLEdBQUcsRUFEYjtBQUFBLE1BRUlPLFVBQVUsR0FBRyxDQUZqQjtBQUFBLE1BR0lDLGNBQWMsR0FBRyxLQUhyQjtBQUFBLE1BSUlDLFVBQVUsR0FBRyxLQUpqQjs7QUFLQSxTQUFPRixVQUFVLEdBQUdGLFlBQVksQ0FBQzdDLE1BQTFCLElBQ0UyQyxLQUFLLENBQUN2RCxLQUFOLEdBQWN1RCxLQUFLLENBQUNqRSxLQUFOLENBQVlzQixNQURuQyxFQUMyQztBQUN6QyxRQUFJa0QsTUFBTSxHQUFHUCxLQUFLLENBQUNqRSxLQUFOLENBQVlpRSxLQUFLLENBQUN2RCxLQUFsQixDQUFiO0FBQUEsUUFDSStELEtBQUssR0FBR04sWUFBWSxDQUFDRSxVQUFELENBRHhCLENBRHlDLENBSXpDOztBQUNBLFFBQUlJLEtBQUssQ0FBQyxDQUFELENBQUwsS0FBYSxHQUFqQixFQUFzQjtBQUNwQjtBQUNEOztBQUVESCxJQUFBQSxjQUFjLEdBQUdBLGNBQWMsSUFBSUUsTUFBTSxDQUFDLENBQUQsQ0FBTixLQUFjLEdBQWpEO0FBRUFWLElBQUFBLE1BQU0sQ0FBQ2xDLElBQVAsQ0FBWTZDLEtBQVo7QUFDQUosSUFBQUEsVUFBVSxHQVorQixDQWN6QztBQUNBOztBQUNBLFFBQUlHLE1BQU0sQ0FBQyxDQUFELENBQU4sS0FBYyxHQUFsQixFQUF1QjtBQUNyQkQsTUFBQUEsVUFBVSxHQUFHLElBQWI7O0FBRUEsYUFBT0MsTUFBTSxDQUFDLENBQUQsQ0FBTixLQUFjLEdBQXJCLEVBQTBCO0FBQ3hCSixRQUFBQSxPQUFPLENBQUN4QyxJQUFSLENBQWE0QyxNQUFiO0FBQ0FBLFFBQUFBLE1BQU0sR0FBR1AsS0FBSyxDQUFDakUsS0FBTixDQUFZLEVBQUVpRSxLQUFLLENBQUN2RCxLQUFwQixDQUFUO0FBQ0Q7QUFDRjs7QUFFRCxRQUFJK0QsS0FBSyxDQUFDQyxNQUFOLENBQWEsQ0FBYixNQUFvQkYsTUFBTSxDQUFDRSxNQUFQLENBQWMsQ0FBZCxDQUF4QixFQUEwQztBQUN4Q04sTUFBQUEsT0FBTyxDQUFDeEMsSUFBUixDQUFhNEMsTUFBYjtBQUNBUCxNQUFBQSxLQUFLLENBQUN2RCxLQUFOO0FBQ0QsS0FIRCxNQUdPO0FBQ0w2RCxNQUFBQSxVQUFVLEdBQUcsSUFBYjtBQUNEO0FBQ0Y7O0FBRUQsTUFBSSxDQUFDSixZQUFZLENBQUNFLFVBQUQsQ0FBWixJQUE0QixFQUE3QixFQUFpQyxDQUFqQyxNQUF3QyxHQUF4QyxJQUNHQyxjQURQLEVBQ3VCO0FBQ3JCQyxJQUFBQSxVQUFVLEdBQUcsSUFBYjtBQUNEOztBQUVELE1BQUlBLFVBQUosRUFBZ0I7QUFDZCxXQUFPSCxPQUFQO0FBQ0Q7O0FBRUQsU0FBT0MsVUFBVSxHQUFHRixZQUFZLENBQUM3QyxNQUFqQyxFQUF5QztBQUN2Q3dDLElBQUFBLE1BQU0sQ0FBQ2xDLElBQVAsQ0FBWXVDLFlBQVksQ0FBQ0UsVUFBVSxFQUFYLENBQXhCO0FBQ0Q7O0FBRUQsU0FBTztBQUNMUCxJQUFBQSxNQUFNLEVBQU5BLE1BREs7QUFFTE0sSUFBQUEsT0FBTyxFQUFQQTtBQUZLLEdBQVA7QUFJRDs7QUFFRCxTQUFTWixVQUFULENBQW9CWSxPQUFwQixFQUE2QjtBQUMzQixTQUFPQSxPQUFPLENBQUNPLE1BQVIsQ0FBZSxVQUFTQyxJQUFULEVBQWVKLE1BQWYsRUFBdUI7QUFDM0MsV0FBT0ksSUFBSSxJQUFJSixNQUFNLENBQUMsQ0FBRCxDQUFOLEtBQWMsR0FBN0I7QUFDRCxHQUZNLEVBRUosSUFGSSxDQUFQO0FBR0Q7O0FBQ0QsU0FBU2Qsa0JBQVQsQ0FBNEJPLEtBQTVCLEVBQW1DWSxhQUFuQyxFQUFrREMsS0FBbEQsRUFBeUQ7QUFDdkQsT0FBSyxJQUFJQyxDQUFDLEdBQUcsQ0FBYixFQUFnQkEsQ0FBQyxHQUFHRCxLQUFwQixFQUEyQkMsQ0FBQyxFQUE1QixFQUFnQztBQUM5QixRQUFJQyxhQUFhLEdBQUdILGFBQWEsQ0FBQ0EsYUFBYSxDQUFDdkQsTUFBZCxHQUF1QndELEtBQXZCLEdBQStCQyxDQUFoQyxDQUFiLENBQWdETCxNQUFoRCxDQUF1RCxDQUF2RCxDQUFwQjs7QUFDQSxRQUFJVCxLQUFLLENBQUNqRSxLQUFOLENBQVlpRSxLQUFLLENBQUN2RCxLQUFOLEdBQWNxRSxDQUExQixNQUFpQyxNQUFNQyxhQUEzQyxFQUEwRDtBQUN4RCxhQUFPLEtBQVA7QUFDRDtBQUNGOztBQUVEZixFQUFBQSxLQUFLLENBQUN2RCxLQUFOLElBQWVvRSxLQUFmO0FBQ0EsU0FBTyxJQUFQO0FBQ0Q7O0FBRUQsU0FBUy9FLG1CQUFULENBQTZCQyxLQUE3QixFQUFvQztBQUNsQyxNQUFJQyxRQUFRLEdBQUcsQ0FBZjtBQUNBLE1BQUlDLFFBQVEsR0FBRyxDQUFmO0FBRUFGLEVBQUFBLEtBQUssQ0FBQ2lGLE9BQU4sQ0FBYyxVQUFTakIsSUFBVCxFQUFlO0FBQzNCLFFBQUksT0FBT0EsSUFBUCxLQUFnQixRQUFwQixFQUE4QjtBQUM1QixVQUFJa0IsT0FBTyxHQUFHbkYsbUJBQW1CLENBQUNpRSxJQUFJLENBQUMzRCxJQUFOLENBQWpDO0FBQ0EsVUFBSThFLFVBQVUsR0FBR3BGLG1CQUFtQixDQUFDaUUsSUFBSSxDQUFDMUQsTUFBTixDQUFwQzs7QUFFQSxVQUFJTCxRQUFRLEtBQUtFLFNBQWpCLEVBQTRCO0FBQzFCLFlBQUkrRSxPQUFPLENBQUNqRixRQUFSLEtBQXFCa0YsVUFBVSxDQUFDbEYsUUFBcEMsRUFBOEM7QUFDNUNBLFVBQUFBLFFBQVEsSUFBSWlGLE9BQU8sQ0FBQ2pGLFFBQXBCO0FBQ0QsU0FGRCxNQUVPO0FBQ0xBLFVBQUFBLFFBQVEsR0FBR0UsU0FBWDtBQUNEO0FBQ0Y7O0FBRUQsVUFBSUQsUUFBUSxLQUFLQyxTQUFqQixFQUE0QjtBQUMxQixZQUFJK0UsT0FBTyxDQUFDaEYsUUFBUixLQUFxQmlGLFVBQVUsQ0FBQ2pGLFFBQXBDLEVBQThDO0FBQzVDQSxVQUFBQSxRQUFRLElBQUlnRixPQUFPLENBQUNoRixRQUFwQjtBQUNELFNBRkQsTUFFTztBQUNMQSxVQUFBQSxRQUFRLEdBQUdDLFNBQVg7QUFDRDtBQUNGO0FBQ0YsS0FuQkQsTUFtQk87QUFDTCxVQUFJRCxRQUFRLEtBQUtDLFNBQWIsS0FBMkI2RCxJQUFJLENBQUMsQ0FBRCxDQUFKLEtBQVksR0FBWixJQUFtQkEsSUFBSSxDQUFDLENBQUQsQ0FBSixLQUFZLEdBQTFELENBQUosRUFBb0U7QUFDbEU5RCxRQUFBQSxRQUFRO0FBQ1Q7O0FBQ0QsVUFBSUQsUUFBUSxLQUFLRSxTQUFiLEtBQTJCNkQsSUFBSSxDQUFDLENBQUQsQ0FBSixLQUFZLEdBQVosSUFBbUJBLElBQUksQ0FBQyxDQUFELENBQUosS0FBWSxHQUExRCxDQUFKLEVBQW9FO0FBQ2xFL0QsUUFBQUEsUUFBUTtBQUNUO0FBQ0Y7QUFDRixHQTVCRDtBQThCQSxTQUFPO0FBQUNBLElBQUFBLFFBQVEsRUFBUkEsUUFBRDtBQUFXQyxJQUFBQSxRQUFRLEVBQVJBO0FBQVgsR0FBUDtBQUNEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHtzdHJ1Y3R1cmVkUGF0Y2h9IGZyb20gJy4vY3JlYXRlJztcbmltcG9ydCB7cGFyc2VQYXRjaH0gZnJvbSAnLi9wYXJzZSc7XG5cbmltcG9ydCB7YXJyYXlFcXVhbCwgYXJyYXlTdGFydHNXaXRofSBmcm9tICcuLi91dGlsL2FycmF5JztcblxuZXhwb3J0IGZ1bmN0aW9uIGNhbGNMaW5lQ291bnQoaHVuaykge1xuICBjb25zdCB7b2xkTGluZXMsIG5ld0xpbmVzfSA9IGNhbGNPbGROZXdMaW5lQ291bnQoaHVuay5saW5lcyk7XG5cbiAgaWYgKG9sZExpbmVzICE9PSB1bmRlZmluZWQpIHtcbiAgICBodW5rLm9sZExpbmVzID0gb2xkTGluZXM7XG4gIH0gZWxzZSB7XG4gICAgZGVsZXRlIGh1bmsub2xkTGluZXM7XG4gIH1cblxuICBpZiAobmV3TGluZXMgIT09IHVuZGVmaW5lZCkge1xuICAgIGh1bmsubmV3TGluZXMgPSBuZXdMaW5lcztcbiAgfSBlbHNlIHtcbiAgICBkZWxldGUgaHVuay5uZXdMaW5lcztcbiAgfVxufVxuXG5leHBvcnQgZnVuY3Rpb24gbWVyZ2UobWluZSwgdGhlaXJzLCBiYXNlKSB7XG4gIG1pbmUgPSBsb2FkUGF0Y2gobWluZSwgYmFzZSk7XG4gIHRoZWlycyA9IGxvYWRQYXRjaCh0aGVpcnMsIGJhc2UpO1xuXG4gIGxldCByZXQgPSB7fTtcblxuICAvLyBGb3IgaW5kZXggd2UganVzdCBsZXQgaXQgcGFzcyB0aHJvdWdoIGFzIGl0IGRvZXNuJ3QgaGF2ZSBhbnkgbmVjZXNzYXJ5IG1lYW5pbmcuXG4gIC8vIExlYXZpbmcgc2FuaXR5IGNoZWNrcyBvbiB0aGlzIHRvIHRoZSBBUEkgY29uc3VtZXIgdGhhdCBtYXkga25vdyBtb3JlIGFib3V0IHRoZVxuICAvLyBtZWFuaW5nIGluIHRoZWlyIG93biBjb250ZXh0LlxuICBpZiAobWluZS5pbmRleCB8fCB0aGVpcnMuaW5kZXgpIHtcbiAgICByZXQuaW5kZXggPSBtaW5lLmluZGV4IHx8IHRoZWlycy5pbmRleDtcbiAgfVxuXG4gIGlmIChtaW5lLm5ld0ZpbGVOYW1lIHx8IHRoZWlycy5uZXdGaWxlTmFtZSkge1xuICAgIGlmICghZmlsZU5hbWVDaGFuZ2VkKG1pbmUpKSB7XG4gICAgICAvLyBObyBoZWFkZXIgb3Igbm8gY2hhbmdlIGluIG91cnMsIHVzZSB0aGVpcnMgKGFuZCBvdXJzIGlmIHRoZWlycyBkb2VzIG5vdCBleGlzdClcbiAgICAgIHJldC5vbGRGaWxlTmFtZSA9IHRoZWlycy5vbGRGaWxlTmFtZSB8fCBtaW5lLm9sZEZpbGVOYW1lO1xuICAgICAgcmV0Lm5ld0ZpbGVOYW1lID0gdGhlaXJzLm5ld0ZpbGVOYW1lIHx8IG1pbmUubmV3RmlsZU5hbWU7XG4gICAgICByZXQub2xkSGVhZGVyID0gdGhlaXJzLm9sZEhlYWRlciB8fCBtaW5lLm9sZEhlYWRlcjtcbiAgICAgIHJldC5uZXdIZWFkZXIgPSB0aGVpcnMubmV3SGVhZGVyIHx8IG1pbmUubmV3SGVhZGVyO1xuICAgIH0gZWxzZSBpZiAoIWZpbGVOYW1lQ2hhbmdlZCh0aGVpcnMpKSB7XG4gICAgICAvLyBObyBoZWFkZXIgb3Igbm8gY2hhbmdlIGluIHRoZWlycywgdXNlIG91cnNcbiAgICAgIHJldC5vbGRGaWxlTmFtZSA9IG1pbmUub2xkRmlsZU5hbWU7XG4gICAgICByZXQubmV3RmlsZU5hbWUgPSBtaW5lLm5ld0ZpbGVOYW1lO1xuICAgICAgcmV0Lm9sZEhlYWRlciA9IG1pbmUub2xkSGVhZGVyO1xuICAgICAgcmV0Lm5ld0hlYWRlciA9IG1pbmUubmV3SGVhZGVyO1xuICAgIH0gZWxzZSB7XG4gICAgICAvLyBCb3RoIGNoYW5nZWQuLi4gZmlndXJlIGl0IG91dFxuICAgICAgcmV0Lm9sZEZpbGVOYW1lID0gc2VsZWN0RmllbGQocmV0LCBtaW5lLm9sZEZpbGVOYW1lLCB0aGVpcnMub2xkRmlsZU5hbWUpO1xuICAgICAgcmV0Lm5ld0ZpbGVOYW1lID0gc2VsZWN0RmllbGQocmV0LCBtaW5lLm5ld0ZpbGVOYW1lLCB0aGVpcnMubmV3RmlsZU5hbWUpO1xuICAgICAgcmV0Lm9sZEhlYWRlciA9IHNlbGVjdEZpZWxkKHJldCwgbWluZS5vbGRIZWFkZXIsIHRoZWlycy5vbGRIZWFkZXIpO1xuICAgICAgcmV0Lm5ld0hlYWRlciA9IHNlbGVjdEZpZWxkKHJldCwgbWluZS5uZXdIZWFkZXIsIHRoZWlycy5uZXdIZWFkZXIpO1xuICAgIH1cbiAgfVxuXG4gIHJldC5odW5rcyA9IFtdO1xuXG4gIGxldCBtaW5lSW5kZXggPSAwLFxuICAgICAgdGhlaXJzSW5kZXggPSAwLFxuICAgICAgbWluZU9mZnNldCA9IDAsXG4gICAgICB0aGVpcnNPZmZzZXQgPSAwO1xuXG4gIHdoaWxlIChtaW5lSW5kZXggPCBtaW5lLmh1bmtzLmxlbmd0aCB8fCB0aGVpcnNJbmRleCA8IHRoZWlycy5odW5rcy5sZW5ndGgpIHtcbiAgICBsZXQgbWluZUN1cnJlbnQgPSBtaW5lLmh1bmtzW21pbmVJbmRleF0gfHwge29sZFN0YXJ0OiBJbmZpbml0eX0sXG4gICAgICAgIHRoZWlyc0N1cnJlbnQgPSB0aGVpcnMuaHVua3NbdGhlaXJzSW5kZXhdIHx8IHtvbGRTdGFydDogSW5maW5pdHl9O1xuXG4gICAgaWYgKGh1bmtCZWZvcmUobWluZUN1cnJlbnQsIHRoZWlyc0N1cnJlbnQpKSB7XG4gICAgICAvLyBUaGlzIHBhdGNoIGRvZXMgbm90IG92ZXJsYXAgd2l0aCBhbnkgb2YgdGhlIG90aGVycywgeWF5LlxuICAgICAgcmV0Lmh1bmtzLnB1c2goY2xvbmVIdW5rKG1pbmVDdXJyZW50LCBtaW5lT2Zmc2V0KSk7XG4gICAgICBtaW5lSW5kZXgrKztcbiAgICAgIHRoZWlyc09mZnNldCArPSBtaW5lQ3VycmVudC5uZXdMaW5lcyAtIG1pbmVDdXJyZW50Lm9sZExpbmVzO1xuICAgIH0gZWxzZSBpZiAoaHVua0JlZm9yZSh0aGVpcnNDdXJyZW50LCBtaW5lQ3VycmVudCkpIHtcbiAgICAgIC8vIFRoaXMgcGF0Y2ggZG9lcyBub3Qgb3ZlcmxhcCB3aXRoIGFueSBvZiB0aGUgb3RoZXJzLCB5YXkuXG4gICAgICByZXQuaHVua3MucHVzaChjbG9uZUh1bmsodGhlaXJzQ3VycmVudCwgdGhlaXJzT2Zmc2V0KSk7XG4gICAgICB0aGVpcnNJbmRleCsrO1xuICAgICAgbWluZU9mZnNldCArPSB0aGVpcnNDdXJyZW50Lm5ld0xpbmVzIC0gdGhlaXJzQ3VycmVudC5vbGRMaW5lcztcbiAgICB9IGVsc2Uge1xuICAgICAgLy8gT3ZlcmxhcCwgbWVyZ2UgYXMgYmVzdCB3ZSBjYW5cbiAgICAgIGxldCBtZXJnZWRIdW5rID0ge1xuICAgICAgICBvbGRTdGFydDogTWF0aC5taW4obWluZUN1cnJlbnQub2xkU3RhcnQsIHRoZWlyc0N1cnJlbnQub2xkU3RhcnQpLFxuICAgICAgICBvbGRMaW5lczogMCxcbiAgICAgICAgbmV3U3RhcnQ6IE1hdGgubWluKG1pbmVDdXJyZW50Lm5ld1N0YXJ0ICsgbWluZU9mZnNldCwgdGhlaXJzQ3VycmVudC5vbGRTdGFydCArIHRoZWlyc09mZnNldCksXG4gICAgICAgIG5ld0xpbmVzOiAwLFxuICAgICAgICBsaW5lczogW11cbiAgICAgIH07XG4gICAgICBtZXJnZUxpbmVzKG1lcmdlZEh1bmssIG1pbmVDdXJyZW50Lm9sZFN0YXJ0LCBtaW5lQ3VycmVudC5saW5lcywgdGhlaXJzQ3VycmVudC5vbGRTdGFydCwgdGhlaXJzQ3VycmVudC5saW5lcyk7XG4gICAgICB0aGVpcnNJbmRleCsrO1xuICAgICAgbWluZUluZGV4Kys7XG5cbiAgICAgIHJldC5odW5rcy5wdXNoKG1lcmdlZEh1bmspO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiByZXQ7XG59XG5cbmZ1bmN0aW9uIGxvYWRQYXRjaChwYXJhbSwgYmFzZSkge1xuICBpZiAodHlwZW9mIHBhcmFtID09PSAnc3RyaW5nJykge1xuICAgIGlmICgoL15AQC9tKS50ZXN0KHBhcmFtKSB8fCAoKC9eSW5kZXg6L20pLnRlc3QocGFyYW0pKSkge1xuICAgICAgcmV0dXJuIHBhcnNlUGF0Y2gocGFyYW0pWzBdO1xuICAgIH1cblxuICAgIGlmICghYmFzZSkge1xuICAgICAgdGhyb3cgbmV3IEVycm9yKCdNdXN0IHByb3ZpZGUgYSBiYXNlIHJlZmVyZW5jZSBvciBwYXNzIGluIGEgcGF0Y2gnKTtcbiAgICB9XG4gICAgcmV0dXJuIHN0cnVjdHVyZWRQYXRjaCh1bmRlZmluZWQsIHVuZGVmaW5lZCwgYmFzZSwgcGFyYW0pO1xuICB9XG5cbiAgcmV0dXJuIHBhcmFtO1xufVxuXG5mdW5jdGlvbiBmaWxlTmFtZUNoYW5nZWQocGF0Y2gpIHtcbiAgcmV0dXJuIHBhdGNoLm5ld0ZpbGVOYW1lICYmIHBhdGNoLm5ld0ZpbGVOYW1lICE9PSBwYXRjaC5vbGRGaWxlTmFtZTtcbn1cblxuZnVuY3Rpb24gc2VsZWN0RmllbGQoaW5kZXgsIG1pbmUsIHRoZWlycykge1xuICBpZiAobWluZSA9PT0gdGhlaXJzKSB7XG4gICAgcmV0dXJuIG1pbmU7XG4gIH0gZWxzZSB7XG4gICAgaW5kZXguY29uZmxpY3QgPSB0cnVlO1xuICAgIHJldHVybiB7bWluZSwgdGhlaXJzfTtcbiAgfVxufVxuXG5mdW5jdGlvbiBodW5rQmVmb3JlKHRlc3QsIGNoZWNrKSB7XG4gIHJldHVybiB0ZXN0Lm9sZFN0YXJ0IDwgY2hlY2sub2xkU3RhcnRcbiAgICAmJiAodGVzdC5vbGRTdGFydCArIHRlc3Qub2xkTGluZXMpIDwgY2hlY2sub2xkU3RhcnQ7XG59XG5cbmZ1bmN0aW9uIGNsb25lSHVuayhodW5rLCBvZmZzZXQpIHtcbiAgcmV0dXJuIHtcbiAgICBvbGRTdGFydDogaHVuay5vbGRTdGFydCwgb2xkTGluZXM6IGh1bmsub2xkTGluZXMsXG4gICAgbmV3U3RhcnQ6IGh1bmsubmV3U3RhcnQgKyBvZmZzZXQsIG5ld0xpbmVzOiBodW5rLm5ld0xpbmVzLFxuICAgIGxpbmVzOiBodW5rLmxpbmVzXG4gIH07XG59XG5cbmZ1bmN0aW9uIG1lcmdlTGluZXMoaHVuaywgbWluZU9mZnNldCwgbWluZUxpbmVzLCB0aGVpck9mZnNldCwgdGhlaXJMaW5lcykge1xuICAvLyBUaGlzIHdpbGwgZ2VuZXJhbGx5IHJlc3VsdCBpbiBhIGNvbmZsaWN0ZWQgaHVuaywgYnV0IHRoZXJlIGFyZSBjYXNlcyB3aGVyZSB0aGUgY29udGV4dFxuICAvLyBpcyB0aGUgb25seSBvdmVybGFwIHdoZXJlIHdlIGNhbiBzdWNjZXNzZnVsbHkgbWVyZ2UgdGhlIGNvbnRlbnQgaGVyZS5cbiAgbGV0IG1pbmUgPSB7b2Zmc2V0OiBtaW5lT2Zmc2V0LCBsaW5lczogbWluZUxpbmVzLCBpbmRleDogMH0sXG4gICAgICB0aGVpciA9IHtvZmZzZXQ6IHRoZWlyT2Zmc2V0LCBsaW5lczogdGhlaXJMaW5lcywgaW5kZXg6IDB9O1xuXG4gIC8vIEhhbmRsZSBhbnkgbGVhZGluZyBjb250ZW50XG4gIGluc2VydExlYWRpbmcoaHVuaywgbWluZSwgdGhlaXIpO1xuICBpbnNlcnRMZWFkaW5nKGh1bmssIHRoZWlyLCBtaW5lKTtcblxuICAvLyBOb3cgaW4gdGhlIG92ZXJsYXAgY29udGVudC4gU2NhbiB0aHJvdWdoIGFuZCBzZWxlY3QgdGhlIGJlc3QgY2hhbmdlcyBmcm9tIGVhY2guXG4gIHdoaWxlIChtaW5lLmluZGV4IDwgbWluZS5saW5lcy5sZW5ndGggJiYgdGhlaXIuaW5kZXggPCB0aGVpci5saW5lcy5sZW5ndGgpIHtcbiAgICBsZXQgbWluZUN1cnJlbnQgPSBtaW5lLmxpbmVzW21pbmUuaW5kZXhdLFxuICAgICAgICB0aGVpckN1cnJlbnQgPSB0aGVpci5saW5lc1t0aGVpci5pbmRleF07XG5cbiAgICBpZiAoKG1pbmVDdXJyZW50WzBdID09PSAnLScgfHwgbWluZUN1cnJlbnRbMF0gPT09ICcrJylcbiAgICAgICAgJiYgKHRoZWlyQ3VycmVudFswXSA9PT0gJy0nIHx8IHRoZWlyQ3VycmVudFswXSA9PT0gJysnKSkge1xuICAgICAgLy8gQm90aCBtb2RpZmllZCAuLi5cbiAgICAgIG11dHVhbENoYW5nZShodW5rLCBtaW5lLCB0aGVpcik7XG4gICAgfSBlbHNlIGlmIChtaW5lQ3VycmVudFswXSA9PT0gJysnICYmIHRoZWlyQ3VycmVudFswXSA9PT0gJyAnKSB7XG4gICAgICAvLyBNaW5lIGluc2VydGVkXG4gICAgICBodW5rLmxpbmVzLnB1c2goLi4uIGNvbGxlY3RDaGFuZ2UobWluZSkpO1xuICAgIH0gZWxzZSBpZiAodGhlaXJDdXJyZW50WzBdID09PSAnKycgJiYgbWluZUN1cnJlbnRbMF0gPT09ICcgJykge1xuICAgICAgLy8gVGhlaXJzIGluc2VydGVkXG4gICAgICBodW5rLmxpbmVzLnB1c2goLi4uIGNvbGxlY3RDaGFuZ2UodGhlaXIpKTtcbiAgICB9IGVsc2UgaWYgKG1pbmVDdXJyZW50WzBdID09PSAnLScgJiYgdGhlaXJDdXJyZW50WzBdID09PSAnICcpIHtcbiAgICAgIC8vIE1pbmUgcmVtb3ZlZCBvciBlZGl0ZWRcbiAgICAgIHJlbW92YWwoaHVuaywgbWluZSwgdGhlaXIpO1xuICAgIH0gZWxzZSBpZiAodGhlaXJDdXJyZW50WzBdID09PSAnLScgJiYgbWluZUN1cnJlbnRbMF0gPT09ICcgJykge1xuICAgICAgLy8gVGhlaXIgcmVtb3ZlZCBvciBlZGl0ZWRcbiAgICAgIHJlbW92YWwoaHVuaywgdGhlaXIsIG1pbmUsIHRydWUpO1xuICAgIH0gZWxzZSBpZiAobWluZUN1cnJlbnQgPT09IHRoZWlyQ3VycmVudCkge1xuICAgICAgLy8gQ29udGV4dCBpZGVudGl0eVxuICAgICAgaHVuay5saW5lcy5wdXNoKG1pbmVDdXJyZW50KTtcbiAgICAgIG1pbmUuaW5kZXgrKztcbiAgICAgIHRoZWlyLmluZGV4Kys7XG4gICAgfSBlbHNlIHtcbiAgICAgIC8vIENvbnRleHQgbWlzbWF0Y2hcbiAgICAgIGNvbmZsaWN0KGh1bmssIGNvbGxlY3RDaGFuZ2UobWluZSksIGNvbGxlY3RDaGFuZ2UodGhlaXIpKTtcbiAgICB9XG4gIH1cblxuICAvLyBOb3cgcHVzaCBhbnl0aGluZyB0aGF0IG1heSBiZSByZW1haW5pbmdcbiAgaW5zZXJ0VHJhaWxpbmcoaHVuaywgbWluZSk7XG4gIGluc2VydFRyYWlsaW5nKGh1bmssIHRoZWlyKTtcblxuICBjYWxjTGluZUNvdW50KGh1bmspO1xufVxuXG5mdW5jdGlvbiBtdXR1YWxDaGFuZ2UoaHVuaywgbWluZSwgdGhlaXIpIHtcbiAgbGV0IG15Q2hhbmdlcyA9IGNvbGxlY3RDaGFuZ2UobWluZSksXG4gICAgICB0aGVpckNoYW5nZXMgPSBjb2xsZWN0Q2hhbmdlKHRoZWlyKTtcblxuICBpZiAoYWxsUmVtb3ZlcyhteUNoYW5nZXMpICYmIGFsbFJlbW92ZXModGhlaXJDaGFuZ2VzKSkge1xuICAgIC8vIFNwZWNpYWwgY2FzZSBmb3IgcmVtb3ZlIGNoYW5nZXMgdGhhdCBhcmUgc3VwZXJzZXRzIG9mIG9uZSBhbm90aGVyXG4gICAgaWYgKGFycmF5U3RhcnRzV2l0aChteUNoYW5nZXMsIHRoZWlyQ2hhbmdlcylcbiAgICAgICAgJiYgc2tpcFJlbW92ZVN1cGVyc2V0KHRoZWlyLCBteUNoYW5nZXMsIG15Q2hhbmdlcy5sZW5ndGggLSB0aGVpckNoYW5nZXMubGVuZ3RoKSkge1xuICAgICAgaHVuay5saW5lcy5wdXNoKC4uLiBteUNoYW5nZXMpO1xuICAgICAgcmV0dXJuO1xuICAgIH0gZWxzZSBpZiAoYXJyYXlTdGFydHNXaXRoKHRoZWlyQ2hhbmdlcywgbXlDaGFuZ2VzKVxuICAgICAgICAmJiBza2lwUmVtb3ZlU3VwZXJzZXQobWluZSwgdGhlaXJDaGFuZ2VzLCB0aGVpckNoYW5nZXMubGVuZ3RoIC0gbXlDaGFuZ2VzLmxlbmd0aCkpIHtcbiAgICAgIGh1bmsubGluZXMucHVzaCguLi4gdGhlaXJDaGFuZ2VzKTtcbiAgICAgIHJldHVybjtcbiAgICB9XG4gIH0gZWxzZSBpZiAoYXJyYXlFcXVhbChteUNoYW5nZXMsIHRoZWlyQ2hhbmdlcykpIHtcbiAgICBodW5rLmxpbmVzLnB1c2goLi4uIG15Q2hhbmdlcyk7XG4gICAgcmV0dXJuO1xuICB9XG5cbiAgY29uZmxpY3QoaHVuaywgbXlDaGFuZ2VzLCB0aGVpckNoYW5nZXMpO1xufVxuXG5mdW5jdGlvbiByZW1vdmFsKGh1bmssIG1pbmUsIHRoZWlyLCBzd2FwKSB7XG4gIGxldCBteUNoYW5nZXMgPSBjb2xsZWN0Q2hhbmdlKG1pbmUpLFxuICAgICAgdGhlaXJDaGFuZ2VzID0gY29sbGVjdENvbnRleHQodGhlaXIsIG15Q2hhbmdlcyk7XG4gIGlmICh0aGVpckNoYW5nZXMubWVyZ2VkKSB7XG4gICAgaHVuay5saW5lcy5wdXNoKC4uLiB0aGVpckNoYW5nZXMubWVyZ2VkKTtcbiAgfSBlbHNlIHtcbiAgICBjb25mbGljdChodW5rLCBzd2FwID8gdGhlaXJDaGFuZ2VzIDogbXlDaGFuZ2VzLCBzd2FwID8gbXlDaGFuZ2VzIDogdGhlaXJDaGFuZ2VzKTtcbiAgfVxufVxuXG5mdW5jdGlvbiBjb25mbGljdChodW5rLCBtaW5lLCB0aGVpcikge1xuICBodW5rLmNvbmZsaWN0ID0gdHJ1ZTtcbiAgaHVuay5saW5lcy5wdXNoKHtcbiAgICBjb25mbGljdDogdHJ1ZSxcbiAgICBtaW5lOiBtaW5lLFxuICAgIHRoZWlyczogdGhlaXJcbiAgfSk7XG59XG5cbmZ1bmN0aW9uIGluc2VydExlYWRpbmcoaHVuaywgaW5zZXJ0LCB0aGVpcikge1xuICB3aGlsZSAoaW5zZXJ0Lm9mZnNldCA8IHRoZWlyLm9mZnNldCAmJiBpbnNlcnQuaW5kZXggPCBpbnNlcnQubGluZXMubGVuZ3RoKSB7XG4gICAgbGV0IGxpbmUgPSBpbnNlcnQubGluZXNbaW5zZXJ0LmluZGV4KytdO1xuICAgIGh1bmsubGluZXMucHVzaChsaW5lKTtcbiAgICBpbnNlcnQub2Zmc2V0Kys7XG4gIH1cbn1cbmZ1bmN0aW9uIGluc2VydFRyYWlsaW5nKGh1bmssIGluc2VydCkge1xuICB3aGlsZSAoaW5zZXJ0LmluZGV4IDwgaW5zZXJ0LmxpbmVzLmxlbmd0aCkge1xuICAgIGxldCBsaW5lID0gaW5zZXJ0LmxpbmVzW2luc2VydC5pbmRleCsrXTtcbiAgICBodW5rLmxpbmVzLnB1c2gobGluZSk7XG4gIH1cbn1cblxuZnVuY3Rpb24gY29sbGVjdENoYW5nZShzdGF0ZSkge1xuICBsZXQgcmV0ID0gW10sXG4gICAgICBvcGVyYXRpb24gPSBzdGF0ZS5saW5lc1tzdGF0ZS5pbmRleF1bMF07XG4gIHdoaWxlIChzdGF0ZS5pbmRleCA8IHN0YXRlLmxpbmVzLmxlbmd0aCkge1xuICAgIGxldCBsaW5lID0gc3RhdGUubGluZXNbc3RhdGUuaW5kZXhdO1xuXG4gICAgLy8gR3JvdXAgYWRkaXRpb25zIHRoYXQgYXJlIGltbWVkaWF0ZWx5IGFmdGVyIHN1YnRyYWN0aW9ucyBhbmQgdHJlYXQgdGhlbSBhcyBvbmUgXCJhdG9taWNcIiBtb2RpZnkgY2hhbmdlLlxuICAgIGlmIChvcGVyYXRpb24gPT09ICctJyAmJiBsaW5lWzBdID09PSAnKycpIHtcbiAgICAgIG9wZXJhdGlvbiA9ICcrJztcbiAgICB9XG5cbiAgICBpZiAob3BlcmF0aW9uID09PSBsaW5lWzBdKSB7XG4gICAgICByZXQucHVzaChsaW5lKTtcbiAgICAgIHN0YXRlLmluZGV4Kys7XG4gICAgfSBlbHNlIHtcbiAgICAgIGJyZWFrO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiByZXQ7XG59XG5mdW5jdGlvbiBjb2xsZWN0Q29udGV4dChzdGF0ZSwgbWF0Y2hDaGFuZ2VzKSB7XG4gIGxldCBjaGFuZ2VzID0gW10sXG4gICAgICBtZXJnZWQgPSBbXSxcbiAgICAgIG1hdGNoSW5kZXggPSAwLFxuICAgICAgY29udGV4dENoYW5nZXMgPSBmYWxzZSxcbiAgICAgIGNvbmZsaWN0ZWQgPSBmYWxzZTtcbiAgd2hpbGUgKG1hdGNoSW5kZXggPCBtYXRjaENoYW5nZXMubGVuZ3RoXG4gICAgICAgICYmIHN0YXRlLmluZGV4IDwgc3RhdGUubGluZXMubGVuZ3RoKSB7XG4gICAgbGV0IGNoYW5nZSA9IHN0YXRlLmxpbmVzW3N0YXRlLmluZGV4XSxcbiAgICAgICAgbWF0Y2ggPSBtYXRjaENoYW5nZXNbbWF0Y2hJbmRleF07XG5cbiAgICAvLyBPbmNlIHdlJ3ZlIGhpdCBvdXIgYWRkLCB0aGVuIHdlIGFyZSBkb25lXG4gICAgaWYgKG1hdGNoWzBdID09PSAnKycpIHtcbiAgICAgIGJyZWFrO1xuICAgIH1cblxuICAgIGNvbnRleHRDaGFuZ2VzID0gY29udGV4dENoYW5nZXMgfHwgY2hhbmdlWzBdICE9PSAnICc7XG5cbiAgICBtZXJnZWQucHVzaChtYXRjaCk7XG4gICAgbWF0Y2hJbmRleCsrO1xuXG4gICAgLy8gQ29uc3VtZSBhbnkgYWRkaXRpb25zIGluIHRoZSBvdGhlciBibG9jayBhcyBhIGNvbmZsaWN0IHRvIGF0dGVtcHRcbiAgICAvLyB0byBwdWxsIGluIHRoZSByZW1haW5pbmcgY29udGV4dCBhZnRlciB0aGlzXG4gICAgaWYgKGNoYW5nZVswXSA9PT0gJysnKSB7XG4gICAgICBjb25mbGljdGVkID0gdHJ1ZTtcblxuICAgICAgd2hpbGUgKGNoYW5nZVswXSA9PT0gJysnKSB7XG4gICAgICAgIGNoYW5nZXMucHVzaChjaGFuZ2UpO1xuICAgICAgICBjaGFuZ2UgPSBzdGF0ZS5saW5lc1srK3N0YXRlLmluZGV4XTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICBpZiAobWF0Y2guc3Vic3RyKDEpID09PSBjaGFuZ2Uuc3Vic3RyKDEpKSB7XG4gICAgICBjaGFuZ2VzLnB1c2goY2hhbmdlKTtcbiAgICAgIHN0YXRlLmluZGV4Kys7XG4gICAgfSBlbHNlIHtcbiAgICAgIGNvbmZsaWN0ZWQgPSB0cnVlO1xuICAgIH1cbiAgfVxuXG4gIGlmICgobWF0Y2hDaGFuZ2VzW21hdGNoSW5kZXhdIHx8ICcnKVswXSA9PT0gJysnXG4gICAgICAmJiBjb250ZXh0Q2hhbmdlcykge1xuICAgIGNvbmZsaWN0ZWQgPSB0cnVlO1xuICB9XG5cbiAgaWYgKGNvbmZsaWN0ZWQpIHtcbiAgICByZXR1cm4gY2hhbmdlcztcbiAgfVxuXG4gIHdoaWxlIChtYXRjaEluZGV4IDwgbWF0Y2hDaGFuZ2VzLmxlbmd0aCkge1xuICAgIG1lcmdlZC5wdXNoKG1hdGNoQ2hhbmdlc1ttYXRjaEluZGV4KytdKTtcbiAgfVxuXG4gIHJldHVybiB7XG4gICAgbWVyZ2VkLFxuICAgIGNoYW5nZXNcbiAgfTtcbn1cblxuZnVuY3Rpb24gYWxsUmVtb3ZlcyhjaGFuZ2VzKSB7XG4gIHJldHVybiBjaGFuZ2VzLnJlZHVjZShmdW5jdGlvbihwcmV2LCBjaGFuZ2UpIHtcbiAgICByZXR1cm4gcHJldiAmJiBjaGFuZ2VbMF0gPT09ICctJztcbiAgfSwgdHJ1ZSk7XG59XG5mdW5jdGlvbiBza2lwUmVtb3ZlU3VwZXJzZXQoc3RhdGUsIHJlbW92ZUNoYW5nZXMsIGRlbHRhKSB7XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgZGVsdGE7IGkrKykge1xuICAgIGxldCBjaGFuZ2VDb250ZW50ID0gcmVtb3ZlQ2hhbmdlc1tyZW1vdmVDaGFuZ2VzLmxlbmd0aCAtIGRlbHRhICsgaV0uc3Vic3RyKDEpO1xuICAgIGlmIChzdGF0ZS5saW5lc1tzdGF0ZS5pbmRleCArIGldICE9PSAnICcgKyBjaGFuZ2VDb250ZW50KSB7XG4gICAgICByZXR1cm4gZmFsc2U7XG4gICAgfVxuICB9XG5cbiAgc3RhdGUuaW5kZXggKz0gZGVsdGE7XG4gIHJldHVybiB0cnVlO1xufVxuXG5mdW5jdGlvbiBjYWxjT2xkTmV3TGluZUNvdW50KGxpbmVzKSB7XG4gIGxldCBvbGRMaW5lcyA9IDA7XG4gIGxldCBuZXdMaW5lcyA9IDA7XG5cbiAgbGluZXMuZm9yRWFjaChmdW5jdGlvbihsaW5lKSB7XG4gICAgaWYgKHR5cGVvZiBsaW5lICE9PSAnc3RyaW5nJykge1xuICAgICAgbGV0IG15Q291bnQgPSBjYWxjT2xkTmV3TGluZUNvdW50KGxpbmUubWluZSk7XG4gICAgICBsZXQgdGhlaXJDb3VudCA9IGNhbGNPbGROZXdMaW5lQ291bnQobGluZS50aGVpcnMpO1xuXG4gICAgICBpZiAob2xkTGluZXMgIT09IHVuZGVmaW5lZCkge1xuICAgICAgICBpZiAobXlDb3VudC5vbGRMaW5lcyA9PT0gdGhlaXJDb3VudC5vbGRMaW5lcykge1xuICAgICAgICAgIG9sZExpbmVzICs9IG15Q291bnQub2xkTGluZXM7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgb2xkTGluZXMgPSB1bmRlZmluZWQ7XG4gICAgICAgIH1cbiAgICAgIH1cblxuICAgICAgaWYgKG5ld0xpbmVzICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgaWYgKG15Q291bnQubmV3TGluZXMgPT09IHRoZWlyQ291bnQubmV3TGluZXMpIHtcbiAgICAgICAgICBuZXdMaW5lcyArPSBteUNvdW50Lm5ld0xpbmVzO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIG5ld0xpbmVzID0gdW5kZWZpbmVkO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfSBlbHNlIHtcbiAgICAgIGlmIChuZXdMaW5lcyAhPT0gdW5kZWZpbmVkICYmIChsaW5lWzBdID09PSAnKycgfHwgbGluZVswXSA9PT0gJyAnKSkge1xuICAgICAgICBuZXdMaW5lcysrO1xuICAgICAgfVxuICAgICAgaWYgKG9sZExpbmVzICE9PSB1bmRlZmluZWQgJiYgKGxpbmVbMF0gPT09ICctJyB8fCBsaW5lWzBdID09PSAnICcpKSB7XG4gICAgICAgIG9sZExpbmVzKys7XG4gICAgICB9XG4gICAgfVxuICB9KTtcblxuICByZXR1cm4ge29sZExpbmVzLCBuZXdMaW5lc307XG59XG4iXX0= diff --git a/node_modules/diff/lib/patch/parse.js b/node_modules/diff/lib/patch/parse.js deleted file mode 100644 index f1501048014f1..0000000000000 --- a/node_modules/diff/lib/patch/parse.js +++ /dev/null @@ -1,167 +0,0 @@ -/*istanbul ignore start*/ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.parsePatch = parsePatch; - -/*istanbul ignore end*/ -function parsePatch(uniDiff) { - /*istanbul ignore start*/ - var - /*istanbul ignore end*/ - options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), - delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], - 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:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { - break; - } else if (/^@@/.test(_line)) { - index.hunks.push(parseHunk()); - } else if (_line && options.strict) { - // Ignore unexpected content unless in strict mode - 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+(.*)$/.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: [], - linedelimiters: [] - }; // 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; i++) { - // Lines starting with '---' could be mistaken for the "remove line" operation - // But they could be the header for the next file. Therefore prune such cases out. - if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { - break; - } - - var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; - - if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { - hunk.lines.push(diffstr[i]); - hunk.linedelimiters.push(delimiters[i] || '\n'); - - if (operation === '+') { - addCount++; - } else if (operation === '-') { - removeCount++; - } else if (operation === ' ') { - addCount++; - removeCount++; - } - } else { - break; - } - } // Handle the empty block count case - - - if (!addCount && hunk.newLines === 1) { - hunk.newLines = 0; - } - - if (!removeCount && hunk.oldLines === 1) { - hunk.oldLines = 0; - } // Perform optional sanity checking - - - if (options.strict) { - 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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9wYXJzZS5qcyJdLCJuYW1lcyI6WyJwYXJzZVBhdGNoIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJkaWZmc3RyIiwic3BsaXQiLCJkZWxpbWl0ZXJzIiwibWF0Y2giLCJsaXN0IiwiaSIsInBhcnNlSW5kZXgiLCJpbmRleCIsInB1c2giLCJsZW5ndGgiLCJsaW5lIiwidGVzdCIsImhlYWRlciIsImV4ZWMiLCJwYXJzZUZpbGVIZWFkZXIiLCJodW5rcyIsInBhcnNlSHVuayIsInN0cmljdCIsIkVycm9yIiwiSlNPTiIsInN0cmluZ2lmeSIsImZpbGVIZWFkZXIiLCJrZXlQcmVmaXgiLCJkYXRhIiwiZmlsZU5hbWUiLCJyZXBsYWNlIiwic3Vic3RyIiwidHJpbSIsImNodW5rSGVhZGVySW5kZXgiLCJjaHVua0hlYWRlckxpbmUiLCJjaHVua0hlYWRlciIsImh1bmsiLCJvbGRTdGFydCIsIm9sZExpbmVzIiwibmV3U3RhcnQiLCJuZXdMaW5lcyIsImxpbmVzIiwibGluZWRlbGltaXRlcnMiLCJhZGRDb3VudCIsInJlbW92ZUNvdW50IiwiaW5kZXhPZiIsIm9wZXJhdGlvbiJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQU8sU0FBU0EsVUFBVCxDQUFvQkMsT0FBcEIsRUFBMkM7QUFBQTtBQUFBO0FBQUE7QUFBZEMsRUFBQUEsT0FBYyx1RUFBSixFQUFJO0FBQ2hELE1BQUlDLE9BQU8sR0FBR0YsT0FBTyxDQUFDRyxLQUFSLENBQWMscUJBQWQsQ0FBZDtBQUFBLE1BQ0lDLFVBQVUsR0FBR0osT0FBTyxDQUFDSyxLQUFSLENBQWMsc0JBQWQsS0FBeUMsRUFEMUQ7QUFBQSxNQUVJQyxJQUFJLEdBQUcsRUFGWDtBQUFBLE1BR0lDLENBQUMsR0FBRyxDQUhSOztBQUtBLFdBQVNDLFVBQVQsR0FBc0I7QUFDcEIsUUFBSUMsS0FBSyxHQUFHLEVBQVo7QUFDQUgsSUFBQUEsSUFBSSxDQUFDSSxJQUFMLENBQVVELEtBQVYsRUFGb0IsQ0FJcEI7O0FBQ0EsV0FBT0YsQ0FBQyxHQUFHTCxPQUFPLENBQUNTLE1BQW5CLEVBQTJCO0FBQ3pCLFVBQUlDLElBQUksR0FBR1YsT0FBTyxDQUFDSyxDQUFELENBQWxCLENBRHlCLENBR3pCOztBQUNBLFVBQUssdUJBQUQsQ0FBMEJNLElBQTFCLENBQStCRCxJQUEvQixDQUFKLEVBQTBDO0FBQ3hDO0FBQ0QsT0FOd0IsQ0FRekI7OztBQUNBLFVBQUlFLE1BQU0sR0FBSSwwQ0FBRCxDQUE2Q0MsSUFBN0MsQ0FBa0RILElBQWxELENBQWI7O0FBQ0EsVUFBSUUsTUFBSixFQUFZO0FBQ1ZMLFFBQUFBLEtBQUssQ0FBQ0EsS0FBTixHQUFjSyxNQUFNLENBQUMsQ0FBRCxDQUFwQjtBQUNEOztBQUVEUCxNQUFBQSxDQUFDO0FBQ0YsS0FwQm1CLENBc0JwQjtBQUNBOzs7QUFDQVMsSUFBQUEsZUFBZSxDQUFDUCxLQUFELENBQWY7QUFDQU8sSUFBQUEsZUFBZSxDQUFDUCxLQUFELENBQWYsQ0F6Qm9CLENBMkJwQjs7QUFDQUEsSUFBQUEsS0FBSyxDQUFDUSxLQUFOLEdBQWMsRUFBZDs7QUFFQSxXQUFPVixDQUFDLEdBQUdMLE9BQU8sQ0FBQ1MsTUFBbkIsRUFBMkI7QUFDekIsVUFBSUMsS0FBSSxHQUFHVixPQUFPLENBQUNLLENBQUQsQ0FBbEI7O0FBRUEsVUFBSyxnQ0FBRCxDQUFtQ00sSUFBbkMsQ0FBd0NELEtBQXhDLENBQUosRUFBbUQ7QUFDakQ7QUFDRCxPQUZELE1BRU8sSUFBSyxLQUFELENBQVFDLElBQVIsQ0FBYUQsS0FBYixDQUFKLEVBQXdCO0FBQzdCSCxRQUFBQSxLQUFLLENBQUNRLEtBQU4sQ0FBWVAsSUFBWixDQUFpQlEsU0FBUyxFQUExQjtBQUNELE9BRk0sTUFFQSxJQUFJTixLQUFJLElBQUlYLE9BQU8sQ0FBQ2tCLE1BQXBCLEVBQTRCO0FBQ2pDO0FBQ0EsY0FBTSxJQUFJQyxLQUFKLENBQVUsbUJBQW1CYixDQUFDLEdBQUcsQ0FBdkIsSUFBNEIsR0FBNUIsR0FBa0NjLElBQUksQ0FBQ0MsU0FBTCxDQUFlVixLQUFmLENBQTVDLENBQU47QUFDRCxPQUhNLE1BR0E7QUFDTEwsUUFBQUEsQ0FBQztBQUNGO0FBQ0Y7QUFDRixHQWxEK0MsQ0FvRGhEO0FBQ0E7OztBQUNBLFdBQVNTLGVBQVQsQ0FBeUJQLEtBQXpCLEVBQWdDO0FBQzlCLFFBQU1jLFVBQVUsR0FBSSx1QkFBRCxDQUEwQlIsSUFBMUIsQ0FBK0JiLE9BQU8sQ0FBQ0ssQ0FBRCxDQUF0QyxDQUFuQjs7QUFDQSxRQUFJZ0IsVUFBSixFQUFnQjtBQUNkLFVBQUlDLFNBQVMsR0FBR0QsVUFBVSxDQUFDLENBQUQsQ0FBVixLQUFrQixLQUFsQixHQUEwQixLQUExQixHQUFrQyxLQUFsRDtBQUNBLFVBQU1FLElBQUksR0FBR0YsVUFBVSxDQUFDLENBQUQsQ0FBVixDQUFjcEIsS0FBZCxDQUFvQixJQUFwQixFQUEwQixDQUExQixDQUFiO0FBQ0EsVUFBSXVCLFFBQVEsR0FBR0QsSUFBSSxDQUFDLENBQUQsQ0FBSixDQUFRRSxPQUFSLENBQWdCLE9BQWhCLEVBQXlCLElBQXpCLENBQWY7O0FBQ0EsVUFBSyxRQUFELENBQVdkLElBQVgsQ0FBZ0JhLFFBQWhCLENBQUosRUFBK0I7QUFDN0JBLFFBQUFBLFFBQVEsR0FBR0EsUUFBUSxDQUFDRSxNQUFULENBQWdCLENBQWhCLEVBQW1CRixRQUFRLENBQUNmLE1BQVQsR0FBa0IsQ0FBckMsQ0FBWDtBQUNEOztBQUNERixNQUFBQSxLQUFLLENBQUNlLFNBQVMsR0FBRyxVQUFiLENBQUwsR0FBZ0NFLFFBQWhDO0FBQ0FqQixNQUFBQSxLQUFLLENBQUNlLFNBQVMsR0FBRyxRQUFiLENBQUwsR0FBOEIsQ0FBQ0MsSUFBSSxDQUFDLENBQUQsQ0FBSixJQUFXLEVBQVosRUFBZ0JJLElBQWhCLEVBQTlCO0FBRUF0QixNQUFBQSxDQUFDO0FBQ0Y7QUFDRixHQXBFK0MsQ0FzRWhEO0FBQ0E7OztBQUNBLFdBQVNXLFNBQVQsR0FBcUI7QUFDbkIsUUFBSVksZ0JBQWdCLEdBQUd2QixDQUF2QjtBQUFBLFFBQ0l3QixlQUFlLEdBQUc3QixPQUFPLENBQUNLLENBQUMsRUFBRixDQUQ3QjtBQUFBLFFBRUl5QixXQUFXLEdBQUdELGVBQWUsQ0FBQzVCLEtBQWhCLENBQXNCLDRDQUF0QixDQUZsQjtBQUlBLFFBQUk4QixJQUFJLEdBQUc7QUFDVEMsTUFBQUEsUUFBUSxFQUFFLENBQUNGLFdBQVcsQ0FBQyxDQUFELENBRGI7QUFFVEcsTUFBQUEsUUFBUSxFQUFFLE9BQU9ILFdBQVcsQ0FBQyxDQUFELENBQWxCLEtBQTBCLFdBQTFCLEdBQXdDLENBQXhDLEdBQTRDLENBQUNBLFdBQVcsQ0FBQyxDQUFELENBRnpEO0FBR1RJLE1BQUFBLFFBQVEsRUFBRSxDQUFDSixXQUFXLENBQUMsQ0FBRCxDQUhiO0FBSVRLLE1BQUFBLFFBQVEsRUFBRSxPQUFPTCxXQUFXLENBQUMsQ0FBRCxDQUFsQixLQUEwQixXQUExQixHQUF3QyxDQUF4QyxHQUE0QyxDQUFDQSxXQUFXLENBQUMsQ0FBRCxDQUp6RDtBQUtUTSxNQUFBQSxLQUFLLEVBQUUsRUFMRTtBQU1UQyxNQUFBQSxjQUFjLEVBQUU7QUFOUCxLQUFYLENBTG1CLENBY25CO0FBQ0E7QUFDQTs7QUFDQSxRQUFJTixJQUFJLENBQUNFLFFBQUwsS0FBa0IsQ0FBdEIsRUFBeUI7QUFDdkJGLE1BQUFBLElBQUksQ0FBQ0MsUUFBTCxJQUFpQixDQUFqQjtBQUNEOztBQUNELFFBQUlELElBQUksQ0FBQ0ksUUFBTCxLQUFrQixDQUF0QixFQUF5QjtBQUN2QkosTUFBQUEsSUFBSSxDQUFDRyxRQUFMLElBQWlCLENBQWpCO0FBQ0Q7O0FBRUQsUUFBSUksUUFBUSxHQUFHLENBQWY7QUFBQSxRQUNJQyxXQUFXLEdBQUcsQ0FEbEI7O0FBRUEsV0FBT2xDLENBQUMsR0FBR0wsT0FBTyxDQUFDUyxNQUFuQixFQUEyQkosQ0FBQyxFQUE1QixFQUFnQztBQUM5QjtBQUNBO0FBQ0EsVUFBSUwsT0FBTyxDQUFDSyxDQUFELENBQVAsQ0FBV21DLE9BQVgsQ0FBbUIsTUFBbkIsTUFBK0IsQ0FBL0IsSUFDTW5DLENBQUMsR0FBRyxDQUFKLEdBQVFMLE9BQU8sQ0FBQ1MsTUFEdEIsSUFFS1QsT0FBTyxDQUFDSyxDQUFDLEdBQUcsQ0FBTCxDQUFQLENBQWVtQyxPQUFmLENBQXVCLE1BQXZCLE1BQW1DLENBRnhDLElBR0t4QyxPQUFPLENBQUNLLENBQUMsR0FBRyxDQUFMLENBQVAsQ0FBZW1DLE9BQWYsQ0FBdUIsSUFBdkIsTUFBaUMsQ0FIMUMsRUFHNkM7QUFDekM7QUFDSDs7QUFDRCxVQUFJQyxTQUFTLEdBQUl6QyxPQUFPLENBQUNLLENBQUQsQ0FBUCxDQUFXSSxNQUFYLElBQXFCLENBQXJCLElBQTBCSixDQUFDLElBQUtMLE9BQU8sQ0FBQ1MsTUFBUixHQUFpQixDQUFsRCxHQUF3RCxHQUF4RCxHQUE4RFQsT0FBTyxDQUFDSyxDQUFELENBQVAsQ0FBVyxDQUFYLENBQTlFOztBQUVBLFVBQUlvQyxTQUFTLEtBQUssR0FBZCxJQUFxQkEsU0FBUyxLQUFLLEdBQW5DLElBQTBDQSxTQUFTLEtBQUssR0FBeEQsSUFBK0RBLFNBQVMsS0FBSyxJQUFqRixFQUF1RjtBQUNyRlYsUUFBQUEsSUFBSSxDQUFDSyxLQUFMLENBQVc1QixJQUFYLENBQWdCUixPQUFPLENBQUNLLENBQUQsQ0FBdkI7QUFDQTBCLFFBQUFBLElBQUksQ0FBQ00sY0FBTCxDQUFvQjdCLElBQXBCLENBQXlCTixVQUFVLENBQUNHLENBQUQsQ0FBVixJQUFpQixJQUExQzs7QUFFQSxZQUFJb0MsU0FBUyxLQUFLLEdBQWxCLEVBQXVCO0FBQ3JCSCxVQUFBQSxRQUFRO0FBQ1QsU0FGRCxNQUVPLElBQUlHLFNBQVMsS0FBSyxHQUFsQixFQUF1QjtBQUM1QkYsVUFBQUEsV0FBVztBQUNaLFNBRk0sTUFFQSxJQUFJRSxTQUFTLEtBQUssR0FBbEIsRUFBdUI7QUFDNUJILFVBQUFBLFFBQVE7QUFDUkMsVUFBQUEsV0FBVztBQUNaO0FBQ0YsT0FaRCxNQVlPO0FBQ0w7QUFDRDtBQUNGLEtBcERrQixDQXNEbkI7OztBQUNBLFFBQUksQ0FBQ0QsUUFBRCxJQUFhUCxJQUFJLENBQUNJLFFBQUwsS0FBa0IsQ0FBbkMsRUFBc0M7QUFDcENKLE1BQUFBLElBQUksQ0FBQ0ksUUFBTCxHQUFnQixDQUFoQjtBQUNEOztBQUNELFFBQUksQ0FBQ0ksV0FBRCxJQUFnQlIsSUFBSSxDQUFDRSxRQUFMLEtBQWtCLENBQXRDLEVBQXlDO0FBQ3ZDRixNQUFBQSxJQUFJLENBQUNFLFFBQUwsR0FBZ0IsQ0FBaEI7QUFDRCxLQTVEa0IsQ0E4RG5COzs7QUFDQSxRQUFJbEMsT0FBTyxDQUFDa0IsTUFBWixFQUFvQjtBQUNsQixVQUFJcUIsUUFBUSxLQUFLUCxJQUFJLENBQUNJLFFBQXRCLEVBQWdDO0FBQzlCLGNBQU0sSUFBSWpCLEtBQUosQ0FBVSxzREFBc0RVLGdCQUFnQixHQUFHLENBQXpFLENBQVYsQ0FBTjtBQUNEOztBQUNELFVBQUlXLFdBQVcsS0FBS1IsSUFBSSxDQUFDRSxRQUF6QixFQUFtQztBQUNqQyxjQUFNLElBQUlmLEtBQUosQ0FBVSx3REFBd0RVLGdCQUFnQixHQUFHLENBQTNFLENBQVYsQ0FBTjtBQUNEO0FBQ0Y7O0FBRUQsV0FBT0csSUFBUDtBQUNEOztBQUVELFNBQU8xQixDQUFDLEdBQUdMLE9BQU8sQ0FBQ1MsTUFBbkIsRUFBMkI7QUFDekJILElBQUFBLFVBQVU7QUFDWDs7QUFFRCxTQUFPRixJQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gcGFyc2VQYXRjaCh1bmlEaWZmLCBvcHRpb25zID0ge30pIHtcbiAgbGV0IGRpZmZzdHIgPSB1bmlEaWZmLnNwbGl0KC9cXHJcXG58W1xcblxcdlxcZlxcclxceDg1XS8pLFxuICAgICAgZGVsaW1pdGVycyA9IHVuaURpZmYubWF0Y2goL1xcclxcbnxbXFxuXFx2XFxmXFxyXFx4ODVdL2cpIHx8IFtdLFxuICAgICAgbGlzdCA9IFtdLFxuICAgICAgaSA9IDA7XG5cbiAgZnVuY3Rpb24gcGFyc2VJbmRleCgpIHtcbiAgICBsZXQgaW5kZXggPSB7fTtcbiAgICBsaXN0LnB1c2goaW5kZXgpO1xuXG4gICAgLy8gUGFyc2UgZGlmZiBtZXRhZGF0YVxuICAgIHdoaWxlIChpIDwgZGlmZnN0ci5sZW5ndGgpIHtcbiAgICAgIGxldCBsaW5lID0gZGlmZnN0cltpXTtcblxuICAgICAgLy8gRmlsZSBoZWFkZXIgZm91bmQsIGVuZCBwYXJzaW5nIGRpZmYgbWV0YWRhdGFcbiAgICAgIGlmICgoL14oXFwtXFwtXFwtfFxcK1xcK1xcK3xAQClcXHMvKS50ZXN0KGxpbmUpKSB7XG4gICAgICAgIGJyZWFrO1xuICAgICAgfVxuXG4gICAgICAvLyBEaWZmIGluZGV4XG4gICAgICBsZXQgaGVhZGVyID0gKC9eKD86SW5kZXg6fGRpZmYoPzogLXIgXFx3KykrKVxccysoLis/KVxccyokLykuZXhlYyhsaW5lKTtcbiAgICAgIGlmIChoZWFkZXIpIHtcbiAgICAgICAgaW5kZXguaW5kZXggPSBoZWFkZXJbMV07XG4gICAgICB9XG5cbiAgICAgIGkrKztcbiAgICB9XG5cbiAgICAvLyBQYXJzZSBmaWxlIGhlYWRlcnMgaWYgdGhleSBhcmUgZGVmaW5lZC4gVW5pZmllZCBkaWZmIHJlcXVpcmVzIHRoZW0sIGJ1dFxuICAgIC8vIHRoZXJlJ3Mgbm8gdGVjaG5pY2FsIGlzc3VlcyB0byBoYXZlIGFuIGlzb2xhdGVkIGh1bmsgd2l0aG91dCBmaWxlIGhlYWRlclxuICAgIHBhcnNlRmlsZUhlYWRlcihpbmRleCk7XG4gICAgcGFyc2VGaWxlSGVhZGVyKGluZGV4KTtcblxuICAgIC8vIFBhcnNlIGh1bmtzXG4gICAgaW5kZXguaHVua3MgPSBbXTtcblxuICAgIHdoaWxlIChpIDwgZGlmZnN0ci5sZW5ndGgpIHtcbiAgICAgIGxldCBsaW5lID0gZGlmZnN0cltpXTtcblxuICAgICAgaWYgKCgvXihJbmRleDp8ZGlmZnxcXC1cXC1cXC18XFwrXFwrXFwrKVxccy8pLnRlc3QobGluZSkpIHtcbiAgICAgICAgYnJlYWs7XG4gICAgICB9IGVsc2UgaWYgKCgvXkBALykudGVzdChsaW5lKSkge1xuICAgICAgICBpbmRleC5odW5rcy5wdXNoKHBhcnNlSHVuaygpKTtcbiAgICAgIH0gZWxzZSBpZiAobGluZSAmJiBvcHRpb25zLnN0cmljdCkge1xuICAgICAgICAvLyBJZ25vcmUgdW5leHBlY3RlZCBjb250ZW50IHVubGVzcyBpbiBzdHJpY3QgbW9kZVxuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ1Vua25vd24gbGluZSAnICsgKGkgKyAxKSArICcgJyArIEpTT04uc3RyaW5naWZ5KGxpbmUpKTtcbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIGkrKztcbiAgICAgIH1cbiAgICB9XG4gIH1cblxuICAvLyBQYXJzZXMgdGhlIC0tLSBhbmQgKysrIGhlYWRlcnMsIGlmIG5vbmUgYXJlIGZvdW5kLCBubyBsaW5lc1xuICAvLyBhcmUgY29uc3VtZWQuXG4gIGZ1bmN0aW9uIHBhcnNlRmlsZUhlYWRlcihpbmRleCkge1xuICAgIGNvbnN0IGZpbGVIZWFkZXIgPSAoL14oLS0tfFxcK1xcK1xcKylcXHMrKC4qKSQvKS5leGVjKGRpZmZzdHJbaV0pO1xuICAgIGlmIChmaWxlSGVhZGVyKSB7XG4gICAgICBsZXQga2V5UHJlZml4ID0gZmlsZUhlYWRlclsxXSA9PT0gJy0tLScgPyAnb2xkJyA6ICduZXcnO1xuICAgICAgY29uc3QgZGF0YSA9IGZpbGVIZWFkZXJbMl0uc3BsaXQoJ1xcdCcsIDIpO1xuICAgICAgbGV0IGZpbGVOYW1lID0gZGF0YVswXS5yZXBsYWNlKC9cXFxcXFxcXC9nLCAnXFxcXCcpO1xuICAgICAgaWYgKCgvXlwiLipcIiQvKS50ZXN0KGZpbGVOYW1lKSkge1xuICAgICAgICBmaWxlTmFtZSA9IGZpbGVOYW1lLnN1YnN0cigxLCBmaWxlTmFtZS5sZW5ndGggLSAyKTtcbiAgICAgIH1cbiAgICAgIGluZGV4W2tleVByZWZpeCArICdGaWxlTmFtZSddID0gZmlsZU5hbWU7XG4gICAgICBpbmRleFtrZXlQcmVmaXggKyAnSGVhZGVyJ10gPSAoZGF0YVsxXSB8fCAnJykudHJpbSgpO1xuXG4gICAgICBpKys7XG4gICAgfVxuICB9XG5cbiAgLy8gUGFyc2VzIGEgaHVua1xuICAvLyBUaGlzIGFzc3VtZXMgdGhhdCB3ZSBhcmUgYXQgdGhlIHN0YXJ0IG9mIGEgaHVuay5cbiAgZnVuY3Rpb24gcGFyc2VIdW5rKCkge1xuICAgIGxldCBjaHVua0hlYWRlckluZGV4ID0gaSxcbiAgICAgICAgY2h1bmtIZWFkZXJMaW5lID0gZGlmZnN0cltpKytdLFxuICAgICAgICBjaHVua0hlYWRlciA9IGNodW5rSGVhZGVyTGluZS5zcGxpdCgvQEAgLShcXGQrKSg/OiwoXFxkKykpPyBcXCsoXFxkKykoPzosKFxcZCspKT8gQEAvKTtcblxuICAgIGxldCBodW5rID0ge1xuICAgICAgb2xkU3RhcnQ6ICtjaHVua0hlYWRlclsxXSxcbiAgICAgIG9sZExpbmVzOiB0eXBlb2YgY2h1bmtIZWFkZXJbMl0gPT09ICd1bmRlZmluZWQnID8gMSA6ICtjaHVua0hlYWRlclsyXSxcbiAgICAgIG5ld1N0YXJ0OiArY2h1bmtIZWFkZXJbM10sXG4gICAgICBuZXdMaW5lczogdHlwZW9mIGNodW5rSGVhZGVyWzRdID09PSAndW5kZWZpbmVkJyA/IDEgOiArY2h1bmtIZWFkZXJbNF0sXG4gICAgICBsaW5lczogW10sXG4gICAgICBsaW5lZGVsaW1pdGVyczogW11cbiAgICB9O1xuXG4gICAgLy8gVW5pZmllZCBEaWZmIEZvcm1hdCBxdWlyazogSWYgdGhlIGNodW5rIHNpemUgaXMgMCxcbiAgICAvLyB0aGUgZmlyc3QgbnVtYmVyIGlzIG9uZSBsb3dlciB0aGFuIG9uZSB3b3VsZCBleHBlY3QuXG4gICAgLy8gaHR0cHM6Ly93d3cuYXJ0aW1hLmNvbS93ZWJsb2dzL3ZpZXdwb3N0LmpzcD90aHJlYWQ9MTY0MjkzXG4gICAgaWYgKGh1bmsub2xkTGluZXMgPT09IDApIHtcbiAgICAgIGh1bmsub2xkU3RhcnQgKz0gMTtcbiAgICB9XG4gICAgaWYgKGh1bmsubmV3TGluZXMgPT09IDApIHtcbiAgICAgIGh1bmsubmV3U3RhcnQgKz0gMTtcbiAgICB9XG5cbiAgICBsZXQgYWRkQ291bnQgPSAwLFxuICAgICAgICByZW1vdmVDb3VudCA9IDA7XG4gICAgZm9yICg7IGkgPCBkaWZmc3RyLmxlbmd0aDsgaSsrKSB7XG4gICAgICAvLyBMaW5lcyBzdGFydGluZyB3aXRoICctLS0nIGNvdWxkIGJlIG1pc3Rha2VuIGZvciB0aGUgXCJyZW1vdmUgbGluZVwiIG9wZXJhdGlvblxuICAgICAgLy8gQnV0IHRoZXkgY291bGQgYmUgdGhlIGhlYWRlciBmb3IgdGhlIG5leHQgZmlsZS4gVGhlcmVmb3JlIHBydW5lIHN1Y2ggY2FzZXMgb3V0LlxuICAgICAgaWYgKGRpZmZzdHJbaV0uaW5kZXhPZignLS0tICcpID09PSAwXG4gICAgICAgICAgICAmJiAoaSArIDIgPCBkaWZmc3RyLmxlbmd0aClcbiAgICAgICAgICAgICYmIGRpZmZzdHJbaSArIDFdLmluZGV4T2YoJysrKyAnKSA9PT0gMFxuICAgICAgICAgICAgJiYgZGlmZnN0cltpICsgMl0uaW5kZXhPZignQEAnKSA9PT0gMCkge1xuICAgICAgICAgIGJyZWFrO1xuICAgICAgfVxuICAgICAgbGV0IG9wZXJhdGlvbiA9IChkaWZmc3RyW2ldLmxlbmd0aCA9PSAwICYmIGkgIT0gKGRpZmZzdHIubGVuZ3RoIC0gMSkpID8gJyAnIDogZGlmZnN0cltpXVswXTtcblxuICAgICAgaWYgKG9wZXJhdGlvbiA9PT0gJysnIHx8IG9wZXJhdGlvbiA9PT0gJy0nIHx8IG9wZXJhdGlvbiA9PT0gJyAnIHx8IG9wZXJhdGlvbiA9PT0gJ1xcXFwnKSB7XG4gICAgICAgIGh1bmsubGluZXMucHVzaChkaWZmc3RyW2ldKTtcbiAgICAgICAgaHVuay5saW5lZGVsaW1pdGVycy5wdXNoKGRlbGltaXRlcnNbaV0gfHwgJ1xcbicpO1xuXG4gICAgICAgIGlmIChvcGVyYXRpb24gPT09ICcrJykge1xuICAgICAgICAgIGFkZENvdW50Kys7XG4gICAgICAgIH0gZWxzZSBpZiAob3BlcmF0aW9uID09PSAnLScpIHtcbiAgICAgICAgICByZW1vdmVDb3VudCsrO1xuICAgICAgICB9IGVsc2UgaWYgKG9wZXJhdGlvbiA9PT0gJyAnKSB7XG4gICAgICAgICAgYWRkQ291bnQrKztcbiAgICAgICAgICByZW1vdmVDb3VudCsrO1xuICAgICAgICB9XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBicmVhaztcbiAgICAgIH1cbiAgICB9XG5cbiAgICAvLyBIYW5kbGUgdGhlIGVtcHR5IGJsb2NrIGNvdW50IGNhc2VcbiAgICBpZiAoIWFkZENvdW50ICYmIGh1bmsubmV3TGluZXMgPT09IDEpIHtcbiAgICAgIGh1bmsubmV3TGluZXMgPSAwO1xuICAgIH1cbiAgICBpZiAoIXJlbW92ZUNvdW50ICYmIGh1bmsub2xkTGluZXMgPT09IDEpIHtcbiAgICAgIGh1bmsub2xkTGluZXMgPSAwO1xuICAgIH1cblxuICAgIC8vIFBlcmZvcm0gb3B0aW9uYWwgc2FuaXR5IGNoZWNraW5nXG4gICAgaWYgKG9wdGlvbnMuc3RyaWN0KSB7XG4gICAgICBpZiAoYWRkQ291bnQgIT09IGh1bmsubmV3TGluZXMpIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdBZGRlZCBsaW5lIGNvdW50IGRpZCBub3QgbWF0Y2ggZm9yIGh1bmsgYXQgbGluZSAnICsgKGNodW5rSGVhZGVySW5kZXggKyAxKSk7XG4gICAgICB9XG4gICAgICBpZiAocmVtb3ZlQ291bnQgIT09IGh1bmsub2xkTGluZXMpIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdSZW1vdmVkIGxpbmUgY291bnQgZGlkIG5vdCBtYXRjaCBmb3IgaHVuayBhdCBsaW5lICcgKyAoY2h1bmtIZWFkZXJJbmRleCArIDEpKTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICByZXR1cm4gaHVuaztcbiAgfVxuXG4gIHdoaWxlIChpIDwgZGlmZnN0ci5sZW5ndGgpIHtcbiAgICBwYXJzZUluZGV4KCk7XG4gIH1cblxuICByZXR1cm4gbGlzdDtcbn1cbiJdfQ== diff --git a/node_modules/diff/lib/patch/reverse.js b/node_modules/diff/lib/patch/reverse.js deleted file mode 100644 index 6e4be99af8ac3..0000000000000 --- a/node_modules/diff/lib/patch/reverse.js +++ /dev/null @@ -1,63 +0,0 @@ -/*istanbul ignore start*/ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.reversePatch = reversePatch; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -/*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, - linedelimiters: hunk.linedelimiters, - 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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9yZXZlcnNlLmpzIl0sIm5hbWVzIjpbInJldmVyc2VQYXRjaCIsInN0cnVjdHVyZWRQYXRjaCIsIkFycmF5IiwiaXNBcnJheSIsIm1hcCIsInJldmVyc2UiLCJvbGRGaWxlTmFtZSIsIm5ld0ZpbGVOYW1lIiwib2xkSGVhZGVyIiwibmV3SGVhZGVyIiwiaHVua3MiLCJodW5rIiwib2xkTGluZXMiLCJuZXdMaW5lcyIsIm9sZFN0YXJ0IiwibmV3U3RhcnQiLCJsaW5lZGVsaW1pdGVycyIsImxpbmVzIiwibCIsInN0YXJ0c1dpdGgiLCJzbGljZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7O0FBQU8sU0FBU0EsWUFBVCxDQUFzQkMsZUFBdEIsRUFBdUM7QUFDNUMsTUFBSUMsS0FBSyxDQUFDQyxPQUFOLENBQWNGLGVBQWQsQ0FBSixFQUFvQztBQUNsQyxXQUFPQSxlQUFlLENBQUNHLEdBQWhCLENBQW9CSixZQUFwQixFQUFrQ0ssT0FBbEMsRUFBUDtBQUNEOztBQUVEO0FBQUE7QUFBQTtBQUFBO0FBQ0tKLElBQUFBLGVBREw7QUFFRUssTUFBQUEsV0FBVyxFQUFFTCxlQUFlLENBQUNNLFdBRi9CO0FBR0VDLE1BQUFBLFNBQVMsRUFBRVAsZUFBZSxDQUFDUSxTQUg3QjtBQUlFRixNQUFBQSxXQUFXLEVBQUVOLGVBQWUsQ0FBQ0ssV0FKL0I7QUFLRUcsTUFBQUEsU0FBUyxFQUFFUixlQUFlLENBQUNPLFNBTDdCO0FBTUVFLE1BQUFBLEtBQUssRUFBRVQsZUFBZSxDQUFDUyxLQUFoQixDQUFzQk4sR0FBdEIsQ0FBMEIsVUFBQU8sSUFBSSxFQUFJO0FBQ3ZDLGVBQU87QUFDTEMsVUFBQUEsUUFBUSxFQUFFRCxJQUFJLENBQUNFLFFBRFY7QUFFTEMsVUFBQUEsUUFBUSxFQUFFSCxJQUFJLENBQUNJLFFBRlY7QUFHTEYsVUFBQUEsUUFBUSxFQUFFRixJQUFJLENBQUNDLFFBSFY7QUFJTEcsVUFBQUEsUUFBUSxFQUFFSixJQUFJLENBQUNHLFFBSlY7QUFLTEUsVUFBQUEsY0FBYyxFQUFFTCxJQUFJLENBQUNLLGNBTGhCO0FBTUxDLFVBQUFBLEtBQUssRUFBRU4sSUFBSSxDQUFDTSxLQUFMLENBQVdiLEdBQVgsQ0FBZSxVQUFBYyxDQUFDLEVBQUk7QUFDekIsZ0JBQUlBLENBQUMsQ0FBQ0MsVUFBRixDQUFhLEdBQWIsQ0FBSixFQUF1QjtBQUFFO0FBQUE7QUFBQTtBQUFBO0FBQVdELGdCQUFBQSxDQUFDLENBQUNFLEtBQUYsQ0FBUSxDQUFSLENBQVg7QUFBQTtBQUEwQjs7QUFDbkQsZ0JBQUlGLENBQUMsQ0FBQ0MsVUFBRixDQUFhLEdBQWIsQ0FBSixFQUF1QjtBQUFFO0FBQUE7QUFBQTtBQUFBO0FBQVdELGdCQUFBQSxDQUFDLENBQUNFLEtBQUYsQ0FBUSxDQUFSLENBQVg7QUFBQTtBQUEwQjs7QUFDbkQsbUJBQU9GLENBQVA7QUFDRCxXQUpNO0FBTkYsU0FBUDtBQVlELE9BYk07QUFOVDtBQUFBO0FBcUJEIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IGZ1bmN0aW9uIHJldmVyc2VQYXRjaChzdHJ1Y3R1cmVkUGF0Y2gpIHtcbiAgaWYgKEFycmF5LmlzQXJyYXkoc3RydWN0dXJlZFBhdGNoKSkge1xuICAgIHJldHVybiBzdHJ1Y3R1cmVkUGF0Y2gubWFwKHJldmVyc2VQYXRjaCkucmV2ZXJzZSgpO1xuICB9XG5cbiAgcmV0dXJuIHtcbiAgICAuLi5zdHJ1Y3R1cmVkUGF0Y2gsXG4gICAgb2xkRmlsZU5hbWU6IHN0cnVjdHVyZWRQYXRjaC5uZXdGaWxlTmFtZSxcbiAgICBvbGRIZWFkZXI6IHN0cnVjdHVyZWRQYXRjaC5uZXdIZWFkZXIsXG4gICAgbmV3RmlsZU5hbWU6IHN0cnVjdHVyZWRQYXRjaC5vbGRGaWxlTmFtZSxcbiAgICBuZXdIZWFkZXI6IHN0cnVjdHVyZWRQYXRjaC5vbGRIZWFkZXIsXG4gICAgaHVua3M6IHN0cnVjdHVyZWRQYXRjaC5odW5rcy5tYXAoaHVuayA9PiB7XG4gICAgICByZXR1cm4ge1xuICAgICAgICBvbGRMaW5lczogaHVuay5uZXdMaW5lcyxcbiAgICAgICAgb2xkU3RhcnQ6IGh1bmsubmV3U3RhcnQsXG4gICAgICAgIG5ld0xpbmVzOiBodW5rLm9sZExpbmVzLFxuICAgICAgICBuZXdTdGFydDogaHVuay5vbGRTdGFydCxcbiAgICAgICAgbGluZWRlbGltaXRlcnM6IGh1bmsubGluZWRlbGltaXRlcnMsXG4gICAgICAgIGxpbmVzOiBodW5rLmxpbmVzLm1hcChsID0+IHtcbiAgICAgICAgICBpZiAobC5zdGFydHNXaXRoKCctJykpIHsgcmV0dXJuIGArJHtsLnNsaWNlKDEpfWA7IH1cbiAgICAgICAgICBpZiAobC5zdGFydHNXaXRoKCcrJykpIHsgcmV0dXJuIGAtJHtsLnNsaWNlKDEpfWA7IH1cbiAgICAgICAgICByZXR1cm4gbDtcbiAgICAgICAgfSlcbiAgICAgIH07XG4gICAgfSlcbiAgfTtcbn1cbiJdfQ== diff --git a/node_modules/diff/lib/util/array.js b/node_modules/diff/lib/util/array.js deleted file mode 100644 index aecf67ac817c1..0000000000000 --- a/node_modules/diff/lib/util/array.js +++ /dev/null @@ -1,32 +0,0 @@ -/*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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2FycmF5LmpzIl0sIm5hbWVzIjpbImFycmF5RXF1YWwiLCJhIiwiYiIsImxlbmd0aCIsImFycmF5U3RhcnRzV2l0aCIsImFycmF5Iiwic3RhcnQiLCJpIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQU8sU0FBU0EsVUFBVCxDQUFvQkMsQ0FBcEIsRUFBdUJDLENBQXZCLEVBQTBCO0FBQy9CLE1BQUlELENBQUMsQ0FBQ0UsTUFBRixLQUFhRCxDQUFDLENBQUNDLE1BQW5CLEVBQTJCO0FBQ3pCLFdBQU8sS0FBUDtBQUNEOztBQUVELFNBQU9DLGVBQWUsQ0FBQ0gsQ0FBRCxFQUFJQyxDQUFKLENBQXRCO0FBQ0Q7O0FBRU0sU0FBU0UsZUFBVCxDQUF5QkMsS0FBekIsRUFBZ0NDLEtBQWhDLEVBQXVDO0FBQzVDLE1BQUlBLEtBQUssQ0FBQ0gsTUFBTixHQUFlRSxLQUFLLENBQUNGLE1BQXpCLEVBQWlDO0FBQy9CLFdBQU8sS0FBUDtBQUNEOztBQUVELE9BQUssSUFBSUksQ0FBQyxHQUFHLENBQWIsRUFBZ0JBLENBQUMsR0FBR0QsS0FBSyxDQUFDSCxNQUExQixFQUFrQ0ksQ0FBQyxFQUFuQyxFQUF1QztBQUNyQyxRQUFJRCxLQUFLLENBQUNDLENBQUQsQ0FBTCxLQUFhRixLQUFLLENBQUNFLENBQUQsQ0FBdEIsRUFBMkI7QUFDekIsYUFBTyxLQUFQO0FBQ0Q7QUFDRjs7QUFFRCxTQUFPLElBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBmdW5jdGlvbiBhcnJheUVxdWFsKGEsIGIpIHtcbiAgaWYgKGEubGVuZ3RoICE9PSBiLmxlbmd0aCkge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIHJldHVybiBhcnJheVN0YXJ0c1dpdGgoYSwgYik7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBhcnJheVN0YXJ0c1dpdGgoYXJyYXksIHN0YXJ0KSB7XG4gIGlmIChzdGFydC5sZW5ndGggPiBhcnJheS5sZW5ndGgpIHtcbiAgICByZXR1cm4gZmFsc2U7XG4gIH1cblxuICBmb3IgKGxldCBpID0gMDsgaSA8IHN0YXJ0Lmxlbmd0aDsgaSsrKSB7XG4gICAgaWYgKHN0YXJ0W2ldICE9PSBhcnJheVtpXSkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiB0cnVlO1xufVxuIl19 diff --git a/node_modules/diff/lib/util/distance-iterator.js b/node_modules/diff/lib/util/distance-iterator.js deleted file mode 100644 index 57c06a3f9cf1c..0000000000000 --- a/node_modules/diff/lib/util/distance-iterator.js +++ /dev/null @@ -1,57 +0,0 @@ -/*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 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 -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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2Rpc3RhbmNlLWl0ZXJhdG9yLmpzIl0sIm5hbWVzIjpbInN0YXJ0IiwibWluTGluZSIsIm1heExpbmUiLCJ3YW50Rm9yd2FyZCIsImJhY2t3YXJkRXhoYXVzdGVkIiwiZm9yd2FyZEV4aGF1c3RlZCIsImxvY2FsT2Zmc2V0IiwiaXRlcmF0b3IiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztBQUFBO0FBQ0E7QUFDQTtBQUNlO0FBQUE7QUFBQTtBQUFBO0FBQUEsQ0FBU0EsS0FBVCxFQUFnQkMsT0FBaEIsRUFBeUJDLE9BQXpCLEVBQWtDO0FBQy9DLE1BQUlDLFdBQVcsR0FBRyxJQUFsQjtBQUFBLE1BQ0lDLGlCQUFpQixHQUFHLEtBRHhCO0FBQUEsTUFFSUMsZ0JBQWdCLEdBQUcsS0FGdkI7QUFBQSxNQUdJQyxXQUFXLEdBQUcsQ0FIbEI7QUFLQSxTQUFPLFNBQVNDLFFBQVQsR0FBb0I7QUFDekIsUUFBSUosV0FBVyxJQUFJLENBQUNFLGdCQUFwQixFQUFzQztBQUNwQyxVQUFJRCxpQkFBSixFQUF1QjtBQUNyQkUsUUFBQUEsV0FBVztBQUNaLE9BRkQsTUFFTztBQUNMSCxRQUFBQSxXQUFXLEdBQUcsS0FBZDtBQUNELE9BTG1DLENBT3BDO0FBQ0E7OztBQUNBLFVBQUlILEtBQUssR0FBR00sV0FBUixJQUF1QkosT0FBM0IsRUFBb0M7QUFDbEMsZUFBT0ksV0FBUDtBQUNEOztBQUVERCxNQUFBQSxnQkFBZ0IsR0FBRyxJQUFuQjtBQUNEOztBQUVELFFBQUksQ0FBQ0QsaUJBQUwsRUFBd0I7QUFDdEIsVUFBSSxDQUFDQyxnQkFBTCxFQUF1QjtBQUNyQkYsUUFBQUEsV0FBVyxHQUFHLElBQWQ7QUFDRCxPQUhxQixDQUt0QjtBQUNBOzs7QUFDQSxVQUFJRixPQUFPLElBQUlELEtBQUssR0FBR00sV0FBdkIsRUFBb0M7QUFDbEMsZUFBTyxDQUFDQSxXQUFXLEVBQW5CO0FBQ0Q7O0FBRURGLE1BQUFBLGlCQUFpQixHQUFHLElBQXBCO0FBQ0EsYUFBT0csUUFBUSxFQUFmO0FBQ0QsS0E5QndCLENBZ0N6QjtBQUNBOztBQUNELEdBbENEO0FBbUNEIiwic291cmNlc0NvbnRlbnQiOlsiLy8gSXRlcmF0b3IgdGhhdCB0cmF2ZXJzZXMgaW4gdGhlIHJhbmdlIG9mIFttaW4sIG1heF0sIHN0ZXBwaW5nXG4vLyBieSBkaXN0YW5jZSBmcm9tIGEgZ2l2ZW4gc3RhcnQgcG9zaXRpb24uIEkuZS4gZm9yIFswLCA0XSwgd2l0aFxuLy8gc3RhcnQgb2YgMiwgdGhpcyB3aWxsIGl0ZXJhdGUgMiwgMywgMSwgNCwgMC5cbmV4cG9ydCBkZWZhdWx0IGZ1bmN0aW9uKHN0YXJ0LCBtaW5MaW5lLCBtYXhMaW5lKSB7XG4gIGxldCB3YW50Rm9yd2FyZCA9IHRydWUsXG4gICAgICBiYWNrd2FyZEV4aGF1c3RlZCA9IGZhbHNlLFxuICAgICAgZm9yd2FyZEV4aGF1c3RlZCA9IGZhbHNlLFxuICAgICAgbG9jYWxPZmZzZXQgPSAxO1xuXG4gIHJldHVybiBmdW5jdGlvbiBpdGVyYXRvcigpIHtcbiAgICBpZiAod2FudEZvcndhcmQgJiYgIWZvcndhcmRFeGhhdXN0ZWQpIHtcbiAgICAgIGlmIChiYWNrd2FyZEV4aGF1c3RlZCkge1xuICAgICAgICBsb2NhbE9mZnNldCsrO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgd2FudEZvcndhcmQgPSBmYWxzZTtcbiAgICAgIH1cblxuICAgICAgLy8gQ2hlY2sgaWYgdHJ5aW5nIHRvIGZpdCBiZXlvbmQgdGV4dCBsZW5ndGgsIGFuZCBpZiBub3QsIGNoZWNrIGl0IGZpdHNcbiAgICAgIC8vIGFmdGVyIG9mZnNldCBsb2NhdGlvbiAob3IgZGVzaXJlZCBsb2NhdGlvbiBvbiBmaXJzdCBpdGVyYXRpb24pXG4gICAgICBpZiAoc3RhcnQgKyBsb2NhbE9mZnNldCA8PSBtYXhMaW5lKSB7XG4gICAgICAgIHJldHVybiBsb2NhbE9mZnNldDtcbiAgICAgIH1cblxuICAgICAgZm9yd2FyZEV4aGF1c3RlZCA9IHRydWU7XG4gICAgfVxuXG4gICAgaWYgKCFiYWNrd2FyZEV4aGF1c3RlZCkge1xuICAgICAgaWYgKCFmb3J3YXJkRXhoYXVzdGVkKSB7XG4gICAgICAgIHdhbnRGb3J3YXJkID0gdHJ1ZTtcbiAgICAgIH1cblxuICAgICAgLy8gQ2hlY2sgaWYgdHJ5aW5nIHRvIGZpdCBiZWZvcmUgdGV4dCBiZWdpbm5pbmcsIGFuZCBpZiBub3QsIGNoZWNrIGl0IGZpdHNcbiAgICAgIC8vIGJlZm9yZSBvZmZzZXQgbG9jYXRpb25cbiAgICAgIGlmIChtaW5MaW5lIDw9IHN0YXJ0IC0gbG9jYWxPZmZzZXQpIHtcbiAgICAgICAgcmV0dXJuIC1sb2NhbE9mZnNldCsrO1xuICAgICAgfVxuXG4gICAgICBiYWNrd2FyZEV4aGF1c3RlZCA9IHRydWU7XG4gICAgICByZXR1cm4gaXRlcmF0b3IoKTtcbiAgICB9XG5cbiAgICAvLyBXZSB0cmllZCB0byBmaXQgaHVuayBiZWZvcmUgdGV4dCBiZWdpbm5pbmcgYW5kIGJleW9uZCB0ZXh0IGxlbmd0aCwgdGhlblxuICAgIC8vIGh1bmsgY2FuJ3QgZml0IG9uIHRoZSB0ZXh0LiBSZXR1cm4gdW5kZWZpbmVkXG4gIH07XG59XG4iXX0= diff --git a/node_modules/diff/lib/util/params.js b/node_modules/diff/lib/util/params.js deleted file mode 100644 index e838eb2f42d15..0000000000000 --- a/node_modules/diff/lib/util/params.js +++ /dev/null @@ -1,24 +0,0 @@ -/*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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL3BhcmFtcy5qcyJdLCJuYW1lcyI6WyJnZW5lcmF0ZU9wdGlvbnMiLCJvcHRpb25zIiwiZGVmYXVsdHMiLCJjYWxsYmFjayIsIm5hbWUiLCJoYXNPd25Qcm9wZXJ0eSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQU8sU0FBU0EsZUFBVCxDQUF5QkMsT0FBekIsRUFBa0NDLFFBQWxDLEVBQTRDO0FBQ2pELE1BQUksT0FBT0QsT0FBUCxLQUFtQixVQUF2QixFQUFtQztBQUNqQ0MsSUFBQUEsUUFBUSxDQUFDQyxRQUFULEdBQW9CRixPQUFwQjtBQUNELEdBRkQsTUFFTyxJQUFJQSxPQUFKLEVBQWE7QUFDbEIsU0FBSyxJQUFJRyxJQUFULElBQWlCSCxPQUFqQixFQUEwQjtBQUN4QjtBQUNBLFVBQUlBLE9BQU8sQ0FBQ0ksY0FBUixDQUF1QkQsSUFBdkIsQ0FBSixFQUFrQztBQUNoQ0YsUUFBQUEsUUFBUSxDQUFDRSxJQUFELENBQVIsR0FBaUJILE9BQU8sQ0FBQ0csSUFBRCxDQUF4QjtBQUNEO0FBQ0Y7QUFDRjs7QUFDRCxTQUFPRixRQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIGRlZmF1bHRzKSB7XG4gIGlmICh0eXBlb2Ygb3B0aW9ucyA9PT0gJ2Z1bmN0aW9uJykge1xuICAgIGRlZmF1bHRzLmNhbGxiYWNrID0gb3B0aW9ucztcbiAgfSBlbHNlIGlmIChvcHRpb25zKSB7XG4gICAgZm9yIChsZXQgbmFtZSBpbiBvcHRpb25zKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9wdGlvbnMuaGFzT3duUHJvcGVydHkobmFtZSkpIHtcbiAgICAgICAgZGVmYXVsdHNbbmFtZV0gPSBvcHRpb25zW25hbWVdO1xuICAgICAgfVxuICAgIH1cbiAgfVxuICByZXR1cm4gZGVmYXVsdHM7XG59XG4iXX0= diff --git a/node_modules/diff/libcjs/convert/dmp.js b/node_modules/diff/libcjs/convert/dmp.js new file mode 100644 index 0000000000000..10680ff38801f --- /dev/null +++ b/node_modules/diff/libcjs/convert/dmp.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertChangesToDMP = convertChangesToDMP; +/** + * converts a list of change objects to the format returned by Google's [diff-match-patch](https://github.com/google/diff-match-patch) library + */ +function convertChangesToDMP(changes) { + var ret = []; + var 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; +} diff --git a/node_modules/diff/libcjs/convert/xml.js b/node_modules/diff/libcjs/convert/xml.js new file mode 100644 index 0000000000000..5ecd8aa255b86 --- /dev/null +++ b/node_modules/diff/libcjs/convert/xml.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertChangesToXML = convertChangesToXML; +/** + * converts a list of change objects to a serialized XML format + */ +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; +} diff --git a/node_modules/diff/libcjs/diff/array.js b/node_modules/diff/libcjs/diff/array.js new file mode 100644 index 0000000000000..2050261be823f --- /dev/null +++ b/node_modules/diff/libcjs/diff/array.js @@ -0,0 +1,40 @@ +"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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.arrayDiff = void 0; +exports.diffArrays = diffArrays; +var base_js_1 = require("./base.js"); +var ArrayDiff = /** @class */ (function (_super) { + __extends(ArrayDiff, _super); + function ArrayDiff() { + return _super !== null && _super.apply(this, arguments) || this; + } + ArrayDiff.prototype.tokenize = function (value) { + return value.slice(); + }; + ArrayDiff.prototype.join = function (value) { + return value; + }; + ArrayDiff.prototype.removeEmpty = function (value) { + return value; + }; + return ArrayDiff; +}(base_js_1.default)); +exports.arrayDiff = new ArrayDiff(); +function diffArrays(oldArr, newArr, options) { + return exports.arrayDiff.diff(oldArr, newArr, options); +} diff --git a/node_modules/diff/libcjs/diff/base.js b/node_modules/diff/libcjs/diff/base.js new file mode 100644 index 0000000000000..5248d95693009 --- /dev/null +++ b/node_modules/diff/libcjs/diff/base.js @@ -0,0 +1,265 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Diff = /** @class */ (function () { + function Diff() { + } + Diff.prototype.diff = function (oldStr, newStr, + // Type below is not accurate/complete - see above for full possibilities - but it compiles + options) { + if (options === void 0) { options = {}; } + var callback; + if (typeof options === 'function') { + callback = options; + options = {}; + } + else if ('callback' in options) { + callback = options.callback; + } + // Allow subclasses to massage the input prior to running + var oldString = this.castInput(oldStr, options); + var newString = this.castInput(newStr, options); + var oldTokens = this.removeEmpty(this.tokenize(oldString, options)); + var newTokens = this.removeEmpty(this.tokenize(newString, options)); + return this.diffWithOptionsObj(oldTokens, newTokens, options, callback); + }; + Diff.prototype.diffWithOptionsObj = function (oldTokens, newTokens, options, callback) { + var _this = this; + var _a; + var done = function (value) { + value = _this.postProcess(value, options); + if (callback) { + setTimeout(function () { callback(value); }, 0); + return undefined; + } + else { + return value; + } + }; + var newLen = newTokens.length, oldLen = oldTokens.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + if (options.maxEditLength != null) { + maxEditLength = Math.min(maxEditLength, options.maxEditLength); + } + var maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : 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], newTokens, oldTokens, 0, options); + if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + // Identity per the equality and tokenizer + return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens)); + } + // 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. + var execEditLength = function () { + 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 + // @ts-expect-error - perf optimisation. This type-violating value will never be read. + 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 + // @ts-expect-error - perf optimisation. This type-violating value will never be read. + 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 = _this.addToPath(addPath, true, false, 0, options); + } + else { + basePath = _this.addToPath(removePath, false, true, 1, options); + } + newPos = _this.extractCommon(basePath, newTokens, oldTokens, 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(_this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true; + } + 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(undefined); + } + if (!execEditLength()) { + exec(); + } + }, 0); + }()); + } + else { + while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { + var ret = execEditLength(); + if (ret) { + return ret; + } + } + } + }; + Diff.prototype.addToPath = function (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 } + }; + } + }; + Diff.prototype.extractCommon = function (basePath, newTokens, oldTokens, diagonalPath, options) { + var newLen = newTokens.length, oldLen = oldTokens.length; + var oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[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; + }; + Diff.prototype.equals = function (left, right, options) { + if (options.comparator) { + return options.comparator(left, right); + } + else { + return left === right + || (!!options.ignoreCase && left.toLowerCase() === right.toLowerCase()); + } + }; + Diff.prototype.removeEmpty = function (array) { + var ret = []; + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; + }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + Diff.prototype.castInput = function (value, options) { + return value; + }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + Diff.prototype.tokenize = function (value, options) { + return Array.from(value); + }; + Diff.prototype.join = function (chars) { + // Assumes ValueT is string, which is the case for most subclasses. + // When it's false, e.g. in diffArrays, this method needs to be overridden (e.g. with a no-op) + // Yes, the casts are verbose and ugly, because this pattern - of having the base class SORT OF + // assume tokens and values are strings, but not completely - is weird and janky. + return chars.join(''); + }; + Diff.prototype.postProcess = function (changeObjects, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + options) { + return changeObjects; + }; + Object.defineProperty(Diff.prototype, "useLongestToken", { + get: function () { + return false; + }, + enumerable: false, + configurable: true + }); + Diff.prototype.buildValues = function (lastComponent, newTokens, oldTokens) { + // 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 componentLen = components.length; + var componentPos = 0, newPos = 0, oldPos = 0; + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + if (!component.removed) { + if (!component.added && this.useLongestToken) { + var value = newTokens.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldTokens[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = this.join(value); + } + else { + component.value = this.join(newTokens.slice(newPos, newPos + component.count)); + } + newPos += component.count; + // Common case + if (!component.added) { + oldPos += component.count; + } + } + else { + component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count)); + oldPos += component.count; + } + } + return components; + }; + return Diff; +}()); +exports.default = Diff; diff --git a/node_modules/diff/libcjs/diff/character.js b/node_modules/diff/libcjs/diff/character.js new file mode 100644 index 0000000000000..8e974ef9ad551 --- /dev/null +++ b/node_modules/diff/libcjs/diff/character.js @@ -0,0 +1,31 @@ +"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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.characterDiff = void 0; +exports.diffChars = diffChars; +var base_js_1 = require("./base.js"); +var CharacterDiff = /** @class */ (function (_super) { + __extends(CharacterDiff, _super); + function CharacterDiff() { + return _super !== null && _super.apply(this, arguments) || this; + } + return CharacterDiff; +}(base_js_1.default)); +exports.characterDiff = new CharacterDiff(); +function diffChars(oldStr, newStr, options) { + return exports.characterDiff.diff(oldStr, newStr, options); +} diff --git a/node_modules/diff/libcjs/diff/css.js b/node_modules/diff/libcjs/diff/css.js new file mode 100644 index 0000000000000..45c5559c00cc1 --- /dev/null +++ b/node_modules/diff/libcjs/diff/css.js @@ -0,0 +1,34 @@ +"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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.cssDiff = void 0; +exports.diffCss = diffCss; +var base_js_1 = require("./base.js"); +var CssDiff = /** @class */ (function (_super) { + __extends(CssDiff, _super); + function CssDiff() { + return _super !== null && _super.apply(this, arguments) || this; + } + CssDiff.prototype.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); + }; + return CssDiff; +}(base_js_1.default)); +exports.cssDiff = new CssDiff(); +function diffCss(oldStr, newStr, options) { + return exports.cssDiff.diff(oldStr, newStr, options); +} diff --git a/node_modules/diff/libcjs/diff/json.js b/node_modules/diff/libcjs/diff/json.js new file mode 100644 index 0000000000000..15f942b4b9168 --- /dev/null +++ b/node_modules/diff/libcjs/diff/json.js @@ -0,0 +1,105 @@ +"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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.jsonDiff = void 0; +exports.diffJson = diffJson; +exports.canonicalize = canonicalize; +var base_js_1 = require("./base.js"); +var line_js_1 = require("./line.js"); +var JsonDiff = /** @class */ (function (_super) { + __extends(JsonDiff, _super); + function JsonDiff() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.tokenize = line_js_1.tokenize; + return _this; + } + Object.defineProperty(JsonDiff.prototype, "useLongestToken", { + get: function () { + // 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: + return true; + }, + enumerable: false, + configurable: true + }); + JsonDiff.prototype.castInput = function (value, options) { + var undefinedReplacement = options.undefinedReplacement, _a = options.stringifyReplacer, stringifyReplacer = _a === void 0 ? function (k, v) { return typeof v === 'undefined' ? undefinedReplacement : v; } : _a; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), null, ' '); + }; + JsonDiff.prototype.equals = function (left, right, options) { + return _super.prototype.equals.call(this, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'), options); + }; + return JsonDiff; +}(base_js_1.default)); +exports.jsonDiff = new JsonDiff(); +function diffJson(oldStr, newStr, options) { + return exports.jsonDiff.diff(oldStr, newStr, 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 === undefined ? '' : 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, String(i)); + } + 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 = []; + var key_1; + for (key_1 in obj) { + /* istanbul ignore else */ + if (Object.prototype.hasOwnProperty.call(obj, key_1)) { + sortedKeys.push(key_1); + } + } + sortedKeys.sort(); + for (i = 0; i < sortedKeys.length; i += 1) { + key_1 = sortedKeys[i]; + canonicalizedObj[key_1] = canonicalize(obj[key_1], stack, replacementStack, replacer, key_1); + } + stack.pop(); + replacementStack.pop(); + } + else { + canonicalizedObj = obj; + } + return canonicalizedObj; +} diff --git a/node_modules/diff/libcjs/diff/line.js b/node_modules/diff/libcjs/diff/line.js new file mode 100644 index 0000000000000..8f4a1f412c171 --- /dev/null +++ b/node_modules/diff/libcjs/diff/line.js @@ -0,0 +1,89 @@ +"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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.lineDiff = void 0; +exports.diffLines = diffLines; +exports.diffTrimmedLines = diffTrimmedLines; +exports.tokenize = tokenize; +var base_js_1 = require("./base.js"); +var params_js_1 = require("../util/params.js"); +var LineDiff = /** @class */ (function (_super) { + __extends(LineDiff, _super); + function LineDiff() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.tokenize = tokenize; + return _this; + } + LineDiff.prototype.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 _super.prototype.equals.call(this, left, right, options); + }; + return LineDiff; +}(base_js_1.default)); +exports.lineDiff = new LineDiff(); +function diffLines(oldStr, newStr, options) { + return exports.lineDiff.diff(oldStr, newStr, options); +} +function diffTrimmedLines(oldStr, newStr, options) { + options = (0, params_js_1.generateOptions)(options, { ignoreWhitespace: true }); + return exports.lineDiff.diff(oldStr, newStr, options); +} +// Exported standalone so it can be used from jsonDiff too. +function tokenize(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; +} diff --git a/node_modules/diff/libcjs/diff/sentence.js b/node_modules/diff/libcjs/diff/sentence.js new file mode 100644 index 0000000000000..dac837fbdc90a --- /dev/null +++ b/node_modules/diff/libcjs/diff/sentence.js @@ -0,0 +1,67 @@ +"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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sentenceDiff = void 0; +exports.diffSentences = diffSentences; +var base_js_1 = require("./base.js"); +function isSentenceEndPunct(char) { + return char == '.' || char == '!' || char == '?'; +} +var SentenceDiff = /** @class */ (function (_super) { + __extends(SentenceDiff, _super); + function SentenceDiff() { + return _super !== null && _super.apply(this, arguments) || this; + } + SentenceDiff.prototype.tokenize = function (value) { + var _a; + // If in future we drop support for environments that don't support lookbehinds, we can replace + // this entire function with: + // return value.split(/(?<=[.!?])(\s+|$)/); + // but until then, for similar reasons to the trailingWs function in string.ts, we are forced + // to do this verbosely "by hand" instead of using a regex. + var result = []; + var tokenStartI = 0; + for (var i = 0; i < value.length; i++) { + if (i == value.length - 1) { + result.push(value.slice(tokenStartI)); + break; + } + if (isSentenceEndPunct(value[i]) && value[i + 1].match(/\s/)) { + // We've hit a sentence break - i.e. a punctuation mark followed by whitespace. + // We now want to push TWO tokens to the result: + // 1. the sentence + result.push(value.slice(tokenStartI, i + 1)); + // 2. the whitespace + i = tokenStartI = i + 1; + while ((_a = value[i + 1]) === null || _a === void 0 ? void 0 : _a.match(/\s/)) { + i++; + } + result.push(value.slice(tokenStartI, i + 1)); + // Then the next token (a sentence) starts on the character after the whitespace. + // (It's okay if this is off the end of the string - then the outer loop will terminate + // here anyway.) + tokenStartI = i + 1; + } + } + return result; + }; + return SentenceDiff; +}(base_js_1.default)); +exports.sentenceDiff = new SentenceDiff(); +function diffSentences(oldStr, newStr, options) { + return exports.sentenceDiff.diff(oldStr, newStr, options); +} diff --git a/node_modules/diff/libcjs/diff/word.js b/node_modules/diff/libcjs/diff/word.js new file mode 100644 index 0000000000000..1a24ac51df2aa --- /dev/null +++ b/node_modules/diff/libcjs/diff/word.js @@ -0,0 +1,312 @@ +"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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordsWithSpaceDiff = exports.wordDiff = void 0; +exports.diffWords = diffWords; +exports.diffWordsWithSpace = diffWordsWithSpace; +var base_js_1 = require("./base.js"); +var string_js_1 = require("../util/string.js"); +// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode +// +// Chars/ranges counted as "word" characters by this regex are as follows: +// +// + U+00AD Soft hyphen +// + 00C0–00FF (letters with diacritics from the Latin-1 Supplement), except: +// - 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, except: +// - 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{AD}\\u{C0}-\\u{D6}\\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 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 = /** @class */ (function (_super) { + __extends(WordDiff, _super); + function WordDiff() { + return _super !== null && _super.apply(this, arguments) || this; + } + WordDiff.prototype.equals = function (left, right, options) { + if (options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + return left.trim() === right.trim(); + }; + WordDiff.prototype.tokenize = function (value, options) { + if (options === void 0) { options = {}; } + var parts; + if (options.intlSegmenter) { + var segmenter = options.intlSegmenter; + if (segmenter.resolvedOptions().granularity != 'word') { + throw new Error('The segmenter passed must have a granularity of "word"'); + } + // We want `parts` to be an array whose elements alternate between being + // pure whitespace and being pure non-whitespace. This is ALMOST what the + // segments returned by a word-based Intl.Segmenter already look like, + // but not quite - see explanation in the docs of our custom segment() + // function. + parts = (0, string_js_1.segment)(value, segmenter); + } + 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 (prevPart != null && (/\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.prototype.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.prototype.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, options.intlSegmenter); + } + lastKeep = change; + insertion = null; + deletion = null; + } + }); + if (insertion || deletion) { + dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null, options.intlSegmenter); + } + return changes; + }; + return WordDiff; +}(base_js_1.default)); +exports.wordDiff = new WordDiff(); +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 exports.wordDiff.diff(oldStr, newStr, options); +} +function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep, segmenter) { + // 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 _a = (0, string_js_1.leadingAndTrailingWs)(deletion.value, segmenter), oldWsPrefix = _a[0], oldWsSuffix = _a[1]; + var _b = (0, string_js_1.leadingAndTrailingWs)(insertion.value, segmenter), newWsPrefix = _b[0], newWsSuffix = _b[1]; + if (startKeep) { + var commonWsPrefix = (0, string_js_1.longestCommonPrefix)(oldWsPrefix, newWsPrefix); + startKeep.value = (0, string_js_1.replaceSuffix)(startKeep.value, newWsPrefix, commonWsPrefix); + deletion.value = (0, string_js_1.removePrefix)(deletion.value, commonWsPrefix); + insertion.value = (0, string_js_1.removePrefix)(insertion.value, commonWsPrefix); + } + if (endKeep) { + var commonWsSuffix = (0, string_js_1.longestCommonSuffix)(oldWsSuffix, newWsSuffix); + endKeep.value = (0, string_js_1.replacePrefix)(endKeep.value, newWsSuffix, commonWsSuffix); + deletion.value = (0, string_js_1.removeSuffix)(deletion.value, commonWsSuffix); + insertion.value = (0, string_js_1.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) { + var ws = (0, string_js_1.leadingWs)(insertion.value, segmenter); + insertion.value = insertion.value.substring(ws.length); + } + if (endKeep) { + var ws = (0, string_js_1.leadingWs)(endKeep.value, segmenter); + endKeep.value = endKeep.value.substring(ws.length); + } + // otherwise we've got a deletion and no insertion + } + else if (startKeep && endKeep) { + var newWsFull = (0, string_js_1.leadingWs)(endKeep.value, segmenter), _c = (0, string_js_1.leadingAndTrailingWs)(deletion.value, segmenter), delWsStart = _c[0], delWsEnd = _c[1]; + // Any whitespace that comes straight after startKeep in both the old and + // new texts, assign to startKeep and remove from the deletion. + var newWsStart = (0, string_js_1.longestCommonPrefix)(newWsFull, delWsStart); + deletion.value = (0, string_js_1.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 = (0, string_js_1.longestCommonSuffix)((0, string_js_1.removePrefix)(newWsFull, newWsStart), delWsEnd); + deletion.value = (0, string_js_1.removeSuffix)(deletion.value, newWsEnd); + endKeep.value = (0, string_js_1.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 = (0, string_js_1.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 = (0, string_js_1.leadingWs)(endKeep.value, segmenter); + var deletionWsSuffix = (0, string_js_1.trailingWs)(deletion.value, segmenter); + var overlap = (0, string_js_1.maximumOverlap)(deletionWsSuffix, endKeepWsPrefix); + deletion.value = (0, string_js_1.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 = (0, string_js_1.trailingWs)(startKeep.value, segmenter); + var deletionWsPrefix = (0, string_js_1.leadingWs)(deletion.value, segmenter); + var overlap = (0, string_js_1.maximumOverlap)(startKeepWsSuffix, deletionWsPrefix); + deletion.value = (0, string_js_1.removePrefix)(deletion.value, overlap); + } +} +var WordsWithSpaceDiff = /** @class */ (function (_super) { + __extends(WordsWithSpaceDiff, _super); + function WordsWithSpaceDiff() { + return _super !== null && _super.apply(this, arguments) || this; + } + WordsWithSpaceDiff.prototype.tokenize = function (value) { + // Slightly different to the tokenizeIncludingWhitespace regex used above in + // that this one treats each individual newline as a distinct token, 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) || []; + }; + return WordsWithSpaceDiff; +}(base_js_1.default)); +exports.wordsWithSpaceDiff = new WordsWithSpaceDiff(); +function diffWordsWithSpace(oldStr, newStr, options) { + return exports.wordsWithSpaceDiff.diff(oldStr, newStr, options); +} diff --git a/node_modules/diff/libcjs/index.js b/node_modules/diff/libcjs/index.js new file mode 100644 index 0000000000000..3ad381e4f3460 --- /dev/null +++ b/node_modules/diff/libcjs/index.js @@ -0,0 +1,64 @@ +"use strict"; +/* See LICENSE file for terms of use */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.canonicalize = exports.convertChangesToXML = exports.convertChangesToDMP = exports.reversePatch = exports.parsePatch = exports.applyPatches = exports.applyPatch = exports.OMIT_HEADERS = exports.FILE_HEADERS_ONLY = exports.INCLUDE_HEADERS = exports.formatPatch = exports.createPatch = exports.createTwoFilesPatch = exports.structuredPatch = exports.arrayDiff = exports.diffArrays = exports.jsonDiff = exports.diffJson = exports.cssDiff = exports.diffCss = exports.sentenceDiff = exports.diffSentences = exports.diffTrimmedLines = exports.lineDiff = exports.diffLines = exports.wordsWithSpaceDiff = exports.diffWordsWithSpace = exports.wordDiff = exports.diffWords = exports.characterDiff = exports.diffChars = exports.Diff = void 0; +/* + * Text diff implementation. + * + * This library supports the following APIs: + * Diff.diffChars: Character by character diff + * Diff.diffWords: Word (as defined by \b regex) diff which ignores whitespace + * Diff.diffLines: Line based diff + * + * Diff.diffCss: Diff targeted at CSS content + * + * These methods are based on the implementation proposed in + * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 + */ +var base_js_1 = require("./diff/base.js"); +exports.Diff = base_js_1.default; +var character_js_1 = require("./diff/character.js"); +Object.defineProperty(exports, "diffChars", { enumerable: true, get: function () { return character_js_1.diffChars; } }); +Object.defineProperty(exports, "characterDiff", { enumerable: true, get: function () { return character_js_1.characterDiff; } }); +var word_js_1 = require("./diff/word.js"); +Object.defineProperty(exports, "diffWords", { enumerable: true, get: function () { return word_js_1.diffWords; } }); +Object.defineProperty(exports, "diffWordsWithSpace", { enumerable: true, get: function () { return word_js_1.diffWordsWithSpace; } }); +Object.defineProperty(exports, "wordDiff", { enumerable: true, get: function () { return word_js_1.wordDiff; } }); +Object.defineProperty(exports, "wordsWithSpaceDiff", { enumerable: true, get: function () { return word_js_1.wordsWithSpaceDiff; } }); +var line_js_1 = require("./diff/line.js"); +Object.defineProperty(exports, "diffLines", { enumerable: true, get: function () { return line_js_1.diffLines; } }); +Object.defineProperty(exports, "diffTrimmedLines", { enumerable: true, get: function () { return line_js_1.diffTrimmedLines; } }); +Object.defineProperty(exports, "lineDiff", { enumerable: true, get: function () { return line_js_1.lineDiff; } }); +var sentence_js_1 = require("./diff/sentence.js"); +Object.defineProperty(exports, "diffSentences", { enumerable: true, get: function () { return sentence_js_1.diffSentences; } }); +Object.defineProperty(exports, "sentenceDiff", { enumerable: true, get: function () { return sentence_js_1.sentenceDiff; } }); +var css_js_1 = require("./diff/css.js"); +Object.defineProperty(exports, "diffCss", { enumerable: true, get: function () { return css_js_1.diffCss; } }); +Object.defineProperty(exports, "cssDiff", { enumerable: true, get: function () { return css_js_1.cssDiff; } }); +var json_js_1 = require("./diff/json.js"); +Object.defineProperty(exports, "diffJson", { enumerable: true, get: function () { return json_js_1.diffJson; } }); +Object.defineProperty(exports, "canonicalize", { enumerable: true, get: function () { return json_js_1.canonicalize; } }); +Object.defineProperty(exports, "jsonDiff", { enumerable: true, get: function () { return json_js_1.jsonDiff; } }); +var array_js_1 = require("./diff/array.js"); +Object.defineProperty(exports, "diffArrays", { enumerable: true, get: function () { return array_js_1.diffArrays; } }); +Object.defineProperty(exports, "arrayDiff", { enumerable: true, get: function () { return array_js_1.arrayDiff; } }); +var apply_js_1 = require("./patch/apply.js"); +Object.defineProperty(exports, "applyPatch", { enumerable: true, get: function () { return apply_js_1.applyPatch; } }); +Object.defineProperty(exports, "applyPatches", { enumerable: true, get: function () { return apply_js_1.applyPatches; } }); +var parse_js_1 = require("./patch/parse.js"); +Object.defineProperty(exports, "parsePatch", { enumerable: true, get: function () { return parse_js_1.parsePatch; } }); +var reverse_js_1 = require("./patch/reverse.js"); +Object.defineProperty(exports, "reversePatch", { enumerable: true, get: function () { return reverse_js_1.reversePatch; } }); +var create_js_1 = require("./patch/create.js"); +Object.defineProperty(exports, "structuredPatch", { enumerable: true, get: function () { return create_js_1.structuredPatch; } }); +Object.defineProperty(exports, "createTwoFilesPatch", { enumerable: true, get: function () { return create_js_1.createTwoFilesPatch; } }); +Object.defineProperty(exports, "createPatch", { enumerable: true, get: function () { return create_js_1.createPatch; } }); +Object.defineProperty(exports, "formatPatch", { enumerable: true, get: function () { return create_js_1.formatPatch; } }); +Object.defineProperty(exports, "INCLUDE_HEADERS", { enumerable: true, get: function () { return create_js_1.INCLUDE_HEADERS; } }); +Object.defineProperty(exports, "FILE_HEADERS_ONLY", { enumerable: true, get: function () { return create_js_1.FILE_HEADERS_ONLY; } }); +Object.defineProperty(exports, "OMIT_HEADERS", { enumerable: true, get: function () { return create_js_1.OMIT_HEADERS; } }); +var dmp_js_1 = require("./convert/dmp.js"); +Object.defineProperty(exports, "convertChangesToDMP", { enumerable: true, get: function () { return dmp_js_1.convertChangesToDMP; } }); +var xml_js_1 = require("./convert/xml.js"); +Object.defineProperty(exports, "convertChangesToXML", { enumerable: true, get: function () { return xml_js_1.convertChangesToXML; } }); diff --git a/node_modules/diff/libcjs/package.json b/node_modules/diff/libcjs/package.json new file mode 100644 index 0000000000000..731cf3f1d319d --- /dev/null +++ b/node_modules/diff/libcjs/package.json @@ -0,0 +1 @@ +{"type":"commonjs","sideEffects":false} \ No newline at end of file diff --git a/node_modules/diff/libcjs/patch/apply.js b/node_modules/diff/libcjs/patch/apply.js new file mode 100644 index 0000000000000..4f49c7c6d08b4 --- /dev/null +++ b/node_modules/diff/libcjs/patch/apply.js @@ -0,0 +1,267 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.applyPatch = applyPatch; +exports.applyPatches = applyPatches; +var string_js_1 = require("../util/string.js"); +var line_endings_js_1 = require("./line-endings.js"); +var parse_js_1 = require("./parse.js"); +var distance_iterator_js_1 = require("../util/distance-iterator.js"); +/** + * attempts to apply a unified diff patch. + * + * Hunks are applied first to last. + * `applyPatch` first tries to apply the first hunk at the line number specified in the hunk header, and with all context lines matching exactly. + * If that fails, it tries scanning backwards and forwards, one line at a time, to find a place to apply the hunk where the context lines match exactly. + * If that still fails, and `fuzzFactor` is greater than zero, it increments the maximum number of mismatches (missing, extra, or changed context lines) that there can be between the hunk context and a region where we are trying to apply the patch such that the hunk will still be considered to match. + * Regardless of `fuzzFactor`, lines to be deleted in the hunk *must* be present for a hunk to match, and the context lines *immediately* before and after an insertion must match exactly. + * + * Once a hunk is successfully fitted, the process begins again with the next hunk. + * Regardless of `fuzzFactor`, later hunks must be applied later in the file than earlier hunks. + * + * If a hunk cannot be successfully fitted *anywhere* with fewer than `fuzzFactor` mismatches, `applyPatch` fails and returns `false`. + * + * If a hunk is successfully fitted but not at the line number specified by the hunk header, all subsequent hunks have their target line number adjusted accordingly. + * (e.g. if the first hunk is applied 10 lines below where the hunk header said it should fit, `applyPatch` will *start* looking for somewhere to apply the second hunk 10 lines below where its hunk header says it goes.) + * + * If the patch was applied successfully, returns a string containing the patched text. + * If the patch could not be applied (because some hunks in the patch couldn't be fitted to the text in `source`), `applyPatch` returns false. + * + * @param patch a string diff or the output from the `parsePatch` or `structuredPatch` methods. + */ +function applyPatch(source, patch, options) { + if (options === void 0) { options = {}; } + var patches; + if (typeof patch === 'string') { + patches = (0, parse_js_1.parsePatch)(patch); + } + else if (Array.isArray(patch)) { + patches = patch; + } + else { + patches = [patch]; + } + if (patches.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + return applyStructuredPatch(source, patches[0], options); +} +function applyStructuredPatch(source, patch, options) { + if (options === void 0) { options = {}; } + if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) { + if ((0, string_js_1.hasOnlyWinLineEndings)(source) && (0, line_endings_js_1.isUnix)(patch)) { + patch = (0, line_endings_js_1.unixToWin)(patch); + } + else if ((0, string_js_1.hasOnlyUnixLineEndings)(source) && (0, line_endings_js_1.isWin)(patch)) { + patch = (0, line_endings_js_1.winToUnix)(patch); + } + } + // Apply the diff to the input + var lines = source.split('\n'), hunks = patch.hunks, compareLine = options.compareLine || (function (lineNumber, line, operation, patchContent) { return line === patchContent; }), fuzzFactor = options.fuzzFactor || 0; + var 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, hunkLinesI, lastContextLineMatched, patchedLines, patchedLinesLength) { + if (hunkLinesI === void 0) { hunkLinesI = 0; } + if (lastContextLineMatched === void 0) { lastContextLineMatched = true; } + if (patchedLines === void 0) { patchedLines = []; } + if (patchedLinesLength === void 0) { patchedLinesLength = 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 = (0, distance_iterator_js_1.default)(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 i_1 = minLine; i_1 < toPos; i_1++) { + resultLines.push(lines[i_1]); + } + // Add the lines produced by applying the hunk: + for (var i_2 = 0; i_2 < hunkResult.patchedLines.length; i_2++) { + var line = hunkResult.patchedLines[i_2]; + 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 i = minLine; i < lines.length; i++) { + resultLines.push(lines[i]); + } + return resultLines.join('\n'); +} +/** + * applies one or more patches. + * + * `patch` may be either an array of structured patch objects, or a string representing a patch in unified diff format (which may patch one or more files). + * + * This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is: + * + * - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. + * - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution. + * + * Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. + */ +function applyPatches(uniDiff, options) { + var spDiff = typeof uniDiff === 'string' ? (0, parse_js_1.parsePatch)(uniDiff) : uniDiff; + var currentIndex = 0; + function processIndex() { + var index = spDiff[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(); +} diff --git a/node_modules/diff/libcjs/patch/create.js b/node_modules/diff/libcjs/patch/create.js new file mode 100644 index 0000000000000..d9328c2e7709f --- /dev/null +++ b/node_modules/diff/libcjs/patch/create.js @@ -0,0 +1,251 @@ +"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 }); +exports.OMIT_HEADERS = exports.FILE_HEADERS_ONLY = exports.INCLUDE_HEADERS = void 0; +exports.structuredPatch = structuredPatch; +exports.formatPatch = formatPatch; +exports.createTwoFilesPatch = createTwoFilesPatch; +exports.createPatch = createPatch; +var line_js_1 = require("../diff/line.js"); +exports.INCLUDE_HEADERS = { + includeIndex: true, + includeUnderline: true, + includeFileHeaders: true +}; +exports.FILE_HEADERS_ONLY = { + includeIndex: false, + includeUnderline: false, + includeFileHeaders: true +}; +exports.OMIT_HEADERS = { + includeIndex: false, + includeUnderline: false, + includeFileHeaders: false +}; +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var optionsObj; + if (!options) { + optionsObj = {}; + } + else if (typeof options === 'function') { + optionsObj = { callback: options }; + } + else { + optionsObj = options; + } + if (typeof optionsObj.context === 'undefined') { + optionsObj.context = 4; + } + // We copy this into its own variable to placate TypeScript, which thinks + // optionsObj.context might be undefined in the callbacks below. + var context = optionsObj.context; + // @ts-expect-error (runtime check for something that is correctly a static type error) + if (optionsObj.newlineIsToken) { + throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions'); + } + if (!optionsObj.callback) { + return diffLinesResultToPatch((0, line_js_1.diffLines)(oldStr, newStr, optionsObj)); + } + else { + var callback_1 = optionsObj.callback; + (0, line_js_1.diffLines)(oldStr, newStr, __assign(__assign({}, optionsObj), { callback: function (diff) { + var patch = diffLinesResultToPatch(diff); + // TypeScript is unhappy without the cast because it does not understand that `patch` may + // be undefined here only if `callback` is StructuredPatchCallbackAbortable: + callback_1(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; + for (var i = 0; i < diff.length; i++) { + var current = diff[i], lines = current.lines || splitLines(current.value); + current.lines = lines; + if (current.added || current.removed) { + // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + if (prev) { + curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + // Output our changes + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + curRange.push((current.added ? '+' : '-') + line); + } + // 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 <= context * 2 && i < diff.length - 2) { + // Overlapping + for (var _a = 0, _b = contextLines(lines); _a < _b.length; _a++) { + var line = _b[_a]; + curRange.push(line); + } + } + else { + // end the range and output + var contextSize = Math.min(lines.length, context); + for (var _c = 0, _d = contextLines(lines.slice(0, contextSize)); _c < _d.length; _c++) { + var line = _d[_c]; + curRange.push(line); + } + 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; + } + } + // Step 2: eliminate the trailing `\n` from each line of each hunk, and, where needed, add + // "\ No newline at end of file". + for (var _e = 0, hunks_1 = hunks; _e < hunks_1.length; _e++) { + var hunk = hunks_1[_e]; + for (var i = 0; i < hunk.lines.length; i++) { + if (hunk.lines[i].endsWith('\n')) { + hunk.lines[i] = hunk.lines[i].slice(0, -1); + } + else { + hunk.lines.splice(i + 1, 0, '\\ No newline at end of file'); + i++; // Skip the line we just added, then continue iterating + } + } + } + return { + oldFileName: oldFileName, newFileName: newFileName, + oldHeader: oldHeader, newHeader: newHeader, + hunks: hunks + }; + } +} +/** + * creates a unified diff patch. + * @param patch either a single structured patch object (as returned by `structuredPatch`) or an array of them (as returned by `parsePatch`) + */ +function formatPatch(patch, headerOptions) { + if (!headerOptions) { + headerOptions = exports.INCLUDE_HEADERS; + } + if (Array.isArray(patch)) { + if (patch.length > 1 && !headerOptions.includeFileHeaders) { + throw new Error('Cannot omit file headers on a multi-file patch. ' + + '(The result would be unparseable; how would a tool trying to apply ' + + 'the patch know which changes are to which file?)'); + } + return patch.map(function (p) { return formatPatch(p, headerOptions); }).join('\n'); + } + var ret = []; + if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) { + ret.push('Index: ' + patch.oldFileName); + } + if (headerOptions.includeUnderline) { + ret.push('==================================================================='); + } + if (headerOptions.includeFileHeaders) { + ret.push('--- ' + patch.oldFileName + (typeof patch.oldHeader === 'undefined' ? '' : '\t' + patch.oldHeader)); + ret.push('+++ ' + patch.newFileName + (typeof patch.newHeader === 'undefined' ? '' : '\t' + patch.newHeader)); + } + for (var i = 0; i < patch.hunks.length; i++) { + var hunk = patch.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 + + ' @@'); + for (var _i = 0, _a = hunk.lines; _i < _a.length; _i++) { + var line = _a[_i]; + ret.push(line); + } + } + return ret.join('\n') + '\n'; +} +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (typeof options === 'function') { + options = { callback: options }; + } + if (!(options === null || options === void 0 ? void 0 : options.callback)) { + var patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + if (!patchObj) { + return; + } + return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions); + } + else { + var callback_2 = options.callback; + structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, __assign(__assign({}, options), { callback: function (patchObj) { + if (!patchObj) { + callback_2(undefined); + } + else { + callback_2(formatPatch(patchObj, options.headerOptions)); + } + } })); + } +} +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; +} diff --git a/node_modules/diff/libcjs/patch/line-endings.js b/node_modules/diff/libcjs/patch/line-endings.js new file mode 100644 index 0000000000000..be45f0c8a326f --- /dev/null +++ b/node_modules/diff/libcjs/patch/line-endings.js @@ -0,0 +1,61 @@ +"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 }); +exports.unixToWin = unixToWin; +exports.winToUnix = winToUnix; +exports.isUnix = isUnix; +exports.isWin = isWin; +function unixToWin(patch) { + if (Array.isArray(patch)) { + // It would be cleaner if instead of the line below we could just write + // return patch.map(unixToWin) + // but mysteriously TypeScript (v5.7.3 at the time of writing) does not like this and it will + // refuse to compile, thinking that unixToWin could then return StructuredPatch[][] and the + // result would be incompatible with the overload signatures. + // See bug report at https://github.com/microsoft/TypeScript/issues/61398. + return patch.map(function (p) { return unixToWin(p); }); + } + return __assign(__assign({}, patch), { hunks: patch.hunks.map(function (hunk) { return (__assign(__assign({}, hunk), { lines: hunk.lines.map(function (line, i) { + var _a; + return (line.startsWith('\\') || line.endsWith('\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\'))) + ? line + : line + '\r'; + }) })); }) }); +} +function winToUnix(patch) { + if (Array.isArray(patch)) { + // (See comment above equivalent line in unixToWin) + return patch.map(function (p) { return winToUnix(p); }); + } + return __assign(__assign({}, patch), { hunks: patch.hunks.map(function (hunk) { return (__assign(__assign({}, 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 _a; return line.startsWith('\\') || line.endsWith('\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\')); }); }); }); +} diff --git a/node_modules/diff/libcjs/patch/parse.js b/node_modules/diff/libcjs/patch/parse.js new file mode 100644 index 0000000000000..f2769cff9a537 --- /dev/null +++ b/node_modules/diff/libcjs/patch/parse.js @@ -0,0 +1,150 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parsePatch = parsePatch; +/** + * Parses a patch into structured data, in the same structure returned by `structuredPatch`. + * + * @return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. + */ +function parsePatch(uniDiff) { + var diffstr = uniDiff.split(/\n/), list = []; + var 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; + } + // Try to parse the line as a diff header, like + // Index: README.md + // or + // diff -r 9117c6561b0b -r 273ce12ad8f1 .hgignore + // or + // Index: something with multiple words + // and extract the filename (or whatever else is used as an index name) + // from the end (i.e. 'README.md', '.hgignore', or + // 'something with multiple words' in the examples above). + // + // TODO: It seems awkward that we indiscriminately trim off trailing + // whitespace here. Theoretically, couldn't that be meaningful - + // e.g. if the patch represents a diff of a file whose name ends + // with a space? Seems wrong to nuke it. + // But this behaviour has been around since v2.2.1 in 2015, so if + // it's going to change, it should be done cautiously and in a new + // major release, for backwards-compat reasons. + // -- ExplodingCabbage + var headerMatch = (/^(?:Index:|diff(?: -r \w+)+)\s+/).exec(line); + if (headerMatch) { + index.index = line.substring(headerMatch[0].length).trim(); + } + 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 fileHeaderMatch = (/^(---|\+\+\+)\s+/).exec(diffstr[i]); + if (fileHeaderMatch) { + var prefix = fileHeaderMatch[1], data = diffstr[i].substring(3).trim().split('\t', 2), header = (data[1] || '').trim(); + var fileName = data[0].replace(/\\\\/g, '\\'); + if (fileName.startsWith('"') && fileName.endsWith('"')) { + fileName = fileName.substr(1, fileName.length - 2); + } + if (prefix === '---') { + index.oldFileName = fileName; + index.oldHeader = header; + } + else { + index.newFileName = fileName; + index.newHeader = header; + } + i++; + } + } + // Parses a hunk + // This assumes that we are at the start of a hunk. + function parseHunk() { + var _a; + 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 || ((_a = diffstr[i]) === null || _a === void 0 ? void 0 : _a.startsWith('\\'))); 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; +} diff --git a/node_modules/diff/libcjs/patch/reverse.js b/node_modules/diff/libcjs/patch/reverse.js new file mode 100644 index 0000000000000..078fcdaea0bbc --- /dev/null +++ b/node_modules/diff/libcjs/patch/reverse.js @@ -0,0 +1,37 @@ +"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 }); +exports.reversePatch = reversePatch; +function reversePatch(structuredPatch) { + if (Array.isArray(structuredPatch)) { + // (See comment in unixToWin for why we need the pointless-looking anonymous function here) + return structuredPatch.map(function (patch) { return reversePatch(patch); }).reverse(); + } + return __assign(__assign({}, 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; + }) + }; + }) }); +} diff --git a/node_modules/@tufjs/models/dist/utils/types.js b/node_modules/diff/libcjs/types.js similarity index 100% rename from node_modules/@tufjs/models/dist/utils/types.js rename to node_modules/diff/libcjs/types.js diff --git a/node_modules/diff/libcjs/util/array.js b/node_modules/diff/libcjs/util/array.js new file mode 100644 index 0000000000000..c21937ee0fe51 --- /dev/null +++ b/node_modules/diff/libcjs/util/array.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.arrayEqual = arrayEqual; +exports.arrayStartsWith = arrayStartsWith; +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; +} diff --git a/node_modules/diff/libcjs/util/distance-iterator.js b/node_modules/diff/libcjs/util/distance-iterator.js new file mode 100644 index 0000000000000..2421553c444ea --- /dev/null +++ b/node_modules/diff/libcjs/util/distance-iterator.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = default_1; +// 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 default_1(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 + return undefined; + }; +} diff --git a/node_modules/diff/libcjs/util/params.js b/node_modules/diff/libcjs/util/params.js new file mode 100644 index 0000000000000..6eefddba7922c --- /dev/null +++ b/node_modules/diff/libcjs/util/params.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.generateOptions = generateOptions; +function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } + else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (Object.prototype.hasOwnProperty.call(options, name)) { + defaults[name] = options[name]; + } + } + } + return defaults; +} diff --git a/node_modules/diff/libcjs/util/string.js b/node_modules/diff/libcjs/util/string.js new file mode 100644 index 0000000000000..0e5a048e646ae --- /dev/null +++ b/node_modules/diff/libcjs/util/string.js @@ -0,0 +1,200 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.longestCommonPrefix = longestCommonPrefix; +exports.longestCommonSuffix = longestCommonSuffix; +exports.replacePrefix = replacePrefix; +exports.replaceSuffix = replaceSuffix; +exports.removePrefix = removePrefix; +exports.removeSuffix = removeSuffix; +exports.maximumOverlap = maximumOverlap; +exports.hasOnlyWinLineEndings = hasOnlyWinLineEndings; +exports.hasOnlyUnixLineEndings = hasOnlyUnixLineEndings; +exports.segment = segment; +exports.trailingWs = trailingWs; +exports.leadingWs = leadingWs; +exports.leadingAndTrailingWs = leadingAndTrailingWs; +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'); +} +/** + * Split a string into segments using a word segmenter, merging consecutive + * segments if they are both whitespace segments. Whitespace segments can + * appear adjacent to one another for two reasons: + * - newlines always get their own segment + * - where a diacritic is attached to a whitespace character in the text, the + * segment ends after the diacritic, so e.g. " \u0300 " becomes two segments. + * This function therefore runs the segmenter's .segment() method and then + * merges consecutive segments of whitespace into a single part. + */ +function segment(string, segmenter) { + var parts = []; + for (var _i = 0, _a = Array.from(segmenter.segment(string)); _i < _a.length; _i++) { + var segmentObj = _a[_i]; + var segment_1 = segmentObj.segment; + if (parts.length && (/\s/).test(parts[parts.length - 1]) && (/\s/).test(segment_1)) { + parts[parts.length - 1] += segment_1; + } + else { + parts.push(segment_1); + } + } + return parts; +} +// The functions below take a `segmenter` argument so that, when called from +// diffWords when it is using a segmenter, they can use a notion of what +// constitutes "whitespace" that is consistent with the segmenter. +// +// USUALLY this will be identical to the result of the non-segmenter-based +// logic, but it differs in at least one case: when whitespace characters are +// modified by diacritics. A word segmenter considers these diacritics to be +// part of the whitespace, whereas our non-segmenter-based logic does not. +// +// Because the segmenter-based approach necessarily requires segmenting the +// entire string, we offer a leadingAndTrailingWs function to allow getting the +// whitespace prefix AND whitespace suffix with a single call to the segmenter, +// for efficiency's sake. +function trailingWs(string, segmenter) { + if (segmenter) { + return leadingAndTrailingWs(string, segmenter)[1]; + } + // Yes, this looks overcomplicated and dumb - why not replace the whole function with + // return string.match(/\s*$/)[0] + // you ask? Because: + // 1. the trap described at https://markamery.com/blog/quadratic-time-regexes/ would mean doing + // this would cause this function to take O(n²) time in the worst case (specifically when + // there is a massive run of NON-TRAILING whitespace in `string`), and + // 2. the fix proposed in the same blog post, of using a negative lookbehind, is incompatible + // with old Safari versions that we'd like to not break if possible (see + // https://github.com/kpdecker/jsdiff/pull/550) + // It feels absurd to do this with an explicit loop instead of a regex, but I really can't see a + // better way that doesn't result in broken behaviour. + var i; + for (i = string.length - 1; i >= 0; i--) { + if (!string[i].match(/\s/)) { + break; + } + } + return string.substring(i + 1); +} +function leadingWs(string, segmenter) { + if (segmenter) { + return leadingAndTrailingWs(string, segmenter)[0]; + } + // Thankfully the annoying considerations described in trailingWs don't apply here: + var match = string.match(/^\s*/); + return match ? match[0] : ''; +} +function leadingAndTrailingWs(string, segmenter) { + if (!segmenter) { + return [leadingWs(string), trailingWs(string)]; + } + if (segmenter.resolvedOptions().granularity != 'word') { + throw new Error('The segmenter passed must have a granularity of "word"'); + } + var segments = segment(string, segmenter); + var firstSeg = segments[0]; + var lastSeg = segments[segments.length - 1]; + var head = (/\s/).test(firstSeg) ? firstSeg : ''; + var tail = (/\s/).test(lastSeg) ? lastSeg : ''; + return [head, tail]; +} diff --git a/node_modules/diff/libesm/convert/dmp.js b/node_modules/diff/libesm/convert/dmp.js new file mode 100644 index 0000000000000..44d2841465887 --- /dev/null +++ b/node_modules/diff/libesm/convert/dmp.js @@ -0,0 +1,21 @@ +/** + * converts a list of change objects to the format returned by Google's [diff-match-patch](https://github.com/google/diff-match-patch) library + */ +export function convertChangesToDMP(changes) { + const ret = []; + let change, operation; + for (let 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; +} diff --git a/node_modules/diff/libesm/convert/xml.js b/node_modules/diff/libesm/convert/xml.js new file mode 100644 index 0000000000000..90ea8a2b8c667 --- /dev/null +++ b/node_modules/diff/libesm/convert/xml.js @@ -0,0 +1,31 @@ +/** + * converts a list of change objects to a serialized XML format + */ +export function convertChangesToXML(changes) { + const ret = []; + for (let i = 0; i < changes.length; i++) { + const 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) { + let n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; +} diff --git a/node_modules/diff/libesm/diff/array.js b/node_modules/diff/libesm/diff/array.js new file mode 100644 index 0000000000000..d92aeb485682d --- /dev/null +++ b/node_modules/diff/libesm/diff/array.js @@ -0,0 +1,16 @@ +import Diff from './base.js'; +class ArrayDiff extends Diff { + tokenize(value) { + return value.slice(); + } + join(value) { + return value; + } + removeEmpty(value) { + return value; + } +} +export const arrayDiff = new ArrayDiff(); +export function diffArrays(oldArr, newArr, options) { + return arrayDiff.diff(oldArr, newArr, options); +} diff --git a/node_modules/diff/libesm/diff/base.js b/node_modules/diff/libesm/diff/base.js new file mode 100644 index 0000000000000..db02845d419b9 --- /dev/null +++ b/node_modules/diff/libesm/diff/base.js @@ -0,0 +1,253 @@ +export default class Diff { + diff(oldStr, newStr, + // Type below is not accurate/complete - see above for full possibilities - but it compiles + options = {}) { + let callback; + if (typeof options === 'function') { + callback = options; + options = {}; + } + else if ('callback' in options) { + callback = options.callback; + } + // Allow subclasses to massage the input prior to running + const oldString = this.castInput(oldStr, options); + const newString = this.castInput(newStr, options); + const oldTokens = this.removeEmpty(this.tokenize(oldString, options)); + const newTokens = this.removeEmpty(this.tokenize(newString, options)); + return this.diffWithOptionsObj(oldTokens, newTokens, options, callback); + } + diffWithOptionsObj(oldTokens, newTokens, options, callback) { + var _a; + const done = (value) => { + value = this.postProcess(value, options); + if (callback) { + setTimeout(function () { callback(value); }, 0); + return undefined; + } + else { + return value; + } + }; + const newLen = newTokens.length, oldLen = oldTokens.length; + let editLength = 1; + let maxEditLength = newLen + oldLen; + if (options.maxEditLength != null) { + maxEditLength = Math.min(maxEditLength, options.maxEditLength); + } + const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity; + const abortAfterTimestamp = Date.now() + maxExecutionTime; + const bestPath = [{ oldPos: -1, lastComponent: undefined }]; + // Seed editLength = 0, i.e. the content starts with the same values + let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options); + if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + // Identity per the equality and tokenizer + return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens)); + } + // 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. + let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; + // Main worker method. checks all permutations of a given edit length for acceptance. + const execEditLength = () => { + for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { + let basePath; + const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; + if (removePath) { + // No one else is going to attempt to use this value, clear it + // @ts-expect-error - perf optimisation. This type-violating value will never be read. + bestPath[diagonalPath - 1] = undefined; + } + let canAdd = false; + if (addPath) { + // what newPos will be after we do an insertion: + const addPathNewPos = addPath.oldPos - diagonalPath; + canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; + } + const canRemove = removePath && removePath.oldPos + 1 < oldLen; + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + // @ts-expect-error - perf optimisation. This type-violating value will never be read. + 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 = this.addToPath(addPath, true, false, 0, options); + } + else { + basePath = this.addToPath(removePath, false, true, 1, options); + } + newPos = this.extractCommon(basePath, newTokens, oldTokens, 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(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true; + } + 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(undefined); + } + if (!execEditLength()) { + exec(); + } + }, 0); + }()); + } + else { + while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { + const ret = execEditLength(); + if (ret) { + return ret; + } + } + } + } + addToPath(path, added, removed, oldPosInc, options) { + const 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(basePath, newTokens, oldTokens, diagonalPath, options) { + const newLen = newTokens.length, oldLen = oldTokens.length; + let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[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(left, right, options) { + if (options.comparator) { + return options.comparator(left, right); + } + else { + return left === right + || (!!options.ignoreCase && left.toLowerCase() === right.toLowerCase()); + } + } + removeEmpty(array) { + const ret = []; + for (let i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + castInput(value, options) { + return value; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + tokenize(value, options) { + return Array.from(value); + } + join(chars) { + // Assumes ValueT is string, which is the case for most subclasses. + // When it's false, e.g. in diffArrays, this method needs to be overridden (e.g. with a no-op) + // Yes, the casts are verbose and ugly, because this pattern - of having the base class SORT OF + // assume tokens and values are strings, but not completely - is weird and janky. + return chars.join(''); + } + postProcess(changeObjects, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + options) { + return changeObjects; + } + get useLongestToken() { + return false; + } + buildValues(lastComponent, newTokens, oldTokens) { + // First we convert our linked list of components in reverse order to an + // array in the right order: + const components = []; + let nextComponent; + while (lastComponent) { + components.push(lastComponent); + nextComponent = lastComponent.previousComponent; + delete lastComponent.previousComponent; + lastComponent = nextComponent; + } + components.reverse(); + const componentLen = components.length; + let componentPos = 0, newPos = 0, oldPos = 0; + for (; componentPos < componentLen; componentPos++) { + const component = components[componentPos]; + if (!component.removed) { + if (!component.added && this.useLongestToken) { + let value = newTokens.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + const oldValue = oldTokens[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = this.join(value); + } + else { + component.value = this.join(newTokens.slice(newPos, newPos + component.count)); + } + newPos += component.count; + // Common case + if (!component.added) { + oldPos += component.count; + } + } + else { + component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count)); + oldPos += component.count; + } + } + return components; + } +} diff --git a/node_modules/diff/libesm/diff/character.js b/node_modules/diff/libesm/diff/character.js new file mode 100644 index 0000000000000..ca70d065d37cb --- /dev/null +++ b/node_modules/diff/libesm/diff/character.js @@ -0,0 +1,7 @@ +import Diff from './base.js'; +class CharacterDiff extends Diff { +} +export const characterDiff = new CharacterDiff(); +export function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); +} diff --git a/node_modules/diff/libesm/diff/css.js b/node_modules/diff/libesm/diff/css.js new file mode 100644 index 0000000000000..2e7adcc3c2c3d --- /dev/null +++ b/node_modules/diff/libesm/diff/css.js @@ -0,0 +1,10 @@ +import Diff from './base.js'; +class CssDiff extends Diff { + tokenize(value) { + return value.split(/([{}:;,]|\s+)/); + } +} +export const cssDiff = new CssDiff(); +export function diffCss(oldStr, newStr, options) { + return cssDiff.diff(oldStr, newStr, options); +} diff --git a/node_modules/diff/libesm/diff/json.js b/node_modules/diff/libesm/diff/json.js new file mode 100644 index 0000000000000..be9f7617df997 --- /dev/null +++ b/node_modules/diff/libesm/diff/json.js @@ -0,0 +1,78 @@ +import Diff from './base.js'; +import { tokenize } from './line.js'; +class JsonDiff extends Diff { + constructor() { + super(...arguments); + this.tokenize = tokenize; + } + get useLongestToken() { + // 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: + return true; + } + castInput(value, options) { + const { undefinedReplacement, stringifyReplacer = (k, v) => typeof v === 'undefined' ? undefinedReplacement : v } = options; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), null, ' '); + } + equals(left, right, options) { + return super.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'), options); + } +} +export const jsonDiff = new JsonDiff(); +export function diffJson(oldStr, newStr, options) { + return jsonDiff.diff(oldStr, newStr, 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 +export function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + if (replacer) { + obj = replacer(key === undefined ? '' : key, obj); + } + let i; + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + let 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, String(i)); + } + 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); + const sortedKeys = []; + let 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; +} diff --git a/node_modules/diff/libesm/diff/line.js b/node_modules/diff/libesm/diff/line.js new file mode 100644 index 0000000000000..0675d4fb003f9 --- /dev/null +++ b/node_modules/diff/libesm/diff/line.js @@ -0,0 +1,65 @@ +import Diff from './base.js'; +import { generateOptions } from '../util/params.js'; +class LineDiff extends Diff { + constructor() { + super(...arguments); + this.tokenize = tokenize; + } + equals(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 super.equals(left, right, options); + } +} +export const lineDiff = new LineDiff(); +export function diffLines(oldStr, newStr, options) { + return lineDiff.diff(oldStr, newStr, options); +} +export function diffTrimmedLines(oldStr, newStr, options) { + options = generateOptions(options, { ignoreWhitespace: true }); + return lineDiff.diff(oldStr, newStr, options); +} +// Exported standalone so it can be used from jsonDiff too. +export function tokenize(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'); + } + const 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 (let i = 0; i < linesAndNewlines.length; i++) { + const line = linesAndNewlines[i]; + if (i % 2 && !options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } + else { + retLines.push(line); + } + } + return retLines; +} diff --git a/node_modules/diff/libesm/diff/sentence.js b/node_modules/diff/libesm/diff/sentence.js new file mode 100644 index 0000000000000..db37010ef6472 --- /dev/null +++ b/node_modules/diff/libesm/diff/sentence.js @@ -0,0 +1,43 @@ +import Diff from './base.js'; +function isSentenceEndPunct(char) { + return char == '.' || char == '!' || char == '?'; +} +class SentenceDiff extends Diff { + tokenize(value) { + var _a; + // If in future we drop support for environments that don't support lookbehinds, we can replace + // this entire function with: + // return value.split(/(?<=[.!?])(\s+|$)/); + // but until then, for similar reasons to the trailingWs function in string.ts, we are forced + // to do this verbosely "by hand" instead of using a regex. + const result = []; + let tokenStartI = 0; + for (let i = 0; i < value.length; i++) { + if (i == value.length - 1) { + result.push(value.slice(tokenStartI)); + break; + } + if (isSentenceEndPunct(value[i]) && value[i + 1].match(/\s/)) { + // We've hit a sentence break - i.e. a punctuation mark followed by whitespace. + // We now want to push TWO tokens to the result: + // 1. the sentence + result.push(value.slice(tokenStartI, i + 1)); + // 2. the whitespace + i = tokenStartI = i + 1; + while ((_a = value[i + 1]) === null || _a === void 0 ? void 0 : _a.match(/\s/)) { + i++; + } + result.push(value.slice(tokenStartI, i + 1)); + // Then the next token (a sentence) starts on the character after the whitespace. + // (It's okay if this is off the end of the string - then the outer loop will terminate + // here anyway.) + tokenStartI = i + 1; + } + } + return result; + } +} +export const sentenceDiff = new SentenceDiff(); +export function diffSentences(oldStr, newStr, options) { + return sentenceDiff.diff(oldStr, newStr, options); +} diff --git a/node_modules/diff/libesm/diff/word.js b/node_modules/diff/libesm/diff/word.js new file mode 100644 index 0000000000000..284231ef9d45a --- /dev/null +++ b/node_modules/diff/libesm/diff/word.js @@ -0,0 +1,281 @@ +import Diff from './base.js'; +import { longestCommonPrefix, longestCommonSuffix, replacePrefix, replaceSuffix, removePrefix, removeSuffix, maximumOverlap, leadingWs, trailingWs, leadingAndTrailingWs, segment } from '../util/string.js'; +// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode +// +// Chars/ranges counted as "word" characters by this regex are as follows: +// +// + U+00AD Soft hyphen +// + 00C0–00FF (letters with diacritics from the Latin-1 Supplement), except: +// - 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, except: +// - 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 +const extendedWordChars = 'a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\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 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. +const tokenizeIncludingWhitespace = new RegExp(`[${extendedWordChars}]+|\\s+|[^${extendedWordChars}]`, 'ug'); +class WordDiff extends Diff { + equals(left, right, options) { + if (options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + return left.trim() === right.trim(); + } + tokenize(value, options = {}) { + let parts; + if (options.intlSegmenter) { + const segmenter = options.intlSegmenter; + if (segmenter.resolvedOptions().granularity != 'word') { + throw new Error('The segmenter passed must have a granularity of "word"'); + } + // We want `parts` to be an array whose elements alternate between being + // pure whitespace and being pure non-whitespace. This is ALMOST what the + // segments returned by a word-based Intl.Segmenter already look like, + // but not quite - see explanation in the docs of our custom segment() + // function. + parts = segment(value, segmenter); + } + else { + parts = value.match(tokenizeIncludingWhitespace) || []; + } + const tokens = []; + let prevPart = null; + parts.forEach(part => { + if ((/\s/).test(part)) { + if (prevPart == null) { + tokens.push(part); + } + else { + tokens.push(tokens.pop() + part); + } + } + else if (prevPart != null && (/\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; + } + join(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((token, i) => { + if (i == 0) { + return token; + } + else { + return token.replace((/^\s+/), ''); + } + }).join(''); + } + postProcess(changes, options) { + if (!changes || options.oneChangePerToken) { + return changes; + } + let lastKeep = null; + // Change objects representing any insertion or deletion since the last + // "keep" change object. There can be at most one of each. + let insertion = null; + let deletion = null; + changes.forEach(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, options.intlSegmenter); + } + lastKeep = change; + insertion = null; + deletion = null; + } + }); + if (insertion || deletion) { + dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null, options.intlSegmenter); + } + return changes; + } +} +export const wordDiff = new WordDiff(); +export 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, segmenter) { + // 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) { + const [oldWsPrefix, oldWsSuffix] = leadingAndTrailingWs(deletion.value, segmenter); + const [newWsPrefix, newWsSuffix] = leadingAndTrailingWs(insertion.value, segmenter); + if (startKeep) { + const 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) { + const 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) { + const ws = leadingWs(insertion.value, segmenter); + insertion.value = insertion.value.substring(ws.length); + } + if (endKeep) { + const ws = leadingWs(endKeep.value, segmenter); + endKeep.value = endKeep.value.substring(ws.length); + } + // otherwise we've got a deletion and no insertion + } + else if (startKeep && endKeep) { + const newWsFull = leadingWs(endKeep.value, segmenter), [delWsStart, delWsEnd] = leadingAndTrailingWs(deletion.value, segmenter); + // Any whitespace that comes straight after startKeep in both the old and + // new texts, assign to startKeep and remove from the deletion. + const 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. + const 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. + const endKeepWsPrefix = leadingWs(endKeep.value, segmenter); + const deletionWsSuffix = trailingWs(deletion.value, segmenter); + const 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. + const startKeepWsSuffix = trailingWs(startKeep.value, segmenter); + const deletionWsPrefix = leadingWs(deletion.value, segmenter); + const overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix); + deletion.value = removePrefix(deletion.value, overlap); + } +} +class WordsWithSpaceDiff extends Diff { + tokenize(value) { + // Slightly different to the tokenizeIncludingWhitespace regex used above in + // that this one treats each individual newline as a distinct token, 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 + const regex = new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`, 'ug'); + return value.match(regex) || []; + } +} +export const wordsWithSpaceDiff = new WordsWithSpaceDiff(); +export function diffWordsWithSpace(oldStr, newStr, options) { + return wordsWithSpaceDiff.diff(oldStr, newStr, options); +} diff --git a/node_modules/diff/libesm/index.js b/node_modules/diff/libesm/index.js new file mode 100644 index 0000000000000..18a495a18f663 --- /dev/null +++ b/node_modules/diff/libesm/index.js @@ -0,0 +1,30 @@ +/* See LICENSE file for terms of use */ +/* + * Text diff implementation. + * + * This library supports the following APIs: + * Diff.diffChars: Character by character diff + * Diff.diffWords: Word (as defined by \b regex) diff which ignores whitespace + * Diff.diffLines: Line based diff + * + * Diff.diffCss: Diff targeted at CSS content + * + * These methods are based on the implementation proposed in + * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 + */ +import Diff from './diff/base.js'; +import { diffChars, characterDiff } from './diff/character.js'; +import { diffWords, diffWordsWithSpace, wordDiff, wordsWithSpaceDiff } from './diff/word.js'; +import { diffLines, diffTrimmedLines, lineDiff } from './diff/line.js'; +import { diffSentences, sentenceDiff } from './diff/sentence.js'; +import { diffCss, cssDiff } from './diff/css.js'; +import { diffJson, canonicalize, jsonDiff } from './diff/json.js'; +import { diffArrays, arrayDiff } from './diff/array.js'; +import { applyPatch, applyPatches } from './patch/apply.js'; +import { parsePatch } from './patch/parse.js'; +import { reversePatch } from './patch/reverse.js'; +import { structuredPatch, createTwoFilesPatch, createPatch, formatPatch, INCLUDE_HEADERS, FILE_HEADERS_ONLY, OMIT_HEADERS } from './patch/create.js'; +import { convertChangesToDMP } from './convert/dmp.js'; +import { convertChangesToXML } from './convert/xml.js'; +export { Diff, diffChars, characterDiff, diffWords, wordDiff, diffWordsWithSpace, wordsWithSpaceDiff, diffLines, lineDiff, diffTrimmedLines, diffSentences, sentenceDiff, diffCss, cssDiff, diffJson, jsonDiff, diffArrays, arrayDiff, structuredPatch, createTwoFilesPatch, createPatch, formatPatch, INCLUDE_HEADERS, FILE_HEADERS_ONLY, OMIT_HEADERS, applyPatch, applyPatches, parsePatch, reversePatch, convertChangesToDMP, convertChangesToXML, canonicalize }; diff --git a/node_modules/diff/libesm/package.json b/node_modules/diff/libesm/package.json new file mode 100644 index 0000000000000..2bd6e5099f38c --- /dev/null +++ b/node_modules/diff/libesm/package.json @@ -0,0 +1 @@ +{"type":"module","sideEffects":false} \ No newline at end of file diff --git a/node_modules/diff/libesm/patch/apply.js b/node_modules/diff/libesm/patch/apply.js new file mode 100644 index 0000000000000..fe2e8db5c465d --- /dev/null +++ b/node_modules/diff/libesm/patch/apply.js @@ -0,0 +1,257 @@ +import { hasOnlyWinLineEndings, hasOnlyUnixLineEndings } from '../util/string.js'; +import { isWin, isUnix, unixToWin, winToUnix } from './line-endings.js'; +import { parsePatch } from './parse.js'; +import distanceIterator from '../util/distance-iterator.js'; +/** + * attempts to apply a unified diff patch. + * + * Hunks are applied first to last. + * `applyPatch` first tries to apply the first hunk at the line number specified in the hunk header, and with all context lines matching exactly. + * If that fails, it tries scanning backwards and forwards, one line at a time, to find a place to apply the hunk where the context lines match exactly. + * If that still fails, and `fuzzFactor` is greater than zero, it increments the maximum number of mismatches (missing, extra, or changed context lines) that there can be between the hunk context and a region where we are trying to apply the patch such that the hunk will still be considered to match. + * Regardless of `fuzzFactor`, lines to be deleted in the hunk *must* be present for a hunk to match, and the context lines *immediately* before and after an insertion must match exactly. + * + * Once a hunk is successfully fitted, the process begins again with the next hunk. + * Regardless of `fuzzFactor`, later hunks must be applied later in the file than earlier hunks. + * + * If a hunk cannot be successfully fitted *anywhere* with fewer than `fuzzFactor` mismatches, `applyPatch` fails and returns `false`. + * + * If a hunk is successfully fitted but not at the line number specified by the hunk header, all subsequent hunks have their target line number adjusted accordingly. + * (e.g. if the first hunk is applied 10 lines below where the hunk header said it should fit, `applyPatch` will *start* looking for somewhere to apply the second hunk 10 lines below where its hunk header says it goes.) + * + * If the patch was applied successfully, returns a string containing the patched text. + * If the patch could not be applied (because some hunks in the patch couldn't be fitted to the text in `source`), `applyPatch` returns false. + * + * @param patch a string diff or the output from the `parsePatch` or `structuredPatch` methods. + */ +export function applyPatch(source, patch, options = {}) { + let patches; + if (typeof patch === 'string') { + patches = parsePatch(patch); + } + else if (Array.isArray(patch)) { + patches = patch; + } + else { + patches = [patch]; + } + if (patches.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + return applyStructuredPatch(source, patches[0], options); +} +function applyStructuredPatch(source, patch, options = {}) { + if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) { + if (hasOnlyWinLineEndings(source) && isUnix(patch)) { + patch = unixToWin(patch); + } + else if (hasOnlyUnixLineEndings(source) && isWin(patch)) { + patch = winToUnix(patch); + } + } + // Apply the diff to the input + const lines = source.split('\n'), hunks = patch.hunks, compareLine = options.compareLine || ((lineNumber, line, operation, patchContent) => line === patchContent), fuzzFactor = options.fuzzFactor || 0; + let 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: + let prevLine = '', removeEOFNL = false, addEOFNL = false; + for (let i = 0; i < hunks[hunks.length - 1].lines.length; i++) { + const 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, hunkLinesI = 0, lastContextLineMatched = true, patchedLines = [], patchedLinesLength = 0) { + let nConsecutiveOldContextLines = 0; + let nextContextLineMustMatch = false; + for (; hunkLinesI < hunkLines.length; hunkLinesI++) { + const 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, + oldLineLastI: toPos - 1 + }; + } + const resultLines = []; + // Search best fit offsets for each hunk based on the previous ones + let prevHunkOffset = 0; + for (let i = 0; i < hunks.length; i++) { + const hunk = hunks[i]; + let hunkResult; + const maxLine = lines.length - hunk.oldLines + fuzzFactor; + let toPos; + for (let maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) { + toPos = hunk.oldStart + prevHunkOffset - 1; + const 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 (let i = minLine; i < toPos; i++) { + resultLines.push(lines[i]); + } + // Add the lines produced by applying the hunk: + for (let i = 0; i < hunkResult.patchedLines.length; i++) { + const line = hunkResult.patchedLines[i]; + 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 (let i = minLine; i < lines.length; i++) { + resultLines.push(lines[i]); + } + return resultLines.join('\n'); +} +/** + * applies one or more patches. + * + * `patch` may be either an array of structured patch objects, or a string representing a patch in unified diff format (which may patch one or more files). + * + * This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is: + * + * - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. + * - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution. + * + * Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. + */ +export function applyPatches(uniDiff, options) { + const spDiff = typeof uniDiff === 'string' ? parsePatch(uniDiff) : uniDiff; + let currentIndex = 0; + function processIndex() { + const index = spDiff[currentIndex++]; + if (!index) { + return options.complete(); + } + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + const updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + processIndex(); + }); + }); + } + processIndex(); +} diff --git a/node_modules/diff/libesm/patch/create.js b/node_modules/diff/libesm/patch/create.js new file mode 100644 index 0000000000000..73ba2969cf94a --- /dev/null +++ b/node_modules/diff/libesm/patch/create.js @@ -0,0 +1,228 @@ +import { diffLines } from '../diff/line.js'; +export const INCLUDE_HEADERS = { + includeIndex: true, + includeUnderline: true, + includeFileHeaders: true +}; +export const FILE_HEADERS_ONLY = { + includeIndex: false, + includeUnderline: false, + includeFileHeaders: true +}; +export const OMIT_HEADERS = { + includeIndex: false, + includeUnderline: false, + includeFileHeaders: false +}; +export function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + let optionsObj; + if (!options) { + optionsObj = {}; + } + else if (typeof options === 'function') { + optionsObj = { callback: options }; + } + else { + optionsObj = options; + } + if (typeof optionsObj.context === 'undefined') { + optionsObj.context = 4; + } + // We copy this into its own variable to placate TypeScript, which thinks + // optionsObj.context might be undefined in the callbacks below. + const context = optionsObj.context; + // @ts-expect-error (runtime check for something that is correctly a static type error) + if (optionsObj.newlineIsToken) { + throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions'); + } + if (!optionsObj.callback) { + return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj)); + } + else { + const { callback } = optionsObj; + diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => { + const patch = diffLinesResultToPatch(diff); + // TypeScript is unhappy without the cast because it does not understand that `patch` may + // be undefined here only if `callback` is StructuredPatchCallbackAbortable: + 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; }); + } + const hunks = []; + let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; + for (let i = 0; i < diff.length; i++) { + const current = diff[i], lines = current.lines || splitLines(current.value); + current.lines = lines; + if (current.added || current.removed) { + // If we have previous context, start with that + if (!oldRangeStart) { + const prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + if (prev) { + curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + // Output our changes + for (const line of lines) { + curRange.push((current.added ? '+' : '-') + line); + } + // 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 <= context * 2 && i < diff.length - 2) { + // Overlapping + for (const line of contextLines(lines)) { + curRange.push(line); + } + } + else { + // end the range and output + const contextSize = Math.min(lines.length, context); + for (const line of contextLines(lines.slice(0, contextSize))) { + curRange.push(line); + } + const 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; + } + } + // Step 2: eliminate the trailing `\n` from each line of each hunk, and, where needed, add + // "\ No newline at end of file". + for (const hunk of hunks) { + for (let i = 0; i < hunk.lines.length; i++) { + if (hunk.lines[i].endsWith('\n')) { + hunk.lines[i] = hunk.lines[i].slice(0, -1); + } + else { + hunk.lines.splice(i + 1, 0, '\\ No newline at end of file'); + i++; // Skip the line we just added, then continue iterating + } + } + } + return { + oldFileName: oldFileName, newFileName: newFileName, + oldHeader: oldHeader, newHeader: newHeader, + hunks: hunks + }; + } +} +/** + * creates a unified diff patch. + * @param patch either a single structured patch object (as returned by `structuredPatch`) or an array of them (as returned by `parsePatch`) + */ +export function formatPatch(patch, headerOptions) { + if (!headerOptions) { + headerOptions = INCLUDE_HEADERS; + } + if (Array.isArray(patch)) { + if (patch.length > 1 && !headerOptions.includeFileHeaders) { + throw new Error('Cannot omit file headers on a multi-file patch. ' + + '(The result would be unparseable; how would a tool trying to apply ' + + 'the patch know which changes are to which file?)'); + } + return patch.map(p => formatPatch(p, headerOptions)).join('\n'); + } + const ret = []; + if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) { + ret.push('Index: ' + patch.oldFileName); + } + if (headerOptions.includeUnderline) { + ret.push('==================================================================='); + } + if (headerOptions.includeFileHeaders) { + ret.push('--- ' + patch.oldFileName + (typeof patch.oldHeader === 'undefined' ? '' : '\t' + patch.oldHeader)); + ret.push('+++ ' + patch.newFileName + (typeof patch.newHeader === 'undefined' ? '' : '\t' + patch.newHeader)); + } + for (let i = 0; i < patch.hunks.length; i++) { + const hunk = patch.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 + + ' @@'); + for (const line of hunk.lines) { + ret.push(line); + } + } + return ret.join('\n') + '\n'; +} +export function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (typeof options === 'function') { + options = { callback: options }; + } + if (!(options === null || options === void 0 ? void 0 : options.callback)) { + const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + if (!patchObj) { + return; + } + return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions); + } + else { + const { callback } = options; + structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: patchObj => { + if (!patchObj) { + callback(undefined); + } + else { + callback(formatPatch(patchObj, options.headerOptions)); + } + } })); + } +} +export 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) { + const hasTrailingNl = text.endsWith('\n'); + const result = text.split('\n').map(line => line + '\n'); + if (hasTrailingNl) { + result.pop(); + } + else { + result.push(result.pop().slice(0, -1)); + } + return result; +} diff --git a/node_modules/diff/libesm/patch/line-endings.js b/node_modules/diff/libesm/patch/line-endings.js new file mode 100644 index 0000000000000..ab54b715f0047 --- /dev/null +++ b/node_modules/diff/libesm/patch/line-endings.js @@ -0,0 +1,44 @@ +export function unixToWin(patch) { + if (Array.isArray(patch)) { + // It would be cleaner if instead of the line below we could just write + // return patch.map(unixToWin) + // but mysteriously TypeScript (v5.7.3 at the time of writing) does not like this and it will + // refuse to compile, thinking that unixToWin could then return StructuredPatch[][] and the + // result would be incompatible with the overload signatures. + // See bug report at https://github.com/microsoft/TypeScript/issues/61398. + return patch.map(p => unixToWin(p)); + } + return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map(hunk => (Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line, i) => { + var _a; + return (line.startsWith('\\') || line.endsWith('\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\'))) + ? line + : line + '\r'; + }) }))) }); +} +export function winToUnix(patch) { + if (Array.isArray(patch)) { + // (See comment above equivalent line in unixToWin) + return patch.map(p => winToUnix(p)); + } + return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map(hunk => (Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map(line => 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). + */ +export function isUnix(patch) { + if (!Array.isArray(patch)) { + patch = [patch]; + } + return !patch.some(index => index.hunks.some(hunk => hunk.lines.some(line => !line.startsWith('\\') && line.endsWith('\r')))); +} +/** + * Returns true if the patch uses Windows line endings and only Windows line endings. + */ +export function isWin(patch) { + if (!Array.isArray(patch)) { + patch = [patch]; + } + return patch.some(index => index.hunks.some(hunk => hunk.lines.some(line => line.endsWith('\r')))) + && patch.every(index => index.hunks.every(hunk => hunk.lines.every((line, i) => { var _a; return line.startsWith('\\') || line.endsWith('\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\')); }))); +} diff --git a/node_modules/diff/libesm/patch/parse.js b/node_modules/diff/libesm/patch/parse.js new file mode 100644 index 0000000000000..1dacac74bcf00 --- /dev/null +++ b/node_modules/diff/libesm/patch/parse.js @@ -0,0 +1,147 @@ +/** + * Parses a patch into structured data, in the same structure returned by `structuredPatch`. + * + * @return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. + */ +export function parsePatch(uniDiff) { + const diffstr = uniDiff.split(/\n/), list = []; + let i = 0; + function parseIndex() { + const index = {}; + list.push(index); + // Parse diff metadata + while (i < diffstr.length) { + const line = diffstr[i]; + // File header found, end parsing diff metadata + if ((/^(---|\+\+\+|@@)\s/).test(line)) { + break; + } + // Try to parse the line as a diff header, like + // Index: README.md + // or + // diff -r 9117c6561b0b -r 273ce12ad8f1 .hgignore + // or + // Index: something with multiple words + // and extract the filename (or whatever else is used as an index name) + // from the end (i.e. 'README.md', '.hgignore', or + // 'something with multiple words' in the examples above). + // + // TODO: It seems awkward that we indiscriminately trim off trailing + // whitespace here. Theoretically, couldn't that be meaningful - + // e.g. if the patch represents a diff of a file whose name ends + // with a space? Seems wrong to nuke it. + // But this behaviour has been around since v2.2.1 in 2015, so if + // it's going to change, it should be done cautiously and in a new + // major release, for backwards-compat reasons. + // -- ExplodingCabbage + const headerMatch = (/^(?:Index:|diff(?: -r \w+)+)\s+/).exec(line); + if (headerMatch) { + index.index = line.substring(headerMatch[0].length).trim(); + } + 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) { + const 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) { + const fileHeaderMatch = (/^(---|\+\+\+)\s+/).exec(diffstr[i]); + if (fileHeaderMatch) { + const prefix = fileHeaderMatch[1], data = diffstr[i].substring(3).trim().split('\t', 2), header = (data[1] || '').trim(); + let fileName = data[0].replace(/\\\\/g, '\\'); + if (fileName.startsWith('"') && fileName.endsWith('"')) { + fileName = fileName.substr(1, fileName.length - 2); + } + if (prefix === '---') { + index.oldFileName = fileName; + index.oldHeader = header; + } + else { + index.newFileName = fileName; + index.newHeader = header; + } + i++; + } + } + // Parses a hunk + // This assumes that we are at the start of a hunk. + function parseHunk() { + var _a; + const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + const 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; + } + let addCount = 0, removeCount = 0; + for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a = diffstr[i]) === null || _a === void 0 ? void 0 : _a.startsWith('\\'))); i++) { + const 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 ${chunkHeaderIndex + 1} contained invalid line ${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; +} diff --git a/node_modules/diff/libesm/patch/reverse.js b/node_modules/diff/libesm/patch/reverse.js new file mode 100644 index 0000000000000..9207b51c63c55 --- /dev/null +++ b/node_modules/diff/libesm/patch/reverse.js @@ -0,0 +1,23 @@ +export function reversePatch(structuredPatch) { + if (Array.isArray(structuredPatch)) { + // (See comment in unixToWin for why we need the pointless-looking anonymous function here) + return structuredPatch.map(patch => reversePatch(patch)).reverse(); + } + return Object.assign(Object.assign({}, structuredPatch), { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(hunk => { + return { + oldLines: hunk.newLines, + oldStart: hunk.newStart, + newLines: hunk.oldLines, + newStart: hunk.oldStart, + lines: hunk.lines.map(l => { + if (l.startsWith('-')) { + return `+${l.slice(1)}`; + } + if (l.startsWith('+')) { + return `-${l.slice(1)}`; + } + return l; + }) + }; + }) }); +} diff --git a/node_modules/diff/libesm/types.js b/node_modules/diff/libesm/types.js new file mode 100644 index 0000000000000..cb0ff5c3b541f --- /dev/null +++ b/node_modules/diff/libesm/types.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/diff/libesm/util/array.js b/node_modules/diff/libesm/util/array.js new file mode 100644 index 0000000000000..c3e00f8500390 --- /dev/null +++ b/node_modules/diff/libesm/util/array.js @@ -0,0 +1,17 @@ +export function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + return arrayStartsWith(a, b); +} +export function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + for (let i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + return true; +} diff --git a/node_modules/diff/libesm/util/distance-iterator.js b/node_modules/diff/libesm/util/distance-iterator.js new file mode 100644 index 0000000000000..afa638143ece1 --- /dev/null +++ b/node_modules/diff/libesm/util/distance-iterator.js @@ -0,0 +1,37 @@ +// 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. +export default function (start, minLine, maxLine) { + let 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 + return undefined; + }; +} diff --git a/node_modules/diff/libesm/util/params.js b/node_modules/diff/libesm/util/params.js new file mode 100644 index 0000000000000..c9921a2106257 --- /dev/null +++ b/node_modules/diff/libesm/util/params.js @@ -0,0 +1,14 @@ +export function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } + else if (options) { + for (const name in options) { + /* istanbul ignore else */ + if (Object.prototype.hasOwnProperty.call(options, name)) { + defaults[name] = options[name]; + } + } + } + return defaults; +} diff --git a/node_modules/diff/libesm/util/string.js b/node_modules/diff/libesm/util/string.js new file mode 100644 index 0000000000000..edb6d14a9aa5a --- /dev/null +++ b/node_modules/diff/libesm/util/string.js @@ -0,0 +1,184 @@ +export function longestCommonPrefix(str1, str2) { + let 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); +} +export function longestCommonSuffix(str1, str2) { + let 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); +} +export function replacePrefix(string, oldPrefix, newPrefix) { + if (string.slice(0, oldPrefix.length) != oldPrefix) { + throw Error(`string ${JSON.stringify(string)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`); + } + return newPrefix + string.slice(oldPrefix.length); +} +export function replaceSuffix(string, oldSuffix, newSuffix) { + if (!oldSuffix) { + return string + newSuffix; + } + if (string.slice(-oldSuffix.length) != oldSuffix) { + throw Error(`string ${JSON.stringify(string)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`); + } + return string.slice(0, -oldSuffix.length) + newSuffix; +} +export function removePrefix(string, oldPrefix) { + return replacePrefix(string, oldPrefix, ''); +} +export function removeSuffix(string, oldSuffix) { + return replaceSuffix(string, oldSuffix, ''); +} +export 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 + let startA = 0; + if (a.length > b.length) { + startA = a.length - b.length; + } + let 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: + const map = Array(endB); + let k = 0; // Index that lags behind j + map[0] = 0; + for (let 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 (let 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. + */ +export 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. + */ +export function hasOnlyUnixLineEndings(string) { + return !string.includes('\r\n') && string.includes('\n'); +} +/** + * Split a string into segments using a word segmenter, merging consecutive + * segments if they are both whitespace segments. Whitespace segments can + * appear adjacent to one another for two reasons: + * - newlines always get their own segment + * - where a diacritic is attached to a whitespace character in the text, the + * segment ends after the diacritic, so e.g. " \u0300 " becomes two segments. + * This function therefore runs the segmenter's .segment() method and then + * merges consecutive segments of whitespace into a single part. + */ +export function segment(string, segmenter) { + const parts = []; + for (const segmentObj of Array.from(segmenter.segment(string))) { + const segment = segmentObj.segment; + if (parts.length && (/\s/).test(parts[parts.length - 1]) && (/\s/).test(segment)) { + parts[parts.length - 1] += segment; + } + else { + parts.push(segment); + } + } + return parts; +} +// The functions below take a `segmenter` argument so that, when called from +// diffWords when it is using a segmenter, they can use a notion of what +// constitutes "whitespace" that is consistent with the segmenter. +// +// USUALLY this will be identical to the result of the non-segmenter-based +// logic, but it differs in at least one case: when whitespace characters are +// modified by diacritics. A word segmenter considers these diacritics to be +// part of the whitespace, whereas our non-segmenter-based logic does not. +// +// Because the segmenter-based approach necessarily requires segmenting the +// entire string, we offer a leadingAndTrailingWs function to allow getting the +// whitespace prefix AND whitespace suffix with a single call to the segmenter, +// for efficiency's sake. +export function trailingWs(string, segmenter) { + if (segmenter) { + return leadingAndTrailingWs(string, segmenter)[1]; + } + // Yes, this looks overcomplicated and dumb - why not replace the whole function with + // return string.match(/\s*$/)[0] + // you ask? Because: + // 1. the trap described at https://markamery.com/blog/quadratic-time-regexes/ would mean doing + // this would cause this function to take O(n²) time in the worst case (specifically when + // there is a massive run of NON-TRAILING whitespace in `string`), and + // 2. the fix proposed in the same blog post, of using a negative lookbehind, is incompatible + // with old Safari versions that we'd like to not break if possible (see + // https://github.com/kpdecker/jsdiff/pull/550) + // It feels absurd to do this with an explicit loop instead of a regex, but I really can't see a + // better way that doesn't result in broken behaviour. + let i; + for (i = string.length - 1; i >= 0; i--) { + if (!string[i].match(/\s/)) { + break; + } + } + return string.substring(i + 1); +} +export function leadingWs(string, segmenter) { + if (segmenter) { + return leadingAndTrailingWs(string, segmenter)[0]; + } + // Thankfully the annoying considerations described in trailingWs don't apply here: + const match = string.match(/^\s*/); + return match ? match[0] : ''; +} +export function leadingAndTrailingWs(string, segmenter) { + if (!segmenter) { + return [leadingWs(string), trailingWs(string)]; + } + if (segmenter.resolvedOptions().granularity != 'word') { + throw new Error('The segmenter passed must have a granularity of "word"'); + } + const segments = segment(string, segmenter); + const firstSeg = segments[0]; + const lastSeg = segments[segments.length - 1]; + const head = (/\s/).test(firstSeg) ? firstSeg : ''; + const tail = (/\s/).test(lastSeg) ? lastSeg : ''; + return [head, tail]; +} diff --git a/node_modules/diff/package.json b/node_modules/diff/package.json index dcffb9474baef..7d021f318c110 100644 --- a/node_modules/diff/package.json +++ b/node_modules/diff/package.json @@ -1,6 +1,6 @@ { "name": "diff", - "version": "5.2.0", + "version": "8.0.4", "description": "A JavaScript text diff implementation.", "keywords": [ "diff", @@ -23,67 +23,108 @@ "license": "BSD-3-Clause", "repository": { "type": "git", - "url": "git://github.com/kpdecker/jsdiff.git" + "url": "https://github.com/kpdecker/jsdiff.git" }, "engines": { "node": ">=0.3.1" }, - "main": "./lib/index.js", - "module": "./lib/index.es6.js", + "main": "./libcjs/index.js", + "module": "./libesm/index.js", "browser": "./dist/diff.js", "unpkg": "./dist/diff.js", "exports": { ".": { - "import": "./lib/index.mjs", - "require": "./lib/index.js" + "import": { + "types": "./libesm/index.d.ts", + "default": "./libesm/index.js" + }, + "require": { + "types": "./libcjs/index.d.ts", + "default": "./libcjs/index.js" + } }, "./package.json": "./package.json", - "./": "./", - "./*": "./*" + "./lib/*.js": { + "import": { + "types": "./libesm/*.d.ts", + "default": "./libesm/*.js" + }, + "require": { + "types": "./libcjs/*.d.ts", + "default": "./libcjs/*.js" + } + }, + "./lib/": { + "import": { + "types": "./libesm/", + "default": "./libesm/" + }, + "require": { + "types": "./libcjs/", + "default": "./libcjs/" + } + } }, + "type": "module", + "types": "libcjs/index.d.ts", "scripts": { - "clean": "rm -rf lib/ dist/", - "build:node": "yarn babel --out-dir lib --source-maps=inline src", - "test": "grunt" + "clean": "rm -rf libcjs/ libesm/ dist/ coverage/ .nyc_output/", + "lint": "yarn eslint", + "build": "yarn lint && yarn generate-esm && yarn generate-cjs && yarn check-types && yarn run-rollup && yarn run-uglify", + "generate-cjs": "yarn tsc --module commonjs --outDir libcjs && node --eval \"fs.writeFileSync('libcjs/package.json', JSON.stringify({type:'commonjs',sideEffects:false}))\"", + "generate-esm": "yarn tsc --module nodenext --outDir libesm --target es6 && node --eval \"fs.writeFileSync('libesm/package.json', JSON.stringify({type:'module',sideEffects:false}))\"", + "check-types": "yarn run-tsd && yarn run-attw", + "test": "nyc yarn _test", + "_test": "yarn build && cross-env NODE_ENV=test yarn run-mocha", + "run-attw": "yarn attw --pack --entrypoints . && yarn attw --pack --entrypoints lib/diff/word.js --profile node16", + "run-tsd": "yarn tsd --typings libesm/ && yarn tsd --files test-d/", + "run-rollup": "rollup -c rollup.config.mjs", + "run-uglify": "uglifyjs dist/diff.js -c -o dist/diff.min.js", + "run-mocha": "mocha --require ./runtime 'test/**/*.js'" }, "devDependencies": { - "@babel/cli": "^7.2.3", - "@babel/core": "^7.2.2", - "@babel/plugin-transform-modules-commonjs": "^7.2.0", - "@babel/preset-env": "^7.2.3", - "@babel/register": "^7.0.0", - "@colors/colors": "^1.3.3", - "babel-eslint": "^10.0.1", - "babel-loader": "^8.0.5", - "chai": "^4.2.0", - "eslint": "^5.12.0", - "grunt": "^1.0.3", - "grunt-babel": "^8.0.0", - "grunt-cli": "^1.3.2", - "grunt-contrib-clean": "^2.0.0", - "grunt-contrib-copy": "^1.0.0", - "grunt-contrib-uglify": "^5.0.0", - "grunt-contrib-watch": "^1.1.0", - "grunt-eslint": "^23.0.0", - "grunt-exec": "^3.0.0", - "grunt-karma": "^4.0.0", - "grunt-mocha-istanbul": "^5.0.2", - "grunt-mocha-test": "^0.13.3", - "grunt-webpack": "^3.1.3", - "istanbul": "github:kpdecker/istanbul", - "karma": "^6.3.16", - "karma-chrome-launcher": "^3.1.0", + "@arethetypeswrong/cli": "^0.18.2", + "@babel/core": "^7.29.0", + "@babel/preset-env": "^7.29.2", + "@babel/register": "^7.28.6", + "@colors/colors": "^1.6.0", + "@eslint/js": "^10.0.1", + "babel-loader": "^10.1.1", + "babel-plugin-istanbul": "^7.0.1", + "chai": "^6.2.2", + "cross-env": "^10.1.0", + "eslint": "^10.1.0", + "globals": "^17.4.0", + "karma": "^6.4.4", "karma-mocha": "^2.0.1", - "karma-mocha-reporter": "^2.0.0", - "karma-sauce-launcher": "^4.1.5", - "karma-sourcemap-loader": "^0.3.6", - "karma-webpack": "^4.0.2", - "mocha": "^6.0.0", - "rollup": "^1.0.2", - "rollup-plugin-babel": "^4.2.0", - "semver": "^7.3.2", - "webpack": "^4.28.3", - "webpack-dev-server": "^3.1.14" + "karma-mocha-reporter": "^2.2.5", + "karma-sourcemap-loader": "^0.4.0", + "karma-webpack": "^5.0.1", + "mocha": "^11.7.5", + "nyc": "^18.0.0", + "rollup": "^4.60.0", + "tsd": "^0.33.0", + "typescript": "^5.9.3", + "typescript-eslint": "^8.57.1", + "uglify-js": "^3.19.3", + "webpack": "^5.105.4", + "webpack-dev-server": "^5.2.3" + }, + "nyc": { + "require": [ + "@babel/register" + ], + "reporter": [ + "lcov", + "text" + ], + "sourceMap": false, + "instrument": false, + "check-coverage": true, + "branches": 100, + "lines": 100, + "functions": 100, + "statements": 100 }, - "optionalDependencies": {} -} + "packageManager": "yarn@4.12.0" +} \ No newline at end of file diff --git a/node_modules/diff/release-notes.md b/node_modules/diff/release-notes.md index fe98f22d239e7..00a277084c8bf 100644 --- a/node_modules/diff/release-notes.md +++ b/node_modules/diff/release-notes.md @@ -1,11 +1,110 @@ # Release Notes +## 8.0.4 + +- [#667](https://github.com/kpdecker/jsdiff/pull/667) - **fix another bug in `diffWords` when used with an `Intl.Segmenter`**. If the text to be diffed included a combining mark after a whitespace character (i.e. roughly speaking, an accented space), `diffWords` would previously crash. Now this case is handled correctly. + +## 8.0.3 + +- [#631](https://github.com/kpdecker/jsdiff/pull/631) - **fix support for using an `Intl.Segmenter` with `diffWords`**. This has been almost completely broken since the feature was added in v6.0.0, since it would outright crash on any text that featured two consecutive newlines between a pair of words (a very common case). +- [#635](https://github.com/kpdecker/jsdiff/pull/635) - **small tweaks to tokenization behaviour of `diffWords`** when used *without* an `Intl.Segmenter`. Specifically, the soft hyphen (U+00AD) is no longer considered to be a word break, and the multiplication and division signs (`×` and `÷`) are now treated as punctuation instead of as letters / word characters. +- [#641](https://github.com/kpdecker/jsdiff/pull/641) - **the format of file headers in `createPatch` etc. patches can now be customised somewhat**. It now takes a `headerOptions` option that can be used to disable the file headers entirely, or omit the `Index:` line and/or the underline. In particular, this was motivated by a request to make jsdiff patches compatible with react-diff-view, which they now are if produced with `headerOptions: FILE_HEADERS_ONLY`. +- [#647](https://github.com/kpdecker/jsdiff/pull/647) and [#649](https://github.com/kpdecker/jsdiff/pull/649) - **fix denial-of-service vulnerabilities in `parsePatch` whereby adversarial input could cause a memory-leaking infinite loop, typically crashing the calling process**. Also fixed ReDOS vulnerabilities whereby adversarially-crafted patch headers could take cubic time to parse. Now, `parsePatch` should reliably take linear time. (Handling of headers that include the line break characters `\r`, `\u2028`, or `\u2029` in non-trailing positions is also now more reasonable as side effect of the fix.) + +## 8.0.2 + +- [#616](https://github.com/kpdecker/jsdiff/pull/616) **Restored compatibility of `diffSentences` with old Safari versions.** This was broken in 8.0.0 by the introduction of a regex with a [lookbehind assertion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion); these weren't supported in Safari prior to version 16.4. +- [#612](https://github.com/kpdecker/jsdiff/pull/612) **Improved tree shakeability** by marking the built CJS and ESM packages with `sideEffects: false`. + +## 8.0.1 + +- [#610](https://github.com/kpdecker/jsdiff/pull/610) **Fixes types for `diffJson` which were broken by 8.0.0**. The new bundled types in 8.0.0 only allowed `diffJson` to be passed string arguments, but it should've been possible to pass either strings or objects (and now is). Thanks to Josh Kelley for the fix. + +## 8.0.0 + +- [#580](https://github.com/kpdecker/jsdiff/pull/580) **Multiple tweaks to `diffSentences`**: + * tokenization no longer takes quadratic time on pathological inputs (reported as a ReDOS vulnerability by Snyk); is now linear instead + * the final sentence in the string is now handled the same by the tokenizer regardless of whether it has a trailing punctuation mark or not. (Previously, "foo. bar." tokenized to `["foo.", " ", "bar."]` but "foo. bar" tokenized to `["foo.", " bar"]` - i.e. whether the space between sentences was treated as a separate token depended upon whether the final sentence had trailing punctuation or not. This was arbitrary and surprising; it is no longer the case.) + * in a string that starts with a sentence end, like "! hello.", the "!" is now treated as a separate sentence + * the README now correctly documents the tokenization behaviour (it was wrong before) +- [#581](https://github.com/kpdecker/jsdiff/pull/581) - **fixed some regex operations used for tokenization in `diffWords` taking O(n^2) time** in pathological cases +- [#595](https://github.com/kpdecker/jsdiff/pull/595) - **fixed a crash in patch creation functions when handling a single hunk consisting of a very large number (e.g. >130k) of lines**. (This was caused by spreading indefinitely-large arrays to `.push()` using `.apply` or the spread operator and hitting the JS-implementation-specific limit on the maximum number of arguments to a function, as shown at https://stackoverflow.com/a/56809779/1709587; thus the exact threshold to hit the error will depend on the environment in which you were running JsDiff.) +- [#596](https://github.com/kpdecker/jsdiff/pull/596) - **removed the `merge` function**. Previously JsDiff included an undocumented function called `merge` that was meant to, in some sense, merge patches. It had at least a couple of serious bugs that could lead to it returning unambiguously wrong results, and it was difficult to simply "fix" because it was [unclear precisely what it was meant to do](https://github.com/kpdecker/jsdiff/issues/181#issuecomment-2198319542). For now, the fix is to remove it entirely. +- [#591](https://github.com/kpdecker/jsdiff/pull/591) - JsDiff's source code has been rewritten in TypeScript. This change entails the following changes for end users: + * **the `diff` package on npm now includes its own TypeScript type definitions**. Users who previously used the `@types/diff` npm package from DefinitelyTyped should remove that dependency when upgrading JsDiff to v8. + + Note that the transition from the DefinitelyTyped types to JsDiff's own type definitions includes multiple fixes and also removes many exported types previously used for `options` arguments to diffing and patch-generation functions. (There are now different exported options types for abortable calls - ones with a `timeout` or `maxEditLength` that may give a result of `undefined` - and non-abortable calls.) See the TypeScript section of the README for some usage tips. + + * **The `Diff` object is now a class**. Custom extensions of `Diff`, as described in the "Defining custom diffing behaviors" section of the README, can therefore now be done by writing a `class CustomDiff extends Diff` and overriding methods, instead of the old way based on prototype inheritance. (I *think* code that did things the old way should still work, though!) + + * **`diff/lib/index.es6.js` and `diff/lib/index.mjs` no longer exist, and the ESM version of the library is no longer bundled into a single file.** + + * **The `ignoreWhitespace` option for `diffWords` is no longer included in the type declarations**. The effect of passing `ignoreWhitespace: true` has always been to make `diffWords` just call `diffWordsWithSpace` instead, which was confusing, because that behaviour doesn't seem properly described as "ignoring" whitespace at all. The property remains available to non-TypeScript applications for the sake of backwards compatibility, but TypeScript applications will now see a type error if they try to pass `ignoreWhitespace: true` to `diffWords` and should change their code to call `diffWordsWithSpace` instead. + + * JsDiff no longer purports to support ES3 environments. (I'm pretty sure it never truly did, despite claiming to in its README, since even the 1.0.0 release used `Array.map` which was added in ES5.) +- [#601](https://github.com/kpdecker/jsdiff/pull/601) - **`diffJson`'s `stringifyReplacer` option behaves more like `JSON.stringify`'s `replacer` argument now.** In particular: + * Each key/value pair now gets passed through the replacer once instead of twice + * The `key` passed to the replacer when the top-level object is passed in as `value` is now `""` (previously, was `undefined`), and the `key` passed with an array element is the array index as a string, like `"0"` or `"1"` (previously was whatever the key for the entire array was). Both the new behaviours match that of `JSON.stringify`. +- [#602](https://github.com/kpdecker/jsdiff/pull/602) - **diffing functions now consistently return `undefined` when called in async mode** (i.e. with a callback). Previously, there was an odd quirk where they would return `true` if the strings being diffed were equal and `undefined` otherwise. + +## 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](https://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`, and `createTwoFilesPatch`** +- [#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. **These invalid patches can also no longer be applied successfully with `applyPatch`.** (It was already the case that tools other than jsdiff, like GNU `patch`, would consider them malformed and refuse to apply them; versions of jsdiff with this fix now do the same thing if you ask them to apply a malformed patch emitted by jsdiff v5.) +- [#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.2 - January 2026 + +Only change from 5.2.0 is a backport of the fix to https://github.com/kpdecker/jsdiff/security/advisories/GHSA-73rr-hh4g-fpgx. + +## v5.2.1 (deprecated) + +Accidental release - do not use. + ## v5.2.0 -[Commits](https://github.com/kpdecker/jsdiff/compare/v5.1.0...master) +[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. +- [#448](https://github.com/kpdecker/jsdiff/pull/448) 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`. @@ -26,6 +125,18 @@ [Commits](https://github.com/kpdecker/jsdiff/compare/v4.0.1...v5.0.0) +## v4.0.4 - January 2026 + +Only change from 4.0.2 is a backport of the fix to https://github.com/kpdecker/jsdiff/security/advisories/GHSA-73rr-hh4g-fpgx. + +## v4.0.3 (deprecated) + +Accidental release - do not use. + +## v4.0.2 + +No meaningful changes from v4.0.1 - just removed some cruft that shouldn't've been published. + ## v4.0.1 - January 6th, 2019 - Fix main reference path - b826104 @@ -51,6 +162,10 @@ Compatibility notes: [Commits](https://github.com/kpdecker/jsdiff/compare/v3.5.0...v4.0.0) +## v3.5.1 - January 2026 + +Only change from 3.5.0 is a backport of the fix to https://github.com/kpdecker/jsdiff/security/advisories/GHSA-73rr-hh4g-fpgx. + ## v3.5.0 - March 4th, 2018 - Omit redundant slice in join method of diffArrays - 1023590 diff --git a/node_modules/diff/runtime.js b/node_modules/diff/runtime.js deleted file mode 100644 index 82ea7e696aa01..0000000000000 --- a/node_modules/diff/runtime.js +++ /dev/null @@ -1,3 +0,0 @@ -require('@babel/register')({ - ignore: ['lib', 'node_modules'] -}); diff --git a/node_modules/eastasianwidth/eastasianwidth.js b/node_modules/eastasianwidth/eastasianwidth.js deleted file mode 100644 index 7d0aa0f6ecbf3..0000000000000 --- a/node_modules/eastasianwidth/eastasianwidth.js +++ /dev/null @@ -1,311 +0,0 @@ -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; -}; diff --git a/node_modules/eastasianwidth/package.json b/node_modules/eastasianwidth/package.json deleted file mode 100644 index cb7ac6ab3b0da..0000000000000 --- a/node_modules/eastasianwidth/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/emoji-regex/LICENSE-MIT.txt b/node_modules/emoji-regex/LICENSE-MIT.txt deleted file mode 100644 index a41e0a7ef970e..0000000000000 --- a/node_modules/emoji-regex/LICENSE-MIT.txt +++ /dev/null @@ -1,20 +0,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. diff --git a/node_modules/emoji-regex/es2015/index.js b/node_modules/emoji-regex/es2015/index.js deleted file mode 100644 index b4cf3dcd38993..0000000000000 --- a/node_modules/emoji-regex/es2015/index.js +++ /dev/null @@ -1,6 +0,0 @@ -"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; -}; diff --git a/node_modules/emoji-regex/es2015/text.js b/node_modules/emoji-regex/es2015/text.js deleted file mode 100644 index 780309df58f1a..0000000000000 --- a/node_modules/emoji-regex/es2015/text.js +++ /dev/null @@ -1,6 +0,0 @@ -"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; -}; diff --git a/node_modules/emoji-regex/index.js b/node_modules/emoji-regex/index.js deleted file mode 100644 index d993a3a99cb95..0000000000000 --- a/node_modules/emoji-regex/index.js +++ /dev/null @@ -1,6 +0,0 @@ -"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; -}; diff --git a/node_modules/emoji-regex/package.json b/node_modules/emoji-regex/package.json deleted file mode 100644 index 6d323528292b0..0000000000000 --- a/node_modules/emoji-regex/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/emoji-regex/text.js b/node_modules/emoji-regex/text.js deleted file mode 100644 index 0a55ce2f2308a..0000000000000 --- a/node_modules/emoji-regex/text.js +++ /dev/null @@ -1,6 +0,0 @@ -"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; -}; diff --git a/node_modules/encoding/LICENSE b/node_modules/encoding/LICENSE deleted file mode 100644 index 33f5a9a366f60..0000000000000 --- a/node_modules/encoding/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -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. diff --git a/node_modules/encoding/lib/encoding.js b/node_modules/encoding/lib/encoding.js deleted file mode 100644 index 865c24bce2e06..0000000000000 --- a/node_modules/encoding/lib/encoding.js +++ /dev/null @@ -1,83 +0,0 @@ -'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(); -} diff --git a/node_modules/encoding/package.json b/node_modules/encoding/package.json deleted file mode 100644 index 773a94384fa63..0000000000000 --- a/node_modules/encoding/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/encoding/test/test.js b/node_modules/encoding/test/test.js deleted file mode 100644 index 3a7dfee989224..0000000000000 --- a/node_modules/encoding/test/test.js +++ /dev/null @@ -1,49 +0,0 @@ -'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(); - }, - */ -}; diff --git a/node_modules/err-code/bower.json b/node_modules/err-code/bower.json deleted file mode 100644 index a39cb702cedb2..0000000000000 --- a/node_modules/err-code/bower.json +++ /dev/null @@ -1,30 +0,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" - ] -} diff --git a/node_modules/err-code/index.js b/node_modules/err-code/index.js deleted file mode 100644 index 9ff3e9c5de4c2..0000000000000 --- a/node_modules/err-code/index.js +++ /dev/null @@ -1,47 +0,0 @@ -'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; diff --git a/node_modules/err-code/index.umd.js b/node_modules/err-code/index.umd.js deleted file mode 100644 index 41007269d3d03..0000000000000 --- a/node_modules/err-code/index.umd.js +++ /dev/null @@ -1,51 +0,0 @@ -(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" - } -} diff --git a/node_modules/err-code/test/test.js b/node_modules/err-code/test/test.js deleted file mode 100644 index 22ba0a8a1a8c1..0000000000000 --- a/node_modules/err-code/test/test.js +++ /dev/null @@ -1,159 +0,0 @@ -'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); - }); - }); - }); -}); diff --git a/node_modules/exponential-backoff/LICENSE b/node_modules/exponential-backoff/LICENSE index 7a4a3ea2424c0..4be46a90670d8 100644 --- a/node_modules/exponential-backoff/LICENSE +++ b/node_modules/exponential-backoff/LICENSE @@ -187,7 +187,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2019 Coveo Solutions Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -199,4 +199,4 @@ 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. \ No newline at end of file + limitations under the License. diff --git a/node_modules/exponential-backoff/dist/backoff.js b/node_modules/exponential-backoff/dist/backoff.js index a0aa0dc34b6b1..6a1b6bd3835ac 100644 --- a/node_modules/exponential-backoff/dist/backoff.js +++ b/node_modules/exponential-backoff/dist/backoff.js @@ -38,6 +38,12 @@ var __generator = (this && this.__generator) || function (thisArg, body) { Object.defineProperty(exports, "__esModule", { value: true }); var options_1 = require("./options"); var delay_factory_1 = require("./delay/delay.factory"); +/** + * Executes a function with exponential backoff. + * @param request the function to be executed + * @param options options to customize the backoff behavior + * @returns Promise that resolves to the result of the `request` function + */ function backOff(request, options) { if (options === void 0) { options = {}; } return __awaiter(this, void 0, void 0, function () { diff --git a/node_modules/exponential-backoff/package.json b/node_modules/exponential-backoff/package.json index 23232a0df2c57..e3e8dc9a5dccd 100644 --- a/node_modules/exponential-backoff/package.json +++ b/node_modules/exponential-backoff/package.json @@ -1,9 +1,10 @@ { "name": "exponential-backoff", - "version": "3.1.1", + "version": "3.1.3", "description": "A utility that allows retrying a function with an exponential delay between attempts.", "files": [ - "dist/" + "dist/", + "src/" ], "main": "dist/backoff.js", "types": "dist/backoff.d.ts", @@ -35,7 +36,7 @@ }, "repository": { "type": "git", - "url": "git+https://github.com/coveo/exponential-backoff.git" + "url": "git+https://github.com/coveooss/exponential-backoff.git" }, "keywords": [ "exponential", @@ -45,9 +46,9 @@ "author": "Sami Sayegh", "license": "Apache-2.0", "bugs": { - "url": "https://github.com/coveo/exponential-backoff/issues" + "url": "https://github.com/coveooss/exponential-backoff/issues" }, - "homepage": "https://github.com/coveo/exponential-backoff#readme", + "homepage": "https://github.com/coveooss/exponential-backoff#readme", "devDependencies": { "@types/jest": "^24.0.18", "@types/node": "^10.14.21", diff --git a/node_modules/foreground-child/LICENSE b/node_modules/foreground-child/LICENSE deleted file mode 100644 index 2d80720fe669c..0000000000000 --- a/node_modules/foreground-child/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/foreground-child/dist/commonjs/all-signals.js b/node_modules/foreground-child/dist/commonjs/all-signals.js deleted file mode 100644 index 1692af01e2878..0000000000000 --- a/node_modules/foreground-child/dist/commonjs/all-signals.js +++ /dev/null @@ -1,58 +0,0 @@ -"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 \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/index.js b/node_modules/foreground-child/dist/commonjs/index.js deleted file mode 100644 index 8ea5413b0935b..0000000000000 --- a/node_modules/foreground-child/dist/commonjs/index.js +++ /dev/null @@ -1,121 +0,0 @@ -"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); - (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); - 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 \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/proxy-signals.js b/node_modules/foreground-child/dist/commonjs/proxy-signals.js deleted file mode 100644 index 3913e7b45bce2..0000000000000 --- a/node_modules/foreground-child/dist/commonjs/proxy-signals.js +++ /dev/null @@ -1,38 +0,0 @@ -"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 \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/watchdog.js b/node_modules/foreground-child/dist/commonjs/watchdog.js deleted file mode 100644 index 514e234c2a0ed..0000000000000 --- a/node_modules/foreground-child/dist/commonjs/watchdog.js +++ /dev/null @@ -1,50 +0,0 @@ -"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.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/all-signals.js b/node_modules/foreground-child/dist/esm/all-signals.js deleted file mode 100644 index 7e8d54d5cbb2a..0000000000000 --- a/node_modules/foreground-child/dist/esm/all-signals.js +++ /dev/null @@ -1,52 +0,0 @@ -import 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.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/index.js b/node_modules/foreground-child/dist/esm/index.js deleted file mode 100644 index d42ba8f31ddd0..0000000000000 --- a/node_modules/foreground-child/dist/esm/index.js +++ /dev/null @@ -1,113 +0,0 @@ -import { 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); - 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); - 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 \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/proxy-signals.js b/node_modules/foreground-child/dist/esm/proxy-signals.js deleted file mode 100644 index 8e1efe3e301d6..0000000000000 --- a/node_modules/foreground-child/dist/esm/proxy-signals.js +++ /dev/null @@ -1,34 +0,0 @@ -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 \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/watchdog.js b/node_modules/foreground-child/dist/esm/watchdog.js deleted file mode 100644 index 7aa184ede4f5a..0000000000000 --- a/node_modules/foreground-child/dist/esm/watchdog.js +++ /dev/null @@ -1,46 +0,0 @@ -// 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 \ No newline at end of file diff --git a/node_modules/foreground-child/package.json b/node_modules/foreground-child/package.json deleted file mode 100644 index e157528477c6f..0000000000000 --- a/node_modules/foreground-child/package.json +++ /dev/null @@ -1,111 +0,0 @@ -{ - "name": "foreground-child", - "version": "3.2.1", - "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" -} diff --git a/node_modules/glob/LICENSE b/node_modules/glob/LICENSE deleted file mode 100644 index ec7df93329abf..0000000000000 --- a/node_modules/glob/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/glob/LICENSE.md b/node_modules/glob/LICENSE.md new file mode 100644 index 0000000000000..881248b6d7f0c --- /dev/null +++ b/node_modules/glob/LICENSE.md @@ -0,0 +1,63 @@ +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.*** diff --git a/node_modules/glob/dist/commonjs/glob.js b/node_modules/glob/dist/commonjs/glob.js index e1339bbbcf57f..2dcbd8a1d867c 100644 --- a/node_modules/glob/dist/commonjs/glob.js +++ b/node_modules/glob/dist/commonjs/glob.js @@ -140,11 +140,12 @@ class Glob { // for the file `AbC` for example. const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32'; const mmo = { - // default nocase based on platform + braceExpandMax: 10_000, ...opts, dot: this.dot, matchBase: this.matchBase, nobrace: this.nobrace, + // default nocase based on platform nocase: this.nocase, nocaseMagicOnly, nocomment: true, diff --git a/node_modules/glob/dist/commonjs/index.js b/node_modules/glob/dist/commonjs/index.js index 31da9dfd53c6a..151495d170efa 100644 --- a/node_modules/glob/dist/commonjs/index.js +++ b/node_modules/glob/dist/commonjs/index.js @@ -1,6 +1,11 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.glob = exports.sync = exports.iterate = exports.iterateSync = exports.stream = exports.streamSync = exports.globIterate = exports.globIterateSync = exports.globSync = exports.globStream = exports.globStreamSync = exports.Ignore = exports.hasMagic = exports.Glob = exports.unescape = exports.escape = void 0; +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"); @@ -16,26 +21,21 @@ Object.defineProperty(exports, "Ignore", { enumerable: true, get: function () { function globStreamSync(pattern, options = {}) { return new glob_js_1.Glob(pattern, options).streamSync(); } -exports.globStreamSync = globStreamSync; function globStream(pattern, options = {}) { return new glob_js_1.Glob(pattern, options).stream(); } -exports.globStream = globStream; function globSync(pattern, options = {}) { return new glob_js_1.Glob(pattern, options).walkSync(); } -exports.globSync = globSync; 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(); } -exports.globIterateSync = globIterateSync; function globIterate(pattern, options = {}) { return new glob_js_1.Glob(pattern, options).iterate(); } -exports.globIterate = globIterate; // aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc exports.streamSync = globStreamSync; exports.stream = Object.assign(globStream, { sync: globStreamSync }); diff --git a/node_modules/glob/dist/commonjs/index.min.js b/node_modules/glob/dist/commonjs/index.min.js new file mode 100644 index 0000000000000..4828ba07860bd --- /dev/null +++ b/node_modules/glob/dist/commonjs/index.min.js @@ -0,0 +1,4 @@ +"use strict";var R=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var Ge=R(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.range=Y.balanced=void 0;var Gs=(n,t,e)=>{let s=n instanceof RegExp?Ie(n,e):n,i=t instanceof RegExp?Ie(t,e):t,r=s!==null&&i!=null&&(0,Y.range)(s,i,e);return r&&{start:r[0],end:r[1],pre:e.slice(0,r[0]),body:e.slice(r[0]+s.length,r[1]),post:e.slice(r[1]+i.length)}};Y.balanced=Gs;var Ie=(n,t)=>{let e=t.match(n);return e?e[0]:null},zs=(n,t,e)=>{let s,i,r,h,o,a=e.indexOf(n),l=e.indexOf(t,a+1),f=a;if(a>=0&&l>0){if(n===t)return[a,l];for(s=[],r=e.length;f>=0&&!o;){if(f===a)s.push(f),a=e.indexOf(n,f+1);else if(s.length===1){let c=s.pop();c!==void 0&&(o=[c,l])}else i=s.pop(),i!==void 0&&i=0?a:l}s.length&&h!==void 0&&(o=[r,h])}return o};Y.range=zs});var Ke=R(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.EXPANSION_MAX=void 0;it.expand=ei;var ze=Ge(),Ue="\0SLASH"+Math.random()+"\0",$e="\0OPEN"+Math.random()+"\0",ue="\0CLOSE"+Math.random()+"\0",qe="\0COMMA"+Math.random()+"\0",He="\0PERIOD"+Math.random()+"\0",Us=new RegExp(Ue,"g"),$s=new RegExp($e,"g"),qs=new RegExp(ue,"g"),Hs=new RegExp(qe,"g"),Vs=new RegExp(He,"g"),Ks=/\\\\/g,Xs=/\\{/g,Ys=/\\}/g,Js=/\\,/g,Zs=/\\./g;it.EXPANSION_MAX=1e5;function ce(n){return isNaN(n)?n.charCodeAt(0):parseInt(n,10)}function Qs(n){return n.replace(Ks,Ue).replace(Xs,$e).replace(Ys,ue).replace(Js,qe).replace(Zs,He)}function ti(n){return n.replace(Us,"\\").replace($s,"{").replace(qs,"}").replace(Hs,",").replace(Vs,".")}function Ve(n){if(!n)return[""];let t=[],e=(0,ze.balanced)("{","}",n);if(!e)return n.split(",");let{pre:s,body:i,post:r}=e,h=s.split(",");h[h.length-1]+="{"+i+"}";let o=Ve(r);return r.length&&(h[h.length-1]+=o.shift(),h.push.apply(h,o)),t.push.apply(t,h),t}function ei(n,t={}){if(!n)return[];let{max:e=it.EXPANSION_MAX}=t;return n.slice(0,2)==="{}"&&(n="\\{\\}"+n.slice(2)),ht(Qs(n),e,!0).map(ti)}function si(n){return"{"+n+"}"}function ii(n){return/^-?0\d/.test(n)}function ri(n,t){return n<=t}function ni(n,t){return n>=t}function ht(n,t,e){let s=[],i=(0,ze.balanced)("{","}",n);if(!i)return[n];let r=i.pre,h=i.post.length?ht(i.post,t,!1):[""];if(/\$$/.test(i.pre))for(let o=0;o=0;if(!l&&!f)return i.post.match(/,(?!,).*\}/)?(n=i.pre+"{"+i.body+ue+i.post,ht(n,t,!0)):[n];let c;if(l)c=i.body.split(/\.\./);else if(c=Ve(i.body),c.length===1&&c[0]!==void 0&&(c=ht(c[0],t,!1).map(si),c.length===1))return h.map(u=>i.pre+c[0]+u);let d;if(l&&c[0]!==void 0&&c[1]!==void 0){let u=ce(c[0]),m=ce(c[1]),p=Math.max(c[0].length,c[1].length),b=c.length===3&&c[2]!==void 0?Math.abs(ce(c[2])):1,w=ri;m0){let U=new Array(B+1).join("0");y<0?S="-"+U+S.slice(1):S=U+S}}d.push(S)}}else{d=[];for(let u=0;u{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.assertValidPattern=void 0;var hi=1024*64,oi=n=>{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>hi)throw new TypeError("pattern is too long")};Ct.assertValidPattern=oi});var Je=R(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.parseClass=void 0;var ai={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},ot=n=>n.replace(/[[\]\\-]/g,"\\$&"),li=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ye=n=>n.join(""),ci=(n,t)=>{let e=t;if(n.charAt(e)!=="[")throw new Error("not in a brace expression");let s=[],i=[],r=e+1,h=!1,o=!1,a=!1,l=!1,f=e,c="";t:for(;rc?s.push(ot(c)+"-"+ot(p)):p===c&&s.push(ot(p)),c="",r++;continue}if(n.startsWith("-]",r+1)){s.push(ot(p+"-")),r+=2;continue}if(n.startsWith("-",r+1)){c=p,r+=2;continue}s.push(ot(p)),r++}if(f{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.unescape=void 0;var ui=(n,{windowsPathsNoEscape:t=!1,magicalBraces:e=!0}={})=>e?t?n.replace(/\[([^\/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?n.replace(/\[([^\/\\{}])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1");At.unescape=ui});var pe=R(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.AST=void 0;var fi=Je(),Mt=kt(),di=new Set(["!","?","+","*","@"]),Ze=n=>di.has(n),pi="(?!(?:^|/)\\.\\.?(?:$|/))",Pt="(?!\\.)",mi=new Set(["[","."]),gi=new Set(["..","."]),wi=new Set("().*{}+?[]^$\\!"),bi=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),de="[^/]",Qe=de+"*?",ts=de+"+?",fe=class n{type;#t;#s;#n=!1;#r=[];#h;#S;#w;#c=!1;#o;#f;#u=!1;constructor(t,e,s={}){this.type=t,t&&(this.#s=!0),this.#h=e,this.#t=this.#h?this.#h.#t:this,this.#o=this.#t===this?s:this.#t.#o,this.#w=this.#t===this?[]:this.#t.#w,t==="!"&&!this.#t.#c&&this.#w.push(this),this.#S=this.#h?this.#h.#r.length:0}get hasMagic(){if(this.#s!==void 0)return this.#s;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#s=!0;return this.#s}toString(){return this.#f!==void 0?this.#f:this.type?this.#f=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#f=this.#r.map(t=>String(t)).join("")}#a(){if(this!==this.#t)throw new Error("should only call on root");if(this.#c)return this;this.toString(),this.#c=!0;let t;for(;t=this.#w.pop();){if(t.type!=="!")continue;let e=t,s=e.#h;for(;s;){for(let i=e.#S+1;!s.type&&itypeof e=="string"?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#c&&this.#h?.type==="!")&&t.push({}),t}isStart(){if(this.#t===this)return!0;if(!this.#h?.isStart())return!1;if(this.#S===0)return!0;let t=this.#h;for(let e=0;etypeof u!="string"),l=this.#r.map(u=>{let[m,p,b,w]=typeof u=="string"?n.#v(u,this.#s,a):u.toRegExpSource(t);return this.#s=this.#s||b,this.#n=this.#n||w,m}).join(""),f="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&gi.has(this.#r[0]))){let m=mi,p=e&&m.has(l.charAt(0))||l.startsWith("\\.")&&m.has(l.charAt(2))||l.startsWith("\\.\\.")&&m.has(l.charAt(4)),b=!e&&!t&&m.has(l.charAt(0));f=p?pi:b?Pt:""}let c="";return this.isEnd()&&this.#t.#c&&this.#h?.type==="!"&&(c="(?:$|\\/)"),[f+l+c,(0,Mt.unescape)(l),this.#s=!!this.#s,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",r=this.#d(e);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){let a=this.toString();return this.#r=[a],this.type=null,this.#s=void 0,[a,(0,Mt.unescape)(this.toString()),!1,!1]}let h=!s||t||e||!Pt?"":this.#d(!0);h===r&&(h=""),h&&(r=`(?:${r})(?:${h})*?`);let o="";if(this.type==="!"&&this.#u)o=(this.isStart()&&!e?Pt:"")+ts;else{let a=this.type==="!"?"))"+(this.isStart()&&!e&&!t?Pt:"")+Qe+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&h?")":this.type==="*"&&h?")?":`)${this.type}`;o=i+r+a}return[o,(0,Mt.unescape)(r),this.#s=!!this.#s,this.#n]}#d(t){return this.#r.map(e=>{if(typeof e=="string")throw new Error("string type in extglob ast??");let[s,i,r,h]=e.toRegExpSource(t);return this.#n=this.#n||h,s}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")}static#v(t,e,s=!1){let i=!1,r="",h=!1,o=!1;for(let a=0;a{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.escape=void 0;var yi=(n,{windowsPathsNoEscape:t=!1,magicalBraces:e=!1}={})=>e?t?n.replace(/[?*()[\]{}]/g,"[$&]"):n.replace(/[?*()[\]\\{}]/g,"\\$&"):t?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");Ft.escape=yi});var H=R(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.unescape=g.escape=g.AST=g.Minimatch=g.match=g.makeRe=g.braceExpand=g.defaults=g.filter=g.GLOBSTAR=g.sep=g.minimatch=void 0;var Si=Ke(),jt=Xe(),is=pe(),vi=me(),Ei=kt(),_i=(n,t,e={})=>((0,jt.assertValidPattern)(t),!e.nocomment&&t.charAt(0)==="#"?!1:new J(t,e).match(n));g.minimatch=_i;var Oi=/^\*+([^+@!?\*\[\(]*)$/,xi=n=>t=>!t.startsWith(".")&&t.endsWith(n),Ti=n=>t=>t.endsWith(n),Ci=n=>(n=n.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(n)),Ri=n=>(n=n.toLowerCase(),t=>t.toLowerCase().endsWith(n)),Ai=/^\*+\.\*+$/,ki=n=>!n.startsWith(".")&&n.includes("."),Mi=n=>n!=="."&&n!==".."&&n.includes("."),Pi=/^\.\*+$/,Di=n=>n!=="."&&n!==".."&&n.startsWith("."),Fi=/^\*+$/,ji=n=>n.length!==0&&!n.startsWith("."),Ni=n=>n.length!==0&&n!=="."&&n!=="..",Li=/^\?+([^+@!?\*\[\(]*)?$/,Wi=([n,t=""])=>{let e=rs([n]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Bi=([n,t=""])=>{let e=ns([n]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Ii=([n,t=""])=>{let e=ns([n]);return t?s=>e(s)&&s.endsWith(t):e},Gi=([n,t=""])=>{let e=rs([n]);return t?s=>e(s)&&s.endsWith(t):e},rs=([n])=>{let t=n.length;return e=>e.length===t&&!e.startsWith(".")},ns=([n])=>{let t=n.length;return e=>e.length===t&&e!=="."&&e!==".."},hs=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",es={win32:{sep:"\\"},posix:{sep:"/"}};g.sep=hs==="win32"?es.win32.sep:es.posix.sep;g.minimatch.sep=g.sep;g.GLOBSTAR=Symbol("globstar **");g.minimatch.GLOBSTAR=g.GLOBSTAR;var zi="[^/]",Ui=zi+"*?",$i="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",qi="(?:(?!(?:\\/|^)\\.).)*?",Hi=(n,t={})=>e=>(0,g.minimatch)(e,n,t);g.filter=Hi;g.minimatch.filter=g.filter;var F=(n,t={})=>Object.assign({},n,t),Vi=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return g.minimatch;let t=g.minimatch;return Object.assign((s,i,r={})=>t(s,i,F(n,r)),{Minimatch:class extends t.Minimatch{constructor(i,r={}){super(i,F(n,r))}static defaults(i){return t.defaults(F(n,i)).Minimatch}},AST:class extends t.AST{constructor(i,r,h={}){super(i,r,F(n,h))}static fromGlob(i,r={}){return t.AST.fromGlob(i,F(n,r))}},unescape:(s,i={})=>t.unescape(s,F(n,i)),escape:(s,i={})=>t.escape(s,F(n,i)),filter:(s,i={})=>t.filter(s,F(n,i)),defaults:s=>t.defaults(F(n,s)),makeRe:(s,i={})=>t.makeRe(s,F(n,i)),braceExpand:(s,i={})=>t.braceExpand(s,F(n,i)),match:(s,i,r={})=>t.match(s,i,F(n,r)),sep:t.sep,GLOBSTAR:g.GLOBSTAR})};g.defaults=Vi;g.minimatch.defaults=g.defaults;var Ki=(n,t={})=>((0,jt.assertValidPattern)(n),t.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:(0,Si.expand)(n,{max:t.braceExpandMax}));g.braceExpand=Ki;g.minimatch.braceExpand=g.braceExpand;var Xi=(n,t={})=>new J(n,t).makeRe();g.makeRe=Xi;g.minimatch.makeRe=g.makeRe;var Yi=(n,t,e={})=>{let s=new J(t,e);return n=n.filter(i=>s.match(i)),s.options.nonull&&!n.length&&n.push(t),n};g.match=Yi;g.minimatch.match=g.match;var ss=/[?*]|[+@!]\(.*?\)|\[|\]/,Ji=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),J=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){(0,jt.assertValidPattern)(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||hs,this.isWindows=this.platform==="win32";let s="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[s]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let s=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let i=this.globParts.map((r,h,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=r[0]===""&&r[1]===""&&(r[2]==="?"||!ss.test(r[2]))&&!ss.test(r[3]),l=/^[a-z]:/i.test(r[0]);if(a)return[...r.slice(0,4),...r.slice(4).map(f=>this.parse(f))];if(l)return[r[0],...r.slice(1).map(f=>this.parse(f))]}return r.map(a=>this.parse(a))});if(this.debug(this.pattern,i),this.set=i.filter(r=>r.indexOf(!1)===-1),this.isWindows)for(let r=0;r=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let s=-1;for(;(s=e.indexOf("**",s+1))!==-1;){let i=s;for(;e[i+1]==="**";)i++;i!==s&&e.splice(s,i-s)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((s,i)=>{let r=s[s.length-1];return i==="**"&&r==="**"?s:i===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(s.pop(),s):(s.push(i),s)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let i=1;ii&&s.splice(i+1,h-i);let o=s[i+1],a=s[i+2],l=s[i+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,s.splice(i,1);let f=s.slice(0);f[i]="**",t.push(f),i--}if(!this.preserveMultipleSlashes){for(let h=1;he.length)}partsMatch(t,e,s=!1){let i=0,r=0,h=[],o="";for(;iE?e=e.slice(y):E>y&&(t=t.slice(E)))}}let{optimizationLevel:r=1}=this.options;r>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var h=0,o=0,a=t.length,l=e.length;h>> no match, partial?`,t,d,e,u),d===a))}let p;if(typeof f=="string"?(p=c===f,this.debug("string match",f,c,p)):(p=f.test(c),this.debug("pattern match",f,c,p)),!p)return!1}if(h===a&&o===l)return!0;if(h===a)return s;if(o===l)return h===a-1&&t[h]==="";throw new Error("wtf?")}braceExpand(){return(0,g.braceExpand)(this.pattern,this.options)}parse(t){(0,jt.assertValidPattern)(t);let e=this.options;if(t==="**")return g.GLOBSTAR;if(t==="")return"";let s,i=null;(s=t.match(Fi))?i=e.dot?Ni:ji:(s=t.match(Oi))?i=(e.nocase?e.dot?Ri:Ci:e.dot?Ti:xi)(s[1]):(s=t.match(Li))?i=(e.nocase?e.dot?Bi:Wi:e.dot?Ii:Gi)(s):(s=t.match(Ai))?i=e.dot?Mi:ki:(s=t.match(Pi))&&(i=Di);let r=is.AST.fromGlob(t,this.options).toMMPattern();return i&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:i}),r}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,s=e.noglobstar?Ui:e.dot?$i:qi,i=new Set(e.nocase?["i"]:[]),r=t.map(a=>{let l=a.map(c=>{if(c instanceof RegExp)for(let d of c.flags.split(""))i.add(d);return typeof c=="string"?Ji(c):c===g.GLOBSTAR?g.GLOBSTAR:c._src});l.forEach((c,d)=>{let u=l[d+1],m=l[d-1];c!==g.GLOBSTAR||m===g.GLOBSTAR||(m===void 0?u!==void 0&&u!==g.GLOBSTAR?l[d+1]="(?:\\/|"+s+"\\/)?"+u:l[d]=s:u===void 0?l[d-1]=m+"(?:\\/|\\/"+s+")?":u!==g.GLOBSTAR&&(l[d-1]=m+"(?:\\/|\\/"+s+"\\/)"+u,l[d+1]=g.GLOBSTAR))});let f=l.filter(c=>c!==g.GLOBSTAR);if(this.partial&&f.length>=1){let c=[];for(let d=1;d<=f.length;d++)c.push(f.slice(0,d).join("/"));return"(?:"+c.join("|")+")"}return f.join("/")}).join("|"),[h,o]=t.length>1?["(?:",")"]:["",""];r="^"+h+r+o+"$",this.partial&&(r="^(?:\\/|"+h+r.slice(1,-1)+o+")$"),this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let s=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let r=this.set;this.debug(this.pattern,"set",r);let h=i[i.length-1];if(!h)for(let o=i.length-2;!h&&o>=0;o--)h=i[o];for(let o=0;o{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.LRUCache=void 0;var er=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,as=new Set,ge=typeof process=="object"&&process?process:{},ls=(n,t,e,s)=>{typeof ge.emitWarning=="function"?ge.emitWarning(n,t,e,s):console.error(`[${e}] ${t}: ${n}`)},Lt=globalThis.AbortController,os=globalThis.AbortSignal;if(typeof Lt>"u"){os=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,s){this._onabort.push(s)}},Lt=class{constructor(){t()}signal=new os;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let s of this.signal._onabort)s(e);this.signal.onabort?.(e)}}};let n=ge.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{n&&(n=!1,ls("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 sr=n=>!as.has(n),V=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),cs=n=>V(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?Nt:null:null,Nt=class extends Array{constructor(n){super(n),this.fill(0)}},ir=class at{heap;length;static#t=!1;static create(t){let e=cs(t);if(!e)return[];at.#t=!0;let s=new at(t,e);return at.#t=!1,s}constructor(t,e){if(!at.#t)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]}},rr=class us{#t;#s;#n;#r;#h;#S;#w;#c;get perf(){return this.#c}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#f;#u;#a;#i;#d;#v;#y;#p;#R;#m;#O;#x;#g;#b;#E;#T;#e;#F;static unsafeExposeInternals(t){return{starts:t.#x,ttls:t.#g,autopurgeTimers:t.#b,sizes:t.#O,keyMap:t.#u,keyList:t.#a,valList:t.#i,next:t.#d,prev:t.#v,get head(){return t.#y},get tail(){return t.#p},free:t.#R,isBackgroundFetch:e=>t.#l(e),backgroundFetch:(e,s,i,r)=>t.#z(e,s,i,r),moveToTail:e=>t.#N(e),indexes:e=>t.#k(e),rindexes:e=>t.#M(e),isStale:e=>t.#_(e)}}get max(){return this.#t}get maxSize(){return this.#s}get calculatedSize(){return this.#f}get size(){return this.#o}get fetchMethod(){return this.#S}get memoMethod(){return this.#w}get dispose(){return this.#n}get onInsert(){return this.#r}get disposeAfter(){return this.#h}constructor(t){let{max:e=0,ttl:s,ttlResolution:i=1,ttlAutopurge:r,updateAgeOnGet:h,updateAgeOnHas:o,allowStale:a,dispose:l,onInsert:f,disposeAfter:c,noDisposeOnSet:d,noUpdateTTL:u,maxSize:m=0,maxEntrySize:p=0,sizeCalculation:b,fetchMethod:w,memoMethod:v,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:S,allowStaleOnFetchAbort:B,ignoreFetchAbort:U,perf:et}=t;if(et!==void 0&&typeof et?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#c=et??er,e!==0&&!V(e))throw new TypeError("max option must be a nonnegative integer");let st=e?cs(e):Array;if(!st)throw new Error("invalid max value: "+e);if(this.#t=e,this.#s=m,this.maxEntrySize=p||this.#s,this.sizeCalculation=b,this.sizeCalculation){if(!this.#s&&!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(v!==void 0&&typeof v!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=v,w!==void 0&&typeof w!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#S=w,this.#T=!!w,this.#u=new Map,this.#a=new Array(e).fill(void 0),this.#i=new Array(e).fill(void 0),this.#d=new st(e),this.#v=new st(e),this.#y=0,this.#p=0,this.#R=ir.create(e),this.#o=0,this.#f=0,typeof l=="function"&&(this.#n=l),typeof f=="function"&&(this.#r=f),typeof c=="function"?(this.#h=c,this.#m=[]):(this.#h=void 0,this.#m=void 0),this.#E=!!this.#n,this.#F=!!this.#r,this.#e=!!this.#h,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!S,this.allowStaleOnFetchAbort=!!B,this.ignoreFetchAbort=!!U,this.maxEntrySize!==0){if(this.#s!==0&&!V(this.#s))throw new TypeError("maxSize must be a positive integer if specified");if(!V(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!h,this.updateAgeOnHas=!!o,this.ttlResolution=V(i)||i===0?i:1,this.ttlAutopurge=!!r,this.ttl=s||0,this.ttl){if(!V(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#t===0&&this.ttl===0&&this.#s===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#s){let le="LRU_CACHE_UNBOUNDED";sr(le)&&(as.add(le),ls("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",le,us))}}getRemainingTTL(t){return this.#u.has(t)?1/0:0}#P(){let t=new Nt(this.#t),e=new Nt(this.#t);this.#g=t,this.#x=e;let s=this.ttlAutopurge?new Array(this.#t):void 0;this.#b=s,this.#W=(h,o,a=this.#c.now())=>{if(e[h]=o!==0?a:0,t[h]=o,s?.[h]&&(clearTimeout(s[h]),s[h]=void 0),o!==0&&s){let l=setTimeout(()=>{this.#_(h)&&this.#A(this.#a[h],"expire")},o+1);l.unref&&l.unref(),s[h]=l}},this.#C=h=>{e[h]=t[h]!==0?this.#c.now():0},this.#D=(h,o)=>{if(t[o]){let a=t[o],l=e[o];if(!a||!l)return;h.ttl=a,h.start=l,h.now=i||r();let f=h.now-l;h.remainingTTL=a-f}};let i=0,r=()=>{let h=this.#c.now();if(this.ttlResolution>0){i=h;let o=setTimeout(()=>i=0,this.ttlResolution);o.unref&&o.unref()}return h};this.getRemainingTTL=h=>{let o=this.#u.get(h);if(o===void 0)return 0;let a=t[o],l=e[o];if(!a||!l)return 1/0;let f=(i||r())-l;return a-f},this.#_=h=>{let o=e[h],a=t[h];return!!a&&!!o&&(i||r())-o>a}}#C=()=>{};#D=()=>{};#W=()=>{};#_=()=>!1;#$(){let t=new Nt(this.#t);this.#f=0,this.#O=t,this.#L=e=>{this.#f-=t[e],t[e]=0},this.#B=(e,s,i,r)=>{if(this.#l(s))return 0;if(!V(i))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(i=r(s,e),!V(i))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 i},this.#j=(e,s,i)=>{if(t[e]=s,this.#s){let r=this.#s-t[e];for(;this.#f>r;)this.#G(!0)}this.#f+=t[e],i&&(i.entrySize=s,i.totalCalculatedSize=this.#f)}}#L=t=>{};#j=(t,e,s)=>{};#B=(t,e,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:t=this.allowStale}={}){if(this.#o)for(let e=this.#p;!(!this.#I(e)||((t||!this.#_(e))&&(yield e),e===this.#y));)e=this.#v[e]}*#M({allowStale:t=this.allowStale}={}){if(this.#o)for(let e=this.#y;!(!this.#I(e)||((t||!this.#_(e))&&(yield e),e===this.#p));)e=this.#d[e]}#I(t){return t!==void 0&&this.#u.get(this.#a[t])===t}*entries(){for(let t of this.#k())this.#i[t]!==void 0&&this.#a[t]!==void 0&&!this.#l(this.#i[t])&&(yield[this.#a[t],this.#i[t]])}*rentries(){for(let t of this.#M())this.#i[t]!==void 0&&this.#a[t]!==void 0&&!this.#l(this.#i[t])&&(yield[this.#a[t],this.#i[t]])}*keys(){for(let t of this.#k()){let e=this.#a[t];e!==void 0&&!this.#l(this.#i[t])&&(yield e)}}*rkeys(){for(let t of this.#M()){let e=this.#a[t];e!==void 0&&!this.#l(this.#i[t])&&(yield e)}}*values(){for(let t of this.#k())this.#i[t]!==void 0&&!this.#l(this.#i[t])&&(yield this.#i[t])}*rvalues(){for(let t of this.#M())this.#i[t]!==void 0&&!this.#l(this.#i[t])&&(yield this.#i[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let s of this.#k()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;if(r!==void 0&&t(r,this.#a[s],this))return this.get(this.#a[s],e)}}forEach(t,e=this){for(let s of this.#k()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;r!==void 0&&t.call(e,r,this.#a[s],this)}}rforEach(t,e=this){for(let s of this.#M()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;r!==void 0&&t.call(e,r,this.#a[s],this)}}purgeStale(){let t=!1;for(let e of this.#M({allowStale:!0}))this.#_(e)&&(this.#A(this.#a[e],"expire"),t=!0);return t}info(t){let e=this.#u.get(t);if(e===void 0)return;let s=this.#i[e],i=this.#l(s)?s.__staleWhileFetching:s;if(i===void 0)return;let r={value:i};if(this.#g&&this.#x){let h=this.#g[e],o=this.#x[e];if(h&&o){let a=h-(this.#c.now()-o);r.ttl=a,r.start=Date.now()}}return this.#O&&(r.size=this.#O[e]),r}dump(){let t=[];for(let e of this.#k({allowStale:!0})){let s=this.#a[e],i=this.#i[e],r=this.#l(i)?i.__staleWhileFetching:i;if(r===void 0||s===void 0)continue;let h={value:r};if(this.#g&&this.#x){h.ttl=this.#g[e];let o=this.#c.now()-this.#x[e];h.start=Math.floor(Date.now()-o)}this.#O&&(h.size=this.#O[e]),t.unshift([s,h])}return t}load(t){this.clear();for(let[e,s]of t){if(s.start){let i=Date.now()-s.start;s.start=this.#c.now()-i}this.set(e,s.value,s)}}set(t,e,s={}){if(e===void 0)return this.delete(t),this;let{ttl:i=this.ttl,start:r,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:a}=s,{noUpdateTTL:l=this.noUpdateTTL}=s,f=this.#B(t,e,s.size||0,o);if(this.maxEntrySize&&f>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#A(t,"set"),this;let c=this.#o===0?void 0:this.#u.get(t);if(c===void 0)c=this.#o===0?this.#p:this.#R.length!==0?this.#R.pop():this.#o===this.#t?this.#G(!1):this.#o,this.#a[c]=t,this.#i[c]=e,this.#u.set(t,c),this.#d[this.#p]=c,this.#v[c]=this.#p,this.#p=c,this.#o++,this.#j(c,f,a),a&&(a.set="add"),l=!1,this.#F&&this.#r?.(e,t,"add");else{this.#N(c);let d=this.#i[c];if(e!==d){if(this.#T&&this.#l(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:u}=d;u!==void 0&&!h&&(this.#E&&this.#n?.(u,t,"set"),this.#e&&this.#m?.push([u,t,"set"]))}else h||(this.#E&&this.#n?.(d,t,"set"),this.#e&&this.#m?.push([d,t,"set"]));if(this.#L(c),this.#j(c,f,a),this.#i[c]=e,a){a.set="replace";let u=d&&this.#l(d)?d.__staleWhileFetching:d;u!==void 0&&(a.oldValue=u)}}else a&&(a.set="update");this.#F&&this.onInsert?.(e,t,e===d?"update":"replace")}if(i!==0&&!this.#g&&this.#P(),this.#g&&(l||this.#W(c,i,r),a&&this.#D(a,c)),!h&&this.#e&&this.#m){let d=this.#m,u;for(;u=d?.shift();)this.#h?.(...u)}return this}pop(){try{for(;this.#o;){let t=this.#i[this.#y];if(this.#G(!0),this.#l(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#e&&this.#m){let t=this.#m,e;for(;e=t?.shift();)this.#h?.(...e)}}}#G(t){let e=this.#y,s=this.#a[e],i=this.#i[e];return this.#T&&this.#l(i)?i.__abortController.abort(new Error("evicted")):(this.#E||this.#e)&&(this.#E&&this.#n?.(i,s,"evict"),this.#e&&this.#m?.push([i,s,"evict"])),this.#L(e),this.#b?.[e]&&(clearTimeout(this.#b[e]),this.#b[e]=void 0),t&&(this.#a[e]=void 0,this.#i[e]=void 0,this.#R.push(e)),this.#o===1?(this.#y=this.#p=0,this.#R.length=0):this.#y=this.#d[e],this.#u.delete(s),this.#o--,e}has(t,e={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=e,r=this.#u.get(t);if(r!==void 0){let h=this.#i[r];if(this.#l(h)&&h.__staleWhileFetching===void 0)return!1;if(this.#_(r))i&&(i.has="stale",this.#D(i,r));else return s&&this.#C(r),i&&(i.has="hit",this.#D(i,r)),!0}else i&&(i.has="miss");return!1}peek(t,e={}){let{allowStale:s=this.allowStale}=e,i=this.#u.get(t);if(i===void 0||!s&&this.#_(i))return;let r=this.#i[i];return this.#l(r)?r.__staleWhileFetching:r}#z(t,e,s,i){let r=e===void 0?void 0:this.#i[e];if(this.#l(r))return r;let h=new Lt,{signal:o}=s;o?.addEventListener("abort",()=>h.abort(o.reason),{signal:h.signal});let a={signal:h.signal,options:s,context:i},l=(p,b=!1)=>{let{aborted:w}=h.signal,v=s.ignoreFetchAbort&&p!==void 0,E=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&p!==void 0);if(s.status&&(w&&!b?(s.status.fetchAborted=!0,s.status.fetchError=h.signal.reason,v&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),w&&!v&&!b)return c(h.signal.reason,E);let y=u,S=this.#i[e];return(S===u||v&&b&&S===void 0)&&(p===void 0?y.__staleWhileFetching!==void 0?this.#i[e]=y.__staleWhileFetching:this.#A(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(t,p,a.options))),p},f=p=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=p),c(p,!1)),c=(p,b)=>{let{aborted:w}=h.signal,v=w&&s.allowStaleOnFetchAbort,E=v||s.allowStaleOnFetchRejection,y=E||s.noDeleteOnFetchRejection,S=u;if(this.#i[e]===u&&(!y||!b&&S.__staleWhileFetching===void 0?this.#A(t,"fetch"):v||(this.#i[e]=S.__staleWhileFetching)),E)return s.status&&S.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),S.__staleWhileFetching;if(S.__returned===S)throw p},d=(p,b)=>{let w=this.#S?.(t,r,a);w&&w instanceof Promise&&w.then(v=>p(v===void 0?void 0:v),b),h.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(p(void 0),s.allowStaleOnFetchAbort&&(p=v=>l(v,!0)))})};s.status&&(s.status.fetchDispatched=!0);let u=new Promise(d).then(l,f),m=Object.assign(u,{__abortController:h,__staleWhileFetching:r,__returned:void 0});return e===void 0?(this.set(t,m,{...a.options,status:void 0}),e=this.#u.get(t)):this.#i[e]=m,m}#l(t){if(!this.#T)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof Lt}async fetch(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:h=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:f=this.noUpdateTTL,noDeleteOnFetchRejection:c=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:u=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:p,forceRefresh:b=!1,status:w,signal:v}=e;if(!this.#T)return w&&(w.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:r,status:w});let E={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:r,ttl:h,noDisposeOnSet:o,size:a,sizeCalculation:l,noUpdateTTL:f,noDeleteOnFetchRejection:c,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:m,ignoreFetchAbort:u,status:w,signal:v},y=this.#u.get(t);if(y===void 0){w&&(w.fetch="miss");let S=this.#z(t,y,E,p);return S.__returned=S}else{let S=this.#i[y];if(this.#l(S)){let st=s&&S.__staleWhileFetching!==void 0;return w&&(w.fetch="inflight",st&&(w.returnedStale=!0)),st?S.__staleWhileFetching:S.__returned=S}let B=this.#_(y);if(!b&&!B)return w&&(w.fetch="hit"),this.#N(y),i&&this.#C(y),w&&this.#D(w,y),S;let U=this.#z(t,y,E,p),et=U.__staleWhileFetching!==void 0&&s;return w&&(w.fetch=B?"stale":"refresh",et&&B&&(w.returnedStale=!0)),et?U.__staleWhileFetching:U.__returned=U}}async forceFetch(t,e={}){let s=await this.fetch(t,e);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,e={}){let s=this.#w;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:r,...h}=e,o=this.get(t,h);if(!r&&o!==void 0)return o;let a=s(t,o,{options:h,context:i});return this.set(t,a,h),a}get(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:h}=e,o=this.#u.get(t);if(o!==void 0){let a=this.#i[o],l=this.#l(a);return h&&this.#D(h,o),this.#_(o)?(h&&(h.get="stale"),l?(h&&s&&a.__staleWhileFetching!==void 0&&(h.returnedStale=!0),s?a.__staleWhileFetching:void 0):(r||this.#A(t,"expire"),h&&s&&(h.returnedStale=!0),s?a:void 0)):(h&&(h.get="hit"),l?a.__staleWhileFetching:(this.#N(o),i&&this.#C(o),a))}else h&&(h.get="miss")}#U(t,e){this.#v[e]=t,this.#d[t]=e}#N(t){t!==this.#p&&(t===this.#y?this.#y=this.#d[t]:this.#U(this.#v[t],this.#d[t]),this.#U(this.#p,t),this.#p=t)}delete(t){return this.#A(t,"delete")}#A(t,e){let s=!1;if(this.#o!==0){let i=this.#u.get(t);if(i!==void 0)if(this.#b?.[i]&&(clearTimeout(this.#b?.[i]),this.#b[i]=void 0),s=!0,this.#o===1)this.#q(e);else{this.#L(i);let r=this.#i[i];if(this.#l(r)?r.__abortController.abort(new Error("deleted")):(this.#E||this.#e)&&(this.#E&&this.#n?.(r,t,e),this.#e&&this.#m?.push([r,t,e])),this.#u.delete(t),this.#a[i]=void 0,this.#i[i]=void 0,i===this.#p)this.#p=this.#v[i];else if(i===this.#y)this.#y=this.#d[i];else{let h=this.#v[i];this.#d[h]=this.#d[i];let o=this.#d[i];this.#v[o]=this.#v[i]}this.#o--,this.#R.push(i)}}if(this.#e&&this.#m?.length){let i=this.#m,r;for(;r=i?.shift();)this.#h?.(...r)}return s}clear(){return this.#q("delete")}#q(t){for(let e of this.#M({allowStale:!0})){let s=this.#i[e];if(this.#l(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#a[e];this.#E&&this.#n?.(s,i,t),this.#e&&this.#m?.push([s,i,t])}}if(this.#u.clear(),this.#i.fill(void 0),this.#a.fill(void 0),this.#g&&this.#x){this.#g.fill(0),this.#x.fill(0);for(let e of this.#b??[])e!==void 0&&clearTimeout(e);this.#b?.fill(void 0)}if(this.#O&&this.#O.fill(0),this.#y=0,this.#p=0,this.#R.length=0,this.#f=0,this.#o=0,this.#e&&this.#m){let e=this.#m,s;for(;s=e?.shift();)this.#h?.(...s)}}};Wt.LRUCache=rr});var Oe=R(P=>{"use strict";var nr=P&&P.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(P,"__esModule",{value:!0});P.Minipass=P.isWritable=P.isReadable=P.isStream=void 0;var ds=typeof process=="object"&&process?process:{stdout:null,stderr:null},_e=require("node:events"),ws=nr(require("node:stream")),hr=require("node:string_decoder"),or=n=>!!n&&typeof n=="object"&&(n instanceof qt||n instanceof ws.default||(0,P.isReadable)(n)||(0,P.isWritable)(n));P.isStream=or;var ar=n=>!!n&&typeof n=="object"&&n instanceof _e.EventEmitter&&typeof n.pipe=="function"&&n.pipe!==ws.default.Writable.prototype.pipe;P.isReadable=ar;var lr=n=>!!n&&typeof n=="object"&&n instanceof _e.EventEmitter&&typeof n.write=="function"&&typeof n.end=="function";P.isWritable=lr;var $=Symbol("EOF"),q=Symbol("maybeEmitEnd"),K=Symbol("emittedEnd"),Bt=Symbol("emittingEnd"),lt=Symbol("emittedError"),It=Symbol("closed"),ps=Symbol("read"),Gt=Symbol("flush"),ms=Symbol("flushChunk"),L=Symbol("encoding"),rt=Symbol("decoder"),x=Symbol("flowing"),ct=Symbol("paused"),nt=Symbol("resume"),T=Symbol("buffer"),M=Symbol("pipes"),C=Symbol("bufferLength"),we=Symbol("bufferPush"),zt=Symbol("bufferShift"),k=Symbol("objectMode"),O=Symbol("destroyed"),be=Symbol("error"),ye=Symbol("emitData"),gs=Symbol("emitEnd"),Se=Symbol("emitEnd2"),I=Symbol("async"),ve=Symbol("abort"),Ut=Symbol("aborted"),ut=Symbol("signal"),Z=Symbol("dataListeners"),D=Symbol("discarded"),ft=n=>Promise.resolve().then(n),cr=n=>n(),ur=n=>n==="end"||n==="finish"||n==="prefinish",fr=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,dr=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),$t=class{src;dest;opts;ondrain;constructor(t,e,s){this.src=t,this.dest=e,this.opts=s,this.ondrain=()=>t[nt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Ee=class extends $t{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,s){super(t,e,s),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},pr=n=>!!n.objectMode,mr=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",qt=class extends _e.EventEmitter{[x]=!1;[ct]=!1;[M]=[];[T]=[];[k];[L];[I];[rt];[$]=!1;[K]=!1;[Bt]=!1;[It]=!1;[lt]=null;[C]=0;[O]=!1;[ut];[Ut]=!1;[Z]=0;[D]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");pr(e)?(this[k]=!0,this[L]=null):mr(e)?(this[L]=e.encoding,this[k]=!1):(this[k]=!1,this[L]=null),this[I]=!!e.async,this[rt]=this[L]?new hr.StringDecoder(this[L]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[T]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[M]});let{signal:s}=e;s&&(this[ut]=s,s.aborted?this[ve]():s.addEventListener("abort",()=>this[ve]()))}get bufferLength(){return this[C]}get encoding(){return this[L]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[k]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[I]}set async(t){this[I]=this[I]||!!t}[ve](){this[Ut]=!0,this.emit("abort",this[ut]?.reason),this.destroy(this[ut]?.reason)}get aborted(){return this[Ut]}set aborted(t){}write(t,e,s){if(this[Ut])return!1;if(this[$])throw new Error("write after end");if(this[O])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(s=e,e="utf8"),e||(e="utf8");let i=this[I]?ft:cr;if(!this[k]&&!Buffer.isBuffer(t)){if(dr(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(fr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[k]?(this[x]&&this[C]!==0&&this[Gt](!0),this[x]?this.emit("data",t):this[we](t),this[C]!==0&&this.emit("readable"),s&&i(s),this[x]):t.length?(typeof t=="string"&&!(e===this[L]&&!this[rt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[L]&&(t=this[rt].write(t)),this[x]&&this[C]!==0&&this[Gt](!0),this[x]?this.emit("data",t):this[we](t),this[C]!==0&&this.emit("readable"),s&&i(s),this[x]):(this[C]!==0&&this.emit("readable"),s&&i(s),this[x])}read(t){if(this[O])return null;if(this[D]=!1,this[C]===0||t===0||t&&t>this[C])return this[q](),null;this[k]&&(t=null),this[T].length>1&&!this[k]&&(this[T]=[this[L]?this[T].join(""):Buffer.concat(this[T],this[C])]);let e=this[ps](t||null,this[T][0]);return this[q](),e}[ps](t,e){if(this[k])this[zt]();else{let s=e;t===s.length||t===null?this[zt]():typeof s=="string"?(this[T][0]=s.slice(t),e=s.slice(0,t),this[C]-=t):(this[T][0]=s.subarray(t),e=s.subarray(0,t),this[C]-=t)}return this.emit("data",e),!this[T].length&&!this[$]&&this.emit("drain"),e}end(t,e,s){return typeof t=="function"&&(s=t,t=void 0),typeof e=="function"&&(s=e,e="utf8"),t!==void 0&&this.write(t,e),s&&this.once("end",s),this[$]=!0,this.writable=!1,(this[x]||!this[ct])&&this[q](),this}[nt](){this[O]||(!this[Z]&&!this[M].length&&(this[D]=!0),this[ct]=!1,this[x]=!0,this.emit("resume"),this[T].length?this[Gt]():this[$]?this[q]():this.emit("drain"))}resume(){return this[nt]()}pause(){this[x]=!1,this[ct]=!0,this[D]=!1}get destroyed(){return this[O]}get flowing(){return this[x]}get paused(){return this[ct]}[we](t){this[k]?this[C]+=1:this[C]+=t.length,this[T].push(t)}[zt](){return this[k]?this[C]-=1:this[C]-=this[T][0].length,this[T].shift()}[Gt](t=!1){do;while(this[ms](this[zt]())&&this[T].length);!t&&!this[T].length&&!this[$]&&this.emit("drain")}[ms](t){return this.emit("data",t),this[x]}pipe(t,e){if(this[O])return t;this[D]=!1;let s=this[K];return e=e||{},t===ds.stdout||t===ds.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[M].push(e.proxyErrors?new Ee(this,t,e):new $t(this,t,e)),this[I]?ft(()=>this[nt]()):this[nt]()),t}unpipe(t){let e=this[M].find(s=>s.dest===t);e&&(this[M].length===1?(this[x]&&this[Z]===0&&(this[x]=!1),this[M]=[]):this[M].splice(this[M].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let s=super.on(t,e);if(t==="data")this[D]=!1,this[Z]++,!this[M].length&&!this[x]&&this[nt]();else if(t==="readable"&&this[C]!==0)super.emit("readable");else if(ur(t)&&this[K])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[lt]){let i=e;this[I]?ft(()=>i.call(this,this[lt])):i.call(this,this[lt])}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[Z]=this.listeners("data").length,this[Z]===0&&!this[D]&&!this[M].length&&(this[x]=!1)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Z]=0,!this[D]&&!this[M].length&&(this[x]=!1)),e}get emittedEnd(){return this[K]}[q](){!this[Bt]&&!this[K]&&!this[O]&&this[T].length===0&&this[$]&&(this[Bt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[It]&&this.emit("close"),this[Bt]=!1)}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==O&&this[O])return!1;if(t==="data")return!this[k]&&!s?!1:this[I]?(ft(()=>this[ye](s)),!0):this[ye](s);if(t==="end")return this[gs]();if(t==="close"){if(this[It]=!0,!this[K]&&!this[O])return!1;let r=super.emit("close");return this.removeAllListeners("close"),r}else if(t==="error"){this[lt]=s,super.emit(be,s);let r=!this[ut]||this.listeners("error").length?super.emit("error",s):!1;return this[q](),r}else if(t==="resume"){let r=super.emit("resume");return this[q](),r}else if(t==="finish"||t==="prefinish"){let r=super.emit(t);return this.removeAllListeners(t),r}let i=super.emit(t,...e);return this[q](),i}[ye](t){for(let s of this[M])s.dest.write(t)===!1&&this.pause();let e=this[D]?!1:super.emit("data",t);return this[q](),e}[gs](){return this[K]?!1:(this[K]=!0,this.readable=!1,this[I]?(ft(()=>this[Se]()),!0):this[Se]())}[Se](){if(this[rt]){let e=this[rt].end();if(e){for(let s of this[M])s.dest.write(e);this[D]||super.emit("data",e)}}for(let e of this[M])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[k]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[k]||(t.dataLength+=s.length)}),await e,t}async concat(){if(this[k])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[L]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(O,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[D]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[$])return e();let r,h,o=c=>{this.off("data",a),this.off("end",l),this.off(O,f),e(),h(c)},a=c=>{this.off("error",o),this.off("end",l),this.off(O,f),this.pause(),r({value:c,done:!!this[$]})},l=()=>{this.off("error",o),this.off("data",a),this.off(O,f),e(),r({done:!0,value:void 0})},f=()=>o(new Error("stream destroyed"));return new Promise((c,d)=>{h=d,r=c,this.once(O,f),this.once("error",o),this.once("end",l),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[D]=!1;let t=!1,e=()=>(this.pause(),this.off(be,e),this.off(O,e),this.off("end",e),t=!0,{done:!0,value:void 0}),s=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(be,e),this.once(O,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[O])return t?this.emit("error",t):this.emit(O),this;this[O]=!0,this[D]=!0,this[T].length=0,this[C]=0;let e=this;return typeof e.close=="function"&&!this[It]&&e.close(),t?this.emit("error",t):this.emit(O),this}static get isStream(){return P.isStream}};P.Minipass=qt});var Ms=R(_=>{"use strict";var gr=_&&_.__createBinding||(Object.create?(function(n,t,e,s){s===void 0&&(s=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,s,i)}):(function(n,t,e,s){s===void 0&&(s=e),n[s]=t[e]})),wr=_&&_.__setModuleDefault||(Object.create?(function(n,t){Object.defineProperty(n,"default",{enumerable:!0,value:t})}):function(n,t){n.default=t}),br=_&&_.__importStar||function(n){if(n&&n.__esModule)return n;var t={};if(n!=null)for(var e in n)e!=="default"&&Object.prototype.hasOwnProperty.call(n,e)&&gr(t,n,e);return wr(t,n),t};Object.defineProperty(_,"__esModule",{value:!0});_.PathScurry=_.Path=_.PathScurryDarwin=_.PathScurryPosix=_.PathScurryWin32=_.PathScurryBase=_.PathPosix=_.PathWin32=_.PathBase=_.ChildrenCache=_.ResolveCache=void 0;var Qt=fs(),Yt=require("node:path"),yr=require("node:url"),pt=require("fs"),Sr=br(require("node:fs")),vr=pt.realpathSync.native,Ht=require("node:fs/promises"),bs=Oe(),mt={lstatSync:pt.lstatSync,readdir:pt.readdir,readdirSync:pt.readdirSync,readlinkSync:pt.readlinkSync,realpathSync:vr,promises:{lstat:Ht.lstat,readdir:Ht.readdir,readlink:Ht.readlink,realpath:Ht.realpath}},_s=n=>!n||n===mt||n===Sr?mt:{...mt,...n,promises:{...mt.promises,...n.promises||{}}},Os=/^\\\\\?\\([a-z]:)\\?$/i,Er=n=>n.replace(/\//g,"\\").replace(Os,"$1\\"),_r=/[\\\/]/,N=0,xs=1,Ts=2,G=4,Cs=6,Rs=8,Q=10,As=12,j=15,dt=~j,xe=16,ys=32,gt=64,W=128,Vt=256,Xt=512,Ss=gt|W|Xt,Or=1023,Te=n=>n.isFile()?Rs:n.isDirectory()?G:n.isSymbolicLink()?Q:n.isCharacterDevice()?Ts:n.isBlockDevice()?Cs:n.isSocket()?As:n.isFIFO()?xs:N,vs=new Qt.LRUCache({max:2**12}),wt=n=>{let t=vs.get(n);if(t)return t;let e=n.normalize("NFKD");return vs.set(n,e),e},Es=new Qt.LRUCache({max:2**12}),Kt=n=>{let t=Es.get(n);if(t)return t;let e=wt(n.toLowerCase());return Es.set(n,e),e},bt=class extends Qt.LRUCache{constructor(){super({max:256})}};_.ResolveCache=bt;var Jt=class extends Qt.LRUCache{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}};_.ChildrenCache=Jt;var ks=Symbol("PathScurry setAsCwd"),A=class{name;root;roots;parent;nocase;isCWD=!1;#t;#s;get dev(){return this.#s}#n;get mode(){return this.#n}#r;get nlink(){return this.#r}#h;get uid(){return this.#h}#S;get gid(){return this.#S}#w;get rdev(){return this.#w}#c;get blksize(){return this.#c}#o;get ino(){return this.#o}#f;get size(){return this.#f}#u;get blocks(){return this.#u}#a;get atimeMs(){return this.#a}#i;get mtimeMs(){return this.#i}#d;get ctimeMs(){return this.#d}#v;get birthtimeMs(){return this.#v}#y;get atime(){return this.#y}#p;get mtime(){return this.#p}#R;get ctime(){return this.#R}#m;get birthtime(){return this.#m}#O;#x;#g;#b;#E;#T;#e;#F;#P;#C;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=N,s,i,r,h,o){this.name=t,this.#O=r?Kt(t):wt(t),this.#e=e&Or,this.nocase=r,this.roots=i,this.root=s||this,this.#F=h,this.#g=o.fullpath,this.#E=o.relative,this.#T=o.relativePosix,this.parent=o.parent,this.parent?this.#t=this.parent.#t:this.#t=_s(o.fs)}depth(){return this.#x!==void 0?this.#x:this.parent?this.#x=this.parent.depth()+1:this.#x=0}childrenCache(){return this.#F}resolve(t){if(!t)return this;let e=this.getRootString(t),i=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#D(i):this.#D(i)}#D(t){let e=this;for(let s of t)e=e.child(s);return e}children(){let t=this.#F.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#F.set(this,e),this.#e&=~xe,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let s=this.children(),i=this.nocase?Kt(t):wt(t);for(let a of s)if(a.#O===i)return a;let r=this.parent?this.sep:"",h=this.#g?this.#g+r+t:void 0,o=this.newChild(t,N,{...e,parent:this,fullpath:h});return this.canReaddir()||(o.#e|=W),s.push(o),o}relative(){if(this.isCWD)return"";if(this.#E!==void 0)return this.#E;let t=this.name,e=this.parent;if(!e)return this.#E=this.name;let s=e.relative();return s+(!s||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#T!==void 0)return this.#T;let t=this.name,e=this.parent;if(!e)return this.#T=this.fullpathPosix();let s=e.relativePosix();return s+(!s||!e.parent?"":"/")+t}fullpath(){if(this.#g!==void 0)return this.#g;let t=this.name,e=this.parent;if(!e)return this.#g=this.name;let i=e.fullpath()+(e.parent?this.sep:"")+t;return this.#g=i}fullpathPosix(){if(this.#b!==void 0)return this.#b;if(this.sep==="/")return this.#b=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#b=`//?/${i}`:this.#b=i}let t=this.parent,e=t.fullpathPosix(),s=e+(!e||!t.parent?"":"/")+this.name;return this.#b=s}isUnknown(){return(this.#e&j)===N}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#e&j)===Rs}isDirectory(){return(this.#e&j)===G}isCharacterDevice(){return(this.#e&j)===Ts}isBlockDevice(){return(this.#e&j)===Cs}isFIFO(){return(this.#e&j)===xs}isSocket(){return(this.#e&j)===As}isSymbolicLink(){return(this.#e&Q)===Q}lstatCached(){return this.#e&ys?this:void 0}readlinkCached(){return this.#P}realpathCached(){return this.#C}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#P)return!0;if(!this.parent)return!1;let t=this.#e&j;return!(t!==N&&t!==Q||this.#e&Vt||this.#e&W)}calledReaddir(){return!!(this.#e&xe)}isENOENT(){return!!(this.#e&W)}isNamed(t){return this.nocase?this.#O===Kt(t):this.#O===wt(t)}async readlink(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#t.promises.readlink(this.fullpath()),s=(await this.parent.realpath())?.resolve(e);if(s)return this.#P=s}catch(e){this.#M(e.code);return}}readlinkSync(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#t.readlinkSync(this.fullpath()),s=this.parent.realpathSync()?.resolve(e);if(s)return this.#P=s}catch(e){this.#M(e.code);return}}#W(t){this.#e|=xe;for(let e=t.provisional;es(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let s=this.children();if(this.calledReaddir()){let r=s.slice(0,s.provisional);e?t(null,r):queueMicrotask(()=>t(null,r));return}if(this.#N.push(t),this.#A)return;this.#A=!0;let i=this.fullpath();this.#t.readdir(i,{withFileTypes:!0},(r,h)=>{if(r)this.#B(r.code),s.provisional=0;else{for(let o of h)this.#I(o,s);this.#W(s)}this.#q(s.slice(0,s.provisional))})}#H;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#H)await this.#H;else{let s=()=>{};this.#H=new Promise(i=>s=i);try{for(let i of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#I(i,t);this.#W(t)}catch(i){this.#B(i.code),t.provisional=0}this.#H=void 0,s()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let s of this.#t.readdirSync(e,{withFileTypes:!0}))this.#I(s,t);this.#W(t)}catch(s){this.#B(s.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#e&Ss)return!1;let t=j&this.#e;return t===N||t===G||t===Q}shouldWalk(t,e){return(this.#e&G)===G&&!(this.#e&Ss)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#C)return this.#C;if(!((Xt|Vt|W)&this.#e))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#C=this.resolve(t)}catch{this.#L()}}realpathSync(){if(this.#C)return this.#C;if(!((Xt|Vt|W)&this.#e))try{let t=this.#t.realpathSync(this.fullpath());return this.#C=this.resolve(t)}catch{this.#L()}}[ks](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),s=[],i=this;for(;i&&i.parent;)e.add(i),i.#E=s.join(this.sep),i.#T=s.join("/"),i=i.parent,s.push("..");for(i=t;i&&i.parent&&!e.has(i);)i.#E=void 0,i.#T=void 0,i=i.parent}};_.PathBase=A;var yt=class n extends A{sep="\\";splitSep=_r;constructor(t,e=N,s,i,r,h,o){super(t,e,s,i,r,h,o)}newChild(t,e=N,s={}){return new n(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return Yt.win32.parse(t).root}getRoot(t){if(t=Er(t.toUpperCase()),t===this.root.name)return this.root;for(let[e,s]of Object.entries(this.roots))if(this.sameRoot(t,e))return this.roots[t]=s;return this.roots[t]=new Et(t,this).root}sameRoot(t,e=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(Os,"$1\\"),t===e}};_.PathWin32=yt;var St=class n extends A{splitSep="/";sep="/";constructor(t,e=N,s,i,r,h,o){super(t,e,s,i,r,h,o)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,e=N,s={}){return new n(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}};_.PathPosix=St;var vt=class{root;rootPath;roots;cwd;#t;#s;#n;nocase;#r;constructor(t=process.cwd(),e,s,{nocase:i,childrenCacheSize:r=16*1024,fs:h=mt}={}){this.#r=_s(h),(t instanceof URL||t.startsWith("file://"))&&(t=(0,yr.fileURLToPath)(t));let o=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#t=new bt,this.#s=new bt,this.#n=new Jt(r);let a=o.substring(this.rootPath.length).split(s);if(a.length===1&&!a[0]&&a.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let l=this.root,f=a.length-1,c=e.sep,d=this.rootPath,u=!1;for(let m of a){let p=f--;l=l.child(m,{relative:new Array(p).fill("..").join(c),relativePosix:new Array(p).fill("..").join("/"),fullpath:d+=(u?"":c)+m}),u=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let r=t.length-1;r>=0;r--){let h=t[r];if(!(!h||h===".")&&(e=e?`${h}/${e}`:h,this.isAbsolute(h)))break}let s=this.#t.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpath();return this.#t.set(e,i),i}resolvePosix(...t){let e="";for(let r=t.length-1;r>=0;r--){let h=t[r];if(!(!h||h===".")&&(e=e?`${h}/${e}`:h,this.isAbsolute(h)))break}let s=this.#s.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpathPosix();return this.#s.set(e,i),i}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s}=e;if(t.canReaddir()){let i=await t.readdir();return s?i:i.map(r=>r.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0}=e;return t.canReaddir()?s?t.readdirSync():t.readdirSync().map(i=>i.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=await t.readlink();return e?s:s?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=t.readlinkSync();return e?s:s?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=await t.realpath();return e?s:s?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=t.realpathSync();return e?s:s?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=[];(!r||r(t))&&o.push(s?t:t.fullpath());let a=new Set,l=(c,d)=>{a.add(c),c.readdirCB((u,m)=>{if(u)return d(u);let p=m.length;if(!p)return d();let b=()=>{--p===0&&d()};for(let w of m)(!r||r(w))&&o.push(s?w:w.fullpath()),i&&w.isSymbolicLink()?w.realpath().then(v=>v?.isUnknown()?v.lstat():v).then(v=>v?.shouldWalk(a,h)?l(v,b):b()):w.shouldWalk(a,h)?l(w,b):b()},!0)},f=t;return new Promise((c,d)=>{l(f,u=>{if(u)return d(u);c(o)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=[];(!r||r(t))&&o.push(s?t:t.fullpath());let a=new Set([t]);for(let l of a){let f=l.readdirSync();for(let c of f){(!r||r(c))&&o.push(s?c:c.fullpath());let d=c;if(c.isSymbolicLink()){if(!(i&&(d=c.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(a,h)&&a.add(d)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e;(!r||r(t))&&(yield s?t:t.fullpath());let o=new Set([t]);for(let a of o){let l=a.readdirSync();for(let f of l){(!r||r(f))&&(yield s?f:f.fullpath());let c=f;if(f.isSymbolicLink()){if(!(i&&(c=f.realpathSync())))continue;c.isUnknown()&&c.lstatSync()}c.shouldWalk(o,h)&&o.add(c)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=new bs.Minipass({objectMode:!0});(!r||r(t))&&o.write(s?t:t.fullpath());let a=new Set,l=[t],f=0,c=()=>{let d=!1;for(;!d;){let u=l.shift();if(!u){f===0&&o.end();return}f++,a.add(u);let m=(b,w,v=!1)=>{if(b)return o.emit("error",b);if(i&&!v){let E=[];for(let y of w)y.isSymbolicLink()&&E.push(y.realpath().then(S=>S?.isUnknown()?S.lstat():S));if(E.length){Promise.all(E).then(()=>m(null,w,!0));return}}for(let E of w)E&&(!r||r(E))&&(o.write(s?E:E.fullpath())||(d=!0));f--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,h)&&l.push(y)}d&&!o.flowing?o.once("drain",c):p||c()},p=!0;u.readdirCB(m,!0),p=!1}};return c(),o}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=new bs.Minipass({objectMode:!0}),a=new Set;(!r||r(t))&&o.write(s?t:t.fullpath());let l=[t],f=0,c=()=>{let d=!1;for(;!d;){let u=l.shift();if(!u){f===0&&o.end();return}f++,a.add(u);let m=u.readdirSync();for(let p of m)(!r||r(p))&&(o.write(s?p:p.fullpath())||(d=!0));f--;for(let p of m){let b=p;if(p.isSymbolicLink()){if(!(i&&(b=p.realpathSync())))continue;b.isUnknown()&&b.lstatSync()}b.shouldWalk(a,h)&&l.push(b)}}d&&!o.flowing&&o.once("drain",c)};return c(),o}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[ks](e)}};_.PathScurryBase=vt;var Et=class extends vt{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,Yt.win32,"\\",{...e,nocase:s}),this.nocase=s;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(t){return Yt.win32.parse(t).root.toUpperCase()}newRoot(t){return new yt(this.rootPath,G,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}};_.PathScurryWin32=Et;var _t=class extends vt{sep="/";constructor(t=process.cwd(),e={}){let{nocase:s=!1}=e;super(t,Yt.posix,"/",{...e,nocase:s}),this.nocase=s}parseRootPath(t){return"/"}newRoot(t){return new St(this.rootPath,G,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}};_.PathScurryPosix=_t;var Zt=class extends _t{constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,{...e,nocase:s})}};_.PathScurryDarwin=Zt;_.Path=process.platform==="win32"?yt:St;_.PathScurry=process.platform==="win32"?Et:process.platform==="darwin"?Zt:_t});var Re=R(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.Pattern=void 0;var xr=H(),Tr=n=>n.length>=1,Cr=n=>n.length>=1,Rr=Symbol.for("nodejs.util.inspect.custom"),Ce=class n{#t;#s;#n;length;#r;#h;#S;#w;#c;#o;#f=!0;constructor(t,e,s,i){if(!Tr(t))throw new TypeError("empty pattern list");if(!Cr(e))throw new TypeError("empty glob list");if(e.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#s=e,this.#n=s,this.#r=i,this.#n===0){if(this.isUNC()){let[r,h,o,a,...l]=this.#t,[f,c,d,u,...m]=this.#s;l[0]===""&&(l.shift(),m.shift());let p=[r,h,o,a,""].join("/"),b=[f,c,d,u,""].join("/");this.#t=[p,...l],this.#s=[b,...m],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[r,...h]=this.#t,[o,...a]=this.#s;h[0]===""&&(h.shift(),a.shift());let l=r+"/",f=o+"/";this.#t=[l,...h],this.#s=[f,...a],this.length=this.#t.length}}}[Rr](){return"Pattern <"+this.#s.slice(this.#n).join("/")+">"}pattern(){return this.#t[this.#n]}isString(){return typeof this.#t[this.#n]=="string"}isGlobstar(){return this.#t[this.#n]===xr.GLOBSTAR}isRegExp(){return this.#t[this.#n]instanceof RegExp}globString(){return this.#S=this.#S||(this.#n===0?this.isAbsolute()?this.#s[0]+this.#s.slice(1).join("/"):this.#s.join("/"):this.#s.slice(this.#n).join("/"))}hasMore(){return this.length>this.#n+1}rest(){return this.#h!==void 0?this.#h:this.hasMore()?(this.#h=new n(this.#t,this.#s,this.#n+1,this.#r),this.#h.#o=this.#o,this.#h.#c=this.#c,this.#h.#w=this.#w,this.#h):this.#h=null}isUNC(){let t=this.#t;return this.#c!==void 0?this.#c:this.#c=this.#r==="win32"&&this.#n===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3]}isDrive(){let t=this.#t;return this.#w!==void 0?this.#w:this.#w=this.#r==="win32"&&this.#n===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#o!==void 0?this.#o:this.#o=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#n===0?t:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#f)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#f?!1:(this.#f=!1,!0)}};te.Pattern=Ce});var ke=R(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.Ignore=void 0;var Ps=H(),Ar=Re(),kr=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ae=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:s,noext:i,noglobstar:r,platform:h=kr}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=h,this.mmopts={dot:!0,nobrace:e,nocase:s,noext:i,noglobstar:r,optimizationLevel:2,platform:h,nocomment:!0,nonegate:!0};for(let o of t)this.add(o)}add(t){let e=new Ps.Minimatch(t,this.mmopts);for(let s=0;s{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.Processor=z.SubWalks=z.MatchRecord=z.HasWalkedCache=void 0;var Ds=H(),se=class n{store;constructor(t=new Map){this.store=t}copy(){return new n(new Map(this.store))}hasWalked(t,e){return this.store.get(t.fullpath())?.has(e.globString())}storeWalked(t,e){let s=t.fullpath(),i=this.store.get(s);i?i.add(e.globString()):this.store.set(s,new Set([e.globString()]))}};z.HasWalkedCache=se;var ie=class{store=new Map;add(t,e,s){let i=(e?2:0)|(s?1:0),r=this.store.get(t);this.store.set(t,r===void 0?i:i&r)}entries(){return[...this.store.entries()].map(([t,e])=>[t,!!(e&2),!!(e&1)])}};z.MatchRecord=ie;var re=class{store=new Map;add(t,e){if(!t.canReaddir())return;let s=this.store.get(t);s?s.find(i=>i.globString()===e.globString())||s.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}};z.SubWalks=re;var Me=class n{hasWalkedCache;matches=new ie;subwalks=new re;patterns;follow;dot;opts;constructor(t,e){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new se}processPatterns(t,e){this.patterns=e;let s=e.map(i=>[t,i]);for(let[i,r]of s){this.hasWalkedCache.storeWalked(i,r);let h=r.root(),o=r.isAbsolute()&&this.opts.absolute!==!1;if(h){i=i.resolve(h==="/"&&this.opts.root!==void 0?this.opts.root:h);let c=r.rest();if(c)r=c;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let a,l,f=!1;for(;typeof(a=r.pattern())=="string"&&(l=r.rest());)i=i.resolve(a),r=l,f=!0;if(a=r.pattern(),l=r.rest(),f){if(this.hasWalkedCache.hasWalked(i,r))continue;this.hasWalkedCache.storeWalked(i,r)}if(typeof a=="string"){let c=a===".."||a===""||a===".";this.matches.add(i.resolve(a),o,c);continue}else if(a===Ds.GLOBSTAR){(!i.isSymbolicLink()||this.follow||r.checkFollowGlobstar())&&this.subwalks.add(i,r);let c=l?.pattern(),d=l?.rest();if(!l||(c===""||c===".")&&!d)this.matches.add(i,o,c===""||c===".");else if(c===".."){let u=i.parent||i;d?this.hasWalkedCache.hasWalked(u,d)||this.subwalks.add(u,d):this.matches.add(u,o,!0)}}else a instanceof RegExp&&this.subwalks.add(i,r)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new n(this.opts,this.hasWalkedCache)}filterEntries(t,e){let s=this.subwalks.get(t),i=this.child();for(let r of e)for(let h of s){let o=h.isAbsolute(),a=h.pattern(),l=h.rest();a===Ds.GLOBSTAR?i.testGlobstar(r,h,l,o):a instanceof RegExp?i.testRegExp(r,a,l,o):i.testString(r,a,l,o)}return i}testGlobstar(t,e,s,i){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(s&&e.checkFollowGlobstar()?this.subwalks.add(t,s):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),s){let r=s.pattern();if(typeof r=="string"&&r!==".."&&r!==""&&r!==".")this.testString(t,r,s.rest(),i);else if(r===".."){let h=t.parent||t;this.subwalks.add(h,s)}else r instanceof RegExp&&this.testRegExp(t,r,s.rest(),i)}}testRegExp(t,e,s,i){e.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,e,s,i){t.isNamed(e)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}};z.Processor=Me});var Ls=R(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.GlobStream=X.GlobWalker=X.GlobUtil=void 0;var Mr=Oe(),js=ke(),Ns=Fs(),Pr=(n,t)=>typeof n=="string"?new js.Ignore([n],t):Array.isArray(n)?new js.Ignore(n,t):n,Ot=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#s;#n;signal;maxDepth;includeChildMatches;constructor(t,e,s){if(this.patterns=t,this.path=e,this.opts=s,this.#n=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==!1,(s.ignore||!this.includeChildMatches)&&(this.#s=Pr(s.ignore??[],s),!this.includeChildMatches&&typeof this.#s.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#r(t){return this.seen.has(t)||!!this.#s?.ignored?.(t)}#h(t){return!!this.#s?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#t.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#t.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||await t.realpath(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let h=await r.realpath();h&&(h.isUnknown()||this.opts.stat)&&await h.lstat()}return this.matchCheckTest(r,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#r(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||t.realpathSync(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let h=r.realpathSync();h&&(h?.isUnknown()||this.opts.stat)&&h.lstatSync()}return this.matchCheckTest(r,e)}matchFinish(t,e){if(this.#r(t))return;if(!this.includeChildMatches&&this.#s?.add){let r=`${t.relativePosix()}/**`;this.#s.add(r)}let s=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let i=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(s){let r=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(r+i)}else{let r=this.opts.posix?t.relativePosix():t.relative(),h=this.opts.dotRelative&&!r.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(r?h+r+i:"."+i)}}async match(t,e,s){let i=await this.matchCheck(t,s);i&&this.matchFinish(i,e)}matchSync(t,e,s){let i=this.matchCheckSync(t,s);i&&this.matchFinish(i,e)}walkCB(t,e,s){this.signal?.aborted&&s(),this.walkCB2(t,e,new Ns.Processor(this.opts),s)}walkCB2(t,e,s,i){if(this.#h(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(t,e,s,i));return}s.processPatterns(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||(r++,this.match(o,a,l).then(()=>h()));for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,s,h):o.readdirCB((l,f)=>this.walkCB3(o,f,s,h),!0)}h()}walkCB3(t,e,s,i){s=s.filterEntries(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||(r++,this.match(o,a,l).then(()=>h()));for(let[o,a]of s.subwalks.entries())r++,this.walkCB2(o,a,s.child(),h);h()}walkCBSync(t,e,s){this.signal?.aborted&&s(),this.walkCB2Sync(t,e,new Ns.Processor(this.opts),s)}walkCB2Sync(t,e,s,i){if(this.#h(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,s,i));return}s.processPatterns(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||this.matchSync(o,a,l);for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let a=o.readdirSync();this.walkCB3Sync(o,a,s,h)}h()}walkCB3Sync(t,e,s,i){s=s.filterEntries(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||this.matchSync(o,a,l);for(let[o,a]of s.subwalks.entries())r++,this.walkCB2Sync(o,a,s.child(),h);h()}};X.GlobUtil=Ot;var Pe=class extends Ot{matches=new Set;constructor(t,e,s){super(t,e,s)}matchEmit(t){this.matches.add(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}};X.GlobWalker=Pe;var De=class extends Ot{results;constructor(t,e,s){super(t,e,s),this.results=new Mr.Minipass({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};X.GlobStream=De});var je=R(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.Glob=void 0;var Dr=H(),Fr=require("node:url"),ne=Ms(),jr=Re(),he=Ls(),Nr=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Fe=class{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;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=(0,Fr.fileURLToPath)(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||Nr,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=e.platform==="win32"?ne.PathScurryWin32:e.platform==="darwin"?ne.PathScurryDarwin:e.platform?ne.PathScurryPosix:ne.PathScurry;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let s=this.platform==="darwin"||this.platform==="win32",i={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:s,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(a=>new Dr.Minimatch(a,i)),[h,o]=r.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=h.map((a,l)=>{let f=o[l];if(!f)throw new Error("invalid pattern object");return new jr.Pattern(a,f,0,this.platform)})}async walk(){return[...await new he.GlobWalker(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new he.GlobWalker(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new he.GlobStream(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new he.GlobStream(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};oe.Glob=Fe});var Ne=R(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.hasMagic=void 0;var Lr=H(),Wr=(n,t={})=>{Array.isArray(n)||(n=[n]);for(let e of n)if(new Lr.Minimatch(e,t).hasMagic())return!0;return!1};ae.hasMagic=Wr});Object.defineProperty(exports,"__esModule",{value:!0});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=xt;exports.globStream=Le;exports.globSync=We;exports.globIterateSync=Tt;exports.globIterate=Be;var Ws=H(),tt=je(),Br=Ne(),Is=H();Object.defineProperty(exports,"escape",{enumerable:!0,get:function(){return Is.escape}});Object.defineProperty(exports,"unescape",{enumerable:!0,get:function(){return Is.unescape}});var Ir=je();Object.defineProperty(exports,"Glob",{enumerable:!0,get:function(){return Ir.Glob}});var Gr=Ne();Object.defineProperty(exports,"hasMagic",{enumerable:!0,get:function(){return Gr.hasMagic}});var zr=ke();Object.defineProperty(exports,"Ignore",{enumerable:!0,get:function(){return zr.Ignore}});function xt(n,t={}){return new tt.Glob(n,t).streamSync()}function Le(n,t={}){return new tt.Glob(n,t).stream()}function We(n,t={}){return new tt.Glob(n,t).walkSync()}async function Bs(n,t={}){return new tt.Glob(n,t).walk()}function Tt(n,t={}){return new tt.Glob(n,t).iterateSync()}function Be(n,t={}){return new tt.Glob(n,t).iterate()}exports.streamSync=xt;exports.stream=Object.assign(Le,{sync:xt});exports.iterateSync=Tt;exports.iterate=Object.assign(Be,{sync:Tt});exports.sync=Object.assign(We,{stream:xt,iterate:Tt});exports.glob=Object.assign(Bs,{glob:Bs,globSync:We,sync:exports.sync,globStream:Le,stream:exports.stream,globStreamSync:xt,streamSync:exports.streamSync,globIterate:Be,iterate:exports.iterate,globIterateSync:Tt,iterateSync:exports.iterateSync,Glob:tt.Glob,hasMagic:Br.hasMagic,escape:Ws.escape,unescape:Ws.unescape});exports.glob.glob=exports.glob; +//# sourceMappingURL=index.min.js.map diff --git a/node_modules/glob/dist/commonjs/pattern.js b/node_modules/glob/dist/commonjs/pattern.js index f0de35fb5bed9..95f9075c5bfcb 100644 --- a/node_modules/glob/dist/commonjs/pattern.js +++ b/node_modules/glob/dist/commonjs/pattern.js @@ -5,6 +5,7 @@ exports.Pattern = void 0; const minimatch_1 = require("minimatch"); const isPatternList = (pl) => pl.length >= 1; const isGlobList = (gl) => gl.length >= 1; +const customInspect = Symbol.for('nodejs.util.inspect.custom'); /** * An immutable-ish view on an array of glob parts and their parsed * results @@ -80,6 +81,9 @@ class Pattern { } } } + [customInspect]() { + return 'Pattern <' + this.#globList.slice(this.#index).join('/') + '>'; + } /** * The first entry in the parsed list of patterns */ diff --git a/node_modules/glob/dist/esm/bin.d.mts b/node_modules/glob/dist/esm/bin.d.mts deleted file mode 100644 index 77298e4770817..0000000000000 --- a/node_modules/glob/dist/esm/bin.d.mts +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env node -export {}; -//# sourceMappingURL=bin.d.mts.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/bin.mjs b/node_modules/glob/dist/esm/bin.mjs deleted file mode 100755 index 5c7bf1e925610..0000000000000 --- a/node_modules/glob/dist/esm/bin.mjs +++ /dev/null @@ -1,270 +0,0 @@ -#!/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 \ No newline at end of file diff --git a/node_modules/glob/dist/esm/glob.js b/node_modules/glob/dist/esm/glob.js index c9ff3b0036d94..d89c3dad90daa 100644 --- a/node_modules/glob/dist/esm/glob.js +++ b/node_modules/glob/dist/esm/glob.js @@ -137,11 +137,12 @@ export class Glob { // for the file `AbC` for example. const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32'; const mmo = { - // default nocase based on platform + braceExpandMax: 10_000, ...opts, dot: this.dot, matchBase: this.matchBase, nobrace: this.nobrace, + // default nocase based on platform nocase: this.nocase, nocaseMagicOnly, nocomment: true, diff --git a/node_modules/glob/dist/esm/index.min.js b/node_modules/glob/dist/esm/index.min.js new file mode 100644 index 0000000000000..e6ea7cc1bc831 --- /dev/null +++ b/node_modules/glob/dist/esm/index.min.js @@ -0,0 +1,4 @@ +var Gt=(n,t,e)=>{let s=n instanceof RegExp?ce(n,e):n,i=t instanceof RegExp?ce(t,e):t,r=s!==null&&i!=null&&ss(s,i,e);return r&&{start:r[0],end:r[1],pre:e.slice(0,r[0]),body:e.slice(r[0]+s.length,r[1]),post:e.slice(r[1]+i.length)}},ce=(n,t)=>{let e=t.match(n);return e?e[0]:null},ss=(n,t,e)=>{let s,i,r,o,h,a=e.indexOf(n),l=e.indexOf(t,a+1),u=a;if(a>=0&&l>0){if(n===t)return[a,l];for(s=[],r=e.length;u>=0&&!h;){if(u===a)s.push(u),a=e.indexOf(n,u+1);else if(s.length===1){let c=s.pop();c!==void 0&&(h=[c,l])}else i=s.pop(),i!==void 0&&i=0?a:l}s.length&&o!==void 0&&(h=[r,o])}return h};var fe="\0SLASH"+Math.random()+"\0",ue="\0OPEN"+Math.random()+"\0",qt="\0CLOSE"+Math.random()+"\0",de="\0COMMA"+Math.random()+"\0",pe="\0PERIOD"+Math.random()+"\0",is=new RegExp(fe,"g"),rs=new RegExp(ue,"g"),ns=new RegExp(qt,"g"),os=new RegExp(de,"g"),hs=new RegExp(pe,"g"),as=/\\\\/g,ls=/\\{/g,cs=/\\}/g,fs=/\\,/g,us=/\\./g,ds=1e5;function Ht(n){return isNaN(n)?n.charCodeAt(0):parseInt(n,10)}function ps(n){return n.replace(as,fe).replace(ls,ue).replace(cs,qt).replace(fs,de).replace(us,pe)}function ms(n){return n.replace(is,"\\").replace(rs,"{").replace(ns,"}").replace(os,",").replace(hs,".")}function me(n){if(!n)return[""];let t=[],e=Gt("{","}",n);if(!e)return n.split(",");let{pre:s,body:i,post:r}=e,o=s.split(",");o[o.length-1]+="{"+i+"}";let h=me(r);return r.length&&(o[o.length-1]+=h.shift(),o.push.apply(o,h)),t.push.apply(t,o),t}function ge(n,t={}){if(!n)return[];let{max:e=ds}=t;return n.slice(0,2)==="{}"&&(n="\\{\\}"+n.slice(2)),ht(ps(n),e,!0).map(ms)}function gs(n){return"{"+n+"}"}function ws(n){return/^-?0\d/.test(n)}function ys(n,t){return n<=t}function bs(n,t){return n>=t}function ht(n,t,e){let s=[],i=Gt("{","}",n);if(!i)return[n];let r=i.pre,o=i.post.length?ht(i.post,t,!1):[""];if(/\$$/.test(i.pre))for(let h=0;h=0;if(!l&&!u)return i.post.match(/,(?!,).*\}/)?(n=i.pre+"{"+i.body+qt+i.post,ht(n,t,!0)):[n];let c;if(l)c=i.body.split(/\.\./);else if(c=me(i.body),c.length===1&&c[0]!==void 0&&(c=ht(c[0],t,!1).map(gs),c.length===1))return o.map(f=>i.pre+c[0]+f);let d;if(l&&c[0]!==void 0&&c[1]!==void 0){let f=Ht(c[0]),m=Ht(c[1]),p=Math.max(c[0].length,c[1].length),w=c.length===3&&c[2]!==void 0?Math.abs(Ht(c[2])):1,g=ys;m0){let $=new Array(z+1).join("0");y<0?b="-"+$+b.slice(1):b=$+b}}d.push(b)}}else{d=[];for(let f=0;f{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>65536)throw new TypeError("pattern is too long")};var Ss={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},lt=n=>n.replace(/[[\]\\-]/g,"\\$&"),Es=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),we=n=>n.join(""),ye=(n,t)=>{let e=t;if(n.charAt(e)!=="[")throw new Error("not in a brace expression");let s=[],i=[],r=e+1,o=!1,h=!1,a=!1,l=!1,u=e,c="";t:for(;rc?s.push(lt(c)+"-"+lt(p)):p===c&&s.push(lt(p)),c="",r++;continue}if(n.startsWith("-]",r+1)){s.push(lt(p+"-")),r+=2;continue}if(n.startsWith("-",r+1)){c=p,r+=2;continue}s.push(lt(p)),r++}if(ue?t?n.replace(/\[([^\/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?n.replace(/\[([^\/\\{}])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1");var xs=new Set(["!","?","+","*","@"]),be=n=>xs.has(n),vs="(?!(?:^|/)\\.\\.?(?:$|/))",Ct="(?!\\.)",Cs=new Set(["[","."]),Ts=new Set(["..","."]),As=new Set("().*{}+?[]^$\\!"),ks=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Kt="[^/]",Se=Kt+"*?",Ee=Kt+"+?",Q=class n{type;#t;#s;#n=!1;#r=[];#o;#S;#w;#c=!1;#h;#u;#f=!1;constructor(t,e,s={}){this.type=t,t&&(this.#s=!0),this.#o=e,this.#t=this.#o?this.#o.#t:this,this.#h=this.#t===this?s:this.#t.#h,this.#w=this.#t===this?[]:this.#t.#w,t==="!"&&!this.#t.#c&&this.#w.push(this),this.#S=this.#o?this.#o.#r.length:0}get hasMagic(){if(this.#s!==void 0)return this.#s;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#s=!0;return this.#s}toString(){return this.#u!==void 0?this.#u:this.type?this.#u=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#u=this.#r.map(t=>String(t)).join("")}#a(){if(this!==this.#t)throw new Error("should only call on root");if(this.#c)return this;this.toString(),this.#c=!0;let t;for(;t=this.#w.pop();){if(t.type!=="!")continue;let e=t,s=e.#o;for(;s;){for(let i=e.#S+1;!s.type&&itypeof e=="string"?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#c&&this.#o?.type==="!")&&t.push({}),t}isStart(){if(this.#t===this)return!0;if(!this.#o?.isStart())return!1;if(this.#S===0)return!0;let t=this.#o;for(let e=0;etypeof f!="string"),l=this.#r.map(f=>{let[m,p,w,g]=typeof f=="string"?n.#E(f,this.#s,a):f.toRegExpSource(t);return this.#s=this.#s||w,this.#n=this.#n||g,m}).join(""),u="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&Ts.has(this.#r[0]))){let m=Cs,p=e&&m.has(l.charAt(0))||l.startsWith("\\.")&&m.has(l.charAt(2))||l.startsWith("\\.\\.")&&m.has(l.charAt(4)),w=!e&&!t&&m.has(l.charAt(0));u=p?vs:w?Ct:""}let c="";return this.isEnd()&&this.#t.#c&&this.#o?.type==="!"&&(c="(?:$|\\/)"),[u+l+c,W(l),this.#s=!!this.#s,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",r=this.#d(e);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){let a=this.toString();return this.#r=[a],this.type=null,this.#s=void 0,[a,W(this.toString()),!1,!1]}let o=!s||t||e||!Ct?"":this.#d(!0);o===r&&(o=""),o&&(r=`(?:${r})(?:${o})*?`);let h="";if(this.type==="!"&&this.#f)h=(this.isStart()&&!e?Ct:"")+Ee;else{let a=this.type==="!"?"))"+(this.isStart()&&!e&&!t?Ct:"")+Se+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;h=i+r+a}return[h,W(r),this.#s=!!this.#s,this.#n]}#d(t){return this.#r.map(e=>{if(typeof e=="string")throw new Error("string type in extglob ast??");let[s,i,r,o]=e.toRegExpSource(t);return this.#n=this.#n||o,s}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")}static#E(t,e,s=!1){let i=!1,r="",o=!1,h=!1;for(let a=0;ae?t?n.replace(/[?*()[\]{}]/g,"[$&]"):n.replace(/[?*()[\]\\{}]/g,"\\$&"):t?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");var O=(n,t,e={})=>(at(t),!e.nocomment&&t.charAt(0)==="#"?!1:new D(t,e).match(n)),Rs=/^\*+([^+@!?\*\[\(]*)$/,Os=n=>t=>!t.startsWith(".")&&t.endsWith(n),Fs=n=>t=>t.endsWith(n),Ds=n=>(n=n.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(n)),Ms=n=>(n=n.toLowerCase(),t=>t.toLowerCase().endsWith(n)),Ns=/^\*+\.\*+$/,_s=n=>!n.startsWith(".")&&n.includes("."),Ls=n=>n!=="."&&n!==".."&&n.includes("."),Ws=/^\.\*+$/,Ps=n=>n!=="."&&n!==".."&&n.startsWith("."),js=/^\*+$/,Is=n=>n.length!==0&&!n.startsWith("."),zs=n=>n.length!==0&&n!=="."&&n!=="..",Bs=/^\?+([^+@!?\*\[\(]*)?$/,Us=([n,t=""])=>{let e=Ce([n]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},$s=([n,t=""])=>{let e=Te([n]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Gs=([n,t=""])=>{let e=Te([n]);return t?s=>e(s)&&s.endsWith(t):e},Hs=([n,t=""])=>{let e=Ce([n]);return t?s=>e(s)&&s.endsWith(t):e},Ce=([n])=>{let t=n.length;return e=>e.length===t&&!e.startsWith(".")},Te=([n])=>{let t=n.length;return e=>e.length===t&&e!=="."&&e!==".."},Ae=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",xe={win32:{sep:"\\"},posix:{sep:"/"}},qs=Ae==="win32"?xe.win32.sep:xe.posix.sep;O.sep=qs;var A=Symbol("globstar **");O.GLOBSTAR=A;var Ks="[^/]",Vs=Ks+"*?",Ys="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Xs="(?:(?!(?:\\/|^)\\.).)*?",Js=(n,t={})=>e=>O(e,n,t);O.filter=Js;var N=(n,t={})=>Object.assign({},n,t),Zs=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return O;let t=O;return Object.assign((s,i,r={})=>t(s,i,N(n,r)),{Minimatch:class extends t.Minimatch{constructor(i,r={}){super(i,N(n,r))}static defaults(i){return t.defaults(N(n,i)).Minimatch}},AST:class extends t.AST{constructor(i,r,o={}){super(i,r,N(n,o))}static fromGlob(i,r={}){return t.AST.fromGlob(i,N(n,r))}},unescape:(s,i={})=>t.unescape(s,N(n,i)),escape:(s,i={})=>t.escape(s,N(n,i)),filter:(s,i={})=>t.filter(s,N(n,i)),defaults:s=>t.defaults(N(n,s)),makeRe:(s,i={})=>t.makeRe(s,N(n,i)),braceExpand:(s,i={})=>t.braceExpand(s,N(n,i)),match:(s,i,r={})=>t.match(s,i,N(n,r)),sep:t.sep,GLOBSTAR:A})};O.defaults=Zs;var ke=(n,t={})=>(at(n),t.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:ge(n,{max:t.braceExpandMax}));O.braceExpand=ke;var Qs=(n,t={})=>new D(n,t).makeRe();O.makeRe=Qs;var ti=(n,t,e={})=>{let s=new D(t,e);return n=n.filter(i=>s.match(i)),s.options.nonull&&!n.length&&n.push(t),n};O.match=ti;var ve=/[?*]|[+@!]\(.*?\)|\[|\]/,ei=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),D=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){at(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||Ae,this.isWindows=this.platform==="win32";let s="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[s]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let s=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let i=this.globParts.map((r,o,h)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=r[0]===""&&r[1]===""&&(r[2]==="?"||!ve.test(r[2]))&&!ve.test(r[3]),l=/^[a-z]:/i.test(r[0]);if(a)return[...r.slice(0,4),...r.slice(4).map(u=>this.parse(u))];if(l)return[r[0],...r.slice(1).map(u=>this.parse(u))]}return r.map(a=>this.parse(a))});if(this.debug(this.pattern,i),this.set=i.filter(r=>r.indexOf(!1)===-1),this.isWindows)for(let r=0;r=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let s=-1;for(;(s=e.indexOf("**",s+1))!==-1;){let i=s;for(;e[i+1]==="**";)i++;i!==s&&e.splice(s,i-s)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((s,i)=>{let r=s[s.length-1];return i==="**"&&r==="**"?s:i===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(s.pop(),s):(s.push(i),s)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let i=1;ii&&s.splice(i+1,o-i);let h=s[i+1],a=s[i+2],l=s[i+3];if(h!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,s.splice(i,1);let u=s.slice(0);u[i]="**",t.push(u),i--}if(!this.preserveMultipleSlashes){for(let o=1;oe.length)}partsMatch(t,e,s=!1){let i=0,r=0,o=[],h="";for(;iE?e=e.slice(y):E>y&&(t=t.slice(E)))}}let{optimizationLevel:r=1}=this.options;r>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var o=0,h=0,a=t.length,l=e.length;o>> no match, partial?`,t,d,e,f),d===a))}let p;if(typeof u=="string"?(p=c===u,this.debug("string match",u,c,p)):(p=u.test(c),this.debug("pattern match",u,c,p)),!p)return!1}if(o===a&&h===l)return!0;if(o===a)return s;if(h===l)return o===a-1&&t[o]==="";throw new Error("wtf?")}braceExpand(){return ke(this.pattern,this.options)}parse(t){at(t);let e=this.options;if(t==="**")return A;if(t==="")return"";let s,i=null;(s=t.match(js))?i=e.dot?zs:Is:(s=t.match(Rs))?i=(e.nocase?e.dot?Ms:Ds:e.dot?Fs:Os)(s[1]):(s=t.match(Bs))?i=(e.nocase?e.dot?$s:Us:e.dot?Gs:Hs)(s):(s=t.match(Ns))?i=e.dot?Ls:_s:(s=t.match(Ws))&&(i=Ps);let r=Q.fromGlob(t,this.options).toMMPattern();return i&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:i}),r}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,s=e.noglobstar?Vs:e.dot?Ys:Xs,i=new Set(e.nocase?["i"]:[]),r=t.map(a=>{let l=a.map(c=>{if(c instanceof RegExp)for(let d of c.flags.split(""))i.add(d);return typeof c=="string"?ei(c):c===A?A:c._src});l.forEach((c,d)=>{let f=l[d+1],m=l[d-1];c!==A||m===A||(m===void 0?f!==void 0&&f!==A?l[d+1]="(?:\\/|"+s+"\\/)?"+f:l[d]=s:f===void 0?l[d-1]=m+"(?:\\/|\\/"+s+")?":f!==A&&(l[d-1]=m+"(?:\\/|\\/"+s+"\\/)"+f,l[d+1]=A))});let u=l.filter(c=>c!==A);if(this.partial&&u.length>=1){let c=[];for(let d=1;d<=u.length;d++)c.push(u.slice(0,d).join("/"));return"(?:"+c.join("|")+")"}return u.join("/")}).join("|"),[o,h]=t.length>1?["(?:",")"]:["",""];r="^"+o+r+h+"$",this.partial&&(r="^(?:\\/|"+o+r.slice(1,-1)+h+")$"),this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let s=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let r=this.set;this.debug(this.pattern,"set",r);let o=i[i.length-1];if(!o)for(let h=i.length-2;!o&&h>=0;h--)o=i[h];for(let h=0;h{typeof Vt.emitWarning=="function"?Vt.emitWarning(n,t,e,s):console.error(`[${e}] ${t}: ${n}`)},At=globalThis.AbortController,Re=globalThis.AbortSignal;if(typeof At>"u"){Re=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,s){this._onabort.push(s)}},At=class{constructor(){t()}signal=new Re;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let s of this.signal._onabort)s(e);this.signal.onabort?.(e)}}};let n=Vt.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{n&&(n=!1,Fe("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 ii=n=>!Oe.has(n);var q=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),De=n=>q(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?Tt:null:null,Tt=class extends Array{constructor(n){super(n),this.fill(0)}},ri=class ct{heap;length;static#t=!1;static create(t){let e=De(t);if(!e)return[];ct.#t=!0;let s=new ct(t,e);return ct.#t=!1,s}constructor(t,e){if(!ct.#t)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]}},ft=class Me{#t;#s;#n;#r;#o;#S;#w;#c;get perf(){return this.#c}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#h;#u;#f;#a;#i;#d;#E;#b;#p;#R;#m;#C;#T;#g;#y;#x;#A;#e;#_;static unsafeExposeInternals(t){return{starts:t.#T,ttls:t.#g,autopurgeTimers:t.#y,sizes:t.#C,keyMap:t.#f,keyList:t.#a,valList:t.#i,next:t.#d,prev:t.#E,get head(){return t.#b},get tail(){return t.#p},free:t.#R,isBackgroundFetch:e=>t.#l(e),backgroundFetch:(e,s,i,r)=>t.#U(e,s,i,r),moveToTail:e=>t.#W(e),indexes:e=>t.#F(e),rindexes:e=>t.#D(e),isStale:e=>t.#v(e)}}get max(){return this.#t}get maxSize(){return this.#s}get calculatedSize(){return this.#u}get size(){return this.#h}get fetchMethod(){return this.#S}get memoMethod(){return this.#w}get dispose(){return this.#n}get onInsert(){return this.#r}get disposeAfter(){return this.#o}constructor(t){let{max:e=0,ttl:s,ttlResolution:i=1,ttlAutopurge:r,updateAgeOnGet:o,updateAgeOnHas:h,allowStale:a,dispose:l,onInsert:u,disposeAfter:c,noDisposeOnSet:d,noUpdateTTL:f,maxSize:m=0,maxEntrySize:p=0,sizeCalculation:w,fetchMethod:g,memoMethod:S,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:b,allowStaleOnFetchAbort:z,ignoreFetchAbort:$,perf:J}=t;if(J!==void 0&&typeof J?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#c=J??si,e!==0&&!q(e))throw new TypeError("max option must be a nonnegative integer");let Z=e?De(e):Array;if(!Z)throw new Error("invalid max value: "+e);if(this.#t=e,this.#s=m,this.maxEntrySize=p||this.#s,this.sizeCalculation=w,this.sizeCalculation){if(!this.#s&&!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(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=S,g!==void 0&&typeof g!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#S=g,this.#A=!!g,this.#f=new Map,this.#a=new Array(e).fill(void 0),this.#i=new Array(e).fill(void 0),this.#d=new Z(e),this.#E=new Z(e),this.#b=0,this.#p=0,this.#R=ri.create(e),this.#h=0,this.#u=0,typeof l=="function"&&(this.#n=l),typeof u=="function"&&(this.#r=u),typeof c=="function"?(this.#o=c,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#x=!!this.#n,this.#_=!!this.#r,this.#e=!!this.#o,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!b,this.allowStaleOnFetchAbort=!!z,this.ignoreFetchAbort=!!$,this.maxEntrySize!==0){if(this.#s!==0&&!q(this.#s))throw new TypeError("maxSize must be a positive integer if specified");if(!q(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#G()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!h,this.ttlResolution=q(i)||i===0?i:1,this.ttlAutopurge=!!r,this.ttl=s||0,this.ttl){if(!q(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#M()}if(this.#t===0&&this.ttl===0&&this.#s===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#s){let $t="LRU_CACHE_UNBOUNDED";ii($t)&&(Oe.add($t),Fe("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",$t,Me))}}getRemainingTTL(t){return this.#f.has(t)?1/0:0}#M(){let t=new Tt(this.#t),e=new Tt(this.#t);this.#g=t,this.#T=e;let s=this.ttlAutopurge?new Array(this.#t):void 0;this.#y=s,this.#j=(o,h,a=this.#c.now())=>{if(e[o]=h!==0?a:0,t[o]=h,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),h!==0&&s){let l=setTimeout(()=>{this.#v(o)&&this.#O(this.#a[o],"expire")},h+1);l.unref&&l.unref(),s[o]=l}},this.#k=o=>{e[o]=t[o]!==0?this.#c.now():0},this.#N=(o,h)=>{if(t[h]){let a=t[h],l=e[h];if(!a||!l)return;o.ttl=a,o.start=l,o.now=i||r();let u=o.now-l;o.remainingTTL=a-u}};let i=0,r=()=>{let o=this.#c.now();if(this.ttlResolution>0){i=o;let h=setTimeout(()=>i=0,this.ttlResolution);h.unref&&h.unref()}return o};this.getRemainingTTL=o=>{let h=this.#f.get(o);if(h===void 0)return 0;let a=t[h],l=e[h];if(!a||!l)return 1/0;let u=(i||r())-l;return a-u},this.#v=o=>{let h=e[o],a=t[o];return!!a&&!!h&&(i||r())-h>a}}#k=()=>{};#N=()=>{};#j=()=>{};#v=()=>!1;#G(){let t=new Tt(this.#t);this.#u=0,this.#C=t,this.#P=e=>{this.#u-=t[e],t[e]=0},this.#I=(e,s,i,r)=>{if(this.#l(s))return 0;if(!q(i))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(i=r(s,e),!q(i))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 i},this.#L=(e,s,i)=>{if(t[e]=s,this.#s){let r=this.#s-t[e];for(;this.#u>r;)this.#B(!0)}this.#u+=t[e],i&&(i.entrySize=s,i.totalCalculatedSize=this.#u)}}#P=t=>{};#L=(t,e,s)=>{};#I=(t,e,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#F({allowStale:t=this.allowStale}={}){if(this.#h)for(let e=this.#p;!(!this.#z(e)||((t||!this.#v(e))&&(yield e),e===this.#b));)e=this.#E[e]}*#D({allowStale:t=this.allowStale}={}){if(this.#h)for(let e=this.#b;!(!this.#z(e)||((t||!this.#v(e))&&(yield e),e===this.#p));)e=this.#d[e]}#z(t){return t!==void 0&&this.#f.get(this.#a[t])===t}*entries(){for(let t of this.#F())this.#i[t]!==void 0&&this.#a[t]!==void 0&&!this.#l(this.#i[t])&&(yield[this.#a[t],this.#i[t]])}*rentries(){for(let t of this.#D())this.#i[t]!==void 0&&this.#a[t]!==void 0&&!this.#l(this.#i[t])&&(yield[this.#a[t],this.#i[t]])}*keys(){for(let t of this.#F()){let e=this.#a[t];e!==void 0&&!this.#l(this.#i[t])&&(yield e)}}*rkeys(){for(let t of this.#D()){let e=this.#a[t];e!==void 0&&!this.#l(this.#i[t])&&(yield e)}}*values(){for(let t of this.#F())this.#i[t]!==void 0&&!this.#l(this.#i[t])&&(yield this.#i[t])}*rvalues(){for(let t of this.#D())this.#i[t]!==void 0&&!this.#l(this.#i[t])&&(yield this.#i[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let s of this.#F()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;if(r!==void 0&&t(r,this.#a[s],this))return this.get(this.#a[s],e)}}forEach(t,e=this){for(let s of this.#F()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;r!==void 0&&t.call(e,r,this.#a[s],this)}}rforEach(t,e=this){for(let s of this.#D()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;r!==void 0&&t.call(e,r,this.#a[s],this)}}purgeStale(){let t=!1;for(let e of this.#D({allowStale:!0}))this.#v(e)&&(this.#O(this.#a[e],"expire"),t=!0);return t}info(t){let e=this.#f.get(t);if(e===void 0)return;let s=this.#i[e],i=this.#l(s)?s.__staleWhileFetching:s;if(i===void 0)return;let r={value:i};if(this.#g&&this.#T){let o=this.#g[e],h=this.#T[e];if(o&&h){let a=o-(this.#c.now()-h);r.ttl=a,r.start=Date.now()}}return this.#C&&(r.size=this.#C[e]),r}dump(){let t=[];for(let e of this.#F({allowStale:!0})){let s=this.#a[e],i=this.#i[e],r=this.#l(i)?i.__staleWhileFetching:i;if(r===void 0||s===void 0)continue;let o={value:r};if(this.#g&&this.#T){o.ttl=this.#g[e];let h=this.#c.now()-this.#T[e];o.start=Math.floor(Date.now()-h)}this.#C&&(o.size=this.#C[e]),t.unshift([s,o])}return t}load(t){this.clear();for(let[e,s]of t){if(s.start){let i=Date.now()-s.start;s.start=this.#c.now()-i}this.set(e,s.value,s)}}set(t,e,s={}){if(e===void 0)return this.delete(t),this;let{ttl:i=this.ttl,start:r,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:a}=s,{noUpdateTTL:l=this.noUpdateTTL}=s,u=this.#I(t,e,s.size||0,h);if(this.maxEntrySize&&u>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#O(t,"set"),this;let c=this.#h===0?void 0:this.#f.get(t);if(c===void 0)c=this.#h===0?this.#p:this.#R.length!==0?this.#R.pop():this.#h===this.#t?this.#B(!1):this.#h,this.#a[c]=t,this.#i[c]=e,this.#f.set(t,c),this.#d[this.#p]=c,this.#E[c]=this.#p,this.#p=c,this.#h++,this.#L(c,u,a),a&&(a.set="add"),l=!1,this.#_&&this.#r?.(e,t,"add");else{this.#W(c);let d=this.#i[c];if(e!==d){if(this.#A&&this.#l(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=d;f!==void 0&&!o&&(this.#x&&this.#n?.(f,t,"set"),this.#e&&this.#m?.push([f,t,"set"]))}else o||(this.#x&&this.#n?.(d,t,"set"),this.#e&&this.#m?.push([d,t,"set"]));if(this.#P(c),this.#L(c,u,a),this.#i[c]=e,a){a.set="replace";let f=d&&this.#l(d)?d.__staleWhileFetching:d;f!==void 0&&(a.oldValue=f)}}else a&&(a.set="update");this.#_&&this.onInsert?.(e,t,e===d?"update":"replace")}if(i!==0&&!this.#g&&this.#M(),this.#g&&(l||this.#j(c,i,r),a&&this.#N(a,c)),!o&&this.#e&&this.#m){let d=this.#m,f;for(;f=d?.shift();)this.#o?.(...f)}return this}pop(){try{for(;this.#h;){let t=this.#i[this.#b];if(this.#B(!0),this.#l(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#e&&this.#m){let t=this.#m,e;for(;e=t?.shift();)this.#o?.(...e)}}}#B(t){let e=this.#b,s=this.#a[e],i=this.#i[e];return this.#A&&this.#l(i)?i.__abortController.abort(new Error("evicted")):(this.#x||this.#e)&&(this.#x&&this.#n?.(i,s,"evict"),this.#e&&this.#m?.push([i,s,"evict"])),this.#P(e),this.#y?.[e]&&(clearTimeout(this.#y[e]),this.#y[e]=void 0),t&&(this.#a[e]=void 0,this.#i[e]=void 0,this.#R.push(e)),this.#h===1?(this.#b=this.#p=0,this.#R.length=0):this.#b=this.#d[e],this.#f.delete(s),this.#h--,e}has(t,e={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=e,r=this.#f.get(t);if(r!==void 0){let o=this.#i[r];if(this.#l(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#v(r))i&&(i.has="stale",this.#N(i,r));else return s&&this.#k(r),i&&(i.has="hit",this.#N(i,r)),!0}else i&&(i.has="miss");return!1}peek(t,e={}){let{allowStale:s=this.allowStale}=e,i=this.#f.get(t);if(i===void 0||!s&&this.#v(i))return;let r=this.#i[i];return this.#l(r)?r.__staleWhileFetching:r}#U(t,e,s,i){let r=e===void 0?void 0:this.#i[e];if(this.#l(r))return r;let o=new At,{signal:h}=s;h?.addEventListener("abort",()=>o.abort(h.reason),{signal:o.signal});let a={signal:o.signal,options:s,context:i},l=(p,w=!1)=>{let{aborted:g}=o.signal,S=s.ignoreFetchAbort&&p!==void 0,E=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&p!==void 0);if(s.status&&(g&&!w?(s.status.fetchAborted=!0,s.status.fetchError=o.signal.reason,S&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),g&&!S&&!w)return c(o.signal.reason,E);let y=f,b=this.#i[e];return(b===f||S&&w&&b===void 0)&&(p===void 0?y.__staleWhileFetching!==void 0?this.#i[e]=y.__staleWhileFetching:this.#O(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(t,p,a.options))),p},u=p=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=p),c(p,!1)),c=(p,w)=>{let{aborted:g}=o.signal,S=g&&s.allowStaleOnFetchAbort,E=S||s.allowStaleOnFetchRejection,y=E||s.noDeleteOnFetchRejection,b=f;if(this.#i[e]===f&&(!y||!w&&b.__staleWhileFetching===void 0?this.#O(t,"fetch"):S||(this.#i[e]=b.__staleWhileFetching)),E)return s.status&&b.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),b.__staleWhileFetching;if(b.__returned===b)throw p},d=(p,w)=>{let g=this.#S?.(t,r,a);g&&g instanceof Promise&&g.then(S=>p(S===void 0?void 0:S),w),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(p(void 0),s.allowStaleOnFetchAbort&&(p=S=>l(S,!0)))})};s.status&&(s.status.fetchDispatched=!0);let f=new Promise(d).then(l,u),m=Object.assign(f,{__abortController:o,__staleWhileFetching:r,__returned:void 0});return e===void 0?(this.set(t,m,{...a.options,status:void 0}),e=this.#f.get(t)):this.#i[e]=m,m}#l(t){if(!this.#A)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof At}async fetch(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:c=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:p,forceRefresh:w=!1,status:g,signal:S}=e;if(!this.#A)return g&&(g.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:r,status:g});let E={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:r,ttl:o,noDisposeOnSet:h,size:a,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:c,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:g,signal:S},y=this.#f.get(t);if(y===void 0){g&&(g.fetch="miss");let b=this.#U(t,y,E,p);return b.__returned=b}else{let b=this.#i[y];if(this.#l(b)){let Z=s&&b.__staleWhileFetching!==void 0;return g&&(g.fetch="inflight",Z&&(g.returnedStale=!0)),Z?b.__staleWhileFetching:b.__returned=b}let z=this.#v(y);if(!w&&!z)return g&&(g.fetch="hit"),this.#W(y),i&&this.#k(y),g&&this.#N(g,y),b;let $=this.#U(t,y,E,p),J=$.__staleWhileFetching!==void 0&&s;return g&&(g.fetch=z?"stale":"refresh",J&&z&&(g.returnedStale=!0)),J?$.__staleWhileFetching:$.__returned=$}}async forceFetch(t,e={}){let s=await this.fetch(t,e);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,e={}){let s=this.#w;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:r,...o}=e,h=this.get(t,o);if(!r&&h!==void 0)return h;let a=s(t,h,{options:o,context:i});return this.set(t,a,o),a}get(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:o}=e,h=this.#f.get(t);if(h!==void 0){let a=this.#i[h],l=this.#l(a);return o&&this.#N(o,h),this.#v(h)?(o&&(o.get="stale"),l?(o&&s&&a.__staleWhileFetching!==void 0&&(o.returnedStale=!0),s?a.__staleWhileFetching:void 0):(r||this.#O(t,"expire"),o&&s&&(o.returnedStale=!0),s?a:void 0)):(o&&(o.get="hit"),l?a.__staleWhileFetching:(this.#W(h),i&&this.#k(h),a))}else o&&(o.get="miss")}#$(t,e){this.#E[e]=t,this.#d[t]=e}#W(t){t!==this.#p&&(t===this.#b?this.#b=this.#d[t]:this.#$(this.#E[t],this.#d[t]),this.#$(this.#p,t),this.#p=t)}delete(t){return this.#O(t,"delete")}#O(t,e){let s=!1;if(this.#h!==0){let i=this.#f.get(t);if(i!==void 0)if(this.#y?.[i]&&(clearTimeout(this.#y?.[i]),this.#y[i]=void 0),s=!0,this.#h===1)this.#H(e);else{this.#P(i);let r=this.#i[i];if(this.#l(r)?r.__abortController.abort(new Error("deleted")):(this.#x||this.#e)&&(this.#x&&this.#n?.(r,t,e),this.#e&&this.#m?.push([r,t,e])),this.#f.delete(t),this.#a[i]=void 0,this.#i[i]=void 0,i===this.#p)this.#p=this.#E[i];else if(i===this.#b)this.#b=this.#d[i];else{let o=this.#E[i];this.#d[o]=this.#d[i];let h=this.#d[i];this.#E[h]=this.#E[i]}this.#h--,this.#R.push(i)}}if(this.#e&&this.#m?.length){let i=this.#m,r;for(;r=i?.shift();)this.#o?.(...r)}return s}clear(){return this.#H("delete")}#H(t){for(let e of this.#D({allowStale:!0})){let s=this.#i[e];if(this.#l(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#a[e];this.#x&&this.#n?.(s,i,t),this.#e&&this.#m?.push([s,i,t])}}if(this.#f.clear(),this.#i.fill(void 0),this.#a.fill(void 0),this.#g&&this.#T){this.#g.fill(0),this.#T.fill(0);for(let e of this.#y??[])e!==void 0&&clearTimeout(e);this.#y?.fill(void 0)}if(this.#C&&this.#C.fill(0),this.#b=0,this.#p=0,this.#R.length=0,this.#u=0,this.#h=0,this.#e&&this.#m){let e=this.#m,s;for(;s=e?.shift();)this.#o?.(...s)}}};import{posix as mi,win32 as re}from"node:path";import{fileURLToPath as gi}from"node:url";import{lstatSync as wi,readdir as yi,readdirSync as bi,readlinkSync as Si,realpathSync as Ei}from"fs";import*as xi from"node:fs";import{lstat as Ci,readdir as Ti,readlink as Ai,realpath as ki}from"node:fs/promises";import{EventEmitter as ee}from"node:events";import Pe from"node:stream";import{StringDecoder as ni}from"node:string_decoder";var Ne=typeof process=="object"&&process?process:{stdout:null,stderr:null},oi=n=>!!n&&typeof n=="object"&&(n instanceof V||n instanceof Pe||hi(n)||ai(n)),hi=n=>!!n&&typeof n=="object"&&n instanceof ee&&typeof n.pipe=="function"&&n.pipe!==Pe.Writable.prototype.pipe,ai=n=>!!n&&typeof n=="object"&&n instanceof ee&&typeof n.write=="function"&&typeof n.end=="function",G=Symbol("EOF"),H=Symbol("maybeEmitEnd"),K=Symbol("emittedEnd"),kt=Symbol("emittingEnd"),ut=Symbol("emittedError"),Rt=Symbol("closed"),_e=Symbol("read"),Ot=Symbol("flush"),Le=Symbol("flushChunk"),P=Symbol("encoding"),et=Symbol("decoder"),v=Symbol("flowing"),dt=Symbol("paused"),st=Symbol("resume"),C=Symbol("buffer"),F=Symbol("pipes"),T=Symbol("bufferLength"),Yt=Symbol("bufferPush"),Ft=Symbol("bufferShift"),k=Symbol("objectMode"),x=Symbol("destroyed"),Xt=Symbol("error"),Jt=Symbol("emitData"),We=Symbol("emitEnd"),Zt=Symbol("emitEnd2"),B=Symbol("async"),Qt=Symbol("abort"),Dt=Symbol("aborted"),pt=Symbol("signal"),Y=Symbol("dataListeners"),M=Symbol("discarded"),mt=n=>Promise.resolve().then(n),li=n=>n(),ci=n=>n==="end"||n==="finish"||n==="prefinish",fi=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,ui=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),Mt=class{src;dest;opts;ondrain;constructor(t,e,s){this.src=t,this.dest=e,this.opts=s,this.ondrain=()=>t[st](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},te=class extends Mt{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,s){super(t,e,s),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},di=n=>!!n.objectMode,pi=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",V=class extends ee{[v]=!1;[dt]=!1;[F]=[];[C]=[];[k];[P];[B];[et];[G]=!1;[K]=!1;[kt]=!1;[Rt]=!1;[ut]=null;[T]=0;[x]=!1;[pt];[Dt]=!1;[Y]=0;[M]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");di(e)?(this[k]=!0,this[P]=null):pi(e)?(this[P]=e.encoding,this[k]=!1):(this[k]=!1,this[P]=null),this[B]=!!e.async,this[et]=this[P]?new ni(this[P]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[C]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[F]});let{signal:s}=e;s&&(this[pt]=s,s.aborted?this[Qt]():s.addEventListener("abort",()=>this[Qt]()))}get bufferLength(){return this[T]}get encoding(){return this[P]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[k]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[B]}set async(t){this[B]=this[B]||!!t}[Qt](){this[Dt]=!0,this.emit("abort",this[pt]?.reason),this.destroy(this[pt]?.reason)}get aborted(){return this[Dt]}set aborted(t){}write(t,e,s){if(this[Dt])return!1;if(this[G])throw new Error("write after end");if(this[x])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(s=e,e="utf8"),e||(e="utf8");let i=this[B]?mt:li;if(!this[k]&&!Buffer.isBuffer(t)){if(ui(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(fi(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[k]?(this[v]&&this[T]!==0&&this[Ot](!0),this[v]?this.emit("data",t):this[Yt](t),this[T]!==0&&this.emit("readable"),s&&i(s),this[v]):t.length?(typeof t=="string"&&!(e===this[P]&&!this[et]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[P]&&(t=this[et].write(t)),this[v]&&this[T]!==0&&this[Ot](!0),this[v]?this.emit("data",t):this[Yt](t),this[T]!==0&&this.emit("readable"),s&&i(s),this[v]):(this[T]!==0&&this.emit("readable"),s&&i(s),this[v])}read(t){if(this[x])return null;if(this[M]=!1,this[T]===0||t===0||t&&t>this[T])return this[H](),null;this[k]&&(t=null),this[C].length>1&&!this[k]&&(this[C]=[this[P]?this[C].join(""):Buffer.concat(this[C],this[T])]);let e=this[_e](t||null,this[C][0]);return this[H](),e}[_e](t,e){if(this[k])this[Ft]();else{let s=e;t===s.length||t===null?this[Ft]():typeof s=="string"?(this[C][0]=s.slice(t),e=s.slice(0,t),this[T]-=t):(this[C][0]=s.subarray(t),e=s.subarray(0,t),this[T]-=t)}return this.emit("data",e),!this[C].length&&!this[G]&&this.emit("drain"),e}end(t,e,s){return typeof t=="function"&&(s=t,t=void 0),typeof e=="function"&&(s=e,e="utf8"),t!==void 0&&this.write(t,e),s&&this.once("end",s),this[G]=!0,this.writable=!1,(this[v]||!this[dt])&&this[H](),this}[st](){this[x]||(!this[Y]&&!this[F].length&&(this[M]=!0),this[dt]=!1,this[v]=!0,this.emit("resume"),this[C].length?this[Ot]():this[G]?this[H]():this.emit("drain"))}resume(){return this[st]()}pause(){this[v]=!1,this[dt]=!0,this[M]=!1}get destroyed(){return this[x]}get flowing(){return this[v]}get paused(){return this[dt]}[Yt](t){this[k]?this[T]+=1:this[T]+=t.length,this[C].push(t)}[Ft](){return this[k]?this[T]-=1:this[T]-=this[C][0].length,this[C].shift()}[Ot](t=!1){do;while(this[Le](this[Ft]())&&this[C].length);!t&&!this[C].length&&!this[G]&&this.emit("drain")}[Le](t){return this.emit("data",t),this[v]}pipe(t,e){if(this[x])return t;this[M]=!1;let s=this[K];return e=e||{},t===Ne.stdout||t===Ne.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[F].push(e.proxyErrors?new te(this,t,e):new Mt(this,t,e)),this[B]?mt(()=>this[st]()):this[st]()),t}unpipe(t){let e=this[F].find(s=>s.dest===t);e&&(this[F].length===1?(this[v]&&this[Y]===0&&(this[v]=!1),this[F]=[]):this[F].splice(this[F].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let s=super.on(t,e);if(t==="data")this[M]=!1,this[Y]++,!this[F].length&&!this[v]&&this[st]();else if(t==="readable"&&this[T]!==0)super.emit("readable");else if(ci(t)&&this[K])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ut]){let i=e;this[B]?mt(()=>i.call(this,this[ut])):i.call(this,this[ut])}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[Y]=this.listeners("data").length,this[Y]===0&&!this[M]&&!this[F].length&&(this[v]=!1)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Y]=0,!this[M]&&!this[F].length&&(this[v]=!1)),e}get emittedEnd(){return this[K]}[H](){!this[kt]&&!this[K]&&!this[x]&&this[C].length===0&&this[G]&&(this[kt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Rt]&&this.emit("close"),this[kt]=!1)}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==x&&this[x])return!1;if(t==="data")return!this[k]&&!s?!1:this[B]?(mt(()=>this[Jt](s)),!0):this[Jt](s);if(t==="end")return this[We]();if(t==="close"){if(this[Rt]=!0,!this[K]&&!this[x])return!1;let r=super.emit("close");return this.removeAllListeners("close"),r}else if(t==="error"){this[ut]=s,super.emit(Xt,s);let r=!this[pt]||this.listeners("error").length?super.emit("error",s):!1;return this[H](),r}else if(t==="resume"){let r=super.emit("resume");return this[H](),r}else if(t==="finish"||t==="prefinish"){let r=super.emit(t);return this.removeAllListeners(t),r}let i=super.emit(t,...e);return this[H](),i}[Jt](t){for(let s of this[F])s.dest.write(t)===!1&&this.pause();let e=this[M]?!1:super.emit("data",t);return this[H](),e}[We](){return this[K]?!1:(this[K]=!0,this.readable=!1,this[B]?(mt(()=>this[Zt]()),!0):this[Zt]())}[Zt](){if(this[et]){let e=this[et].end();if(e){for(let s of this[F])s.dest.write(e);this[M]||super.emit("data",e)}}for(let e of this[F])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[k]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[k]||(t.dataLength+=s.length)}),await e,t}async concat(){if(this[k])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[P]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(x,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[M]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[G])return e();let r,o,h=c=>{this.off("data",a),this.off("end",l),this.off(x,u),e(),o(c)},a=c=>{this.off("error",h),this.off("end",l),this.off(x,u),this.pause(),r({value:c,done:!!this[G]})},l=()=>{this.off("error",h),this.off("data",a),this.off(x,u),e(),r({done:!0,value:void 0})},u=()=>h(new Error("stream destroyed"));return new Promise((c,d)=>{o=d,r=c,this.once(x,u),this.once("error",h),this.once("end",l),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[M]=!1;let t=!1,e=()=>(this.pause(),this.off(Xt,e),this.off(x,e),this.off("end",e),t=!0,{done:!0,value:void 0}),s=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Xt,e),this.once(x,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[x])return t?this.emit("error",t):this.emit(x),this;this[x]=!0,this[M]=!0,this[C].length=0,this[T]=0;let e=this;return typeof e.close=="function"&&!this[Rt]&&e.close(),t?this.emit("error",t):this.emit(x),this}static get isStream(){return oi}};var vi=Ei.native,wt={lstatSync:wi,readdir:yi,readdirSync:bi,readlinkSync:Si,realpathSync:vi,promises:{lstat:Ci,readdir:Ti,readlink:Ai,realpath:ki}},Ue=n=>!n||n===wt||n===xi?wt:{...wt,...n,promises:{...wt.promises,...n.promises||{}}},$e=/^\\\\\?\\([a-z]:)\\?$/i,Ri=n=>n.replace(/\//g,"\\").replace($e,"$1\\"),Oi=/[\\\/]/,L=0,Ge=1,He=2,U=4,qe=6,Ke=8,X=10,Ve=12,_=15,gt=~_,se=16,je=32,yt=64,j=128,Nt=256,Lt=512,Ie=yt|j|Lt,Fi=1023,ie=n=>n.isFile()?Ke:n.isDirectory()?U:n.isSymbolicLink()?X:n.isCharacterDevice()?He:n.isBlockDevice()?qe:n.isSocket()?Ve:n.isFIFO()?Ge:L,ze=new ft({max:2**12}),bt=n=>{let t=ze.get(n);if(t)return t;let e=n.normalize("NFKD");return ze.set(n,e),e},Be=new ft({max:2**12}),_t=n=>{let t=Be.get(n);if(t)return t;let e=bt(n.toLowerCase());return Be.set(n,e),e},Wt=class extends ft{constructor(){super({max:256})}},ne=class extends ft{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}},Ye=Symbol("PathScurry setAsCwd"),R=class{name;root;roots;parent;nocase;isCWD=!1;#t;#s;get dev(){return this.#s}#n;get mode(){return this.#n}#r;get nlink(){return this.#r}#o;get uid(){return this.#o}#S;get gid(){return this.#S}#w;get rdev(){return this.#w}#c;get blksize(){return this.#c}#h;get ino(){return this.#h}#u;get size(){return this.#u}#f;get blocks(){return this.#f}#a;get atimeMs(){return this.#a}#i;get mtimeMs(){return this.#i}#d;get ctimeMs(){return this.#d}#E;get birthtimeMs(){return this.#E}#b;get atime(){return this.#b}#p;get mtime(){return this.#p}#R;get ctime(){return this.#R}#m;get birthtime(){return this.#m}#C;#T;#g;#y;#x;#A;#e;#_;#M;#k;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=L,s,i,r,o,h){this.name=t,this.#C=r?_t(t):bt(t),this.#e=e&Fi,this.nocase=r,this.roots=i,this.root=s||this,this.#_=o,this.#g=h.fullpath,this.#x=h.relative,this.#A=h.relativePosix,this.parent=h.parent,this.parent?this.#t=this.parent.#t:this.#t=Ue(h.fs)}depth(){return this.#T!==void 0?this.#T:this.parent?this.#T=this.parent.depth()+1:this.#T=0}childrenCache(){return this.#_}resolve(t){if(!t)return this;let e=this.getRootString(t),i=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#N(i):this.#N(i)}#N(t){let e=this;for(let s of t)e=e.child(s);return e}children(){let t=this.#_.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#_.set(this,e),this.#e&=~se,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let s=this.children(),i=this.nocase?_t(t):bt(t);for(let a of s)if(a.#C===i)return a;let r=this.parent?this.sep:"",o=this.#g?this.#g+r+t:void 0,h=this.newChild(t,L,{...e,parent:this,fullpath:o});return this.canReaddir()||(h.#e|=j),s.push(h),h}relative(){if(this.isCWD)return"";if(this.#x!==void 0)return this.#x;let t=this.name,e=this.parent;if(!e)return this.#x=this.name;let s=e.relative();return s+(!s||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#A!==void 0)return this.#A;let t=this.name,e=this.parent;if(!e)return this.#A=this.fullpathPosix();let s=e.relativePosix();return s+(!s||!e.parent?"":"/")+t}fullpath(){if(this.#g!==void 0)return this.#g;let t=this.name,e=this.parent;if(!e)return this.#g=this.name;let i=e.fullpath()+(e.parent?this.sep:"")+t;return this.#g=i}fullpathPosix(){if(this.#y!==void 0)return this.#y;if(this.sep==="/")return this.#y=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#y=`//?/${i}`:this.#y=i}let t=this.parent,e=t.fullpathPosix(),s=e+(!e||!t.parent?"":"/")+this.name;return this.#y=s}isUnknown(){return(this.#e&_)===L}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#e&_)===Ke}isDirectory(){return(this.#e&_)===U}isCharacterDevice(){return(this.#e&_)===He}isBlockDevice(){return(this.#e&_)===qe}isFIFO(){return(this.#e&_)===Ge}isSocket(){return(this.#e&_)===Ve}isSymbolicLink(){return(this.#e&X)===X}lstatCached(){return this.#e&je?this:void 0}readlinkCached(){return this.#M}realpathCached(){return this.#k}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#M)return!0;if(!this.parent)return!1;let t=this.#e&_;return!(t!==L&&t!==X||this.#e&Nt||this.#e&j)}calledReaddir(){return!!(this.#e&se)}isENOENT(){return!!(this.#e&j)}isNamed(t){return this.nocase?this.#C===_t(t):this.#C===bt(t)}async readlink(){let t=this.#M;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#t.promises.readlink(this.fullpath()),s=(await this.parent.realpath())?.resolve(e);if(s)return this.#M=s}catch(e){this.#D(e.code);return}}readlinkSync(){let t=this.#M;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#t.readlinkSync(this.fullpath()),s=this.parent.realpathSync()?.resolve(e);if(s)return this.#M=s}catch(e){this.#D(e.code);return}}#j(t){this.#e|=se;for(let e=t.provisional;es(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let s=this.children();if(this.calledReaddir()){let r=s.slice(0,s.provisional);e?t(null,r):queueMicrotask(()=>t(null,r));return}if(this.#W.push(t),this.#O)return;this.#O=!0;let i=this.fullpath();this.#t.readdir(i,{withFileTypes:!0},(r,o)=>{if(r)this.#I(r.code),s.provisional=0;else{for(let h of o)this.#z(h,s);this.#j(s)}this.#H(s.slice(0,s.provisional))})}#q;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#q)await this.#q;else{let s=()=>{};this.#q=new Promise(i=>s=i);try{for(let i of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#z(i,t);this.#j(t)}catch(i){this.#I(i.code),t.provisional=0}this.#q=void 0,s()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let s of this.#t.readdirSync(e,{withFileTypes:!0}))this.#z(s,t);this.#j(t)}catch(s){this.#I(s.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#e&Ie)return!1;let t=_&this.#e;return t===L||t===U||t===X}shouldWalk(t,e){return(this.#e&U)===U&&!(this.#e&Ie)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#k)return this.#k;if(!((Lt|Nt|j)&this.#e))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#k=this.resolve(t)}catch{this.#P()}}realpathSync(){if(this.#k)return this.#k;if(!((Lt|Nt|j)&this.#e))try{let t=this.#t.realpathSync(this.fullpath());return this.#k=this.resolve(t)}catch{this.#P()}}[Ye](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),s=[],i=this;for(;i&&i.parent;)e.add(i),i.#x=s.join(this.sep),i.#A=s.join("/"),i=i.parent,s.push("..");for(i=t;i&&i.parent&&!e.has(i);)i.#x=void 0,i.#A=void 0,i=i.parent}},Pt=class n extends R{sep="\\";splitSep=Oi;constructor(t,e=L,s,i,r,o,h){super(t,e,s,i,r,o,h)}newChild(t,e=L,s={}){return new n(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return re.parse(t).root}getRoot(t){if(t=Ri(t.toUpperCase()),t===this.root.name)return this.root;for(let[e,s]of Object.entries(this.roots))if(this.sameRoot(t,e))return this.roots[t]=s;return this.roots[t]=new it(t,this).root}sameRoot(t,e=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace($e,"$1\\"),t===e}},jt=class n extends R{splitSep="/";sep="/";constructor(t,e=L,s,i,r,o,h){super(t,e,s,i,r,o,h)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,e=L,s={}){return new n(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}},It=class{root;rootPath;roots;cwd;#t;#s;#n;nocase;#r;constructor(t=process.cwd(),e,s,{nocase:i,childrenCacheSize:r=16*1024,fs:o=wt}={}){this.#r=Ue(o),(t instanceof URL||t.startsWith("file://"))&&(t=gi(t));let h=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(h),this.#t=new Wt,this.#s=new Wt,this.#n=new ne(r);let a=h.substring(this.rootPath.length).split(s);if(a.length===1&&!a[0]&&a.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let l=this.root,u=a.length-1,c=e.sep,d=this.rootPath,f=!1;for(let m of a){let p=u--;l=l.child(m,{relative:new Array(p).fill("..").join(c),relativePosix:new Array(p).fill("..").join("/"),fullpath:d+=(f?"":c)+m}),f=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let r=t.length-1;r>=0;r--){let o=t[r];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let s=this.#t.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpath();return this.#t.set(e,i),i}resolvePosix(...t){let e="";for(let r=t.length-1;r>=0;r--){let o=t[r];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let s=this.#s.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpathPosix();return this.#s.set(e,i),i}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s}=e;if(t.canReaddir()){let i=await t.readdir();return s?i:i.map(r=>r.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0}=e;return t.canReaddir()?s?t.readdirSync():t.readdirSync().map(i=>i.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t.withFileTypes,t=this.cwd);let s=await t.readlink();return e?s:s?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t.withFileTypes,t=this.cwd);let s=t.readlinkSync();return e?s:s?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t.withFileTypes,t=this.cwd);let s=await t.realpath();return e?s:s?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t.withFileTypes,t=this.cwd);let s=t.realpathSync();return e?s:s?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:o}=e,h=[];(!r||r(t))&&h.push(s?t:t.fullpath());let a=new Set,l=(c,d)=>{a.add(c),c.readdirCB((f,m)=>{if(f)return d(f);let p=m.length;if(!p)return d();let w=()=>{--p===0&&d()};for(let g of m)(!r||r(g))&&h.push(s?g:g.fullpath()),i&&g.isSymbolicLink()?g.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(a,o)?l(S,w):w()):g.shouldWalk(a,o)?l(g,w):w()},!0)},u=t;return new Promise((c,d)=>{l(u,f=>{if(f)return d(f);c(h)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:o}=e,h=[];(!r||r(t))&&h.push(s?t:t.fullpath());let a=new Set([t]);for(let l of a){let u=l.readdirSync();for(let c of u){(!r||r(c))&&h.push(s?c:c.fullpath());let d=c;if(c.isSymbolicLink()){if(!(i&&(d=c.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(a,o)&&a.add(d)}}return h}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:o}=e;(!r||r(t))&&(yield s?t:t.fullpath());let h=new Set([t]);for(let a of h){let l=a.readdirSync();for(let u of l){(!r||r(u))&&(yield s?u:u.fullpath());let c=u;if(u.isSymbolicLink()){if(!(i&&(c=u.realpathSync())))continue;c.isUnknown()&&c.lstatSync()}c.shouldWalk(h,o)&&h.add(c)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:o}=e,h=new V({objectMode:!0});(!r||r(t))&&h.write(s?t:t.fullpath());let a=new Set,l=[t],u=0,c=()=>{let d=!1;for(;!d;){let f=l.shift();if(!f){u===0&&h.end();return}u++,a.add(f);let m=(w,g,S=!1)=>{if(w)return h.emit("error",w);if(i&&!S){let E=[];for(let y of g)y.isSymbolicLink()&&E.push(y.realpath().then(b=>b?.isUnknown()?b.lstat():b));if(E.length){Promise.all(E).then(()=>m(null,g,!0));return}}for(let E of g)E&&(!r||r(E))&&(h.write(s?E:E.fullpath())||(d=!0));u--;for(let E of g){let y=E.realpathCached()||E;y.shouldWalk(a,o)&&l.push(y)}d&&!h.flowing?h.once("drain",c):p||c()},p=!0;f.readdirCB(m,!0),p=!1}};return c(),h}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:o}=e,h=new V({objectMode:!0}),a=new Set;(!r||r(t))&&h.write(s?t:t.fullpath());let l=[t],u=0,c=()=>{let d=!1;for(;!d;){let f=l.shift();if(!f){u===0&&h.end();return}u++,a.add(f);let m=f.readdirSync();for(let p of m)(!r||r(p))&&(h.write(s?p:p.fullpath())||(d=!0));u--;for(let p of m){let w=p;if(p.isSymbolicLink()){if(!(i&&(w=p.realpathSync())))continue;w.isUnknown()&&w.lstatSync()}w.shouldWalk(a,o)&&l.push(w)}}d&&!h.flowing&&h.once("drain",c)};return c(),h}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[Ye](e)}},it=class extends It{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,re,"\\",{...e,nocase:s}),this.nocase=s;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(t){return re.parse(t).root.toUpperCase()}newRoot(t){return new Pt(this.rootPath,U,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},rt=class extends It{sep="/";constructor(t=process.cwd(),e={}){let{nocase:s=!1}=e;super(t,mi,"/",{...e,nocase:s}),this.nocase=s}parseRootPath(t){return"/"}newRoot(t){return new jt(this.rootPath,U,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},St=class extends rt{constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,{...e,nocase:s})}},Cr=process.platform==="win32"?Pt:jt,Xe=process.platform==="win32"?it:process.platform==="darwin"?St:rt;var Di=n=>n.length>=1,Mi=n=>n.length>=1,Ni=Symbol.for("nodejs.util.inspect.custom"),nt=class n{#t;#s;#n;length;#r;#o;#S;#w;#c;#h;#u=!0;constructor(t,e,s,i){if(!Di(t))throw new TypeError("empty pattern list");if(!Mi(e))throw new TypeError("empty glob list");if(e.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#s=e,this.#n=s,this.#r=i,this.#n===0){if(this.isUNC()){let[r,o,h,a,...l]=this.#t,[u,c,d,f,...m]=this.#s;l[0]===""&&(l.shift(),m.shift());let p=[r,o,h,a,""].join("/"),w=[u,c,d,f,""].join("/");this.#t=[p,...l],this.#s=[w,...m],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[r,...o]=this.#t,[h,...a]=this.#s;o[0]===""&&(o.shift(),a.shift());let l=r+"/",u=h+"/";this.#t=[l,...o],this.#s=[u,...a],this.length=this.#t.length}}}[Ni](){return"Pattern <"+this.#s.slice(this.#n).join("/")+">"}pattern(){return this.#t[this.#n]}isString(){return typeof this.#t[this.#n]=="string"}isGlobstar(){return this.#t[this.#n]===A}isRegExp(){return this.#t[this.#n]instanceof RegExp}globString(){return this.#S=this.#S||(this.#n===0?this.isAbsolute()?this.#s[0]+this.#s.slice(1).join("/"):this.#s.join("/"):this.#s.slice(this.#n).join("/"))}hasMore(){return this.length>this.#n+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new n(this.#t,this.#s,this.#n+1,this.#r),this.#o.#h=this.#h,this.#o.#c=this.#c,this.#o.#w=this.#w,this.#o):this.#o=null}isUNC(){let t=this.#t;return this.#c!==void 0?this.#c:this.#c=this.#r==="win32"&&this.#n===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3]}isDrive(){let t=this.#t;return this.#w!==void 0?this.#w:this.#w=this.#r==="win32"&&this.#n===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#h!==void 0?this.#h:this.#h=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#n===0?t:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#u)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#u?!1:(this.#u=!1,!0)}};var _i=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ot=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:s,noext:i,noglobstar:r,platform:o=_i}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=o,this.mmopts={dot:!0,nobrace:e,nocase:s,noext:i,noglobstar:r,optimizationLevel:2,platform:o,nocomment:!0,nonegate:!0};for(let h of t)this.add(h)}add(t){let e=new D(t,this.mmopts);for(let s=0;s[t,!!(e&2),!!(e&1)])}},ae=class{store=new Map;add(t,e){if(!t.canReaddir())return;let s=this.store.get(t);s?s.find(i=>i.globString()===e.globString())||s.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}},Et=class n{hasWalkedCache;matches=new he;subwalks=new ae;patterns;follow;dot;opts;constructor(t,e){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new oe}processPatterns(t,e){this.patterns=e;let s=e.map(i=>[t,i]);for(let[i,r]of s){this.hasWalkedCache.storeWalked(i,r);let o=r.root(),h=r.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let c=r.rest();if(c)r=c;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let a,l,u=!1;for(;typeof(a=r.pattern())=="string"&&(l=r.rest());)i=i.resolve(a),r=l,u=!0;if(a=r.pattern(),l=r.rest(),u){if(this.hasWalkedCache.hasWalked(i,r))continue;this.hasWalkedCache.storeWalked(i,r)}if(typeof a=="string"){let c=a===".."||a===""||a===".";this.matches.add(i.resolve(a),h,c);continue}else if(a===A){(!i.isSymbolicLink()||this.follow||r.checkFollowGlobstar())&&this.subwalks.add(i,r);let c=l?.pattern(),d=l?.rest();if(!l||(c===""||c===".")&&!d)this.matches.add(i,h,c===""||c===".");else if(c===".."){let f=i.parent||i;d?this.hasWalkedCache.hasWalked(f,d)||this.subwalks.add(f,d):this.matches.add(f,h,!0)}}else a instanceof RegExp&&this.subwalks.add(i,r)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new n(this.opts,this.hasWalkedCache)}filterEntries(t,e){let s=this.subwalks.get(t),i=this.child();for(let r of e)for(let o of s){let h=o.isAbsolute(),a=o.pattern(),l=o.rest();a===A?i.testGlobstar(r,o,l,h):a instanceof RegExp?i.testRegExp(r,a,l,h):i.testString(r,a,l,h)}return i}testGlobstar(t,e,s,i){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(s&&e.checkFollowGlobstar()?this.subwalks.add(t,s):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),s){let r=s.pattern();if(typeof r=="string"&&r!==".."&&r!==""&&r!==".")this.testString(t,r,s.rest(),i);else if(r===".."){let o=t.parent||t;this.subwalks.add(o,s)}else r instanceof RegExp&&this.testRegExp(t,r,s.rest(),i)}}testRegExp(t,e,s,i){e.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,e,s,i){t.isNamed(e)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}};var Li=(n,t)=>typeof n=="string"?new ot([n],t):Array.isArray(n)?new ot(n,t):n,zt=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#s;#n;signal;maxDepth;includeChildMatches;constructor(t,e,s){if(this.patterns=t,this.path=e,this.opts=s,this.#n=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==!1,(s.ignore||!this.includeChildMatches)&&(this.#s=Li(s.ignore??[],s),!this.includeChildMatches&&typeof this.#s.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#r(t){return this.seen.has(t)||!!this.#s?.ignored?.(t)}#o(t){return!!this.#s?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#t.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#t.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||await t.realpath(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let o=await r.realpath();o&&(o.isUnknown()||this.opts.stat)&&await o.lstat()}return this.matchCheckTest(r,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#r(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||t.realpathSync(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let o=r.realpathSync();o&&(o?.isUnknown()||this.opts.stat)&&o.lstatSync()}return this.matchCheckTest(r,e)}matchFinish(t,e){if(this.#r(t))return;if(!this.includeChildMatches&&this.#s?.add){let r=`${t.relativePosix()}/**`;this.#s.add(r)}let s=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let i=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(s){let r=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(r+i)}else{let r=this.opts.posix?t.relativePosix():t.relative(),o=this.opts.dotRelative&&!r.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(r?o+r+i:"."+i)}}async match(t,e,s){let i=await this.matchCheck(t,s);i&&this.matchFinish(i,e)}matchSync(t,e,s){let i=this.matchCheckSync(t,s);i&&this.matchFinish(i,e)}walkCB(t,e,s){this.signal?.aborted&&s(),this.walkCB2(t,e,new Et(this.opts),s)}walkCB2(t,e,s,i){if(this.#o(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(t,e,s,i));return}s.processPatterns(t,e);let r=1,o=()=>{--r===0&&i()};for(let[h,a,l]of s.matches.entries())this.#r(h)||(r++,this.match(h,a,l).then(()=>o()));for(let h of s.subwalkTargets()){if(this.maxDepth!==1/0&&h.depth()>=this.maxDepth)continue;r++;let a=h.readdirCached();h.calledReaddir()?this.walkCB3(h,a,s,o):h.readdirCB((l,u)=>this.walkCB3(h,u,s,o),!0)}o()}walkCB3(t,e,s,i){s=s.filterEntries(t,e);let r=1,o=()=>{--r===0&&i()};for(let[h,a,l]of s.matches.entries())this.#r(h)||(r++,this.match(h,a,l).then(()=>o()));for(let[h,a]of s.subwalks.entries())r++,this.walkCB2(h,a,s.child(),o);o()}walkCBSync(t,e,s){this.signal?.aborted&&s(),this.walkCB2Sync(t,e,new Et(this.opts),s)}walkCB2Sync(t,e,s,i){if(this.#o(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,s,i));return}s.processPatterns(t,e);let r=1,o=()=>{--r===0&&i()};for(let[h,a,l]of s.matches.entries())this.#r(h)||this.matchSync(h,a,l);for(let h of s.subwalkTargets()){if(this.maxDepth!==1/0&&h.depth()>=this.maxDepth)continue;r++;let a=h.readdirSync();this.walkCB3Sync(h,a,s,o)}o()}walkCB3Sync(t,e,s,i){s=s.filterEntries(t,e);let r=1,o=()=>{--r===0&&i()};for(let[h,a,l]of s.matches.entries())this.#r(h)||this.matchSync(h,a,l);for(let[h,a]of s.subwalks.entries())r++,this.walkCB2Sync(h,a,s.child(),o);o()}},xt=class extends zt{matches=new Set;constructor(t,e,s){super(t,e,s)}matchEmit(t){this.matches.add(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},vt=class extends zt{results;constructor(t,e,s){super(t,e,s),this.results=new V({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var Pi=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",I=class{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;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=Wi(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||Pi,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=e.platform==="win32"?it:e.platform==="darwin"?St:e.platform?rt:Xe;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let s=this.platform==="darwin"||this.platform==="win32",i={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:s,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(a=>new D(a,i)),[o,h]=r.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=o.map((a,l)=>{let u=h[l];if(!u)throw new Error("invalid pattern object");return new nt(a,u,0,this.platform)})}async walk(){return[...await new xt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new xt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new vt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new vt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var le=(n,t={})=>{Array.isArray(n)||(n=[n]);for(let e of n)if(new D(e,t).hasMagic())return!0;return!1};function Bt(n,t={}){return new I(n,t).streamSync()}function Qe(n,t={}){return new I(n,t).stream()}function ts(n,t={}){return new I(n,t).walkSync()}async function Je(n,t={}){return new I(n,t).walk()}function Ut(n,t={}){return new I(n,t).iterateSync()}function es(n,t={}){return new I(n,t).iterate()}var ji=Bt,Ii=Object.assign(Qe,{sync:Bt}),zi=Ut,Bi=Object.assign(es,{sync:Ut}),Ui=Object.assign(ts,{stream:Bt,iterate:Ut}),Ze=Object.assign(Je,{glob:Je,globSync:ts,sync:Ui,globStream:Qe,stream:Ii,globStreamSync:Bt,streamSync:ji,globIterate:es,iterate:Bi,globIterateSync:Ut,iterateSync:zi,Glob:I,hasMagic:le,escape:tt,unescape:W});Ze.glob=Ze;export{I as Glob,ot as Ignore,tt as escape,Ze as glob,es as globIterate,Ut as globIterateSync,Qe as globStream,Bt as globStreamSync,ts as globSync,le as hasMagic,Bi as iterate,zi as iterateSync,Ii as stream,ji as streamSync,Ui as sync,W as unescape}; +//# sourceMappingURL=index.min.js.map diff --git a/node_modules/glob/dist/esm/pattern.js b/node_modules/glob/dist/esm/pattern.js index b41defa10c6a3..2f733da5bf4f9 100644 --- a/node_modules/glob/dist/esm/pattern.js +++ b/node_modules/glob/dist/esm/pattern.js @@ -2,6 +2,7 @@ import { GLOBSTAR } from 'minimatch'; const isPatternList = (pl) => pl.length >= 1; const isGlobList = (gl) => gl.length >= 1; +const customInspect = Symbol.for('nodejs.util.inspect.custom'); /** * An immutable-ish view on an array of glob parts and their parsed * results @@ -77,6 +78,9 @@ export class Pattern { } } } + [customInspect]() { + return 'Pattern <' + this.#globList.slice(this.#index).join('/') + '>'; + } /** * The first entry in the parsed list of patterns */ diff --git a/node_modules/glob/package.json b/node_modules/glob/package.json index 4838947dfc188..03ed19143e0c5 100644 --- a/node_modules/glob/package.json +++ b/node_modules/glob/package.json @@ -2,21 +2,30 @@ "author": "Isaac Z. Schlueter (https://blog.izs.me/)", "name": "glob", "description": "the most correct and second fastest glob implementation in JavaScript", - "version": "10.4.2", + "version": "13.0.6", "type": "module", "tshy": { - "main": true, "exports": { "./package.json": "./package.json", - ".": "./src/index.ts" + "./raw": "./src/index.ts", + ".": { + "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" + } + } } }, - "bin": "./dist/esm/bin.mjs", - "main": "./dist/commonjs/index.js", + "main": "./dist/commonjs/index.min.js", + "module": "./dist/esm/index.min.js", "types": "./dist/commonjs/index.d.ts", "exports": { "./package.json": "./package.json", - ".": { + "./raw": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" @@ -25,11 +34,21 @@ "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } + }, + ".": { + "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-glob.git" + "url": "git@github.com:isaacs/node-glob.git" }, "files": [ "dist" @@ -37,15 +56,14 @@ "scripts": { "preversion": "npm test", "postversion": "npm publish", - "prepublishOnly": "git push origin --follow-tags", - "prepare": "tshy", + "prepublishOnly": "npm run benchclean; git push origin --follow-tags", + "prepare": "tshy && bash scripts/build.sh", "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", + "typedoc": "typedoc", "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", @@ -54,45 +72,27 @@ "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" + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" }, "devDependencies": { - "@types/node": "^20.11.30", - "memfs": "^3.4.13", + "@types/node": "^25.3.0", + "esbuild": "^0.27.3", + "memfs": "^4.50.0", "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" + "prettier": "^3.6.2", + "rimraf": "^6.1.3", + "tap": "^21.6.1", + "tshy": "^3.3.2", + "typedoc": "^0.28.17" }, - "license": "ISC", + "license": "BlueOak-1.0.0", "funding": { "url": "https://github.com/sponsors/isaacs" }, "engines": { - "node": ">=16 || 14 >=14.18" + "node": "18 || 20 || >=22" } } diff --git a/node_modules/hosted-git-info/lib/hosts.js b/node_modules/hosted-git-info/lib/hosts.js index 9a08efd1b2d7e..a1635d3c898fe 100644 --- a/node_modules/hosted-git-info/lib/hosts.js +++ b/node_modules/hosted-git-info/lib/hosts.js @@ -4,7 +4,11 @@ const maybeJoin = (...args) => args.every(arg => arg) ? args.join('') : '' const maybeEncode = (arg) => arg ? encodeURIComponent(arg) : '' -const formatHashFragment = (f) => f.toLowerCase().replace(/^\W+|\/|\W+$/g, '').replace(/\W+/g, '-') +const formatHashFragment = (f) => f.toLowerCase() + .replace(/^\W+/g, '') // strip leading non-characters + .replace(/(? @@ -105,10 +109,8 @@ hosts.gitlab = { 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')}`, + `https://${domain}/api/v4/projects/${maybeEncode(user + '/' + project)}/repository/archive.tar.gz?sha=${maybeEncode(committish || 'HEAD')}`, extract: (url) => { const path = url.pathname.slice(1) if (path.includes('/-/') || path.includes('/archive.tar.gz')) { @@ -196,7 +198,7 @@ hosts.sourcehut = { 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)}`, + `https://${domain}/${user}/${project}${maybeJoin('#', committish)}`, tarballtemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/archive/${maybeEncode(committish) || 'HEAD'}.tar.gz`, bugstemplate: () => null, diff --git a/node_modules/hosted-git-info/lib/index.js b/node_modules/hosted-git-info/lib/index.js index 0c9d0b08c866b..2a7100dcee6e7 100644 --- a/node_modules/hosted-git-info/lib/index.js +++ b/node_modules/hosted-git-info/lib/index.js @@ -7,6 +7,26 @@ const parseUrl = require('./parse-url.js') const cache = new LRUCache({ max: 1000 }) +function unknownHostedUrl (url) { + try { + const { + protocol, + hostname, + pathname, + } = new URL(url) + + if (!hostname) { + return null + } + + const proto = /(?:git\+)http:$/.test(protocol) ? 'http:' : 'https:' + const path = pathname.replace(/\.git$/, '') + return `${proto}//${hostname}${path}` + } catch { + return null + } +} + class GitHost { constructor (type, user, auth, project, committish, defaultRepresentation, opts = {}) { Object.assign(this, GitHost.#gitHosts[type], { @@ -56,6 +76,34 @@ class GitHost { return cache.get(key) } + static fromManifest (manifest, opts = {}) { + if (!manifest || typeof manifest !== 'object') { + return + } + + const r = manifest.repository + // TODO: look into also checking the `bugs`/`homepage` URLs + + const rurl = r && ( + typeof r === 'string' + ? r + : typeof r === 'object' && typeof r.url === 'string' + ? r.url + : null + ) + + if (!rurl) { + throw new Error('no repository') + } + + const info = (rurl && GitHost.fromUrl(rurl.replace(/^git\+/, ''), opts)) || null + if (info) { + return info + } + const unk = unknownHostedUrl(rurl) + return GitHost.fromUrl(unk, opts) || unk + } + static parseUrl (url) { return parseUrl(url) } diff --git a/node_modules/hosted-git-info/lib/parse-url.js b/node_modules/hosted-git-info/lib/parse-url.js index 7d5489c008ab4..1f7d092065228 100644 --- a/node_modules/hosted-git-info/lib/parse-url.js +++ b/node_modules/hosted-git-info/lib/parse-url.js @@ -1,5 +1,3 @@ -const url = require('url') - const lastIndexOfBefore = (str, char, beforeChar) => { const startPosition = str.indexOf(beforeChar) return str.lastIndexOf(char, startPosition > -1 ? startPosition : Infinity) @@ -7,7 +5,7 @@ const lastIndexOfBefore = (str, char, beforeChar) => { const safeUrl = (u) => { try { - return new url.URL(u) + return new URL(u) } catch { // this fn should never throw } @@ -21,20 +19,23 @@ const correctProtocol = (arg, protocols) => { return arg } + if (arg.substr(firstColon, 3) === '://') { + // If arg is given as ://, then this is already a valid URL. + return arg + } + const firstAt = arg.indexOf('@') if (firstAt > -1) { if (firstAt > firstColon) { + // URL has the form of :@. Assume this is a git+ssh URL. return `git+ssh://${arg}` } else { + // URL has the form 'git@github.com:npm/hosted-git-info.git'. return arg } } - const doubleSlash = arg.indexOf('//') - if (doubleSlash === firstColon + 1) { - return arg - } - + // Correct : to :// return `${arg.slice(0, firstColon + 1)}//${arg.slice(firstColon + 1)}` } diff --git a/node_modules/hosted-git-info/package.json b/node_modules/hosted-git-info/package.json index d7eebd474f625..6edff000952c5 100644 --- a/node_modules/hosted-git-info/package.json +++ b/node_modules/hosted-git-info/package.json @@ -1,6 +1,6 @@ { "name": "hosted-git-info", - "version": "7.0.2", + "version": "10.1.1", "description": "Provides metadata and conversions from repository urls for GitHub, Bitbucket and GitLab", "main": "./lib/index.js", "repository": { @@ -21,40 +21,37 @@ "homepage": "https://github.com/npm/hosted-git-info", "scripts": { "posttest": "npm run lint", - "snap": "tap", - "test": "tap", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "test": "node --test './test/**/*.js'", "test:coverage": "tap --coverage-report=html", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "template-oss-apply": "template-oss-apply --force" + "lintfix": "npm run eslint -- --fix", + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test:node20": "node --test test", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'" }, "dependencies": { - "lru-cache": "^10.0.1" + "lru-cache": "^11.1.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.1" + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.1.0" }, "files": [ "bin/", "lib/" ], "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "tap": { - "color": 1, - "coverage": true, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": "true" + "version": "5.1.0", + "publish": "true", + "testRunner": "node:test", + "latestCiVersion": 24, + "updateNpm": false } } diff --git a/node_modules/http-cache-semantics/index.js b/node_modules/http-cache-semantics/index.js index 31fba4860024c..f01e9a16b4781 100644 --- a/node_modules/http-cache-semantics/index.js +++ b/node_modules/http-cache-semantics/index.js @@ -1,5 +1,22 @@ 'use strict'; -// rfc7231 6.1 + +/** + * @typedef {Object} HttpRequest + * @property {Record} headers - Request headers + * @property {string} [method] - HTTP method + * @property {string} [url] - Request URL + */ + +/** + * @typedef {Object} HttpResponse + * @property {Record} headers - Response headers + * @property {number} [status] - HTTP status code + */ + +/** + * Set of default cacheable status codes per RFC 7231 section 6.1. + * @type {Set} + */ const statusCodeCacheableByDefault = new Set([ 200, 203, @@ -15,7 +32,11 @@ const statusCodeCacheableByDefault = new Set([ 501, ]); -// This implementation does not understand partial responses (206) +/** + * Set of HTTP status codes that the cache implementation understands. + * Note: This implementation does not understand partial responses (206). + * @type {Set} + */ const understoodStatuses = new Set([ 200, 203, @@ -33,13 +54,21 @@ const understoodStatuses = new Set([ 501, ]); +/** + * Set of HTTP error status codes. + * @type {Set} + */ const errorStatusCodes = new Set([ 500, 502, - 503, + 503, 504, ]); +/** + * Object representing hop-by-hop headers that should be removed. + * @type {Record} + */ const hopByHopHeaders = { date: true, // included, because we add Age update Date connection: true, @@ -52,6 +81,10 @@ const hopByHopHeaders = { upgrade: true, }; +/** + * Headers that are excluded from revalidation update. + * @type {Record} + */ const excludedFromRevalidationUpdate = { // Since the old body is reused, it doesn't make sense to change properties of the body 'content-length': true, @@ -60,21 +93,37 @@ const excludedFromRevalidationUpdate = { 'content-range': true, }; +/** + * Converts a string to a number or returns zero if the conversion fails. + * @param {string} s - The string to convert. + * @returns {number} The parsed number or 0. + */ function toNumberOrZero(s) { const n = parseInt(s, 10); return isFinite(n) ? n : 0; } -// RFC 5861 +/** + * Determines if the given response is an error response. + * Implements RFC 5861 behavior. + * @param {HttpResponse|undefined} response - The HTTP response object. + * @returns {boolean} true if the response is an error or undefined, false otherwise. + */ function isErrorResponse(response) { // consider undefined response as faulty - if(!response) { - return true + if (!response) { + return true; } return errorStatusCodes.has(response.status); } +/** + * Parses a Cache-Control header string into an object. + * @param {string} [header] - The Cache-Control header value. + * @returns {Record} An object representing Cache-Control directives. + */ function parseCacheControl(header) { + /** @type {Record} */ const cc = {}; if (!header) return cc; @@ -89,6 +138,11 @@ function parseCacheControl(header) { return cc; } +/** + * Formats a Cache-Control directives object into a header string. + * @param {Record} cc - The Cache-Control directives. + * @returns {string|undefined} A formatted Cache-Control header string or undefined if empty. + */ function formatCacheControl(cc) { let parts = []; for (const k in cc) { @@ -102,6 +156,17 @@ function formatCacheControl(cc) { } module.exports = class CachePolicy { + /** + * Creates a new CachePolicy instance. + * @param {HttpRequest} req - Incoming client request. + * @param {HttpResponse} res - Received server response. + * @param {Object} [options={}] - Configuration options. + * @param {boolean} [options.shared=true] - Is the cache shared (a public proxy)? `false` for personal browser caches. + * @param {number} [options.cacheHeuristic=0.1] - Fallback heuristic (age fraction) for cache duration. + * @param {number} [options.immutableMinTimeToLive=86400000] - Minimum TTL for immutable responses in milliseconds. + * @param {boolean} [options.ignoreCargoCult=false] - Detect nonsense cache headers, and override them. + * @param {any} [options._fromObject] - Internal parameter for deserialization. Do not use. + */ constructor( req, res, @@ -123,29 +188,44 @@ module.exports = class CachePolicy { } this._assertRequestHasHeaders(req); + /** @type {number} Timestamp when the response was received */ this._responseTime = this.now(); + /** @type {boolean} Indicates if the cache is shared */ this._isShared = shared !== false; + /** @type {boolean} Indicates if legacy cargo cult directives should be ignored */ + this._ignoreCargoCult = !!ignoreCargoCult; + /** @type {number} Heuristic cache fraction */ this._cacheHeuristic = undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE + /** @type {number} Minimum TTL for immutable responses in ms */ this._immutableMinTtl = undefined !== immutableMinTimeToLive ? immutableMinTimeToLive : 24 * 3600 * 1000; + /** @type {number} HTTP status code */ this._status = 'status' in res ? res.status : 200; + /** @type {Record} Response headers */ this._resHeaders = res.headers; + /** @type {Record} Parsed Cache-Control directives from response */ this._rescc = parseCacheControl(res.headers['cache-control']); + /** @type {string} HTTP method (e.g., GET, POST) */ this._method = 'method' in req ? req.method : 'GET'; + /** @type {string} Request URL */ this._url = req.url; + /** @type {string} Host header from the request */ this._host = req.headers.host; + /** @type {boolean} Whether the request does not include an Authorization header */ this._noAuthorization = !req.headers.authorization; + /** @type {Record|null} Request headers used for Vary matching */ this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used + /** @type {Record} Parsed Cache-Control directives from request */ 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 && + this._ignoreCargoCult && 'pre-check' in this._rescc && 'post-check' in this._rescc ) { @@ -171,10 +251,18 @@ module.exports = class CachePolicy { } } + /** + * You can monkey-patch it for testing. + * @returns {number} Current time in milliseconds. + */ now() { return Date.now(); } + /** + * Determines if the response is storable in a cache. + * @returns {boolean} `false` if can never be cached. + */ 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 !!( @@ -208,62 +296,160 @@ module.exports = class CachePolicy { ); } + /** + * @returns {boolean} true if expiration is explicitly defined. + */ _hasExplicitExpiration() { // 4.2.1 Calculating Freshness Lifetime - return ( + return !!( (this._isShared && this._rescc['s-maxage']) || this._rescc['max-age'] || this._resHeaders.expires ); } + /** + * @param {HttpRequest} req - a request + * @throws {Error} if the headers are missing. + */ _assertRequestHasHeaders(req) { if (!req || !req.headers) { throw Error('Request headers missing'); } } + /** + * Checks if the request matches the cache and can be satisfied from the cache immediately, + * without having to make a request to the server. + * + * This doesn't support `stale-while-revalidate`. See `evaluateRequest()` for a more complete solution. + * + * @param {HttpRequest} req - The new incoming HTTP request. + * @returns {boolean} `true`` if the cached response used to construct this cache policy satisfies the request without revalidation. + */ satisfiesWithoutRevalidation(req) { + const result = this.evaluateRequest(req); + return !result.revalidation; + } + + /** + * @param {{headers: Record, synchronous: boolean}|undefined} revalidation - Revalidation information, if any. + * @returns {{response: {headers: Record}, revalidation: {headers: Record, synchronous: boolean}|undefined}} An object with a cached response headers and revalidation info. + */ + _evaluateRequestHitResult(revalidation) { + return { + response: { + headers: this.responseHeaders(), + }, + revalidation, + }; + } + + /** + * @param {HttpRequest} request - new incoming + * @param {boolean} synchronous - whether revalidation must be synchronous (not s-w-r). + * @returns {{headers: Record, synchronous: boolean}} An object with revalidation headers and a synchronous flag. + */ + _evaluateRequestRevalidation(request, synchronous) { + return { + synchronous, + headers: this.revalidationHeaders(request), + }; + } + + /** + * @param {HttpRequest} request - new incoming + * @returns {{response: undefined, revalidation: {headers: Record, synchronous: boolean}}} An object indicating no cached response and revalidation details. + */ + _evaluateRequestMissResult(request) { + return { + response: undefined, + revalidation: this._evaluateRequestRevalidation(request, true), + }; + } + + /** + * Checks if the given request matches this cache entry, and how the cache can be used to satisfy it. Returns an object with: + * + * ``` + * { + * // If defined, you must send a request to the server. + * revalidation: { + * headers: {}, // HTTP headers to use when sending the revalidation response + * // If true, you MUST wait for a response from the server before using the cache + * // If false, this is stale-while-revalidate. The cache is stale, but you can use it while you update it asynchronously. + * synchronous: bool, + * }, + * // If defined, you can use this cached response. + * response: { + * headers: {}, // Updated cached HTTP headers you must use when responding to the client + * }, + * } + * ``` + * @param {HttpRequest} req - new incoming HTTP request + * @returns {{response: {headers: Record}|undefined, revalidation: {headers: Record, synchronous: boolean}|undefined}} An object containing keys: + * - revalidation: { headers: Record, synchronous: boolean } Set if you should send this to the origin server + * - response: { headers: Record } Set if you can respond to the client with these cached headers + */ + evaluateRequest(req) { this._assertRequestHasHeaders(req); + // In all circumstances, a cache MUST NOT ignore the must-revalidate directive + if (this._rescc['must-revalidate']) { + return this._evaluateRequestMissResult(req); + } + + if (!this._requestMatches(req, false)) { + return this._evaluateRequestMissResult(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; + return this._evaluateRequestMissResult(req); } - if (requestCC['max-age'] && this.age() > requestCC['max-age']) { - return false; + if (requestCC['max-age'] && this.age() > toNumberOrZero(requestCC['max-age'])) { + return this._evaluateRequestMissResult(req); } - if ( - requestCC['min-fresh'] && - this.timeToLive() < 1000 * requestCC['min-fresh'] - ) { - return false; + if (requestCC['min-fresh'] && this.maxAge() - this.age() < toNumberOrZero(requestCC['min-fresh'])) { + return this._evaluateRequestMissResult(req); } // 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; + // If a value is present, then the client is willing to accept a response that has + // exceeded its freshness lifetime by no more than the specified number of seconds + const allowsStaleWithoutRevalidation = 'max-stale' in requestCC && + (true === requestCC['max-stale'] || requestCC['max-stale'] > this.age() - this.maxAge()); + + if (allowsStaleWithoutRevalidation) { + return this._evaluateRequestHitResult(undefined); + } + + if (this.useStaleWhileRevalidate()) { + return this._evaluateRequestHitResult(this._evaluateRequestRevalidation(req, false)); } + + return this._evaluateRequestMissResult(req); } - return this._requestMatches(req, false); + return this._evaluateRequestHitResult(undefined); } + /** + * @param {HttpRequest} req - check if this is for the same cache entry + * @param {boolean} allowHeadMethod - allow a HEAD method to match. + * @returns {boolean} `true` if the request matches. + */ _requestMatches(req, allowHeadMethod) { // The presented effective request URI and that of the stored response match, and - return ( + 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 @@ -275,15 +461,24 @@ module.exports = class CachePolicy { ); } + /** + * Determines whether storing authenticated responses is allowed. + * @returns {boolean} `true` if allowed. + */ _allowsStoringAuthenticated() { - // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. - return ( + // 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'] ); } + /** + * Checks whether the Vary header in the response matches the new request. + * @param {HttpRequest} req - incoming HTTP request + * @returns {boolean} `true` if the vary headers match. + */ _varyMatches(req) { if (!this._resHeaders.vary) { return true; @@ -304,7 +499,13 @@ module.exports = class CachePolicy { return true; } + /** + * Creates a copy of the given headers without any hop-by-hop headers. + * @param {Record} inHeaders - old headers from the cached response + * @returns {Record} A new headers object without hop-by-hop headers. + */ _copyWithoutHopByHopHeaders(inHeaders) { + /** @type {Record} */ const headers = {}; for (const name in inHeaders) { if (hopByHopHeaders[name]) continue; @@ -330,6 +531,11 @@ module.exports = class CachePolicy { return headers; } + /** + * Returns the response headers adjusted for serving the cached response. + * Removes hop-by-hop headers and updates the Age and Date headers. + * @returns {Record} The adjusted response headers. + */ responseHeaders() { const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); const age = this.age(); @@ -351,8 +557,8 @@ module.exports = class CachePolicy { } /** - * Value of the Date response header or current time if Date was invalid - * @return timestamp + * Returns the Date header value from the response or the current time if invalid. + * @returns {number} Timestamp (in milliseconds) representing the Date header or response time. */ date() { const serverDate = Date.parse(this._resHeaders.date); @@ -365,8 +571,7 @@ module.exports = class CachePolicy { /** * Value of the Age header, in seconds, updated for the current time. * May be fractional. - * - * @return Number + * @returns {number} The age in seconds. */ age() { let age = this._ageValue(); @@ -375,16 +580,21 @@ module.exports = class CachePolicy { return age + residentTime; } + /** + * @returns {number} The Age header value as a number. + */ _ageValue() { return toNumberOrZero(this._resHeaders.age); } /** - * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. + * Possibly outdated 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 + * Returns the maximum age (freshness lifetime) of the response in seconds. + * @returns {number} The max-age value in seconds. */ maxAge() { if (!this.storable() || this._rescc['no-cache']) { @@ -446,29 +656,57 @@ module.exports = class CachePolicy { return defaultMinTtl; } + /** + * Remaining time this cache entry may be useful for, in *milliseconds*. + * You can use this as an expiration time for your cache storage. + * + * Prefer this method over `maxAge()`, because it includes other factors like `age` and `stale-while-revalidate`. + * @returns {number} Time-to-live in milliseconds. + */ 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; + return Math.round(Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000); } + /** + * If true, this cache entry is past its expiration date. + * Note that stale cache may be useful sometimes, see `evaluateRequest()`. + * @returns {boolean} `false` doesn't mean it's fresh nor usable + */ stale() { return this.maxAge() <= this.age(); } + /** + * @returns {boolean} `true` if `stale-if-error` condition allows use of a stale response. + */ _useStaleIfError() { return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); } + /** See `evaluateRequest()` for a more complete solution + * @returns {boolean} `true` if `stale-while-revalidate` is currently allowed. + */ useStaleWhileRevalidate() { - return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); + const swr = toNumberOrZero(this._rescc['stale-while-revalidate']); + return swr > 0 && this.maxAge() + swr > this.age(); } + /** + * Creates a `CachePolicy` instance from a serialized object. + * @param {Object} obj - The serialized object. + * @returns {CachePolicy} A new CachePolicy instance. + */ static fromObject(obj) { return new this(undefined, undefined, { _fromObject: obj }); } + /** + * @param {any} obj - The serialized object. + * @throws {Error} If already initialized or if the object is invalid. + */ _fromObject(obj) { if (this._responseTime) throw Error('Reinitialized'); if (!obj || obj.v !== 1) throw Error('Invalid serialization'); @@ -478,6 +716,7 @@ module.exports = class CachePolicy { this._cacheHeuristic = obj.ch; this._immutableMinTtl = obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; + this._ignoreCargoCult = !!obj.icc; this._status = obj.st; this._resHeaders = obj.resh; this._rescc = obj.rescc; @@ -489,6 +728,10 @@ module.exports = class CachePolicy { this._reqcc = obj.reqcc; } + /** + * Serializes the `CachePolicy` instance into a JSON-serializable object. + * @returns {Object} The serialized object. + */ toObject() { return { v: 1, @@ -496,6 +739,7 @@ module.exports = class CachePolicy { sh: this._isShared, ch: this._cacheHeuristic, imm: this._immutableMinTtl, + icc: this._ignoreCargoCult, st: this._status, resh: this._resHeaders, rescc: this._rescc, @@ -514,6 +758,8 @@ module.exports = class CachePolicy { * * Hop by hop headers are always stripped. * Revalidation headers may be added or removed, depending on request. + * @param {HttpRequest} incomingReq - The incoming HTTP request. + * @returns {Record} The headers for the revalidation request. */ revalidationHeaders(incomingReq) { this._assertRequestHasHeaders(incomingReq); @@ -578,17 +824,22 @@ module.exports = class CachePolicy { * 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} + * @param {HttpRequest} request - The latest HTTP request asking for the cached entry. + * @param {HttpResponse} response - The latest revalidation HTTP response from the origin server. + * @returns {{policy: CachePolicy, modified: boolean, matches: boolean}} The updated policy and modification status. + * @throws {Error} If the response headers are missing. */ revalidatedPolicy(request, response) { this._assertRequestHasHeaders(request); - if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful + + if (this._useStaleIfError() && isErrorResponse(response)) { return { - modified: false, - matches: false, - policy: this, + policy: this, + modified: false, + matches: true, }; } + if (!response || !response.headers) { throw Error('Response headers missing'); } @@ -635,9 +886,16 @@ module.exports = class CachePolicy { } } + const optionsCopy = { + shared: this._isShared, + cacheHeuristic: this._cacheHeuristic, + immutableMinTimeToLive: this._immutableMinTtl, + ignoreCargoCult: this._ignoreCargoCult, + }; + if (!matches) { return { - policy: new this.constructor(request, response), + policy: new this.constructor(request, response, optionsCopy), // 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. @@ -662,11 +920,7 @@ module.exports = class CachePolicy { headers, }); return { - policy: new this.constructor(request, newResponse, { - shared: this._isShared, - cacheHeuristic: this._cacheHeuristic, - immutableMinTimeToLive: this._immutableMinTtl, - }), + policy: new this.constructor(request, newResponse, optionsCopy), modified: false, matches: true, }; diff --git a/node_modules/http-cache-semantics/package.json b/node_modules/http-cache-semantics/package.json index defbb045a6383..d45dfa1274e0d 100644 --- a/node_modules/http-cache-semantics/package.json +++ b/node_modules/http-cache-semantics/package.json @@ -1,18 +1,22 @@ { "name": "http-cache-semantics", - "version": "4.1.1", + "version": "4.2.0", "description": "Parses Cache-Control and other headers. Helps building correct HTTP caches and proxies", - "repository": "https://github.com/kornelski/http-cache-semantics.git", + "repository": { + "type": "git", + "url": "git+https://github.com/kornelski/http-cache-semantics.git" + }, "main": "index.js", + "types": "index.js", "scripts": { "test": "mocha" }, "files": [ "index.js" ], - "author": "Kornel Lesiński (https://kornel.ski/)", + "author": "Kornel Lesiński (https://kornel.ski/)", "license": "BSD-2-Clause", "devDependencies": { - "mocha": "^10.0" + "mocha": "^11.0" } } diff --git a/node_modules/http-proxy-agent/dist/index.js b/node_modules/http-proxy-agent/dist/index.js deleted file mode 100644 index fb2751c226431..0000000000000 --- a/node_modules/http-proxy-agent/dist/index.js +++ /dev/null @@ -1,148 +0,0 @@ -"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 \ No newline at end of file diff --git a/node_modules/http-proxy-agent/package.json b/node_modules/http-proxy-agent/package.json deleted file mode 100644 index a53940a3d88a3..0000000000000 --- a/node_modules/http-proxy-agent/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "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" - } -} \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/index.js b/node_modules/https-proxy-agent/dist/index.js deleted file mode 100644 index 0c91722035f07..0000000000000 --- a/node_modules/https-proxy-agent/dist/index.js +++ /dev/null @@ -1,175 +0,0 @@ -"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'); -/** - * 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); - const servername = this.connectOpts.servername || this.connectOpts.host; - socket = tls.connect({ - ...this.connectOpts, - servername, - }); - } - 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'); - const servername = opts.servername || opts.host; - return tls.connect({ - ...omit(opts, 'host', 'path', 'port'), - socket, - servername, - }); - } - 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 \ No newline at end of file diff --git a/node_modules/https-proxy-agent/package.json b/node_modules/https-proxy-agent/package.json deleted file mode 100644 index 3c793b769dc5d..0000000000000 --- a/node_modules/https-proxy-agent/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "https-proxy-agent", - "version": "7.0.5", - "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.0.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" - } -} \ No newline at end of file diff --git a/node_modules/iconv-lite/encodings/dbcs-codec.js b/node_modules/iconv-lite/encodings/dbcs-codec.js index fa839170367b2..bfec7f2ef9071 100644 --- a/node_modules/iconv-lite/encodings/dbcs-codec.js +++ b/node_modules/iconv-lite/encodings/dbcs-codec.js @@ -1,597 +1,532 @@ -"use strict"; -var Buffer = require("safer-buffer").Buffer; +"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; +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; +var UNASSIGNED = -1 +var GB18030_CODE = -2 +var SEQ_START = -10 +var NODE_START = -1000 +var UNASSIGNED_NODE = new Array(0x100) +var 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; - } - } - } +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") } - } - 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; + 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 } + } } - - // 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.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) - 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); + // 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; +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._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); +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 (code >= 0xD800 && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++) + if (codeTrail >= 0xDC00 && 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 (code > 0x0FF0 && 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._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._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); +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 } } + } - // 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; + // 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; - } +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; + } + 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; +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; - } +DBCSEncoder.prototype.write = function (str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)) + var leadSurrogate = this.leadSurrogate + var seqObj = this.seqObj + var nextChar = -1 + var i = 0; var 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; - } - - } + // 1. Handle surrogates. + if (uCode >= 0xD800 && 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 if (leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. - leadSurrogate = -1; + } 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; + // 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. } - 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; - } - } + } + 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; - } + // 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); + 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; +DBCSEncoder.prototype.end = function () { + if (this.leadSurrogate === -1 && this.seqObj === undefined) { return } // All clean. Most often case. + + var newBuf = Buffer.alloc(10); var 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); + 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; - +DBCSEncoder.prototype.findIdx = findIdx // == Decoder ================================================================== -function DBCSDecoder(options, codec) { - // Decoder state - this.nodeIdx = 0; - this.prevBytes = []; +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; + // 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; +DBCSDecoder.prototype.write = function (buf) { + var newBuf = Buffer.alloc(buf.length * 2) + var nodeIdx = this.nodeIdx + var prevBytes = this.prevBytes; var prevOffset = this.prevBytes.length + var seqStart = -this.prevBytes.length // idx of the start of current parsed sequence. + var 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)); + 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'); + return newBuf.slice(0, j).toString("ucs2") } -DBCSDecoder.prototype.end = function() { - var ret = ''; +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); + // 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); - } + // Parse remaining as usual. + this.prevBytes = [] + this.nodeIdx = 0 + if (bytesArr.length > 0) { ret += this.write(bytesArr) } + } - this.prevBytes = []; - this.nodeIdx = 0; - return ret; + 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; +function findIdx (table, val) { + if (table[0] > val) { return -1 } + + var l = 0; var 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 } - diff --git a/node_modules/iconv-lite/encodings/dbcs-data.js b/node_modules/iconv-lite/encodings/dbcs-data.js index 0d17e5821b3df..a3858d4cf3625 100644 --- a/node_modules/iconv-lite/encodings/dbcs-data.js +++ b/node_modules/iconv-lite/encodings/dbcs-data.js @@ -1,188 +1,185 @@ -"use strict"; +"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', -}; + + // == 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" +} diff --git a/node_modules/iconv-lite/encodings/index.js b/node_modules/iconv-lite/encodings/index.js index d95c2441151a9..9d90e3cac6b09 100644 --- a/node_modules/iconv-lite/encodings/index.js +++ b/node_modules/iconv-lite/encodings/index.js @@ -1,23 +1,23 @@ -"use strict"; +"use strict" + +var mergeModules = require("../lib/helpers/merge-exports") // 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"), -]; + 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]; + var module = modules[i] + mergeModules(exports, module) } diff --git a/node_modules/iconv-lite/encodings/internal.js b/node_modules/iconv-lite/encodings/internal.js index dc1074f04f11a..4e5c3ff25ac15 100644 --- a/node_modules/iconv-lite/encodings/internal.js +++ b/node_modules/iconv-lite/encodings/internal.js @@ -1,198 +1,218 @@ -"use strict"; -var Buffer = require("safer-buffer").Buffer; +"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; - } - } -} + // Encodings + utf8: { type: "_internal", bomAware: true }, + cesu8: { type: "_internal", bomAware: true }, + unicode11utf8: "utf8", -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; + ucs2: { type: "_internal", bomAware: true }, + utf16le: "ucs2", -//------------------------------------------------------------------------------ + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = require('string_decoder').StringDecoder; + // Codec. + _internal: InternalCodec +} -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; +// ------------------------------------------------------------------------------ +function InternalCodec (codecOptions, iconv) { + this.enc = codecOptions.encodingName + this.bomAware = codecOptions.bomAware -function InternalDecoder(options, codec) { - this.decoder = new StringDecoder(codec.enc); -} + if (this.enc === "base64") { this.encoder = InternalEncoderBase64 } else if (this.enc === "utf8") { this.encoder = InternalEncoderUtf8 } else if (this.enc === "cesu8") { + this.enc = "utf8" // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8 -InternalDecoder.prototype.write = function(buf) { - if (!Buffer.isBuffer(buf)) { - buf = Buffer.from(buf); + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from("eda0bdedb2a9", "hex").toString() !== "💩") { + this.decoder = InternalDecoderCesu8 + this.defaultCharUnicode = iconv.defaultCharUnicode } + } +} - return this.decoder.write(buf); +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 + +function InternalDecoder (options, codec) { + this.decoder = new StringDecoder(codec.enc) } -InternalDecoder.prototype.end = function() { - return this.decoder.end(); +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; +function InternalEncoder (options, codec) { + this.enc = codec.enc } -InternalEncoder.prototype.write = function(str) { - return Buffer.from(str, this.enc); +InternalEncoder.prototype.write = function (str) { + return Buffer.from(str, this.enc) } -InternalEncoder.prototype.end = function() { +InternalEncoder.prototype.end = function () { } - -//------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------ // Except base64 encoder, which must keep its state. -function InternalEncoderBase64(options, codec) { - this.prevStr = ''; +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); +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"); + return Buffer.from(str, "base64") } -InternalEncoderBase64.prototype.end = function() { - return Buffer.from(this.prevStr, "base64"); +InternalEncoderBase64.prototype.end = function () { + return Buffer.from(this.prevStr, "base64") } - -//------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------ // CESU-8 encoder is also special. -function InternalEncoderCesu8(options, codec) { +function InternalEncoderCesu8 (options, codec) { +} + +InternalEncoderCesu8.prototype.write = function (str) { + var buf = Buffer.alloc(str.length * 3); var 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.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); +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; var contBytes = this.contBytes; var accBytes = this.accBytes + var 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 + } } - return buf.slice(0, bufIdx); + } + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes + return res } -InternalEncoderCesu8.prototype.end = function() { +InternalDecoderCesu8.prototype.end = function () { + var res = 0 + if (this.contBytes > 0) { res += this.defaultCharUnicode } + return res } -//------------------------------------------------------------------------------ -// CESU-8 decoder is not implemented in Node v4.0+ +// ------------------------------------------------------------------------------ +// check the chunk boundaries for surrogate pair -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; - } - } +function InternalEncoderUtf8 (options, codec) { + this.highSurrogate = "" +} + +InternalEncoderUtf8.prototype.write = function (str) { + if (this.highSurrogate) { + str = this.highSurrogate + str + this.highSurrogate = "" + } + + if (str.length > 0) { + var charCode = str.charCodeAt(str.length - 1) + if (charCode >= 0xd800 && charCode < 0xdc00) { + this.highSurrogate = str[str.length - 1] + str = str.slice(0, str.length - 1) } - this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; - return res; + } + + return Buffer.from(str, this.enc) } -InternalDecoderCesu8.prototype.end = function() { - var res = 0; - if (this.contBytes > 0) - res += this.defaultCharUnicode; - return res; +InternalEncoderUtf8.prototype.end = function () { + if (this.highSurrogate) { + var str = this.highSurrogate + this.highSurrogate = "" + return Buffer.from(str, this.enc) + } } diff --git a/node_modules/iconv-lite/encodings/sbcs-codec.js b/node_modules/iconv-lite/encodings/sbcs-codec.js index abac5ffaac97d..0e2fc924e1d40 100644 --- a/node_modules/iconv-lite/encodings/sbcs-codec.js +++ b/node_modules/iconv-lite/encodings/sbcs-codec.js @@ -1,72 +1,75 @@ -"use strict"; -var Buffer = require("safer-buffer").Buffer; +"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; - } +// correspond to encoded bytes (if 128 - then lower half is ASCII). - this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); - - // Encoding buffer. - var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); +exports._sbcs = SBCSCodec +function SBCSCodec (codecOptions, iconv) { + if (!codecOptions) { + throw new Error("SBCS codec is called without the data.") + } - for (var i = 0; i < codecOptions.chars.length; i++) - encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + // 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)") + } - this.encodeBuf = encodeBuf; -} + 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") -SBCSCodec.prototype.encoder = SBCSEncoder; -SBCSCodec.prototype.decoder = SBCSDecoder; + // 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 + } -function SBCSEncoder(options, codec) { - this.encodeBuf = codec.encodeBuf; + this.encodeBuf = 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; +SBCSCodec.prototype.encoder = SBCSEncoder +SBCSCodec.prototype.decoder = SBCSDecoder + +function SBCSEncoder (options, codec) { + this.encodeBuf = codec.encodeBuf } -SBCSEncoder.prototype.end = function() { +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; +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.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; var 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() { +SBCSDecoder.prototype.end = function () { } diff --git a/node_modules/iconv-lite/encodings/sbcs-data.js b/node_modules/iconv-lite/encodings/sbcs-data.js index 066f904e5f1d3..d8f8e1729e6af 100644 --- a/node_modules/iconv-lite/encodings/sbcs-data.js +++ b/node_modules/iconv-lite/encodings/sbcs-data.js @@ -1,179 +1,178 @@ -"use strict"; +"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", -}; - + // 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" +} diff --git a/node_modules/iconv-lite/encodings/utf16.js b/node_modules/iconv-lite/encodings/utf16.js index 97d066925bbd5..ae60d98e30514 100644 --- a/node_modules/iconv-lite/encodings/utf16.js +++ b/node_modules/iconv-lite/encodings/utf16.js @@ -1,70 +1,66 @@ -"use strict"; -var Buffer = require("safer-buffer").Buffer; +"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() { +exports.utf16be = Utf16BECodec +function Utf16BECodec () { } -Utf16BECodec.prototype.encoder = Utf16BEEncoder; -Utf16BECodec.prototype.decoder = Utf16BEDecoder; -Utf16BECodec.prototype.bomAware = true; - +Utf16BECodec.prototype.encoder = Utf16BEEncoder +Utf16BECodec.prototype.decoder = Utf16BEDecoder +Utf16BECodec.prototype.bomAware = true // -- Encoding -function Utf16BEEncoder() { +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.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() { +Utf16BEEncoder.prototype.end = function () { } - // -- Decoding -function Utf16BEDecoder() { - this.overflowByte = -1; +function Utf16BEDecoder () { + this.overflowByte = -1 } -Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) - return ''; +Utf16BEDecoder.prototype.write = function (buf) { + if (buf.length == 0) { return "" } - var buf2 = Buffer.alloc(buf.length + 1), - i = 0, j = 0; + var buf2 = Buffer.alloc(buf.length + 1) + var i = 0; var j = 0 - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i = 1; j = 2; - } + 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]; - } + 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; + this.overflowByte = (i == buf.length - 1) ? buf[buf.length - 1] : -1 - return buf2.slice(0, j).toString('ucs2'); + return buf2.slice(0, j).toString("ucs2") } -Utf16BEDecoder.prototype.end = function() { - this.overflowByte = -1; +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. @@ -73,125 +69,119 @@ Utf16BEDecoder.prototype.end = function() { // Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). -exports.utf16 = Utf16Codec; -function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; +exports.utf16 = Utf16Codec +function Utf16Codec (codecOptions, iconv) { + this.iconv = iconv } -Utf16Codec.prototype.encoder = Utf16Encoder; -Utf16Codec.prototype.decoder = Utf16Decoder; - +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); +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.write = function (str) { + return this.encoder.write(str) } -Utf16Encoder.prototype.end = function() { - return this.encoder.end(); +Utf16Encoder.prototype.end = function () { + return this.encoder.end() } - // -- Decoding -function Utf16Decoder(options, codec) { - this.decoder = null; - this.initialBufs = []; - this.initialBufsLen = 0; +function Utf16Decoder (options, codec) { + this.decoder = null + this.initialBufs = [] + this.initialBufsLen = 0 - this.options = options || {}; - this.iconv = codec.iconv; + 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; - } +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 "" } - return this.decoder.write(buf); + // 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); +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 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; + var trail = this.decoder.end() + if (trail) { resStr += trail } - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } - return this.decoder.end(); + 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; - } - } +function detectEncoding (bufs, defaultEncoding) { + var b = [] + var charsProcessed = 0 + // Number of ASCII chars when decoded as LE or BE. + var asciiCharsLE = 0 + var asciiCharsBE = 0 + + outerLoop: + 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" } - } - // 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'; + if (b[0] === 0 && b[1] !== 0) asciiCharsBE++ + if (b[0] !== 0 && b[1] === 0) asciiCharsLE++ - // Couldn't decide (likely all zeros or not enough data). - return defaultEncoding || 'utf-16le'; -} + b.length = 0 + charsProcessed++ + if (charsProcessed >= 100) { + break outerLoop + } + } + } + } + // 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" +} diff --git a/node_modules/iconv-lite/encodings/utf32.js b/node_modules/iconv-lite/encodings/utf32.js index 2fa900a12eb35..723178937a3a7 100644 --- a/node_modules/iconv-lite/encodings/utf32.js +++ b/node_modules/iconv-lite/encodings/utf32.js @@ -1,186 +1,176 @@ -'use strict'; +"use strict" -var Buffer = require('safer-buffer').Buffer; +var Buffer = require("safer-buffer").Buffer // == UTF32-LE/BE codec. ========================================================== -exports._utf32 = Utf32Codec; +exports._utf32 = Utf32Codec -function Utf32Codec(codecOptions, iconv) { - this.iconv = iconv; - this.bomAware = true; - this.isLE = codecOptions.isLE; +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 }; +exports.utf32le = { type: "_utf32", isLE: true } +exports.utf32be = { type: "_utf32", isLE: false } // Aliases -exports.ucs4le = 'utf32le'; -exports.ucs4be = 'utf32be'; +exports.ucs4le = "utf32le" +exports.ucs4be = "utf32be" -Utf32Codec.prototype.encoder = Utf32Encoder; -Utf32Codec.prototype.decoder = Utf32Decoder; +Utf32Codec.prototype.encoder = Utf32Encoder +Utf32Codec.prototype.decoder = Utf32Decoder // -- Encoding -function Utf32Encoder(options, codec) { - this.isLE = codec.isLE; - this.highSurrogate = 0; +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; - } - } +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 = (code >= 0xD800 && code < 0xDC00) + var isLowSurrogate = (code >= 0xDC00 && 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 (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); + if (offset < dst.length) { dst = dst.slice(0, offset) } - return dst; -}; + return dst +} -Utf32Encoder.prototype.end = function() { - // Treat any leftover high surrogate as a semi-valid independent character. - if (!this.highSurrogate) - return; +Utf32Encoder.prototype.end = function () { + // Treat any leftover high surrogate as a semi-valid independent character. + if (!this.highSurrogate) { return } - var buf = Buffer.alloc(4); + var buf = Buffer.alloc(4) - if (this.isLE) - buf.writeUInt32LE(this.highSurrogate, 0); - else - buf.writeUInt32BE(this.highSurrogate, 0); + if (this.isLE) { buf.writeUInt32LE(this.highSurrogate, 0) } else { buf.writeUInt32BE(this.highSurrogate, 0) } - this.highSurrogate = 0; + this.highSurrogate = 0 - return buf; -}; + return buf +} // -- Decoding -function Utf32Decoder(options, codec) { - this.isLE = codec.isLE; - this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0); - this.overflow = []; +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); - } +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); + } + + // 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]); - } + // Keep overflowing bytes. + for (; i < src.length; i++) { + overflow.push(src[i]) + } - return dst.slice(0, offset).toString('ucs2'); -}; + 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; - } +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; + // Ephemeral Planes: Write high surrogate. + if (codepoint >= 0x10000) { + codepoint -= 0x10000 - var high = 0xD800 | (codepoint >> 10); - dst[offset++] = high & 0xff; - dst[offset++] = high >> 8; + var high = 0xD800 | (codepoint >> 10) + dst[offset++] = high & 0xff + dst[offset++] = high >> 8 - // Low surrogate is written below. - var codepoint = 0xDC00 | (codepoint & 0x3FF); - } + // Low surrogate is written below. + var codepoint = 0xDC00 | (codepoint & 0x3FF) + } - // Write BMP char or low surrogate. - dst[offset++] = codepoint & 0xff; - dst[offset++] = codepoint >> 8; + // Write BMP char or low surrogate. + dst[offset++] = codepoint & 0xff + dst[offset++] = codepoint >> 8 - return offset; + return offset }; -Utf32Decoder.prototype.end = function() { - this.overflow.length = 0; -}; +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. @@ -189,131 +179,129 @@ Utf32Decoder.prototype.end = function() { // Encoder prepends BOM (which can be overridden with (addBOM: false}). -exports.utf32 = Utf32AutoCodec; -exports.ucs4 = 'utf32'; +exports.utf32 = Utf32AutoCodec +exports.ucs4 = "utf32" -function Utf32AutoCodec(options, iconv) { - this.iconv = iconv; +function Utf32AutoCodec (options, iconv) { + this.iconv = iconv } -Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder; -Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder; +Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder +Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder // -- Encoding -function Utf32AutoEncoder(options, codec) { - options = options || {}; +function Utf32AutoEncoder (options, codec) { + options = options || {} - if (options.addBOM === undefined) - options.addBOM = true; + if (options.addBOM === undefined) { + options.addBOM = true + } - this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options); + this.encoder = codec.iconv.getEncoder(options.defaultEncoding || "utf-32le", options) } -Utf32AutoEncoder.prototype.write = function(str) { - return this.encoder.write(str); -}; +Utf32AutoEncoder.prototype.write = function (str) { + return this.encoder.write(str) +} -Utf32AutoEncoder.prototype.end = function() { - return this.encoder.end(); -}; +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; +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; +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 ''; + 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); + // 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]); + 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; - } + this.initialBufs.length = this.initialBufsLen = 0 + return resStr + } - return this.decoder.write(buf); -}; + 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); +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 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; + var trail = this.decoder.end() + if (trail) { resStr += trail } - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } + this.initialBufs.length = this.initialBufsLen = 0 + return resStr + } - return this.decoder.end(); -}; + return this.decoder.end() +} + +function detectEncoding (bufs, defaultEncoding) { + var b = [] + var charsProcessed = 0 + var invalidLE = 0; var invalidBE = 0 // Number of invalid chars when decoded as LE or BE. + var bmpCharsLE = 0; var bmpCharsBE = 0 // Number of BMP chars when decoded as LE or BE. + + outerLoop: + 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++ -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; - } - } + if (charsProcessed >= 100) { + break outerLoop } + } } + } - // Make decisions. - if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return 'utf-32be'; - if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return 'utf-32le'; + // 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'; + // Couldn't decide (likely all zeros or not enough data). + return defaultEncoding || "utf-32le" } diff --git a/node_modules/iconv-lite/encodings/utf7.js b/node_modules/iconv-lite/encodings/utf7.js index eacae34d5f80d..fe72a9d9b52b1 100644 --- a/node_modules/iconv-lite/encodings/utf7.js +++ b/node_modules/iconv-lite/encodings/utf7.js @@ -1,122 +1,122 @@ -"use strict"; -var Buffer = require("safer-buffer").Buffer; +"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; +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; - +Utf7Codec.prototype.encoder = Utf7Encoder +Utf7Codec.prototype.decoder = Utf7Decoder +Utf7Codec.prototype.bomAware = true // -- Encoding -var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; +// Why scape ()?./? +// eslint-disable-next-line no-useless-escape +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g -function Utf7Encoder(options, codec) { - this.iconv = codec.iconv; +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.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() { +Utf7Encoder.prototype.end = function () { } - // -- Decoding -function Utf7Decoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; +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 = ''; - } +// Why scape /? +// eslint-disable-next-line no-useless-escape +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) +var minusChar = "-".charCodeAt(0) +var andChar = "&".charCodeAt(0) + +Utf7Decoder.prototype.write = function (buf) { + var res = ""; var lastI = 0 + var inBase64 = this.inBase64 + var 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"); + 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); + 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"); - } + res += this.iconv.decode(Buffer.from(b64str, "base64"), "utf16-be") + } - this.inBase64 = inBase64; - this.base64Accum = base64Accum; + this.inBase64 = inBase64 + this.base64Accum = base64Accum - return res; + 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"); +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; + 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: @@ -128,163 +128,156 @@ Utf7Decoder.prototype.end = function() { // * String must end in non-shifted position. // * "-&" while in base64 is not allowed. - -exports.utf7imap = Utf7IMAPCodec; -function Utf7IMAPCodec(codecOptions, iconv) { - this.iconv = iconv; +exports.utf7imap = Utf7IMAPCodec +function Utf7IMAPCodec (codecOptions, iconv) { + this.iconv = iconv }; -Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; -Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; -Utf7IMAPCodec.prototype.bomAware = true; - +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; +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; - } - } +Utf7IMAPEncoder.prototype.write = function (str) { + var inBase64 = this.inBase64 + var base64Accum = this.base64Accum + var base64AccumIdx = this.base64AccumIdx + var buf = Buffer.alloc(str.length * 5 + 10); var bufIdx = 0 + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i) + if (uChar >= 0x20 && 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; + this.inBase64 = inBase64 + this.base64AccumIdx = base64AccumIdx - return buf.slice(0, bufIdx); + 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; +Utf7IMAPEncoder.prototype.end = function () { + var buf = Buffer.alloc(10); var 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 } - return buf.slice(0, bufIdx); -} + 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 = ''; +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 = ''; - } +var base64IMAPChars = base64Chars.slice() +base64IMAPChars[",".charCodeAt(0)] = true + +Utf7IMAPDecoder.prototype.write = function (buf) { + var res = ""; var lastI = 0 + var inBase64 = this.inBase64 + var 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 (!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, '/'); + if (buf[i] != minusChar) // Minus may be absorbed after base64. + { i-- } - 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"); + lastI = i + 1 + inBase64 = false + base64Accum = "" + } } + } - this.inBase64 = inBase64; - this.base64Accum = 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, "/") - return res; -} + 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) -Utf7IMAPDecoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + res += this.iconv.decode(Buffer.from(b64str, "base64"), "utf16-be") + } - this.inBase64 = false; - this.base64Accum = ''; - return res; + 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 +} diff --git a/node_modules/iconv-lite/lib/bom-handling.js b/node_modules/iconv-lite/lib/bom-handling.js index 1050872385c7f..a86a6b55ce198 100644 --- a/node_modules/iconv-lite/lib/bom-handling.js +++ b/node_modules/iconv-lite/lib/bom-handling.js @@ -1,52 +1,48 @@ -"use strict"; +"use strict" -var BOMChar = '\uFEFF'; +var BOMChar = "\uFEFF" exports.PrependBOM = PrependBOMWrapper -function PrependBOMWrapper(encoder, options) { - this.encoder = encoder; - this.addBOM = true; +function PrependBOMWrapper (encoder, options) { + this.encoder = encoder + this.addBOM = true } -PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; - } +PrependBOMWrapper.prototype.write = function (str) { + if (this.addBOM) { + str = BOMChar + str + this.addBOM = false + } - return this.encoder.write(str); + return this.encoder.write(str) } -PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); +PrependBOMWrapper.prototype.end = function () { + return this.encoder.end() } +// ------------------------------------------------------------------------------ -//------------------------------------------------------------------------------ - -exports.StripBOM = StripBOMWrapper; -function StripBOMWrapper(decoder, options) { - this.decoder = decoder; - this.pass = false; - this.options = options || {}; +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; +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(); - } + if (res[0] === BOMChar) { + res = res.slice(1) + if (typeof this.options.stripBOM === "function") { this.options.stripBOM() } + } - this.pass = true; - return res; + this.pass = true + return res } -StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); +StripBOMWrapper.prototype.end = function () { + return this.decoder.end() } - diff --git a/node_modules/iconv-lite/lib/helpers/merge-exports.js b/node_modules/iconv-lite/lib/helpers/merge-exports.js new file mode 100644 index 0000000000000..e79e041d9529b --- /dev/null +++ b/node_modules/iconv-lite/lib/helpers/merge-exports.js @@ -0,0 +1,13 @@ +"use strict" + +var hasOwn = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn + +function mergeModules (target, module) { + for (var key in module) { + if (hasOwn(module, key)) { + target[key] = module[key] + } + } +} + +module.exports = mergeModules diff --git a/node_modules/iconv-lite/lib/index.js b/node_modules/iconv-lite/lib/index.js index 657701c38d243..bd5d6bc0d90ac 100644 --- a/node_modules/iconv-lite/lib/index.js +++ b/node_modules/iconv-lite/lib/index.js @@ -1,134 +1,136 @@ -"use strict"; +"use strict" -var Buffer = require("safer-buffer").Buffer; +var Buffer = require("safer-buffer").Buffer -var bomHandling = require("./bom-handling"), - iconv = module.exports; +var bomHandling = require("./bom-handling") +var mergeModules = require("./helpers/merge-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; +// Cannot initialize with { __proto__: null } because Boolean({ __proto__: null }) === true +module.exports.encodings = null // Characters emitted in case of error. -iconv.defaultCharUnicode = '�'; -iconv.defaultCharSingleByte = '?'; +module.exports.defaultCharUnicode = "�" +module.exports.defaultCharSingleByte = "?" // Public API. -iconv.encode = function encode(str, encoding, options) { - str = "" + (str || ""); // Ensure string. +module.exports.encode = function encode (str, encoding, options) { + str = "" + (str || "") // Ensure string. - var encoder = iconv.getEncoder(encoding, options); + var encoder = module.exports.getEncoder(encoding, options) - var res = encoder.write(str); - var trail = encoder.end(); - - return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; -} + var res = encoder.write(str) + var trail = encoder.end() -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; - } + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res +} - buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. +module.exports.decode = function decode (buf, encoding, options) { + if (typeof buf === "string") { + if (!module.exports.skipDecodeWarning) { + console.error("Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding") + module.exports.skipDecodeWarning = true } - var decoder = iconv.getDecoder(encoding, options); + buf = Buffer.from("" + (buf || ""), "binary") // Ensure buffer. + } + + var decoder = module.exports.getDecoder(encoding, options) - var res = decoder.write(buf); - var trail = decoder.end(); + var res = decoder.write(buf) + var trail = decoder.end() - return trail ? (res + trail) : res; + return trail ? (res + trail) : res } -iconv.encodingExists = function encodingExists(enc) { - try { - iconv.getCodec(enc); - return true; - } catch (e) { - return false; - } +module.exports.encodingExists = function encodingExists (enc) { + try { + module.exports.getCodec(enc) + return true + } catch (e) { + return false + } } // Legacy aliases to convert functions -iconv.toEncoding = iconv.encode; -iconv.fromEncoding = iconv.decode; +module.exports.toEncoding = module.exports.encode +module.exports.fromEncoding = module.exports.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+"')"); - } +module.exports._codecDataCache = { __proto__: null } + +module.exports.getCodec = function getCodec (encoding) { + if (!module.exports.encodings) { + var raw = require("../encodings") + // TODO: In future versions when old nodejs support is removed can use object.assign + module.exports.encodings = { __proto__: null } // Initialize as empty object. + mergeModules(module.exports.encodings, raw) + } + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = module.exports._canonicalizeEncoding(encoding) + + // Traverse iconv.encodings to find actual codec. + var codecOptions = {} + while (true) { + var codec = module.exports._codecDataCache[enc] + + if (codec) { return codec } + + var codecDef = module.exports.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, module.exports) + + module.exports._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, ""); +module.exports._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); +module.exports.getEncoder = function getEncoder (encoding, options) { + var codec = module.exports.getCodec(encoding) + var encoder = new codec.encoder(options, codec) - if (codec.bomAware && options && options.addBOM) - encoder = new bomHandling.PrependBOM(encoder, options); + if (codec.bomAware && options && options.addBOM) { encoder = new bomHandling.PrependBOM(encoder, options) } - return encoder; + return encoder } -iconv.getDecoder = function getDecoder(encoding, options) { - var codec = iconv.getCodec(encoding), - decoder = new codec.decoder(options, codec); +module.exports.getDecoder = function getDecoder (encoding, options) { + var codec = module.exports.getCodec(encoding) + var decoder = new codec.decoder(options, codec) - if (codec.bomAware && !(options && options.stripBOM === false)) - decoder = new bomHandling.StripBOM(decoder, options); + if (codec.bomAware && !(options && options.stripBOM === false)) { decoder = new bomHandling.StripBOM(decoder, options) } - return decoder; + return decoder } // Streaming API @@ -136,45 +138,45 @@ iconv.getDecoder = function getDecoder(encoding, options) { // 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; +module.exports.enableStreamingAPI = function enableStreamingAPI (streamModule) { + if (module.exports.supportsStreams) { return } - // Dependency-inject stream module to create IconvLite stream classes. - var streams = require("./streams")(stream_module); + // Dependency-inject stream module to create IconvLite stream classes. + var streams = require("./streams")(streamModule) - // Not public API yet, but expose the stream classes. - iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream; - iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream; + // Not public API yet, but expose the stream classes. + module.exports.IconvLiteEncoderStream = streams.IconvLiteEncoderStream + module.exports.IconvLiteDecoderStream = streams.IconvLiteDecoderStream - // Streaming API. - iconv.encodeStream = function encodeStream(encoding, options) { - return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); - } + // Streaming API. + module.exports.encodeStream = function encodeStream (encoding, options) { + return new module.exports.IconvLiteEncoderStream(module.exports.getEncoder(encoding, options), options) + } - iconv.decodeStream = function decodeStream(encoding, options) { - return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); - } + module.exports.decodeStream = function decodeStream (encoding, options) { + return new module.exports.IconvLiteDecoderStream(module.exports.getDecoder(encoding, options), options) + } - iconv.supportsStreams = true; + module.exports.supportsStreams = true } // Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments). -var stream_module; +var streamModule try { - stream_module = require("stream"); + streamModule = require("stream") } catch (e) {} -if (stream_module && stream_module.Transform) { - iconv.enableStreamingAPI(stream_module); - +if (streamModule && streamModule.Transform) { + module.exports.enableStreamingAPI(streamModule) } 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."); - }; + // In rare cases where 'stream' module is not available by default, throw a helpful exception. + module.exports.encodeStream = module.exports.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."); +// Some environments, such as browsers, may not load JavaScript files as UTF-8 +// eslint-disable-next-line no-constant-condition +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.") } diff --git a/node_modules/iconv-lite/lib/streams.js b/node_modules/iconv-lite/lib/streams.js index a1506482f5801..ebfed8e0dc39c 100644 --- a/node_modules/iconv-lite/lib/streams.js +++ b/node_modules/iconv-lite/lib/streams.js @@ -1,109 +1,105 @@ -"use strict"; +"use strict" -var Buffer = require("safer-buffer").Buffer; +var Buffer = require("safer-buffer").Buffer -// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), +// 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; +module.exports = function (streamModule) { + var Transform = streamModule.Transform - // == Encoder stream ======================================================= + // == 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); - } + 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 = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } + }) - 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._transform = function (chunk, encoding, done) { + if (typeof chunk !== "string") { + return done(new Error("Iconv encoding stream needs strings as its input.")) } - 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); + try { + var res = this.conv.write(chunk) + if (res && res.length) this.push(res) + done() + } catch (e) { + done(e) } - - 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); - } + } + + IconvLiteEncoderStream.prototype._flush = function (done) { + try { + var res = this.conv.end() + if (res && res.length) this.push(res) + 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); - } + } + + 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.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; + } + + 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) } - - return { - IconvLiteEncoderStream: IconvLiteEncoderStream, - IconvLiteDecoderStream: IconvLiteDecoderStream, - }; -}; + } + + 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 + } +} diff --git a/node_modules/iconv-lite/package.json b/node_modules/iconv-lite/package.json index d351115a839fa..2a573574293a9 100644 --- a/node_modules/iconv-lite/package.json +++ b/node_modules/iconv-lite/package.json @@ -1,7 +1,7 @@ { "name": "iconv-lite", "description": "Convert character encodings in pure javascript.", - "version": "0.6.3", + "version": "0.7.2", "license": "MIT", "keywords": [ "iconv", @@ -12,30 +12,56 @@ "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", + "homepage": "https://github.com/pillarjs/iconv-lite", + "bugs": "https://github.com/pillarjs/iconv-lite/issues", + "files": [ + "lib/", + "encodings/", + "types/" + ], + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, "repository": { "type": "git", - "url": "git://github.com/ashtuchkin/iconv-lite.git" + "url": "https://github.com/pillarjs/iconv-lite.git" }, "engines": { "node": ">=0.10.0" }, "scripts": { - "coverage": "c8 _mocha --grep .", - "test": "mocha --reporter spec --grep ." + "lint": "eslint", + "lint:fix": "eslint --fix", + "test": "mocha --reporter spec --check-leaks --grep .", + "test:ci": "nyc --exclude test --reporter=lcovonly --reporter=text npm test", + "test:cov": "nyc --exclude test --reporter=html --reporter=text npm test", + "test:performance": "node --allow-natives-syntax performance/index.js", + "test:tap": "mocha --reporter tap --check-leaks --grep .", + "test:typescript": "tsc && attw --pack", + "test:webpack": "npm pack && mv iconv-lite-*.tgz test/webpack/iconv-lite.tgz && cd test/webpack && npm install && npm run test && rm iconv-lite.tgz", + "typegen": "node generation/gen-typings.js" }, "browser": { "stream": false }, "devDependencies": { + "@arethetypeswrong/cli": "^0.17.4", + "@stylistic/eslint-plugin": "^5.1.0", + "@stylistic/eslint-plugin-js": "^4.1.0", + "@types/node": "^24.0.12", "async": "^3.2.0", - "c8": "^7.2.0", + "bench-node": "^0.10.0", + "eslint": "^9.0.0", "errto": "^0.2.1", + "expect-type": "^1.2.0", "iconv": "^2.3.5", - "mocha": "^3.5.3", + "mocha": "^6.2.2", + "neostandard": "^0.12.0", + "nyc": "^14.1.1", "request": "^2.88.2", "semver": "^6.3.0", + "typescript": "~5.9.2", "unorm": "^1.6.0" }, "dependencies": { diff --git a/node_modules/ignore-walk/package.json b/node_modules/ignore-walk/package.json deleted file mode 100644 index f44a7a587a10b..0000000000000 --- a/node_modules/ignore-walk/package.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "name": "ignore-walk", - "version": "6.0.5", - "description": "Nested/recursive `.gitignore`/`.npmignore` parsing and filtering.", - "main": "lib/index.js", - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "mutate-fs": "^2.1.1", - "tap": "^16.0.1" - }, - "scripts": { - "test": "tap", - "posttest": "npm run lint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --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" - }, - "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": "^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.22.0", - "content": "scripts/template-oss", - "publish": "true" - } -} diff --git a/node_modules/imurmurhash/imurmurhash.js b/node_modules/imurmurhash/imurmurhash.js deleted file mode 100644 index e63146a2b7e70..0000000000000 --- a/node_modules/imurmurhash/imurmurhash.js +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @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; - } -}()); diff --git a/node_modules/imurmurhash/imurmurhash.min.js b/node_modules/imurmurhash/imurmurhash.min.js deleted file mode 100644 index dc0ee88d6b69c..0000000000000 --- a/node_modules/imurmurhash/imurmurhash.min.js +++ /dev/null @@ -1,12 +0,0 @@ -/** - * @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}(); \ No newline at end of file diff --git a/node_modules/imurmurhash/package.json b/node_modules/imurmurhash/package.json deleted file mode 100644 index 8a93edb55a224..0000000000000 --- a/node_modules/imurmurhash/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/indent-string/index.js b/node_modules/indent-string/index.js deleted file mode 100644 index e1ab804f2fd8a..0000000000000 --- a/node_modules/indent-string/index.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -module.exports = (string, count = 1, options) => { - options = { - indent: ' ', - includeEmptyLines: false, - ...options - }; - - if (typeof string !== 'string') { - throw new TypeError( - `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` - ); - } - - if (typeof count !== 'number') { - throw new TypeError( - `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` - ); - } - - if (typeof options.indent !== 'string') { - throw new TypeError( - `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` - ); - } - - if (count === 0) { - return string; - } - - const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; - - return string.replace(regex, options.indent.repeat(count)); -}; diff --git a/node_modules/indent-string/license b/node_modules/indent-string/license deleted file mode 100644 index e7af2f77107d7..0000000000000 --- a/node_modules/indent-string/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/indent-string/package.json b/node_modules/indent-string/package.json deleted file mode 100644 index 497bb83bbd9b7..0000000000000 --- a/node_modules/indent-string/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "indent-string", - "version": "4.0.0", - "description": "Indent each line in a string", - "license": "MIT", - "repository": "sindresorhus/indent-string", - "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": [ - "indent", - "string", - "pad", - "align", - "line", - "text", - "each", - "every" - ], - "devDependencies": { - "ava": "^1.4.1", - "tsd": "^0.7.2", - "xo": "^0.24.0" - } -} diff --git a/node_modules/ini/package.json b/node_modules/ini/package.json index 67aa927825947..6d6ade1f25343 100644 --- a/node_modules/ini/package.json +++ b/node_modules/ini/package.json @@ -2,16 +2,16 @@ "author": "GitHub Inc.", "name": "ini", "description": "An ini encoder/decoder for node", - "version": "4.1.3", + "version": "7.0.0", "repository": { "type": "git", "url": "git+https://github.com/npm/ini.git" }, "main": "lib/ini.js", "scripts": { - "eslint": "eslint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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", @@ -19,8 +19,8 @@ "template-oss-apply": "template-oss-apply --force" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0", "tap": "^16.0.1" }, "license": "ISC", @@ -29,11 +29,11 @@ "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.0.0", "publish": "true" }, "tap": { diff --git a/node_modules/init-package-json/lib/default-input.js b/node_modules/init-package-json/lib/default-input.js index 490e83c139887..a20217b0e470c 100644 --- a/node_modules/init-package-json/lib/default-input.js +++ b/node_modules/init-package-json/lib/default-input.js @@ -2,42 +2,13 @@ const fs = require('fs/promises') const path = require('path') -const validateLicense = require('validate-npm-package-license') +const validateLicense = require('@npmcli/package-json/lib/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}`] @@ -157,14 +128,6 @@ exports.directories = async () => { 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 || {} @@ -199,16 +162,17 @@ if (!package.scripts) { if (!package.repository) { exports.repository = async () => { - const gconf = await fs.readFile('.git/config', 'utf8').catch(() => '') + 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 = gconf[i + 1] + url = lines[i + 1] if (!url.match(/^\s*url =/)) { - url = gconf[i + 2] + url = lines[i + 2] } if (!url.match(/^\s*url =/)) { url = null @@ -240,23 +204,66 @@ if (!package.keywords) { }) } -if (!package.author) { +let author +if (package.author) { + if (typeof package.author === 'string') { + author = package.author + } else { + const authorName = package.author.name + const authorEmail = package.author.email || package.author.mail + const authorUrl = package.author.url || package.author.web + author = `${authorName}${authorEmail ? ` <${authorEmail}>` : ''}${authorUrl ? ` (${authorUrl})` : ''}` + } +} else { const authorName = getConfig('author.name') - exports.author = authorName - ? { - name: authorName, - email: getConfig('author.email'), - url: getConfig('author.url'), - } - : yes ? '' : prompt('author') + if (authorName) { + const authorEmail = getConfig('author.email') + const authorUrl = getConfig('author.url') + author = `${authorName}${authorEmail ? ` <${authorEmail}>` : ''}${authorUrl ? ` (${authorUrl})` : ''}` + } } -const license = package.license || getConfig('license') || 'ISC' -exports.license = yes ? license : prompt('license', license, (data) => { - const its = validateLicense(data) - if (its.validForNewPackages) { - return data +if (yes) { + if (author) { + exports.author = author } - const errors = (its.errors || []).concat(its.warnings || []) - return invalid(`Sorry, ${errors.join(' and ')}.`) +} else { + exports.author = prompt('author', author || undefined) +} + +const configLicense = getConfig('license') +const license = package.license || configLicense || undefined + +if (yes) { + // Only include license if explicitly set in config or already in package.json + if (license) { + exports.license = license + } +} else { + exports.license = prompt('license', license || undefined, (data) => { + if (!data) { + return undefined + } + if (validateLicense(data)) { + return data + } + return invalid( + 'License should be a valid SPDX license expression' + ) + }) +} + +const type = package.type || getConfig('type') || 'commonjs' +exports.type = yes ? type : prompt('type', type, (data) => { + return data }) + +// Only include private field if it already exists or if explicitly set in config +const configPrivate = getConfig('private') +if (package.private !== undefined || configPrivate !== undefined) { + if (package.private !== undefined) { + exports.private = package.private + } else if (!config.isDefault || !config.isDefault('init-private')) { + exports.private = configPrivate + } +} diff --git a/node_modules/init-package-json/lib/init-package-json.js b/node_modules/init-package-json/lib/init-package-json.js index 51cbd21a1ebe6..257bd5de0dbe5 100644 --- a/node_modules/init-package-json/lib/init-package-json.js +++ b/node_modules/init-package-json/lib/init-package-json.js @@ -100,6 +100,16 @@ async function init (dir, delete pkg.content.repository } + // if no license was explicitly provided, don't include one + if (!pzData.license) { + delete pkg.content.license + } + + // if no author was explicitly provided, don't include one + if (!pzData.author) { + delete pkg.content.author + } + // readJson filters out empty descriptions, but init-package-json // traditionally leaves them alone if (!pkg.content.description) { @@ -139,7 +149,7 @@ async function init (dir, return } - await pkg.save() + await pkg.save({ sort: true }) return pkg.content } diff --git a/node_modules/init-package-json/package.json b/node_modules/init-package-json/package.json index 969e124378966..9bad73d16346d 100644 --- a/node_modules/init-package-json/package.json +++ b/node_modules/init-package-json/package.json @@ -1,15 +1,16 @@ { "name": "init-package-json", - "version": "6.0.3", + "version": "9.0.0", "main": "lib/init-package-json.js", "scripts": { "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", @@ -19,22 +20,21 @@ "license": "ISC", "description": "A node module to get your node module started", "dependencies": { - "@npmcli/package-json": "^5.0.0", - "npm-package-arg": "^11.0.0", - "promzard": "^1.0.0", - "read": "^3.0.1", - "semver": "^7.3.5", - "validate-npm-package-license": "^3.0.4", - "validate-npm-package-name": "^5.0.0" + "@npmcli/package-json": "^8.0.0", + "npm-package-arg": "^14.0.0", + "promzard": "^4.0.0", + "read": "^6.0.0", + "semver": "^7.7.2", + "validate-npm-package-name": "^8.0.0" }, "devDependencies": { - "@npmcli/config": "^8.2.0", - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/config": "^10.0.0", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.0", "tap": "^16.0.1" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "tap": { "test-ignore": "fixtures/", @@ -60,7 +60,8 @@ ], "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true + "version": "5.1.0", + "publish": true, + "updateNpm": false } } diff --git a/node_modules/ip-address/dist/address-error.js b/node_modules/ip-address/dist/address-error.js index 4fcade3ba2486..c178ae48200ac 100644 --- a/node_modules/ip-address/dist/address-error.js +++ b/node_modules/ip-address/dist/address-error.js @@ -5,9 +5,7 @@ class AddressError extends Error { constructor(message, parseMessage) { super(message); this.name = 'AddressError'; - if (parseMessage !== null) { - this.parseMessage = parseMessage; - } + this.parseMessage = parseMessage; } } exports.AddressError = AddressError; diff --git a/node_modules/ip-address/dist/common.js b/node_modules/ip-address/dist/common.js index 4d10c9a4e8203..6b76e051b44e4 100644 --- a/node_modules/ip-address/dist/common.js +++ b/node_modules/ip-address/dist/common.js @@ -1,6 +1,12 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.isCorrect = exports.isInSubnet = void 0; +exports.isInSubnet = isInSubnet; +exports.isCorrect = isCorrect; +exports.prefixLengthFromMask = prefixLengthFromMask; +exports.numberToPaddedHex = numberToPaddedHex; +exports.stringToPaddedHex = stringToPaddedHex; +exports.testBit = testBit; +const address_error_1 = require("./address-error"); function isInSubnet(address) { if (this.subnetMask < address.subnetMask) { return false; @@ -10,7 +16,6 @@ function isInSubnet(address) { } return false; } -exports.isInSubnet = isInSubnet; function isCorrect(defaultBits) { return function () { if (this.addressMinusSuffix !== this.correctForm()) { @@ -22,5 +27,41 @@ function isCorrect(defaultBits) { return this.parsedSubnet === String(this.subnetMask); }; } -exports.isCorrect = isCorrect; +/** + * Returns the prefix length (number of leading 1 bits) of a contiguous + * subnet mask. Throws `AddressError` if the mask is non-contiguous (e.g. + * `255.0.255.0`). + */ +function prefixLengthFromMask(value, totalBits) { + const binary = value.toString(2).padStart(totalBits, '0'); + if (binary.length > totalBits) { + throw new address_error_1.AddressError('Invalid subnet mask.'); + } + const firstZero = binary.indexOf('0'); + if (firstZero === -1) { + return totalBits; + } + if (binary.slice(firstZero).includes('1')) { + throw new address_error_1.AddressError('Invalid subnet mask.'); + } + return firstZero; +} +function numberToPaddedHex(number) { + return number.toString(16).padStart(2, '0'); +} +function stringToPaddedHex(numberString) { + return numberToPaddedHex(parseInt(numberString, 10)); +} +/** + * @param binaryValue Binary representation of a value (e.g. `10`) + * @param position Byte position, where 0 is the least significant bit + */ +function testBit(binaryValue, position) { + const { length } = binaryValue; + if (position > length) { + return false; + } + const positionInString = length - position; + return binaryValue.substring(positionInString, positionInString + 1) === '1'; +} //# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/node_modules/ip-address/dist/ip-address.js b/node_modules/ip-address/dist/ip-address.js index 553c005a63cb6..84f348709fe54 100644 --- a/node_modules/ip-address/dist/ip-address.js +++ b/node_modules/ip-address/dist/ip-address.js @@ -24,11 +24,11 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0; -const ipv4_1 = require("./ipv4"); +var ipv4_1 = require("./ipv4"); Object.defineProperty(exports, "Address4", { enumerable: true, get: function () { return ipv4_1.Address4; } }); -const ipv6_1 = require("./ipv6"); +var ipv6_1 = require("./ipv6"); Object.defineProperty(exports, "Address6", { enumerable: true, get: function () { return ipv6_1.Address6; } }); -const address_error_1 = require("./address-error"); +var 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 }; diff --git a/node_modules/ip-address/dist/ipv4.js b/node_modules/ip-address/dist/ipv4.js index 22a81b5047f05..2c0fd182086d2 100644 --- a/node_modules/ip-address/dist/ipv4.js +++ b/node_modules/ip-address/dist/ipv4.js @@ -28,11 +28,9 @@ 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"); +const isCorrect4 = common.isCorrect(constants.BITS); /** * Represents an IPv4 address - * @class Address4 * @param {string} address - An IPv4 address string */ class Address4 { @@ -45,15 +43,11 @@ class Address4 { this.v4 = true; /** * Returns true if the address is correct, false otherwise - * @memberof Address4 - * @instance * @returns {Boolean} */ - this.isCorrect = common.isCorrect(constants.BITS); + this.isCorrect = isCorrect4; /** * Returns true if the given address is in the subnet of the current address - * @memberof Address4 - * @instance * @returns {boolean} */ this.isInSubnet = common.isInSubnet; @@ -71,6 +65,13 @@ class Address4 { this.addressMinusSuffix = address; this.parsedAddress = this.parse(address); } + /** + * Returns true if the given string is a valid IPv4 address (with optional + * CIDR subnet), false otherwise. Host bits in the subnet portion are + * allowed (e.g. `192.168.1.5/24` is valid); for strict network-address + * validation compare `correctForm()` to `startAddress().correctForm()`, + * or use `networkForm()`. + */ static isValid(address) { try { // eslint-disable-next-line no-new @@ -81,8 +82,11 @@ class Address4 { return false; } } - /* - * Parses a v4 address + /** + * Parses an IPv4 address string into its four octet groups and stores the + * result on `this.parsedAddress`. Called automatically by the constructor; + * you typically don't need to call it directly. Throws `AddressError` if + * the input is not a valid IPv4 address. */ parse(address) { const groups = address.split('.'); @@ -92,45 +96,110 @@ class Address4 { return groups; } /** - * Returns the correct form of an address - * @memberof Address4 - * @instance - * @returns {String} + * Returns the address in correct form: octets joined with `.` and any + * leading zeros stripped (e.g. `192.168.1.1`). For IPv4 this matches the + * canonical dotted-decimal representation. */ correctForm() { return this.parsedAddress.map((part) => parseInt(part, 10)).join('.'); } /** - * Converts a hex string to an IPv4 address object - * @memberof Address4 - * @static + * Construct an `Address4` from an address and a dotted-decimal subnet + * mask given as separate strings (e.g. as returned by Node's + * `os.networkInterfaces()`). Throws `AddressError` if the mask is + * non-contiguous (e.g. `255.0.255.0`). + * @example + * var address = Address4.fromAddressAndMask('192.168.1.1', '255.255.255.0'); + * address.subnetMask; // 24 + */ + static fromAddressAndMask(address, mask) { + const bits = common.prefixLengthFromMask(new Address4(mask).bigInt(), constants.BITS); + return new Address4(`${address}/${bits}`); + } + /** + * Construct an `Address4` from an address and a Cisco-style wildcard mask + * given as separate strings (e.g. `0.0.0.255` for a `/24`). The wildcard + * mask is the bitwise inverse of the subnet mask. Throws `AddressError` + * if the mask is non-contiguous (e.g. `0.255.0.255`). + * @example + * var address = Address4.fromAddressAndWildcardMask('10.0.0.1', '0.0.0.255'); + * address.subnetMask; // 24 + */ + static fromAddressAndWildcardMask(address, wildcardMask) { + const wildcard = new Address4(wildcardMask).bigInt(); + const allOnes = (BigInt(1) << BigInt(constants.BITS)) - BigInt(1); + // eslint-disable-next-line no-bitwise + const mask = wildcard ^ allOnes; + const bits = common.prefixLengthFromMask(mask, constants.BITS); + return new Address4(`${address}/${bits}`); + } + /** + * Construct an `Address4` from a wildcard pattern with trailing `*` + * octets. The number of trailing wildcards determines the prefix + * length: each `*` represents 8 bits. + * + * Only trailing whole-octet wildcards are supported. Partial-octet + * wildcards (e.g. `192.168.0.1*`) and interior wildcards (e.g. + * `192.*.0.1`) throw `AddressError`. + * @example + * Address4.fromWildcard('192.168.0.*').subnet; // '/24' + * Address4.fromWildcard('192.168.*.*').subnet; // '/16' + * Address4.fromWildcard('*.*.*.*').subnet; // '/0' + */ + static fromWildcard(input) { + const groups = input.split('.'); + if (groups.length !== constants.GROUPS) { + throw new address_error_1.AddressError('Wildcard pattern must have 4 octets'); + } + let firstWildcard = -1; + for (let i = 0; i < groups.length; i++) { + if (groups[i] === '*') { + if (firstWildcard === -1) { + firstWildcard = i; + } + } + else if (firstWildcard !== -1) { + throw new address_error_1.AddressError('Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)'); + } + } + const trailing = firstWildcard === -1 ? 0 : groups.length - firstWildcard; + const replaced = groups.map((g) => (g === '*' ? '0' : g)); + const subnetBits = constants.BITS - trailing * 8; + return new Address4(`${replaced.join('.')}/${subnetBits}`); + } + /** + * Converts a hex string to an IPv4 address object. Accepts 8 hex digits + * with optional `:` separators (e.g. `'7f000001'` or `'7f:00:00:01'`). + * Throws `AddressError` for any other length or for non-hex characters. * @param {string} hex - a hex string to convert * @returns {Address4} */ static fromHex(hex) { - const padded = hex.replace(/:/g, '').padStart(8, '0'); + const stripped = hex.replace(/:/g, ''); + if (!/^[0-9a-fA-F]{8}$/.test(stripped)) { + throw new address_error_1.AddressError('IPv4 hex must be exactly 8 hex digits'); + } const groups = []; - let i; - for (i = 0; i < 8; i += 2) { - const h = padded.slice(i, i + 2); - groups.push(parseInt(h, 16)); + for (let i = 0; i < 8; i += 2) { + groups.push(parseInt(stripped.slice(i, i + 2), 16)); } return new Address4(groups.join('.')); } /** - * Converts an integer into a IPv4 address object - * @memberof Address4 - * @static + * Converts an integer into a IPv4 address object. The integer must be a + * non-negative safe integer in the range `[0, 2**32 - 1]`; otherwise + * `AddressError` is thrown. * @param {integer} integer - a number to convert * @returns {Address4} */ static fromInteger(integer) { - return Address4.fromHex(integer.toString(16)); + if (!Number.isInteger(integer) || integer < 0 || integer > 0xffffffff) { + throw new address_error_1.AddressError('IPv4 integer must be in the range 0 to 2**32 - 1'); + } + return Address4.fromHex(integer.toString(16).padStart(8, '0')); } /** * Return an address from in-addr.arpa form - * @memberof Address4 - * @static * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address * @returns {Adress4} * @example @@ -145,17 +214,15 @@ class Address4 { } /** * 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(':'); + return this.parsedAddress.map((part) => common.stringToPaddedHex(part)).join(':'); } /** - * Converts an IPv4 address object to an array of bytes - * @memberof Address4 - * @instance + * Converts an IPv4 address object to an array of bytes. + * + * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toArray())`. * @returns {Array} */ toArray() { @@ -163,103 +230,143 @@ class Address4 { } /** * 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))); + output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } return output.join(':'); } /** - * Returns the address as a BigInteger - * @memberof Address4 - * @instance - * @returns {BigInteger} + * Returns the address as a `bigint` + * @returns {bigint} */ - bigInteger() { - return new jsbn_1.BigInteger(this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%02x', parseInt(n, 10))).join(''), 16); + bigInt() { + return BigInt(`0x${this.parsedAddress.map((n) => common.stringToPaddedHex(n)).join('')}`); } /** * Helper function getting start address. - * @memberof Address4 - * @instance - * @returns {BigInteger} + * @returns {bigint} */ _startAddress() { - return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants.BITS - this.subnetMask), 2); + return BigInt(`0b${this.mask() + '0'.repeat(constants.BITS - this.subnetMask)}`); } /** * 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()); + return Address4.fromBigInt(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)); + const adjust = BigInt('1'); + return Address4.fromBigInt(this._startAddress() + adjust); } /** * Helper function getting end address. - * @memberof Address4 - * @instance - * @returns {BigInteger} + * @returns {bigint} */ _endAddress() { - return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants.BITS - this.subnetMask), 2); + return BigInt(`0b${this.mask() + '1'.repeat(constants.BITS - this.subnetMask)}`); } /** * 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()); + return Address4.fromBigInt(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)); + const adjust = BigInt('1'); + return Address4.fromBigInt(this._endAddress() - adjust); + } + /** + * The dotted-decimal form of the subnet mask, e.g. `255.255.240.0` for + * a `/20`. Returns an `Address4`; call `.correctForm()` for the string. + * @returns {Address4} + */ + subnetMaskAddress() { + return Address4.fromBigInt(BigInt(`0b${'1'.repeat(this.subnetMask)}${'0'.repeat(constants.BITS - this.subnetMask)}`)); + } + /** + * The Cisco-style wildcard mask, e.g. `0.0.0.255` for a `/24`. This is + * the bitwise inverse of `subnetMaskAddress()`. Returns an `Address4`; + * call `.correctForm()` for the string. + * @returns {Address4} + */ + wildcardMask() { + return Address4.fromBigInt(BigInt(`0b${'0'.repeat(this.subnetMask)}${'1'.repeat(constants.BITS - this.subnetMask)}`)); + } + /** + * The network address in CIDR string form, e.g. `192.168.1.0/24` for + * `192.168.1.5/24`. For an address with no explicit subnet the prefix is + * `/32`, e.g. `networkForm()` on `192.168.1.5` returns `192.168.1.5/32`. + * @returns {string} + */ + networkForm() { + return `${this.startAddress().correctForm()}/${this.subnetMask}`; + } + /** + * Converts a BigInt to a v4 address object. The value must be in the + * range `[0, 2**32 - 1]`; otherwise `AddressError` is thrown. + * @param {bigint} bigInt - a BigInt to convert + * @returns {Address4} + */ + static fromBigInt(bigInt) { + if (bigInt < 0n || bigInt > 0xffffffffn) { + throw new address_error_1.AddressError('IPv4 BigInt must be in the range 0 to 2**32 - 1'); + } + return Address4.fromHex(bigInt.toString(16).padStart(8, '0')); } /** - * Converts a BigInteger to a v4 address object - * @memberof Address4 - * @static - * @param {BigInteger} bigInteger - a BigInteger to convert + * Convert a byte array to an Address4 object. + * + * To convert from a Node.js `Buffer`, spread it: `Address4.fromByteArray([...buf])`. + * @param {Array} bytes - an array of 4 bytes (0-255) * @returns {Address4} */ - static fromBigInteger(bigInteger) { - return Address4.fromInteger(parseInt(bigInteger.toString(), 10)); + static fromByteArray(bytes) { + if (bytes.length !== 4) { + throw new address_error_1.AddressError('IPv4 addresses require exactly 4 bytes'); + } + // Validate that all bytes are within valid range (0-255) + for (let i = 0; i < bytes.length; i++) { + if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) { + throw new address_error_1.AddressError('All bytes must be integers between 0 and 255'); + } + } + return this.fromUnsignedByteArray(bytes); + } + /** + * Convert an unsigned byte array to an Address4 object + * @param {Array} bytes - an array of 4 unsigned bytes (0-255) + * @returns {Address4} + */ + static fromUnsignedByteArray(bytes) { + if (bytes.length !== 4) { + throw new address_error_1.AddressError('IPv4 addresses require exactly 4 bytes'); + } + const address = bytes.join('.'); + return new Address4(address); } /** * Returns the first n bits of the address, defaulting to the * subnet mask - * @memberof Address4 - * @instance * @returns {String} */ mask(mask) { @@ -270,8 +377,6 @@ class Address4 { } /** * Returns the bits in the given range as a base-2 string - * @memberof Address4 - * @instance * @returns {string} */ getBitsBase2(start, end) { @@ -279,10 +384,8 @@ class Address4 { } /** * 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) { @@ -293,25 +396,66 @@ class Address4 { if (options.omitSuffix) { return reversed; } - return (0, sprintf_js_1.sprintf)('%s.in-addr.arpa.', reversed); + return `${reversed}.in-addr.arpa.`; } /** * 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')); + return this.isInSubnet(MULTICAST_V4); + } + /** + * Returns true if the address is in one of the [RFC 1918](https://datatracker.ietf.org/doc/html/rfc1918) private address ranges (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`). + * @returns {boolean} + */ + isPrivate() { + return PRIVATE_V4.some((subnet) => this.isInSubnet(subnet)); + } + /** + * Returns true if the address is in the loopback range `127.0.0.0/8` ([RFC 1122](https://datatracker.ietf.org/doc/html/rfc1122)). + * @returns {boolean} + */ + isLoopback() { + return this.isInSubnet(LOOPBACK_V4); + } + /** + * Returns true if the address is in the link-local range `169.254.0.0/16` ([RFC 3927](https://datatracker.ietf.org/doc/html/rfc3927)). + * @returns {boolean} + */ + isLinkLocal() { + return this.isInSubnet(LINK_LOCAL_V4); + } + /** + * Returns true if the address is the unspecified address `0.0.0.0`. + * @returns {boolean} + */ + isUnspecified() { + return this.isInSubnet(UNSPECIFIED_V4); + } + /** + * Returns true if the address is the limited broadcast address `255.255.255.255` ([RFC 919](https://datatracker.ietf.org/doc/html/rfc919)). + * @returns {boolean} + */ + isBroadcast() { + return this.isInSubnet(BROADCAST_V4); + } + /** + * Returns true if the address is in the carrier-grade NAT range `100.64.0.0/10` ([RFC 6598](https://datatracker.ietf.org/doc/html/rfc6598)). + * @returns {boolean} + */ + isCGNAT() { + return this.isInSubnet(CGNAT_V4); } /** * 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'); + if (this._binaryZeroPad === undefined) { + this._binaryZeroPad = this.bigInt().toString(2).padStart(constants.BITS, '0'); + } + return this._binaryZeroPad; } /** * Groups an IPv4 address for inclusion at the end of an IPv6 address @@ -319,8 +463,23 @@ class Address4 { */ 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('.'))); + return this.address.replace(constants.RE_ADDRESS, `${segments + .slice(0, 2) + .join('.')}.${segments + .slice(2, 4) + .join('.')}`); } } exports.Address4 = Address4; +const MULTICAST_V4 = new Address4('224.0.0.0/4'); +const PRIVATE_V4 = [ + new Address4('10.0.0.0/8'), + new Address4('172.16.0.0/12'), + new Address4('192.168.0.0/16'), +]; +const LOOPBACK_V4 = new Address4('127.0.0.0/8'); +const LINK_LOCAL_V4 = new Address4('169.254.0.0/16'); +const UNSPECIFIED_V4 = new Address4('0.0.0.0/32'); +const BROADCAST_V4 = new Address4('255.255.255.255/32'); +const CGNAT_V4 = new Address4('100.64.0.0/10'); //# sourceMappingURL=ipv4.js.map \ No newline at end of file diff --git a/node_modules/ip-address/dist/ipv6.js b/node_modules/ip-address/dist/ipv6.js index c88ab84b9ad77..a78020ee7886f 100644 --- a/node_modules/ip-address/dist/ipv6.js +++ b/node_modules/ip-address/dist/ipv6.js @@ -33,8 +33,8 @@ 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"); +const common_1 = require("./common"); +const isCorrect6 = common.isCorrect(constants6.BITS); function assert(condition) { if (!condition) { throw new Error('Assertion failed.'); @@ -70,7 +70,7 @@ function compact(address, slice) { return s1.concat(['compact']).concat(s2); } function paddedHex(octet) { - return (0, sprintf_js_1.sprintf)('%04x', parseInt(octet, 16)); + return parseInt(octet, 16).toString(16).padStart(4, '0'); } function unsignByte(b) { // eslint-disable-next-line no-bitwise @@ -78,7 +78,6 @@ function unsignByte(b) { } /** * Represents an IPv6 address - * @class Address6 * @param {string} address - An IPv6 address string * @param {number} [groups=8] - How many octets to parse * @example @@ -95,18 +94,14 @@ class Address6 { // #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); + this.isCorrect = isCorrect6; if (optionalGroups === undefined) { this.groups = constants6.GROUPS; } @@ -137,6 +132,13 @@ class Address6 { this.addressMinusSuffix = address; this.parsedAddress = this.parse(this.addressMinusSuffix); } + /** + * Returns true if the given string is a valid IPv6 address (with optional + * CIDR subnet and zone identifier), false otherwise. Host bits in the + * subnet portion are allowed (e.g. `2001:db8::1/32` is valid); for strict + * network-address validation compare `correctForm()` to + * `startAddress().correctForm()`, or use `networkForm()`. + */ static isValid(address) { try { // eslint-disable-next-line no-new @@ -148,30 +150,31 @@ class Address6 { } } /** - * Convert a BigInteger to a v6 address object - * @memberof Address6 - * @static - * @param {BigInteger} bigInteger - a BigInteger to convert + * Convert a BigInt to a v6 address object. The value must be in the + * range `[0, 2**128 - 1]`; otherwise `AddressError` is thrown. + * @param {bigint} bigInt - a BigInt to convert * @returns {Address6} * @example - * var bigInteger = new BigInteger('1000000000000'); - * var address = Address6.fromBigInteger(bigInteger); + * var bigInt = BigInt('1000000000000'); + * var address = Address6.fromBigInt(bigInt); * address.correctForm(); // '::e8:d4a5:1000' */ - static fromBigInteger(bigInteger) { - const hex = bigInteger.toString(16).padStart(32, '0'); + static fromBigInt(bigInt) { + if (bigInt < 0n || bigInt > (1n << BigInt(constants6.BITS)) - 1n) { + throw new address_error_1.AddressError('IPv6 BigInt must be in the range 0 to 2**128 - 1'); + } + const hex = bigInt.toString(16).padStart(32, '0'); const groups = []; - let i; - for (i = 0; i < constants6.GROUPS; i++) { + for (let 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 + * Parse a URL (with optional bracketed host and port) into an address and + * port. Returns either `{ address, port }` on success or + * `{ error, address: null, port: null }` if the URL could not be parsed. + * Ports are returned as numbers (or `null` if absent or out of range). * @example * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/'); * addressAndPort.address.correctForm(); // 'ffff::' @@ -230,10 +233,92 @@ class Address6 { port, }; } + /** + * Construct an `Address6` from an address and a hex subnet mask given as + * separate strings (e.g. as returned by Node's `os.networkInterfaces()`). + * Throws `AddressError` if the mask is non-contiguous (e.g. + * `ffff::ffff`). + * @example + * var address = Address6.fromAddressAndMask('fe80::1', 'ffff:ffff:ffff:ffff::'); + * address.subnetMask; // 64 + */ + static fromAddressAndMask(address, mask) { + const bits = common.prefixLengthFromMask(new Address6(mask).bigInt(), constants6.BITS); + return new Address6(`${address}/${bits}`); + } + /** + * Construct an `Address6` from an address and a Cisco-style wildcard mask + * given as separate strings (e.g. `::ffff:ffff:ffff:ffff` for a `/64`). + * The wildcard mask is the bitwise inverse of the subnet mask. Throws + * `AddressError` if the mask is non-contiguous. + * @example + * var address = Address6.fromAddressAndWildcardMask('fe80::1', '::ffff:ffff:ffff:ffff'); + * address.subnetMask; // 64 + */ + static fromAddressAndWildcardMask(address, wildcardMask) { + const wildcard = new Address6(wildcardMask).bigInt(); + const allOnes = (BigInt(1) << BigInt(constants6.BITS)) - BigInt(1); + // eslint-disable-next-line no-bitwise + const mask = wildcard ^ allOnes; + const bits = common.prefixLengthFromMask(mask, constants6.BITS); + return new Address6(`${address}/${bits}`); + } + /** + * Construct an `Address6` from a wildcard pattern with trailing `*` + * groups. The number of trailing wildcards determines the prefix + * length: each `*` represents 16 bits. `::` is expanded to zero groups + * (not wildcards) before evaluating trailing wildcards. + * + * Only trailing whole-group wildcards are supported. Partial-group + * wildcards (e.g. `2001:db8::0*`) and interior wildcards (e.g. + * `*::1`) throw `AddressError`. + * @example + * Address6.fromWildcard('2001:db8:*:*:*:*:*:*').subnet; // '/32' + * Address6.fromWildcard('2001:db8::*').subnet; // '/112' + * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' + */ + static fromWildcard(input) { + if (input.includes('%') || input.includes('/')) { + throw new address_error_1.AddressError('Wildcard pattern must not include a zone or CIDR suffix'); + } + const halves = input.split('::'); + if (halves.length > 2) { + throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); + } + let groups; + if (halves.length === 2) { + const left = halves[0] === '' ? [] : halves[0].split(':'); + const right = halves[1] === '' ? [] : halves[1].split(':'); + const remaining = constants6.GROUPS - left.length - right.length; + if (remaining < 1) { + throw new address_error_1.AddressError("Wildcard pattern with '::' has too many groups"); + } + groups = [...left, ...new Array(remaining).fill('0'), ...right]; + } + else { + groups = input.split(':'); + } + if (groups.length !== constants6.GROUPS) { + throw new address_error_1.AddressError('Wildcard pattern must have 8 groups'); + } + let firstWildcard = -1; + for (let i = 0; i < groups.length; i++) { + if (groups[i] === '*') { + if (firstWildcard === -1) { + firstWildcard = i; + } + } + else if (firstWildcard !== -1) { + throw new address_error_1.AddressError('Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)'); + } + } + const trailing = firstWildcard === -1 ? 0 : groups.length - firstWildcard; + const replaced = groups.map((g) => (g === '*' ? '0' : g)); + const subnetBits = constants6.BITS - trailing * 16; + return new Address6(`${replaced.join(':')}/${subnetBits}`); + } /** * Create an IPv6-mapped address given an IPv4 address - * @memberof Address6 - * @static * @param {string} address - An IPv4 address string * @returns {Address6} * @example @@ -248,8 +333,6 @@ class Address6 { } /** * Return an address from ip6.arpa form - * @memberof Address6 - * @static * @param {string} arpaFormAddress - an 'ip6.arpa' form address * @returns {Adress6} * @example @@ -274,17 +357,13 @@ class Address6 { } /** * 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 `${this.correctForm().replace(/:/g, '-')}.ipv6-literal.net`; } /** * 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 */ @@ -293,9 +372,7 @@ class Address6 { } /** * Return the number of possible subnets of a given size in the address - * @memberof Address6 - * @instance - * @param {number} [size=128] - the subnet size + * @param {number} [subnetSize=128] - the subnet size * @returns {String} */ // TODO: probably useful to have a numeric version of this too @@ -306,108 +383,131 @@ class Address6 { if (subnetPowers < 0) { return '0'; } - return addCommas(new jsbn_1.BigInteger('2', 10).pow(subnetPowers).toString(10)); + return addCommas((BigInt('2') ** BigInt(subnetPowers)).toString(10)); } /** * Helper function getting start address. - * @memberof Address6 - * @instance - * @returns {BigInteger} + * @returns {bigint} */ _startAddress() { - return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants6.BITS - this.subnetMask), 2); + return BigInt(`0b${this.mask() + '0'.repeat(constants6.BITS - this.subnetMask)}`); } /** * 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()); + return Address6.fromBigInt(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)); + const adjust = BigInt('1'); + return Address6.fromBigInt(this._startAddress() + adjust); } /** * Helper function getting end address. - * @memberof Address6 - * @instance - * @returns {BigInteger} + * @returns {bigint} */ _endAddress() { - return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants6.BITS - this.subnetMask), 2); + return BigInt(`0b${this.mask() + '1'.repeat(constants6.BITS - this.subnetMask)}`); } /** * 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()); + return Address6.fromBigInt(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)); + const adjust = BigInt('1'); + return Address6.fromBigInt(this._endAddress() - adjust); + } + /** + * The hex form of the subnet mask, e.g. `ffff:ffff:ffff:ffff::` for a + * `/64`. Returns an `Address6`; call `.correctForm()` for the string. + * @returns {Address6} + */ + subnetMaskAddress() { + return Address6.fromBigInt(BigInt(`0b${'1'.repeat(this.subnetMask)}${'0'.repeat(constants6.BITS - this.subnetMask)}`)); + } + /** + * The Cisco-style wildcard mask, e.g. `::ffff:ffff:ffff:ffff` for a + * `/64`. This is the bitwise inverse of `subnetMaskAddress()`. Returns + * an `Address6`; call `.correctForm()` for the string. + * @returns {Address6} + */ + wildcardMask() { + return Address6.fromBigInt(BigInt(`0b${'0'.repeat(this.subnetMask)}${'1'.repeat(constants6.BITS - this.subnetMask)}`)); + } + /** + * The network address in CIDR string form, e.g. `2001:db8::/32` for + * `2001:db8::1/32`. For an address with no explicit subnet the prefix + * is `/128`, e.g. `networkForm()` on `2001:db8::1` returns + * `2001:db8::1/128`. + * @returns {string} + */ + networkForm() { + return `${this.startAddress().correctForm()}/${this.subnetMask}`; } /** - * Return the scope of the address - * @memberof Address6 - * @instance + * Return the scope of the address. The 4-bit scope field + * ([RFC 4291 §2.7](https://datatracker.ietf.org/doc/html/rfc4291#section-2.7)) + * is only defined for multicast addresses; for unicast addresses the scope + * is derived from the address type per + * [RFC 4007 §6](https://datatracker.ietf.org/doc/html/rfc4007#section-6). * @returns {String} */ getScope() { - let scope = constants6.SCOPES[this.getBits(12, 16).intValue()]; - if (this.getType() === 'Global unicast' && scope !== 'Link local') { - scope = 'Global'; + const type = this.getType(); + if (type === 'Multicast' || type.startsWith('Multicast ')) { + const scope = constants6.SCOPES[parseInt(this.getBits(12, 16).toString(10), 10)]; + return scope || 'Unknown'; } - return scope || 'Unknown'; + // RFC 4291 §2.5.3: the loopback address is treated as having Link-Local + // scope. (Multicast scope 1, "Interface-Local", is a different concept + // used only for loopback transmission of multicast.) + if (type === 'Link-local unicast' || type === 'Loopback') { + return 'Link local'; + } + // RFC 4007 §6: the unspecified address has no scope. + if (type === 'Unspecified') { + return 'Unknown'; + } + return 'Global'; } /** * 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]; + for (let i = 0; i < TYPE_SUBNETS.length; i++) { + const entry = TYPE_SUBNETS[i]; + if (this.isInSubnet(entry[0])) { + return entry[1]; } } return 'Global unicast'; } /** - * Return the bits in the given range as a BigInteger - * @memberof Address6 - * @instance - * @returns {BigInteger} + * Return the bits in the given range as a BigInt + * @returns {bigint} */ getBits(start, end) { - return new jsbn_1.BigInteger(this.getBitsBase2(start, end), 2); + return BigInt(`0b${this.getBitsBase2(start, end)}`); } /** * Return the bits in the given range as a base-2 string - * @memberof Address6 - * @instance * @returns {String} */ getBitsBase2(start, end) { @@ -415,8 +515,6 @@ class Address6 { } /** * Return the bits in the given range as a base-16 string - * @memberof Address6 - * @instance * @returns {String} */ getBitsBase16(start, end) { @@ -430,8 +528,6 @@ class Address6 { } /** * Return the bits that are set past the subnet mask length - * @memberof Address6 - * @instance * @returns {String} */ getBitsPastSubnet() { @@ -439,10 +535,8 @@ class Address6 { } /** * 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) { @@ -460,7 +554,7 @@ class Address6 { if (options.omitSuffix) { return reversed; } - return (0, sprintf_js_1.sprintf)('%s.ip6.arpa.', reversed); + return `${reversed}.ip6.arpa.`; } if (options.omitSuffix) { return ''; @@ -468,10 +562,10 @@ class Address6 { return 'ip6.arpa.'; } /** - * Return the correct form of the address - * @memberof Address6 - * @instance - * @returns {String} + * Returns the address in correct form, per + * [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952): leading zeros + * stripped, the longest run of zero groups collapsed to `::`, and hex digits + * lowercased (e.g. `2001:db8::1`). This is the recommended form for display. */ correctForm() { let i; @@ -509,14 +603,12 @@ class Address6 { } let correct = groups.join(':'); correct = correct.replace(/^compact$/, '::'); - correct = correct.replace(/^compact|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'); @@ -525,10 +617,22 @@ class Address6 { * // 0000000000000000000000000000000000000000000000000001000000010001' */ binaryZeroPad() { - return this.bigInteger().toString(2).padStart(constants6.BITS, '0'); + if (this._binaryZeroPad === undefined) { + this._binaryZeroPad = this.bigInt().toString(2).padStart(constants6.BITS, '0'); + } + return this._binaryZeroPad; } + /** + * Parses a v4-in-v6 string (e.g. `::ffff:192.168.0.1`) by extracting the + * trailing IPv4 address into `this.address4` / `this.parsedAddress4` and + * returning the address with the v4 portion converted to two v6 groups. + * Used internally by `parse()`. + */ // TODO: Improve the semantics of this helper function parse4in6(address) { + if (address.indexOf('.') === -1) { + return address; + } const groups = address.split(':'); const lastGroup = groups.slice(-1)[0]; const address4 = lastGroup.match(constants4.RE_ADDRESS); @@ -537,7 +641,12 @@ class Address6 { 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('.'))); + // The prefix groups haven't been through the bad-character check + // yet, so escape them before including in the error HTML. + const highlighted = this.address4.parsedAddress.map(spanLeadingZeroes4).join('.'); + const prefix = groups.slice(0, -1).map(helpers.escapeHtml).join(':'); + const separator = groups.length > 1 ? ':' : ''; + throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", `${prefix}${separator}${highlighted}`); } } this.v4 = true; @@ -546,16 +655,23 @@ class Address6 { } return address; } + /** + * Parses an IPv6 address string into its 8 hexadecimal groups (expanding + * any `::` elision and any trailing v4-in-v6 portion) and stores the result + * on `this.parsedAddress`. Called automatically by the constructor; you + * typically don't need to call it directly. Throws `AddressError` if the + * input is malformed. + */ // 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')); + throw new address_error_1.AddressError(`Bad character${badCharacters.length > 1 ? 's' : ''} detected in address: ${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')); + throw new address_error_1.AddressError(`Address failed regex: ${badAddress.join('')}`, address.replace(constants6.RE_BAD_ADDRESS, '$1')); } let groups = []; const halves = address.split('::'); @@ -588,43 +704,37 @@ class Address6 { else { throw new address_error_1.AddressError('Too many :: groups found'); } - groups = groups.map((group) => (0, sprintf_js_1.sprintf)('%x', parseInt(group, 16))); + groups = groups.map((group) => parseInt(group, 16).toString(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} + * Returns the canonical (fully expanded) form of the address: all 8 groups, + * each padded to 4 hex digits, with no `::` collapsing + * (e.g. `2001:0db8:0000:0000:0000:0000:0000:0001`). Useful for sorting and + * byte-exact comparison. */ 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 this.parsedAddress.map((n) => parseInt(n, 16).toString(10).padStart(5, '0')).join(':'); } /** - * Return the address as a BigInteger - * @memberof Address6 - * @instance - * @returns {BigInteger} + * Return the address as a BigInt + * @returns {bigint} */ - bigInteger() { - return new jsbn_1.BigInteger(this.parsedAddress.map(paddedHex).join(''), 16); + bigInt() { + return BigInt(`0x${this.parsedAddress.map(paddedHex).join('')}`); } /** * 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'); @@ -632,12 +742,10 @@ class Address6 { */ to4() { const binary = this.binaryZeroPad().split(''); - return ipv4_1.Address4.fromHex(new jsbn_1.BigInteger(binary.slice(96, 128).join(''), 2).toString(16)); + return ipv4_1.Address4.fromHex(BigInt(`0b${binary.slice(96, 128).join('')}`).toString(16).padStart(8, '0')); } /** * Return the v4-in-v6 form of the address - * @memberof Address6 - * @instance * @returns {String} */ to4in6() { @@ -651,10 +759,10 @@ class Address6 { return correct + infix + address4.address; } /** - * Return an object containing the Teredo properties of the address - * @memberof Address6 - * @instance - * @returns {Object} + * Decodes the Teredo tunneling fields embedded in this address. Returns the + * Teredo prefix, server IPv4, client IPv4, raw flag bits, cone-NAT flag, + * UDP port, and Microsoft-format flag breakdown (reserved, universal/local, + * group/individual, nonce). Only meaningful for addresses in `2001::/32`. */ inspectTeredo() { /* @@ -679,18 +787,21 @@ class Address6 { 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 bitsForUdpPort = this.getBits(80, 96); + // eslint-disable-next-line no-bitwise + const udpPort = (bitsForUdpPort ^ BigInt('0xffff')).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 bitsForClient4 = this.getBits(96, 128); + // eslint-disable-next-line no-bitwise + const client4 = ipv4_1.Address4.fromHex((bitsForClient4 ^ BigInt('0xffffffff')).toString(16).padStart(8, '0')); 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); + const coneNat = (0, common_1.testBit)(flagsBase2, 15); + const reserved = (0, common_1.testBit)(flagsBase2, 14); + const groupIndividual = (0, common_1.testBit)(flagsBase2, 8); + const universalLocal = (0, common_1.testBit)(flagsBase2, 9); + const nonce = BigInt(`0b${flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16)}`).toString(10); return { - prefix: (0, sprintf_js_1.sprintf)('%s:%s', prefix.slice(0, 4), prefix.slice(4, 8)), + prefix: `${prefix.slice(0, 4)}:${prefix.slice(4, 8)}`, server4: server4.address, client4: client4.address, flags: flagsBase2, @@ -705,10 +816,9 @@ class Address6 { }; } /** - * Return an object containing the 6to4 properties of the address - * @memberof Address6 - * @instance - * @returns {Object} + * Decodes the 6to4 tunneling fields embedded in this address. Returns the + * 6to4 prefix and the embedded IPv4 gateway address. Only meaningful for + * addresses in `2002::/16`. */ inspect6to4() { /* @@ -718,14 +828,12 @@ class Address6 { 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)), + prefix: prefix.slice(0, 4), gateway: gateway.address, }; } /** * Return a v6 6to4 address from a v6 v4inv6 address - * @memberof Address6 - * @instance * @returns {Address6} */ to6to4() { @@ -742,57 +850,128 @@ class Address6 { return new Address6(addr6to4); } /** - * Return a byte array - * @memberof Address6 - * @instance + * Embed an IPv4 address into a NAT64 IPv6 address using the encoding + * defined by [RFC 6052](https://datatracker.ietf.org/doc/html/rfc6052). + * The default prefix is the well-known prefix `64:ff9b::/96`. The prefix + * length must be one of 32, 40, 48, 56, 64, or 96; for prefixes shorter + * than /64 the IPv4 octets are split around the reserved bits 64–71. + * @example + * Address6.fromAddress4Nat64('192.0.2.33').correctForm(); // '64:ff9b::c000:221' + * Address6.fromAddress4Nat64('192.0.2.33', '2001:db8::/32').correctForm(); // '2001:db8:c000:221::' + */ + static fromAddress4Nat64(address, prefix = '64:ff9b::/96') { + const v4 = new ipv4_1.Address4(address); + const prefix6 = new Address6(prefix); + const pl = prefix6.subnetMask; + if (pl !== 32 && pl !== 40 && pl !== 48 && pl !== 56 && pl !== 64 && pl !== 96) { + throw new address_error_1.AddressError('NAT64 prefix length must be 32, 40, 48, 56, 64, or 96'); + } + const prefixBits = prefix6.binaryZeroPad(); + const v4Bits = v4.binaryZeroPad(); + let bits; + if (pl === 96) { + bits = prefixBits.slice(0, 96) + v4Bits; + } + else { + const beforeU = 64 - pl; + bits = + prefixBits.slice(0, pl) + + v4Bits.slice(0, beforeU) + + '00000000' + + v4Bits.slice(beforeU) + + '0'.repeat(128 - 72 - (32 - beforeU)); + } + const hex = BigInt(`0b${bits}`).toString(16).padStart(32, '0'); + const groups = []; + for (let i = 0; i < 8; i++) { + groups.push(hex.slice(i * 4, (i + 1) * 4)); + } + return new Address6(groups.join(':')); + } + /** + * Extract the embedded IPv4 address from a NAT64 IPv6 address using the + * encoding defined by [RFC 6052](https://datatracker.ietf.org/doc/html/rfc6052). + * The default prefix is the well-known prefix `64:ff9b::/96`. Returns + * `null` if this address is not contained within the given prefix. + * @example + * new Address6('64:ff9b::c000:221').toAddress4Nat64()!.correctForm(); // '192.0.2.33' + */ + toAddress4Nat64(prefix = '64:ff9b::/96') { + const prefix6 = new Address6(prefix); + const pl = prefix6.subnetMask; + if (pl !== 32 && pl !== 40 && pl !== 48 && pl !== 56 && pl !== 64 && pl !== 96) { + throw new address_error_1.AddressError('NAT64 prefix length must be 32, 40, 48, 56, 64, or 96'); + } + if (!this.isInSubnet(prefix6)) { + return null; + } + const bits = this.binaryZeroPad(); + let v4Bits; + if (pl === 96) { + v4Bits = bits.slice(96, 128); + } + else { + const beforeU = 64 - pl; + v4Bits = bits.slice(pl, pl + beforeU) + bits.slice(72, 72 + (32 - beforeU)); + } + const octets = []; + for (let i = 0; i < 4; i++) { + octets.push(parseInt(v4Bits.slice(i * 8, (i + 1) * 8), 2).toString()); + } + return new ipv4_1.Address4(octets.join('.')); + } + /** + * Return a byte array. + * + * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toByteArray())`. * @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); + const valueWithoutPadding = this.bigInt().toString(16); + const leadingPad = '0'.repeat(valueWithoutPadding.length % 2); + const value = `${leadingPad}${valueWithoutPadding}`; + const bytes = []; + for (let i = 0, length = value.length; i < length; i += 2) { + bytes.push(parseInt(value.substring(i, i + 2), 16)); } - return byteArray; + return bytes; } /** - * Return an unsigned byte array - * @memberof Address6 - * @instance + * Return an unsigned byte array. + * + * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toUnsignedByteArray())`. * @returns {Array} */ toUnsignedByteArray() { return this.toByteArray().map(unsignByte); } /** - * Convert a byte array to an Address6 object - * @memberof Address6 - * @static + * Convert a byte array to an Address6 object. + * + * To convert from a Node.js `Buffer`, spread it: `Address6.fromByteArray([...buf])`. * @returns {Address6} */ static fromByteArray(bytes) { return this.fromUnsignedByteArray(bytes.map(unsignByte)); } /** - * Convert an unsigned byte array to an Address6 object - * @memberof Address6 - * @static + * Convert an unsigned byte array to an Address6 object. + * + * To convert from a Node.js `Buffer`, spread it: `Address6.fromUnsignedByteArray([...buf])`. * @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); + const BYTE_MAX = BigInt('256'); + let result = BigInt('0'); + let multiplier = BigInt('1'); 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); + result += multiplier * BigInt(bytes[i].toString(10)); + multiplier *= BYTE_MAX; } - return Address6.fromBigInteger(result); + return Address6.fromBigInt(result); } /** * Returns true if the address is in the canonical form, false otherwise - * @memberof Address6 - * @instance * @returns {boolean} */ isCanonical() { @@ -800,8 +979,6 @@ class Address6 { } /** * Returns true if the address is a link local address, false otherwise - * @memberof Address6 - * @instance * @returns {boolean} */ isLinkLocal() { @@ -814,65 +991,98 @@ class Address6 { } /** * Returns true if the address is a multicast address, false otherwise - * @memberof Address6 - * @instance * @returns {boolean} */ isMulticast() { - return this.getType() === 'Multicast'; + const type = this.getType(); + return type === 'Multicast' || type.startsWith('Multicast '); } /** - * Returns true if the address is a v4-in-v6 address, false otherwise - * @memberof Address6 - * @instance + * Returns true if the address was written in v4-in-v6 dotted-quad notation + * (e.g. `::ffff:127.0.0.1`), false otherwise. This is a notation-level flag + * and does not reflect whether the address bits lie in the IPv4-mapped + * (`::ffff:0:0/96`) subnet — for that, see {@link isMapped4}. * @returns {boolean} */ is4() { return this.v4; } + /** + * Returns true if the address is an IPv4-mapped IPv6 address in + * `::ffff:0:0/96` ([RFC 4291 §2.5.5.2](https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2)), + * false otherwise. Unlike {@link is4}, this checks the underlying address + * bits rather than the textual notation, so `::ffff:127.0.0.1` and + * `::ffff:7f00:1` both return true. + * @returns {boolean} + */ + isMapped4() { + return this.isInSubnet(IPV4_MAPPED_SUBNET); + } /** * Returns true if the address is a Teredo address, false otherwise - * @memberof Address6 - * @instance * @returns {boolean} */ isTeredo() { - return this.isInSubnet(new Address6('2001::/32')); + return this.isInSubnet(TEREDO_SUBNET); } /** * Returns true if the address is a 6to4 address, false otherwise - * @memberof Address6 - * @instance * @returns {boolean} */ is6to4() { - return this.isInSubnet(new Address6('2002::/16')); + return this.isInSubnet(SIX_TO_FOUR_SUBNET); } /** * Returns true if the address is a loopback address, false otherwise - * @memberof Address6 - * @instance * @returns {boolean} */ isLoopback() { return this.getType() === 'Loopback'; } + /** + * Returns true if the address is a Unique Local Address in `fc00::/7` ([RFC 4193](https://datatracker.ietf.org/doc/html/rfc4193)). ULAs are the IPv6 equivalent of IPv4 [RFC 1918](https://datatracker.ietf.org/doc/html/rfc1918) private addresses. + * @returns {boolean} + */ + isULA() { + return this.isInSubnet(ULA_SUBNET); + } + /** + * Returns true if the address is the unspecified address `::`. + * @returns {boolean} + */ + isUnspecified() { + return this.getType() === 'Unspecified'; + } + /** + * Returns true if the address is in the documentation prefix `2001:db8::/32` ([RFC 3849](https://datatracker.ietf.org/doc/html/rfc3849)). + * @returns {boolean} + */ + isDocumentation() { + return this.isInSubnet(DOCUMENTATION_SUBNET); + } // #endregion // #region HTML /** - * @returns {String} the address in link form with a default port of 80 + * Returns the address as an HTTP URL with the host bracketed, e.g. + * `http://[2001:db8::1]/`. If `optionalPort` is provided it is appended, + * e.g. `http://[2001:db8::1]:8080/`. */ href(optionalPort) { if (optionalPort === undefined) { optionalPort = ''; } else { - optionalPort = (0, sprintf_js_1.sprintf)(':%s', optionalPort); + optionalPort = `:${optionalPort}`; } - return (0, sprintf_js_1.sprintf)('http://[%s]%s/', this.correctForm(), optionalPort); + return `http://[${this.correctForm()}]${optionalPort}/`; } /** - * @returns {String} a link suitable for conveying the address via a URL hash + * Returns an HTML `` element whose `href` encodes the address in a URL + * hash fragment (default prefix `/#address=`). Useful for linking between + * pages of an address-inspector UI. + * @param options.className - CSS class for the rendered `` element + * @param options.prefix - hash prefix prepended to the address (default `/#address=`) + * @param options.v4 - when true, render the address in v4-in-v6 form */ link(options) { if (!options) { @@ -891,10 +1101,14 @@ class Address6 { if (options.v4) { formFunction = this.to4in6; } + const form = formFunction.call(this); + const safeHref = helpers.escapeHtml(`${options.prefix}${form}`); + const safeForm = helpers.escapeHtml(form); if (options.className) { - return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this), options.className); + const safeClass = helpers.escapeHtml(options.className); + return `${safeForm}`; } - return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this)); + return `${safeForm}`; } /** * Groups an address @@ -903,13 +1117,13 @@ class Address6 { group() { if (this.elidedGroups === 0) { // The simple case - return helpers.simpleGroup(this.address).join(':'); + return helpers.simpleGroup(this.addressMinusSuffix).join(':'); } assert(typeof this.elidedGroups === 'number'); assert(typeof this.elisionBegin === 'number'); // The elided case const output = []; - const [left, right] = this.address.split('::'); + const [left, right] = this.addressMinusSuffix.split('::'); if (left.length) { output.push(...helpers.simpleGroup(left)); } @@ -918,9 +1132,9 @@ class Address6 { } 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)); + classes.push(`group-${i}`); } - output.push((0, sprintf_js_1.sprintf)('', classes.join(' '))); + output.push(``); if (right.length) { output.push(...helpers.simpleGroup(right, this.elisionEnd)); } @@ -939,8 +1153,6 @@ class Address6 { /** * 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} */ @@ -985,8 +1197,6 @@ class Address6 { /** * 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} */ @@ -995,4 +1205,13 @@ class Address6 { } } exports.Address6 = Address6; +const TYPE_SUBNETS = Object.keys(constants6.TYPES).map((subnet) => [ + new Address6(subnet), + constants6.TYPES[subnet], +]); +const TEREDO_SUBNET = new Address6('2001::/32'); +const SIX_TO_FOUR_SUBNET = new Address6('2002::/16'); +const ULA_SUBNET = new Address6('fc00::/7'); +const DOCUMENTATION_SUBNET = new Address6('2001:db8::/32'); +const IPV4_MAPPED_SUBNET = new Address6('::ffff:0:0/96'); //# sourceMappingURL=ipv6.js.map \ No newline at end of file diff --git a/node_modules/ip-address/dist/v6/constants.js b/node_modules/ip-address/dist/v6/constants.js index e316bb0d0c2cd..1a8cd1dd616e8 100644 --- a/node_modules/ip-address/dist/v6/constants.js +++ b/node_modules/ip-address/dist/v6/constants.js @@ -46,6 +46,11 @@ exports.TYPES = { '::1/128': 'Loopback', 'ff00::/8': 'Multicast', 'fe80::/10': 'Link-local unicast', + 'fc00::/7': 'Unique local', + '2002::/16': '6to4', + '2001:db8::/32': 'Documentation', + '64:ff9b::/96': 'NAT64 (well-known)', + '64:ff9b:1::/48': 'NAT64 (local-use)', }; /** * A regular expression that matches bad characters in an IPv6 address @@ -71,6 +76,6 @@ exports.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/; * @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})/); +exports.RE_URL = /^\[{0,1}([0-9a-f:]+)\]{0,1}/; +exports.RE_URL_WITH_PORT = /\[([0-9a-f:]+)\]:([0-9]{1,5})/; //# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/ip-address/dist/v6/helpers.js b/node_modules/ip-address/dist/v6/helpers.js index 918aaa58c85d7..e6bae04698a66 100644 --- a/node_modules/ip-address/dist/v6/helpers.js +++ b/node_modules/ip-address/dist/v6/helpers.js @@ -1,27 +1,35 @@ "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"); +exports.escapeHtml = escapeHtml; +exports.spanAllZeroes = spanAllZeroes; +exports.spanAll = spanAll; +exports.spanLeadingZeroes = spanLeadingZeroes; +exports.simpleGroup = simpleGroup; +function escapeHtml(s) { + return s + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} /** * @returns {String} the string with all zeroes contained in a */ function spanAllZeroes(s) { - return s.replace(/(0+)/g, '$1'); + return escapeHtml(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? - ) + .map((n, i) => `${spanAllZeroes(n)}`) .join(''); } -exports.spanAll = spanAll; function spanLeadingZeroesSimple(group) { - return group.replace(/^(0+)/, '$1'); + return escapeHtml(group).replace(/^(0+)/, '$1'); } /** * @returns {String} the string with leading zeroes contained in a @@ -30,7 +38,6 @@ 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 @@ -41,8 +48,7 @@ function simpleGroup(addressString, offset = 0) { if (/group-v4/.test(g)) { return g; } - return (0, sprintf_js_1.sprintf)('%s', i + offset, spanLeadingZeroesSimple(g)); + return `${spanLeadingZeroesSimple(g)}`; }); } -exports.simpleGroup = simpleGroup; //# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/ip-address/dist/v6/regular-expressions.js b/node_modules/ip-address/dist/v6/regular-expressions.js index 616550a864509..a2c51459307fd 100644 --- a/node_modules/ip-address/dist/v6/regular-expressions.js +++ b/node_modules/ip-address/dist/v6/regular-expressions.js @@ -23,20 +23,21 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.possibleElisions = exports.simpleRegularExpression = exports.ADDRESS_BOUNDARY = exports.padGroup = exports.groupPossibilities = void 0; +exports.ADDRESS_BOUNDARY = void 0; +exports.groupPossibilities = groupPossibilities; +exports.padGroup = padGroup; +exports.simpleRegularExpression = simpleRegularExpression; +exports.possibleElisions = possibleElisions; const v6 = __importStar(require("./constants")); -const sprintf_js_1 = require("sprintf-js"); function groupPossibilities(possibilities) { - return (0, sprintf_js_1.sprintf)('(%s)', possibilities.join('|')); + return `(${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 `0{0,${4 - group.length}}${group}`; } return group; } -exports.padGroup = padGroup; exports.ADDRESS_BOUNDARY = '[^A-Fa-f0-9:]'; function simpleRegularExpression(groups) { const zeroIndexes = []; @@ -61,7 +62,6 @@ function simpleRegularExpression(groups) { possibilities.push(groups.map(padGroup).join(':')); return groupPossibilities(possibilities); } -exports.simpleRegularExpression = simpleRegularExpression; function possibleElisions(elidedGroups, moreLeft, moreRight) { const left = moreLeft ? '' : ':'; const right = moreRight ? '' : ':'; @@ -79,18 +79,17 @@ function possibleElisions(elidedGroups, moreLeft, moreRight) { possibilities.push(':'); } // 4. elision from the left side - possibilities.push((0, sprintf_js_1.sprintf)('%s(:0{1,4}){1,%d}', left, elidedGroups - 1)); + possibilities.push(`${left}(:0{1,4}){1,${elidedGroups - 1}}`); // 5. elision from the right side - possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){1,%d}%s', elidedGroups - 1, right)); + possibilities.push(`(0{1,4}:){1,${elidedGroups - 1}}${right}`); // 6. no elision - possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}0{1,4}', elidedGroups - 1)); + possibilities.push(`(0{1,4}:){${elidedGroups - 1}}0{1,4}`); // 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)); + possibilities.push(`(0{1,4}:){${position}}:(0{1,4}:){${elidedGroups - position - groups - 1}}0{1,4}`); } } return groupPossibilities(possibilities); } -exports.possibleElisions = possibleElisions; //# sourceMappingURL=regular-expressions.js.map \ No newline at end of file diff --git a/node_modules/ip-address/package.json b/node_modules/ip-address/package.json index 0543fc41a1306..47d109ec6f34d 100644 --- a/node_modules/ip-address/package.json +++ b/node_modules/ip-address/package.json @@ -2,86 +2,87 @@ "name": "ip-address", "description": "A library for parsing IPv4 and IPv6 IP addresses in node and the browser.", "keywords": [ - "ipv6", + "ip", "ipv4", - "browser", - "validation" + "ipv6", + "address", + "cidr", + "subnet", + "netmask", + "validate", + "validation", + "parse", + "arpa", + "bigint", + "browser" ], - "version": "9.0.5", + "version": "10.2.0", "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", + "docs": "tsx scripts/build-readme.ts", "build": "rm -rf dist; mkdir dist; tsc", - "prepack": "npm run build", - "release": "release-it", - "test-ci": "nyc mocha", + "prepack": "npm run docs && npm run build", + "test-ci": "c8 --experimental-monocart mocha", "test": "mocha", "watch": "mocha --watch" }, - "nyc": { - "extension": [ - ".ts" + "c8": { + "include": [ + "src/**/*.ts" ], "exclude": [ "**/*.d.ts", - ".eslintrc.js", - "coverage/", - "dist/", - "test/", - "tmp/" + "src/ip-address.ts", + "src/v4/constants.ts", + "src/v6/constants.ts" ], "reporter": [ "html", "lcov", "text" - ], - "all": true + ] }, "engines": { "node": ">= 12" }, + "sideEffects": false, "files": [ - "src", "dist" ], "repository": { "type": "git", "url": "git://github.com/beaugunderson/ip-address.git" }, - "dependencies": { - "jsbn": "1.1.0", - "sprintf-js": "^1.1.3" + "overrides": { + "diff": "^8.0.3", + "serialize-javascript": "^7.0.5", + "@eslint/plugin-kit": "^0.7.1" }, "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", + "@types/chai": "^5.2.3", + "@types/mocha": "^10.0.10", + "@typescript-eslint/eslint-plugin": "^8.59.1", + "@typescript-eslint/parser": "^8.59.1", + "c8": "^11.0.0", + "chai": "^6.2.2", + "eslint": "^8.57.1", + "eslint_d": "^14.0.4", "eslint-config-airbnb": "^19.0.4", - "eslint-config-prettier": "^9.0.0", + "eslint-config-prettier": "^10.1.8", "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-import": "^2.32.0", + "eslint-plugin-jsx-a11y": "^6.10.2", + "eslint-plugin-prettier": "^5.5.5", "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" + "mocha": "^11.7.5", + "monocart-coverage-reports": "^2.12.11", + "prettier": "^3.8.3", + "source-map-support": "^0.5.21", + "tsx": "^4.21.0", + "typedoc": "^0.28.19", + "typescript": "<5.6.0" } } diff --git a/node_modules/ip-regex/index.js b/node_modules/ip-regex/index.js deleted file mode 100644 index 1fe723cb7f5a9..0000000000000 --- a/node_modules/ip-regex/index.js +++ /dev/null @@ -1,36 +0,0 @@ -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; diff --git a/node_modules/ip-regex/license b/node_modules/ip-regex/license deleted file mode 100644 index fa7ceba3eb4a9..0000000000000 --- a/node_modules/ip-regex/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/ip-regex/package.json b/node_modules/ip-regex/package.json deleted file mode 100644 index 1f82fd5947262..0000000000000 --- a/node_modules/ip-regex/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/is-cidr/LICENSE b/node_modules/is-cidr/LICENSE new file mode 100644 index 0000000000000..9669c20f85511 --- /dev/null +++ b/node_modules/is-cidr/LICENSE @@ -0,0 +1,22 @@ +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. diff --git a/node_modules/is-cidr/dist/index.js b/node_modules/is-cidr/dist/index.js index 35fba31c48c66..e035837673a7e 100644 --- a/node_modules/is-cidr/dist/index.js +++ b/node_modules/is-cidr/dist/index.js @@ -1,11 +1,11 @@ import { v4 as v4$1, v6 as v6$1 } from "cidr-regex"; + +//#region index.ts 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 -}; + +//#endregion +export { isCidr as default, v4, v6 }; \ No newline at end of file diff --git a/node_modules/is-cidr/package.json b/node_modules/is-cidr/package.json index 4b0e95b9c78c7..ace65f1de9986 100644 --- a/node_modules/is-cidr/package.json +++ b/node_modules/is-cidr/package.json @@ -1,6 +1,6 @@ { "name": "is-cidr", - "version": "5.1.0", + "version": "7.0.0", "description": "Check if a string is an IP address in CIDR notation", "author": "silverwind ", "contributors": [ @@ -8,6 +8,14 @@ ], "repository": "silverwind/is-cidr", "license": "BSD-2-Clause", + "keywords": [ + "cidr", + "ip", + "ipv4", + "ipv6", + "subnet", + "network" + ], "type": "module", "sideEffects": false, "main": "./dist/index.js", @@ -17,24 +25,25 @@ "dist" ], "engines": { - "node": ">=14" + "node": ">=22" }, "dependencies": { - "cidr-regex": "^4.1.1" + "cidr-regex": "^6.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" + "@types/node": "25.6.0", + "@typescript/native-preview": "7.0.0-dev.20260427.1", + "eslint": "10.2.1", + "eslint-config-silverwind": "132.0.0", + "jest-extended": "7.0.0", + "tsdown": "0.21.10", + "tsdown-config-silverwind": "3.0.0", + "typescript": "6.0.3", + "typescript-config-silverwind": "18.0.0", + "updates": "17.16.4", + "updates-config-silverwind": "3.0.0", + "versions": "15.0.1", + "vitest": "4.1.5", + "vitest-config-silverwind": "11.3.3" } -} +} \ No newline at end of file diff --git a/node_modules/is-fullwidth-code-point/index.js b/node_modules/is-fullwidth-code-point/index.js deleted file mode 100644 index 671f97f760779..0000000000000 --- a/node_modules/is-fullwidth-code-point/index.js +++ /dev/null @@ -1,50 +0,0 @@ -/* 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; diff --git a/node_modules/is-fullwidth-code-point/license b/node_modules/is-fullwidth-code-point/license deleted file mode 100644 index e7af2f77107d7..0000000000000 --- a/node_modules/is-fullwidth-code-point/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/is-fullwidth-code-point/package.json b/node_modules/is-fullwidth-code-point/package.json deleted file mode 100644 index 2137e888fa503..0000000000000 --- a/node_modules/is-fullwidth-code-point/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/is-lambda/LICENSE b/node_modules/is-lambda/LICENSE deleted file mode 100644 index 4a59c94175c2a..0000000000000 --- a/node_modules/is-lambda/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016-2017 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. diff --git a/node_modules/is-lambda/index.js b/node_modules/is-lambda/index.js deleted file mode 100644 index b245ab1c68df1..0000000000000 --- a/node_modules/is-lambda/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict' - -module.exports = !!( - (process.env.LAMBDA_TASK_ROOT && process.env.AWS_EXECUTION_ENV) || - false -) diff --git a/node_modules/is-lambda/package.json b/node_modules/is-lambda/package.json deleted file mode 100644 index d8550898b4e4d..0000000000000 --- a/node_modules/is-lambda/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "is-lambda", - "version": "1.0.1", - "description": "Detect if your code is running on an AWS Lambda server", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "clear-require": "^1.0.1", - "standard": "^10.0.2" - }, - "scripts": { - "test": "standard && node test.js" - }, - "repository": { - "type": "git", - "url": "https://github.com/watson/is-lambda.git" - }, - "keywords": [ - "aws", - "hosting", - "hosted", - "lambda", - "detect" - ], - "author": "Thomas Watson Steen (https://twitter.com/wa7son)", - "license": "MIT", - "bugs": { - "url": "https://github.com/watson/is-lambda/issues" - }, - "homepage": "https://github.com/watson/is-lambda", - "coordinates": [ - 37.3859955, - -122.0838831 - ] -} diff --git a/node_modules/is-lambda/test.js b/node_modules/is-lambda/test.js deleted file mode 100644 index e8e73257ad4ad..0000000000000 --- a/node_modules/is-lambda/test.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict' - -var assert = require('assert') -var clearRequire = require('clear-require') - -process.env.AWS_EXECUTION_ENV = 'AWS_Lambda_nodejs6.10' -process.env.LAMBDA_TASK_ROOT = '/var/task' - -var isCI = require('./') -assert(isCI) - -delete process.env.AWS_EXECUTION_ENV - -clearRequire('./') -isCI = require('./') -assert(!isCI) diff --git a/node_modules/isexe/LICENSE b/node_modules/isexe/LICENSE deleted file mode 100644 index 19129e315fe59..0000000000000 --- a/node_modules/isexe/LICENSE +++ /dev/null @@ -1,15 +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. diff --git a/node_modules/isexe/LICENSE.md b/node_modules/isexe/LICENSE.md new file mode 100644 index 0000000000000..c5402b9577a8c --- /dev/null +++ b/node_modules/isexe/LICENSE.md @@ -0,0 +1,55 @@ +# 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.*** diff --git a/node_modules/isexe/dist/commonjs/index.js b/node_modules/isexe/dist/commonjs/index.js new file mode 100644 index 0000000000000..71882e7b4d518 --- /dev/null +++ b/node_modules/isexe/dist/commonjs/index.js @@ -0,0 +1,56 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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.sync = exports.isexe = exports.posix = exports.win32 = void 0; +const posix = __importStar(require("./posix.js")); +exports.posix = posix; +const win32 = __importStar(require("./win32.js")); +exports.win32 = win32; +__exportStar(require("./options.js"), exports); +const platform = process.env._ISEXE_TEST_PLATFORM_ || process.platform; +const impl = platform === 'win32' ? win32 : posix; +/** + * Determine whether a path is executable on the current platform. + */ +exports.isexe = impl.isexe; +/** + * Synchronously determine whether a path is executable on the + * current platform. + */ +exports.sync = impl.sync; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/isexe/dist/commonjs/index.min.js b/node_modules/isexe/dist/commonjs/index.min.js new file mode 100644 index 0000000000000..7cb0271bca096 --- /dev/null +++ b/node_modules/isexe/dist/commonjs/index.min.js @@ -0,0 +1,2 @@ +"use strict";var a=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var _=a(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0});i.sync=i.isexe=void 0;var M=require("node:fs"),x=require("node:fs/promises"),q=async(t,e={})=>{let{ignoreErrors:r=!1}=e;try{return d(await(0,x.stat)(t),e)}catch(s){let n=s;if(r||n.code==="EACCES")return!1;throw n}};i.isexe=q;var m=(t,e={})=>{let{ignoreErrors:r=!1}=e;try{return d((0,M.statSync)(t),e)}catch(s){let n=s;if(r||n.code==="EACCES")return!1;throw n}};i.sync=m;var d=(t,e)=>t.isFile()&&A(t,e),A=(t,e)=>{let r=e.uid??process.getuid?.(),s=e.groups??process.getgroups?.()??[],n=e.gid??process.getgid?.()??s[0];if(r===void 0||n===void 0)throw new Error("cannot get uid or gid");let u=new Set([n,...s]),c=t.mode,S=t.uid,P=t.gid,f=parseInt("100",8),l=parseInt("010",8),j=parseInt("001",8),C=f|l;return!!(c&j||c&l&&u.has(P)||c&f&&S===r||c&C&&r===0)}});var g=a(o=>{"use strict";Object.defineProperty(o,"__esModule",{value:!0});o.sync=o.isexe=void 0;var T=require("node:fs"),I=require("node:fs/promises"),D=require("node:path"),F=async(t,e={})=>{let{ignoreErrors:r=!1}=e;try{return y(await(0,I.stat)(t),t,e)}catch(s){let n=s;if(r||n.code==="EACCES")return!1;throw n}};o.isexe=F;var L=(t,e={})=>{let{ignoreErrors:r=!1}=e;try{return y((0,T.statSync)(t),t,e)}catch(s){let n=s;if(r||n.code==="EACCES")return!1;throw n}};o.sync=L;var B=(t,e)=>{let{pathExt:r=process.env.PATHEXT||""}=e,s=r.split(D.delimiter);if(s.indexOf("")!==-1)return!0;for(let n of s){let u=n.toLowerCase(),c=t.substring(t.length-u.length).toLowerCase();if(u&&c===u)return!0}return!1},y=(t,e,r)=>t.isFile()&&B(e,r)});var p=a(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0})});var v=exports&&exports.__createBinding||(Object.create?(function(t,e,r,s){s===void 0&&(s=r);var n=Object.getOwnPropertyDescriptor(e,r);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,s,n)}):(function(t,e,r,s){s===void 0&&(s=r),t[s]=e[r]})),G=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),w=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var s=[];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(s[s.length]=n);return s},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var s=t(e),n=0;n { + const { ignoreErrors = false } = options; + try { + return checkStat(await (0, promises_1.stat)(path), options); + } + catch (e) { + const er = e; + if (ignoreErrors || er.code === 'EACCES') + return false; + throw er; + } +}; +exports.isexe = isexe; +/** + * Synchronously determine whether a path is executable according to + * the mode and current (or specified) user and group IDs. + */ +const sync = (path, options = {}) => { + const { ignoreErrors = false } = options; + try { + return checkStat((0, node_fs_1.statSync)(path), options); + } + catch (e) { + const er = e; + if (ignoreErrors || er.code === 'EACCES') + return false; + throw er; + } +}; +exports.sync = sync; +const checkStat = (stat, options) => stat.isFile() && checkMode(stat, options); +const checkMode = (stat, options) => { + const myUid = options.uid ?? process.getuid?.(); + const myGroups = options.groups ?? process.getgroups?.() ?? []; + const myGid = options.gid ?? process.getgid?.() ?? myGroups[0]; + if (myUid === undefined || myGid === undefined) { + throw new Error('cannot get uid or gid'); + } + const groups = new Set([myGid, ...myGroups]); + const mod = stat.mode; + const uid = stat.uid; + const gid = stat.gid; + const u = parseInt('100', 8); + const g = parseInt('010', 8); + const o = parseInt('001', 8); + const ug = u | g; + return !!(mod & o || + (mod & g && groups.has(gid)) || + (mod & u && uid === myUid) || + (mod & ug && myUid === 0)); +}; +//# sourceMappingURL=posix.js.map \ No newline at end of file diff --git a/node_modules/isexe/dist/commonjs/win32.js b/node_modules/isexe/dist/commonjs/win32.js new file mode 100644 index 0000000000000..c1524a1d53348 --- /dev/null +++ b/node_modules/isexe/dist/commonjs/win32.js @@ -0,0 +1,63 @@ +"use strict"; +/** + * This is the Windows implementation of isexe, which uses the file + * extension and PATHEXT setting. + * + * @module + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sync = exports.isexe = void 0; +const node_fs_1 = require("node:fs"); +const promises_1 = require("node:fs/promises"); +const node_path_1 = require("node:path"); +/** + * Determine whether a path is executable based on the file extension + * and PATHEXT environment variable (or specified pathExt option) + */ +const isexe = async (path, options = {}) => { + const { ignoreErrors = false } = options; + try { + return checkStat(await (0, promises_1.stat)(path), path, options); + } + catch (e) { + const er = e; + if (ignoreErrors || er.code === 'EACCES') + return false; + throw er; + } +}; +exports.isexe = isexe; +/** + * Synchronously determine whether a path is executable based on the file + * extension and PATHEXT environment variable (or specified pathExt option) + */ +const sync = (path, options = {}) => { + const { ignoreErrors = false } = options; + try { + return checkStat((0, node_fs_1.statSync)(path), path, options); + } + catch (e) { + const er = e; + if (ignoreErrors || er.code === 'EACCES') + return false; + throw er; + } +}; +exports.sync = sync; +const checkPathExt = (path, options) => { + const { pathExt = process.env.PATHEXT || '' } = options; + const peSplit = pathExt.split(node_path_1.delimiter); + if (peSplit.indexOf('') !== -1) { + return true; + } + for (const pes of peSplit) { + const p = pes.toLowerCase(); + const ext = path.substring(path.length - p.length).toLowerCase(); + if (p && ext === p) { + return true; + } + } + return false; +}; +const checkStat = (stat, path, options) => stat.isFile() && checkPathExt(path, options); +//# sourceMappingURL=win32.js.map \ No newline at end of file diff --git a/node_modules/which/node_modules/isexe/dist/mjs/index.js b/node_modules/isexe/dist/esm/index.js similarity index 100% rename from node_modules/which/node_modules/isexe/dist/mjs/index.js rename to node_modules/isexe/dist/esm/index.js diff --git a/node_modules/isexe/dist/esm/index.min.js b/node_modules/isexe/dist/esm/index.min.js new file mode 100644 index 0000000000000..f3a6fc37d6c66 --- /dev/null +++ b/node_modules/isexe/dist/esm/index.min.js @@ -0,0 +1,2 @@ +var y=Object.defineProperty;var u=(t,r)=>{for(var e in r)y(t,e,{get:r[e],enumerable:!0})};var i={};u(i,{isexe:()=>C,sync:()=>A});import{statSync as w}from"node:fs";import{stat as S}from"node:fs/promises";var C=async(t,r={})=>{let{ignoreErrors:e=!1}=r;try{return d(await S(t),r)}catch(s){let o=s;if(e||o.code==="EACCES")return!1;throw o}},A=(t,r={})=>{let{ignoreErrors:e=!1}=r;try{return d(w(t),r)}catch(s){let o=s;if(e||o.code==="EACCES")return!1;throw o}},d=(t,r)=>t.isFile()&&T(t,r),T=(t,r)=>{let e=r.uid??process.getuid?.(),s=r.groups??process.getgroups?.()??[],o=r.gid??process.getgid?.()??s[0];if(e===void 0||o===void 0)throw new Error("cannot get uid or gid");let c=new Set([o,...s]),n=t.mode,l=t.uid,E=t.gid,f=parseInt("100",8),p=parseInt("010",8),x=parseInt("001",8),h=f|p;return!!(n&x||n&p&&c.has(E)||n&f&&l===e||n&h&&e===0)};var a={};u(a,{isexe:()=>F,sync:()=>L});import{statSync as k}from"node:fs";import{stat as I}from"node:fs/promises";import{delimiter as _}from"node:path";var F=async(t,r={})=>{let{ignoreErrors:e=!1}=r;try{return m(await I(t),t,r)}catch(s){let o=s;if(e||o.code==="EACCES")return!1;throw o}},L=(t,r={})=>{let{ignoreErrors:e=!1}=r;try{return m(k(t),t,r)}catch(s){let o=s;if(e||o.code==="EACCES")return!1;throw o}},P=(t,r)=>{let{pathExt:e=process.env.PATHEXT||""}=r,s=e.split(_);if(s.indexOf("")!==-1)return!0;for(let o of s){let c=o.toLowerCase(),n=t.substring(t.length-c.length).toLowerCase();if(c&&n===c)return!0}return!1},m=(t,r,e)=>t.isFile()&&P(r,e);var v=process.env._ISEXE_TEST_PLATFORM_||process.platform,g=v==="win32"?a:i,R=g.isexe,U=g.sync;export{R as isexe,i as posix,U as sync,a as win32}; +//# sourceMappingURL=index.min.js.map diff --git a/node_modules/which/node_modules/isexe/dist/mjs/options.js b/node_modules/isexe/dist/esm/options.js similarity index 100% rename from node_modules/which/node_modules/isexe/dist/mjs/options.js rename to node_modules/isexe/dist/esm/options.js diff --git a/node_modules/isexe/dist/esm/package.json b/node_modules/isexe/dist/esm/package.json new file mode 100644 index 0000000000000..3dbc1ca591c05 --- /dev/null +++ b/node_modules/isexe/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/isexe/dist/esm/posix.js b/node_modules/isexe/dist/esm/posix.js new file mode 100644 index 0000000000000..f1af6d51a402d --- /dev/null +++ b/node_modules/isexe/dist/esm/posix.js @@ -0,0 +1,62 @@ +/** + * This is the Posix implementation of isexe, which uses the file + * mode and uid/gid values. + * + * @module + */ +import { statSync } from 'node:fs'; +import { stat } from 'node:fs/promises'; +/** + * Determine whether a path is executable according to the mode and + * current (or specified) user and group IDs. + */ +export const isexe = async (path, options = {}) => { + const { ignoreErrors = false } = options; + try { + return checkStat(await stat(path), options); + } + catch (e) { + const er = e; + if (ignoreErrors || er.code === 'EACCES') + return false; + throw er; + } +}; +/** + * Synchronously determine whether a path is executable according to + * the mode and current (or specified) user and group IDs. + */ +export const sync = (path, options = {}) => { + const { ignoreErrors = false } = options; + try { + return checkStat(statSync(path), options); + } + catch (e) { + const er = e; + if (ignoreErrors || er.code === 'EACCES') + return false; + throw er; + } +}; +const checkStat = (stat, options) => stat.isFile() && checkMode(stat, options); +const checkMode = (stat, options) => { + const myUid = options.uid ?? process.getuid?.(); + const myGroups = options.groups ?? process.getgroups?.() ?? []; + const myGid = options.gid ?? process.getgid?.() ?? myGroups[0]; + if (myUid === undefined || myGid === undefined) { + throw new Error('cannot get uid or gid'); + } + const groups = new Set([myGid, ...myGroups]); + const mod = stat.mode; + const uid = stat.uid; + const gid = stat.gid; + const u = parseInt('100', 8); + const g = parseInt('010', 8); + const o = parseInt('001', 8); + const ug = u | g; + return !!(mod & o || + (mod & g && groups.has(gid)) || + (mod & u && uid === myUid) || + (mod & ug && myUid === 0)); +}; +//# sourceMappingURL=posix.js.map \ No newline at end of file diff --git a/node_modules/isexe/dist/esm/win32.js b/node_modules/isexe/dist/esm/win32.js new file mode 100644 index 0000000000000..2c75e67cdfaa2 --- /dev/null +++ b/node_modules/isexe/dist/esm/win32.js @@ -0,0 +1,58 @@ +/** + * This is the Windows implementation of isexe, which uses the file + * extension and PATHEXT setting. + * + * @module + */ +import { statSync } from 'node:fs'; +import { stat } from 'node:fs/promises'; +import { delimiter } from 'node:path'; +/** + * Determine whether a path is executable based on the file extension + * and PATHEXT environment variable (or specified pathExt option) + */ +export const isexe = async (path, options = {}) => { + const { ignoreErrors = false } = options; + try { + return checkStat(await stat(path), path, options); + } + catch (e) { + const er = e; + if (ignoreErrors || er.code === 'EACCES') + return false; + throw er; + } +}; +/** + * Synchronously determine whether a path is executable based on the file + * extension and PATHEXT environment variable (or specified pathExt option) + */ +export const sync = (path, options = {}) => { + const { ignoreErrors = false } = options; + try { + return checkStat(statSync(path), path, options); + } + catch (e) { + const er = e; + if (ignoreErrors || er.code === 'EACCES') + return false; + throw er; + } +}; +const checkPathExt = (path, options) => { + const { pathExt = process.env.PATHEXT || '' } = options; + const peSplit = pathExt.split(delimiter); + if (peSplit.indexOf('') !== -1) { + return true; + } + for (const pes of peSplit) { + const p = pes.toLowerCase(); + const ext = path.substring(path.length - p.length).toLowerCase(); + if (p && ext === p) { + return true; + } + } + return false; +}; +const checkStat = (stat, path, options) => stat.isFile() && checkPathExt(path, options); +//# sourceMappingURL=win32.js.map \ No newline at end of file diff --git a/node_modules/isexe/index.js b/node_modules/isexe/index.js deleted file mode 100644 index 553fb32b119bd..0000000000000 --- a/node_modules/isexe/index.js +++ /dev/null @@ -1,57 +0,0 @@ -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 - } - } -} diff --git a/node_modules/isexe/mode.js b/node_modules/isexe/mode.js deleted file mode 100644 index 1995ea4a06aec..0000000000000 --- a/node_modules/isexe/mode.js +++ /dev/null @@ -1,41 +0,0 @@ -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 -} diff --git a/node_modules/isexe/package.json b/node_modules/isexe/package.json index e452689442f20..31c05fa303078 100644 --- a/node_modules/isexe/package.json +++ b/node_modules/isexe/package.json @@ -1,31 +1,78 @@ { "name": "isexe", - "version": "2.0.0", + "version": "4.0.0", "description": "Minimal module to check if a file is executable.", - "main": "index.js", - "directories": { - "test": "test" + "main": "./dist/commonjs/index.min.js", + "module": "./dist/esm/index.min.js", + "types": "./dist/commonjs/index.d.ts", + "files": [ + "dist" + ], + "tshy": { + "selfLink": false, + "exports": { + "./raw": "./src/index.ts", + "./package.json": "./package.json", + ".": { + "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" + } + } + } + }, + "exports": { + "./raw": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + }, + "./package.json": "./package.json", + ".": { + "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" + } + } }, "devDependencies": { - "mkdirp": "^0.5.1", - "rimraf": "^2.5.0", - "tap": "^10.3.0" + "@types/node": "^25.2.1", + "esbuild": "^0.27.3", + "prettier": "^3.8.1", + "tap": "^21.5.1", + "tshy": "^3.1.3", + "typedoc": "^0.28.16" }, "scripts": { - "test": "tap test/*.js --100", "preversion": "npm test", "postversion": "npm publish", - "postpublish": "git push origin --all; git push origin --tags" + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy && bash build.sh", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write .", + "typedoc": "typedoc" }, "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" + "license": "BlueOak-1.0.0", + "repository": "https://github.com/isaacs/isexe", + "engines": { + "node": ">=20" }, - "homepage": "https://github.com/isaacs/isexe#readme" + "type": "module" } diff --git a/node_modules/isexe/test/basic.js b/node_modules/isexe/test/basic.js deleted file mode 100644 index d926df64b9024..0000000000000 --- a/node_modules/isexe/test/basic.js +++ /dev/null @@ -1,221 +0,0 @@ -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() -} diff --git a/node_modules/isexe/windows.js b/node_modules/isexe/windows.js deleted file mode 100644 index 34996734d8ef3..0000000000000 --- a/node_modules/isexe/windows.js +++ /dev/null @@ -1,42 +0,0 @@ -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) -} diff --git a/node_modules/jackspeak/dist/commonjs/index.js b/node_modules/jackspeak/dist/commonjs/index.js deleted file mode 100644 index b0e016d175ad0..0000000000000 --- a/node_modules/jackspeak/dist/commonjs/index.js +++ /dev/null @@ -1,1010 +0,0 @@ -"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 ??= { 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 ??= { 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 \ No newline at end of file diff --git a/node_modules/jackspeak/dist/commonjs/parse-args.js b/node_modules/jackspeak/dist/commonjs/parse-args.js deleted file mode 100644 index fc918a41fe603..0000000000000 --- a/node_modules/jackspeak/dist/commonjs/parse-args.js +++ /dev/null @@ -1,50 +0,0 @@ -"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.map \ No newline at end of file diff --git a/node_modules/jackspeak/dist/esm/index.js b/node_modules/jackspeak/dist/esm/index.js deleted file mode 100644 index 8eef5b4e8f5f8..0000000000000 --- a/node_modules/jackspeak/dist/esm/index.js +++ /dev/null @@ -1,1000 +0,0 @@ -import { 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 ??= { 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 ??= { 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 \ No newline at end of file diff --git a/node_modules/jackspeak/dist/esm/parse-args.js b/node_modules/jackspeak/dist/esm/parse-args.js deleted file mode 100644 index a4be7153de1f1..0000000000000 --- a/node_modules/jackspeak/dist/esm/parse-args.js +++ /dev/null @@ -1,26 +0,0 @@ -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 \ No newline at end of file diff --git a/node_modules/jackspeak/package.json b/node_modules/jackspeak/package.json deleted file mode 100644 index f9f7430673311..0000000000000 --- a/node_modules/jackspeak/package.json +++ /dev/null @@ -1,95 +0,0 @@ -{ - "name": "jackspeak", - "version": "3.4.0", - "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" - }, - "engines": { - "node": ">=14" - }, - "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" - } -} diff --git a/node_modules/jsbn/LICENSE b/node_modules/jsbn/LICENSE deleted file mode 100644 index 24502a9cf7483..0000000000000 --- a/node_modules/jsbn/LICENSE +++ /dev/null @@ -1,40 +0,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 diff --git a/node_modules/jsbn/example.html b/node_modules/jsbn/example.html deleted file mode 100644 index 1c0489b137635..0000000000000 --- a/node_modules/jsbn/example.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/node_modules/jsbn/example.js b/node_modules/jsbn/example.js deleted file mode 100644 index 85979909d7b1d..0000000000000 --- a/node_modules/jsbn/example.js +++ /dev/null @@ -1,5 +0,0 @@ -(function () { - var BigInteger = jsbn.BigInteger; - var a = new BigInteger('91823918239182398123'); - console.log(a.bitLength()); -}()); diff --git a/node_modules/jsbn/index.js b/node_modules/jsbn/index.js deleted file mode 100644 index e9eb697b07a89..0000000000000 --- a/node_modules/jsbn/index.js +++ /dev/null @@ -1,1361 +0,0 @@ -(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); diff --git a/node_modules/jsbn/package.json b/node_modules/jsbn/package.json deleted file mode 100644 index 97b137c2e2db9..0000000000000 --- a/node_modules/jsbn/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "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" -} diff --git a/node_modules/jsbn/test/es6-import.js b/node_modules/jsbn/test/es6-import.js deleted file mode 100644 index 668cbdfdc5bef..0000000000000 --- a/node_modules/jsbn/test/es6-import.js +++ /dev/null @@ -1,3 +0,0 @@ -import {BigInteger} from '../'; - -console.log(typeof BigInteger) diff --git a/node_modules/json-parse-even-better-errors/lib/index.js b/node_modules/json-parse-even-better-errors/lib/index.js index 3ffdaac96d2dc..3fd812dba3e3d 100644 --- a/node_modules/json-parse-even-better-errors/lib/index.js +++ b/node_modules/json-parse-even-better-errors/lib/index.js @@ -52,11 +52,13 @@ const parseError = (e, txt, context = 20) => { let errIdx if (badIndexMatch) { errIdx = +badIndexMatch[1] - } else /* istanbul ignore next - doesnt happen in Node 22 */ if ( + } else /* node:coverage disable */ if ( + // doesn't happen in Node 22+ msg.match(/^Unexpected end of JSON.*/i) ) { errIdx = txt.length - 1 } + /* node:coverage enable */ if (errIdx == null) { return makeParsedError(msg, `'${txt.slice(0, context * 2)}'`) diff --git a/node_modules/json-parse-even-better-errors/package.json b/node_modules/json-parse-even-better-errors/package.json index c7156df325fa2..23d27149ddcdf 100644 --- a/node_modules/json-parse-even-better-errors/package.json +++ b/node_modules/json-parse-even-better-errors/package.json @@ -1,6 +1,6 @@ { "name": "json-parse-even-better-errors", - "version": "3.0.2", + "version": "6.0.0", "description": "JSON.parse with context information on error", "main": "lib/index.js", "files": [ @@ -8,13 +8,16 @@ "lib/" ], "scripts": { - "test": "tap", - "snap": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test": "node --test './test/**/*.js'", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint" + "lintfix": "npm run eslint -- --fix", + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test:node20": "node --test test", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'" }, "repository": { "type": "git", @@ -27,23 +30,17 @@ "author": "GitHub Inc.", "license": "MIT", "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.3.0" - }, - "tap": { - "check-coverage": true, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true + "version": "5.0.0", + "publish": true, + "testRunner": "node:test", + "latestCiVersion": 24 } } diff --git a/node_modules/lru-cache/LICENSE b/node_modules/lru-cache/LICENSE deleted file mode 100644 index f785757cd63f8..0000000000000 --- a/node_modules/lru-cache/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/lru-cache/LICENSE.md b/node_modules/lru-cache/LICENSE.md new file mode 100644 index 0000000000000..c5402b9577a8c --- /dev/null +++ b/node_modules/lru-cache/LICENSE.md @@ -0,0 +1,55 @@ +# 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.*** diff --git a/node_modules/lru-cache/dist/commonjs/browser/diagnostics-channel.js b/node_modules/lru-cache/dist/commonjs/browser/diagnostics-channel.js new file mode 100644 index 0000000000000..8f6a8f12edb39 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/browser/diagnostics-channel.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.tracing = exports.metrics = void 0; +const dummy = { hasSubscribers: false }; +exports.metrics = dummy; +exports.tracing = dummy; +//# sourceMappingURL=diagnostics-channel-browser.js.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/commonjs/browser/index.js b/node_modules/lru-cache/dist/commonjs/browser/index.js new file mode 100644 index 0000000000000..179694b1b7b75 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/browser/index.js @@ -0,0 +1,1726 @@ +"use strict"; +/** + * @module LRUCache + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LRUCache = void 0; +const diagnostics_channel_js_1 = require("./diagnostics-channel.js"); +const perf_js_1 = require("./perf.js"); +const hasSubscribers = () => diagnostics_channel_js_1.metrics.hasSubscribers || diagnostics_channel_js_1.tracing.hasSubscribers; +const warned = new Set(); +/* c8 ignore start */ +const PROCESS = (typeof process === 'object' && !!process ? + process + : {}); +/* c8 ignore stop */ +const emitWarning = (msg, type, code, fn) => { + if (typeof PROCESS.emitWarning === 'function') { + PROCESS.emitWarning(msg, type, code, fn); + } + else { + //oxlint-disable-next-line no-console + console.error(`[${code}] ${type}: ${msg}`); + } +}; +const shouldWarn = (code) => !warned.has(code); +const TYPE = Symbol('type'); +const isPosInt = (n) => !!n && n === Math.floor(n) && n > 0 && isFinite(n); +// 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. +/* c8 ignore start */ +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 { + /* c8 ignore start - not sure why this is showing up uncovered?? */ + heap; + /* c8 ignore stop */ + 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; + #onInsert; + #disposeAfter; + #fetchMethod; + #memoMethod; + #perf; + /** + * {@link LRUCache.OptionsBase.perf} + */ + get perf() { + return this.#perf; + } + /** + * {@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; + /** {@link LRUCache.OptionsBase.backgroundFetchSize} */ + backgroundFetchSize; + // computed properties + #size; + #calculatedSize; + #keyMap; + #keyList; + #valList; + #next; + #prev; + #head; + #tail; + #free; + #disposed; + #sizes; + #starts; + #ttls; + #autopurgeTimers; + #hasDispose; + #hasFetchMethod; + #hasDisposeAfter; + #hasOnInsert; + /** + * 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, + autopurgeTimers: c.#autopurgeTimers, + 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.onInsert} (read-only) + */ + get onInsert() { + return this.#onInsert; + } + /** + * {@link LRUCache.OptionsBase.disposeAfter} (read-only) + */ + get disposeAfter() { + return this.#disposeAfter; + } + constructor(options) { + const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, onInsert, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, backgroundFetchSize = 1, perf, } = options; + this.backgroundFetchSize = backgroundFetchSize; + if (perf !== undefined) { + if (typeof perf?.now !== 'function') { + throw new TypeError('perf option must have a now() method if specified'); + } + } + this.#perf = perf ?? perf_js_1.defaultPerf; + 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 = Array.from({ length: max }).fill(undefined); + this.#valList = Array.from({ length: 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 onInsert === 'function') { + this.#onInsert = onInsert; + } + if (typeof disposeAfter === 'function') { + this.#disposeAfter = disposeAfter; + this.#disposed = []; + } + else { + this.#disposeAfter = undefined; + this.#disposed = undefined; + } + this.#hasDispose = !!this.#dispose; + this.#hasOnInsert = !!this.#onInsert; + 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; + const purgeTimers = this.ttlAutopurge ? + Array.from({ + length: this.#max, + }) + : undefined; + this.#autopurgeTimers = purgeTimers; + this.#setItemTTL = (index, ttl, start = this.#perf.now()) => { + starts[index] = ttl !== 0 ? start : 0; + ttls[index] = ttl; + setPurgetTimer(index, ttl); + }; + this.#updateItemAge = index => { + starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0; + setPurgetTimer(index, ttls[index]); + }; + // clear out the purge timer if we're setting TTL to 0, and + // previously had a ttl purge timer running, so it doesn't + // fire unnecessarily. Don't need to do this if we're not doing + // autopurge. + const setPurgetTimer = !this.ttlAutopurge ? + () => { } + : (index, ttl) => { + if (purgeTimers?.[index]) { + clearTimeout(purgeTimers[index]); + purgeTimers[index] = undefined; + } + if (ttl && ttl !== 0 && purgeTimers) { + 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 */ + purgeTimers[index] = t; + } + }; + this.#statusTTL = (status, index) => { + if (ttls[index]) { + const ttl = ttls[index]; + const start = starts[index]; + /* c8 ignore start */ + if (!ttl || !start) { + return; + } + /* c8 ignore stop */ + 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 = this.#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) => { + if (!isPosInt(size)) { + // provisionally accept background fetches. + // actual value size will be checked when they return. + if (this.#isBackgroundFetch(v)) { + // NB: this cannot occur if v.__staleWhileFetching is set, + // because in that case, it would take on the size of the + // existing entry that it temporarily replaces. + return this.backgroundFetchSize; + } + 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; this.#isValidIndex(i);) { + 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; this.#isValidIndex(i);) { + 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]; + /* c8 ignore start - this isn't tested for the info function, + * but it's the same logic as found in other places. */ + const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + if (value === undefined) + return undefined; + /* c8 ignore stop */ + const entry = { value }; + if (this.#ttls && this.#starts) { + const ttl = this.#ttls[i]; + const start = this.#starts[i]; + if (ttl && start) { + const remain = ttl - (this.#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 LRUCache#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 = this.#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 = this.#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 = {}) { + const { status = diagnostics_channel_js_1.metrics.hasSubscribers ? {} : undefined } = setOptions; + setOptions.status = status; + if (status) { + status.op = 'set'; + status.key = k; + if (v !== undefined) + status.value = v; + status.cache = this; + } + const result = this.#set(k, v, setOptions); + if (status && diagnostics_channel_js_1.metrics.hasSubscribers) { + diagnostics_channel_js_1.metrics.publish(status); + } + return result; + } + #set(k, v, setOptions, bf) { + const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; + const isBF = this.#isBackgroundFetch(v); + if (v === undefined) { + if (status) + status.set = 'deleted'; + this.delete(k); + return this; + } + let { noUpdateTTL = this.noUpdateTTL } = setOptions; + if (status && !isBF) + status.value = v; + const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation, status); + // if the item doesn't fit, don't do anything + // NB: maxEntrySize set to maxSize by default + if (this.maxEntrySize && size > this.maxEntrySize) { + // have to delete, in case something is there already. + this.#delete(k, 'set'); + if (status) { + status.set = 'miss'; + status.maxEntrySizeExceeded = true; + } + 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; + if (this.#hasOnInsert && !isBF) { + this.#onInsert?.(v, k, 'add'); + } + } + else { + // update + // might be updating a background fetch! + this.#moveToTail(index); + const oldVal = this.#valList[index]; + if (v !== oldVal) { + if (!noDisposeOnSet) { + if (this.#isBackgroundFetch(oldVal)) { + if (oldVal !== bf) { + // setting over a background fetch, not merely resolving it. + oldVal.__abortController.abort(new Error('replaced')); + } + const { __staleWhileFetching: s } = oldVal; + if (s !== undefined && s !== v) { + if (this.#hasDispose) { + this.#dispose?.(s, k, 'set'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([s, k, 'set']); + } + } + } + else { + 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 (!isBF) { + const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? + oldVal.__staleWhileFetching + : oldVal; + const setType = oldValue === undefined ? 'add' + : v !== oldValue ? 'replace' + : 'update'; + if (status) { + status.set = setType; + if (oldValue !== undefined) + status.oldValue = oldValue; + } + if (this.#hasOnInsert) { + this.onInsert?.(v, k, setType); + } + } + } + else if (!isBF) { + if (status) { + status.set = 'update'; + } + if (this.#hasOnInsert) { + this.onInsert?.(v, k, '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]; + const isBF = this.#isBackgroundFetch(v); + if (isBF) { + v.__abortController.abort(new Error('evicted')); + } + const oldValue = isBF ? v.__staleWhileFetching : v; + if ((this.#hasDispose || this.#hasDisposeAfter) && + oldValue !== undefined) { + if (this.#hasDispose) { + this.#dispose?.(oldValue, k, 'evict'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([oldValue, k, 'evict']); + } + } + this.#removeItemSize(head); + if (this.#autopurgeTimers?.[head]) { + clearTimeout(this.#autopurgeTimers[head]); + this.#autopurgeTimers[head] = undefined; + } + // 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 { status = diagnostics_channel_js_1.metrics.hasSubscribers ? {} : undefined } = hasOptions; + hasOptions.status = status; + if (status) { + status.op = 'has'; + status.key = k; + status.cache = this; + } + const result = this.#has(k, hasOptions); + if (diagnostics_channel_js_1.metrics.hasSubscribers) + diagnostics_channel_js_1.metrics.publish(status); + return result; + } + #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 { status = hasSubscribers() ? {} : undefined } = peekOptions; + if (status) { + status.op = 'peek'; + status.key = k; + status.cache = this; + } + peekOptions.status = status; + const result = this.#peek(k, peekOptions); + if (diagnostics_channel_js_1.metrics.hasSubscribers) { + diagnostics_channel_js_1.metrics.publish(status); + } + return result; + } + #peek(k, peekOptions) { + const { status, allowStale = this.allowStale } = peekOptions; + const index = this.#keyMap.get(k); + if (index === undefined || (!allowStale && this.#isStale(index))) { + if (status) + status.peek = index === undefined ? 'miss' : 'stale'; + return undefined; + } + const v = this.#valList[index]; + const val = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + if (status) { + if (val !== undefined) { + status.peek = 'hit'; + status.value = val; + } + else { + status.peek = 'miss'; + } + } + return val; + } + #backgroundFetch(k, index, options, context) { + const v = index === undefined ? undefined : this.#valList[index]; + if (this.#isBackgroundFetch(v)) { + return v; + } + const ac = new AbortController(); + 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; + const proceed = options.ignoreFetchAbort || + !!(options.allowStaleOnFetchAbort && 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, proceed); + } + // either we didn't abort, and are still here, or we did, and ignored + const bf = p; + // if nothing else has been written there but we're set to update the + // cache and ignore the abort, or if it's still pending on this specific + // background request, then write it to the cache. + const vl = this.#valList[index]; + if (vl === p || (vl === undefined && ignoreAbort && updateCache)) { + if (v === undefined) { + if (bf.__staleWhileFetching !== undefined) { + this.#valList[index] = bf.__staleWhileFetching; + } + else { + this.#delete(k, 'fetch'); + } + } + else { + if (options.status) + options.status.fetchUpdated = true; + this.#set(k, v, fetchOpts.options, bf); + } + } + return v; + }; + const eb = (er) => { + if (options.status) { + options.status.fetchRejected = true; + options.status.fetchError = er; + } + // do not pass go, do not collect $200 + return fetchFail(er, false); + }; + const fetchFail = (er, proceed) => { + 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 || (!proceed && 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); + // 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 (fmp && fmp instanceof Promise) { + fmp.then(v => res(v === undefined ? undefined : v), rej); + } + else if (fmp !== undefined) { + res(fmp); + } + }; + 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 { + // do not call #set, because we do not want to adjust its place + // in the lru queue, as it has not yet been "used". Also, we don't + // need to worry about evicting for size, because a background fetch + // over a stale value is treated as the same size as its stale value. + 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 AbortController); + } + fetch(k, fetchOptions = {}) { + const ths = diagnostics_channel_js_1.tracing.hasSubscribers; + const { status = hasSubscribers() ? {} : undefined } = fetchOptions; + fetchOptions.status = status; + if (status && fetchOptions.context) { + status.context = fetchOptions.context; + } + const p = this.#fetch(k, fetchOptions); + if (status && ths) { + status.trace = true; + diagnostics_channel_js_1.tracing.tracePromise(() => p, status).catch(() => { }); + } + return p; + } + 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 (status) { + status.op = 'fetch'; + status.key = k; + if (forceRefresh) + status.forceRefresh = true; + status.cache = this; + } + 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); + } + } + forceFetch(k, fetchOptions = {}) { + const ths = diagnostics_channel_js_1.tracing.hasSubscribers; + const { status = hasSubscribers() ? {} : undefined } = fetchOptions; + fetchOptions.status = status; + if (status && fetchOptions.context) { + status.context = fetchOptions.context; + } + const p = this.#forceFetch(k, fetchOptions); + if (status && ths) { + status.trace = true; + diagnostics_channel_js_1.tracing.tracePromise(() => p, status).catch(() => { }); + } + return 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 { status = diagnostics_channel_js_1.metrics.hasSubscribers ? {} : undefined } = memoOptions; + memoOptions.status = status; + if (status) { + status.op = 'memo'; + status.key = k; + if (memoOptions.context) { + status.context = memoOptions.context; + } + status.cache = this; + } + const result = this.#memo(k, memoOptions); + if (status) + status.value = result; + if (diagnostics_channel_js_1.metrics.hasSubscribers) + diagnostics_channel_js_1.metrics.publish(status); + return result; + } + #memo(k, memoOptions = {}) { + const memoMethod = this.#memoMethod; + if (!memoMethod) { + throw new Error('no memoMethod provided to constructor'); + } + const { context, status, forceRefresh, ...options } = memoOptions; + if (status && forceRefresh) + status.forceRefresh = true; + const v = this.#get(k, options); + const refresh = forceRefresh || v === undefined; + if (status) { + status.memo = refresh ? 'miss' : 'hit'; + if (!refresh) + status.value = v; + } + if (!refresh) + return v; + const vv = memoMethod(k, v, { + options, + context, + }); + if (status) + status.value = vv; + 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 { status = diagnostics_channel_js_1.metrics.hasSubscribers ? {} : undefined } = getOptions; + getOptions.status = status; + if (status) { + status.op = 'get'; + status.key = k; + status.cache = this; + } + const result = this.#get(k, getOptions); + if (status) { + if (result !== undefined) + status.value = result; + if (diagnostics_channel_js_1.metrics.hasSubscribers) + diagnostics_channel_js_1.metrics.publish(status); + } + return result; + } + #get(k, getOptions = {}) { + const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; + const index = this.#keyMap.get(k); + if (index === undefined) { + if (status) + status.get = 'miss'; + return undefined; + } + const value = this.#valList[index]; + const fetching = this.#isBackgroundFetch(value); + if (status) + this.#statusTTL(status, index); + if (this.#isStale(index)) { + // delete only if not an in-flight background fetch + if (!fetching) { + if (!noDeleteOnStaleGet) { + this.#delete(k, 'expire'); + } + if (status) + status.get = 'stale'; + if (allowStale) { + if (status) + status.returnedStale = true; + return value; + } + return undefined; + } + if (status) + status.get = 'stale-fetching'; + if (allowStale && value.__staleWhileFetching !== undefined) { + if (status) + status.returnedStale = true; + return value.__staleWhileFetching; + } + return undefined; + } + // not stale + if (status) + status.get = fetching ? 'fetching' : '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. + this.#moveToTail(index); + if (updateAgeOnGet) { + this.#updateItemAge(index); + } + return fetching ? value.__staleWhileFetching : value; + } + #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) { + if (diagnostics_channel_js_1.metrics.hasSubscribers) { + diagnostics_channel_js_1.metrics.publish({ + op: 'delete', + delete: reason, + key: k, + cache: this, + }); + } + let deleted = false; + if (this.#size !== 0) { + const index = this.#keyMap.get(k); + if (index !== undefined) { + if (this.#autopurgeTimers?.[index]) { + clearTimeout(this.#autopurgeTimers?.[index]); + this.#autopurgeTimers[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(); + void this.#valList.fill(undefined); + this.#keyList.fill(undefined); + if (this.#ttls && this.#starts) { + this.#ttls.fill(0); + this.#starts.fill(0); + for (const t of this.#autopurgeTimers ?? []) { + if (t !== undefined) + clearTimeout(t); + } + this.#autopurgeTimers?.fill(undefined); + } + 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 \ No newline at end of file diff --git a/node_modules/lru-cache/dist/commonjs/browser/index.min.js b/node_modules/lru-cache/dist/commonjs/browser/index.min.js new file mode 100644 index 0000000000000..8e42461074475 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/browser/index.min.js @@ -0,0 +1,2 @@ +"use strict";var j=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var I=j(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.tracing=O.metrics=void 0;var U={hasSubscribers:!1};O.metrics=U;O.tracing=U});var P=j(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.defaultPerf=void 0;D.defaultPerf=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date});Object.defineProperty(exports,"__esModule",{value:!0});exports.LRUCache=void 0;var g=I(),N=P(),x=()=>g.metrics.hasSubscribers||g.tracing.hasSubscribers,k=new Set,G=typeof process=="object"&&process?process:{},V=(c,t,e,i)=>{typeof G.emitWarning=="function"?G.emitWarning(c,t,e,i):console.error(`[${e}] ${t}: ${c}`)},B=c=>!k.has(c);var T=c=>!!c&&c===Math.floor(c)&&c>0&&isFinite(c),H=c=>T(c)?c<=Math.pow(2,8)?Uint8Array:c<=Math.pow(2,16)?Uint16Array:c<=Math.pow(2,32)?Uint32Array:c<=Number.MAX_SAFE_INTEGER?W:null:null,W=class extends Array{constructor(t){super(t),this.fill(0)}},C=class c{heap;length;static#o=!1;static create(t){let e=H(t);if(!e)return[];c.#o=!0;let i=new c(t,e);return c.#o=!1,i}constructor(t,e){if(!c.#o)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]}},L=class c{#o;#c;#m;#W;#S;#M;#j;#w;get perf(){return this.#w}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#n;#b;#s;#i;#t;#l;#u;#a;#h;#y;#r;#_;#F;#d;#g;#T;#U;#f;#D;static unsafeExposeInternals(t){return{starts:t.#F,ttls:t.#d,autopurgeTimers:t.#g,sizes:t.#_,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#l,prev:t.#u,get head(){return t.#a},get tail(){return t.#h},free:t.#y,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,n)=>t.#G(e,i,s,n),moveToTail:e=>t.#L(e),indexes:e=>t.#A(e),rindexes:e=>t.#z(e),isStale:e=>t.#p(e)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#b}get size(){return this.#n}get fetchMethod(){return this.#M}get memoMethod(){return this.#j}get dispose(){return this.#m}get onInsert(){return this.#W}get disposeAfter(){return this.#S}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:r,updateAgeOnHas:h,allowStale:a,dispose:o,onInsert:d,disposeAfter:y,noDisposeOnSet:_,noUpdateTTL:u,maxSize:p=0,maxEntrySize:f=0,sizeCalculation:b,fetchMethod:l,memoMethod:S,noDeleteOnFetchRejection:F,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:A,ignoreFetchAbort:z,backgroundFetchSize:M=1,perf:v}=t;if(this.backgroundFetchSize=M,v!==void 0&&typeof v?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#w=v??N.defaultPerf,e!==0&&!T(e))throw new TypeError("max option must be a nonnegative integer");let E=e?H(e):Array;if(!E)throw new Error("invalid max value: "+e);if(this.#o=e,this.#c=p,this.maxEntrySize=f||this.#c,this.sizeCalculation=b,this.sizeCalculation){if(!this.#c&&!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(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#j=S,l!==void 0&&typeof l!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#M=l,this.#U=!!l,this.#s=new Map,this.#i=Array.from({length:e}).fill(void 0),this.#t=Array.from({length:e}).fill(void 0),this.#l=new E(e),this.#u=new E(e),this.#a=0,this.#h=0,this.#y=C.create(e),this.#n=0,this.#b=0,typeof o=="function"&&(this.#m=o),typeof d=="function"&&(this.#W=d),typeof y=="function"?(this.#S=y,this.#r=[]):(this.#S=void 0,this.#r=void 0),this.#T=!!this.#m,this.#D=!!this.#W,this.#f=!!this.#S,this.noDisposeOnSet=!!_,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!F,this.allowStaleOnFetchRejection=!!m,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.#c!==0&&!T(this.#c))throw new TypeError("maxSize must be a positive integer if specified");if(!T(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#X()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!r,this.updateAgeOnHas=!!h,this.ttlResolution=T(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!T(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#k()}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let R="LRU_CACHE_UNBOUNDED";B(R)&&(k.add(R),V("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}#k(){let t=new W(this.#o),e=new W(this.#o);this.#d=t,this.#F=e;let i=this.ttlAutopurge?Array.from({length:this.#o}):void 0;this.#g=i,this.#H=(h,a,o=this.#w.now())=>{e[h]=a!==0?o:0,t[h]=a,s(h,a)},this.#R=h=>{e[h]=t[h]!==0?this.#w.now():0,s(h,t[h])};let s=this.ttlAutopurge?(h,a)=>{if(i?.[h]&&(clearTimeout(i[h]),i[h]=void 0),a&&a!==0&&i){let o=setTimeout(()=>{this.#p(h)&&this.#v(this.#i[h],"expire")},a+1);o.unref&&o.unref(),i[h]=o}}:()=>{};this.#E=(h,a)=>{if(t[a]){let o=t[a],d=e[a];if(!o||!d)return;h.ttl=o,h.start=d,h.now=n||r();let y=h.now-d;h.remainingTTL=o-y}};let n=0,r=()=>{let h=this.#w.now();if(this.ttlResolution>0){n=h;let a=setTimeout(()=>n=0,this.ttlResolution);a.unref&&a.unref()}return h};this.getRemainingTTL=h=>{let a=this.#s.get(h);if(a===void 0)return 0;let o=t[a],d=e[a];if(!o||!d)return 1/0;let y=(n||r())-d;return o-y},this.#p=h=>{let a=e[h],o=t[h];return!!o&&!!a&&(n||r())-a>o}}#R=()=>{};#E=()=>{};#H=()=>{};#p=()=>!1;#X(){let t=new W(this.#o);this.#b=0,this.#_=t,this.#x=e=>{this.#b-=t[e],t[e]=0},this.#N=(e,i,s,n)=>{if(!T(s)){if(this.#e(i))return this.backgroundFetchSize;if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,e),!T(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.#I=(e,i,s)=>{if(t[e]=i,this.#c){let n=this.#c-t[e];for(;this.#b>n;)this.#P(!0)}this.#b+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#b)}}#x=t=>{};#I=(t,e,i)=>{};#N=(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.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#a);)e=this.#u[e]}*#z({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#a;this.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#h);)e=this.#l[e]}#V(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.#z())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.#z()){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.#z())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.#C(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.#z()){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.#z({allowStale:!0}))this.#p(e)&&(this.#v(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.#d&&this.#F){let r=this.#d[e],h=this.#F[e];if(r&&h){let a=r-(this.#w.now()-h);n.ttl=a,n.start=Date.now()}}return this.#_&&(n.size=this.#_[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 r={value:n};if(this.#d&&this.#F){r.ttl=this.#d[e];let h=this.#w.now()-this.#F[e];r.start=Math.floor(Date.now()-h)}this.#_&&(r.size=this.#_[e]),t.unshift([i,r])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=this.#w.now()-s}this.#O(e,i.value,i)}}set(t,e,i={}){let{status:s=g.metrics.hasSubscribers?{}:void 0}=i;i.status=s,s&&(s.op="set",s.key=t,e!==void 0&&(s.value=e),s.cache=this);let n=this.#O(t,e,i);return s&&g.metrics.hasSubscribers&&g.metrics.publish(s),n}#O(t,e,i,s){let{ttl:n=this.ttl,start:r,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:o}=i,d=this.#e(e);if(e===void 0)return o&&(o.set="deleted"),this.delete(t),this;let{noUpdateTTL:y=this.noUpdateTTL}=i;o&&!d&&(o.value=e);let _=this.#N(t,e,i.size||0,a,o);if(this.maxEntrySize&&_>this.maxEntrySize)return this.#v(t,"set"),o&&(o.set="miss",o.maxEntrySizeExceeded=!0),this;let u=this.#n===0?void 0:this.#s.get(t);if(u===void 0)u=this.#n===0?this.#h:this.#y.length!==0?this.#y.pop():this.#n===this.#o?this.#P(!1):this.#n,this.#i[u]=t,this.#t[u]=e,this.#s.set(t,u),this.#l[this.#h]=u,this.#u[u]=this.#h,this.#h=u,this.#n++,this.#I(u,_,o),o&&(o.set="add"),y=!1,this.#D&&!d&&this.#W?.(e,t,"add");else{this.#L(u);let p=this.#t[u];if(e!==p){if(!h)if(this.#e(p)){p!==s&&p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&f!==e&&(this.#T&&this.#m?.(f,t,"set"),this.#f&&this.#r?.push([f,t,"set"]))}else this.#T&&this.#m?.(p,t,"set"),this.#f&&this.#r?.push([p,t,"set"]);if(this.#x(u),this.#I(u,_,o),this.#t[u]=e,!d){let f=p&&this.#e(p)?p.__staleWhileFetching:p,b=f===void 0?"add":e!==f?"replace":"update";o&&(o.set=b,f!==void 0&&(o.oldValue=f)),this.#D&&this.onInsert?.(e,t,b)}}else d||(o&&(o.set="update"),this.#D&&this.onInsert?.(e,t,"update"))}if(n!==0&&!this.#d&&this.#k(),this.#d&&(y||this.#H(u,n,r),o&&this.#E(o,u)),!h&&this.#f&&this.#r){let p=this.#r,f;for(;f=p?.shift();)this.#S?.(...f)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#a];if(this.#P(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#f&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#S?.(...e)}}}#P(t){let e=this.#a,i=this.#i[e],s=this.#t[e],n=this.#e(s);n&&s.__abortController.abort(new Error("evicted"));let r=n?s.__staleWhileFetching:s;return(this.#T||this.#f)&&r!==void 0&&(this.#T&&this.#m?.(r,i,"evict"),this.#f&&this.#r?.push([r,i,"evict"])),this.#x(e),this.#g?.[e]&&(clearTimeout(this.#g[e]),this.#g[e]=void 0),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#y.push(e)),this.#n===1?(this.#a=this.#h=0,this.#y.length=0):this.#a=this.#l[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="has",i.key=t,i.cache=this);let s=this.#Y(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Y(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,n=this.#s.get(t);if(n!==void 0){let r=this.#t[n];if(this.#e(r)&&r.__staleWhileFetching===void 0)return!1;if(this.#p(n))s&&(s.has="stale",this.#E(s,n));else return i&&this.#R(n),s&&(s.has="hit",this.#E(s,n)),!0}else s&&(s.has="miss");return!1}peek(t,e={}){let{status:i=x()?{}:void 0}=e;i&&(i.op="peek",i.key=t,i.cache=this),e.status=i;let s=this.#J(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#J(t,e){let{status:i,allowStale:s=this.allowStale}=e,n=this.#s.get(t);if(n===void 0||!s&&this.#p(n)){i&&(i.peek=n===void 0?"miss":"stale");return}let r=this.#t[n],h=this.#e(r)?r.__staleWhileFetching:r;return i&&(h!==void 0?(i.peek="hit",i.value=h):i.peek="miss"),h}#G(t,e,i,s){let n=e===void 0?void 0:this.#t[e];if(this.#e(n))return n;let r=new AbortController,{signal:h}=i;h?.addEventListener("abort",()=>r.abort(h.reason),{signal:r.signal});let a={signal:r.signal,options:i,context:s},o=(f,b=!1)=>{let{aborted:l}=r.signal,S=i.ignoreFetchAbort&&f!==void 0,F=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&f!==void 0);if(i.status&&(l&&!b?(i.status.fetchAborted=!0,i.status.fetchError=r.signal.reason,S&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),l&&!S&&!b)return y(r.signal.reason,F);let w=u,m=this.#t[e];return(m===u||m===void 0&&S&&b)&&(f===void 0?w.__staleWhileFetching!==void 0?this.#t[e]=w.__staleWhileFetching:this.#v(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.#O(t,f,a.options,w))),f},d=f=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=f),y(f,!1)),y=(f,b)=>{let{aborted:l}=r.signal,S=l&&i.allowStaleOnFetchAbort,F=S||i.allowStaleOnFetchRejection,w=F||i.noDeleteOnFetchRejection,m=u;if(this.#t[e]===u&&(!w||!b&&m.__staleWhileFetching===void 0?this.#v(t,"fetch"):S||(this.#t[e]=m.__staleWhileFetching)),F)return i.status&&m.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),m.__staleWhileFetching;if(m.__returned===m)throw f},_=(f,b)=>{let l=this.#M?.(t,n,a);r.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(f(void 0),i.allowStaleOnFetchAbort&&(f=S=>o(S,!0)))}),l&&l instanceof Promise?l.then(S=>f(S===void 0?void 0:S),b):l!==void 0&&f(l)};i.status&&(i.status.fetchDispatched=!0);let u=new Promise(_).then(o,d),p=Object.assign(u,{__abortController:r,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.#O(t,p,{...a.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=p,p}#e(t){if(!this.#U)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof AbortController}fetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=x()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#B(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#B(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:r=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:a=0,sizeCalculation:o=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:y=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:_=this.allowStaleOnFetchRejection,ignoreFetchAbort:u=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:f,forceRefresh:b=!1,status:l,signal:S}=e;if(l&&(l.op="fetch",l.key=t,b&&(l.forceRefresh=!0),l.cache=this),!this.#U)return l&&(l.fetch="get"),this.#C(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:l});let F={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:r,noDisposeOnSet:h,size:a,sizeCalculation:o,noUpdateTTL:d,noDeleteOnFetchRejection:y,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:p,ignoreFetchAbort:u,status:l,signal:S},w=this.#s.get(t);if(w===void 0){l&&(l.fetch="miss");let m=this.#G(t,w,F,f);return m.__returned=m}else{let m=this.#t[w];if(this.#e(m)){let E=i&&m.__staleWhileFetching!==void 0;return l&&(l.fetch="inflight",E&&(l.returnedStale=!0)),E?m.__staleWhileFetching:m.__returned=m}let A=this.#p(w);if(!b&&!A)return l&&(l.fetch="hit"),this.#L(w),s&&this.#R(w),l&&this.#E(l,w),m;let z=this.#G(t,w,F,f),v=z.__staleWhileFetching!==void 0&&i;return l&&(l.fetch=A?"stale":"refresh",v&&A&&(l.returnedStale=!0)),v?z.__staleWhileFetching:z.__returned=z}}forceFetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=x()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#K(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#K(t,e={}){let i=await this.#B(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="memo",i.key=t,e.context&&(i.context=e.context),i.cache=this);let s=this.#Q(t,e);return i&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Q(t,e={}){let i=this.#j;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,status:n,forceRefresh:r,...h}=e;n&&r&&(n.forceRefresh=!0);let a=this.#C(t,h),o=r||a===void 0;if(n&&(n.memo=o?"miss":"hit",o||(n.value=a)),!o)return a;let d=i(t,a,{options:h,context:s});return n&&(n.value=d),this.#O(t,d,h),d}get(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="get",i.key=t,i.cache=this);let s=this.#C(t,e);return i&&(s!==void 0&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i)),s}#C(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:r}=e,h=this.#s.get(t);if(h===void 0){r&&(r.get="miss");return}let a=this.#t[h],o=this.#e(a);return r&&this.#E(r,h),this.#p(h)?o?(r&&(r.get="stale-fetching"),i&&a.__staleWhileFetching!==void 0?(r&&(r.returnedStale=!0),a.__staleWhileFetching):void 0):(n||this.#v(t,"expire"),r&&(r.get="stale"),i?(r&&(r.returnedStale=!0),a):void 0):(r&&(r.get=o?"fetching":"hit"),this.#L(h),s&&this.#R(h),o?a.__staleWhileFetching:a)}#q(t,e){this.#u[e]=t,this.#l[t]=e}#L(t){t!==this.#h&&(t===this.#a?this.#a=this.#l[t]:this.#q(this.#u[t],this.#l[t]),this.#q(this.#h,t),this.#h=t)}delete(t){return this.#v(t,"delete")}#v(t,e){g.metrics.hasSubscribers&&g.metrics.publish({op:"delete",delete:e,key:t,cache:this});let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g?.[s]),this.#g[s]=void 0),i=!0,this.#n===1)this.#$(e);else{this.#x(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#T||this.#f)&&(this.#T&&this.#m?.(n,t,e),this.#f&&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.#u[s];else if(s===this.#a)this.#a=this.#l[s];else{let r=this.#u[s];this.#l[r]=this.#l[s];let h=this.#l[s];this.#u[h]=this.#u[s]}this.#n--,this.#y.push(s)}}if(this.#f&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#S?.(...n)}return i}clear(){return this.#$("delete")}#$(t){for(let e of this.#z({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[e];this.#T&&this.#m?.(i,s,t),this.#f&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#F){this.#d.fill(0),this.#F.fill(0);for(let e of this.#g??[])e!==void 0&&clearTimeout(e);this.#g?.fill(void 0)}if(this.#_&&this.#_.fill(0),this.#a=0,this.#h=0,this.#y.length=0,this.#b=0,this.#n=0,this.#f&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#S?.(...i)}}};exports.LRUCache=L; +//# sourceMappingURL=index.min.js.map diff --git a/node_modules/lru-cache/dist/commonjs/browser/perf.js b/node_modules/lru-cache/dist/commonjs/browser/perf.js new file mode 100644 index 0000000000000..bd4c80f461d6c --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/browser/perf.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultPerf = void 0; +exports.defaultPerf = (typeof performance === 'object' && + performance && + typeof performance.now === 'function') ? + /* c8 ignore start - this gets covered, but c8 gets confused */ + performance + : /* c8 ignore stop */ Date; +//# sourceMappingURL=perf.js.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/commonjs/diagnostics-channel.js b/node_modules/lru-cache/dist/commonjs/diagnostics-channel.js new file mode 100644 index 0000000000000..bdd4f41f90366 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/diagnostics-channel.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.tracing = exports.metrics = void 0; +const dummy = { hasSubscribers: false }; +exports.metrics = dummy; +exports.tracing = dummy; +//# sourceMappingURL=diagnostics-channel-cjs.cjs.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/commonjs/index.js b/node_modules/lru-cache/dist/commonjs/index.js index 8e8c2435079b0..179694b1b7b75 100644 --- a/node_modules/lru-cache/dist/commonjs/index.js +++ b/node_modules/lru-cache/dist/commonjs/index.js @@ -4,73 +4,27 @@ */ Object.defineProperty(exports, "__esModule", { value: true }); exports.LRUCache = void 0; -const perf = typeof performance === 'object' && - performance && - typeof performance.now === 'function' - ? performance - : Date; +const diagnostics_channel_js_1 = require("./diagnostics-channel.js"); +const perf_js_1 = require("./perf.js"); +const hasSubscribers = () => diagnostics_channel_js_1.metrics.hasSubscribers || diagnostics_channel_js_1.tracing.hasSubscribers; const warned = new Set(); /* c8 ignore start */ -const PROCESS = (typeof process === 'object' && !!process ? process : {}); -/* c8 ignore start */ +const PROCESS = (typeof process === 'object' && !!process ? + process + : {}); +/* c8 ignore stop */ const emitWarning = (msg, type, code, fn) => { - typeof PROCESS.emitWarning === 'function' - ? PROCESS.emitWarning(msg, type, code, fn) - : console.error(`[${code}] ${type}: ${msg}`); + if (typeof PROCESS.emitWarning === 'function') { + PROCESS.emitWarning(msg, type, code, fn); + } + else { + //oxlint-disable-next-line no-console + 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 */ +const isPosInt = (n) => !!n && n === Math.floor(n) && n > 0 && isFinite(n); // 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, @@ -79,16 +33,12 @@ const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n); // 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 +/* c8 ignore start */ +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 { @@ -98,7 +48,9 @@ class ZeroArray extends Array { } } class Stack { + /* c8 ignore start - not sure why this is showing up uncovered?? */ heap; + /* c8 ignore stop */ length; // private constructor static #constructing = false; @@ -130,21 +82,34 @@ class Stack { /** * Default export, the thing you're using this module to get. * - * All properties from the options object (with the exception of - * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as - * normal public members. (`max` and `maxBase` are read-only getters.) - * Changing any of these will alter the defaults for subsequent method calls, - * but is otherwise safe. + * 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 { - // properties coming in from the options of these, only max and maxSize - // really *need* to be protected. The rest can be modified, as they just - // set defaults for various methods. + // options that cannot be changed without disaster #max; #maxSize; #dispose; + #onInsert; #disposeAfter; #fetchMethod; + #memoMethod; + #perf; + /** + * {@link LRUCache.OptionsBase.perf} + */ + get perf() { + return this.#perf; + } /** * {@link LRUCache.OptionsBase.ttl} */ @@ -205,6 +170,8 @@ class LRUCache { * {@link LRUCache.OptionsBase.ignoreFetchAbort} */ ignoreFetchAbort; + /** {@link LRUCache.OptionsBase.backgroundFetchSize} */ + backgroundFetchSize; // computed properties #size; #calculatedSize; @@ -220,9 +187,11 @@ class LRUCache { #sizes; #starts; #ttls; + #autopurgeTimers; #hasDispose; #hasFetchMethod; #hasDisposeAfter; + #hasOnInsert; /** * Do not call this method unless you need to inspect the * inner workings of the cache. If anything returned by this @@ -237,6 +206,7 @@ class LRUCache { // properties starts: c.#starts, ttls: c.#ttls, + autopurgeTimers: c.#autopurgeTimers, sizes: c.#sizes, keyMap: c.#keyMap, keyList: c.#keyList, @@ -290,12 +260,21 @@ class LRUCache { get fetchMethod() { return this.#fetchMethod; } + get memoMethod() { + return this.#memoMethod; + } /** * {@link LRUCache.OptionsBase.dispose} (read-only) */ get dispose() { return this.#dispose; } + /** + * {@link LRUCache.OptionsBase.onInsert} (read-only) + */ + get onInsert() { + return this.#onInsert; + } /** * {@link LRUCache.OptionsBase.disposeAfter} (read-only) */ @@ -303,7 +282,14 @@ class LRUCache { 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, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options; + const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, onInsert, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, backgroundFetchSize = 1, perf, } = options; + this.backgroundFetchSize = backgroundFetchSize; + if (perf !== undefined) { + if (typeof perf?.now !== 'function') { + throw new TypeError('perf option must have a now() method if specified'); + } + } + this.#perf = perf ?? perf_js_1.defaultPerf; if (max !== 0 && !isPosInt(max)) { throw new TypeError('max option must be a nonnegative integer'); } @@ -323,15 +309,18 @@ class LRUCache { throw new TypeError('sizeCalculation set to non-function'); } } - if (fetchMethod !== undefined && - typeof fetchMethod !== '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.#keyList = Array.from({ length: max }).fill(undefined); + this.#valList = Array.from({ length: max }).fill(undefined); this.#next = new UintArray(max); this.#prev = new UintArray(max); this.#head = 0; @@ -342,6 +331,9 @@ class LRUCache { if (typeof dispose === 'function') { this.#dispose = dispose; } + if (typeof onInsert === 'function') { + this.#onInsert = onInsert; + } if (typeof disposeAfter === 'function') { this.#disposeAfter = disposeAfter; this.#disposed = []; @@ -351,6 +343,7 @@ class LRUCache { this.#disposed = undefined; } this.#hasDispose = !!this.#dispose; + this.#hasOnInsert = !!this.#onInsert; this.#hasDisposeAfter = !!this.#disposeAfter; this.noDisposeOnSet = !!noDisposeOnSet; this.noUpdateTTL = !!noUpdateTTL; @@ -375,9 +368,7 @@ class LRUCache { this.updateAgeOnGet = !!updateAgeOnGet; this.updateAgeOnHas = !!updateAgeOnHas; this.ttlResolution = - isPosInt(ttlResolution) || ttlResolution === 0 - ? ttlResolution - : 1; + isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1; this.ttlAutopurge = !!ttlAutopurge; this.ttl = ttl || 0; if (this.ttl) { @@ -401,7 +392,8 @@ class LRUCache { } } /** - * Return the remaining TTL time for a given entry key + * 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; @@ -411,33 +403,56 @@ class LRUCache { const starts = new ZeroArray(this.#max); this.#ttls = ttls; this.#starts = starts; - this.#setItemTTL = (index, ttl, start = perf.now()) => { + const purgeTimers = this.ttlAutopurge ? + Array.from({ + length: this.#max, + }) + : undefined; + this.#autopurgeTimers = purgeTimers; + this.#setItemTTL = (index, ttl, start = this.#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]); - } - }, ttl + 1); - // unref() not supported on all platforms - /* c8 ignore start */ - if (t.unref) { - t.unref(); - } - /* c8 ignore stop */ - } + setPurgetTimer(index, ttl); }; this.#updateItemAge = index => { - starts[index] = ttls[index] !== 0 ? perf.now() : 0; + starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0; + setPurgetTimer(index, ttls[index]); }; + // clear out the purge timer if we're setting TTL to 0, and + // previously had a ttl purge timer running, so it doesn't + // fire unnecessarily. Don't need to do this if we're not doing + // autopurge. + const setPurgetTimer = !this.ttlAutopurge ? + () => { } + : (index, ttl) => { + if (purgeTimers?.[index]) { + clearTimeout(purgeTimers[index]); + purgeTimers[index] = undefined; + } + if (ttl && ttl !== 0 && purgeTimers) { + 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 */ + purgeTimers[index] = t; + } + }; this.#statusTTL = (status, index) => { if (ttls[index]) { const ttl = ttls[index]; const start = starts[index]; - /* c8 ignore next */ - if (!ttl || !start) + /* c8 ignore start */ + if (!ttl || !start) { return; + } + /* c8 ignore stop */ status.ttl = ttl; status.start = start; status.now = cachedNow || getNow(); @@ -449,7 +464,7 @@ class LRUCache { // that costly call repeatedly. let cachedNow = 0; const getNow = () => { - const n = perf.now(); + const n = this.#perf.now(); if (this.ttlResolution > 0) { cachedNow = n; const t = setTimeout(() => (cachedNow = 0), this.ttlResolution); @@ -496,12 +511,15 @@ class LRUCache { 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)) { + // provisionally accept background fetches. + // actual value size will be checked when they return. + if (this.#isBackgroundFetch(v)) { + // NB: this cannot occur if v.__staleWhileFetching is set, + // because in that case, it would take on the size of the + // existing entry that it temporarily replaces. + return this.backgroundFetchSize; + } if (sizeCalculation) { if (typeof sizeCalculation !== 'function') { throw new TypeError('sizeCalculation must be a function'); @@ -544,10 +562,7 @@ class LRUCache { }; *#indexes({ allowStale = this.allowStale } = {}) { if (this.#size) { - for (let i = this.#tail; true;) { - if (!this.#isValidIndex(i)) { - break; - } + for (let i = this.#tail; this.#isValidIndex(i);) { if (allowStale || !this.#isStale(i)) { yield i; } @@ -562,10 +577,7 @@ class LRUCache { } *#rindexes({ allowStale = this.allowStale } = {}) { if (this.#size) { - for (let i = this.#head; true;) { - if (!this.#isValidIndex(i)) { - break; - } + for (let i = this.#head; this.#isValidIndex(i);) { if (allowStale || !this.#isStale(i)) { yield i; } @@ -617,8 +629,7 @@ class LRUCache { *keys() { for (const i of this.#indexes()) { const k = this.#keyList[i]; - if (k !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { + if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield k; } } @@ -632,8 +643,7 @@ class LRUCache { *rkeys() { for (const i of this.#rindexes()) { const k = this.#keyList[i]; - if (k !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { + if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield k; } } @@ -645,8 +655,7 @@ class LRUCache { *values() { for (const i of this.#indexes()) { const v = this.#valList[i]; - if (v !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { + if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield this.#valList[i]; } } @@ -660,8 +669,7 @@ class LRUCache { *rvalues() { for (const i of this.#rindexes()) { const v = this.#valList[i]; - if (v !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { + if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield this.#valList[i]; } } @@ -674,39 +682,41 @@ class LRUCache { 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. + * 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). + * 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; + 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); + 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). Does not update age or recenty of use. - * Does not iterate over stale values. + * 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; + const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; fn.call(thisp, value, this.#keyList[i], this); @@ -719,9 +729,7 @@ class LRUCache { rforEach(fn, thisp = this) { for (const i of this.#rindexes()) { const v = this.#valList[i]; - const value = this.#isBackgroundFetch(v) - ? v.__staleWhileFetching - : v; + const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; fn.call(thisp, value, this.#keyList[i], this); @@ -735,7 +743,7 @@ class LRUCache { let deleted = false; for (const i of this.#rindexes({ allowStale: true })) { if (this.#isStale(i)) { - this.delete(this.#keyList[i]); + this.#delete(this.#keyList[i], 'expire'); deleted = true; } } @@ -743,26 +751,33 @@ class LRUCache { } /** * Get the extended info about a given entry, to get its value, size, and - * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a - * single key. Always returns stale values, if their info is found in the - * cache, so be sure to check for expired TTLs if relevant. + * 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; + /* c8 ignore start - this isn't tested for the info function, + * but it's the same logic as found in other places. */ + const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) return undefined; + /* c8 ignore stop */ 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); + const remain = ttl - (this.#perf.now() - start); entry.ttl = remain; entry.start = Date.now(); } @@ -774,16 +789,23 @@ class LRUCache { } /** * Return an array of [key, {@link LRUCache.Entry}] tuples which can be - * passed to cache.load() + * passed to {@link LRUCache#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; + const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined || key === undefined) continue; const entry = { value }; @@ -791,7 +813,7 @@ class LRUCache { 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]; + const age = this.#perf.now() - this.#starts[i]; entry.start = Math.floor(Date.now() - age); } if (this.#sizes) { @@ -803,8 +825,12 @@ class LRUCache { } /** * Reset the cache and load in the items in entries in the order listed. - * Note that the shape of the resulting cache may be different if the - * same options are not used in both caches. + * + * 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(); @@ -817,9 +843,9 @@ class LRUCache { // // 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; + entry.start = this.#perf.now() - age; } - this.set(key, entry.value, entry); + this.#set(key, entry.value, entry); } } /** @@ -827,35 +853,77 @@ class LRUCache { * * 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 = {}) { + const { status = diagnostics_channel_js_1.metrics.hasSubscribers ? {} : undefined } = setOptions; + setOptions.status = status; + if (status) { + status.op = 'set'; + status.key = k; + if (v !== undefined) + status.value = v; + status.cache = this; + } + const result = this.#set(k, v, setOptions); + if (status && diagnostics_channel_js_1.metrics.hasSubscribers) { + diagnostics_channel_js_1.metrics.publish(status); + } + return result; + } + #set(k, v, setOptions, bf) { + const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; + const isBF = this.#isBackgroundFetch(v); if (v === undefined) { + if (status) + status.set = 'deleted'; 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 (status && !isBF) + status.value = v; + const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation, status); // if the item doesn't fit, don't do anything // NB: maxEntrySize set to maxSize by default if (this.maxEntrySize && size > this.maxEntrySize) { + // have to delete, in case something is there already. + this.#delete(k, 'set'); if (status) { status.set = 'miss'; status.maxEntrySizeExceeded = true; } - // have to delete, in case something is there already. - this.delete(k); 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) + 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; @@ -868,46 +936,68 @@ class LRUCache { if (status) status.set = 'add'; noUpdateTTL = false; + if (this.#hasOnInsert && !isBF) { + this.#onInsert?.(v, k, 'add'); + } } else { // update + // might be updating a background fetch! 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 (!noDisposeOnSet) { + if (this.#isBackgroundFetch(oldVal)) { + if (oldVal !== bf) { + // setting over a background fetch, not merely resolving it. + oldVal.__abortController.abort(new Error('replaced')); + } + const { __staleWhileFetching: s } = oldVal; + if (s !== undefined && s !== v) { + if (this.#hasDispose) { + this.#dispose?.(s, k, 'set'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([s, k, 'set']); + } + } + } + else { if (this.#hasDispose) { - this.#dispose?.(s, k, 'set'); + this.#dispose?.(oldVal, k, 'set'); } if (this.#hasDisposeAfter) { - this.#disposed?.push([s, k, 'set']); + this.#disposed?.push([oldVal, 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 + if (!isBF) { + const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? + oldVal.__staleWhileFetching : oldVal; - if (oldValue !== undefined) - status.oldValue = oldValue; + const setType = oldValue === undefined ? 'add' + : v !== oldValue ? 'replace' + : 'update'; + if (status) { + status.set = setType; + if (oldValue !== undefined) + status.oldValue = oldValue; + } + if (this.#hasOnInsert) { + this.onInsert?.(v, k, setType); + } } } - else if (status) { - status.set = 'update'; + else if (!isBF) { + if (status) { + status.set = 'update'; + } + if (this.#hasOnInsert) { + this.onInsert?.(v, k, 'update'); + } } } if (ttl !== 0 && !this.#ttls) { @@ -962,18 +1052,25 @@ class LRUCache { const head = this.#head; const k = this.#keyList[head]; const v = this.#valList[head]; - if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) { + const isBF = this.#isBackgroundFetch(v); + if (isBF) { v.__abortController.abort(new Error('evicted')); } - else if (this.#hasDispose || this.#hasDisposeAfter) { + const oldValue = isBF ? v.__staleWhileFetching : v; + if ((this.#hasDispose || this.#hasDisposeAfter) && + oldValue !== undefined) { if (this.#hasDispose) { - this.#dispose?.(v, k, 'evict'); + this.#dispose?.(oldValue, k, 'evict'); } if (this.#hasDisposeAfter) { - this.#disposed?.push([v, k, 'evict']); + this.#disposed?.push([oldValue, k, 'evict']); } } this.#removeItemSize(head); + if (this.#autopurgeTimers?.[head]) { + clearTimeout(this.#autopurgeTimers[head]); + this.#autopurgeTimers[head] = undefined; + } // if we aren't about to use the index, then null these out if (free) { this.#keyList[head] = undefined; @@ -996,10 +1093,31 @@ class LRUCache { * 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 { status = diagnostics_channel_js_1.metrics.hasSubscribers ? {} : undefined } = hasOptions; + hasOptions.status = status; + if (status) { + status.op = 'has'; + status.key = k; + status.cache = this; + } + const result = this.#has(k, hasOptions); + if (diagnostics_channel_js_1.metrics.hasSubscribers) + diagnostics_channel_js_1.metrics.publish(status); + return result; + } + #has(k, hasOptions = {}) { const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions; const index = this.#keyMap.get(k); if (index !== undefined) { @@ -1036,22 +1154,46 @@ class LRUCache { * {@link LRUCache.OptionsBase.allowStale} is set. */ peek(k, peekOptions = {}) { - const { allowStale = this.allowStale } = peekOptions; + const { status = hasSubscribers() ? {} : undefined } = peekOptions; + if (status) { + status.op = 'peek'; + status.key = k; + status.cache = this; + } + peekOptions.status = status; + const result = this.#peek(k, peekOptions); + if (diagnostics_channel_js_1.metrics.hasSubscribers) { + diagnostics_channel_js_1.metrics.publish(status); + } + return result; + } + #peek(k, peekOptions) { + const { status, allowStale = this.allowStale } = peekOptions; const index = this.#keyMap.get(k); - if (index === undefined || - (!allowStale && this.#isStale(index))) { - return; + if (index === undefined || (!allowStale && this.#isStale(index))) { + if (status) + status.peek = index === undefined ? 'miss' : 'stale'; + return undefined; } const v = this.#valList[index]; - // either stale and allowed, or forcing a refresh of non-stale value - return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + const val = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + if (status) { + if (val !== undefined) { + status.peek = 'hit'; + status.value = val; + } + else { + status.peek = 'miss'; + } + } + return val; } #backgroundFetch(k, index, options, context) { const v = index === undefined ? undefined : this.#valList[index]; if (this.#isBackgroundFetch(v)) { return v; } - const ac = new AC(); + const ac = new AbortController(); const { signal } = options; // when/if our AC signals, then stop listening to theirs. signal?.addEventListener('abort', () => ac.abort(signal.reason), { @@ -1065,6 +1207,8 @@ class LRUCache { const cb = (v, updateCache = false) => { const { aborted } = ac.signal; const ignoreAbort = options.ignoreFetchAbort && v !== undefined; + const proceed = options.ignoreFetchAbort || + !!(options.allowStaleOnFetchAbort && v !== undefined); if (options.status) { if (aborted && !updateCache) { options.status.fetchAborted = true; @@ -1077,23 +1221,27 @@ class LRUCache { } } if (aborted && !ignoreAbort && !updateCache) { - return fetchFail(ac.signal.reason); + return fetchFail(ac.signal.reason, proceed); } // either we didn't abort, and are still here, or we did, and ignored const bf = p; - if (this.#valList[index] === p) { + // if nothing else has been written there but we're set to update the + // cache and ignore the abort, or if it's still pending on this specific + // background request, then write it to the cache. + const vl = this.#valList[index]; + if (vl === p || (vl === undefined && ignoreAbort && updateCache)) { if (v === undefined) { - if (bf.__staleWhileFetching) { + if (bf.__staleWhileFetching !== undefined) { this.#valList[index] = bf.__staleWhileFetching; } else { - this.delete(k); + this.#delete(k, 'fetch'); } } else { if (options.status) options.status.fetchUpdated = true; - this.set(k, v, fetchOpts.options); + this.#set(k, v, fetchOpts.options, bf); } } return v; @@ -1103,9 +1251,10 @@ class LRUCache { options.status.fetchRejected = true; options.status.fetchError = er; } - return fetchFail(er); + // do not pass go, do not collect $200 + return fetchFail(er, false); }; - const fetchFail = (er) => { + const fetchFail = (er, proceed) => { const { aborted } = ac.signal; const allowStaleAborted = aborted && options.allowStaleOnFetchAbort; const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection; @@ -1114,9 +1263,9 @@ class LRUCache { 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; + const del = !noDelete || (!proceed && bf.__staleWhileFetching === undefined); if (del) { - this.delete(k); + this.#delete(k, 'fetch'); } else if (!allowStaleAborted) { // still replace the *promise* with the stale value, @@ -1138,15 +1287,11 @@ class LRUCache { }; 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) { + if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) { res(undefined); // when it eventually resolves, update the cache. if (options.allowStaleOnFetchAbort) { @@ -1154,6 +1299,12 @@ class LRUCache { } } }); + if (fmp && fmp instanceof Promise) { + fmp.then(v => res(v === undefined ? undefined : v), rej); + } + else if (fmp !== undefined) { + res(fmp); + } }; if (options.status) options.status.fetchDispatched = true; @@ -1165,10 +1316,14 @@ class LRUCache { }); if (index === undefined) { // internal, don't expose status. - this.set(k, bf, { ...fetchOpts.options, status: undefined }); + this.#set(k, bf, { ...fetchOpts.options, status: undefined }); index = this.#keyMap.get(k); } else { + // do not call #set, because we do not want to adjust its place + // in the lru queue, as it has not yet been "used". Also, we don't + // need to worry about evicting for size, because a background fetch + // over a stale value is treated as the same size as its stale value. this.#valList[index] = bf; } return bf; @@ -1180,9 +1335,23 @@ class LRUCache { return (!!b && b instanceof Promise && b.hasOwnProperty('__staleWhileFetching') && - b.__abortController instanceof AC); + b.__abortController instanceof AbortController); + } + fetch(k, fetchOptions = {}) { + const ths = diagnostics_channel_js_1.tracing.hasSubscribers; + const { status = hasSubscribers() ? {} : undefined } = fetchOptions; + fetchOptions.status = status; + if (status && fetchOptions.context) { + status.context = fetchOptions.context; + } + const p = this.#fetch(k, fetchOptions); + if (status && ths) { + status.trace = true; + diagnostics_channel_js_1.tracing.tracePromise(() => p, status).catch(() => { }); + } + return p; } - async fetch(k, fetchOptions = {}) { + async #fetch(k, fetchOptions = {}) { const { // get options allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, @@ -1190,10 +1359,17 @@ class LRUCache { 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 (status) { + status.op = 'fetch'; + status.key = k; + if (forceRefresh) + status.forceRefresh = true; + status.cache = this; + } if (!this.#hasFetchMethod) { if (status) status.fetch = 'get'; - return this.get(k, { + return this.#get(k, { allowStale, updateAgeOnGet, noDeleteOnStaleGet, @@ -1262,6 +1438,70 @@ class LRUCache { return staleVal ? p.__staleWhileFetching : (p.__returned = p); } } + forceFetch(k, fetchOptions = {}) { + const ths = diagnostics_channel_js_1.tracing.hasSubscribers; + const { status = hasSubscribers() ? {} : undefined } = fetchOptions; + fetchOptions.status = status; + if (status && fetchOptions.context) { + status.context = fetchOptions.context; + } + const p = this.#forceFetch(k, fetchOptions); + if (status && ths) { + status.trace = true; + diagnostics_channel_js_1.tracing.tracePromise(() => p, status).catch(() => { }); + } + return 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 { status = diagnostics_channel_js_1.metrics.hasSubscribers ? {} : undefined } = memoOptions; + memoOptions.status = status; + if (status) { + status.op = 'memo'; + status.key = k; + if (memoOptions.context) { + status.context = memoOptions.context; + } + status.cache = this; + } + const result = this.#memo(k, memoOptions); + if (status) + status.value = result; + if (diagnostics_channel_js_1.metrics.hasSubscribers) + diagnostics_channel_js_1.metrics.publish(status); + return result; + } + #memo(k, memoOptions = {}) { + const memoMethod = this.#memoMethod; + if (!memoMethod) { + throw new Error('no memoMethod provided to constructor'); + } + const { context, status, forceRefresh, ...options } = memoOptions; + if (status && forceRefresh) + status.forceRefresh = true; + const v = this.#get(k, options); + const refresh = forceRefresh || v === undefined; + if (status) { + status.memo = refresh ? 'miss' : 'hit'; + if (!refresh) + status.value = v; + } + if (!refresh) + return v; + const vv = memoMethod(k, v, { + options, + context, + }); + if (status) + status.value = vv; + this.#set(k, vv, options); + return vv; + } /** * Return a value from the cache. Will update the recency of the cache * entry found. @@ -1269,55 +1509,71 @@ class LRUCache { * If the key is not found, get() will return `undefined`. */ get(k, getOptions = {}) { + const { status = diagnostics_channel_js_1.metrics.hasSubscribers ? {} : undefined } = getOptions; + getOptions.status = status; + if (status) { + status.op = 'get'; + status.key = k; + status.cache = this; + } + const result = this.#get(k, getOptions); + if (status) { + if (result !== undefined) + status.value = result; + if (diagnostics_channel_js_1.metrics.hasSubscribers) + diagnostics_channel_js_1.metrics.publish(status); + } + return result; + } + #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 (index === undefined) { if (status) - this.#statusTTL(status, index); - if (this.#isStale(index)) { + status.get = 'miss'; + return undefined; + } + const value = this.#valList[index]; + const fetching = this.#isBackgroundFetch(value); + if (status) + this.#statusTTL(status, index); + if (this.#isStale(index)) { + // delete only if not an in-flight background fetch + if (!fetching) { + if (!noDeleteOnStaleGet) { + this.#delete(k, 'expire'); + } if (status) status.get = 'stale'; - // delete only if not an in-flight background fetch - if (!fetching) { - if (!noDeleteOnStaleGet) { - this.delete(k); - } - if (status && allowStale) - status.returnedStale = true; - return allowStale ? value : undefined; - } - else { - if (status && - allowStale && - value.__staleWhileFetching !== undefined) { + if (allowStale) { + if (status) status.returnedStale = true; - } - return allowStale ? value.__staleWhileFetching : undefined; + return value; } + return undefined; } - else { + if (status) + status.get = 'stale-fetching'; + if (allowStale && value.__staleWhileFetching !== undefined) { 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; + status.returnedStale = true; + return value.__staleWhileFetching; } + return undefined; } - else if (status) { - status.get = 'miss'; - } + // not stale + if (status) + status.get = fetching ? 'fetching' : '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. + this.#moveToTail(index); + if (updateAgeOnGet) { + this.#updateItemAge(index); + } + return fetching ? value.__staleWhileFetching : value; } #connect(p, n) { this.#prev[n] = p; @@ -1345,16 +1601,32 @@ class LRUCache { } /** * 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) { + if (diagnostics_channel_js_1.metrics.hasSubscribers) { + diagnostics_channel_js_1.metrics.publish({ + op: 'delete', + delete: reason, + key: k, + cache: this, + }); + } let deleted = false; if (this.#size !== 0) { const index = this.#keyMap.get(k); if (index !== undefined) { + if (this.#autopurgeTimers?.[index]) { + clearTimeout(this.#autopurgeTimers?.[index]); + this.#autopurgeTimers[index] = undefined; + } deleted = true; if (this.#size === 1) { - this.clear(); + this.#clear(reason); } else { this.#removeItemSize(index); @@ -1364,10 +1636,10 @@ class LRUCache { } else if (this.#hasDispose || this.#hasDisposeAfter) { if (this.#hasDispose) { - this.#dispose?.(v, k, 'delete'); + this.#dispose?.(v, k, reason); } if (this.#hasDisposeAfter) { - this.#disposed?.push([v, k, 'delete']); + this.#disposed?.push([v, k, reason]); } } this.#keyMap.delete(k); @@ -1403,6 +1675,9 @@ class LRUCache { * 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)) { @@ -1411,19 +1686,24 @@ class LRUCache { else { const k = this.#keyList[index]; if (this.#hasDispose) { - this.#dispose?.(v, k, 'delete'); + this.#dispose?.(v, k, reason); } if (this.#hasDisposeAfter) { - this.#disposed?.push([v, k, 'delete']); + this.#disposed?.push([v, k, reason]); } } } this.#keyMap.clear(); - this.#valList.fill(undefined); + void this.#valList.fill(undefined); this.#keyList.fill(undefined); if (this.#ttls && this.#starts) { this.#ttls.fill(0); this.#starts.fill(0); + for (const t of this.#autopurgeTimers ?? []) { + if (t !== undefined) + clearTimeout(t); + } + this.#autopurgeTimers?.fill(undefined); } if (this.#sizes) { this.#sizes.fill(0); diff --git a/node_modules/lru-cache/dist/commonjs/index.min.js b/node_modules/lru-cache/dist/commonjs/index.min.js index b7149f5415a45..8e42461074475 100644 --- a/node_modules/lru-cache/dist/commonjs/index.min.js +++ b/node_modules/lru-cache/dist/commonjs/index.min.js @@ -1,2 +1,2 @@ -"use strict";var G=(o,t,e)=>{if(!t.has(o))throw TypeError("Cannot "+e)};var j=(o,t,e)=>(G(o,t,"read from private field"),e?e.call(o):t.get(o)),I=(o,t,e)=>{if(t.has(o))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(o):t.set(o,e)},D=(o,t,e,i)=>(G(o,t,"write to private field"),i?i.call(o,e):t.set(o,e),e);Object.defineProperty(exports,"__esModule",{value:!0});exports.LRUCache=void 0;var T=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,N=new Set,L=typeof process=="object"&&process?process:{},P=(o,t,e,i)=>{typeof L.emitWarning=="function"?L.emitWarning(o,t,e,i):console.error(`[${e}] ${t}: ${o}`)},W=globalThis.AbortController,M=globalThis.AbortSignal;if(typeof W>"u"){M=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,s){this._onabort.push(s)}},W=class{constructor(){t()}signal=new M;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 o=L.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{o&&(o=!1,P("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=o=>!N.has(o),Y=Symbol("type"),A=o=>o&&o===Math.floor(o)&&o>0&&isFinite(o),H=o=>A(o)?o<=Math.pow(2,8)?Uint8Array:o<=Math.pow(2,16)?Uint16Array:o<=Math.pow(2,32)?Uint32Array:o<=Number.MAX_SAFE_INTEGER?E:null:null,E=class extends Array{constructor(t){super(t),this.fill(0)}},v,z=class{heap;length;static create(t){let e=H(t);if(!e)return[];D(z,v,!0);let i=new z(t,e);return D(z,v,!1),i}constructor(t,e){if(!j(z,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]}},R=z;v=new WeakMap,I(R,v,!1);var C=class{#g;#f;#p;#w;#C;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;#y;#u;#m;#T;#a;static unsafeExposeInternals(t){return{starts:t.#y,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.#D(e,i,s,n),moveToTail:e=>t.#v(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.#C}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:l,allowStale:r,dispose:g,disposeAfter:b,noDisposeOnSet:f,noUpdateTTL:u,maxSize:c=0,maxEntrySize:F=0,sizeCalculation:d,fetchMethod:S,noDeleteOnFetchRejection:a,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:y,allowStaleOnFetchAbort:p,ignoreFetchAbort:_}=t;if(e!==0&&!A(e))throw new TypeError("max option must be a nonnegative integer");let O=e?H(e):Array;if(!O)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(S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#C=S,this.#T=!!S,this.#s=new Map,this.#i=new Array(e).fill(void 0),this.#t=new Array(e).fill(void 0),this.#l=new O(e),this.#c=new O(e),this.#o=0,this.#h=0,this.#_=R.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.#m=!!this.#p,this.#a=!!this.#w,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!a,this.allowStaleOnFetchRejection=!!y,this.allowStaleOnFetchAbort=!!p,this.ignoreFetchAbort=!!_,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.#I()}if(this.allowStale=!!r,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!h,this.updateAgeOnHas=!!l,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.#L()}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 m="LRU_CACHE_UNBOUNDED";V(m)&&(N.add(m),P("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",m,C))}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#L(){let t=new E(this.#g),e=new E(this.#g);this.#u=t,this.#y=e,this.#U=(n,h,l=T.now())=>{if(e[n]=h!==0?l:0,t[n]=h,h!==0&&this.ttlAutopurge){let r=setTimeout(()=>{this.#d(n)&&this.delete(this.#i[n])},h+1);r.unref&&r.unref()}},this.#z=n=>{e[n]=t[n]!==0?T.now():0},this.#O=(n,h)=>{if(t[h]){let l=t[h],r=e[h];if(!l||!r)return;n.ttl=l,n.start=r,n.now=i||s();let g=n.now-r;n.remainingTTL=l-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 l=t[h],r=e[h];if(!l||!r)return 1/0;let g=(i||s())-r;return l-g},this.#d=n=>{let h=e[n],l=t[n];return!!l&&!!h&&(i||s())-h>l}}#z=()=>{};#O=()=>{};#U=()=>{};#d=()=>!1;#I(){let t=new E(this.#g);this.#S=0,this.#b=t,this.#E=e=>{this.#S-=t[e],t[e]=0},this.#x=(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.#R=(e,i,s)=>{if(t[e]=i,this.#f){let n=this.#f-t[e];for(;this.#S>n;)this.#W(!0)}this.#S+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#S)}}#E=t=>{};#R=(t,e,i)=>{};#x=(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.#G(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.#G(e)||((t||!this.#d(e))&&(yield e),e===this.#h));)e=this.#l[e]}#G(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.delete(this.#i[e]),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.#y){let h=this.#u[e],l=this.#y[e];if(h&&l){let r=h-(T.now()-l);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.#y){h.ttl=this.#u[e];let l=T.now()-this.#y[e];h.start=Math.floor(Date.now()-l)}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:l=this.sizeCalculation,status:r}=i,{noUpdateTTL:g=this.noUpdateTTL}=i,b=this.#x(t,e,i.size||0,l);if(this.maxEntrySize&&b>this.maxEntrySize)return r&&(r.set="miss",r.maxEntrySizeExceeded=!0),this.delete(t),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.#W(!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.#R(f,b,r),r&&(r.set="add"),g=!1;else{this.#v(f);let u=this.#t[f];if(e!==u){if(this.#T&&this.#e(u)){u.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:c}=u;c!==void 0&&!h&&(this.#m&&this.#p?.(c,t,"set"),this.#a&&this.#r?.push([c,t,"set"]))}else h||(this.#m&&this.#p?.(u,t,"set"),this.#a&&this.#r?.push([u,t,"set"]));if(this.#E(f),this.#R(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.#L(),this.#u&&(g||this.#U(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.#W(!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)}}}#W(t){let e=this.#o,i=this.#i[e],s=this.#t[e];return this.#T&&this.#e(s)?s.__abortController.abort(new Error("evicted")):(this.#m||this.#a)&&(this.#m&&this.#p?.(s,i,"evict"),this.#a&&this.#r?.push([s,i,"evict"])),this.#E(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.#z(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}#D(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:l}=i;l?.addEventListener("abort",()=>h.abort(l.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 y=c;return this.#t[e]===c&&(d===void 0?y.__staleWhileFetching?this.#t[e]=y.__staleWhileFetching:this.delete(t):(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,y=w||i.noDeleteOnFetchRejection,p=c;if(this.#t[e]===c&&(!y||p.__staleWhileFetching===void 0?this.delete(t):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.#C?.(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.#T)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:l=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.#T)return a&&(a.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:a});let y={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:h,noDisposeOnSet:l,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.#D(t,p,y,d);return _.__returned=_}else{let _=this.#t[p];if(this.#e(_)){let x=i&&_.__staleWhileFetching!==void 0;return a&&(a.fetch="inflight",x&&(a.returnedStale=!0)),x?_.__staleWhileFetching:_.__returned=_}let O=this.#d(p);if(!S&&!O)return a&&(a.fetch="hit"),this.#v(p),s&&this.#z(p),a&&this.#O(a,p),_;let m=this.#D(t,p,y,d),U=m.__staleWhileFetching!==void 0&&i;return a&&(a.fetch=O?"stale":"refresh",U&&O&&(a.returnedStale=!0)),U?m.__staleWhileFetching:m.__returned=m}}get(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:h}=e,l=this.#s.get(t);if(l!==void 0){let r=this.#t[l],g=this.#e(r);return h&&this.#O(h,l),this.#d(l)?(h&&(h.get="stale"),g?(h&&i&&r.__staleWhileFetching!==void 0&&(h.returnedStale=!0),i?r.__staleWhileFetching:void 0):(n||this.delete(t),h&&i&&(h.returnedStale=!0),i?r:void 0)):(h&&(h.get="hit"),g?r.__staleWhileFetching:(this.#v(l),s&&this.#z(l),r))}else h&&(h.get="miss")}#j(t,e){this.#c[e]=t,this.#l[t]=e}#v(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){let e=!1;if(this.#n!==0){let i=this.#s.get(t);if(i!==void 0)if(e=!0,this.#n===1)this.clear();else{this.#E(i);let s=this.#t[i];if(this.#e(s)?s.__abortController.abort(new Error("deleted")):(this.#m||this.#a)&&(this.#m&&this.#p?.(s,t,"delete"),this.#a&&this.#r?.push([s,t,"delete"])),this.#s.delete(t),this.#i[i]=void 0,this.#t[i]=void 0,i===this.#h)this.#h=this.#c[i];else if(i===this.#o)this.#o=this.#l[i];else{let n=this.#c[i];this.#l[n]=this.#l[i];let h=this.#l[i];this.#c[h]=this.#c[i]}this.#n--,this.#_.push(i)}}if(this.#a&&this.#r?.length){let i=this.#r,s;for(;s=i?.shift();)this.#w?.(...s)}return e}clear(){for(let t of this.#F({allowStale:!0})){let e=this.#t[t];if(this.#e(e))e.__abortController.abort(new Error("deleted"));else{let i=this.#i[t];this.#m&&this.#p?.(e,i,"delete"),this.#a&&this.#r?.push([e,i,"delete"])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#u&&this.#y&&(this.#u.fill(0),this.#y.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 t=this.#r,e;for(;e=t?.shift();)this.#w?.(...e)}}};exports.LRUCache=C; +"use strict";var j=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var I=j(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.tracing=O.metrics=void 0;var U={hasSubscribers:!1};O.metrics=U;O.tracing=U});var P=j(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.defaultPerf=void 0;D.defaultPerf=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date});Object.defineProperty(exports,"__esModule",{value:!0});exports.LRUCache=void 0;var g=I(),N=P(),x=()=>g.metrics.hasSubscribers||g.tracing.hasSubscribers,k=new Set,G=typeof process=="object"&&process?process:{},V=(c,t,e,i)=>{typeof G.emitWarning=="function"?G.emitWarning(c,t,e,i):console.error(`[${e}] ${t}: ${c}`)},B=c=>!k.has(c);var T=c=>!!c&&c===Math.floor(c)&&c>0&&isFinite(c),H=c=>T(c)?c<=Math.pow(2,8)?Uint8Array:c<=Math.pow(2,16)?Uint16Array:c<=Math.pow(2,32)?Uint32Array:c<=Number.MAX_SAFE_INTEGER?W:null:null,W=class extends Array{constructor(t){super(t),this.fill(0)}},C=class c{heap;length;static#o=!1;static create(t){let e=H(t);if(!e)return[];c.#o=!0;let i=new c(t,e);return c.#o=!1,i}constructor(t,e){if(!c.#o)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]}},L=class c{#o;#c;#m;#W;#S;#M;#j;#w;get perf(){return this.#w}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#n;#b;#s;#i;#t;#l;#u;#a;#h;#y;#r;#_;#F;#d;#g;#T;#U;#f;#D;static unsafeExposeInternals(t){return{starts:t.#F,ttls:t.#d,autopurgeTimers:t.#g,sizes:t.#_,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#l,prev:t.#u,get head(){return t.#a},get tail(){return t.#h},free:t.#y,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,n)=>t.#G(e,i,s,n),moveToTail:e=>t.#L(e),indexes:e=>t.#A(e),rindexes:e=>t.#z(e),isStale:e=>t.#p(e)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#b}get size(){return this.#n}get fetchMethod(){return this.#M}get memoMethod(){return this.#j}get dispose(){return this.#m}get onInsert(){return this.#W}get disposeAfter(){return this.#S}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:r,updateAgeOnHas:h,allowStale:a,dispose:o,onInsert:d,disposeAfter:y,noDisposeOnSet:_,noUpdateTTL:u,maxSize:p=0,maxEntrySize:f=0,sizeCalculation:b,fetchMethod:l,memoMethod:S,noDeleteOnFetchRejection:F,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:A,ignoreFetchAbort:z,backgroundFetchSize:M=1,perf:v}=t;if(this.backgroundFetchSize=M,v!==void 0&&typeof v?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#w=v??N.defaultPerf,e!==0&&!T(e))throw new TypeError("max option must be a nonnegative integer");let E=e?H(e):Array;if(!E)throw new Error("invalid max value: "+e);if(this.#o=e,this.#c=p,this.maxEntrySize=f||this.#c,this.sizeCalculation=b,this.sizeCalculation){if(!this.#c&&!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(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#j=S,l!==void 0&&typeof l!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#M=l,this.#U=!!l,this.#s=new Map,this.#i=Array.from({length:e}).fill(void 0),this.#t=Array.from({length:e}).fill(void 0),this.#l=new E(e),this.#u=new E(e),this.#a=0,this.#h=0,this.#y=C.create(e),this.#n=0,this.#b=0,typeof o=="function"&&(this.#m=o),typeof d=="function"&&(this.#W=d),typeof y=="function"?(this.#S=y,this.#r=[]):(this.#S=void 0,this.#r=void 0),this.#T=!!this.#m,this.#D=!!this.#W,this.#f=!!this.#S,this.noDisposeOnSet=!!_,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!F,this.allowStaleOnFetchRejection=!!m,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.#c!==0&&!T(this.#c))throw new TypeError("maxSize must be a positive integer if specified");if(!T(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#X()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!r,this.updateAgeOnHas=!!h,this.ttlResolution=T(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!T(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#k()}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let R="LRU_CACHE_UNBOUNDED";B(R)&&(k.add(R),V("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}#k(){let t=new W(this.#o),e=new W(this.#o);this.#d=t,this.#F=e;let i=this.ttlAutopurge?Array.from({length:this.#o}):void 0;this.#g=i,this.#H=(h,a,o=this.#w.now())=>{e[h]=a!==0?o:0,t[h]=a,s(h,a)},this.#R=h=>{e[h]=t[h]!==0?this.#w.now():0,s(h,t[h])};let s=this.ttlAutopurge?(h,a)=>{if(i?.[h]&&(clearTimeout(i[h]),i[h]=void 0),a&&a!==0&&i){let o=setTimeout(()=>{this.#p(h)&&this.#v(this.#i[h],"expire")},a+1);o.unref&&o.unref(),i[h]=o}}:()=>{};this.#E=(h,a)=>{if(t[a]){let o=t[a],d=e[a];if(!o||!d)return;h.ttl=o,h.start=d,h.now=n||r();let y=h.now-d;h.remainingTTL=o-y}};let n=0,r=()=>{let h=this.#w.now();if(this.ttlResolution>0){n=h;let a=setTimeout(()=>n=0,this.ttlResolution);a.unref&&a.unref()}return h};this.getRemainingTTL=h=>{let a=this.#s.get(h);if(a===void 0)return 0;let o=t[a],d=e[a];if(!o||!d)return 1/0;let y=(n||r())-d;return o-y},this.#p=h=>{let a=e[h],o=t[h];return!!o&&!!a&&(n||r())-a>o}}#R=()=>{};#E=()=>{};#H=()=>{};#p=()=>!1;#X(){let t=new W(this.#o);this.#b=0,this.#_=t,this.#x=e=>{this.#b-=t[e],t[e]=0},this.#N=(e,i,s,n)=>{if(!T(s)){if(this.#e(i))return this.backgroundFetchSize;if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,e),!T(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.#I=(e,i,s)=>{if(t[e]=i,this.#c){let n=this.#c-t[e];for(;this.#b>n;)this.#P(!0)}this.#b+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#b)}}#x=t=>{};#I=(t,e,i)=>{};#N=(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.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#a);)e=this.#u[e]}*#z({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#a;this.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#h);)e=this.#l[e]}#V(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.#z())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.#z()){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.#z())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.#C(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.#z()){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.#z({allowStale:!0}))this.#p(e)&&(this.#v(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.#d&&this.#F){let r=this.#d[e],h=this.#F[e];if(r&&h){let a=r-(this.#w.now()-h);n.ttl=a,n.start=Date.now()}}return this.#_&&(n.size=this.#_[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 r={value:n};if(this.#d&&this.#F){r.ttl=this.#d[e];let h=this.#w.now()-this.#F[e];r.start=Math.floor(Date.now()-h)}this.#_&&(r.size=this.#_[e]),t.unshift([i,r])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=this.#w.now()-s}this.#O(e,i.value,i)}}set(t,e,i={}){let{status:s=g.metrics.hasSubscribers?{}:void 0}=i;i.status=s,s&&(s.op="set",s.key=t,e!==void 0&&(s.value=e),s.cache=this);let n=this.#O(t,e,i);return s&&g.metrics.hasSubscribers&&g.metrics.publish(s),n}#O(t,e,i,s){let{ttl:n=this.ttl,start:r,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:o}=i,d=this.#e(e);if(e===void 0)return o&&(o.set="deleted"),this.delete(t),this;let{noUpdateTTL:y=this.noUpdateTTL}=i;o&&!d&&(o.value=e);let _=this.#N(t,e,i.size||0,a,o);if(this.maxEntrySize&&_>this.maxEntrySize)return this.#v(t,"set"),o&&(o.set="miss",o.maxEntrySizeExceeded=!0),this;let u=this.#n===0?void 0:this.#s.get(t);if(u===void 0)u=this.#n===0?this.#h:this.#y.length!==0?this.#y.pop():this.#n===this.#o?this.#P(!1):this.#n,this.#i[u]=t,this.#t[u]=e,this.#s.set(t,u),this.#l[this.#h]=u,this.#u[u]=this.#h,this.#h=u,this.#n++,this.#I(u,_,o),o&&(o.set="add"),y=!1,this.#D&&!d&&this.#W?.(e,t,"add");else{this.#L(u);let p=this.#t[u];if(e!==p){if(!h)if(this.#e(p)){p!==s&&p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&f!==e&&(this.#T&&this.#m?.(f,t,"set"),this.#f&&this.#r?.push([f,t,"set"]))}else this.#T&&this.#m?.(p,t,"set"),this.#f&&this.#r?.push([p,t,"set"]);if(this.#x(u),this.#I(u,_,o),this.#t[u]=e,!d){let f=p&&this.#e(p)?p.__staleWhileFetching:p,b=f===void 0?"add":e!==f?"replace":"update";o&&(o.set=b,f!==void 0&&(o.oldValue=f)),this.#D&&this.onInsert?.(e,t,b)}}else d||(o&&(o.set="update"),this.#D&&this.onInsert?.(e,t,"update"))}if(n!==0&&!this.#d&&this.#k(),this.#d&&(y||this.#H(u,n,r),o&&this.#E(o,u)),!h&&this.#f&&this.#r){let p=this.#r,f;for(;f=p?.shift();)this.#S?.(...f)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#a];if(this.#P(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#f&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#S?.(...e)}}}#P(t){let e=this.#a,i=this.#i[e],s=this.#t[e],n=this.#e(s);n&&s.__abortController.abort(new Error("evicted"));let r=n?s.__staleWhileFetching:s;return(this.#T||this.#f)&&r!==void 0&&(this.#T&&this.#m?.(r,i,"evict"),this.#f&&this.#r?.push([r,i,"evict"])),this.#x(e),this.#g?.[e]&&(clearTimeout(this.#g[e]),this.#g[e]=void 0),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#y.push(e)),this.#n===1?(this.#a=this.#h=0,this.#y.length=0):this.#a=this.#l[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="has",i.key=t,i.cache=this);let s=this.#Y(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Y(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,n=this.#s.get(t);if(n!==void 0){let r=this.#t[n];if(this.#e(r)&&r.__staleWhileFetching===void 0)return!1;if(this.#p(n))s&&(s.has="stale",this.#E(s,n));else return i&&this.#R(n),s&&(s.has="hit",this.#E(s,n)),!0}else s&&(s.has="miss");return!1}peek(t,e={}){let{status:i=x()?{}:void 0}=e;i&&(i.op="peek",i.key=t,i.cache=this),e.status=i;let s=this.#J(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#J(t,e){let{status:i,allowStale:s=this.allowStale}=e,n=this.#s.get(t);if(n===void 0||!s&&this.#p(n)){i&&(i.peek=n===void 0?"miss":"stale");return}let r=this.#t[n],h=this.#e(r)?r.__staleWhileFetching:r;return i&&(h!==void 0?(i.peek="hit",i.value=h):i.peek="miss"),h}#G(t,e,i,s){let n=e===void 0?void 0:this.#t[e];if(this.#e(n))return n;let r=new AbortController,{signal:h}=i;h?.addEventListener("abort",()=>r.abort(h.reason),{signal:r.signal});let a={signal:r.signal,options:i,context:s},o=(f,b=!1)=>{let{aborted:l}=r.signal,S=i.ignoreFetchAbort&&f!==void 0,F=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&f!==void 0);if(i.status&&(l&&!b?(i.status.fetchAborted=!0,i.status.fetchError=r.signal.reason,S&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),l&&!S&&!b)return y(r.signal.reason,F);let w=u,m=this.#t[e];return(m===u||m===void 0&&S&&b)&&(f===void 0?w.__staleWhileFetching!==void 0?this.#t[e]=w.__staleWhileFetching:this.#v(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.#O(t,f,a.options,w))),f},d=f=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=f),y(f,!1)),y=(f,b)=>{let{aborted:l}=r.signal,S=l&&i.allowStaleOnFetchAbort,F=S||i.allowStaleOnFetchRejection,w=F||i.noDeleteOnFetchRejection,m=u;if(this.#t[e]===u&&(!w||!b&&m.__staleWhileFetching===void 0?this.#v(t,"fetch"):S||(this.#t[e]=m.__staleWhileFetching)),F)return i.status&&m.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),m.__staleWhileFetching;if(m.__returned===m)throw f},_=(f,b)=>{let l=this.#M?.(t,n,a);r.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(f(void 0),i.allowStaleOnFetchAbort&&(f=S=>o(S,!0)))}),l&&l instanceof Promise?l.then(S=>f(S===void 0?void 0:S),b):l!==void 0&&f(l)};i.status&&(i.status.fetchDispatched=!0);let u=new Promise(_).then(o,d),p=Object.assign(u,{__abortController:r,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.#O(t,p,{...a.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=p,p}#e(t){if(!this.#U)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof AbortController}fetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=x()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#B(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#B(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:r=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:a=0,sizeCalculation:o=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:y=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:_=this.allowStaleOnFetchRejection,ignoreFetchAbort:u=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:f,forceRefresh:b=!1,status:l,signal:S}=e;if(l&&(l.op="fetch",l.key=t,b&&(l.forceRefresh=!0),l.cache=this),!this.#U)return l&&(l.fetch="get"),this.#C(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:l});let F={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:r,noDisposeOnSet:h,size:a,sizeCalculation:o,noUpdateTTL:d,noDeleteOnFetchRejection:y,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:p,ignoreFetchAbort:u,status:l,signal:S},w=this.#s.get(t);if(w===void 0){l&&(l.fetch="miss");let m=this.#G(t,w,F,f);return m.__returned=m}else{let m=this.#t[w];if(this.#e(m)){let E=i&&m.__staleWhileFetching!==void 0;return l&&(l.fetch="inflight",E&&(l.returnedStale=!0)),E?m.__staleWhileFetching:m.__returned=m}let A=this.#p(w);if(!b&&!A)return l&&(l.fetch="hit"),this.#L(w),s&&this.#R(w),l&&this.#E(l,w),m;let z=this.#G(t,w,F,f),v=z.__staleWhileFetching!==void 0&&i;return l&&(l.fetch=A?"stale":"refresh",v&&A&&(l.returnedStale=!0)),v?z.__staleWhileFetching:z.__returned=z}}forceFetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=x()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#K(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#K(t,e={}){let i=await this.#B(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="memo",i.key=t,e.context&&(i.context=e.context),i.cache=this);let s=this.#Q(t,e);return i&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Q(t,e={}){let i=this.#j;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,status:n,forceRefresh:r,...h}=e;n&&r&&(n.forceRefresh=!0);let a=this.#C(t,h),o=r||a===void 0;if(n&&(n.memo=o?"miss":"hit",o||(n.value=a)),!o)return a;let d=i(t,a,{options:h,context:s});return n&&(n.value=d),this.#O(t,d,h),d}get(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="get",i.key=t,i.cache=this);let s=this.#C(t,e);return i&&(s!==void 0&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i)),s}#C(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:r}=e,h=this.#s.get(t);if(h===void 0){r&&(r.get="miss");return}let a=this.#t[h],o=this.#e(a);return r&&this.#E(r,h),this.#p(h)?o?(r&&(r.get="stale-fetching"),i&&a.__staleWhileFetching!==void 0?(r&&(r.returnedStale=!0),a.__staleWhileFetching):void 0):(n||this.#v(t,"expire"),r&&(r.get="stale"),i?(r&&(r.returnedStale=!0),a):void 0):(r&&(r.get=o?"fetching":"hit"),this.#L(h),s&&this.#R(h),o?a.__staleWhileFetching:a)}#q(t,e){this.#u[e]=t,this.#l[t]=e}#L(t){t!==this.#h&&(t===this.#a?this.#a=this.#l[t]:this.#q(this.#u[t],this.#l[t]),this.#q(this.#h,t),this.#h=t)}delete(t){return this.#v(t,"delete")}#v(t,e){g.metrics.hasSubscribers&&g.metrics.publish({op:"delete",delete:e,key:t,cache:this});let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g?.[s]),this.#g[s]=void 0),i=!0,this.#n===1)this.#$(e);else{this.#x(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#T||this.#f)&&(this.#T&&this.#m?.(n,t,e),this.#f&&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.#u[s];else if(s===this.#a)this.#a=this.#l[s];else{let r=this.#u[s];this.#l[r]=this.#l[s];let h=this.#l[s];this.#u[h]=this.#u[s]}this.#n--,this.#y.push(s)}}if(this.#f&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#S?.(...n)}return i}clear(){return this.#$("delete")}#$(t){for(let e of this.#z({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[e];this.#T&&this.#m?.(i,s,t),this.#f&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#F){this.#d.fill(0),this.#F.fill(0);for(let e of this.#g??[])e!==void 0&&clearTimeout(e);this.#g?.fill(void 0)}if(this.#_&&this.#_.fill(0),this.#a=0,this.#h=0,this.#y.length=0,this.#b=0,this.#n=0,this.#f&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#S?.(...i)}}};exports.LRUCache=L; //# sourceMappingURL=index.min.js.map diff --git a/node_modules/lru-cache/dist/commonjs/node/diagnostics-channel.js b/node_modules/lru-cache/dist/commonjs/node/diagnostics-channel.js new file mode 100644 index 0000000000000..30f39a05a5630 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/node/diagnostics-channel.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.tracing = exports.metrics = void 0; +// simple node version that imports from node builtin +// this is built to both ESM and CommonJS on the 'node' import path +const node_diagnostics_channel_1 = require("node:diagnostics_channel"); +exports.metrics = (0, node_diagnostics_channel_1.channel)('lru-cache:metrics'); +exports.tracing = (0, node_diagnostics_channel_1.tracingChannel)('lru-cache'); +//# sourceMappingURL=diagnostics-channel-node.js.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/commonjs/node/index.js b/node_modules/lru-cache/dist/commonjs/node/index.js new file mode 100644 index 0000000000000..179694b1b7b75 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/node/index.js @@ -0,0 +1,1726 @@ +"use strict"; +/** + * @module LRUCache + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LRUCache = void 0; +const diagnostics_channel_js_1 = require("./diagnostics-channel.js"); +const perf_js_1 = require("./perf.js"); +const hasSubscribers = () => diagnostics_channel_js_1.metrics.hasSubscribers || diagnostics_channel_js_1.tracing.hasSubscribers; +const warned = new Set(); +/* c8 ignore start */ +const PROCESS = (typeof process === 'object' && !!process ? + process + : {}); +/* c8 ignore stop */ +const emitWarning = (msg, type, code, fn) => { + if (typeof PROCESS.emitWarning === 'function') { + PROCESS.emitWarning(msg, type, code, fn); + } + else { + //oxlint-disable-next-line no-console + console.error(`[${code}] ${type}: ${msg}`); + } +}; +const shouldWarn = (code) => !warned.has(code); +const TYPE = Symbol('type'); +const isPosInt = (n) => !!n && n === Math.floor(n) && n > 0 && isFinite(n); +// 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. +/* c8 ignore start */ +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 { + /* c8 ignore start - not sure why this is showing up uncovered?? */ + heap; + /* c8 ignore stop */ + 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; + #onInsert; + #disposeAfter; + #fetchMethod; + #memoMethod; + #perf; + /** + * {@link LRUCache.OptionsBase.perf} + */ + get perf() { + return this.#perf; + } + /** + * {@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; + /** {@link LRUCache.OptionsBase.backgroundFetchSize} */ + backgroundFetchSize; + // computed properties + #size; + #calculatedSize; + #keyMap; + #keyList; + #valList; + #next; + #prev; + #head; + #tail; + #free; + #disposed; + #sizes; + #starts; + #ttls; + #autopurgeTimers; + #hasDispose; + #hasFetchMethod; + #hasDisposeAfter; + #hasOnInsert; + /** + * 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, + autopurgeTimers: c.#autopurgeTimers, + 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.onInsert} (read-only) + */ + get onInsert() { + return this.#onInsert; + } + /** + * {@link LRUCache.OptionsBase.disposeAfter} (read-only) + */ + get disposeAfter() { + return this.#disposeAfter; + } + constructor(options) { + const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, onInsert, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, backgroundFetchSize = 1, perf, } = options; + this.backgroundFetchSize = backgroundFetchSize; + if (perf !== undefined) { + if (typeof perf?.now !== 'function') { + throw new TypeError('perf option must have a now() method if specified'); + } + } + this.#perf = perf ?? perf_js_1.defaultPerf; + 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 = Array.from({ length: max }).fill(undefined); + this.#valList = Array.from({ length: 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 onInsert === 'function') { + this.#onInsert = onInsert; + } + if (typeof disposeAfter === 'function') { + this.#disposeAfter = disposeAfter; + this.#disposed = []; + } + else { + this.#disposeAfter = undefined; + this.#disposed = undefined; + } + this.#hasDispose = !!this.#dispose; + this.#hasOnInsert = !!this.#onInsert; + 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; + const purgeTimers = this.ttlAutopurge ? + Array.from({ + length: this.#max, + }) + : undefined; + this.#autopurgeTimers = purgeTimers; + this.#setItemTTL = (index, ttl, start = this.#perf.now()) => { + starts[index] = ttl !== 0 ? start : 0; + ttls[index] = ttl; + setPurgetTimer(index, ttl); + }; + this.#updateItemAge = index => { + starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0; + setPurgetTimer(index, ttls[index]); + }; + // clear out the purge timer if we're setting TTL to 0, and + // previously had a ttl purge timer running, so it doesn't + // fire unnecessarily. Don't need to do this if we're not doing + // autopurge. + const setPurgetTimer = !this.ttlAutopurge ? + () => { } + : (index, ttl) => { + if (purgeTimers?.[index]) { + clearTimeout(purgeTimers[index]); + purgeTimers[index] = undefined; + } + if (ttl && ttl !== 0 && purgeTimers) { + 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 */ + purgeTimers[index] = t; + } + }; + this.#statusTTL = (status, index) => { + if (ttls[index]) { + const ttl = ttls[index]; + const start = starts[index]; + /* c8 ignore start */ + if (!ttl || !start) { + return; + } + /* c8 ignore stop */ + 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 = this.#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) => { + if (!isPosInt(size)) { + // provisionally accept background fetches. + // actual value size will be checked when they return. + if (this.#isBackgroundFetch(v)) { + // NB: this cannot occur if v.__staleWhileFetching is set, + // because in that case, it would take on the size of the + // existing entry that it temporarily replaces. + return this.backgroundFetchSize; + } + 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; this.#isValidIndex(i);) { + 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; this.#isValidIndex(i);) { + 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]; + /* c8 ignore start - this isn't tested for the info function, + * but it's the same logic as found in other places. */ + const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + if (value === undefined) + return undefined; + /* c8 ignore stop */ + const entry = { value }; + if (this.#ttls && this.#starts) { + const ttl = this.#ttls[i]; + const start = this.#starts[i]; + if (ttl && start) { + const remain = ttl - (this.#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 LRUCache#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 = this.#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 = this.#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 = {}) { + const { status = diagnostics_channel_js_1.metrics.hasSubscribers ? {} : undefined } = setOptions; + setOptions.status = status; + if (status) { + status.op = 'set'; + status.key = k; + if (v !== undefined) + status.value = v; + status.cache = this; + } + const result = this.#set(k, v, setOptions); + if (status && diagnostics_channel_js_1.metrics.hasSubscribers) { + diagnostics_channel_js_1.metrics.publish(status); + } + return result; + } + #set(k, v, setOptions, bf) { + const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; + const isBF = this.#isBackgroundFetch(v); + if (v === undefined) { + if (status) + status.set = 'deleted'; + this.delete(k); + return this; + } + let { noUpdateTTL = this.noUpdateTTL } = setOptions; + if (status && !isBF) + status.value = v; + const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation, status); + // if the item doesn't fit, don't do anything + // NB: maxEntrySize set to maxSize by default + if (this.maxEntrySize && size > this.maxEntrySize) { + // have to delete, in case something is there already. + this.#delete(k, 'set'); + if (status) { + status.set = 'miss'; + status.maxEntrySizeExceeded = true; + } + 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; + if (this.#hasOnInsert && !isBF) { + this.#onInsert?.(v, k, 'add'); + } + } + else { + // update + // might be updating a background fetch! + this.#moveToTail(index); + const oldVal = this.#valList[index]; + if (v !== oldVal) { + if (!noDisposeOnSet) { + if (this.#isBackgroundFetch(oldVal)) { + if (oldVal !== bf) { + // setting over a background fetch, not merely resolving it. + oldVal.__abortController.abort(new Error('replaced')); + } + const { __staleWhileFetching: s } = oldVal; + if (s !== undefined && s !== v) { + if (this.#hasDispose) { + this.#dispose?.(s, k, 'set'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([s, k, 'set']); + } + } + } + else { + 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 (!isBF) { + const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? + oldVal.__staleWhileFetching + : oldVal; + const setType = oldValue === undefined ? 'add' + : v !== oldValue ? 'replace' + : 'update'; + if (status) { + status.set = setType; + if (oldValue !== undefined) + status.oldValue = oldValue; + } + if (this.#hasOnInsert) { + this.onInsert?.(v, k, setType); + } + } + } + else if (!isBF) { + if (status) { + status.set = 'update'; + } + if (this.#hasOnInsert) { + this.onInsert?.(v, k, '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]; + const isBF = this.#isBackgroundFetch(v); + if (isBF) { + v.__abortController.abort(new Error('evicted')); + } + const oldValue = isBF ? v.__staleWhileFetching : v; + if ((this.#hasDispose || this.#hasDisposeAfter) && + oldValue !== undefined) { + if (this.#hasDispose) { + this.#dispose?.(oldValue, k, 'evict'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([oldValue, k, 'evict']); + } + } + this.#removeItemSize(head); + if (this.#autopurgeTimers?.[head]) { + clearTimeout(this.#autopurgeTimers[head]); + this.#autopurgeTimers[head] = undefined; + } + // 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 { status = diagnostics_channel_js_1.metrics.hasSubscribers ? {} : undefined } = hasOptions; + hasOptions.status = status; + if (status) { + status.op = 'has'; + status.key = k; + status.cache = this; + } + const result = this.#has(k, hasOptions); + if (diagnostics_channel_js_1.metrics.hasSubscribers) + diagnostics_channel_js_1.metrics.publish(status); + return result; + } + #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 { status = hasSubscribers() ? {} : undefined } = peekOptions; + if (status) { + status.op = 'peek'; + status.key = k; + status.cache = this; + } + peekOptions.status = status; + const result = this.#peek(k, peekOptions); + if (diagnostics_channel_js_1.metrics.hasSubscribers) { + diagnostics_channel_js_1.metrics.publish(status); + } + return result; + } + #peek(k, peekOptions) { + const { status, allowStale = this.allowStale } = peekOptions; + const index = this.#keyMap.get(k); + if (index === undefined || (!allowStale && this.#isStale(index))) { + if (status) + status.peek = index === undefined ? 'miss' : 'stale'; + return undefined; + } + const v = this.#valList[index]; + const val = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + if (status) { + if (val !== undefined) { + status.peek = 'hit'; + status.value = val; + } + else { + status.peek = 'miss'; + } + } + return val; + } + #backgroundFetch(k, index, options, context) { + const v = index === undefined ? undefined : this.#valList[index]; + if (this.#isBackgroundFetch(v)) { + return v; + } + const ac = new AbortController(); + 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; + const proceed = options.ignoreFetchAbort || + !!(options.allowStaleOnFetchAbort && 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, proceed); + } + // either we didn't abort, and are still here, or we did, and ignored + const bf = p; + // if nothing else has been written there but we're set to update the + // cache and ignore the abort, or if it's still pending on this specific + // background request, then write it to the cache. + const vl = this.#valList[index]; + if (vl === p || (vl === undefined && ignoreAbort && updateCache)) { + if (v === undefined) { + if (bf.__staleWhileFetching !== undefined) { + this.#valList[index] = bf.__staleWhileFetching; + } + else { + this.#delete(k, 'fetch'); + } + } + else { + if (options.status) + options.status.fetchUpdated = true; + this.#set(k, v, fetchOpts.options, bf); + } + } + return v; + }; + const eb = (er) => { + if (options.status) { + options.status.fetchRejected = true; + options.status.fetchError = er; + } + // do not pass go, do not collect $200 + return fetchFail(er, false); + }; + const fetchFail = (er, proceed) => { + 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 || (!proceed && 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); + // 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 (fmp && fmp instanceof Promise) { + fmp.then(v => res(v === undefined ? undefined : v), rej); + } + else if (fmp !== undefined) { + res(fmp); + } + }; + 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 { + // do not call #set, because we do not want to adjust its place + // in the lru queue, as it has not yet been "used". Also, we don't + // need to worry about evicting for size, because a background fetch + // over a stale value is treated as the same size as its stale value. + 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 AbortController); + } + fetch(k, fetchOptions = {}) { + const ths = diagnostics_channel_js_1.tracing.hasSubscribers; + const { status = hasSubscribers() ? {} : undefined } = fetchOptions; + fetchOptions.status = status; + if (status && fetchOptions.context) { + status.context = fetchOptions.context; + } + const p = this.#fetch(k, fetchOptions); + if (status && ths) { + status.trace = true; + diagnostics_channel_js_1.tracing.tracePromise(() => p, status).catch(() => { }); + } + return p; + } + 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 (status) { + status.op = 'fetch'; + status.key = k; + if (forceRefresh) + status.forceRefresh = true; + status.cache = this; + } + 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); + } + } + forceFetch(k, fetchOptions = {}) { + const ths = diagnostics_channel_js_1.tracing.hasSubscribers; + const { status = hasSubscribers() ? {} : undefined } = fetchOptions; + fetchOptions.status = status; + if (status && fetchOptions.context) { + status.context = fetchOptions.context; + } + const p = this.#forceFetch(k, fetchOptions); + if (status && ths) { + status.trace = true; + diagnostics_channel_js_1.tracing.tracePromise(() => p, status).catch(() => { }); + } + return 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 { status = diagnostics_channel_js_1.metrics.hasSubscribers ? {} : undefined } = memoOptions; + memoOptions.status = status; + if (status) { + status.op = 'memo'; + status.key = k; + if (memoOptions.context) { + status.context = memoOptions.context; + } + status.cache = this; + } + const result = this.#memo(k, memoOptions); + if (status) + status.value = result; + if (diagnostics_channel_js_1.metrics.hasSubscribers) + diagnostics_channel_js_1.metrics.publish(status); + return result; + } + #memo(k, memoOptions = {}) { + const memoMethod = this.#memoMethod; + if (!memoMethod) { + throw new Error('no memoMethod provided to constructor'); + } + const { context, status, forceRefresh, ...options } = memoOptions; + if (status && forceRefresh) + status.forceRefresh = true; + const v = this.#get(k, options); + const refresh = forceRefresh || v === undefined; + if (status) { + status.memo = refresh ? 'miss' : 'hit'; + if (!refresh) + status.value = v; + } + if (!refresh) + return v; + const vv = memoMethod(k, v, { + options, + context, + }); + if (status) + status.value = vv; + 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 { status = diagnostics_channel_js_1.metrics.hasSubscribers ? {} : undefined } = getOptions; + getOptions.status = status; + if (status) { + status.op = 'get'; + status.key = k; + status.cache = this; + } + const result = this.#get(k, getOptions); + if (status) { + if (result !== undefined) + status.value = result; + if (diagnostics_channel_js_1.metrics.hasSubscribers) + diagnostics_channel_js_1.metrics.publish(status); + } + return result; + } + #get(k, getOptions = {}) { + const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; + const index = this.#keyMap.get(k); + if (index === undefined) { + if (status) + status.get = 'miss'; + return undefined; + } + const value = this.#valList[index]; + const fetching = this.#isBackgroundFetch(value); + if (status) + this.#statusTTL(status, index); + if (this.#isStale(index)) { + // delete only if not an in-flight background fetch + if (!fetching) { + if (!noDeleteOnStaleGet) { + this.#delete(k, 'expire'); + } + if (status) + status.get = 'stale'; + if (allowStale) { + if (status) + status.returnedStale = true; + return value; + } + return undefined; + } + if (status) + status.get = 'stale-fetching'; + if (allowStale && value.__staleWhileFetching !== undefined) { + if (status) + status.returnedStale = true; + return value.__staleWhileFetching; + } + return undefined; + } + // not stale + if (status) + status.get = fetching ? 'fetching' : '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. + this.#moveToTail(index); + if (updateAgeOnGet) { + this.#updateItemAge(index); + } + return fetching ? value.__staleWhileFetching : value; + } + #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) { + if (diagnostics_channel_js_1.metrics.hasSubscribers) { + diagnostics_channel_js_1.metrics.publish({ + op: 'delete', + delete: reason, + key: k, + cache: this, + }); + } + let deleted = false; + if (this.#size !== 0) { + const index = this.#keyMap.get(k); + if (index !== undefined) { + if (this.#autopurgeTimers?.[index]) { + clearTimeout(this.#autopurgeTimers?.[index]); + this.#autopurgeTimers[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(); + void this.#valList.fill(undefined); + this.#keyList.fill(undefined); + if (this.#ttls && this.#starts) { + this.#ttls.fill(0); + this.#starts.fill(0); + for (const t of this.#autopurgeTimers ?? []) { + if (t !== undefined) + clearTimeout(t); + } + this.#autopurgeTimers?.fill(undefined); + } + 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 \ No newline at end of file diff --git a/node_modules/lru-cache/dist/commonjs/node/index.min.js b/node_modules/lru-cache/dist/commonjs/node/index.min.js new file mode 100644 index 0000000000000..a03fc77191387 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/node/index.min.js @@ -0,0 +1,2 @@ +"use strict";var j=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var I=j(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.tracing=O.metrics=void 0;var U=require("node:diagnostics_channel");O.metrics=(0,U.channel)("lru-cache:metrics");O.tracing=(0,U.tracingChannel)("lru-cache")});var P=j(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.defaultPerf=void 0;D.defaultPerf=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date});Object.defineProperty(exports,"__esModule",{value:!0});exports.LRUCache=void 0;var g=I(),N=P(),C=()=>g.metrics.hasSubscribers||g.tracing.hasSubscribers,k=new Set,G=typeof process=="object"&&process?process:{},V=(c,t,e,i)=>{typeof G.emitWarning=="function"?G.emitWarning(c,t,e,i):console.error(`[${e}] ${t}: ${c}`)},q=c=>!k.has(c);var T=c=>!!c&&c===Math.floor(c)&&c>0&&isFinite(c),H=c=>T(c)?c<=Math.pow(2,8)?Uint8Array:c<=Math.pow(2,16)?Uint16Array:c<=Math.pow(2,32)?Uint32Array:c<=Number.MAX_SAFE_INTEGER?W:null:null,W=class extends Array{constructor(t){super(t),this.fill(0)}},x=class c{heap;length;static#o=!1;static create(t){let e=H(t);if(!e)return[];c.#o=!0;let i=new c(t,e);return c.#o=!1,i}constructor(t,e){if(!c.#o)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]}},L=class c{#o;#c;#m;#W;#S;#M;#j;#w;get perf(){return this.#w}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#n;#b;#s;#i;#t;#l;#u;#a;#h;#_;#r;#y;#F;#d;#g;#T;#U;#f;#D;static unsafeExposeInternals(t){return{starts:t.#F,ttls:t.#d,autopurgeTimers:t.#g,sizes:t.#y,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#l,prev:t.#u,get head(){return t.#a},get tail(){return t.#h},free:t.#_,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,n)=>t.#G(e,i,s,n),moveToTail:e=>t.#L(e),indexes:e=>t.#A(e),rindexes:e=>t.#z(e),isStale:e=>t.#p(e)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#b}get size(){return this.#n}get fetchMethod(){return this.#M}get memoMethod(){return this.#j}get dispose(){return this.#m}get onInsert(){return this.#W}get disposeAfter(){return this.#S}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:r,updateAgeOnHas:h,allowStale:a,dispose:o,onInsert:d,disposeAfter:_,noDisposeOnSet:y,noUpdateTTL:u,maxSize:p=0,maxEntrySize:f=0,sizeCalculation:b,fetchMethod:l,memoMethod:S,noDeleteOnFetchRejection:F,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:A,ignoreFetchAbort:z,backgroundFetchSize:M=1,perf:v}=t;if(this.backgroundFetchSize=M,v!==void 0&&typeof v?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#w=v??N.defaultPerf,e!==0&&!T(e))throw new TypeError("max option must be a nonnegative integer");let E=e?H(e):Array;if(!E)throw new Error("invalid max value: "+e);if(this.#o=e,this.#c=p,this.maxEntrySize=f||this.#c,this.sizeCalculation=b,this.sizeCalculation){if(!this.#c&&!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(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#j=S,l!==void 0&&typeof l!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#M=l,this.#U=!!l,this.#s=new Map,this.#i=Array.from({length:e}).fill(void 0),this.#t=Array.from({length:e}).fill(void 0),this.#l=new E(e),this.#u=new E(e),this.#a=0,this.#h=0,this.#_=x.create(e),this.#n=0,this.#b=0,typeof o=="function"&&(this.#m=o),typeof d=="function"&&(this.#W=d),typeof _=="function"?(this.#S=_,this.#r=[]):(this.#S=void 0,this.#r=void 0),this.#T=!!this.#m,this.#D=!!this.#W,this.#f=!!this.#S,this.noDisposeOnSet=!!y,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!F,this.allowStaleOnFetchRejection=!!m,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.#c!==0&&!T(this.#c))throw new TypeError("maxSize must be a positive integer if specified");if(!T(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#X()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!r,this.updateAgeOnHas=!!h,this.ttlResolution=T(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!T(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#k()}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let R="LRU_CACHE_UNBOUNDED";q(R)&&(k.add(R),V("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}#k(){let t=new W(this.#o),e=new W(this.#o);this.#d=t,this.#F=e;let i=this.ttlAutopurge?Array.from({length:this.#o}):void 0;this.#g=i,this.#H=(h,a,o=this.#w.now())=>{e[h]=a!==0?o:0,t[h]=a,s(h,a)},this.#R=h=>{e[h]=t[h]!==0?this.#w.now():0,s(h,t[h])};let s=this.ttlAutopurge?(h,a)=>{if(i?.[h]&&(clearTimeout(i[h]),i[h]=void 0),a&&a!==0&&i){let o=setTimeout(()=>{this.#p(h)&&this.#v(this.#i[h],"expire")},a+1);o.unref&&o.unref(),i[h]=o}}:()=>{};this.#E=(h,a)=>{if(t[a]){let o=t[a],d=e[a];if(!o||!d)return;h.ttl=o,h.start=d,h.now=n||r();let _=h.now-d;h.remainingTTL=o-_}};let n=0,r=()=>{let h=this.#w.now();if(this.ttlResolution>0){n=h;let a=setTimeout(()=>n=0,this.ttlResolution);a.unref&&a.unref()}return h};this.getRemainingTTL=h=>{let a=this.#s.get(h);if(a===void 0)return 0;let o=t[a],d=e[a];if(!o||!d)return 1/0;let _=(n||r())-d;return o-_},this.#p=h=>{let a=e[h],o=t[h];return!!o&&!!a&&(n||r())-a>o}}#R=()=>{};#E=()=>{};#H=()=>{};#p=()=>!1;#X(){let t=new W(this.#o);this.#b=0,this.#y=t,this.#C=e=>{this.#b-=t[e],t[e]=0},this.#N=(e,i,s,n)=>{if(!T(s)){if(this.#e(i))return this.backgroundFetchSize;if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,e),!T(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.#I=(e,i,s)=>{if(t[e]=i,this.#c){let n=this.#c-t[e];for(;this.#b>n;)this.#P(!0)}this.#b+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#b)}}#C=t=>{};#I=(t,e,i)=>{};#N=(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.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#a);)e=this.#u[e]}*#z({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#a;this.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#h);)e=this.#l[e]}#V(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.#z())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.#z()){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.#z())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.#x(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.#z()){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.#z({allowStale:!0}))this.#p(e)&&(this.#v(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.#d&&this.#F){let r=this.#d[e],h=this.#F[e];if(r&&h){let a=r-(this.#w.now()-h);n.ttl=a,n.start=Date.now()}}return this.#y&&(n.size=this.#y[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 r={value:n};if(this.#d&&this.#F){r.ttl=this.#d[e];let h=this.#w.now()-this.#F[e];r.start=Math.floor(Date.now()-h)}this.#y&&(r.size=this.#y[e]),t.unshift([i,r])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=this.#w.now()-s}this.#O(e,i.value,i)}}set(t,e,i={}){let{status:s=g.metrics.hasSubscribers?{}:void 0}=i;i.status=s,s&&(s.op="set",s.key=t,e!==void 0&&(s.value=e),s.cache=this);let n=this.#O(t,e,i);return s&&g.metrics.hasSubscribers&&g.metrics.publish(s),n}#O(t,e,i,s){let{ttl:n=this.ttl,start:r,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:o}=i,d=this.#e(e);if(e===void 0)return o&&(o.set="deleted"),this.delete(t),this;let{noUpdateTTL:_=this.noUpdateTTL}=i;o&&!d&&(o.value=e);let y=this.#N(t,e,i.size||0,a,o);if(this.maxEntrySize&&y>this.maxEntrySize)return this.#v(t,"set"),o&&(o.set="miss",o.maxEntrySizeExceeded=!0),this;let u=this.#n===0?void 0:this.#s.get(t);if(u===void 0)u=this.#n===0?this.#h:this.#_.length!==0?this.#_.pop():this.#n===this.#o?this.#P(!1):this.#n,this.#i[u]=t,this.#t[u]=e,this.#s.set(t,u),this.#l[this.#h]=u,this.#u[u]=this.#h,this.#h=u,this.#n++,this.#I(u,y,o),o&&(o.set="add"),_=!1,this.#D&&!d&&this.#W?.(e,t,"add");else{this.#L(u);let p=this.#t[u];if(e!==p){if(!h)if(this.#e(p)){p!==s&&p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&f!==e&&(this.#T&&this.#m?.(f,t,"set"),this.#f&&this.#r?.push([f,t,"set"]))}else this.#T&&this.#m?.(p,t,"set"),this.#f&&this.#r?.push([p,t,"set"]);if(this.#C(u),this.#I(u,y,o),this.#t[u]=e,!d){let f=p&&this.#e(p)?p.__staleWhileFetching:p,b=f===void 0?"add":e!==f?"replace":"update";o&&(o.set=b,f!==void 0&&(o.oldValue=f)),this.#D&&this.onInsert?.(e,t,b)}}else d||(o&&(o.set="update"),this.#D&&this.onInsert?.(e,t,"update"))}if(n!==0&&!this.#d&&this.#k(),this.#d&&(_||this.#H(u,n,r),o&&this.#E(o,u)),!h&&this.#f&&this.#r){let p=this.#r,f;for(;f=p?.shift();)this.#S?.(...f)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#a];if(this.#P(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#f&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#S?.(...e)}}}#P(t){let e=this.#a,i=this.#i[e],s=this.#t[e],n=this.#e(s);n&&s.__abortController.abort(new Error("evicted"));let r=n?s.__staleWhileFetching:s;return(this.#T||this.#f)&&r!==void 0&&(this.#T&&this.#m?.(r,i,"evict"),this.#f&&this.#r?.push([r,i,"evict"])),this.#C(e),this.#g?.[e]&&(clearTimeout(this.#g[e]),this.#g[e]=void 0),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#_.push(e)),this.#n===1?(this.#a=this.#h=0,this.#_.length=0):this.#a=this.#l[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="has",i.key=t,i.cache=this);let s=this.#Y(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Y(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,n=this.#s.get(t);if(n!==void 0){let r=this.#t[n];if(this.#e(r)&&r.__staleWhileFetching===void 0)return!1;if(this.#p(n))s&&(s.has="stale",this.#E(s,n));else return i&&this.#R(n),s&&(s.has="hit",this.#E(s,n)),!0}else s&&(s.has="miss");return!1}peek(t,e={}){let{status:i=C()?{}:void 0}=e;i&&(i.op="peek",i.key=t,i.cache=this),e.status=i;let s=this.#J(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#J(t,e){let{status:i,allowStale:s=this.allowStale}=e,n=this.#s.get(t);if(n===void 0||!s&&this.#p(n)){i&&(i.peek=n===void 0?"miss":"stale");return}let r=this.#t[n],h=this.#e(r)?r.__staleWhileFetching:r;return i&&(h!==void 0?(i.peek="hit",i.value=h):i.peek="miss"),h}#G(t,e,i,s){let n=e===void 0?void 0:this.#t[e];if(this.#e(n))return n;let r=new AbortController,{signal:h}=i;h?.addEventListener("abort",()=>r.abort(h.reason),{signal:r.signal});let a={signal:r.signal,options:i,context:s},o=(f,b=!1)=>{let{aborted:l}=r.signal,S=i.ignoreFetchAbort&&f!==void 0,F=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&f!==void 0);if(i.status&&(l&&!b?(i.status.fetchAborted=!0,i.status.fetchError=r.signal.reason,S&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),l&&!S&&!b)return _(r.signal.reason,F);let w=u,m=this.#t[e];return(m===u||m===void 0&&S&&b)&&(f===void 0?w.__staleWhileFetching!==void 0?this.#t[e]=w.__staleWhileFetching:this.#v(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.#O(t,f,a.options,w))),f},d=f=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=f),_(f,!1)),_=(f,b)=>{let{aborted:l}=r.signal,S=l&&i.allowStaleOnFetchAbort,F=S||i.allowStaleOnFetchRejection,w=F||i.noDeleteOnFetchRejection,m=u;if(this.#t[e]===u&&(!w||!b&&m.__staleWhileFetching===void 0?this.#v(t,"fetch"):S||(this.#t[e]=m.__staleWhileFetching)),F)return i.status&&m.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),m.__staleWhileFetching;if(m.__returned===m)throw f},y=(f,b)=>{let l=this.#M?.(t,n,a);r.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(f(void 0),i.allowStaleOnFetchAbort&&(f=S=>o(S,!0)))}),l&&l instanceof Promise?l.then(S=>f(S===void 0?void 0:S),b):l!==void 0&&f(l)};i.status&&(i.status.fetchDispatched=!0);let u=new Promise(y).then(o,d),p=Object.assign(u,{__abortController:r,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.#O(t,p,{...a.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=p,p}#e(t){if(!this.#U)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof AbortController}fetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=C()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#q(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#q(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:r=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:a=0,sizeCalculation:o=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:_=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:y=this.allowStaleOnFetchRejection,ignoreFetchAbort:u=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:f,forceRefresh:b=!1,status:l,signal:S}=e;if(l&&(l.op="fetch",l.key=t,b&&(l.forceRefresh=!0),l.cache=this),!this.#U)return l&&(l.fetch="get"),this.#x(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:l});let F={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:r,noDisposeOnSet:h,size:a,sizeCalculation:o,noUpdateTTL:d,noDeleteOnFetchRejection:_,allowStaleOnFetchRejection:y,allowStaleOnFetchAbort:p,ignoreFetchAbort:u,status:l,signal:S},w=this.#s.get(t);if(w===void 0){l&&(l.fetch="miss");let m=this.#G(t,w,F,f);return m.__returned=m}else{let m=this.#t[w];if(this.#e(m)){let E=i&&m.__staleWhileFetching!==void 0;return l&&(l.fetch="inflight",E&&(l.returnedStale=!0)),E?m.__staleWhileFetching:m.__returned=m}let A=this.#p(w);if(!b&&!A)return l&&(l.fetch="hit"),this.#L(w),s&&this.#R(w),l&&this.#E(l,w),m;let z=this.#G(t,w,F,f),v=z.__staleWhileFetching!==void 0&&i;return l&&(l.fetch=A?"stale":"refresh",v&&A&&(l.returnedStale=!0)),v?z.__staleWhileFetching:z.__returned=z}}forceFetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=C()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#K(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#K(t,e={}){let i=await this.#q(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="memo",i.key=t,e.context&&(i.context=e.context),i.cache=this);let s=this.#Q(t,e);return i&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Q(t,e={}){let i=this.#j;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,status:n,forceRefresh:r,...h}=e;n&&r&&(n.forceRefresh=!0);let a=this.#x(t,h),o=r||a===void 0;if(n&&(n.memo=o?"miss":"hit",o||(n.value=a)),!o)return a;let d=i(t,a,{options:h,context:s});return n&&(n.value=d),this.#O(t,d,h),d}get(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="get",i.key=t,i.cache=this);let s=this.#x(t,e);return i&&(s!==void 0&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i)),s}#x(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:r}=e,h=this.#s.get(t);if(h===void 0){r&&(r.get="miss");return}let a=this.#t[h],o=this.#e(a);return r&&this.#E(r,h),this.#p(h)?o?(r&&(r.get="stale-fetching"),i&&a.__staleWhileFetching!==void 0?(r&&(r.returnedStale=!0),a.__staleWhileFetching):void 0):(n||this.#v(t,"expire"),r&&(r.get="stale"),i?(r&&(r.returnedStale=!0),a):void 0):(r&&(r.get=o?"fetching":"hit"),this.#L(h),s&&this.#R(h),o?a.__staleWhileFetching:a)}#B(t,e){this.#u[e]=t,this.#l[t]=e}#L(t){t!==this.#h&&(t===this.#a?this.#a=this.#l[t]:this.#B(this.#u[t],this.#l[t]),this.#B(this.#h,t),this.#h=t)}delete(t){return this.#v(t,"delete")}#v(t,e){g.metrics.hasSubscribers&&g.metrics.publish({op:"delete",delete:e,key:t,cache:this});let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g?.[s]),this.#g[s]=void 0),i=!0,this.#n===1)this.#$(e);else{this.#C(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#T||this.#f)&&(this.#T&&this.#m?.(n,t,e),this.#f&&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.#u[s];else if(s===this.#a)this.#a=this.#l[s];else{let r=this.#u[s];this.#l[r]=this.#l[s];let h=this.#l[s];this.#u[h]=this.#u[s]}this.#n--,this.#_.push(s)}}if(this.#f&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#S?.(...n)}return i}clear(){return this.#$("delete")}#$(t){for(let e of this.#z({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[e];this.#T&&this.#m?.(i,s,t),this.#f&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#F){this.#d.fill(0),this.#F.fill(0);for(let e of this.#g??[])e!==void 0&&clearTimeout(e);this.#g?.fill(void 0)}if(this.#y&&this.#y.fill(0),this.#a=0,this.#h=0,this.#_.length=0,this.#b=0,this.#n=0,this.#f&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#S?.(...i)}}};exports.LRUCache=L; +//# sourceMappingURL=index.min.js.map diff --git a/node_modules/lru-cache/dist/commonjs/node/perf.js b/node_modules/lru-cache/dist/commonjs/node/perf.js new file mode 100644 index 0000000000000..bd4c80f461d6c --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/node/perf.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultPerf = void 0; +exports.defaultPerf = (typeof performance === 'object' && + performance && + typeof performance.now === 'function') ? + /* c8 ignore start - this gets covered, but c8 gets confused */ + performance + : /* c8 ignore stop */ Date; +//# sourceMappingURL=perf.js.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/commonjs/perf.js b/node_modules/lru-cache/dist/commonjs/perf.js new file mode 100644 index 0000000000000..bd4c80f461d6c --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/perf.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultPerf = void 0; +exports.defaultPerf = (typeof performance === 'object' && + performance && + typeof performance.now === 'function') ? + /* c8 ignore start - this gets covered, but c8 gets confused */ + performance + : /* c8 ignore stop */ Date; +//# sourceMappingURL=perf.js.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/esm/browser/diagnostics-channel.js b/node_modules/lru-cache/dist/esm/browser/diagnostics-channel.js new file mode 100644 index 0000000000000..37524f355f050 --- /dev/null +++ b/node_modules/lru-cache/dist/esm/browser/diagnostics-channel.js @@ -0,0 +1,4 @@ +const dummy = { hasSubscribers: false }; +export const metrics = dummy; +export const tracing = dummy; +//# sourceMappingURL=diagnostics-channel-browser.js.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/esm/browser/index.js b/node_modules/lru-cache/dist/esm/browser/index.js new file mode 100644 index 0000000000000..2dd10cf8f908f --- /dev/null +++ b/node_modules/lru-cache/dist/esm/browser/index.js @@ -0,0 +1,1722 @@ +/** + * @module LRUCache + */ +import { metrics, tracing } from './diagnostics-channel.js'; +import { defaultPerf } from './perf.js'; +const hasSubscribers = () => metrics.hasSubscribers || tracing.hasSubscribers; +const warned = new Set(); +/* c8 ignore start */ +const PROCESS = (typeof process === 'object' && !!process ? + process + : {}); +/* c8 ignore stop */ +const emitWarning = (msg, type, code, fn) => { + if (typeof PROCESS.emitWarning === 'function') { + PROCESS.emitWarning(msg, type, code, fn); + } + else { + //oxlint-disable-next-line no-console + console.error(`[${code}] ${type}: ${msg}`); + } +}; +const shouldWarn = (code) => !warned.has(code); +const TYPE = Symbol('type'); +const isPosInt = (n) => !!n && n === Math.floor(n) && n > 0 && isFinite(n); +// 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. +/* c8 ignore start */ +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 { + /* c8 ignore start - not sure why this is showing up uncovered?? */ + heap; + /* c8 ignore stop */ + 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; + #onInsert; + #disposeAfter; + #fetchMethod; + #memoMethod; + #perf; + /** + * {@link LRUCache.OptionsBase.perf} + */ + get perf() { + return this.#perf; + } + /** + * {@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; + /** {@link LRUCache.OptionsBase.backgroundFetchSize} */ + backgroundFetchSize; + // computed properties + #size; + #calculatedSize; + #keyMap; + #keyList; + #valList; + #next; + #prev; + #head; + #tail; + #free; + #disposed; + #sizes; + #starts; + #ttls; + #autopurgeTimers; + #hasDispose; + #hasFetchMethod; + #hasDisposeAfter; + #hasOnInsert; + /** + * 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, + autopurgeTimers: c.#autopurgeTimers, + 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.onInsert} (read-only) + */ + get onInsert() { + return this.#onInsert; + } + /** + * {@link LRUCache.OptionsBase.disposeAfter} (read-only) + */ + get disposeAfter() { + return this.#disposeAfter; + } + constructor(options) { + const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, onInsert, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, backgroundFetchSize = 1, perf, } = options; + this.backgroundFetchSize = backgroundFetchSize; + if (perf !== undefined) { + if (typeof perf?.now !== 'function') { + throw new TypeError('perf option must have a now() method if specified'); + } + } + this.#perf = perf ?? defaultPerf; + 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 = Array.from({ length: max }).fill(undefined); + this.#valList = Array.from({ length: 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 onInsert === 'function') { + this.#onInsert = onInsert; + } + if (typeof disposeAfter === 'function') { + this.#disposeAfter = disposeAfter; + this.#disposed = []; + } + else { + this.#disposeAfter = undefined; + this.#disposed = undefined; + } + this.#hasDispose = !!this.#dispose; + this.#hasOnInsert = !!this.#onInsert; + 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; + const purgeTimers = this.ttlAutopurge ? + Array.from({ + length: this.#max, + }) + : undefined; + this.#autopurgeTimers = purgeTimers; + this.#setItemTTL = (index, ttl, start = this.#perf.now()) => { + starts[index] = ttl !== 0 ? start : 0; + ttls[index] = ttl; + setPurgetTimer(index, ttl); + }; + this.#updateItemAge = index => { + starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0; + setPurgetTimer(index, ttls[index]); + }; + // clear out the purge timer if we're setting TTL to 0, and + // previously had a ttl purge timer running, so it doesn't + // fire unnecessarily. Don't need to do this if we're not doing + // autopurge. + const setPurgetTimer = !this.ttlAutopurge ? + () => { } + : (index, ttl) => { + if (purgeTimers?.[index]) { + clearTimeout(purgeTimers[index]); + purgeTimers[index] = undefined; + } + if (ttl && ttl !== 0 && purgeTimers) { + 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 */ + purgeTimers[index] = t; + } + }; + this.#statusTTL = (status, index) => { + if (ttls[index]) { + const ttl = ttls[index]; + const start = starts[index]; + /* c8 ignore start */ + if (!ttl || !start) { + return; + } + /* c8 ignore stop */ + 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 = this.#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) => { + if (!isPosInt(size)) { + // provisionally accept background fetches. + // actual value size will be checked when they return. + if (this.#isBackgroundFetch(v)) { + // NB: this cannot occur if v.__staleWhileFetching is set, + // because in that case, it would take on the size of the + // existing entry that it temporarily replaces. + return this.backgroundFetchSize; + } + 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; this.#isValidIndex(i);) { + 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; this.#isValidIndex(i);) { + 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]; + /* c8 ignore start - this isn't tested for the info function, + * but it's the same logic as found in other places. */ + const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + if (value === undefined) + return undefined; + /* c8 ignore stop */ + const entry = { value }; + if (this.#ttls && this.#starts) { + const ttl = this.#ttls[i]; + const start = this.#starts[i]; + if (ttl && start) { + const remain = ttl - (this.#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 LRUCache#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 = this.#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 = this.#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 = {}) { + const { status = metrics.hasSubscribers ? {} : undefined } = setOptions; + setOptions.status = status; + if (status) { + status.op = 'set'; + status.key = k; + if (v !== undefined) + status.value = v; + status.cache = this; + } + const result = this.#set(k, v, setOptions); + if (status && metrics.hasSubscribers) { + metrics.publish(status); + } + return result; + } + #set(k, v, setOptions, bf) { + const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; + const isBF = this.#isBackgroundFetch(v); + if (v === undefined) { + if (status) + status.set = 'deleted'; + this.delete(k); + return this; + } + let { noUpdateTTL = this.noUpdateTTL } = setOptions; + if (status && !isBF) + status.value = v; + const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation, status); + // if the item doesn't fit, don't do anything + // NB: maxEntrySize set to maxSize by default + if (this.maxEntrySize && size > this.maxEntrySize) { + // have to delete, in case something is there already. + this.#delete(k, 'set'); + if (status) { + status.set = 'miss'; + status.maxEntrySizeExceeded = true; + } + 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; + if (this.#hasOnInsert && !isBF) { + this.#onInsert?.(v, k, 'add'); + } + } + else { + // update + // might be updating a background fetch! + this.#moveToTail(index); + const oldVal = this.#valList[index]; + if (v !== oldVal) { + if (!noDisposeOnSet) { + if (this.#isBackgroundFetch(oldVal)) { + if (oldVal !== bf) { + // setting over a background fetch, not merely resolving it. + oldVal.__abortController.abort(new Error('replaced')); + } + const { __staleWhileFetching: s } = oldVal; + if (s !== undefined && s !== v) { + if (this.#hasDispose) { + this.#dispose?.(s, k, 'set'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([s, k, 'set']); + } + } + } + else { + 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 (!isBF) { + const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? + oldVal.__staleWhileFetching + : oldVal; + const setType = oldValue === undefined ? 'add' + : v !== oldValue ? 'replace' + : 'update'; + if (status) { + status.set = setType; + if (oldValue !== undefined) + status.oldValue = oldValue; + } + if (this.#hasOnInsert) { + this.onInsert?.(v, k, setType); + } + } + } + else if (!isBF) { + if (status) { + status.set = 'update'; + } + if (this.#hasOnInsert) { + this.onInsert?.(v, k, '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]; + const isBF = this.#isBackgroundFetch(v); + if (isBF) { + v.__abortController.abort(new Error('evicted')); + } + const oldValue = isBF ? v.__staleWhileFetching : v; + if ((this.#hasDispose || this.#hasDisposeAfter) && + oldValue !== undefined) { + if (this.#hasDispose) { + this.#dispose?.(oldValue, k, 'evict'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([oldValue, k, 'evict']); + } + } + this.#removeItemSize(head); + if (this.#autopurgeTimers?.[head]) { + clearTimeout(this.#autopurgeTimers[head]); + this.#autopurgeTimers[head] = undefined; + } + // 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 { status = metrics.hasSubscribers ? {} : undefined } = hasOptions; + hasOptions.status = status; + if (status) { + status.op = 'has'; + status.key = k; + status.cache = this; + } + const result = this.#has(k, hasOptions); + if (metrics.hasSubscribers) + metrics.publish(status); + return result; + } + #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 { status = hasSubscribers() ? {} : undefined } = peekOptions; + if (status) { + status.op = 'peek'; + status.key = k; + status.cache = this; + } + peekOptions.status = status; + const result = this.#peek(k, peekOptions); + if (metrics.hasSubscribers) { + metrics.publish(status); + } + return result; + } + #peek(k, peekOptions) { + const { status, allowStale = this.allowStale } = peekOptions; + const index = this.#keyMap.get(k); + if (index === undefined || (!allowStale && this.#isStale(index))) { + if (status) + status.peek = index === undefined ? 'miss' : 'stale'; + return undefined; + } + const v = this.#valList[index]; + const val = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + if (status) { + if (val !== undefined) { + status.peek = 'hit'; + status.value = val; + } + else { + status.peek = 'miss'; + } + } + return val; + } + #backgroundFetch(k, index, options, context) { + const v = index === undefined ? undefined : this.#valList[index]; + if (this.#isBackgroundFetch(v)) { + return v; + } + const ac = new AbortController(); + 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; + const proceed = options.ignoreFetchAbort || + !!(options.allowStaleOnFetchAbort && 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, proceed); + } + // either we didn't abort, and are still here, or we did, and ignored + const bf = p; + // if nothing else has been written there but we're set to update the + // cache and ignore the abort, or if it's still pending on this specific + // background request, then write it to the cache. + const vl = this.#valList[index]; + if (vl === p || (vl === undefined && ignoreAbort && updateCache)) { + if (v === undefined) { + if (bf.__staleWhileFetching !== undefined) { + this.#valList[index] = bf.__staleWhileFetching; + } + else { + this.#delete(k, 'fetch'); + } + } + else { + if (options.status) + options.status.fetchUpdated = true; + this.#set(k, v, fetchOpts.options, bf); + } + } + return v; + }; + const eb = (er) => { + if (options.status) { + options.status.fetchRejected = true; + options.status.fetchError = er; + } + // do not pass go, do not collect $200 + return fetchFail(er, false); + }; + const fetchFail = (er, proceed) => { + 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 || (!proceed && 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); + // 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 (fmp && fmp instanceof Promise) { + fmp.then(v => res(v === undefined ? undefined : v), rej); + } + else if (fmp !== undefined) { + res(fmp); + } + }; + 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 { + // do not call #set, because we do not want to adjust its place + // in the lru queue, as it has not yet been "used". Also, we don't + // need to worry about evicting for size, because a background fetch + // over a stale value is treated as the same size as its stale value. + 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 AbortController); + } + fetch(k, fetchOptions = {}) { + const ths = tracing.hasSubscribers; + const { status = hasSubscribers() ? {} : undefined } = fetchOptions; + fetchOptions.status = status; + if (status && fetchOptions.context) { + status.context = fetchOptions.context; + } + const p = this.#fetch(k, fetchOptions); + if (status && ths) { + status.trace = true; + tracing.tracePromise(() => p, status).catch(() => { }); + } + return p; + } + 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 (status) { + status.op = 'fetch'; + status.key = k; + if (forceRefresh) + status.forceRefresh = true; + status.cache = this; + } + 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); + } + } + forceFetch(k, fetchOptions = {}) { + const ths = tracing.hasSubscribers; + const { status = hasSubscribers() ? {} : undefined } = fetchOptions; + fetchOptions.status = status; + if (status && fetchOptions.context) { + status.context = fetchOptions.context; + } + const p = this.#forceFetch(k, fetchOptions); + if (status && ths) { + status.trace = true; + tracing.tracePromise(() => p, status).catch(() => { }); + } + return 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 { status = metrics.hasSubscribers ? {} : undefined } = memoOptions; + memoOptions.status = status; + if (status) { + status.op = 'memo'; + status.key = k; + if (memoOptions.context) { + status.context = memoOptions.context; + } + status.cache = this; + } + const result = this.#memo(k, memoOptions); + if (status) + status.value = result; + if (metrics.hasSubscribers) + metrics.publish(status); + return result; + } + #memo(k, memoOptions = {}) { + const memoMethod = this.#memoMethod; + if (!memoMethod) { + throw new Error('no memoMethod provided to constructor'); + } + const { context, status, forceRefresh, ...options } = memoOptions; + if (status && forceRefresh) + status.forceRefresh = true; + const v = this.#get(k, options); + const refresh = forceRefresh || v === undefined; + if (status) { + status.memo = refresh ? 'miss' : 'hit'; + if (!refresh) + status.value = v; + } + if (!refresh) + return v; + const vv = memoMethod(k, v, { + options, + context, + }); + if (status) + status.value = vv; + 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 { status = metrics.hasSubscribers ? {} : undefined } = getOptions; + getOptions.status = status; + if (status) { + status.op = 'get'; + status.key = k; + status.cache = this; + } + const result = this.#get(k, getOptions); + if (status) { + if (result !== undefined) + status.value = result; + if (metrics.hasSubscribers) + metrics.publish(status); + } + return result; + } + #get(k, getOptions = {}) { + const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; + const index = this.#keyMap.get(k); + if (index === undefined) { + if (status) + status.get = 'miss'; + return undefined; + } + const value = this.#valList[index]; + const fetching = this.#isBackgroundFetch(value); + if (status) + this.#statusTTL(status, index); + if (this.#isStale(index)) { + // delete only if not an in-flight background fetch + if (!fetching) { + if (!noDeleteOnStaleGet) { + this.#delete(k, 'expire'); + } + if (status) + status.get = 'stale'; + if (allowStale) { + if (status) + status.returnedStale = true; + return value; + } + return undefined; + } + if (status) + status.get = 'stale-fetching'; + if (allowStale && value.__staleWhileFetching !== undefined) { + if (status) + status.returnedStale = true; + return value.__staleWhileFetching; + } + return undefined; + } + // not stale + if (status) + status.get = fetching ? 'fetching' : '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. + this.#moveToTail(index); + if (updateAgeOnGet) { + this.#updateItemAge(index); + } + return fetching ? value.__staleWhileFetching : value; + } + #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) { + if (metrics.hasSubscribers) { + metrics.publish({ + op: 'delete', + delete: reason, + key: k, + cache: this, + }); + } + let deleted = false; + if (this.#size !== 0) { + const index = this.#keyMap.get(k); + if (index !== undefined) { + if (this.#autopurgeTimers?.[index]) { + clearTimeout(this.#autopurgeTimers?.[index]); + this.#autopurgeTimers[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(); + void this.#valList.fill(undefined); + this.#keyList.fill(undefined); + if (this.#ttls && this.#starts) { + this.#ttls.fill(0); + this.#starts.fill(0); + for (const t of this.#autopurgeTimers ?? []) { + if (t !== undefined) + clearTimeout(t); + } + this.#autopurgeTimers?.fill(undefined); + } + 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.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/esm/browser/index.min.js b/node_modules/lru-cache/dist/esm/browser/index.min.js new file mode 100644 index 0000000000000..86618ad212c13 --- /dev/null +++ b/node_modules/lru-cache/dist/esm/browser/index.min.js @@ -0,0 +1,2 @@ +var L={hasSubscribers:!1},S=L,W=L;var M=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date;var D=()=>S.hasSubscribers||W.hasSubscribers,j=new Set,I=typeof process=="object"&&process?process:{},P=(u,e,t,i)=>{typeof I.emitWarning=="function"?I.emitWarning(u,e,t,i):console.error(`[${t}] ${e}: ${u}`)},k=u=>!j.has(u);var T=u=>!!u&&u===Math.floor(u)&&u>0&&isFinite(u),G=u=>T(u)?u<=Math.pow(2,8)?Uint8Array:u<=Math.pow(2,16)?Uint16Array:u<=Math.pow(2,32)?Uint32Array:u<=Number.MAX_SAFE_INTEGER?O:null:null,O=class extends Array{constructor(e){super(e),this.fill(0)}},R=class u{heap;length;static#o=!1;static create(e){let t=G(e);if(!t)return[];u.#o=!0;let i=new u(e,t);return u.#o=!1,i}constructor(e,t){if(!u.#o)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},U=class u{#o;#c;#S;#O;#w;#M;#I;#m;get perf(){return this.#m}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#n;#b;#s;#i;#t;#l;#u;#a;#h;#y;#r;#_;#F;#d;#g;#T;#U;#f;#x;static unsafeExposeInternals(e){return{starts:e.#F,ttls:e.#d,autopurgeTimers:e.#g,sizes:e.#_,keyMap:e.#s,keyList:e.#i,valList:e.#t,next:e.#l,prev:e.#u,get head(){return e.#a},get tail(){return e.#h},free:e.#y,isBackgroundFetch:t=>e.#e(t),backgroundFetch:(t,i,s,n)=>e.#P(t,i,s,n),moveToTail:t=>e.#L(t),indexes:t=>e.#A(t),rindexes:t=>e.#z(t),isStale:t=>e.#p(t)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#b}get size(){return this.#n}get fetchMethod(){return this.#M}get memoMethod(){return this.#I}get dispose(){return this.#S}get onInsert(){return this.#O}get disposeAfter(){return this.#w}constructor(e){let{max:t=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:r,updateAgeOnHas:h,allowStale:a,dispose:o,onInsert:d,disposeAfter:y,noDisposeOnSet:_,noUpdateTTL:c,maxSize:g=0,maxEntrySize:f=0,sizeCalculation:b,fetchMethod:l,memoMethod:w,noDeleteOnFetchRejection:F,noDeleteOnStaleGet:m,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:A,ignoreFetchAbort:z,backgroundFetchSize:C=1,perf:E}=e;if(this.backgroundFetchSize=C,E!==void 0&&typeof E?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#m=E??M,t!==0&&!T(t))throw new TypeError("max option must be a nonnegative integer");let v=t?G(t):Array;if(!v)throw new Error("invalid max value: "+t);if(this.#o=t,this.#c=g,this.maxEntrySize=f||this.#c,this.sizeCalculation=b,this.sizeCalculation){if(!this.#c&&!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(w!==void 0&&typeof w!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#I=w,l!==void 0&&typeof l!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#M=l,this.#U=!!l,this.#s=new Map,this.#i=Array.from({length:t}).fill(void 0),this.#t=Array.from({length:t}).fill(void 0),this.#l=new v(t),this.#u=new v(t),this.#a=0,this.#h=0,this.#y=R.create(t),this.#n=0,this.#b=0,typeof o=="function"&&(this.#S=o),typeof d=="function"&&(this.#O=d),typeof y=="function"?(this.#w=y,this.#r=[]):(this.#w=void 0,this.#r=void 0),this.#T=!!this.#S,this.#x=!!this.#O,this.#f=!!this.#w,this.noDisposeOnSet=!!_,this.noUpdateTTL=!!c,this.noDeleteOnFetchRejection=!!F,this.allowStaleOnFetchRejection=!!p,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.#c!==0&&!T(this.#c))throw new TypeError("maxSize must be a positive integer if specified");if(!T(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#X()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!m,this.updateAgeOnGet=!!r,this.updateAgeOnHas=!!h,this.ttlResolution=T(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!T(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#k()}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let x="LRU_CACHE_UNBOUNDED";k(x)&&(j.add(x),P("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",x,u))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#k(){let e=new O(this.#o),t=new O(this.#o);this.#d=e,this.#F=t;let i=this.ttlAutopurge?Array.from({length:this.#o}):void 0;this.#g=i,this.#H=(h,a,o=this.#m.now())=>{t[h]=a!==0?o:0,e[h]=a,s(h,a)},this.#D=h=>{t[h]=e[h]!==0?this.#m.now():0,s(h,e[h])};let s=this.ttlAutopurge?(h,a)=>{if(i?.[h]&&(clearTimeout(i[h]),i[h]=void 0),a&&a!==0&&i){let o=setTimeout(()=>{this.#p(h)&&this.#E(this.#i[h],"expire")},a+1);o.unref&&o.unref(),i[h]=o}}:()=>{};this.#v=(h,a)=>{if(e[a]){let o=e[a],d=t[a];if(!o||!d)return;h.ttl=o,h.start=d,h.now=n||r();let y=h.now-d;h.remainingTTL=o-y}};let n=0,r=()=>{let h=this.#m.now();if(this.ttlResolution>0){n=h;let a=setTimeout(()=>n=0,this.ttlResolution);a.unref&&a.unref()}return h};this.getRemainingTTL=h=>{let a=this.#s.get(h);if(a===void 0)return 0;let o=e[a],d=t[a];if(!o||!d)return 1/0;let y=(n||r())-d;return o-y},this.#p=h=>{let a=t[h],o=e[h];return!!o&&!!a&&(n||r())-a>o}}#D=()=>{};#v=()=>{};#H=()=>{};#p=()=>!1;#X(){let e=new O(this.#o);this.#b=0,this.#_=e,this.#R=t=>{this.#b-=e[t],e[t]=0},this.#N=(t,i,s,n)=>{if(!T(s)){if(this.#e(i))return this.backgroundFetchSize;if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,t),!T(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.#j=(t,i,s)=>{if(e[t]=i,this.#c){let n=this.#c-e[t];for(;this.#b>n;)this.#G(!0)}this.#b+=e[t],s&&(s.entrySize=i,s.totalCalculatedSize=this.#b)}}#R=e=>{};#j=(e,t,i)=>{};#N=(e,t,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:e=this.allowStale}={}){if(this.#n)for(let t=this.#h;this.#V(t)&&((e||!this.#p(t))&&(yield t),t!==this.#a);)t=this.#u[t]}*#z({allowStale:e=this.allowStale}={}){if(this.#n)for(let t=this.#a;this.#V(t)&&((e||!this.#p(t))&&(yield t),t!==this.#h);)t=this.#l[t]}#V(e){return e!==void 0&&this.#s.get(this.#i[e])===e}*entries(){for(let e of this.#A())this.#t[e]!==void 0&&this.#i[e]!==void 0&&!this.#e(this.#t[e])&&(yield[this.#i[e],this.#t[e]])}*rentries(){for(let e of this.#z())this.#t[e]!==void 0&&this.#i[e]!==void 0&&!this.#e(this.#t[e])&&(yield[this.#i[e],this.#t[e]])}*keys(){for(let e of this.#A()){let t=this.#i[e];t!==void 0&&!this.#e(this.#t[e])&&(yield t)}}*rkeys(){for(let e of this.#z()){let t=this.#i[e];t!==void 0&&!this.#e(this.#t[e])&&(yield t)}}*values(){for(let e of this.#A())this.#t[e]!==void 0&&!this.#e(this.#t[e])&&(yield this.#t[e])}*rvalues(){for(let e of this.#z())this.#t[e]!==void 0&&!this.#e(this.#t[e])&&(yield this.#t[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;if(n!==void 0&&e(n,this.#i[i],this))return this.#C(this.#i[i],t)}}forEach(e,t=this){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&e.call(t,n,this.#i[i],this)}}rforEach(e,t=this){for(let i of this.#z()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&e.call(t,n,this.#i[i],this)}}purgeStale(){let e=!1;for(let t of this.#z({allowStale:!0}))this.#p(t)&&(this.#E(this.#i[t],"expire"),e=!0);return e}info(e){let t=this.#s.get(e);if(t===void 0)return;let i=this.#t[t],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let n={value:s};if(this.#d&&this.#F){let r=this.#d[t],h=this.#F[t];if(r&&h){let a=r-(this.#m.now()-h);n.ttl=a,n.start=Date.now()}}return this.#_&&(n.size=this.#_[t]),n}dump(){let e=[];for(let t of this.#A({allowStale:!0})){let i=this.#i[t],s=this.#t[t],n=this.#e(s)?s.__staleWhileFetching:s;if(n===void 0||i===void 0)continue;let r={value:n};if(this.#d&&this.#F){r.ttl=this.#d[t];let h=this.#m.now()-this.#F[t];r.start=Math.floor(Date.now()-h)}this.#_&&(r.size=this.#_[t]),e.unshift([i,r])}return e}load(e){this.clear();for(let[t,i]of e){if(i.start){let s=Date.now()-i.start;i.start=this.#m.now()-s}this.#W(t,i.value,i)}}set(e,t,i={}){let{status:s=S.hasSubscribers?{}:void 0}=i;i.status=s,s&&(s.op="set",s.key=e,t!==void 0&&(s.value=t),s.cache=this);let n=this.#W(e,t,i);return s&&S.hasSubscribers&&S.publish(s),n}#W(e,t,i,s){let{ttl:n=this.ttl,start:r,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:o}=i,d=this.#e(t);if(t===void 0)return o&&(o.set="deleted"),this.delete(e),this;let{noUpdateTTL:y=this.noUpdateTTL}=i;o&&!d&&(o.value=t);let _=this.#N(e,t,i.size||0,a,o);if(this.maxEntrySize&&_>this.maxEntrySize)return this.#E(e,"set"),o&&(o.set="miss",o.maxEntrySizeExceeded=!0),this;let c=this.#n===0?void 0:this.#s.get(e);if(c===void 0)c=this.#n===0?this.#h:this.#y.length!==0?this.#y.pop():this.#n===this.#o?this.#G(!1):this.#n,this.#i[c]=e,this.#t[c]=t,this.#s.set(e,c),this.#l[this.#h]=c,this.#u[c]=this.#h,this.#h=c,this.#n++,this.#j(c,_,o),o&&(o.set="add"),y=!1,this.#x&&!d&&this.#O?.(t,e,"add");else{this.#L(c);let g=this.#t[c];if(t!==g){if(!h)if(this.#e(g)){g!==s&&g.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=g;f!==void 0&&f!==t&&(this.#T&&this.#S?.(f,e,"set"),this.#f&&this.#r?.push([f,e,"set"]))}else this.#T&&this.#S?.(g,e,"set"),this.#f&&this.#r?.push([g,e,"set"]);if(this.#R(c),this.#j(c,_,o),this.#t[c]=t,!d){let f=g&&this.#e(g)?g.__staleWhileFetching:g,b=f===void 0?"add":t!==f?"replace":"update";o&&(o.set=b,f!==void 0&&(o.oldValue=f)),this.#x&&this.onInsert?.(t,e,b)}}else d||(o&&(o.set="update"),this.#x&&this.onInsert?.(t,e,"update"))}if(n!==0&&!this.#d&&this.#k(),this.#d&&(y||this.#H(c,n,r),o&&this.#v(o,c)),!h&&this.#f&&this.#r){let g=this.#r,f;for(;f=g?.shift();)this.#w?.(...f)}return this}pop(){try{for(;this.#n;){let e=this.#t[this.#a];if(this.#G(!0),this.#e(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#f&&this.#r){let e=this.#r,t;for(;t=e?.shift();)this.#w?.(...t)}}}#G(e){let t=this.#a,i=this.#i[t],s=this.#t[t],n=this.#e(s);n&&s.__abortController.abort(new Error("evicted"));let r=n?s.__staleWhileFetching:s;return(this.#T||this.#f)&&r!==void 0&&(this.#T&&this.#S?.(r,i,"evict"),this.#f&&this.#r?.push([r,i,"evict"])),this.#R(t),this.#g?.[t]&&(clearTimeout(this.#g[t]),this.#g[t]=void 0),e&&(this.#i[t]=void 0,this.#t[t]=void 0,this.#y.push(t)),this.#n===1?(this.#a=this.#h=0,this.#y.length=0):this.#a=this.#l[t],this.#s.delete(i),this.#n--,t}has(e,t={}){let{status:i=S.hasSubscribers?{}:void 0}=t;t.status=i,i&&(i.op="has",i.key=e,i.cache=this);let s=this.#Y(e,t);return S.hasSubscribers&&S.publish(i),s}#Y(e,t={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=t,n=this.#s.get(e);if(n!==void 0){let r=this.#t[n];if(this.#e(r)&&r.__staleWhileFetching===void 0)return!1;if(this.#p(n))s&&(s.has="stale",this.#v(s,n));else return i&&this.#D(n),s&&(s.has="hit",this.#v(s,n)),!0}else s&&(s.has="miss");return!1}peek(e,t={}){let{status:i=D()?{}:void 0}=t;i&&(i.op="peek",i.key=e,i.cache=this),t.status=i;let s=this.#J(e,t);return S.hasSubscribers&&S.publish(i),s}#J(e,t){let{status:i,allowStale:s=this.allowStale}=t,n=this.#s.get(e);if(n===void 0||!s&&this.#p(n)){i&&(i.peek=n===void 0?"miss":"stale");return}let r=this.#t[n],h=this.#e(r)?r.__staleWhileFetching:r;return i&&(h!==void 0?(i.peek="hit",i.value=h):i.peek="miss"),h}#P(e,t,i,s){let n=t===void 0?void 0:this.#t[t];if(this.#e(n))return n;let r=new AbortController,{signal:h}=i;h?.addEventListener("abort",()=>r.abort(h.reason),{signal:r.signal});let a={signal:r.signal,options:i,context:s},o=(f,b=!1)=>{let{aborted:l}=r.signal,w=i.ignoreFetchAbort&&f!==void 0,F=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&f!==void 0);if(i.status&&(l&&!b?(i.status.fetchAborted=!0,i.status.fetchError=r.signal.reason,w&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),l&&!w&&!b)return y(r.signal.reason,F);let m=c,p=this.#t[t];return(p===c||p===void 0&&w&&b)&&(f===void 0?m.__staleWhileFetching!==void 0?this.#t[t]=m.__staleWhileFetching:this.#E(e,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.#W(e,f,a.options,m))),f},d=f=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=f),y(f,!1)),y=(f,b)=>{let{aborted:l}=r.signal,w=l&&i.allowStaleOnFetchAbort,F=w||i.allowStaleOnFetchRejection,m=F||i.noDeleteOnFetchRejection,p=c;if(this.#t[t]===c&&(!m||!b&&p.__staleWhileFetching===void 0?this.#E(e,"fetch"):w||(this.#t[t]=p.__staleWhileFetching)),F)return i.status&&p.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),p.__staleWhileFetching;if(p.__returned===p)throw f},_=(f,b)=>{let l=this.#M?.(e,n,a);r.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(f(void 0),i.allowStaleOnFetchAbort&&(f=w=>o(w,!0)))}),l&&l instanceof Promise?l.then(w=>f(w===void 0?void 0:w),b):l!==void 0&&f(l)};i.status&&(i.status.fetchDispatched=!0);let c=new Promise(_).then(o,d),g=Object.assign(c,{__abortController:r,__staleWhileFetching:n,__returned:void 0});return t===void 0?(this.#W(e,g,{...a.options,status:void 0}),t=this.#s.get(e)):this.#t[t]=g,g}#e(e){if(!this.#U)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof AbortController}fetch(e,t={}){let i=W.hasSubscribers,{status:s=D()?{}:void 0}=t;t.status=s,s&&t.context&&(s.context=t.context);let n=this.#B(e,t);return s&&i&&(s.trace=!0,W.tracePromise(()=>n,s).catch(()=>{})),n}async#B(e,t={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:r=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:a=0,sizeCalculation:o=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:y=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:_=this.allowStaleOnFetchRejection,ignoreFetchAbort:c=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:f,forceRefresh:b=!1,status:l,signal:w}=t;if(l&&(l.op="fetch",l.key=e,b&&(l.forceRefresh=!0),l.cache=this),!this.#U)return l&&(l.fetch="get"),this.#C(e,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:l});let F={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:r,noDisposeOnSet:h,size:a,sizeCalculation:o,noUpdateTTL:d,noDeleteOnFetchRejection:y,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:g,ignoreFetchAbort:c,status:l,signal:w},m=this.#s.get(e);if(m===void 0){l&&(l.fetch="miss");let p=this.#P(e,m,F,f);return p.__returned=p}else{let p=this.#t[m];if(this.#e(p)){let v=i&&p.__staleWhileFetching!==void 0;return l&&(l.fetch="inflight",v&&(l.returnedStale=!0)),v?p.__staleWhileFetching:p.__returned=p}let A=this.#p(m);if(!b&&!A)return l&&(l.fetch="hit"),this.#L(m),s&&this.#D(m),l&&this.#v(l,m),p;let z=this.#P(e,m,F,f),E=z.__staleWhileFetching!==void 0&&i;return l&&(l.fetch=A?"stale":"refresh",E&&A&&(l.returnedStale=!0)),E?z.__staleWhileFetching:z.__returned=z}}forceFetch(e,t={}){let i=W.hasSubscribers,{status:s=D()?{}:void 0}=t;t.status=s,s&&t.context&&(s.context=t.context);let n=this.#K(e,t);return s&&i&&(s.trace=!0,W.tracePromise(()=>n,s).catch(()=>{})),n}async#K(e,t={}){let i=await this.#B(e,t);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(e,t={}){let{status:i=S.hasSubscribers?{}:void 0}=t;t.status=i,i&&(i.op="memo",i.key=e,t.context&&(i.context=t.context),i.cache=this);let s=this.#Q(e,t);return i&&(i.value=s),S.hasSubscribers&&S.publish(i),s}#Q(e,t={}){let i=this.#I;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,status:n,forceRefresh:r,...h}=t;n&&r&&(n.forceRefresh=!0);let a=this.#C(e,h),o=r||a===void 0;if(n&&(n.memo=o?"miss":"hit",o||(n.value=a)),!o)return a;let d=i(e,a,{options:h,context:s});return n&&(n.value=d),this.#W(e,d,h),d}get(e,t={}){let{status:i=S.hasSubscribers?{}:void 0}=t;t.status=i,i&&(i.op="get",i.key=e,i.cache=this);let s=this.#C(e,t);return i&&(s!==void 0&&(i.value=s),S.hasSubscribers&&S.publish(i)),s}#C(e,t={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:r}=t,h=this.#s.get(e);if(h===void 0){r&&(r.get="miss");return}let a=this.#t[h],o=this.#e(a);return r&&this.#v(r,h),this.#p(h)?o?(r&&(r.get="stale-fetching"),i&&a.__staleWhileFetching!==void 0?(r&&(r.returnedStale=!0),a.__staleWhileFetching):void 0):(n||this.#E(e,"expire"),r&&(r.get="stale"),i?(r&&(r.returnedStale=!0),a):void 0):(r&&(r.get=o?"fetching":"hit"),this.#L(h),s&&this.#D(h),o?a.__staleWhileFetching:a)}#$(e,t){this.#u[t]=e,this.#l[e]=t}#L(e){e!==this.#h&&(e===this.#a?this.#a=this.#l[e]:this.#$(this.#u[e],this.#l[e]),this.#$(this.#h,e),this.#h=e)}delete(e){return this.#E(e,"delete")}#E(e,t){S.hasSubscribers&&S.publish({op:"delete",delete:t,key:e,cache:this});let i=!1;if(this.#n!==0){let s=this.#s.get(e);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g?.[s]),this.#g[s]=void 0),i=!0,this.#n===1)this.#q(t);else{this.#R(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#T||this.#f)&&(this.#T&&this.#S?.(n,e,t),this.#f&&this.#r?.push([n,e,t])),this.#s.delete(e),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#u[s];else if(s===this.#a)this.#a=this.#l[s];else{let r=this.#u[s];this.#l[r]=this.#l[s];let h=this.#l[s];this.#u[h]=this.#u[s]}this.#n--,this.#y.push(s)}}if(this.#f&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#w?.(...n)}return i}clear(){return this.#q("delete")}#q(e){for(let t of this.#z({allowStale:!0})){let i=this.#t[t];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[t];this.#T&&this.#S?.(i,s,e),this.#f&&this.#r?.push([i,s,e])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#F){this.#d.fill(0),this.#F.fill(0);for(let t of this.#g??[])t!==void 0&&clearTimeout(t);this.#g?.fill(void 0)}if(this.#_&&this.#_.fill(0),this.#a=0,this.#h=0,this.#y.length=0,this.#b=0,this.#n=0,this.#f&&this.#r){let t=this.#r,i;for(;i=t?.shift();)this.#w?.(...i)}}};export{U as LRUCache}; +//# sourceMappingURL=index.min.js.map diff --git a/node_modules/lru-cache/dist/esm/browser/perf.js b/node_modules/lru-cache/dist/esm/browser/perf.js new file mode 100644 index 0000000000000..f21cd88c8692d --- /dev/null +++ b/node_modules/lru-cache/dist/esm/browser/perf.js @@ -0,0 +1,7 @@ +export const defaultPerf = (typeof performance === 'object' && + performance && + typeof performance.now === 'function') ? + /* c8 ignore start - this gets covered, but c8 gets confused */ + performance + : /* c8 ignore stop */ Date; +//# sourceMappingURL=perf.js.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/esm/diagnostics-channel.js b/node_modules/lru-cache/dist/esm/diagnostics-channel.js new file mode 100644 index 0000000000000..76d86f8125aaa --- /dev/null +++ b/node_modules/lru-cache/dist/esm/diagnostics-channel.js @@ -0,0 +1,19 @@ +/** + * no-op polyfills for non-node environments. tries to load the actual + * diagnostics_channel module on platforms that support it, but fails + * gracefully if not found. This means that the first tick of metrics + * and tracing will be missed, but that probably doesn't matter much. + */ +// conditionally import from diagnostic_channel, fall back to dummyfill +// all we actually have to mock is the hasSubscribers, since we always check +/* v8 ignore next */ +const dummy = { hasSubscribers: false }; +export let metrics = dummy; +export let tracing = dummy; +import('node:diagnostics_channel') + .then(dc => { + metrics = dc.channel('lru-cache:metrics'); + tracing = dc.tracingChannel('lru-cache'); +}) + .catch(() => { }); +//# sourceMappingURL=diagnostics-channel-esm.mjs.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/esm/index.js b/node_modules/lru-cache/dist/esm/index.js index 41f16cf1b6417..2dd10cf8f908f 100644 --- a/node_modules/lru-cache/dist/esm/index.js +++ b/node_modules/lru-cache/dist/esm/index.js @@ -1,73 +1,27 @@ /** * @module LRUCache */ -const perf = typeof performance === 'object' && - performance && - typeof performance.now === 'function' - ? performance - : Date; +import { metrics, tracing } from './diagnostics-channel.js'; +import { defaultPerf } from './perf.js'; +const hasSubscribers = () => metrics.hasSubscribers || tracing.hasSubscribers; const warned = new Set(); /* c8 ignore start */ -const PROCESS = (typeof process === 'object' && !!process ? process : {}); -/* c8 ignore start */ +const PROCESS = (typeof process === 'object' && !!process ? + process + : {}); +/* c8 ignore stop */ const emitWarning = (msg, type, code, fn) => { - typeof PROCESS.emitWarning === 'function' - ? PROCESS.emitWarning(msg, type, code, fn) - : console.error(`[${code}] ${type}: ${msg}`); + if (typeof PROCESS.emitWarning === 'function') { + PROCESS.emitWarning(msg, type, code, fn); + } + else { + //oxlint-disable-next-line no-console + 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 */ +const isPosInt = (n) => !!n && n === Math.floor(n) && n > 0 && isFinite(n); // 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, @@ -76,16 +30,12 @@ const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n); // 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 +/* c8 ignore start */ +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 { @@ -95,7 +45,9 @@ class ZeroArray extends Array { } } class Stack { + /* c8 ignore start - not sure why this is showing up uncovered?? */ heap; + /* c8 ignore stop */ length; // private constructor static #constructing = false; @@ -127,21 +79,34 @@ class Stack { /** * Default export, the thing you're using this module to get. * - * All properties from the options object (with the exception of - * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as - * normal public members. (`max` and `maxBase` are read-only getters.) - * Changing any of these will alter the defaults for subsequent method calls, - * but is otherwise safe. + * 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 { - // properties coming in from the options of these, only max and maxSize - // really *need* to be protected. The rest can be modified, as they just - // set defaults for various methods. + // options that cannot be changed without disaster #max; #maxSize; #dispose; + #onInsert; #disposeAfter; #fetchMethod; + #memoMethod; + #perf; + /** + * {@link LRUCache.OptionsBase.perf} + */ + get perf() { + return this.#perf; + } /** * {@link LRUCache.OptionsBase.ttl} */ @@ -202,6 +167,8 @@ export class LRUCache { * {@link LRUCache.OptionsBase.ignoreFetchAbort} */ ignoreFetchAbort; + /** {@link LRUCache.OptionsBase.backgroundFetchSize} */ + backgroundFetchSize; // computed properties #size; #calculatedSize; @@ -217,9 +184,11 @@ export class LRUCache { #sizes; #starts; #ttls; + #autopurgeTimers; #hasDispose; #hasFetchMethod; #hasDisposeAfter; + #hasOnInsert; /** * Do not call this method unless you need to inspect the * inner workings of the cache. If anything returned by this @@ -234,6 +203,7 @@ export class LRUCache { // properties starts: c.#starts, ttls: c.#ttls, + autopurgeTimers: c.#autopurgeTimers, sizes: c.#sizes, keyMap: c.#keyMap, keyList: c.#keyList, @@ -287,12 +257,21 @@ export class LRUCache { get fetchMethod() { return this.#fetchMethod; } + get memoMethod() { + return this.#memoMethod; + } /** * {@link LRUCache.OptionsBase.dispose} (read-only) */ get dispose() { return this.#dispose; } + /** + * {@link LRUCache.OptionsBase.onInsert} (read-only) + */ + get onInsert() { + return this.#onInsert; + } /** * {@link LRUCache.OptionsBase.disposeAfter} (read-only) */ @@ -300,7 +279,14 @@ export class LRUCache { 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, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options; + const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, onInsert, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, backgroundFetchSize = 1, perf, } = options; + this.backgroundFetchSize = backgroundFetchSize; + if (perf !== undefined) { + if (typeof perf?.now !== 'function') { + throw new TypeError('perf option must have a now() method if specified'); + } + } + this.#perf = perf ?? defaultPerf; if (max !== 0 && !isPosInt(max)) { throw new TypeError('max option must be a nonnegative integer'); } @@ -320,15 +306,18 @@ export class LRUCache { throw new TypeError('sizeCalculation set to non-function'); } } - if (fetchMethod !== undefined && - typeof fetchMethod !== '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.#keyList = Array.from({ length: max }).fill(undefined); + this.#valList = Array.from({ length: max }).fill(undefined); this.#next = new UintArray(max); this.#prev = new UintArray(max); this.#head = 0; @@ -339,6 +328,9 @@ export class LRUCache { if (typeof dispose === 'function') { this.#dispose = dispose; } + if (typeof onInsert === 'function') { + this.#onInsert = onInsert; + } if (typeof disposeAfter === 'function') { this.#disposeAfter = disposeAfter; this.#disposed = []; @@ -348,6 +340,7 @@ export class LRUCache { this.#disposed = undefined; } this.#hasDispose = !!this.#dispose; + this.#hasOnInsert = !!this.#onInsert; this.#hasDisposeAfter = !!this.#disposeAfter; this.noDisposeOnSet = !!noDisposeOnSet; this.noUpdateTTL = !!noUpdateTTL; @@ -372,9 +365,7 @@ export class LRUCache { this.updateAgeOnGet = !!updateAgeOnGet; this.updateAgeOnHas = !!updateAgeOnHas; this.ttlResolution = - isPosInt(ttlResolution) || ttlResolution === 0 - ? ttlResolution - : 1; + isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1; this.ttlAutopurge = !!ttlAutopurge; this.ttl = ttl || 0; if (this.ttl) { @@ -398,7 +389,8 @@ export class LRUCache { } } /** - * Return the remaining TTL time for a given entry key + * 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; @@ -408,33 +400,56 @@ export class LRUCache { const starts = new ZeroArray(this.#max); this.#ttls = ttls; this.#starts = starts; - this.#setItemTTL = (index, ttl, start = perf.now()) => { + const purgeTimers = this.ttlAutopurge ? + Array.from({ + length: this.#max, + }) + : undefined; + this.#autopurgeTimers = purgeTimers; + this.#setItemTTL = (index, ttl, start = this.#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]); - } - }, ttl + 1); - // unref() not supported on all platforms - /* c8 ignore start */ - if (t.unref) { - t.unref(); - } - /* c8 ignore stop */ - } + setPurgetTimer(index, ttl); }; this.#updateItemAge = index => { - starts[index] = ttls[index] !== 0 ? perf.now() : 0; + starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0; + setPurgetTimer(index, ttls[index]); }; + // clear out the purge timer if we're setting TTL to 0, and + // previously had a ttl purge timer running, so it doesn't + // fire unnecessarily. Don't need to do this if we're not doing + // autopurge. + const setPurgetTimer = !this.ttlAutopurge ? + () => { } + : (index, ttl) => { + if (purgeTimers?.[index]) { + clearTimeout(purgeTimers[index]); + purgeTimers[index] = undefined; + } + if (ttl && ttl !== 0 && purgeTimers) { + 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 */ + purgeTimers[index] = t; + } + }; this.#statusTTL = (status, index) => { if (ttls[index]) { const ttl = ttls[index]; const start = starts[index]; - /* c8 ignore next */ - if (!ttl || !start) + /* c8 ignore start */ + if (!ttl || !start) { return; + } + /* c8 ignore stop */ status.ttl = ttl; status.start = start; status.now = cachedNow || getNow(); @@ -446,7 +461,7 @@ export class LRUCache { // that costly call repeatedly. let cachedNow = 0; const getNow = () => { - const n = perf.now(); + const n = this.#perf.now(); if (this.ttlResolution > 0) { cachedNow = n; const t = setTimeout(() => (cachedNow = 0), this.ttlResolution); @@ -493,12 +508,15 @@ export class LRUCache { 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)) { + // provisionally accept background fetches. + // actual value size will be checked when they return. + if (this.#isBackgroundFetch(v)) { + // NB: this cannot occur if v.__staleWhileFetching is set, + // because in that case, it would take on the size of the + // existing entry that it temporarily replaces. + return this.backgroundFetchSize; + } if (sizeCalculation) { if (typeof sizeCalculation !== 'function') { throw new TypeError('sizeCalculation must be a function'); @@ -541,10 +559,7 @@ export class LRUCache { }; *#indexes({ allowStale = this.allowStale } = {}) { if (this.#size) { - for (let i = this.#tail; true;) { - if (!this.#isValidIndex(i)) { - break; - } + for (let i = this.#tail; this.#isValidIndex(i);) { if (allowStale || !this.#isStale(i)) { yield i; } @@ -559,10 +574,7 @@ export class LRUCache { } *#rindexes({ allowStale = this.allowStale } = {}) { if (this.#size) { - for (let i = this.#head; true;) { - if (!this.#isValidIndex(i)) { - break; - } + for (let i = this.#head; this.#isValidIndex(i);) { if (allowStale || !this.#isStale(i)) { yield i; } @@ -614,8 +626,7 @@ export class LRUCache { *keys() { for (const i of this.#indexes()) { const k = this.#keyList[i]; - if (k !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { + if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield k; } } @@ -629,8 +640,7 @@ export class LRUCache { *rkeys() { for (const i of this.#rindexes()) { const k = this.#keyList[i]; - if (k !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { + if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield k; } } @@ -642,8 +652,7 @@ export class LRUCache { *values() { for (const i of this.#indexes()) { const v = this.#valList[i]; - if (v !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { + if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield this.#valList[i]; } } @@ -657,8 +666,7 @@ export class LRUCache { *rvalues() { for (const i of this.#rindexes()) { const v = this.#valList[i]; - if (v !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { + if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield this.#valList[i]; } } @@ -671,39 +679,41 @@ export class LRUCache { 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. + * 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). + * 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; + 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); + 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). Does not update age or recenty of use. - * Does not iterate over stale values. + * 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; + const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; fn.call(thisp, value, this.#keyList[i], this); @@ -716,9 +726,7 @@ export class LRUCache { rforEach(fn, thisp = this) { for (const i of this.#rindexes()) { const v = this.#valList[i]; - const value = this.#isBackgroundFetch(v) - ? v.__staleWhileFetching - : v; + const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; fn.call(thisp, value, this.#keyList[i], this); @@ -732,7 +740,7 @@ export class LRUCache { let deleted = false; for (const i of this.#rindexes({ allowStale: true })) { if (this.#isStale(i)) { - this.delete(this.#keyList[i]); + this.#delete(this.#keyList[i], 'expire'); deleted = true; } } @@ -740,26 +748,33 @@ export class LRUCache { } /** * Get the extended info about a given entry, to get its value, size, and - * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a - * single key. Always returns stale values, if their info is found in the - * cache, so be sure to check for expired TTLs if relevant. + * 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; + /* c8 ignore start - this isn't tested for the info function, + * but it's the same logic as found in other places. */ + const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) return undefined; + /* c8 ignore stop */ 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); + const remain = ttl - (this.#perf.now() - start); entry.ttl = remain; entry.start = Date.now(); } @@ -771,16 +786,23 @@ export class LRUCache { } /** * Return an array of [key, {@link LRUCache.Entry}] tuples which can be - * passed to cache.load() + * passed to {@link LRUCache#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; + const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined || key === undefined) continue; const entry = { value }; @@ -788,7 +810,7 @@ export class LRUCache { 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]; + const age = this.#perf.now() - this.#starts[i]; entry.start = Math.floor(Date.now() - age); } if (this.#sizes) { @@ -800,8 +822,12 @@ export class LRUCache { } /** * Reset the cache and load in the items in entries in the order listed. - * Note that the shape of the resulting cache may be different if the - * same options are not used in both caches. + * + * 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(); @@ -814,9 +840,9 @@ export class LRUCache { // // 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; + entry.start = this.#perf.now() - age; } - this.set(key, entry.value, entry); + this.#set(key, entry.value, entry); } } /** @@ -824,35 +850,77 @@ export class LRUCache { * * 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 = {}) { + const { status = metrics.hasSubscribers ? {} : undefined } = setOptions; + setOptions.status = status; + if (status) { + status.op = 'set'; + status.key = k; + if (v !== undefined) + status.value = v; + status.cache = this; + } + const result = this.#set(k, v, setOptions); + if (status && metrics.hasSubscribers) { + metrics.publish(status); + } + return result; + } + #set(k, v, setOptions, bf) { + const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; + const isBF = this.#isBackgroundFetch(v); if (v === undefined) { + if (status) + status.set = 'deleted'; 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 (status && !isBF) + status.value = v; + const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation, status); // if the item doesn't fit, don't do anything // NB: maxEntrySize set to maxSize by default if (this.maxEntrySize && size > this.maxEntrySize) { + // have to delete, in case something is there already. + this.#delete(k, 'set'); if (status) { status.set = 'miss'; status.maxEntrySizeExceeded = true; } - // have to delete, in case something is there already. - this.delete(k); 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) + 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; @@ -865,46 +933,68 @@ export class LRUCache { if (status) status.set = 'add'; noUpdateTTL = false; + if (this.#hasOnInsert && !isBF) { + this.#onInsert?.(v, k, 'add'); + } } else { // update + // might be updating a background fetch! 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 (!noDisposeOnSet) { + if (this.#isBackgroundFetch(oldVal)) { + if (oldVal !== bf) { + // setting over a background fetch, not merely resolving it. + oldVal.__abortController.abort(new Error('replaced')); + } + const { __staleWhileFetching: s } = oldVal; + if (s !== undefined && s !== v) { + if (this.#hasDispose) { + this.#dispose?.(s, k, 'set'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([s, k, 'set']); + } + } + } + else { if (this.#hasDispose) { - this.#dispose?.(s, k, 'set'); + this.#dispose?.(oldVal, k, 'set'); } if (this.#hasDisposeAfter) { - this.#disposed?.push([s, k, 'set']); + this.#disposed?.push([oldVal, 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 + if (!isBF) { + const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? + oldVal.__staleWhileFetching : oldVal; - if (oldValue !== undefined) - status.oldValue = oldValue; + const setType = oldValue === undefined ? 'add' + : v !== oldValue ? 'replace' + : 'update'; + if (status) { + status.set = setType; + if (oldValue !== undefined) + status.oldValue = oldValue; + } + if (this.#hasOnInsert) { + this.onInsert?.(v, k, setType); + } } } - else if (status) { - status.set = 'update'; + else if (!isBF) { + if (status) { + status.set = 'update'; + } + if (this.#hasOnInsert) { + this.onInsert?.(v, k, 'update'); + } } } if (ttl !== 0 && !this.#ttls) { @@ -959,18 +1049,25 @@ export class LRUCache { const head = this.#head; const k = this.#keyList[head]; const v = this.#valList[head]; - if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) { + const isBF = this.#isBackgroundFetch(v); + if (isBF) { v.__abortController.abort(new Error('evicted')); } - else if (this.#hasDispose || this.#hasDisposeAfter) { + const oldValue = isBF ? v.__staleWhileFetching : v; + if ((this.#hasDispose || this.#hasDisposeAfter) && + oldValue !== undefined) { if (this.#hasDispose) { - this.#dispose?.(v, k, 'evict'); + this.#dispose?.(oldValue, k, 'evict'); } if (this.#hasDisposeAfter) { - this.#disposed?.push([v, k, 'evict']); + this.#disposed?.push([oldValue, k, 'evict']); } } this.#removeItemSize(head); + if (this.#autopurgeTimers?.[head]) { + clearTimeout(this.#autopurgeTimers[head]); + this.#autopurgeTimers[head] = undefined; + } // if we aren't about to use the index, then null these out if (free) { this.#keyList[head] = undefined; @@ -993,10 +1090,31 @@ export class LRUCache { * 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 { status = metrics.hasSubscribers ? {} : undefined } = hasOptions; + hasOptions.status = status; + if (status) { + status.op = 'has'; + status.key = k; + status.cache = this; + } + const result = this.#has(k, hasOptions); + if (metrics.hasSubscribers) + metrics.publish(status); + return result; + } + #has(k, hasOptions = {}) { const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions; const index = this.#keyMap.get(k); if (index !== undefined) { @@ -1033,22 +1151,46 @@ export class LRUCache { * {@link LRUCache.OptionsBase.allowStale} is set. */ peek(k, peekOptions = {}) { - const { allowStale = this.allowStale } = peekOptions; + const { status = hasSubscribers() ? {} : undefined } = peekOptions; + if (status) { + status.op = 'peek'; + status.key = k; + status.cache = this; + } + peekOptions.status = status; + const result = this.#peek(k, peekOptions); + if (metrics.hasSubscribers) { + metrics.publish(status); + } + return result; + } + #peek(k, peekOptions) { + const { status, allowStale = this.allowStale } = peekOptions; const index = this.#keyMap.get(k); - if (index === undefined || - (!allowStale && this.#isStale(index))) { - return; + if (index === undefined || (!allowStale && this.#isStale(index))) { + if (status) + status.peek = index === undefined ? 'miss' : 'stale'; + return undefined; } const v = this.#valList[index]; - // either stale and allowed, or forcing a refresh of non-stale value - return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + const val = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + if (status) { + if (val !== undefined) { + status.peek = 'hit'; + status.value = val; + } + else { + status.peek = 'miss'; + } + } + return val; } #backgroundFetch(k, index, options, context) { const v = index === undefined ? undefined : this.#valList[index]; if (this.#isBackgroundFetch(v)) { return v; } - const ac = new AC(); + const ac = new AbortController(); const { signal } = options; // when/if our AC signals, then stop listening to theirs. signal?.addEventListener('abort', () => ac.abort(signal.reason), { @@ -1062,6 +1204,8 @@ export class LRUCache { const cb = (v, updateCache = false) => { const { aborted } = ac.signal; const ignoreAbort = options.ignoreFetchAbort && v !== undefined; + const proceed = options.ignoreFetchAbort || + !!(options.allowStaleOnFetchAbort && v !== undefined); if (options.status) { if (aborted && !updateCache) { options.status.fetchAborted = true; @@ -1074,23 +1218,27 @@ export class LRUCache { } } if (aborted && !ignoreAbort && !updateCache) { - return fetchFail(ac.signal.reason); + return fetchFail(ac.signal.reason, proceed); } // either we didn't abort, and are still here, or we did, and ignored const bf = p; - if (this.#valList[index] === p) { + // if nothing else has been written there but we're set to update the + // cache and ignore the abort, or if it's still pending on this specific + // background request, then write it to the cache. + const vl = this.#valList[index]; + if (vl === p || (vl === undefined && ignoreAbort && updateCache)) { if (v === undefined) { - if (bf.__staleWhileFetching) { + if (bf.__staleWhileFetching !== undefined) { this.#valList[index] = bf.__staleWhileFetching; } else { - this.delete(k); + this.#delete(k, 'fetch'); } } else { if (options.status) options.status.fetchUpdated = true; - this.set(k, v, fetchOpts.options); + this.#set(k, v, fetchOpts.options, bf); } } return v; @@ -1100,9 +1248,10 @@ export class LRUCache { options.status.fetchRejected = true; options.status.fetchError = er; } - return fetchFail(er); + // do not pass go, do not collect $200 + return fetchFail(er, false); }; - const fetchFail = (er) => { + const fetchFail = (er, proceed) => { const { aborted } = ac.signal; const allowStaleAborted = aborted && options.allowStaleOnFetchAbort; const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection; @@ -1111,9 +1260,9 @@ export class LRUCache { 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; + const del = !noDelete || (!proceed && bf.__staleWhileFetching === undefined); if (del) { - this.delete(k); + this.#delete(k, 'fetch'); } else if (!allowStaleAborted) { // still replace the *promise* with the stale value, @@ -1135,15 +1284,11 @@ export class LRUCache { }; 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) { + if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) { res(undefined); // when it eventually resolves, update the cache. if (options.allowStaleOnFetchAbort) { @@ -1151,6 +1296,12 @@ export class LRUCache { } } }); + if (fmp && fmp instanceof Promise) { + fmp.then(v => res(v === undefined ? undefined : v), rej); + } + else if (fmp !== undefined) { + res(fmp); + } }; if (options.status) options.status.fetchDispatched = true; @@ -1162,10 +1313,14 @@ export class LRUCache { }); if (index === undefined) { // internal, don't expose status. - this.set(k, bf, { ...fetchOpts.options, status: undefined }); + this.#set(k, bf, { ...fetchOpts.options, status: undefined }); index = this.#keyMap.get(k); } else { + // do not call #set, because we do not want to adjust its place + // in the lru queue, as it has not yet been "used". Also, we don't + // need to worry about evicting for size, because a background fetch + // over a stale value is treated as the same size as its stale value. this.#valList[index] = bf; } return bf; @@ -1177,9 +1332,23 @@ export class LRUCache { return (!!b && b instanceof Promise && b.hasOwnProperty('__staleWhileFetching') && - b.__abortController instanceof AC); + b.__abortController instanceof AbortController); + } + fetch(k, fetchOptions = {}) { + const ths = tracing.hasSubscribers; + const { status = hasSubscribers() ? {} : undefined } = fetchOptions; + fetchOptions.status = status; + if (status && fetchOptions.context) { + status.context = fetchOptions.context; + } + const p = this.#fetch(k, fetchOptions); + if (status && ths) { + status.trace = true; + tracing.tracePromise(() => p, status).catch(() => { }); + } + return p; } - async fetch(k, fetchOptions = {}) { + async #fetch(k, fetchOptions = {}) { const { // get options allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, @@ -1187,10 +1356,17 @@ export class LRUCache { 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 (status) { + status.op = 'fetch'; + status.key = k; + if (forceRefresh) + status.forceRefresh = true; + status.cache = this; + } if (!this.#hasFetchMethod) { if (status) status.fetch = 'get'; - return this.get(k, { + return this.#get(k, { allowStale, updateAgeOnGet, noDeleteOnStaleGet, @@ -1259,6 +1435,70 @@ export class LRUCache { return staleVal ? p.__staleWhileFetching : (p.__returned = p); } } + forceFetch(k, fetchOptions = {}) { + const ths = tracing.hasSubscribers; + const { status = hasSubscribers() ? {} : undefined } = fetchOptions; + fetchOptions.status = status; + if (status && fetchOptions.context) { + status.context = fetchOptions.context; + } + const p = this.#forceFetch(k, fetchOptions); + if (status && ths) { + status.trace = true; + tracing.tracePromise(() => p, status).catch(() => { }); + } + return 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 { status = metrics.hasSubscribers ? {} : undefined } = memoOptions; + memoOptions.status = status; + if (status) { + status.op = 'memo'; + status.key = k; + if (memoOptions.context) { + status.context = memoOptions.context; + } + status.cache = this; + } + const result = this.#memo(k, memoOptions); + if (status) + status.value = result; + if (metrics.hasSubscribers) + metrics.publish(status); + return result; + } + #memo(k, memoOptions = {}) { + const memoMethod = this.#memoMethod; + if (!memoMethod) { + throw new Error('no memoMethod provided to constructor'); + } + const { context, status, forceRefresh, ...options } = memoOptions; + if (status && forceRefresh) + status.forceRefresh = true; + const v = this.#get(k, options); + const refresh = forceRefresh || v === undefined; + if (status) { + status.memo = refresh ? 'miss' : 'hit'; + if (!refresh) + status.value = v; + } + if (!refresh) + return v; + const vv = memoMethod(k, v, { + options, + context, + }); + if (status) + status.value = vv; + this.#set(k, vv, options); + return vv; + } /** * Return a value from the cache. Will update the recency of the cache * entry found. @@ -1266,55 +1506,71 @@ export class LRUCache { * If the key is not found, get() will return `undefined`. */ get(k, getOptions = {}) { + const { status = metrics.hasSubscribers ? {} : undefined } = getOptions; + getOptions.status = status; + if (status) { + status.op = 'get'; + status.key = k; + status.cache = this; + } + const result = this.#get(k, getOptions); + if (status) { + if (result !== undefined) + status.value = result; + if (metrics.hasSubscribers) + metrics.publish(status); + } + return result; + } + #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 (index === undefined) { if (status) - this.#statusTTL(status, index); - if (this.#isStale(index)) { + status.get = 'miss'; + return undefined; + } + const value = this.#valList[index]; + const fetching = this.#isBackgroundFetch(value); + if (status) + this.#statusTTL(status, index); + if (this.#isStale(index)) { + // delete only if not an in-flight background fetch + if (!fetching) { + if (!noDeleteOnStaleGet) { + this.#delete(k, 'expire'); + } if (status) status.get = 'stale'; - // delete only if not an in-flight background fetch - if (!fetching) { - if (!noDeleteOnStaleGet) { - this.delete(k); - } - if (status && allowStale) - status.returnedStale = true; - return allowStale ? value : undefined; - } - else { - if (status && - allowStale && - value.__staleWhileFetching !== undefined) { + if (allowStale) { + if (status) status.returnedStale = true; - } - return allowStale ? value.__staleWhileFetching : undefined; + return value; } + return undefined; } - else { + if (status) + status.get = 'stale-fetching'; + if (allowStale && value.__staleWhileFetching !== undefined) { 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; + status.returnedStale = true; + return value.__staleWhileFetching; } + return undefined; } - else if (status) { - status.get = 'miss'; - } + // not stale + if (status) + status.get = fetching ? 'fetching' : '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. + this.#moveToTail(index); + if (updateAgeOnGet) { + this.#updateItemAge(index); + } + return fetching ? value.__staleWhileFetching : value; } #connect(p, n) { this.#prev[n] = p; @@ -1342,16 +1598,32 @@ export class LRUCache { } /** * 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) { + if (metrics.hasSubscribers) { + metrics.publish({ + op: 'delete', + delete: reason, + key: k, + cache: this, + }); + } let deleted = false; if (this.#size !== 0) { const index = this.#keyMap.get(k); if (index !== undefined) { + if (this.#autopurgeTimers?.[index]) { + clearTimeout(this.#autopurgeTimers?.[index]); + this.#autopurgeTimers[index] = undefined; + } deleted = true; if (this.#size === 1) { - this.clear(); + this.#clear(reason); } else { this.#removeItemSize(index); @@ -1361,10 +1633,10 @@ export class LRUCache { } else if (this.#hasDispose || this.#hasDisposeAfter) { if (this.#hasDispose) { - this.#dispose?.(v, k, 'delete'); + this.#dispose?.(v, k, reason); } if (this.#hasDisposeAfter) { - this.#disposed?.push([v, k, 'delete']); + this.#disposed?.push([v, k, reason]); } } this.#keyMap.delete(k); @@ -1400,6 +1672,9 @@ export class LRUCache { * 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)) { @@ -1408,19 +1683,24 @@ export class LRUCache { else { const k = this.#keyList[index]; if (this.#hasDispose) { - this.#dispose?.(v, k, 'delete'); + this.#dispose?.(v, k, reason); } if (this.#hasDisposeAfter) { - this.#disposed?.push([v, k, 'delete']); + this.#disposed?.push([v, k, reason]); } } } this.#keyMap.clear(); - this.#valList.fill(undefined); + void this.#valList.fill(undefined); this.#keyList.fill(undefined); if (this.#ttls && this.#starts) { this.#ttls.fill(0); this.#starts.fill(0); + for (const t of this.#autopurgeTimers ?? []) { + if (t !== undefined) + clearTimeout(t); + } + this.#autopurgeTimers?.fill(undefined); } if (this.#sizes) { this.#sizes.fill(0); diff --git a/node_modules/lru-cache/dist/esm/index.min.js b/node_modules/lru-cache/dist/esm/index.min.js index 4285815f9abb1..5715ef55079b7 100644 --- a/node_modules/lru-cache/dist/esm/index.min.js +++ b/node_modules/lru-cache/dist/esm/index.min.js @@ -1,2 +1,2 @@ -var G=(o,t,e)=>{if(!t.has(o))throw TypeError("Cannot "+e)};var I=(o,t,e)=>(G(o,t,"read from private field"),e?e.call(o):t.get(o)),j=(o,t,e)=>{if(t.has(o))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(o):t.set(o,e)},D=(o,t,e,i)=>(G(o,t,"write to private field"),i?i.call(o,e):t.set(o,e),e);var O=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,M=new Set,L=typeof process=="object"&&process?process:{},P=(o,t,e,i)=>{typeof L.emitWarning=="function"?L.emitWarning(o,t,e,i):console.error(`[${e}] ${t}: ${o}`)},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 o=L.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{o&&(o=!1,P("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=o=>!M.has(o),Y=Symbol("type"),A=o=>o&&o===Math.floor(o)&&o>0&&isFinite(o),H=o=>A(o)?o<=Math.pow(2,8)?Uint8Array:o<=Math.pow(2,16)?Uint16Array:o<=Math.pow(2,32)?Uint32Array:o<=Number.MAX_SAFE_INTEGER?E:null:null,E=class extends Array{constructor(t){super(t),this.fill(0)}},v,z=class{heap;length;static create(t){let e=H(t);if(!e)return[];D(z,v,!0);let i=new z(t,e);return D(z,v,!1),i}constructor(t,e){if(!I(z,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]}},C=z;v=new WeakMap,j(C,v,!1);var R=class{#g;#f;#p;#w;#C;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;#y;#u;#m;#O;#a;static unsafeExposeInternals(t){return{starts:t.#y,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.#D(e,i,s,n),moveToTail:e=>t.#v(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.#C}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:l,allowStale:r,dispose:g,disposeAfter:b,noDisposeOnSet:f,noUpdateTTL:u,maxSize:c=0,maxEntrySize:F=0,sizeCalculation:d,fetchMethod:S,noDeleteOnFetchRejection:a,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:y,allowStaleOnFetchAbort:p,ignoreFetchAbort:_}=t;if(e!==0&&!A(e))throw new TypeError("max option must be a nonnegative integer");let T=e?H(e):Array;if(!T)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(S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#C=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 T(e),this.#c=new T(e),this.#o=0,this.#h=0,this.#_=C.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.#m=!!this.#p,this.#a=!!this.#w,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!a,this.allowStaleOnFetchRejection=!!y,this.allowStaleOnFetchAbort=!!p,this.ignoreFetchAbort=!!_,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.#j()}if(this.allowStale=!!r,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!h,this.updateAgeOnHas=!!l,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.#L()}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 m="LRU_CACHE_UNBOUNDED";V(m)&&(M.add(m),P("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",m,R))}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#L(){let t=new E(this.#g),e=new E(this.#g);this.#u=t,this.#y=e,this.#x=(n,h,l=O.now())=>{if(e[n]=h!==0?l:0,t[n]=h,h!==0&&this.ttlAutopurge){let r=setTimeout(()=>{this.#d(n)&&this.delete(this.#i[n])},h+1);r.unref&&r.unref()}},this.#z=n=>{e[n]=t[n]!==0?O.now():0},this.#T=(n,h)=>{if(t[h]){let l=t[h],r=e[h];if(!l||!r)return;n.ttl=l,n.start=r,n.now=i||s();let g=n.now-r;n.remainingTTL=l-g}};let i=0,s=()=>{let n=O.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 l=t[h],r=e[h];if(!l||!r)return 1/0;let g=(i||s())-r;return l-g},this.#d=n=>{let h=e[n],l=t[n];return!!l&&!!h&&(i||s())-h>l}}#z=()=>{};#T=()=>{};#x=()=>{};#d=()=>!1;#j(){let t=new E(this.#g);this.#S=0,this.#b=t,this.#E=e=>{this.#S-=t[e],t[e]=0},this.#U=(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.#W=(e,i,s)=>{if(t[e]=i,this.#f){let n=this.#f-t[e];for(;this.#S>n;)this.#R(!0)}this.#S+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#S)}}#E=t=>{};#W=(t,e,i)=>{};#U=(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.#G(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.#G(e)||((t||!this.#d(e))&&(yield e),e===this.#h));)e=this.#l[e]}#G(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.delete(this.#i[e]),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.#y){let h=this.#u[e],l=this.#y[e];if(h&&l){let r=h-(O.now()-l);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.#y){h.ttl=this.#u[e];let l=O.now()-this.#y[e];h.start=Math.floor(Date.now()-l)}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=O.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:l=this.sizeCalculation,status:r}=i,{noUpdateTTL:g=this.noUpdateTTL}=i,b=this.#U(t,e,i.size||0,l);if(this.maxEntrySize&&b>this.maxEntrySize)return r&&(r.set="miss",r.maxEntrySizeExceeded=!0),this.delete(t),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.#R(!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.#W(f,b,r),r&&(r.set="add"),g=!1;else{this.#v(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.#m&&this.#p?.(c,t,"set"),this.#a&&this.#r?.push([c,t,"set"]))}else h||(this.#m&&this.#p?.(u,t,"set"),this.#a&&this.#r?.push([u,t,"set"]));if(this.#E(f),this.#W(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.#L(),this.#u&&(g||this.#x(f,s,n),r&&this.#T(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.#R(!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)}}}#R(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.#m||this.#a)&&(this.#m&&this.#p?.(s,i,"evict"),this.#a&&this.#r?.push([s,i,"evict"])),this.#E(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.#T(s,n));else return i&&this.#z(n),s&&(s.has="hit",this.#T(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}#D(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:l}=i;l?.addEventListener("abort",()=>h.abort(l.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 y=c;return this.#t[e]===c&&(d===void 0?y.__staleWhileFetching?this.#t[e]=y.__staleWhileFetching:this.delete(t):(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,y=w||i.noDeleteOnFetchRejection,p=c;if(this.#t[e]===c&&(!y||p.__staleWhileFetching===void 0?this.delete(t):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.#C?.(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.#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:l=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.#O)return a&&(a.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:a});let y={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:h,noDisposeOnSet:l,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.#D(t,p,y,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 T=this.#d(p);if(!S&&!T)return a&&(a.fetch="hit"),this.#v(p),s&&this.#z(p),a&&this.#T(a,p),_;let m=this.#D(t,p,y,d),x=m.__staleWhileFetching!==void 0&&i;return a&&(a.fetch=T?"stale":"refresh",x&&T&&(a.returnedStale=!0)),x?m.__staleWhileFetching:m.__returned=m}}get(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:h}=e,l=this.#s.get(t);if(l!==void 0){let r=this.#t[l],g=this.#e(r);return h&&this.#T(h,l),this.#d(l)?(h&&(h.get="stale"),g?(h&&i&&r.__staleWhileFetching!==void 0&&(h.returnedStale=!0),i?r.__staleWhileFetching:void 0):(n||this.delete(t),h&&i&&(h.returnedStale=!0),i?r:void 0)):(h&&(h.get="hit"),g?r.__staleWhileFetching:(this.#v(l),s&&this.#z(l),r))}else h&&(h.get="miss")}#I(t,e){this.#c[e]=t,this.#l[t]=e}#v(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){let e=!1;if(this.#n!==0){let i=this.#s.get(t);if(i!==void 0)if(e=!0,this.#n===1)this.clear();else{this.#E(i);let s=this.#t[i];if(this.#e(s)?s.__abortController.abort(new Error("deleted")):(this.#m||this.#a)&&(this.#m&&this.#p?.(s,t,"delete"),this.#a&&this.#r?.push([s,t,"delete"])),this.#s.delete(t),this.#i[i]=void 0,this.#t[i]=void 0,i===this.#h)this.#h=this.#c[i];else if(i===this.#o)this.#o=this.#l[i];else{let n=this.#c[i];this.#l[n]=this.#l[i];let h=this.#l[i];this.#c[h]=this.#c[i]}this.#n--,this.#_.push(i)}}if(this.#a&&this.#r?.length){let i=this.#r,s;for(;s=i?.shift();)this.#w?.(...s)}return e}clear(){for(let t of this.#F({allowStale:!0})){let e=this.#t[t];if(this.#e(e))e.__abortController.abort(new Error("deleted"));else{let i=this.#i[t];this.#m&&this.#p?.(e,i,"delete"),this.#a&&this.#r?.push([e,i,"delete"])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#u&&this.#y&&(this.#u.fill(0),this.#y.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 t=this.#r,e;for(;e=t?.shift();)this.#w?.(...e)}}};export{R as LRUCache}; +var L={hasSubscribers:!1},S=L,A=L;import("node:diagnostics_channel").then(c=>{S=c.channel("lru-cache:metrics"),A=c.tracingChannel("lru-cache")}).catch(()=>{});var M=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date;var D=()=>S.hasSubscribers||A.hasSubscribers,j=new Set,I=typeof process=="object"&&process?process:{},P=(c,e,t,i)=>{typeof I.emitWarning=="function"?I.emitWarning(c,e,t,i):console.error(`[${t}] ${e}: ${c}`)},k=c=>!j.has(c);var T=c=>!!c&&c===Math.floor(c)&&c>0&&isFinite(c),G=c=>T(c)?c<=Math.pow(2,8)?Uint8Array:c<=Math.pow(2,16)?Uint16Array:c<=Math.pow(2,32)?Uint32Array:c<=Number.MAX_SAFE_INTEGER?O:null:null,O=class extends Array{constructor(e){super(e),this.fill(0)}},R=class c{heap;length;static#o=!1;static create(e){let t=G(e);if(!t)return[];c.#o=!0;let i=new c(e,t);return c.#o=!1,i}constructor(e,t){if(!c.#o)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},U=class c{#o;#c;#S;#O;#w;#M;#I;#m;get perf(){return this.#m}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#n;#b;#s;#i;#t;#l;#u;#a;#h;#y;#r;#_;#F;#d;#g;#T;#U;#f;#x;static unsafeExposeInternals(e){return{starts:e.#F,ttls:e.#d,autopurgeTimers:e.#g,sizes:e.#_,keyMap:e.#s,keyList:e.#i,valList:e.#t,next:e.#l,prev:e.#u,get head(){return e.#a},get tail(){return e.#h},free:e.#y,isBackgroundFetch:t=>e.#e(t),backgroundFetch:(t,i,s,n)=>e.#P(t,i,s,n),moveToTail:t=>e.#L(t),indexes:t=>e.#A(t),rindexes:t=>e.#z(t),isStale:t=>e.#p(t)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#b}get size(){return this.#n}get fetchMethod(){return this.#M}get memoMethod(){return this.#I}get dispose(){return this.#S}get onInsert(){return this.#O}get disposeAfter(){return this.#w}constructor(e){let{max:t=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:r,updateAgeOnHas:h,allowStale:a,dispose:o,onInsert:d,disposeAfter:y,noDisposeOnSet:_,noUpdateTTL:u,maxSize:g=0,maxEntrySize:f=0,sizeCalculation:b,fetchMethod:l,memoMethod:w,noDeleteOnFetchRejection:F,noDeleteOnStaleGet:m,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:z,ignoreFetchAbort:E,backgroundFetchSize:C=1,perf:v}=e;if(this.backgroundFetchSize=C,v!==void 0&&typeof v?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#m=v??M,t!==0&&!T(t))throw new TypeError("max option must be a nonnegative integer");let W=t?G(t):Array;if(!W)throw new Error("invalid max value: "+t);if(this.#o=t,this.#c=g,this.maxEntrySize=f||this.#c,this.sizeCalculation=b,this.sizeCalculation){if(!this.#c&&!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(w!==void 0&&typeof w!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#I=w,l!==void 0&&typeof l!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#M=l,this.#U=!!l,this.#s=new Map,this.#i=Array.from({length:t}).fill(void 0),this.#t=Array.from({length:t}).fill(void 0),this.#l=new W(t),this.#u=new W(t),this.#a=0,this.#h=0,this.#y=R.create(t),this.#n=0,this.#b=0,typeof o=="function"&&(this.#S=o),typeof d=="function"&&(this.#O=d),typeof y=="function"?(this.#w=y,this.#r=[]):(this.#w=void 0,this.#r=void 0),this.#T=!!this.#S,this.#x=!!this.#O,this.#f=!!this.#w,this.noDisposeOnSet=!!_,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!F,this.allowStaleOnFetchRejection=!!p,this.allowStaleOnFetchAbort=!!z,this.ignoreFetchAbort=!!E,this.maxEntrySize!==0){if(this.#c!==0&&!T(this.#c))throw new TypeError("maxSize must be a positive integer if specified");if(!T(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#X()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!m,this.updateAgeOnGet=!!r,this.updateAgeOnHas=!!h,this.ttlResolution=T(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!T(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#k()}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let x="LRU_CACHE_UNBOUNDED";k(x)&&(j.add(x),P("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",x,c))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#k(){let e=new O(this.#o),t=new O(this.#o);this.#d=e,this.#F=t;let i=this.ttlAutopurge?Array.from({length:this.#o}):void 0;this.#g=i,this.#H=(h,a,o=this.#m.now())=>{t[h]=a!==0?o:0,e[h]=a,s(h,a)},this.#D=h=>{t[h]=e[h]!==0?this.#m.now():0,s(h,e[h])};let s=this.ttlAutopurge?(h,a)=>{if(i?.[h]&&(clearTimeout(i[h]),i[h]=void 0),a&&a!==0&&i){let o=setTimeout(()=>{this.#p(h)&&this.#E(this.#i[h],"expire")},a+1);o.unref&&o.unref(),i[h]=o}}:()=>{};this.#v=(h,a)=>{if(e[a]){let o=e[a],d=t[a];if(!o||!d)return;h.ttl=o,h.start=d,h.now=n||r();let y=h.now-d;h.remainingTTL=o-y}};let n=0,r=()=>{let h=this.#m.now();if(this.ttlResolution>0){n=h;let a=setTimeout(()=>n=0,this.ttlResolution);a.unref&&a.unref()}return h};this.getRemainingTTL=h=>{let a=this.#s.get(h);if(a===void 0)return 0;let o=e[a],d=t[a];if(!o||!d)return 1/0;let y=(n||r())-d;return o-y},this.#p=h=>{let a=t[h],o=e[h];return!!o&&!!a&&(n||r())-a>o}}#D=()=>{};#v=()=>{};#H=()=>{};#p=()=>!1;#X(){let e=new O(this.#o);this.#b=0,this.#_=e,this.#R=t=>{this.#b-=e[t],e[t]=0},this.#N=(t,i,s,n)=>{if(!T(s)){if(this.#e(i))return this.backgroundFetchSize;if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,t),!T(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.#j=(t,i,s)=>{if(e[t]=i,this.#c){let n=this.#c-e[t];for(;this.#b>n;)this.#G(!0)}this.#b+=e[t],s&&(s.entrySize=i,s.totalCalculatedSize=this.#b)}}#R=e=>{};#j=(e,t,i)=>{};#N=(e,t,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:e=this.allowStale}={}){if(this.#n)for(let t=this.#h;this.#V(t)&&((e||!this.#p(t))&&(yield t),t!==this.#a);)t=this.#u[t]}*#z({allowStale:e=this.allowStale}={}){if(this.#n)for(let t=this.#a;this.#V(t)&&((e||!this.#p(t))&&(yield t),t!==this.#h);)t=this.#l[t]}#V(e){return e!==void 0&&this.#s.get(this.#i[e])===e}*entries(){for(let e of this.#A())this.#t[e]!==void 0&&this.#i[e]!==void 0&&!this.#e(this.#t[e])&&(yield[this.#i[e],this.#t[e]])}*rentries(){for(let e of this.#z())this.#t[e]!==void 0&&this.#i[e]!==void 0&&!this.#e(this.#t[e])&&(yield[this.#i[e],this.#t[e]])}*keys(){for(let e of this.#A()){let t=this.#i[e];t!==void 0&&!this.#e(this.#t[e])&&(yield t)}}*rkeys(){for(let e of this.#z()){let t=this.#i[e];t!==void 0&&!this.#e(this.#t[e])&&(yield t)}}*values(){for(let e of this.#A())this.#t[e]!==void 0&&!this.#e(this.#t[e])&&(yield this.#t[e])}*rvalues(){for(let e of this.#z())this.#t[e]!==void 0&&!this.#e(this.#t[e])&&(yield this.#t[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;if(n!==void 0&&e(n,this.#i[i],this))return this.#C(this.#i[i],t)}}forEach(e,t=this){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&e.call(t,n,this.#i[i],this)}}rforEach(e,t=this){for(let i of this.#z()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&e.call(t,n,this.#i[i],this)}}purgeStale(){let e=!1;for(let t of this.#z({allowStale:!0}))this.#p(t)&&(this.#E(this.#i[t],"expire"),e=!0);return e}info(e){let t=this.#s.get(e);if(t===void 0)return;let i=this.#t[t],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let n={value:s};if(this.#d&&this.#F){let r=this.#d[t],h=this.#F[t];if(r&&h){let a=r-(this.#m.now()-h);n.ttl=a,n.start=Date.now()}}return this.#_&&(n.size=this.#_[t]),n}dump(){let e=[];for(let t of this.#A({allowStale:!0})){let i=this.#i[t],s=this.#t[t],n=this.#e(s)?s.__staleWhileFetching:s;if(n===void 0||i===void 0)continue;let r={value:n};if(this.#d&&this.#F){r.ttl=this.#d[t];let h=this.#m.now()-this.#F[t];r.start=Math.floor(Date.now()-h)}this.#_&&(r.size=this.#_[t]),e.unshift([i,r])}return e}load(e){this.clear();for(let[t,i]of e){if(i.start){let s=Date.now()-i.start;i.start=this.#m.now()-s}this.#W(t,i.value,i)}}set(e,t,i={}){let{status:s=S.hasSubscribers?{}:void 0}=i;i.status=s,s&&(s.op="set",s.key=e,t!==void 0&&(s.value=t),s.cache=this);let n=this.#W(e,t,i);return s&&S.hasSubscribers&&S.publish(s),n}#W(e,t,i,s){let{ttl:n=this.ttl,start:r,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:o}=i,d=this.#e(t);if(t===void 0)return o&&(o.set="deleted"),this.delete(e),this;let{noUpdateTTL:y=this.noUpdateTTL}=i;o&&!d&&(o.value=t);let _=this.#N(e,t,i.size||0,a,o);if(this.maxEntrySize&&_>this.maxEntrySize)return this.#E(e,"set"),o&&(o.set="miss",o.maxEntrySizeExceeded=!0),this;let u=this.#n===0?void 0:this.#s.get(e);if(u===void 0)u=this.#n===0?this.#h:this.#y.length!==0?this.#y.pop():this.#n===this.#o?this.#G(!1):this.#n,this.#i[u]=e,this.#t[u]=t,this.#s.set(e,u),this.#l[this.#h]=u,this.#u[u]=this.#h,this.#h=u,this.#n++,this.#j(u,_,o),o&&(o.set="add"),y=!1,this.#x&&!d&&this.#O?.(t,e,"add");else{this.#L(u);let g=this.#t[u];if(t!==g){if(!h)if(this.#e(g)){g!==s&&g.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=g;f!==void 0&&f!==t&&(this.#T&&this.#S?.(f,e,"set"),this.#f&&this.#r?.push([f,e,"set"]))}else this.#T&&this.#S?.(g,e,"set"),this.#f&&this.#r?.push([g,e,"set"]);if(this.#R(u),this.#j(u,_,o),this.#t[u]=t,!d){let f=g&&this.#e(g)?g.__staleWhileFetching:g,b=f===void 0?"add":t!==f?"replace":"update";o&&(o.set=b,f!==void 0&&(o.oldValue=f)),this.#x&&this.onInsert?.(t,e,b)}}else d||(o&&(o.set="update"),this.#x&&this.onInsert?.(t,e,"update"))}if(n!==0&&!this.#d&&this.#k(),this.#d&&(y||this.#H(u,n,r),o&&this.#v(o,u)),!h&&this.#f&&this.#r){let g=this.#r,f;for(;f=g?.shift();)this.#w?.(...f)}return this}pop(){try{for(;this.#n;){let e=this.#t[this.#a];if(this.#G(!0),this.#e(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#f&&this.#r){let e=this.#r,t;for(;t=e?.shift();)this.#w?.(...t)}}}#G(e){let t=this.#a,i=this.#i[t],s=this.#t[t],n=this.#e(s);n&&s.__abortController.abort(new Error("evicted"));let r=n?s.__staleWhileFetching:s;return(this.#T||this.#f)&&r!==void 0&&(this.#T&&this.#S?.(r,i,"evict"),this.#f&&this.#r?.push([r,i,"evict"])),this.#R(t),this.#g?.[t]&&(clearTimeout(this.#g[t]),this.#g[t]=void 0),e&&(this.#i[t]=void 0,this.#t[t]=void 0,this.#y.push(t)),this.#n===1?(this.#a=this.#h=0,this.#y.length=0):this.#a=this.#l[t],this.#s.delete(i),this.#n--,t}has(e,t={}){let{status:i=S.hasSubscribers?{}:void 0}=t;t.status=i,i&&(i.op="has",i.key=e,i.cache=this);let s=this.#Y(e,t);return S.hasSubscribers&&S.publish(i),s}#Y(e,t={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=t,n=this.#s.get(e);if(n!==void 0){let r=this.#t[n];if(this.#e(r)&&r.__staleWhileFetching===void 0)return!1;if(this.#p(n))s&&(s.has="stale",this.#v(s,n));else return i&&this.#D(n),s&&(s.has="hit",this.#v(s,n)),!0}else s&&(s.has="miss");return!1}peek(e,t={}){let{status:i=D()?{}:void 0}=t;i&&(i.op="peek",i.key=e,i.cache=this),t.status=i;let s=this.#J(e,t);return S.hasSubscribers&&S.publish(i),s}#J(e,t){let{status:i,allowStale:s=this.allowStale}=t,n=this.#s.get(e);if(n===void 0||!s&&this.#p(n)){i&&(i.peek=n===void 0?"miss":"stale");return}let r=this.#t[n],h=this.#e(r)?r.__staleWhileFetching:r;return i&&(h!==void 0?(i.peek="hit",i.value=h):i.peek="miss"),h}#P(e,t,i,s){let n=t===void 0?void 0:this.#t[t];if(this.#e(n))return n;let r=new AbortController,{signal:h}=i;h?.addEventListener("abort",()=>r.abort(h.reason),{signal:r.signal});let a={signal:r.signal,options:i,context:s},o=(f,b=!1)=>{let{aborted:l}=r.signal,w=i.ignoreFetchAbort&&f!==void 0,F=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&f!==void 0);if(i.status&&(l&&!b?(i.status.fetchAborted=!0,i.status.fetchError=r.signal.reason,w&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),l&&!w&&!b)return y(r.signal.reason,F);let m=u,p=this.#t[t];return(p===u||p===void 0&&w&&b)&&(f===void 0?m.__staleWhileFetching!==void 0?this.#t[t]=m.__staleWhileFetching:this.#E(e,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.#W(e,f,a.options,m))),f},d=f=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=f),y(f,!1)),y=(f,b)=>{let{aborted:l}=r.signal,w=l&&i.allowStaleOnFetchAbort,F=w||i.allowStaleOnFetchRejection,m=F||i.noDeleteOnFetchRejection,p=u;if(this.#t[t]===u&&(!m||!b&&p.__staleWhileFetching===void 0?this.#E(e,"fetch"):w||(this.#t[t]=p.__staleWhileFetching)),F)return i.status&&p.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),p.__staleWhileFetching;if(p.__returned===p)throw f},_=(f,b)=>{let l=this.#M?.(e,n,a);r.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(f(void 0),i.allowStaleOnFetchAbort&&(f=w=>o(w,!0)))}),l&&l instanceof Promise?l.then(w=>f(w===void 0?void 0:w),b):l!==void 0&&f(l)};i.status&&(i.status.fetchDispatched=!0);let u=new Promise(_).then(o,d),g=Object.assign(u,{__abortController:r,__staleWhileFetching:n,__returned:void 0});return t===void 0?(this.#W(e,g,{...a.options,status:void 0}),t=this.#s.get(e)):this.#t[t]=g,g}#e(e){if(!this.#U)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof AbortController}fetch(e,t={}){let i=A.hasSubscribers,{status:s=D()?{}:void 0}=t;t.status=s,s&&t.context&&(s.context=t.context);let n=this.#B(e,t);return s&&i&&(s.trace=!0,A.tracePromise(()=>n,s).catch(()=>{})),n}async#B(e,t={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:r=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:a=0,sizeCalculation:o=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:y=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:_=this.allowStaleOnFetchRejection,ignoreFetchAbort:u=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:f,forceRefresh:b=!1,status:l,signal:w}=t;if(l&&(l.op="fetch",l.key=e,b&&(l.forceRefresh=!0),l.cache=this),!this.#U)return l&&(l.fetch="get"),this.#C(e,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:l});let F={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:r,noDisposeOnSet:h,size:a,sizeCalculation:o,noUpdateTTL:d,noDeleteOnFetchRejection:y,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:g,ignoreFetchAbort:u,status:l,signal:w},m=this.#s.get(e);if(m===void 0){l&&(l.fetch="miss");let p=this.#P(e,m,F,f);return p.__returned=p}else{let p=this.#t[m];if(this.#e(p)){let W=i&&p.__staleWhileFetching!==void 0;return l&&(l.fetch="inflight",W&&(l.returnedStale=!0)),W?p.__staleWhileFetching:p.__returned=p}let z=this.#p(m);if(!b&&!z)return l&&(l.fetch="hit"),this.#L(m),s&&this.#D(m),l&&this.#v(l,m),p;let E=this.#P(e,m,F,f),v=E.__staleWhileFetching!==void 0&&i;return l&&(l.fetch=z?"stale":"refresh",v&&z&&(l.returnedStale=!0)),v?E.__staleWhileFetching:E.__returned=E}}forceFetch(e,t={}){let i=A.hasSubscribers,{status:s=D()?{}:void 0}=t;t.status=s,s&&t.context&&(s.context=t.context);let n=this.#K(e,t);return s&&i&&(s.trace=!0,A.tracePromise(()=>n,s).catch(()=>{})),n}async#K(e,t={}){let i=await this.#B(e,t);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(e,t={}){let{status:i=S.hasSubscribers?{}:void 0}=t;t.status=i,i&&(i.op="memo",i.key=e,t.context&&(i.context=t.context),i.cache=this);let s=this.#Q(e,t);return i&&(i.value=s),S.hasSubscribers&&S.publish(i),s}#Q(e,t={}){let i=this.#I;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,status:n,forceRefresh:r,...h}=t;n&&r&&(n.forceRefresh=!0);let a=this.#C(e,h),o=r||a===void 0;if(n&&(n.memo=o?"miss":"hit",o||(n.value=a)),!o)return a;let d=i(e,a,{options:h,context:s});return n&&(n.value=d),this.#W(e,d,h),d}get(e,t={}){let{status:i=S.hasSubscribers?{}:void 0}=t;t.status=i,i&&(i.op="get",i.key=e,i.cache=this);let s=this.#C(e,t);return i&&(s!==void 0&&(i.value=s),S.hasSubscribers&&S.publish(i)),s}#C(e,t={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:r}=t,h=this.#s.get(e);if(h===void 0){r&&(r.get="miss");return}let a=this.#t[h],o=this.#e(a);return r&&this.#v(r,h),this.#p(h)?o?(r&&(r.get="stale-fetching"),i&&a.__staleWhileFetching!==void 0?(r&&(r.returnedStale=!0),a.__staleWhileFetching):void 0):(n||this.#E(e,"expire"),r&&(r.get="stale"),i?(r&&(r.returnedStale=!0),a):void 0):(r&&(r.get=o?"fetching":"hit"),this.#L(h),s&&this.#D(h),o?a.__staleWhileFetching:a)}#$(e,t){this.#u[t]=e,this.#l[e]=t}#L(e){e!==this.#h&&(e===this.#a?this.#a=this.#l[e]:this.#$(this.#u[e],this.#l[e]),this.#$(this.#h,e),this.#h=e)}delete(e){return this.#E(e,"delete")}#E(e,t){S.hasSubscribers&&S.publish({op:"delete",delete:t,key:e,cache:this});let i=!1;if(this.#n!==0){let s=this.#s.get(e);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g?.[s]),this.#g[s]=void 0),i=!0,this.#n===1)this.#q(t);else{this.#R(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#T||this.#f)&&(this.#T&&this.#S?.(n,e,t),this.#f&&this.#r?.push([n,e,t])),this.#s.delete(e),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#u[s];else if(s===this.#a)this.#a=this.#l[s];else{let r=this.#u[s];this.#l[r]=this.#l[s];let h=this.#l[s];this.#u[h]=this.#u[s]}this.#n--,this.#y.push(s)}}if(this.#f&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#w?.(...n)}return i}clear(){return this.#q("delete")}#q(e){for(let t of this.#z({allowStale:!0})){let i=this.#t[t];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[t];this.#T&&this.#S?.(i,s,e),this.#f&&this.#r?.push([i,s,e])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#F){this.#d.fill(0),this.#F.fill(0);for(let t of this.#g??[])t!==void 0&&clearTimeout(t);this.#g?.fill(void 0)}if(this.#_&&this.#_.fill(0),this.#a=0,this.#h=0,this.#y.length=0,this.#b=0,this.#n=0,this.#f&&this.#r){let t=this.#r,i;for(;i=t?.shift();)this.#w?.(...i)}}};export{U as LRUCache}; //# sourceMappingURL=index.min.js.map diff --git a/node_modules/lru-cache/dist/esm/node/diagnostics-channel.js b/node_modules/lru-cache/dist/esm/node/diagnostics-channel.js new file mode 100644 index 0000000000000..f37e0baac5977 --- /dev/null +++ b/node_modules/lru-cache/dist/esm/node/diagnostics-channel.js @@ -0,0 +1,6 @@ +// simple node version that imports from node builtin +// this is built to both ESM and CommonJS on the 'node' import path +import { tracingChannel, channel } from 'node:diagnostics_channel'; +export const metrics = channel('lru-cache:metrics'); +export const tracing = tracingChannel('lru-cache'); +//# sourceMappingURL=diagnostics-channel-node.js.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/esm/node/index.js b/node_modules/lru-cache/dist/esm/node/index.js new file mode 100644 index 0000000000000..2dd10cf8f908f --- /dev/null +++ b/node_modules/lru-cache/dist/esm/node/index.js @@ -0,0 +1,1722 @@ +/** + * @module LRUCache + */ +import { metrics, tracing } from './diagnostics-channel.js'; +import { defaultPerf } from './perf.js'; +const hasSubscribers = () => metrics.hasSubscribers || tracing.hasSubscribers; +const warned = new Set(); +/* c8 ignore start */ +const PROCESS = (typeof process === 'object' && !!process ? + process + : {}); +/* c8 ignore stop */ +const emitWarning = (msg, type, code, fn) => { + if (typeof PROCESS.emitWarning === 'function') { + PROCESS.emitWarning(msg, type, code, fn); + } + else { + //oxlint-disable-next-line no-console + console.error(`[${code}] ${type}: ${msg}`); + } +}; +const shouldWarn = (code) => !warned.has(code); +const TYPE = Symbol('type'); +const isPosInt = (n) => !!n && n === Math.floor(n) && n > 0 && isFinite(n); +// 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. +/* c8 ignore start */ +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 { + /* c8 ignore start - not sure why this is showing up uncovered?? */ + heap; + /* c8 ignore stop */ + 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; + #onInsert; + #disposeAfter; + #fetchMethod; + #memoMethod; + #perf; + /** + * {@link LRUCache.OptionsBase.perf} + */ + get perf() { + return this.#perf; + } + /** + * {@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; + /** {@link LRUCache.OptionsBase.backgroundFetchSize} */ + backgroundFetchSize; + // computed properties + #size; + #calculatedSize; + #keyMap; + #keyList; + #valList; + #next; + #prev; + #head; + #tail; + #free; + #disposed; + #sizes; + #starts; + #ttls; + #autopurgeTimers; + #hasDispose; + #hasFetchMethod; + #hasDisposeAfter; + #hasOnInsert; + /** + * 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, + autopurgeTimers: c.#autopurgeTimers, + 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.onInsert} (read-only) + */ + get onInsert() { + return this.#onInsert; + } + /** + * {@link LRUCache.OptionsBase.disposeAfter} (read-only) + */ + get disposeAfter() { + return this.#disposeAfter; + } + constructor(options) { + const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, onInsert, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, backgroundFetchSize = 1, perf, } = options; + this.backgroundFetchSize = backgroundFetchSize; + if (perf !== undefined) { + if (typeof perf?.now !== 'function') { + throw new TypeError('perf option must have a now() method if specified'); + } + } + this.#perf = perf ?? defaultPerf; + 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 = Array.from({ length: max }).fill(undefined); + this.#valList = Array.from({ length: 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 onInsert === 'function') { + this.#onInsert = onInsert; + } + if (typeof disposeAfter === 'function') { + this.#disposeAfter = disposeAfter; + this.#disposed = []; + } + else { + this.#disposeAfter = undefined; + this.#disposed = undefined; + } + this.#hasDispose = !!this.#dispose; + this.#hasOnInsert = !!this.#onInsert; + 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; + const purgeTimers = this.ttlAutopurge ? + Array.from({ + length: this.#max, + }) + : undefined; + this.#autopurgeTimers = purgeTimers; + this.#setItemTTL = (index, ttl, start = this.#perf.now()) => { + starts[index] = ttl !== 0 ? start : 0; + ttls[index] = ttl; + setPurgetTimer(index, ttl); + }; + this.#updateItemAge = index => { + starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0; + setPurgetTimer(index, ttls[index]); + }; + // clear out the purge timer if we're setting TTL to 0, and + // previously had a ttl purge timer running, so it doesn't + // fire unnecessarily. Don't need to do this if we're not doing + // autopurge. + const setPurgetTimer = !this.ttlAutopurge ? + () => { } + : (index, ttl) => { + if (purgeTimers?.[index]) { + clearTimeout(purgeTimers[index]); + purgeTimers[index] = undefined; + } + if (ttl && ttl !== 0 && purgeTimers) { + 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 */ + purgeTimers[index] = t; + } + }; + this.#statusTTL = (status, index) => { + if (ttls[index]) { + const ttl = ttls[index]; + const start = starts[index]; + /* c8 ignore start */ + if (!ttl || !start) { + return; + } + /* c8 ignore stop */ + 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 = this.#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) => { + if (!isPosInt(size)) { + // provisionally accept background fetches. + // actual value size will be checked when they return. + if (this.#isBackgroundFetch(v)) { + // NB: this cannot occur if v.__staleWhileFetching is set, + // because in that case, it would take on the size of the + // existing entry that it temporarily replaces. + return this.backgroundFetchSize; + } + 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; this.#isValidIndex(i);) { + 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; this.#isValidIndex(i);) { + 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]; + /* c8 ignore start - this isn't tested for the info function, + * but it's the same logic as found in other places. */ + const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + if (value === undefined) + return undefined; + /* c8 ignore stop */ + const entry = { value }; + if (this.#ttls && this.#starts) { + const ttl = this.#ttls[i]; + const start = this.#starts[i]; + if (ttl && start) { + const remain = ttl - (this.#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 LRUCache#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 = this.#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 = this.#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 = {}) { + const { status = metrics.hasSubscribers ? {} : undefined } = setOptions; + setOptions.status = status; + if (status) { + status.op = 'set'; + status.key = k; + if (v !== undefined) + status.value = v; + status.cache = this; + } + const result = this.#set(k, v, setOptions); + if (status && metrics.hasSubscribers) { + metrics.publish(status); + } + return result; + } + #set(k, v, setOptions, bf) { + const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; + const isBF = this.#isBackgroundFetch(v); + if (v === undefined) { + if (status) + status.set = 'deleted'; + this.delete(k); + return this; + } + let { noUpdateTTL = this.noUpdateTTL } = setOptions; + if (status && !isBF) + status.value = v; + const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation, status); + // if the item doesn't fit, don't do anything + // NB: maxEntrySize set to maxSize by default + if (this.maxEntrySize && size > this.maxEntrySize) { + // have to delete, in case something is there already. + this.#delete(k, 'set'); + if (status) { + status.set = 'miss'; + status.maxEntrySizeExceeded = true; + } + 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; + if (this.#hasOnInsert && !isBF) { + this.#onInsert?.(v, k, 'add'); + } + } + else { + // update + // might be updating a background fetch! + this.#moveToTail(index); + const oldVal = this.#valList[index]; + if (v !== oldVal) { + if (!noDisposeOnSet) { + if (this.#isBackgroundFetch(oldVal)) { + if (oldVal !== bf) { + // setting over a background fetch, not merely resolving it. + oldVal.__abortController.abort(new Error('replaced')); + } + const { __staleWhileFetching: s } = oldVal; + if (s !== undefined && s !== v) { + if (this.#hasDispose) { + this.#dispose?.(s, k, 'set'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([s, k, 'set']); + } + } + } + else { + 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 (!isBF) { + const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? + oldVal.__staleWhileFetching + : oldVal; + const setType = oldValue === undefined ? 'add' + : v !== oldValue ? 'replace' + : 'update'; + if (status) { + status.set = setType; + if (oldValue !== undefined) + status.oldValue = oldValue; + } + if (this.#hasOnInsert) { + this.onInsert?.(v, k, setType); + } + } + } + else if (!isBF) { + if (status) { + status.set = 'update'; + } + if (this.#hasOnInsert) { + this.onInsert?.(v, k, '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]; + const isBF = this.#isBackgroundFetch(v); + if (isBF) { + v.__abortController.abort(new Error('evicted')); + } + const oldValue = isBF ? v.__staleWhileFetching : v; + if ((this.#hasDispose || this.#hasDisposeAfter) && + oldValue !== undefined) { + if (this.#hasDispose) { + this.#dispose?.(oldValue, k, 'evict'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([oldValue, k, 'evict']); + } + } + this.#removeItemSize(head); + if (this.#autopurgeTimers?.[head]) { + clearTimeout(this.#autopurgeTimers[head]); + this.#autopurgeTimers[head] = undefined; + } + // 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 { status = metrics.hasSubscribers ? {} : undefined } = hasOptions; + hasOptions.status = status; + if (status) { + status.op = 'has'; + status.key = k; + status.cache = this; + } + const result = this.#has(k, hasOptions); + if (metrics.hasSubscribers) + metrics.publish(status); + return result; + } + #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 { status = hasSubscribers() ? {} : undefined } = peekOptions; + if (status) { + status.op = 'peek'; + status.key = k; + status.cache = this; + } + peekOptions.status = status; + const result = this.#peek(k, peekOptions); + if (metrics.hasSubscribers) { + metrics.publish(status); + } + return result; + } + #peek(k, peekOptions) { + const { status, allowStale = this.allowStale } = peekOptions; + const index = this.#keyMap.get(k); + if (index === undefined || (!allowStale && this.#isStale(index))) { + if (status) + status.peek = index === undefined ? 'miss' : 'stale'; + return undefined; + } + const v = this.#valList[index]; + const val = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + if (status) { + if (val !== undefined) { + status.peek = 'hit'; + status.value = val; + } + else { + status.peek = 'miss'; + } + } + return val; + } + #backgroundFetch(k, index, options, context) { + const v = index === undefined ? undefined : this.#valList[index]; + if (this.#isBackgroundFetch(v)) { + return v; + } + const ac = new AbortController(); + 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; + const proceed = options.ignoreFetchAbort || + !!(options.allowStaleOnFetchAbort && 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, proceed); + } + // either we didn't abort, and are still here, or we did, and ignored + const bf = p; + // if nothing else has been written there but we're set to update the + // cache and ignore the abort, or if it's still pending on this specific + // background request, then write it to the cache. + const vl = this.#valList[index]; + if (vl === p || (vl === undefined && ignoreAbort && updateCache)) { + if (v === undefined) { + if (bf.__staleWhileFetching !== undefined) { + this.#valList[index] = bf.__staleWhileFetching; + } + else { + this.#delete(k, 'fetch'); + } + } + else { + if (options.status) + options.status.fetchUpdated = true; + this.#set(k, v, fetchOpts.options, bf); + } + } + return v; + }; + const eb = (er) => { + if (options.status) { + options.status.fetchRejected = true; + options.status.fetchError = er; + } + // do not pass go, do not collect $200 + return fetchFail(er, false); + }; + const fetchFail = (er, proceed) => { + 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 || (!proceed && 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); + // 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 (fmp && fmp instanceof Promise) { + fmp.then(v => res(v === undefined ? undefined : v), rej); + } + else if (fmp !== undefined) { + res(fmp); + } + }; + 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 { + // do not call #set, because we do not want to adjust its place + // in the lru queue, as it has not yet been "used". Also, we don't + // need to worry about evicting for size, because a background fetch + // over a stale value is treated as the same size as its stale value. + 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 AbortController); + } + fetch(k, fetchOptions = {}) { + const ths = tracing.hasSubscribers; + const { status = hasSubscribers() ? {} : undefined } = fetchOptions; + fetchOptions.status = status; + if (status && fetchOptions.context) { + status.context = fetchOptions.context; + } + const p = this.#fetch(k, fetchOptions); + if (status && ths) { + status.trace = true; + tracing.tracePromise(() => p, status).catch(() => { }); + } + return p; + } + 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 (status) { + status.op = 'fetch'; + status.key = k; + if (forceRefresh) + status.forceRefresh = true; + status.cache = this; + } + 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); + } + } + forceFetch(k, fetchOptions = {}) { + const ths = tracing.hasSubscribers; + const { status = hasSubscribers() ? {} : undefined } = fetchOptions; + fetchOptions.status = status; + if (status && fetchOptions.context) { + status.context = fetchOptions.context; + } + const p = this.#forceFetch(k, fetchOptions); + if (status && ths) { + status.trace = true; + tracing.tracePromise(() => p, status).catch(() => { }); + } + return 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 { status = metrics.hasSubscribers ? {} : undefined } = memoOptions; + memoOptions.status = status; + if (status) { + status.op = 'memo'; + status.key = k; + if (memoOptions.context) { + status.context = memoOptions.context; + } + status.cache = this; + } + const result = this.#memo(k, memoOptions); + if (status) + status.value = result; + if (metrics.hasSubscribers) + metrics.publish(status); + return result; + } + #memo(k, memoOptions = {}) { + const memoMethod = this.#memoMethod; + if (!memoMethod) { + throw new Error('no memoMethod provided to constructor'); + } + const { context, status, forceRefresh, ...options } = memoOptions; + if (status && forceRefresh) + status.forceRefresh = true; + const v = this.#get(k, options); + const refresh = forceRefresh || v === undefined; + if (status) { + status.memo = refresh ? 'miss' : 'hit'; + if (!refresh) + status.value = v; + } + if (!refresh) + return v; + const vv = memoMethod(k, v, { + options, + context, + }); + if (status) + status.value = vv; + 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 { status = metrics.hasSubscribers ? {} : undefined } = getOptions; + getOptions.status = status; + if (status) { + status.op = 'get'; + status.key = k; + status.cache = this; + } + const result = this.#get(k, getOptions); + if (status) { + if (result !== undefined) + status.value = result; + if (metrics.hasSubscribers) + metrics.publish(status); + } + return result; + } + #get(k, getOptions = {}) { + const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; + const index = this.#keyMap.get(k); + if (index === undefined) { + if (status) + status.get = 'miss'; + return undefined; + } + const value = this.#valList[index]; + const fetching = this.#isBackgroundFetch(value); + if (status) + this.#statusTTL(status, index); + if (this.#isStale(index)) { + // delete only if not an in-flight background fetch + if (!fetching) { + if (!noDeleteOnStaleGet) { + this.#delete(k, 'expire'); + } + if (status) + status.get = 'stale'; + if (allowStale) { + if (status) + status.returnedStale = true; + return value; + } + return undefined; + } + if (status) + status.get = 'stale-fetching'; + if (allowStale && value.__staleWhileFetching !== undefined) { + if (status) + status.returnedStale = true; + return value.__staleWhileFetching; + } + return undefined; + } + // not stale + if (status) + status.get = fetching ? 'fetching' : '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. + this.#moveToTail(index); + if (updateAgeOnGet) { + this.#updateItemAge(index); + } + return fetching ? value.__staleWhileFetching : value; + } + #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) { + if (metrics.hasSubscribers) { + metrics.publish({ + op: 'delete', + delete: reason, + key: k, + cache: this, + }); + } + let deleted = false; + if (this.#size !== 0) { + const index = this.#keyMap.get(k); + if (index !== undefined) { + if (this.#autopurgeTimers?.[index]) { + clearTimeout(this.#autopurgeTimers?.[index]); + this.#autopurgeTimers[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(); + void this.#valList.fill(undefined); + this.#keyList.fill(undefined); + if (this.#ttls && this.#starts) { + this.#ttls.fill(0); + this.#starts.fill(0); + for (const t of this.#autopurgeTimers ?? []) { + if (t !== undefined) + clearTimeout(t); + } + this.#autopurgeTimers?.fill(undefined); + } + 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.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/esm/node/index.min.js b/node_modules/lru-cache/dist/esm/node/index.min.js new file mode 100644 index 0000000000000..84c4c3ec14ffa --- /dev/null +++ b/node_modules/lru-cache/dist/esm/node/index.min.js @@ -0,0 +1,2 @@ +import{tracingChannel as G,channel as P}from"node:diagnostics_channel";var S=P("lru-cache:metrics"),W=G("lru-cache");var L=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date;var D=()=>S.hasSubscribers||W.hasSubscribers,U=new Set,M=typeof process=="object"&&process?process:{},k=(u,e,t,i)=>{typeof M.emitWarning=="function"?M.emitWarning(u,e,t,i):console.error(`[${t}] ${e}: ${u}`)},H=u=>!U.has(u);var T=u=>!!u&&u===Math.floor(u)&&u>0&&isFinite(u),j=u=>T(u)?u<=Math.pow(2,8)?Uint8Array:u<=Math.pow(2,16)?Uint16Array:u<=Math.pow(2,32)?Uint32Array:u<=Number.MAX_SAFE_INTEGER?O:null:null,O=class extends Array{constructor(e){super(e),this.fill(0)}},R=class u{heap;length;static#o=!1;static create(e){let t=j(e);if(!t)return[];u.#o=!0;let i=new u(e,t);return u.#o=!1,i}constructor(e,t){if(!u.#o)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},I=class u{#o;#c;#S;#O;#w;#M;#I;#m;get perf(){return this.#m}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#n;#b;#s;#i;#t;#l;#u;#a;#h;#y;#r;#_;#F;#d;#g;#T;#U;#f;#x;static unsafeExposeInternals(e){return{starts:e.#F,ttls:e.#d,autopurgeTimers:e.#g,sizes:e.#_,keyMap:e.#s,keyList:e.#i,valList:e.#t,next:e.#l,prev:e.#u,get head(){return e.#a},get tail(){return e.#h},free:e.#y,isBackgroundFetch:t=>e.#e(t),backgroundFetch:(t,i,s,n)=>e.#P(t,i,s,n),moveToTail:t=>e.#L(t),indexes:t=>e.#A(t),rindexes:t=>e.#z(t),isStale:t=>e.#p(t)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#b}get size(){return this.#n}get fetchMethod(){return this.#M}get memoMethod(){return this.#I}get dispose(){return this.#S}get onInsert(){return this.#O}get disposeAfter(){return this.#w}constructor(e){let{max:t=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:r,updateAgeOnHas:h,allowStale:a,dispose:o,onInsert:d,disposeAfter:y,noDisposeOnSet:_,noUpdateTTL:c,maxSize:g=0,maxEntrySize:f=0,sizeCalculation:b,fetchMethod:l,memoMethod:w,noDeleteOnFetchRejection:F,noDeleteOnStaleGet:m,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:A,ignoreFetchAbort:z,backgroundFetchSize:C=1,perf:E}=e;if(this.backgroundFetchSize=C,E!==void 0&&typeof E?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#m=E??L,t!==0&&!T(t))throw new TypeError("max option must be a nonnegative integer");let v=t?j(t):Array;if(!v)throw new Error("invalid max value: "+t);if(this.#o=t,this.#c=g,this.maxEntrySize=f||this.#c,this.sizeCalculation=b,this.sizeCalculation){if(!this.#c&&!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(w!==void 0&&typeof w!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#I=w,l!==void 0&&typeof l!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#M=l,this.#U=!!l,this.#s=new Map,this.#i=Array.from({length:t}).fill(void 0),this.#t=Array.from({length:t}).fill(void 0),this.#l=new v(t),this.#u=new v(t),this.#a=0,this.#h=0,this.#y=R.create(t),this.#n=0,this.#b=0,typeof o=="function"&&(this.#S=o),typeof d=="function"&&(this.#O=d),typeof y=="function"?(this.#w=y,this.#r=[]):(this.#w=void 0,this.#r=void 0),this.#T=!!this.#S,this.#x=!!this.#O,this.#f=!!this.#w,this.noDisposeOnSet=!!_,this.noUpdateTTL=!!c,this.noDeleteOnFetchRejection=!!F,this.allowStaleOnFetchRejection=!!p,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.#c!==0&&!T(this.#c))throw new TypeError("maxSize must be a positive integer if specified");if(!T(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#X()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!m,this.updateAgeOnGet=!!r,this.updateAgeOnHas=!!h,this.ttlResolution=T(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!T(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#k()}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let x="LRU_CACHE_UNBOUNDED";H(x)&&(U.add(x),k("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",x,u))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#k(){let e=new O(this.#o),t=new O(this.#o);this.#d=e,this.#F=t;let i=this.ttlAutopurge?Array.from({length:this.#o}):void 0;this.#g=i,this.#H=(h,a,o=this.#m.now())=>{t[h]=a!==0?o:0,e[h]=a,s(h,a)},this.#D=h=>{t[h]=e[h]!==0?this.#m.now():0,s(h,e[h])};let s=this.ttlAutopurge?(h,a)=>{if(i?.[h]&&(clearTimeout(i[h]),i[h]=void 0),a&&a!==0&&i){let o=setTimeout(()=>{this.#p(h)&&this.#E(this.#i[h],"expire")},a+1);o.unref&&o.unref(),i[h]=o}}:()=>{};this.#v=(h,a)=>{if(e[a]){let o=e[a],d=t[a];if(!o||!d)return;h.ttl=o,h.start=d,h.now=n||r();let y=h.now-d;h.remainingTTL=o-y}};let n=0,r=()=>{let h=this.#m.now();if(this.ttlResolution>0){n=h;let a=setTimeout(()=>n=0,this.ttlResolution);a.unref&&a.unref()}return h};this.getRemainingTTL=h=>{let a=this.#s.get(h);if(a===void 0)return 0;let o=e[a],d=t[a];if(!o||!d)return 1/0;let y=(n||r())-d;return o-y},this.#p=h=>{let a=t[h],o=e[h];return!!o&&!!a&&(n||r())-a>o}}#D=()=>{};#v=()=>{};#H=()=>{};#p=()=>!1;#X(){let e=new O(this.#o);this.#b=0,this.#_=e,this.#R=t=>{this.#b-=e[t],e[t]=0},this.#N=(t,i,s,n)=>{if(!T(s)){if(this.#e(i))return this.backgroundFetchSize;if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,t),!T(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.#j=(t,i,s)=>{if(e[t]=i,this.#c){let n=this.#c-e[t];for(;this.#b>n;)this.#G(!0)}this.#b+=e[t],s&&(s.entrySize=i,s.totalCalculatedSize=this.#b)}}#R=e=>{};#j=(e,t,i)=>{};#N=(e,t,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:e=this.allowStale}={}){if(this.#n)for(let t=this.#h;this.#V(t)&&((e||!this.#p(t))&&(yield t),t!==this.#a);)t=this.#u[t]}*#z({allowStale:e=this.allowStale}={}){if(this.#n)for(let t=this.#a;this.#V(t)&&((e||!this.#p(t))&&(yield t),t!==this.#h);)t=this.#l[t]}#V(e){return e!==void 0&&this.#s.get(this.#i[e])===e}*entries(){for(let e of this.#A())this.#t[e]!==void 0&&this.#i[e]!==void 0&&!this.#e(this.#t[e])&&(yield[this.#i[e],this.#t[e]])}*rentries(){for(let e of this.#z())this.#t[e]!==void 0&&this.#i[e]!==void 0&&!this.#e(this.#t[e])&&(yield[this.#i[e],this.#t[e]])}*keys(){for(let e of this.#A()){let t=this.#i[e];t!==void 0&&!this.#e(this.#t[e])&&(yield t)}}*rkeys(){for(let e of this.#z()){let t=this.#i[e];t!==void 0&&!this.#e(this.#t[e])&&(yield t)}}*values(){for(let e of this.#A())this.#t[e]!==void 0&&!this.#e(this.#t[e])&&(yield this.#t[e])}*rvalues(){for(let e of this.#z())this.#t[e]!==void 0&&!this.#e(this.#t[e])&&(yield this.#t[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;if(n!==void 0&&e(n,this.#i[i],this))return this.#C(this.#i[i],t)}}forEach(e,t=this){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&e.call(t,n,this.#i[i],this)}}rforEach(e,t=this){for(let i of this.#z()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&e.call(t,n,this.#i[i],this)}}purgeStale(){let e=!1;for(let t of this.#z({allowStale:!0}))this.#p(t)&&(this.#E(this.#i[t],"expire"),e=!0);return e}info(e){let t=this.#s.get(e);if(t===void 0)return;let i=this.#t[t],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let n={value:s};if(this.#d&&this.#F){let r=this.#d[t],h=this.#F[t];if(r&&h){let a=r-(this.#m.now()-h);n.ttl=a,n.start=Date.now()}}return this.#_&&(n.size=this.#_[t]),n}dump(){let e=[];for(let t of this.#A({allowStale:!0})){let i=this.#i[t],s=this.#t[t],n=this.#e(s)?s.__staleWhileFetching:s;if(n===void 0||i===void 0)continue;let r={value:n};if(this.#d&&this.#F){r.ttl=this.#d[t];let h=this.#m.now()-this.#F[t];r.start=Math.floor(Date.now()-h)}this.#_&&(r.size=this.#_[t]),e.unshift([i,r])}return e}load(e){this.clear();for(let[t,i]of e){if(i.start){let s=Date.now()-i.start;i.start=this.#m.now()-s}this.#W(t,i.value,i)}}set(e,t,i={}){let{status:s=S.hasSubscribers?{}:void 0}=i;i.status=s,s&&(s.op="set",s.key=e,t!==void 0&&(s.value=t),s.cache=this);let n=this.#W(e,t,i);return s&&S.hasSubscribers&&S.publish(s),n}#W(e,t,i,s){let{ttl:n=this.ttl,start:r,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:o}=i,d=this.#e(t);if(t===void 0)return o&&(o.set="deleted"),this.delete(e),this;let{noUpdateTTL:y=this.noUpdateTTL}=i;o&&!d&&(o.value=t);let _=this.#N(e,t,i.size||0,a,o);if(this.maxEntrySize&&_>this.maxEntrySize)return this.#E(e,"set"),o&&(o.set="miss",o.maxEntrySizeExceeded=!0),this;let c=this.#n===0?void 0:this.#s.get(e);if(c===void 0)c=this.#n===0?this.#h:this.#y.length!==0?this.#y.pop():this.#n===this.#o?this.#G(!1):this.#n,this.#i[c]=e,this.#t[c]=t,this.#s.set(e,c),this.#l[this.#h]=c,this.#u[c]=this.#h,this.#h=c,this.#n++,this.#j(c,_,o),o&&(o.set="add"),y=!1,this.#x&&!d&&this.#O?.(t,e,"add");else{this.#L(c);let g=this.#t[c];if(t!==g){if(!h)if(this.#e(g)){g!==s&&g.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=g;f!==void 0&&f!==t&&(this.#T&&this.#S?.(f,e,"set"),this.#f&&this.#r?.push([f,e,"set"]))}else this.#T&&this.#S?.(g,e,"set"),this.#f&&this.#r?.push([g,e,"set"]);if(this.#R(c),this.#j(c,_,o),this.#t[c]=t,!d){let f=g&&this.#e(g)?g.__staleWhileFetching:g,b=f===void 0?"add":t!==f?"replace":"update";o&&(o.set=b,f!==void 0&&(o.oldValue=f)),this.#x&&this.onInsert?.(t,e,b)}}else d||(o&&(o.set="update"),this.#x&&this.onInsert?.(t,e,"update"))}if(n!==0&&!this.#d&&this.#k(),this.#d&&(y||this.#H(c,n,r),o&&this.#v(o,c)),!h&&this.#f&&this.#r){let g=this.#r,f;for(;f=g?.shift();)this.#w?.(...f)}return this}pop(){try{for(;this.#n;){let e=this.#t[this.#a];if(this.#G(!0),this.#e(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#f&&this.#r){let e=this.#r,t;for(;t=e?.shift();)this.#w?.(...t)}}}#G(e){let t=this.#a,i=this.#i[t],s=this.#t[t],n=this.#e(s);n&&s.__abortController.abort(new Error("evicted"));let r=n?s.__staleWhileFetching:s;return(this.#T||this.#f)&&r!==void 0&&(this.#T&&this.#S?.(r,i,"evict"),this.#f&&this.#r?.push([r,i,"evict"])),this.#R(t),this.#g?.[t]&&(clearTimeout(this.#g[t]),this.#g[t]=void 0),e&&(this.#i[t]=void 0,this.#t[t]=void 0,this.#y.push(t)),this.#n===1?(this.#a=this.#h=0,this.#y.length=0):this.#a=this.#l[t],this.#s.delete(i),this.#n--,t}has(e,t={}){let{status:i=S.hasSubscribers?{}:void 0}=t;t.status=i,i&&(i.op="has",i.key=e,i.cache=this);let s=this.#Y(e,t);return S.hasSubscribers&&S.publish(i),s}#Y(e,t={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=t,n=this.#s.get(e);if(n!==void 0){let r=this.#t[n];if(this.#e(r)&&r.__staleWhileFetching===void 0)return!1;if(this.#p(n))s&&(s.has="stale",this.#v(s,n));else return i&&this.#D(n),s&&(s.has="hit",this.#v(s,n)),!0}else s&&(s.has="miss");return!1}peek(e,t={}){let{status:i=D()?{}:void 0}=t;i&&(i.op="peek",i.key=e,i.cache=this),t.status=i;let s=this.#J(e,t);return S.hasSubscribers&&S.publish(i),s}#J(e,t){let{status:i,allowStale:s=this.allowStale}=t,n=this.#s.get(e);if(n===void 0||!s&&this.#p(n)){i&&(i.peek=n===void 0?"miss":"stale");return}let r=this.#t[n],h=this.#e(r)?r.__staleWhileFetching:r;return i&&(h!==void 0?(i.peek="hit",i.value=h):i.peek="miss"),h}#P(e,t,i,s){let n=t===void 0?void 0:this.#t[t];if(this.#e(n))return n;let r=new AbortController,{signal:h}=i;h?.addEventListener("abort",()=>r.abort(h.reason),{signal:r.signal});let a={signal:r.signal,options:i,context:s},o=(f,b=!1)=>{let{aborted:l}=r.signal,w=i.ignoreFetchAbort&&f!==void 0,F=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&f!==void 0);if(i.status&&(l&&!b?(i.status.fetchAborted=!0,i.status.fetchError=r.signal.reason,w&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),l&&!w&&!b)return y(r.signal.reason,F);let m=c,p=this.#t[t];return(p===c||p===void 0&&w&&b)&&(f===void 0?m.__staleWhileFetching!==void 0?this.#t[t]=m.__staleWhileFetching:this.#E(e,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.#W(e,f,a.options,m))),f},d=f=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=f),y(f,!1)),y=(f,b)=>{let{aborted:l}=r.signal,w=l&&i.allowStaleOnFetchAbort,F=w||i.allowStaleOnFetchRejection,m=F||i.noDeleteOnFetchRejection,p=c;if(this.#t[t]===c&&(!m||!b&&p.__staleWhileFetching===void 0?this.#E(e,"fetch"):w||(this.#t[t]=p.__staleWhileFetching)),F)return i.status&&p.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),p.__staleWhileFetching;if(p.__returned===p)throw f},_=(f,b)=>{let l=this.#M?.(e,n,a);r.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(f(void 0),i.allowStaleOnFetchAbort&&(f=w=>o(w,!0)))}),l&&l instanceof Promise?l.then(w=>f(w===void 0?void 0:w),b):l!==void 0&&f(l)};i.status&&(i.status.fetchDispatched=!0);let c=new Promise(_).then(o,d),g=Object.assign(c,{__abortController:r,__staleWhileFetching:n,__returned:void 0});return t===void 0?(this.#W(e,g,{...a.options,status:void 0}),t=this.#s.get(e)):this.#t[t]=g,g}#e(e){if(!this.#U)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof AbortController}fetch(e,t={}){let i=W.hasSubscribers,{status:s=D()?{}:void 0}=t;t.status=s,s&&t.context&&(s.context=t.context);let n=this.#B(e,t);return s&&i&&(s.trace=!0,W.tracePromise(()=>n,s).catch(()=>{})),n}async#B(e,t={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:r=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:a=0,sizeCalculation:o=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:y=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:_=this.allowStaleOnFetchRejection,ignoreFetchAbort:c=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:f,forceRefresh:b=!1,status:l,signal:w}=t;if(l&&(l.op="fetch",l.key=e,b&&(l.forceRefresh=!0),l.cache=this),!this.#U)return l&&(l.fetch="get"),this.#C(e,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:l});let F={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:r,noDisposeOnSet:h,size:a,sizeCalculation:o,noUpdateTTL:d,noDeleteOnFetchRejection:y,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:g,ignoreFetchAbort:c,status:l,signal:w},m=this.#s.get(e);if(m===void 0){l&&(l.fetch="miss");let p=this.#P(e,m,F,f);return p.__returned=p}else{let p=this.#t[m];if(this.#e(p)){let v=i&&p.__staleWhileFetching!==void 0;return l&&(l.fetch="inflight",v&&(l.returnedStale=!0)),v?p.__staleWhileFetching:p.__returned=p}let A=this.#p(m);if(!b&&!A)return l&&(l.fetch="hit"),this.#L(m),s&&this.#D(m),l&&this.#v(l,m),p;let z=this.#P(e,m,F,f),E=z.__staleWhileFetching!==void 0&&i;return l&&(l.fetch=A?"stale":"refresh",E&&A&&(l.returnedStale=!0)),E?z.__staleWhileFetching:z.__returned=z}}forceFetch(e,t={}){let i=W.hasSubscribers,{status:s=D()?{}:void 0}=t;t.status=s,s&&t.context&&(s.context=t.context);let n=this.#K(e,t);return s&&i&&(s.trace=!0,W.tracePromise(()=>n,s).catch(()=>{})),n}async#K(e,t={}){let i=await this.#B(e,t);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(e,t={}){let{status:i=S.hasSubscribers?{}:void 0}=t;t.status=i,i&&(i.op="memo",i.key=e,t.context&&(i.context=t.context),i.cache=this);let s=this.#Q(e,t);return i&&(i.value=s),S.hasSubscribers&&S.publish(i),s}#Q(e,t={}){let i=this.#I;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,status:n,forceRefresh:r,...h}=t;n&&r&&(n.forceRefresh=!0);let a=this.#C(e,h),o=r||a===void 0;if(n&&(n.memo=o?"miss":"hit",o||(n.value=a)),!o)return a;let d=i(e,a,{options:h,context:s});return n&&(n.value=d),this.#W(e,d,h),d}get(e,t={}){let{status:i=S.hasSubscribers?{}:void 0}=t;t.status=i,i&&(i.op="get",i.key=e,i.cache=this);let s=this.#C(e,t);return i&&(s!==void 0&&(i.value=s),S.hasSubscribers&&S.publish(i)),s}#C(e,t={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:r}=t,h=this.#s.get(e);if(h===void 0){r&&(r.get="miss");return}let a=this.#t[h],o=this.#e(a);return r&&this.#v(r,h),this.#p(h)?o?(r&&(r.get="stale-fetching"),i&&a.__staleWhileFetching!==void 0?(r&&(r.returnedStale=!0),a.__staleWhileFetching):void 0):(n||this.#E(e,"expire"),r&&(r.get="stale"),i?(r&&(r.returnedStale=!0),a):void 0):(r&&(r.get=o?"fetching":"hit"),this.#L(h),s&&this.#D(h),o?a.__staleWhileFetching:a)}#$(e,t){this.#u[t]=e,this.#l[e]=t}#L(e){e!==this.#h&&(e===this.#a?this.#a=this.#l[e]:this.#$(this.#u[e],this.#l[e]),this.#$(this.#h,e),this.#h=e)}delete(e){return this.#E(e,"delete")}#E(e,t){S.hasSubscribers&&S.publish({op:"delete",delete:t,key:e,cache:this});let i=!1;if(this.#n!==0){let s=this.#s.get(e);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g?.[s]),this.#g[s]=void 0),i=!0,this.#n===1)this.#q(t);else{this.#R(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#T||this.#f)&&(this.#T&&this.#S?.(n,e,t),this.#f&&this.#r?.push([n,e,t])),this.#s.delete(e),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#u[s];else if(s===this.#a)this.#a=this.#l[s];else{let r=this.#u[s];this.#l[r]=this.#l[s];let h=this.#l[s];this.#u[h]=this.#u[s]}this.#n--,this.#y.push(s)}}if(this.#f&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#w?.(...n)}return i}clear(){return this.#q("delete")}#q(e){for(let t of this.#z({allowStale:!0})){let i=this.#t[t];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[t];this.#T&&this.#S?.(i,s,e),this.#f&&this.#r?.push([i,s,e])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#F){this.#d.fill(0),this.#F.fill(0);for(let t of this.#g??[])t!==void 0&&clearTimeout(t);this.#g?.fill(void 0)}if(this.#_&&this.#_.fill(0),this.#a=0,this.#h=0,this.#y.length=0,this.#b=0,this.#n=0,this.#f&&this.#r){let t=this.#r,i;for(;i=t?.shift();)this.#w?.(...i)}}};export{I as LRUCache}; +//# sourceMappingURL=index.min.js.map diff --git a/node_modules/lru-cache/dist/esm/node/perf.js b/node_modules/lru-cache/dist/esm/node/perf.js new file mode 100644 index 0000000000000..f21cd88c8692d --- /dev/null +++ b/node_modules/lru-cache/dist/esm/node/perf.js @@ -0,0 +1,7 @@ +export const defaultPerf = (typeof performance === 'object' && + performance && + typeof performance.now === 'function') ? + /* c8 ignore start - this gets covered, but c8 gets confused */ + performance + : /* c8 ignore stop */ Date; +//# sourceMappingURL=perf.js.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/esm/perf.js b/node_modules/lru-cache/dist/esm/perf.js new file mode 100644 index 0000000000000..f21cd88c8692d --- /dev/null +++ b/node_modules/lru-cache/dist/esm/perf.js @@ -0,0 +1,7 @@ +export const defaultPerf = (typeof performance === 'object' && + performance && + typeof performance.now === 'function') ? + /* c8 ignore start - this gets covered, but c8 gets confused */ + performance + : /* c8 ignore stop */ Date; +//# sourceMappingURL=perf.js.map \ No newline at end of file diff --git a/node_modules/lru-cache/package.json b/node_modules/lru-cache/package.json index ef11862319611..6ada2c211f2d6 100644 --- a/node_modules/lru-cache/package.json +++ b/node_modules/lru-cache/package.json @@ -1,7 +1,7 @@ { "name": "lru-cache", "description": "A cache object that deletes the least-recently-used items.", - "version": "10.2.2", + "version": "11.5.1", "author": "Isaac Z. Schlueter ", "keywords": [ "mru", @@ -11,7 +11,7 @@ "sideEffects": false, "scripts": { "build": "npm run prepare", - "prepare": "tshy && bash fixup.sh", + "prepare": "tshy && bash scripts/build.sh", "pretest": "npm run prepare", "presnap": "npm run prepare", "test": "tap", @@ -25,93 +25,130 @@ "prebenchmark": "npm run prepare", "benchmark": "make -C benchmark", "preprofile": "npm run prepare", - "profile": "make -C benchmark profile" + "profile": "make -C benchmark profile", + "lint": "oxlint --fix src test", + "postsnap": "npm run lint", + "postlint": "npm run format" }, - "main": "./dist/commonjs/index.js", + "main": "./dist/commonjs/index.min.js", "types": "./dist/commonjs/index.d.ts", "tshy": { + "esmDialects": [ + "browser", + "node" + ], + "commonjsDialects": [ + "browser", + "node" + ], "exports": { - ".": "./src/index.ts", - "./min": { + "./raw": "./src/index.ts", + ".": { "import": { + "browser": { + "types": "./dist/esm/browser/index.d.ts", + "default": "./dist/esm/browser/index.min.js" + }, + "node": { + "types": "./dist/esm/node/index.d.ts", + "default": "./dist/esm/node/index.min.js" + }, "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.min.js" }, "require": { + "browser": { + "types": "./dist/commonjs/browser/index.d.ts", + "default": "./dist/commonjs/browser/index.min.js" + }, + "node": { + "types": "./dist/commonjs/node/index.d.ts", + "default": "./dist/commonjs/node/index.min.js" + }, "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.min.js" } } - } + }, + "selfLink": false }, "repository": { "type": "git", - "url": "git://github.com/isaacs/node-lru-cache.git" + "url": "git+ssh://git@github.com/isaacs/node-lru-cache.git" }, "devDependencies": { - "@tapjs/clock": "^1.1.16", - "@types/node": "^20.2.5", - "@types/tap": "^15.0.6", "benchmark": "^2.1.4", - "clock-mock": "^2.0.2", - "esbuild": "^0.17.11", - "eslint-config-prettier": "^8.5.0", + "esbuild": "^0.28.0", "marked": "^4.2.12", - "mkdirp": "^2.1.5", - "prettier": "^2.6.2", - "tap": "^18.5.7", - "tshy": "^1.8.0", - "tslib": "^2.4.0", - "typedoc": "^0.25.3", - "typescript": "^5.2.2" + "mkdirp": "^3.0.1", + "oxlint": "^1.65.0", + "oxlint-tsgolint": "^0.22.1", + "prettier": "^3.8.3", + "tap": "^21.7.4", + "tshy": "^4.1.2", + "typedoc": "^0.28.19" }, - "license": "ISC", + "license": "BlueOak-1.0.0", "files": [ "dist" ], "engines": { - "node": "14 || >=16.14" - }, - "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" - ] + "node": "20 || >=22" }, "exports": { - ".": { + "./raw": { "import": { + "browser": { + "types": "./dist/esm/browser/index.d.ts", + "default": "./dist/esm/browser/index.js" + }, + "node": { + "types": "./dist/esm/node/index.d.ts", + "default": "./dist/esm/node/index.js" + }, "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { + "browser": { + "types": "./dist/commonjs/browser/index.d.ts", + "default": "./dist/commonjs/browser/index.js" + }, + "node": { + "types": "./dist/commonjs/node/index.d.ts", + "default": "./dist/commonjs/node/index.js" + }, "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } }, - "./min": { + ".": { "import": { + "browser": { + "types": "./dist/esm/browser/index.d.ts", + "default": "./dist/esm/browser/index.min.js" + }, + "node": { + "types": "./dist/esm/node/index.d.ts", + "default": "./dist/esm/node/index.min.js" + }, "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.min.js" }, "require": { + "browser": { + "types": "./dist/commonjs/browser/index.d.ts", + "default": "./dist/commonjs/browser/index.min.js" + }, + "node": { + "types": "./dist/commonjs/node/index.d.ts", + "default": "./dist/commonjs/node/index.min.js" + }, "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.min.js" } } }, - "type": "module" + "type": "module", + "module": "./dist/esm/index.min.js" } diff --git a/node_modules/make-fetch-happen/lib/options.js b/node_modules/make-fetch-happen/lib/options.js index f77511279f831..db51cc6324817 100644 --- a/node_modules/make-fetch-happen/lib/options.js +++ b/node_modules/make-fetch-happen/lib/options.js @@ -11,7 +11,12 @@ const conditionalHeaders = [ const configureOptions = (opts) => { const { strictSSL, ...options } = { ...opts } options.method = options.method ? options.method.toUpperCase() : 'GET' - options.rejectUnauthorized = strictSSL !== false + + 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 } diff --git a/node_modules/make-fetch-happen/lib/remote.js b/node_modules/make-fetch-happen/lib/remote.js index 8554564074de6..061759638f05c 100644 --- a/node_modules/make-fetch-happen/lib/remote.js +++ b/node_modules/make-fetch-happen/lib/remote.js @@ -1,8 +1,9 @@ const { Minipass } = require('minipass') const fetch = require('minipass-fetch') -const promiseRetry = require('promise-retry') +const { promiseRetry } = require('@gar/promise-retry') const ssri = require('ssri') const { log } = require('proc-log') +const { redact: cleanUrl } = require('@npmcli/redact') const CachingMinipassPipeline = require('./pipeline.js') const { getAgent } = require('@npmcli/agent') @@ -35,7 +36,8 @@ const RETRY_TYPES = [ // following redirects (through the cache if necessary) // and verifying response integrity const remoteFetch = (request, options) => { - const agent = getAgent(request.url, 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') } @@ -54,6 +56,7 @@ const remoteFetch = (request, options) => { return promiseRetry(async (retryHandler, attemptNum) => { const req = new fetch.Request(request, _opts) + const url = cleanUrl(req.url) try { let res = await fetch(req, _opts) if (_opts.integrity && res.status === 200) { @@ -91,7 +94,7 @@ const remoteFetch = (request, options) => { } /* eslint-disable-next-line max-len */ - log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${res.status}`) + log.http('fetch', `${req.method} ${url} attempt ${attemptNum} failed with ${res.status}`) return retryHandler(res) } @@ -115,7 +118,7 @@ const remoteFetch = (request, options) => { options.onRetry(err) } - log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${err.code}`) + log.http('fetch', `${req.method} ${url} attempt ${attemptNum} failed with ${err.code}`) return retryHandler(err) } }, options.retry).catch((err) => { diff --git a/node_modules/minipass-fetch/LICENSE b/node_modules/make-fetch-happen/node_modules/minipass-fetch/LICENSE similarity index 100% rename from node_modules/minipass-fetch/LICENSE rename to node_modules/make-fetch-happen/node_modules/minipass-fetch/LICENSE diff --git a/node_modules/minipass-fetch/lib/abort-error.js b/node_modules/make-fetch-happen/node_modules/minipass-fetch/lib/abort-error.js similarity index 100% rename from node_modules/minipass-fetch/lib/abort-error.js rename to node_modules/make-fetch-happen/node_modules/minipass-fetch/lib/abort-error.js diff --git a/node_modules/minipass-fetch/lib/blob.js b/node_modules/make-fetch-happen/node_modules/minipass-fetch/lib/blob.js similarity index 100% rename from node_modules/minipass-fetch/lib/blob.js rename to node_modules/make-fetch-happen/node_modules/minipass-fetch/lib/blob.js diff --git a/node_modules/make-fetch-happen/node_modules/minipass-fetch/lib/body.js b/node_modules/make-fetch-happen/node_modules/minipass-fetch/lib/body.js new file mode 100644 index 0000000000000..f38ee807ca287 --- /dev/null +++ b/node_modules/make-fetch-happen/node_modules/minipass-fetch/lib/body.js @@ -0,0 +1,360 @@ +'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 'iconv-lite' +let decode +try { + decode = require('iconv-lite').decode +} 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 () { + /* istanbul ignore if */ + if (typeof decode !== 'function') { + throw new Error('The package `iconv-lite` must be installed to use the textConverted() function') + } + 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) => { + 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 = / { + 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 + res.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 diff --git a/node_modules/minipass-fetch/lib/request.js b/node_modules/make-fetch-happen/node_modules/minipass-fetch/lib/request.js similarity index 100% rename from node_modules/minipass-fetch/lib/request.js rename to node_modules/make-fetch-happen/node_modules/minipass-fetch/lib/request.js diff --git a/node_modules/minipass-fetch/lib/response.js b/node_modules/make-fetch-happen/node_modules/minipass-fetch/lib/response.js similarity index 100% rename from node_modules/minipass-fetch/lib/response.js rename to node_modules/make-fetch-happen/node_modules/minipass-fetch/lib/response.js diff --git a/node_modules/make-fetch-happen/node_modules/minipass-fetch/package.json b/node_modules/make-fetch-happen/node_modules/minipass-fetch/package.json new file mode 100644 index 0000000000000..9b64fa5be8be2 --- /dev/null +++ b/node_modules/make-fetch-happen/node_modules/minipass-fetch/package.json @@ -0,0 +1,70 @@ +{ + "name": "minipass-fetch", + "version": "6.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": "5.0.0", + "@ungap/url-search-params": "^0.2.2", + "abort-controller": "^3.0.0", + "abortcontroller-polyfill": "~1.7.3", + "form-data": "^4.0.0", + "iconv-lite": "^0.7.2", + "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": "^2.0.0", + "minizlib": "^3.0.1" + }, + "optionalDependencies": { + "iconv-lite": "^0.7.2" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/npm/minipass-fetch.git" + }, + "keywords": [ + "fetch", + "minipass", + "node-fetch", + "window.fetch" + ], + "files": [ + "bin/", + "lib/" + ], + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "5.0.0", + "publish": "true" + } +} diff --git a/node_modules/make-fetch-happen/package.json b/node_modules/make-fetch-happen/package.json index 7adb4d1e7f971..2bca3e4af11d3 100644 --- a/node_modules/make-fetch-happen/package.json +++ b/node_modules/make-fetch-happen/package.json @@ -1,6 +1,6 @@ { "name": "make-fetch-happen", - "version": "13.0.1", + "version": "16.0.1", "description": "Opinionated, caching, retrying fetch client", "main": "lib/index.js", "files": [ @@ -10,16 +10,16 @@ "scripts": { "test": "tap", "posttest": "npm run lint", - "eslint": "eslint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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": "https://github.com/npm/make-fetch-happen.git" + "url": "git+https://github.com/npm/make-fetch-happen.git" }, "keywords": [ "http", @@ -33,29 +33,29 @@ "author": "GitHub Inc.", "license": "ISC", "dependencies": { - "@npmcli/agent": "^2.0.0", - "cacache": "^18.0.0", + "@gar/promise-retry": "^1.0.0", + "@npmcli/agent": "^5.0.0", + "@npmcli/redact": "^5.0.0", + "cacache": "^21.0.0", "http-cache-semantics": "^4.1.1", - "is-lambda": "^1.0.1", "minipass": "^7.0.2", - "minipass-fetch": "^3.0.0", + "minipass-fetch": "^6.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", - "negotiator": "^0.6.3", - "proc-log": "^4.2.0", - "promise-retry": "^2.0.1", - "ssri": "^10.0.0" + "negotiator": "^1.0.0", + "proc-log": "^7.0.0", + "ssri": "^14.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.4", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.0", "nock": "^13.2.4", "safe-buffer": "^5.2.1", "standard-version": "^9.3.2", "tap": "^16.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "tap": { "color": 1, @@ -69,7 +69,7 @@ }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.4", + "version": "5.1.0", "publish": "true" } } diff --git a/node_modules/minimatch/LICENSE b/node_modules/minimatch/LICENSE deleted file mode 100644 index 1493534e60dce..0000000000000 --- a/node_modules/minimatch/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/jackspeak/LICENSE.md b/node_modules/minimatch/LICENSE.md similarity index 100% rename from node_modules/jackspeak/LICENSE.md rename to node_modules/minimatch/LICENSE.md diff --git a/node_modules/minimatch/dist/commonjs/ast.js b/node_modules/minimatch/dist/commonjs/ast.js index 7b2109625eaeb..33df3769f3ca0 100644 --- a/node_modules/minimatch/dist/commonjs/ast.js +++ b/node_modules/minimatch/dist/commonjs/ast.js @@ -1,11 +1,113 @@ "use strict"; // parse a single path portion +var _a; 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); +const isExtglobAST = (c) => isExtglobType(c.type); +// Map of which extglob types can adopt the children of a nested extglob +// +// anything but ! can adopt a matching type: +// +(a|+(b|c)|d) => +(a|b|c|d) +// *(a|*(b|c)|d) => *(a|b|c|d) +// @(a|@(b|c)|d) => @(a|b|c|d) +// ?(a|?(b|c)|d) => ?(a|b|c|d) +// +// * can adopt anything, because 0 or repetition is allowed +// *(a|?(b|c)|d) => *(a|b|c|d) +// *(a|+(b|c)|d) => *(a|b|c|d) +// *(a|@(b|c)|d) => *(a|b|c|d) +// +// + can adopt @, because 1 or repetition is allowed +// +(a|@(b|c)|d) => +(a|b|c|d) +// +// + and @ CANNOT adopt *, because 0 would be allowed +// +(a|*(b|c)|d) => would match "", on *(b|c) +// @(a|*(b|c)|d) => would match "", on *(b|c) +// +// + and @ CANNOT adopt ?, because 0 would be allowed +// +(a|?(b|c)|d) => would match "", on ?(b|c) +// @(a|?(b|c)|d) => would match "", on ?(b|c) +// +// ? can adopt @, because 0 or 1 is allowed +// ?(a|@(b|c)|d) => ?(a|b|c|d) +// +// ? and @ CANNOT adopt * or +, because >1 would be allowed +// ?(a|*(b|c)|d) => would match bbb on *(b|c) +// @(a|*(b|c)|d) => would match bbb on *(b|c) +// ?(a|+(b|c)|d) => would match bbb on +(b|c) +// @(a|+(b|c)|d) => would match bbb on +(b|c) +// +// ! CANNOT adopt ! (nothing else can either) +// !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c) +// +// ! can adopt @ +// !(a|@(b|c)|d) => !(a|b|c|d) +// +// ! CANNOT adopt * +// !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed +// +// ! CANNOT adopt + +// !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed +// +// ! CANNOT adopt ? +// x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x" +const adoptionMap = new Map([ + ['!', ['@']], + ['?', ['?', '@']], + ['@', ['@']], + ['*', ['*', '+', '?', '@']], + ['+', ['+', '@']], +]); +// nested extglobs that can be adopted in, but with the addition of +// a blank '' element. +const adoptionWithSpaceMap = new Map([ + ['!', ['?']], + ['@', ['?']], + ['+', ['?', '*']], +]); +// union of the previous two maps +const adoptionAnyMap = new Map([ + ['!', ['?', '@']], + ['?', ['?', '@']], + ['@', ['?', '@']], + ['*', ['*', '+', '?', '@']], + ['+', ['+', '@', '?', '*']], +]); +// Extglobs that can take over their parent if they are the only child +// the key is parent, value maps child to resulting extglob parent type +// '@' is omitted because it's a special case. An `@` extglob with a single +// member can always be usurped by that subpattern. +const usurpMap = new Map([ + ['!', new Map([['!', '@']])], + [ + '?', + new Map([ + ['*', '*'], + ['+', '*'], + ]), + ], + [ + '@', + new Map([ + ['!', '!'], + ['?', '?'], + ['@', '@'], + ['*', '*'], + ['+', '+'], + ]), + ], + [ + '+', + new Map([ + ['?', '*'], + ['*', '*'], + ]), + ], +]); // 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. @@ -29,6 +131,7 @@ const star = qmark + '*?'; 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') +let ID = 0; class AST { type; #root; @@ -44,6 +147,22 @@ class AST { // set to true if it's an extglob with no children // (which really means one child of '') #emptyExt = false; + id = ++ID; + get depth() { + return (this.#parent?.depth ?? -1) + 1; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return { + '@@type': 'AST', + id: this.id, + type: this.type, + root: this.#root.id, + parent: this.#parent?.id, + depth: this.depth, + partsLength: this.#parts.length, + parts: this.#parts, + }; + } constructor(type, parent, options = {}) { this.type = type; // extglobs are inherently magical @@ -73,15 +192,14 @@ class AST { } // 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('|') + ')'); - } + return (this.#toString !== undefined ? this.#toString + : !this.type ? + (this.#toString = this.#parts.map(p => String(p)).join('')) + : (this.#toString = + this.type + + '(' + + this.#parts.map(p => String(p)).join('|') + + ')')); } #fillNegs() { /* c8 ignore start */ @@ -122,7 +240,8 @@ class AST { if (p === '') continue; /* c8 ignore start */ - if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) { + if (typeof p !== 'string' && + !(p instanceof _a && p.#parent === this)) { throw new Error('invalid part: ' + p); } /* c8 ignore stop */ @@ -130,8 +249,10 @@ class AST { } } toJSON() { - const ret = this.type === null - ? this.#parts.slice().map(p => (typeof p === 'string' ? p : 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([]); @@ -154,7 +275,7 @@ class AST { const p = this.#parent; for (let i = 0; i < this.#parentIndex; i++) { const pp = p.#parts[i]; - if (!(pp instanceof AST && pp.type === '!')) { + if (!(pp instanceof _a && pp.type === '!')) { return false; } } @@ -182,13 +303,14 @@ class AST { this.push(part.clone(this)); } clone(parent) { - const c = new AST(this.type, parent); + const c = new _a(this.type, parent); for (const p of this.#parts) { c.copyIn(p); } return c; } - static #parseAST(str, ast, pos, opt) { + static #parseAST(str, ast, pos, opt, extDepth) { + const maxDepth = opt.maxExtglobRecursion ?? 2; let escaping = false; let inBrace = false; let braceStart = -1; @@ -225,11 +347,17 @@ class AST { acc += c; continue; } - if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') { + // we don't have to check for adoption here, because that's + // done at the other recursion point. + const doRecurse = !opt.noext && + isExtglobType(c) && + str.charAt(i) === '(' && + extDepth <= maxDepth; + if (doRecurse) { ast.push(acc); acc = ''; - const ext = new AST(c, ast); - i = AST.#parseAST(str, ext, i, opt); + const ext = new _a(c, ast); + i = _a.#parseAST(str, ext, i, opt, extDepth + 1); ast.push(ext); continue; } @@ -241,7 +369,7 @@ class AST { // some kind of extglob, pos is at the ( // find the next | or ) let i = pos + 1; - let part = new AST(null, ast); + let part = new _a(null, ast); const parts = []; let acc = ''; while (i < str.length) { @@ -272,19 +400,26 @@ class AST { acc += c; continue; } - if (isExtglobType(c) && str.charAt(i) === '(') { + const doRecurse = !opt.noext && + isExtglobType(c) && + str.charAt(i) === '(' && + /* c8 ignore start - the maxDepth is sufficient here */ + (extDepth <= maxDepth || (ast && ast.#canAdoptType(c))); + /* c8 ignore stop */ + if (doRecurse) { + const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1; part.push(acc); acc = ''; - const ext = new AST(c, part); + const ext = new _a(c, part); part.push(ext); - i = AST.#parseAST(str, ext, i, opt); + i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd); continue; } if (c === '|') { part.push(acc); acc = ''; parts.push(part); - part = new AST(null, ast); + part = new _a(null, ast); continue; } if (c === ')') { @@ -306,9 +441,82 @@ class AST { ast.#parts = [str.substring(pos - 1)]; return i; } + #canAdoptWithSpace(child) { + return this.#canAdopt(child, adoptionWithSpaceMap); + } + #canAdopt(child, map = adoptionMap) { + if (!child || + typeof child !== 'object' || + child.type !== null || + child.#parts.length !== 1 || + this.type === null) { + return false; + } + const gc = child.#parts[0]; + if (!gc || typeof gc !== 'object' || gc.type === null) { + return false; + } + return this.#canAdoptType(gc.type, map); + } + #canAdoptType(c, map = adoptionAnyMap) { + return !!map.get(this.type)?.includes(c); + } + #adoptWithSpace(child, index) { + const gc = child.#parts[0]; + const blank = new _a(null, gc, this.options); + blank.#parts.push(''); + gc.push(blank); + this.#adopt(child, index); + } + #adopt(child, index) { + const gc = child.#parts[0]; + this.#parts.splice(index, 1, ...gc.#parts); + for (const p of gc.#parts) { + if (typeof p === 'object') + p.#parent = this; + } + this.#toString = undefined; + } + #canUsurpType(c) { + const m = usurpMap.get(this.type); + return !!m?.has(c); + } + #canUsurp(child) { + if (!child || + typeof child !== 'object' || + child.type !== null || + child.#parts.length !== 1 || + this.type === null || + this.#parts.length !== 1) { + return false; + } + const gc = child.#parts[0]; + if (!gc || typeof gc !== 'object' || gc.type === null) { + return false; + } + return this.#canUsurpType(gc.type); + } + #usurp(child) { + const m = usurpMap.get(this.type); + const gc = child.#parts[0]; + const nt = m?.get(gc.type); + /* c8 ignore start - impossible */ + if (!nt) + return false; + /* c8 ignore stop */ + this.#parts = gc.#parts; + for (const p of this.#parts) { + if (typeof p === 'object') { + p.#parent = this; + } + } + this.type = nt; + this.#toString = undefined; + this.#emptyExt = false; + } static fromGlob(pattern, options = {}) { - const ast = new AST(null, undefined, options); - AST.#parseAST(pattern, ast, 0, options); + const ast = new _a(null, undefined, options); + _a.#parseAST(pattern, ast, 0, options, 0); return ast; } // returns the regular expression if there's magic, or the unescaped @@ -412,14 +620,18 @@ class AST { // or start or whatever) and prepend ^ or / at the Regexp construction. toRegExpSource(allowDot) { const dot = allowDot ?? !!this.#options.dot; - if (this.#root === this) + if (this.#root === this) { + this.#flatten(); this.#fillNegs(); - if (!this.type) { - const noEmpty = this.isStart() && this.isEnd(); + } + if (!isExtglobAST(this)) { + const noEmpty = this.isStart() && + this.isEnd() && + !this.#parts.some(s => typeof s !== 'string'); const src = this.#parts .map(p => { - const [re, _, hasMagic, uflag] = typeof p === 'string' - ? AST.#parseGlob(p, this.#hasMagic, noEmpty) + const [re, _, hasMagic, uflag] = typeof p === 'string' ? + _a.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot); this.#hasMagic = this.#hasMagic || hasMagic; this.#uflag = this.#uflag || uflag; @@ -448,7 +660,10 @@ class AST { // 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 : ''; + start = + needNoTrav ? startNoTraversal + : needNoDot ? startNoDot + : ''; } } } @@ -478,14 +693,14 @@ class AST { // 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; + const me = this; + me.#parts = [s]; + me.type = null; + me.#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 - ? '' + let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? + '' : this.#partsToRegExp(true); if (bodyDotAllowed === body) { bodyDotAllowed = ''; @@ -499,20 +714,16 @@ class AST { 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 - ? `)?` + 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; } @@ -523,6 +734,42 @@ class AST { this.#uflag, ]; } + #flatten() { + if (!isExtglobAST(this)) { + for (const p of this.#parts) { + if (typeof p === 'object') { + p.#flatten(); + } + } + } + else { + // do up to 10 passes to flatten as much as possible + let iterations = 0; + let done = false; + do { + done = true; + for (let i = 0; i < this.#parts.length; i++) { + const c = this.#parts[i]; + if (typeof c === 'object') { + c.#flatten(); + if (this.#canAdopt(c)) { + done = false; + this.#adopt(c, i); + } + else if (this.#canAdoptWithSpace(c)) { + done = false; + this.#adoptWithSpace(c, i); + } + else if (this.#canUsurp(c)) { + done = false; + this.#usurp(c); + } + } + } + } while (!done && ++iterations < 10); + } + this.#toString = undefined; + } #partsToRegExp(dot) { return this.#parts .map(p => { @@ -544,6 +791,8 @@ class AST { let escaping = false; let re = ''; let uflag = false; + // multiple stars that aren't globstars coalesce into one * + let inStar = false; for (let i = 0; i < glob.length; i++) { const c = glob.charAt(i); if (escaping) { @@ -551,6 +800,17 @@ class AST { re += (reSpecials.has(c) ? '\\' : '') + c; continue; } + if (c === '*') { + if (inStar) + continue; + inStar = true; + re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star; + hasMagic = true; + continue; + } + else { + inStar = false; + } if (c === '\\') { if (i === glob.length - 1) { re += '\\\\'; @@ -570,14 +830,6 @@ class AST { continue; } } - if (c === '*') { - if (noEmpty && glob === '*') - re += starNoEmpty; - else - re += star; - hasMagic = true; - continue; - } if (c === '?') { re += qmark; hasMagic = true; @@ -589,4 +841,5 @@ class AST { } } exports.AST = AST; +_a = AST; //# sourceMappingURL=ast.js.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/brace-expressions.js b/node_modules/minimatch/dist/commonjs/brace-expressions.js index 0e13eefc4cfee..2b7b03712b874 100644 --- a/node_modules/minimatch/dist/commonjs/brace-expressions.js +++ b/node_modules/minimatch/dist/commonjs/brace-expressions.js @@ -141,10 +141,8 @@ const parseClass = (glob, position) => { } const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'; const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'; - const comb = ranges.length && negs.length - ? '(' + sranges + '|' + snegs + ')' - : ranges.length - ? sranges + const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')' + : ranges.length ? sranges : snegs; return [comb, uflag, endPos - pos, true]; }; diff --git a/node_modules/minimatch/dist/commonjs/escape.js b/node_modules/minimatch/dist/commonjs/escape.js index 02a4f8a8e0a58..83a713a255077 100644 --- a/node_modules/minimatch/dist/commonjs/escape.js +++ b/node_modules/minimatch/dist/commonjs/escape.js @@ -4,18 +4,26 @@ exports.escape = void 0; /** * Escape all magic characters in a glob pattern. * - * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape} + * If the {@link MinimatchOptions.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. + * + * If the {@link MinimatchOptions.magicalBraces} option is used, + * then braces (`{` and `}`) will be escaped. */ -const escape = (s, { windowsPathsNoEscape = false, } = {}) => { +const escape = (s, { windowsPathsNoEscape = false, magicalBraces = 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, '[$&]') + if (magicalBraces) { + return windowsPathsNoEscape ? + s.replace(/[?*()[\]{}]/g, '[$&]') + : s.replace(/[?*()[\]\\{}]/g, '\\$&'); + } + return windowsPathsNoEscape ? + s.replace(/[?*()[\]]/g, '[$&]') : s.replace(/[?*()[\]\\]/g, '\\$&'); }; exports.escape = escape; diff --git a/node_modules/minimatch/dist/commonjs/index.js b/node_modules/minimatch/dist/commonjs/index.js index 64a0f1f833222..5a6983481b785 100644 --- a/node_modules/minimatch/dist/commonjs/index.js +++ b/node_modules/minimatch/dist/commonjs/index.js @@ -1,10 +1,7 @@ "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 brace_expansion_1 = 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"); @@ -19,7 +16,7 @@ const minimatch = (p, pattern, options = {}) => { }; exports.minimatch = minimatch; // Optimized checking for the most common glob patterns. -const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; +const starDotExtRE = /^\*+([^+@!?*[(]*)$/; const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext); const starDotExtTestDot = (ext) => (f) => f.endsWith(ext); const starDotExtTestNocase = (ext) => { @@ -38,7 +35,7 @@ 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 qmarksRE = /^\?+([^+@!?*[(]*)?$/; const qmarksTestNocase = ([$0, ext = '']) => { const noext = qmarksTestNoExt([$0]); if (!ext) @@ -70,8 +67,8 @@ const qmarksTestNoExtDot = ([$0]) => { return (f) => f.length === len && f !== '.' && f !== '..'; }; /* c8 ignore start */ -const defaultPlatform = (typeof process === 'object' && process - ? (typeof process.env === 'object' && +const defaultPlatform = (typeof process === 'object' && process ? + (typeof process.env === 'object' && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__) || process.platform @@ -157,7 +154,7 @@ const braceExpand = (pattern, options = {}) => { // shortcut. no need to expand. return [pattern]; } - return (0, brace_expansion_1.default)(pattern); + return (0, brace_expansion_1.expand)(pattern, { max: options.braceExpandMax }); }; exports.braceExpand = braceExpand; exports.minimatch.braceExpand = exports.braceExpand; @@ -205,16 +202,20 @@ class Minimatch { isWindows; platform; windowsNoMagicRoot; + maxGlobstarRecursion; regexp; constructor(pattern, options = {}) { (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); options = options || {}; this.options = options; + this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200; this.pattern = pattern; this.platform = options.platform || defaultPlatform; this.isWindows = this.platform === 'win32'; + // avoid the annoying deprecation flag lol + const awe = ('allowWindow' + 'sEscape'); this.windowsPathsNoEscape = - !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; + !!options.windowsPathsNoEscape || options[awe] === false; if (this.windowsPathsNoEscape) { this.pattern = this.pattern.replace(/\\/g, '/'); } @@ -227,8 +228,8 @@ class Minimatch { this.partial = !!options.partial; this.nocase = !!this.options.nocase; this.windowsNoMagicRoot = - options.windowsNoMagicRoot !== undefined - ? options.windowsNoMagicRoot + options.windowsNoMagicRoot !== undefined ? + options.windowsNoMagicRoot : !!(this.isWindows && this.nocase); this.globSet = []; this.globParts = []; @@ -266,6 +267,7 @@ class Minimatch { // step 2: expand braces this.globSet = [...new Set(this.braceExpand())]; if (options.debug) { + //oxlint-disable-next-line no-console this.debug = (...args) => console.error(...args); } this.debug(this.pattern, this.globSet); @@ -291,7 +293,10 @@ class Minimatch { !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))]; + 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))]; @@ -323,12 +328,12 @@ class Minimatch { // 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 we're not in globstar mode, then turn ** 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] = '*'; + for (const partset of globParts) { + for (let j = 0; j < partset.length; j++) { + if (partset[j] === '**') { + partset[j] = '*'; } } } @@ -416,7 +421,11 @@ class Minimatch { let dd = 0; while (-1 !== (dd = parts.indexOf('..', dd + 1))) { const p = parts[dd - 1]; - if (p && p !== '.' && p !== '..' && p !== '**') { + if (p && + p !== '.' && + p !== '..' && + p !== '**' && + !(this.isWindows && /^[a-z]:$/i.test(p))) { didSomething = true; parts.splice(dd - 1, 2); dd -= 2; @@ -609,7 +618,8 @@ class Minimatch { // out of pattern, then that's fine, as long as all // the parts match. matchOne(file, pattern, partial = false) { - const options = this.options; + let fileStartIndex = 0; + let patternStartIndex = 0; // UNC paths like //?/X:/... can match X:/... and vice versa // Drive letters in absolute drive or unc paths are always compared // case-insensitively. @@ -627,120 +637,212 @@ class Minimatch { 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; + 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]]; + const [fd, pd] = [ + file[fdi], + pattern[pdi], + ]; + // start matching at the drive letter index of each if (fd.toLowerCase() === pd.toLowerCase()) { pattern[pdi] = fd; - if (pdi > fdi) { - pattern = pattern.slice(pdi); - } - else if (fdi > pdi) { - file = file.slice(fdi); - } + patternStartIndex = pdi; + fileStartIndex = fdi; } } } // resolve and reduce . and .. portions in the file as well. - // dont' need to do the second phase, because it's only one string[] + // don't 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++) { + if (pattern.includes(exports.GLOBSTAR)) { + return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex); + } + return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex); + } + #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) { + // split the pattern into head, tail, and middle of ** delimited parts + const firstgs = pattern.indexOf(exports.GLOBSTAR, patternIndex); + const lastgs = pattern.lastIndexOf(exports.GLOBSTAR); + // split the pattern up into globstar-delimited sections + // the tail has to be at the end, and the others just have + // to be found in order from the head. + const [head, body, tail] = partial ? + [ + pattern.slice(patternIndex, firstgs), + pattern.slice(firstgs + 1), + [], + ] + : [ + pattern.slice(patternIndex, firstgs), + pattern.slice(firstgs + 1, lastgs), + pattern.slice(lastgs + 1), + ]; + // check the head, from the current file/pattern index. + if (head.length) { + const fileHead = file.slice(fileIndex, fileIndex + head.length); + if (!this.#matchOne(fileHead, head, partial, 0, 0)) { + return false; + } + fileIndex += head.length; + patternIndex += head.length; + } + // now we know the head matches! + // if the last portion is not empty, it MUST match the end + // check the tail + let fileTailMatch = 0; + if (tail.length) { + // if head + tail > file, then we cannot possibly match + if (tail.length + fileIndex > file.length) + return false; + // try to match the tail + let tailStart = file.length - tail.length; + if (this.#matchOne(file, tail, partial, tailStart, 0)) { + fileTailMatch = tail.length; + } + else { + // affordance for stuff like a/**/* matching a/b/ + // if the last file portion is '', and there's more to the pattern + // then try without the '' bit. + if (file[file.length - 1] !== '' || + fileIndex + tail.length === file.length) { + return false; + } + tailStart--; + if (!this.#matchOne(file, tail, partial, tailStart, 0)) { + return false; + } + fileTailMatch = tail.length + 1; + } + } + // now we know the tail matches! + // the middle is zero or more portions wrapped in **, possibly + // containing more ** sections. + // so a/**/b/**/c/**/d has become **/b/**/c/** + // if it's empty, it means a/**/b, just verify we have no bad dots + // if there's no tail, so it ends on /**, then we must have *something* + // after the head, or it's not a matc + if (!body.length) { + let sawSome = !!fileTailMatch; + for (let i = fileIndex; i < file.length - fileTailMatch; i++) { + const f = String(file[i]); + sawSome = true; + if (f === '.' || + f === '..' || + (!this.options.dot && f.startsWith('.'))) { + return false; + } + } + // in partial mode, we just need to get past all file parts + return partial || sawSome; + } + // now we know that there's one or more body sections, which can + // be matched anywhere from the 0 index (because the head was pruned) + // through to the length-fileTailMatch index. + // split the body up into sections, and note the minimum index it can + // be found at (start with the length of all previous segments) + // [section, before, after] + const bodySegments = [[[], 0]]; + let currentBody = bodySegments[0]; + let nonGsParts = 0; + const nonGsPartsSums = [0]; + for (const b of body) { + if (b === exports.GLOBSTAR) { + nonGsPartsSums.push(nonGsParts); + currentBody = [[], 0]; + bodySegments.push(currentBody); + } + else { + currentBody[0].push(b); + nonGsParts++; + } + } + let i = bodySegments.length - 1; + const fileLength = file.length - fileTailMatch; + for (const b of bodySegments) { + b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length); + } + return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch); + } + // return false for "nope, not matching" + // return null for "not matching, cannot keep trying" + #matchGlobStarBodySections(file, + // pattern section, last possible position for it + bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) { + // take the first body segment, and walk from fileIndex to its "after" + // value at the end + // If it doesn't match at that position, we increment, until we hit + // that final possible position, and give up. + // If it does match, then advance and try to rest. + // If any of them fail we keep walking forward. + // this is still a bit recursively painful, but it's more constrained + // than previous implementations, because we never test something that + // can't possibly be a valid matching condition. + const bs = bodySegments[bodyIndex]; + if (!bs) { + // just make sure that there's no bad dots + for (let i = fileIndex; i < file.length; i++) { + sawTail = true; + const f = file[i]; + if (f === '.' || + f === '..' || + (!this.options.dot && f.startsWith('.'))) { + return false; + } + } + return sawTail; + } + // have a non-globstar body section to test + const [body, after] = bs; + while (fileIndex <= after) { + const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0); + // if limit exceeded, no match. intentional false negative, + // acceptable break in correctness for security. + if (m && globStarDepth < this.maxGlobstarRecursion) { + // match! see if the rest match. if so, we're done! + const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail); + if (sub !== false) { + return sub; + } + } + const f = file[fileIndex]; + if (f === '.' || + f === '..' || + (!this.options.dot && f.startsWith('.'))) { + return false; + } + fileIndex++; + } + // walked off. no point continuing + return partial || null; + } + #matchOne(file, pattern, partial, fileIndex, patternIndex) { + let fi; + let pi; + let pl; + let fl; + for (fi = fileIndex, + pi = patternIndex, + fl = file.length, + pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { this.debug('matchOne loop'); - var p = pattern[pi]; - var f = file[fi]; + let p = pattern[pi]; + let f = file[fi]; this.debug(pattern, p, f); // should be impossible. // some invalid regexp stuff in the set. /* c8 ignore start */ - if (p === false) { + if (p === false || p === exports.GLOBSTAR) { 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. @@ -811,21 +913,19 @@ class Minimatch { fastTest = options.dot ? starTestDot : starTest; } else if ((m = pattern.match(starDotExtRE))) { - fastTest = (options.nocase - ? options.dot - ? starDotExtTestNocaseDot + fastTest = (options.nocase ? + options.dot ? + starDotExtTestNocaseDot : starDotExtTestNocase - : options.dot - ? starDotExtTestDot + : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]); } else if ((m = pattern.match(qmarksRE))) { - fastTest = (options.nocase - ? options.dot - ? qmarksTestNocaseDot + fastTest = (options.nocase ? + options.dot ? + qmarksTestNocaseDot : qmarksTestNocase - : options.dot - ? qmarksTestDot + : options.dot ? qmarksTestDot : qmarksTest)(m); } else if ((m = pattern.match(starDotStarRE))) { @@ -856,10 +956,8 @@ class Minimatch { return this.regexp; } const options = this.options; - const twoStar = options.noglobstar - ? star - : options.dot - ? twoStarDot + const twoStar = options.noglobstar ? star + : options.dot ? twoStarDot : twoStarNoDot; const flags = new Set(options.nocase ? ['i'] : []); // regexpify non-globstar patterns @@ -875,11 +973,9 @@ class Minimatch { for (const f of p.flags.split('')) flags.add(f); } - return typeof p === 'string' - ? regExpEscape(p) - : p === exports.GLOBSTAR - ? exports.GLOBSTAR - : p._src; + return (typeof p === 'string' ? regExpEscape(p) + : p === exports.GLOBSTAR ? exports.GLOBSTAR + : p._src); }); pp.forEach((p, i) => { const next = pp[i + 1]; @@ -896,14 +992,25 @@ class Minimatch { } } else if (next === undefined) { - pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?'; + 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('/'); + const filtered = pp.filter(p => p !== exports.GLOBSTAR); + // For partial matches, we need to make the pattern match + // any prefix of the full path. We do this by generating + // alternative patterns that match progressively longer prefixes. + if (this.partial && filtered.length >= 1) { + const prefixes = []; + for (let i = 1; i <= filtered.length; i++) { + prefixes.push(filtered.slice(0, i).join('/')); + } + return '(?:' + prefixes.join('|') + ')'; + } + return filtered.join('/'); }) .join('|'); // need to wrap in parens if we had more than one thing with |, @@ -912,6 +1019,10 @@ class Minimatch { // must match entire pattern // ending in a * or ** will make it less strict. re = '^' + open + re + close + '$'; + // In partial mode, '/' should always match as it's a valid prefix for any pattern + if (this.partial) { + re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$'; + } // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').+$'; @@ -919,7 +1030,7 @@ class Minimatch { this.regexp = new RegExp(re, [...flags].join('')); /* c8 ignore start */ } - catch (ex) { + catch { // should be impossible this.regexp = false; } @@ -934,7 +1045,7 @@ class Minimatch { if (this.preserveMultipleSlashes) { return p.split('/'); } - else if (this.isWindows && /^\/\/[^\/]+/.test(p)) { + else if (this.isWindows && /^\/\/[^/]+/.test(p)) { // add an extra '' for the one we lose return ['', ...p.split(/\/+/)]; } @@ -976,8 +1087,7 @@ class Minimatch { filename = ff[i]; } } - for (let i = 0; i < set.length; i++) { - const pattern = set[i]; + for (const pattern of set) { let file = ff; if (options.matchBase && pattern.length === 1) { file = [filename]; diff --git a/node_modules/minimatch/dist/commonjs/unescape.js b/node_modules/minimatch/dist/commonjs/unescape.js index 47c36bcee5a02..ad648fba64d40 100644 --- a/node_modules/minimatch/dist/commonjs/unescape.js +++ b/node_modules/minimatch/dist/commonjs/unescape.js @@ -4,21 +4,35 @@ 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. + * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then + * square-bracket escapes are removed, but not backslash escapes. * - * When `windowsPathsNoEscape` is not set, then both brace escapes and + * 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 square-bracket escapes and * backslash escapes are removed. * * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped * or unescaped. + * + * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be + * unescaped. */ -const unescape = (s, { windowsPathsNoEscape = false, } = {}) => { - return windowsPathsNoEscape - ? s.replace(/\[([^\/\\])\]/g, '$1') - : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1'); +const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => { + if (magicalBraces) { + return windowsPathsNoEscape ? + s.replace(/\[([^/\\])\]/g, '$1') + : s + .replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2') + .replace(/\\([^/])/g, '$1'); + } + return windowsPathsNoEscape ? + s.replace(/\[([^/\\{}])\]/g, '$1') + : s + .replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2') + .replace(/\\([^/{}])/g, '$1'); }; exports.unescape = unescape; //# sourceMappingURL=unescape.js.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/esm/ast.js b/node_modules/minimatch/dist/esm/ast.js index 2d2bced6533de..f639546593db6 100644 --- a/node_modules/minimatch/dist/esm/ast.js +++ b/node_modules/minimatch/dist/esm/ast.js @@ -1,8 +1,110 @@ // parse a single path portion +var _a; import { parseClass } from './brace-expressions.js'; import { unescape } from './unescape.js'; const types = new Set(['!', '?', '+', '*', '@']); const isExtglobType = (c) => types.has(c); +const isExtglobAST = (c) => isExtglobType(c.type); +// Map of which extglob types can adopt the children of a nested extglob +// +// anything but ! can adopt a matching type: +// +(a|+(b|c)|d) => +(a|b|c|d) +// *(a|*(b|c)|d) => *(a|b|c|d) +// @(a|@(b|c)|d) => @(a|b|c|d) +// ?(a|?(b|c)|d) => ?(a|b|c|d) +// +// * can adopt anything, because 0 or repetition is allowed +// *(a|?(b|c)|d) => *(a|b|c|d) +// *(a|+(b|c)|d) => *(a|b|c|d) +// *(a|@(b|c)|d) => *(a|b|c|d) +// +// + can adopt @, because 1 or repetition is allowed +// +(a|@(b|c)|d) => +(a|b|c|d) +// +// + and @ CANNOT adopt *, because 0 would be allowed +// +(a|*(b|c)|d) => would match "", on *(b|c) +// @(a|*(b|c)|d) => would match "", on *(b|c) +// +// + and @ CANNOT adopt ?, because 0 would be allowed +// +(a|?(b|c)|d) => would match "", on ?(b|c) +// @(a|?(b|c)|d) => would match "", on ?(b|c) +// +// ? can adopt @, because 0 or 1 is allowed +// ?(a|@(b|c)|d) => ?(a|b|c|d) +// +// ? and @ CANNOT adopt * or +, because >1 would be allowed +// ?(a|*(b|c)|d) => would match bbb on *(b|c) +// @(a|*(b|c)|d) => would match bbb on *(b|c) +// ?(a|+(b|c)|d) => would match bbb on +(b|c) +// @(a|+(b|c)|d) => would match bbb on +(b|c) +// +// ! CANNOT adopt ! (nothing else can either) +// !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c) +// +// ! can adopt @ +// !(a|@(b|c)|d) => !(a|b|c|d) +// +// ! CANNOT adopt * +// !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed +// +// ! CANNOT adopt + +// !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed +// +// ! CANNOT adopt ? +// x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x" +const adoptionMap = new Map([ + ['!', ['@']], + ['?', ['?', '@']], + ['@', ['@']], + ['*', ['*', '+', '?', '@']], + ['+', ['+', '@']], +]); +// nested extglobs that can be adopted in, but with the addition of +// a blank '' element. +const adoptionWithSpaceMap = new Map([ + ['!', ['?']], + ['@', ['?']], + ['+', ['?', '*']], +]); +// union of the previous two maps +const adoptionAnyMap = new Map([ + ['!', ['?', '@']], + ['?', ['?', '@']], + ['@', ['?', '@']], + ['*', ['*', '+', '?', '@']], + ['+', ['+', '@', '?', '*']], +]); +// Extglobs that can take over their parent if they are the only child +// the key is parent, value maps child to resulting extglob parent type +// '@' is omitted because it's a special case. An `@` extglob with a single +// member can always be usurped by that subpattern. +const usurpMap = new Map([ + ['!', new Map([['!', '@']])], + [ + '?', + new Map([ + ['*', '*'], + ['+', '*'], + ]), + ], + [ + '@', + new Map([ + ['!', '!'], + ['?', '?'], + ['@', '@'], + ['*', '*'], + ['+', '+'], + ]), + ], + [ + '+', + new Map([ + ['?', '*'], + ['*', '*'], + ]), + ], +]); // 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. @@ -26,6 +128,7 @@ const star = qmark + '*?'; 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') +let ID = 0; export class AST { type; #root; @@ -41,6 +144,22 @@ export class AST { // set to true if it's an extglob with no children // (which really means one child of '') #emptyExt = false; + id = ++ID; + get depth() { + return (this.#parent?.depth ?? -1) + 1; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return { + '@@type': 'AST', + id: this.id, + type: this.type, + root: this.#root.id, + parent: this.#parent?.id, + depth: this.depth, + partsLength: this.#parts.length, + parts: this.#parts, + }; + } constructor(type, parent, options = {}) { this.type = type; // extglobs are inherently magical @@ -70,15 +189,14 @@ export class AST { } // 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('|') + ')'); - } + return (this.#toString !== undefined ? this.#toString + : !this.type ? + (this.#toString = this.#parts.map(p => String(p)).join('')) + : (this.#toString = + this.type + + '(' + + this.#parts.map(p => String(p)).join('|') + + ')')); } #fillNegs() { /* c8 ignore start */ @@ -119,7 +237,8 @@ export class AST { if (p === '') continue; /* c8 ignore start */ - if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) { + if (typeof p !== 'string' && + !(p instanceof _a && p.#parent === this)) { throw new Error('invalid part: ' + p); } /* c8 ignore stop */ @@ -127,8 +246,10 @@ export class AST { } } toJSON() { - const ret = this.type === null - ? this.#parts.slice().map(p => (typeof p === 'string' ? p : 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([]); @@ -151,7 +272,7 @@ export class AST { const p = this.#parent; for (let i = 0; i < this.#parentIndex; i++) { const pp = p.#parts[i]; - if (!(pp instanceof AST && pp.type === '!')) { + if (!(pp instanceof _a && pp.type === '!')) { return false; } } @@ -179,13 +300,14 @@ export class AST { this.push(part.clone(this)); } clone(parent) { - const c = new AST(this.type, parent); + const c = new _a(this.type, parent); for (const p of this.#parts) { c.copyIn(p); } return c; } - static #parseAST(str, ast, pos, opt) { + static #parseAST(str, ast, pos, opt, extDepth) { + const maxDepth = opt.maxExtglobRecursion ?? 2; let escaping = false; let inBrace = false; let braceStart = -1; @@ -222,11 +344,17 @@ export class AST { acc += c; continue; } - if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') { + // we don't have to check for adoption here, because that's + // done at the other recursion point. + const doRecurse = !opt.noext && + isExtglobType(c) && + str.charAt(i) === '(' && + extDepth <= maxDepth; + if (doRecurse) { ast.push(acc); acc = ''; - const ext = new AST(c, ast); - i = AST.#parseAST(str, ext, i, opt); + const ext = new _a(c, ast); + i = _a.#parseAST(str, ext, i, opt, extDepth + 1); ast.push(ext); continue; } @@ -238,7 +366,7 @@ export class AST { // some kind of extglob, pos is at the ( // find the next | or ) let i = pos + 1; - let part = new AST(null, ast); + let part = new _a(null, ast); const parts = []; let acc = ''; while (i < str.length) { @@ -269,19 +397,26 @@ export class AST { acc += c; continue; } - if (isExtglobType(c) && str.charAt(i) === '(') { + const doRecurse = !opt.noext && + isExtglobType(c) && + str.charAt(i) === '(' && + /* c8 ignore start - the maxDepth is sufficient here */ + (extDepth <= maxDepth || (ast && ast.#canAdoptType(c))); + /* c8 ignore stop */ + if (doRecurse) { + const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1; part.push(acc); acc = ''; - const ext = new AST(c, part); + const ext = new _a(c, part); part.push(ext); - i = AST.#parseAST(str, ext, i, opt); + i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd); continue; } if (c === '|') { part.push(acc); acc = ''; parts.push(part); - part = new AST(null, ast); + part = new _a(null, ast); continue; } if (c === ')') { @@ -303,9 +438,82 @@ export class AST { ast.#parts = [str.substring(pos - 1)]; return i; } + #canAdoptWithSpace(child) { + return this.#canAdopt(child, adoptionWithSpaceMap); + } + #canAdopt(child, map = adoptionMap) { + if (!child || + typeof child !== 'object' || + child.type !== null || + child.#parts.length !== 1 || + this.type === null) { + return false; + } + const gc = child.#parts[0]; + if (!gc || typeof gc !== 'object' || gc.type === null) { + return false; + } + return this.#canAdoptType(gc.type, map); + } + #canAdoptType(c, map = adoptionAnyMap) { + return !!map.get(this.type)?.includes(c); + } + #adoptWithSpace(child, index) { + const gc = child.#parts[0]; + const blank = new _a(null, gc, this.options); + blank.#parts.push(''); + gc.push(blank); + this.#adopt(child, index); + } + #adopt(child, index) { + const gc = child.#parts[0]; + this.#parts.splice(index, 1, ...gc.#parts); + for (const p of gc.#parts) { + if (typeof p === 'object') + p.#parent = this; + } + this.#toString = undefined; + } + #canUsurpType(c) { + const m = usurpMap.get(this.type); + return !!m?.has(c); + } + #canUsurp(child) { + if (!child || + typeof child !== 'object' || + child.type !== null || + child.#parts.length !== 1 || + this.type === null || + this.#parts.length !== 1) { + return false; + } + const gc = child.#parts[0]; + if (!gc || typeof gc !== 'object' || gc.type === null) { + return false; + } + return this.#canUsurpType(gc.type); + } + #usurp(child) { + const m = usurpMap.get(this.type); + const gc = child.#parts[0]; + const nt = m?.get(gc.type); + /* c8 ignore start - impossible */ + if (!nt) + return false; + /* c8 ignore stop */ + this.#parts = gc.#parts; + for (const p of this.#parts) { + if (typeof p === 'object') { + p.#parent = this; + } + } + this.type = nt; + this.#toString = undefined; + this.#emptyExt = false; + } static fromGlob(pattern, options = {}) { - const ast = new AST(null, undefined, options); - AST.#parseAST(pattern, ast, 0, options); + const ast = new _a(null, undefined, options); + _a.#parseAST(pattern, ast, 0, options, 0); return ast; } // returns the regular expression if there's magic, or the unescaped @@ -409,14 +617,18 @@ export class AST { // or start or whatever) and prepend ^ or / at the Regexp construction. toRegExpSource(allowDot) { const dot = allowDot ?? !!this.#options.dot; - if (this.#root === this) + if (this.#root === this) { + this.#flatten(); this.#fillNegs(); - if (!this.type) { - const noEmpty = this.isStart() && this.isEnd(); + } + if (!isExtglobAST(this)) { + const noEmpty = this.isStart() && + this.isEnd() && + !this.#parts.some(s => typeof s !== 'string'); const src = this.#parts .map(p => { - const [re, _, hasMagic, uflag] = typeof p === 'string' - ? AST.#parseGlob(p, this.#hasMagic, noEmpty) + const [re, _, hasMagic, uflag] = typeof p === 'string' ? + _a.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot); this.#hasMagic = this.#hasMagic || hasMagic; this.#uflag = this.#uflag || uflag; @@ -445,7 +657,10 @@ export class AST { // 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 : ''; + start = + needNoTrav ? startNoTraversal + : needNoDot ? startNoDot + : ''; } } } @@ -475,14 +690,14 @@ export class AST { // 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; + const me = this; + me.#parts = [s]; + me.type = null; + me.#hasMagic = undefined; return [s, unescape(this.toString()), false, false]; } - // XXX abstract out this map method - let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot - ? '' + let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? + '' : this.#partsToRegExp(true); if (bodyDotAllowed === body) { bodyDotAllowed = ''; @@ -496,20 +711,16 @@ export class AST { 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 - ? `)?` + 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; } @@ -520,6 +731,42 @@ export class AST { this.#uflag, ]; } + #flatten() { + if (!isExtglobAST(this)) { + for (const p of this.#parts) { + if (typeof p === 'object') { + p.#flatten(); + } + } + } + else { + // do up to 10 passes to flatten as much as possible + let iterations = 0; + let done = false; + do { + done = true; + for (let i = 0; i < this.#parts.length; i++) { + const c = this.#parts[i]; + if (typeof c === 'object') { + c.#flatten(); + if (this.#canAdopt(c)) { + done = false; + this.#adopt(c, i); + } + else if (this.#canAdoptWithSpace(c)) { + done = false; + this.#adoptWithSpace(c, i); + } + else if (this.#canUsurp(c)) { + done = false; + this.#usurp(c); + } + } + } + } while (!done && ++iterations < 10); + } + this.#toString = undefined; + } #partsToRegExp(dot) { return this.#parts .map(p => { @@ -541,6 +788,8 @@ export class AST { let escaping = false; let re = ''; let uflag = false; + // multiple stars that aren't globstars coalesce into one * + let inStar = false; for (let i = 0; i < glob.length; i++) { const c = glob.charAt(i); if (escaping) { @@ -548,6 +797,17 @@ export class AST { re += (reSpecials.has(c) ? '\\' : '') + c; continue; } + if (c === '*') { + if (inStar) + continue; + inStar = true; + re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star; + hasMagic = true; + continue; + } + else { + inStar = false; + } if (c === '\\') { if (i === glob.length - 1) { re += '\\\\'; @@ -567,14 +827,6 @@ export class AST { continue; } } - if (c === '*') { - if (noEmpty && glob === '*') - re += starNoEmpty; - else - re += star; - hasMagic = true; - continue; - } if (c === '?') { re += qmark; hasMagic = true; @@ -585,4 +837,5 @@ export class AST { return [re, unescape(glob), !!hasMagic, uflag]; } } +_a = AST; //# sourceMappingURL=ast.js.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/esm/brace-expressions.js b/node_modules/minimatch/dist/esm/brace-expressions.js index c629d6ae816e2..4b49d40bd7421 100644 --- a/node_modules/minimatch/dist/esm/brace-expressions.js +++ b/node_modules/minimatch/dist/esm/brace-expressions.js @@ -138,10 +138,8 @@ export const parseClass = (glob, position) => { } const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'; const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'; - const comb = ranges.length && negs.length - ? '(' + sranges + '|' + snegs + ')' - : ranges.length - ? sranges + const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')' + : ranges.length ? sranges : snegs; return [comb, uflag, endPos - pos, true]; }; diff --git a/node_modules/minimatch/dist/esm/escape.js b/node_modules/minimatch/dist/esm/escape.js index 16f7c8c7bdc64..46d0ec8858e5b 100644 --- a/node_modules/minimatch/dist/esm/escape.js +++ b/node_modules/minimatch/dist/esm/escape.js @@ -1,18 +1,26 @@ /** * Escape all magic characters in a glob pattern. * - * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape} + * If the {@link MinimatchOptions.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. + * + * If the {@link MinimatchOptions.magicalBraces} option is used, + * then braces (`{` and `}`) will be escaped. */ -export const escape = (s, { windowsPathsNoEscape = false, } = {}) => { +export const escape = (s, { windowsPathsNoEscape = false, magicalBraces = 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, '[$&]') + if (magicalBraces) { + return windowsPathsNoEscape ? + s.replace(/[?*()[\]{}]/g, '[$&]') + : s.replace(/[?*()[\]\\{}]/g, '\\$&'); + } + return windowsPathsNoEscape ? + s.replace(/[?*()[\]]/g, '[$&]') : s.replace(/[?*()[\]\\]/g, '\\$&'); }; //# sourceMappingURL=escape.js.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/esm/index.js b/node_modules/minimatch/dist/esm/index.js index 84b577b0472cb..a5e6fa88fdc6d 100644 --- a/node_modules/minimatch/dist/esm/index.js +++ b/node_modules/minimatch/dist/esm/index.js @@ -1,4 +1,4 @@ -import expand from 'brace-expansion'; +import { expand } from 'brace-expansion'; import { assertValidPattern } from './assert-valid-pattern.js'; import { AST } from './ast.js'; import { escape } from './escape.js'; @@ -12,7 +12,7 @@ export const minimatch = (p, pattern, options = {}) => { return new Minimatch(pattern, options).match(p); }; // Optimized checking for the most common glob patterns. -const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; +const starDotExtRE = /^\*+([^+@!?*[(]*)$/; const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext); const starDotExtTestDot = (ext) => (f) => f.endsWith(ext); const starDotExtTestNocase = (ext) => { @@ -31,7 +31,7 @@ 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 qmarksRE = /^\?+([^+@!?*[(]*)?$/; const qmarksTestNocase = ([$0, ext = '']) => { const noext = qmarksTestNoExt([$0]); if (!ext) @@ -63,8 +63,8 @@ const qmarksTestNoExtDot = ([$0]) => { return (f) => f.length === len && f !== '.' && f !== '..'; }; /* c8 ignore start */ -const defaultPlatform = (typeof process === 'object' && process - ? (typeof process.env === 'object' && +const defaultPlatform = (typeof process === 'object' && process ? + (typeof process.env === 'object' && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__) || process.platform @@ -148,7 +148,7 @@ export const braceExpand = (pattern, options = {}) => { // shortcut. no need to expand. return [pattern]; } - return expand(pattern); + return expand(pattern, { max: options.braceExpandMax }); }; minimatch.braceExpand = braceExpand; // parse a component of the expanded set. @@ -193,16 +193,20 @@ export class Minimatch { isWindows; platform; windowsNoMagicRoot; + maxGlobstarRecursion; regexp; constructor(pattern, options = {}) { assertValidPattern(pattern); options = options || {}; this.options = options; + this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200; this.pattern = pattern; this.platform = options.platform || defaultPlatform; this.isWindows = this.platform === 'win32'; + // avoid the annoying deprecation flag lol + const awe = ('allowWindow' + 'sEscape'); this.windowsPathsNoEscape = - !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; + !!options.windowsPathsNoEscape || options[awe] === false; if (this.windowsPathsNoEscape) { this.pattern = this.pattern.replace(/\\/g, '/'); } @@ -215,8 +219,8 @@ export class Minimatch { this.partial = !!options.partial; this.nocase = !!this.options.nocase; this.windowsNoMagicRoot = - options.windowsNoMagicRoot !== undefined - ? options.windowsNoMagicRoot + options.windowsNoMagicRoot !== undefined ? + options.windowsNoMagicRoot : !!(this.isWindows && this.nocase); this.globSet = []; this.globParts = []; @@ -254,6 +258,7 @@ export class Minimatch { // step 2: expand braces this.globSet = [...new Set(this.braceExpand())]; if (options.debug) { + //oxlint-disable-next-line no-console this.debug = (...args) => console.error(...args); } this.debug(this.pattern, this.globSet); @@ -279,7 +284,10 @@ export class Minimatch { !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))]; + 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))]; @@ -311,12 +319,12 @@ export class Minimatch { // 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 we're not in globstar mode, then turn ** 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] = '*'; + for (const partset of globParts) { + for (let j = 0; j < partset.length; j++) { + if (partset[j] === '**') { + partset[j] = '*'; } } } @@ -404,7 +412,11 @@ export class Minimatch { let dd = 0; while (-1 !== (dd = parts.indexOf('..', dd + 1))) { const p = parts[dd - 1]; - if (p && p !== '.' && p !== '..' && p !== '**') { + if (p && + p !== '.' && + p !== '..' && + p !== '**' && + !(this.isWindows && /^[a-z]:$/i.test(p))) { didSomething = true; parts.splice(dd - 1, 2); dd -= 2; @@ -597,7 +609,8 @@ export class Minimatch { // out of pattern, then that's fine, as long as all // the parts match. matchOne(file, pattern, partial = false) { - const options = this.options; + let fileStartIndex = 0; + let patternStartIndex = 0; // UNC paths like //?/X:/... can match X:/... and vice versa // Drive letters in absolute drive or unc paths are always compared // case-insensitively. @@ -615,120 +628,212 @@ export class Minimatch { 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; + 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]]; + const [fd, pd] = [ + file[fdi], + pattern[pdi], + ]; + // start matching at the drive letter index of each if (fd.toLowerCase() === pd.toLowerCase()) { pattern[pdi] = fd; - if (pdi > fdi) { - pattern = pattern.slice(pdi); - } - else if (fdi > pdi) { - file = file.slice(fdi); - } + patternStartIndex = pdi; + fileStartIndex = fdi; } } } // resolve and reduce . and .. portions in the file as well. - // dont' need to do the second phase, because it's only one string[] + // don't 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++) { + if (pattern.includes(GLOBSTAR)) { + return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex); + } + return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex); + } + #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) { + // split the pattern into head, tail, and middle of ** delimited parts + const firstgs = pattern.indexOf(GLOBSTAR, patternIndex); + const lastgs = pattern.lastIndexOf(GLOBSTAR); + // split the pattern up into globstar-delimited sections + // the tail has to be at the end, and the others just have + // to be found in order from the head. + const [head, body, tail] = partial ? + [ + pattern.slice(patternIndex, firstgs), + pattern.slice(firstgs + 1), + [], + ] + : [ + pattern.slice(patternIndex, firstgs), + pattern.slice(firstgs + 1, lastgs), + pattern.slice(lastgs + 1), + ]; + // check the head, from the current file/pattern index. + if (head.length) { + const fileHead = file.slice(fileIndex, fileIndex + head.length); + if (!this.#matchOne(fileHead, head, partial, 0, 0)) { + return false; + } + fileIndex += head.length; + patternIndex += head.length; + } + // now we know the head matches! + // if the last portion is not empty, it MUST match the end + // check the tail + let fileTailMatch = 0; + if (tail.length) { + // if head + tail > file, then we cannot possibly match + if (tail.length + fileIndex > file.length) + return false; + // try to match the tail + let tailStart = file.length - tail.length; + if (this.#matchOne(file, tail, partial, tailStart, 0)) { + fileTailMatch = tail.length; + } + else { + // affordance for stuff like a/**/* matching a/b/ + // if the last file portion is '', and there's more to the pattern + // then try without the '' bit. + if (file[file.length - 1] !== '' || + fileIndex + tail.length === file.length) { + return false; + } + tailStart--; + if (!this.#matchOne(file, tail, partial, tailStart, 0)) { + return false; + } + fileTailMatch = tail.length + 1; + } + } + // now we know the tail matches! + // the middle is zero or more portions wrapped in **, possibly + // containing more ** sections. + // so a/**/b/**/c/**/d has become **/b/**/c/** + // if it's empty, it means a/**/b, just verify we have no bad dots + // if there's no tail, so it ends on /**, then we must have *something* + // after the head, or it's not a matc + if (!body.length) { + let sawSome = !!fileTailMatch; + for (let i = fileIndex; i < file.length - fileTailMatch; i++) { + const f = String(file[i]); + sawSome = true; + if (f === '.' || + f === '..' || + (!this.options.dot && f.startsWith('.'))) { + return false; + } + } + // in partial mode, we just need to get past all file parts + return partial || sawSome; + } + // now we know that there's one or more body sections, which can + // be matched anywhere from the 0 index (because the head was pruned) + // through to the length-fileTailMatch index. + // split the body up into sections, and note the minimum index it can + // be found at (start with the length of all previous segments) + // [section, before, after] + const bodySegments = [[[], 0]]; + let currentBody = bodySegments[0]; + let nonGsParts = 0; + const nonGsPartsSums = [0]; + for (const b of body) { + if (b === GLOBSTAR) { + nonGsPartsSums.push(nonGsParts); + currentBody = [[], 0]; + bodySegments.push(currentBody); + } + else { + currentBody[0].push(b); + nonGsParts++; + } + } + let i = bodySegments.length - 1; + const fileLength = file.length - fileTailMatch; + for (const b of bodySegments) { + b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length); + } + return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch); + } + // return false for "nope, not matching" + // return null for "not matching, cannot keep trying" + #matchGlobStarBodySections(file, + // pattern section, last possible position for it + bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) { + // take the first body segment, and walk from fileIndex to its "after" + // value at the end + // If it doesn't match at that position, we increment, until we hit + // that final possible position, and give up. + // If it does match, then advance and try to rest. + // If any of them fail we keep walking forward. + // this is still a bit recursively painful, but it's more constrained + // than previous implementations, because we never test something that + // can't possibly be a valid matching condition. + const bs = bodySegments[bodyIndex]; + if (!bs) { + // just make sure that there's no bad dots + for (let i = fileIndex; i < file.length; i++) { + sawTail = true; + const f = file[i]; + if (f === '.' || + f === '..' || + (!this.options.dot && f.startsWith('.'))) { + return false; + } + } + return sawTail; + } + // have a non-globstar body section to test + const [body, after] = bs; + while (fileIndex <= after) { + const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0); + // if limit exceeded, no match. intentional false negative, + // acceptable break in correctness for security. + if (m && globStarDepth < this.maxGlobstarRecursion) { + // match! see if the rest match. if so, we're done! + const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail); + if (sub !== false) { + return sub; + } + } + const f = file[fileIndex]; + if (f === '.' || + f === '..' || + (!this.options.dot && f.startsWith('.'))) { + return false; + } + fileIndex++; + } + // walked off. no point continuing + return partial || null; + } + #matchOne(file, pattern, partial, fileIndex, patternIndex) { + let fi; + let pi; + let pl; + let fl; + for (fi = fileIndex, + pi = patternIndex, + fl = file.length, + pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { this.debug('matchOne loop'); - var p = pattern[pi]; - var f = file[fi]; + let p = pattern[pi]; + let f = file[fi]; this.debug(pattern, p, f); // should be impossible. // some invalid regexp stuff in the set. /* c8 ignore start */ - if (p === false) { + if (p === false || p === GLOBSTAR) { 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. @@ -799,21 +904,19 @@ export class Minimatch { fastTest = options.dot ? starTestDot : starTest; } else if ((m = pattern.match(starDotExtRE))) { - fastTest = (options.nocase - ? options.dot - ? starDotExtTestNocaseDot + fastTest = (options.nocase ? + options.dot ? + starDotExtTestNocaseDot : starDotExtTestNocase - : options.dot - ? starDotExtTestDot + : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]); } else if ((m = pattern.match(qmarksRE))) { - fastTest = (options.nocase - ? options.dot - ? qmarksTestNocaseDot + fastTest = (options.nocase ? + options.dot ? + qmarksTestNocaseDot : qmarksTestNocase - : options.dot - ? qmarksTestDot + : options.dot ? qmarksTestDot : qmarksTest)(m); } else if ((m = pattern.match(starDotStarRE))) { @@ -844,10 +947,8 @@ export class Minimatch { return this.regexp; } const options = this.options; - const twoStar = options.noglobstar - ? star - : options.dot - ? twoStarDot + const twoStar = options.noglobstar ? star + : options.dot ? twoStarDot : twoStarNoDot; const flags = new Set(options.nocase ? ['i'] : []); // regexpify non-globstar patterns @@ -863,11 +964,9 @@ export class Minimatch { for (const f of p.flags.split('')) flags.add(f); } - return typeof p === 'string' - ? regExpEscape(p) - : p === GLOBSTAR - ? GLOBSTAR - : p._src; + return (typeof p === 'string' ? regExpEscape(p) + : p === GLOBSTAR ? GLOBSTAR + : p._src); }); pp.forEach((p, i) => { const next = pp[i + 1]; @@ -884,14 +983,25 @@ export class Minimatch { } } else if (next === undefined) { - pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?'; + 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('/'); + const filtered = pp.filter(p => p !== GLOBSTAR); + // For partial matches, we need to make the pattern match + // any prefix of the full path. We do this by generating + // alternative patterns that match progressively longer prefixes. + if (this.partial && filtered.length >= 1) { + const prefixes = []; + for (let i = 1; i <= filtered.length; i++) { + prefixes.push(filtered.slice(0, i).join('/')); + } + return '(?:' + prefixes.join('|') + ')'; + } + return filtered.join('/'); }) .join('|'); // need to wrap in parens if we had more than one thing with |, @@ -900,6 +1010,10 @@ export class Minimatch { // must match entire pattern // ending in a * or ** will make it less strict. re = '^' + open + re + close + '$'; + // In partial mode, '/' should always match as it's a valid prefix for any pattern + if (this.partial) { + re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$'; + } // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').+$'; @@ -907,7 +1021,7 @@ export class Minimatch { this.regexp = new RegExp(re, [...flags].join('')); /* c8 ignore start */ } - catch (ex) { + catch { // should be impossible this.regexp = false; } @@ -922,7 +1036,7 @@ export class Minimatch { if (this.preserveMultipleSlashes) { return p.split('/'); } - else if (this.isWindows && /^\/\/[^\/]+/.test(p)) { + else if (this.isWindows && /^\/\/[^/]+/.test(p)) { // add an extra '' for the one we lose return ['', ...p.split(/\/+/)]; } @@ -964,8 +1078,7 @@ export class Minimatch { filename = ff[i]; } } - for (let i = 0; i < set.length; i++) { - const pattern = set[i]; + for (const pattern of set) { let file = ff; if (options.matchBase && pattern.length === 1) { file = [filename]; diff --git a/node_modules/minimatch/dist/esm/unescape.js b/node_modules/minimatch/dist/esm/unescape.js index 0faf9a2b7306f..19ce86e7c8605 100644 --- a/node_modules/minimatch/dist/esm/unescape.js +++ b/node_modules/minimatch/dist/esm/unescape.js @@ -1,20 +1,34 @@ /** * 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. + * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then + * square-bracket escapes are removed, but not backslash escapes. * - * When `windowsPathsNoEscape` is not set, then both brace escapes and + * 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 square-bracket escapes and * backslash escapes are removed. * * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped * or unescaped. + * + * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be + * unescaped. */ -export const unescape = (s, { windowsPathsNoEscape = false, } = {}) => { - return windowsPathsNoEscape - ? s.replace(/\[([^\/\\])\]/g, '$1') - : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1'); +export const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => { + if (magicalBraces) { + return windowsPathsNoEscape ? + s.replace(/\[([^/\\])\]/g, '$1') + : s + .replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2') + .replace(/\\([^/])/g, '$1'); + } + return windowsPathsNoEscape ? + s.replace(/\[([^/\\{}])\]/g, '$1') + : s + .replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2') + .replace(/\\([^/{}])/g, '$1'); }; //# sourceMappingURL=unescape.js.map \ No newline at end of file diff --git a/node_modules/minimatch/package.json b/node_modules/minimatch/package.json index 01fc48ecfd6a9..211875c62b724 100644 --- a/node_modules/minimatch/package.json +++ b/node_modules/minimatch/package.json @@ -2,10 +2,10 @@ "author": "Isaac Z. Schlueter (http://blog.izs.me)", "name": "minimatch", "description": "a glob matcher in javascript", - "version": "9.0.5", + "version": "10.2.5", "repository": { "type": "git", - "url": "git://github.com/isaacs/minimatch.git" + "url": "git@github.com:isaacs/minimatch" }, "main": "./dist/commonjs/index.js", "types": "./dist/commonjs/index.d.ts", @@ -34,49 +34,40 @@ "presnap": "npm run prepare", "test": "tap", "snap": "tap", - "format": "prettier --write . --loglevel warn", + "format": "prettier --write .", "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" + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts", + "lint": "oxlint --fix src test", + "postsnap": "npm run lint", + "postlint": "npm run format" }, "engines": { - "node": ">=16 || 14 >=14.17" - }, - "dependencies": { - "brace-expansion": "^2.0.1" + "node": "18 || 20 || >=22" }, "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" + "@types/node": "^25.5.0", + "mkdirp": "^3.0.1", + "oxlint": "^1.57.0", + "oxlint-tsgolint": "^0.18.1", + "prettier": "^3.8.1", + "tap": "^21.6.2", + "tshy": "^4.0.0", + "typedoc": "^0.28.18" }, "funding": { "url": "https://github.com/sponsors/isaacs" }, - "license": "ISC", + "license": "BlueOak-1.0.0", "tshy": { "exports": { "./package.json": "./package.json", ".": "./src/index.ts" - } + }, + "selfLink": false }, - "type": "module" + "type": "module", + "module": "./dist/esm/index.js", + "dependencies": { + "brace-expansion": "^5.0.5" + } } diff --git a/node_modules/minipass-fetch/lib/body.js b/node_modules/minipass-fetch/lib/body.js deleted file mode 100644 index 62286bd1de0d9..0000000000000 --- a/node_modules/minipass-fetch/lib/body.js +++ /dev/null @@ -1,350 +0,0 @@ -'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 = / { - 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 diff --git a/node_modules/minipass-fetch/package.json b/node_modules/minipass-fetch/package.json deleted file mode 100644 index d491a7fba126d..0000000000000 --- a/node_modules/minipass-fetch/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "name": "minipass-fetch", - "version": "3.0.5", - "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": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" - }, - "tap": { - "coverage-map": "map.js", - "check-coverage": true, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "@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": "^2.1.2" - }, - "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": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "author": "GitHub Inc.", - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": "true" - } -} diff --git a/node_modules/minipass-flush/LICENSE b/node_modules/minipass-flush/LICENSE deleted file mode 100644 index 19129e315fe59..0000000000000 --- a/node_modules/minipass-flush/LICENSE +++ /dev/null @@ -1,15 +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. diff --git a/node_modules/minipass-flush/LICENSE.md b/node_modules/minipass-flush/LICENSE.md new file mode 100644 index 0000000000000..c5402b9577a8c --- /dev/null +++ b/node_modules/minipass-flush/LICENSE.md @@ -0,0 +1,55 @@ +# 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.*** diff --git a/node_modules/minipass-flush/index.js b/node_modules/minipass-flush/index.js index cb2537fa6b2b5..f435f5d7fde51 100644 --- a/node_modules/minipass-flush/index.js +++ b/node_modules/minipass-flush/index.js @@ -1,4 +1,4 @@ -const Minipass = require('minipass') +const { Minipass } = require('minipass') const _flush = Symbol('_flush') const _flushed = Symbol('_flushed') const _flushing = Symbol('_flushing') diff --git a/node_modules/minipass-flush/node_modules/minipass/LICENSE b/node_modules/minipass-flush/node_modules/minipass/LICENSE deleted file mode 100644 index bf1dece2e1f12..0000000000000 --- a/node_modules/minipass-flush/node_modules/minipass/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/minipass-flush/node_modules/minipass/index.js b/node_modules/minipass-flush/node_modules/minipass/index.js deleted file mode 100644 index e8797aab6cc27..0000000000000 --- a/node_modules/minipass-flush/node_modules/minipass/index.js +++ /dev/null @@ -1,649 +0,0 @@ -'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 - )) - } -} diff --git a/node_modules/minipass-flush/node_modules/minipass/package.json b/node_modules/minipass-flush/node_modules/minipass/package.json deleted file mode 100644 index 548d03fa6d5d4..0000000000000 --- a/node_modules/minipass-flush/node_modules/minipass/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/minipass-flush/package.json b/node_modules/minipass-flush/package.json index 09127d0ec2015..f4608a0c365b1 100644 --- a/node_modules/minipass-flush/package.json +++ b/node_modules/minipass-flush/package.json @@ -1,9 +1,9 @@ { "name": "minipass-flush", - "version": "1.0.5", + "version": "1.0.6", "description": "A Minipass stream that calls a flush function before emitting 'end'", "author": "Isaac Z. Schlueter (https://izs.me)", - "license": "ISC", + "license": "BlueOak-1.0.0", "scripts": { "test": "tap", "snap": "tap", @@ -15,10 +15,10 @@ "check-coverage": true }, "devDependencies": { - "tap": "^14.6.9" + "tap": "^15.1.6" }, "dependencies": { - "minipass": "^3.0.0" + "minipass": "^7.1.3" }, "files": [ "index.js" @@ -34,6 +34,6 @@ "stream" ], "engines": { - "node": ">= 8" + "node": ">=16 || 14 >=14.17" } } diff --git a/node_modules/cross-spawn/node_modules/which/LICENSE b/node_modules/minipass-pipeline/node_modules/yallist/LICENSE similarity index 100% rename from node_modules/cross-spawn/node_modules/which/LICENSE rename to node_modules/minipass-pipeline/node_modules/yallist/LICENSE diff --git a/node_modules/yallist/iterator.js b/node_modules/minipass-pipeline/node_modules/yallist/iterator.js similarity index 100% rename from node_modules/yallist/iterator.js rename to node_modules/minipass-pipeline/node_modules/yallist/iterator.js diff --git a/node_modules/minipass-pipeline/node_modules/yallist/package.json b/node_modules/minipass-pipeline/node_modules/yallist/package.json new file mode 100644 index 0000000000000..8a083867d72e0 --- /dev/null +++ b/node_modules/minipass-pipeline/node_modules/yallist/package.json @@ -0,0 +1,29 @@ +{ + "name": "yallist", + "version": "4.0.0", + "description": "Yet Another Linked List", + "main": "yallist.js", + "directories": { + "test": "test" + }, + "files": [ + "yallist.js", + "iterator.js" + ], + "dependencies": {}, + "devDependencies": { + "tap": "^12.1.0" + }, + "scripts": { + "test": "tap test/*.js --100", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/yallist.git" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC" +} diff --git a/node_modules/yallist/yallist.js b/node_modules/minipass-pipeline/node_modules/yallist/yallist.js similarity index 100% rename from node_modules/yallist/yallist.js rename to node_modules/minipass-pipeline/node_modules/yallist/yallist.js diff --git a/node_modules/minipass-sized/dist/commonjs/index.js b/node_modules/minipass-sized/dist/commonjs/index.js new file mode 100644 index 0000000000000..fbf76406d60d9 --- /dev/null +++ b/node_modules/minipass-sized/dist/commonjs/index.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MinipassSized = exports.SizeError = void 0; +const minipass_1 = require("minipass"); +const isBufferEncoding = (enc) => typeof enc === 'string'; +class SizeError extends Error { + expect; + found; + code = 'EBADSIZE'; + constructor(found, expect, from) { + super(`Bad data size: expected ${expect} bytes, but got ${found}`); + this.expect = expect; + this.found = found; + Error.captureStackTrace(this, from ?? this.constructor); + } + get name() { + return 'SizeError'; + } +} +exports.SizeError = SizeError; +class MinipassSized extends minipass_1.Minipass { + found = 0; + expect; + constructor(options) { + const size = options?.size; + if (typeof size !== 'number' || + size > Number.MAX_SAFE_INTEGER || + isNaN(size) || + size < 0 || + !isFinite(size) || + size !== Math.floor(size)) { + throw new Error('invalid expected size: ' + size); + } + //@ts-ignore + super(options); + if (options.objectMode) { + throw new TypeError(`${this.constructor.name} streams only work with string and buffer data`); + } + this.expect = size; + } + write(chunk, encoding, cb) { + const buffer = Buffer.isBuffer(chunk) ? chunk + : typeof chunk === 'string' ? + Buffer.from(chunk, isBufferEncoding(encoding) ? encoding : 'utf8') + : chunk; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + 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, ...args) { + if (ev === 'end') { + if (this.found !== this.expect) { + this.emit('error', new SizeError(this.found, this.expect, this.emit)); + } + } + return super.emit(ev, ...args); + } +} +exports.MinipassSized = MinipassSized; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/minipass-sized/dist/commonjs/package.json b/node_modules/minipass-sized/dist/commonjs/package.json new file mode 100644 index 0000000000000..5bbefffbabee3 --- /dev/null +++ b/node_modules/minipass-sized/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/minipass-sized/dist/esm/index.js b/node_modules/minipass-sized/dist/esm/index.js new file mode 100644 index 0000000000000..69ed1846aa969 --- /dev/null +++ b/node_modules/minipass-sized/dist/esm/index.js @@ -0,0 +1,64 @@ +import { Minipass } from 'minipass'; +const isBufferEncoding = (enc) => typeof enc === 'string'; +export class SizeError extends Error { + expect; + found; + code = 'EBADSIZE'; + constructor(found, expect, from) { + super(`Bad data size: expected ${expect} bytes, but got ${found}`); + this.expect = expect; + this.found = found; + Error.captureStackTrace(this, from ?? this.constructor); + } + get name() { + return 'SizeError'; + } +} +export class MinipassSized extends Minipass { + found = 0; + expect; + constructor(options) { + const size = options?.size; + if (typeof size !== 'number' || + size > Number.MAX_SAFE_INTEGER || + isNaN(size) || + size < 0 || + !isFinite(size) || + size !== Math.floor(size)) { + throw new Error('invalid expected size: ' + size); + } + //@ts-ignore + super(options); + if (options.objectMode) { + throw new TypeError(`${this.constructor.name} streams only work with string and buffer data`); + } + this.expect = size; + } + write(chunk, encoding, cb) { + const buffer = Buffer.isBuffer(chunk) ? chunk + : typeof chunk === 'string' ? + Buffer.from(chunk, isBufferEncoding(encoding) ? encoding : 'utf8') + : chunk; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + 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, ...args) { + if (ev === 'end') { + if (this.found !== this.expect) { + this.emit('error', new SizeError(this.found, this.expect, this.emit)); + } + } + return super.emit(ev, ...args); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/minipass-sized/dist/esm/package.json b/node_modules/minipass-sized/dist/esm/package.json new file mode 100644 index 0000000000000..3dbc1ca591c05 --- /dev/null +++ b/node_modules/minipass-sized/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/minipass-sized/index.js b/node_modules/minipass-sized/index.js deleted file mode 100644 index a0c8acde487fc..0000000000000 --- a/node_modules/minipass-sized/index.js +++ /dev/null @@ -1,67 +0,0 @@ -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 diff --git a/node_modules/minipass-sized/node_modules/minipass/LICENSE b/node_modules/minipass-sized/node_modules/minipass/LICENSE deleted file mode 100644 index bf1dece2e1f12..0000000000000 --- a/node_modules/minipass-sized/node_modules/minipass/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/minipass-sized/node_modules/minipass/index.js b/node_modules/minipass-sized/node_modules/minipass/index.js deleted file mode 100644 index e8797aab6cc27..0000000000000 --- a/node_modules/minipass-sized/node_modules/minipass/index.js +++ /dev/null @@ -1,649 +0,0 @@ -'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 - )) - } -} diff --git a/node_modules/minipass-sized/node_modules/minipass/package.json b/node_modules/minipass-sized/node_modules/minipass/package.json deleted file mode 100644 index 548d03fa6d5d4..0000000000000 --- a/node_modules/minipass-sized/node_modules/minipass/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/minipass-sized/package.json b/node_modules/minipass-sized/package.json index a3257fd8f673a..e1160104dc5ec 100644 --- a/node_modules/minipass-sized/package.json +++ b/node_modules/minipass-sized/package.json @@ -1,26 +1,34 @@ { "name": "minipass-sized", - "version": "1.0.3", + "version": "2.0.0", "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", + "files": [ + "dist" + ], "scripts": { "test": "tap", "snap": "tap", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "prepare": "tshy", "preversion": "npm test", "postversion": "npm publish", - "postpublish": "git push origin --follow-tags" - }, - "tap": { - "check-coverage": true + "prepublishOnly": "git push origin --follow-tags", + "format": "prettier --write . --log-level warn", + "typedoc": "typedoc" }, "devDependencies": { - "tap": "^14.6.4" + "prettier": "^3.7.4", + "tap": "^21.5.0", + "tshy": "^3.1.0", + "typedoc": "^0.28.15" }, "dependencies": { - "minipass": "^3.0.0" + "minipass": "^7.1.2" }, - "main": "index.js", + "main": "./dist/commonjs/index.js", "keywords": [ "minipass", "size", @@ -35,5 +43,27 @@ }, "engines": { "node": ">=8" - } + }, + "type": "module", + "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", + "module": "./dist/esm/index.js" } diff --git a/node_modules/minipass-sized/test/basic.js b/node_modules/minipass-sized/test/basic.js deleted file mode 100644 index bbdcadaa8c4e2..0000000000000 --- a/node_modules/minipass-sized/test/basic.js +++ /dev/null @@ -1,83 +0,0 @@ -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() -}) diff --git a/node_modules/minipass/LICENSE b/node_modules/minipass/LICENSE deleted file mode 100644 index 97f8e32ed82e4..0000000000000 --- a/node_modules/minipass/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/minipass/LICENSE.md b/node_modules/minipass/LICENSE.md new file mode 100644 index 0000000000000..c5402b9577a8c --- /dev/null +++ b/node_modules/minipass/LICENSE.md @@ -0,0 +1,55 @@ +# 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.*** diff --git a/node_modules/minipass/dist/commonjs/index.js b/node_modules/minipass/dist/commonjs/index.js index 068c095b69793..91f3a5cfc7a0b 100644 --- a/node_modules/minipass/dist/commonjs/index.js +++ b/node_modules/minipass/dist/commonjs/index.js @@ -22,7 +22,11 @@ const isStream = (s) => !!s && (s instanceof Minipass || s instanceof node_stream_1.default || (0, exports.isReadable)(s) || - (0, exports.isWritable)(s)); + (0, exports.isWritable)(s)) +/** + * Return true if the argument is a valid {@link Minipass.Readable} + */ +; exports.isStream = isStream; /** * Return true if the argument is a valid {@link Minipass.Readable} @@ -32,7 +36,11 @@ const isReadable = (s) => !!s && 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; + s.pipe !== node_stream_1.default.Writable.prototype.pipe +/** + * Return true if the argument is a valid {@link Minipass.Writable} + */ +; exports.isReadable = isReadable; /** * Return true if the argument is a valid {@link Minipass.Writable} @@ -129,7 +137,7 @@ class PipeProxyErrors extends Pipe { } constructor(src, dest, opts) { super(src, dest, opts); - this.proxyErrors = er => dest.emit('error', er); + this.proxyErrors = (er) => this.dest.emit('error', er); src.on('error', this.proxyErrors); } } @@ -939,6 +947,7 @@ class Minipass extends node_events_1.EventEmitter { [Symbol.asyncIterator]() { return this; }, + [Symbol.asyncDispose]: async () => { }, }; } /** @@ -976,6 +985,7 @@ class Minipass extends node_events_1.EventEmitter { [Symbol.iterator]() { return this; }, + [Symbol.dispose]: () => { }, }; } /** diff --git a/node_modules/minipass/dist/esm/index.js b/node_modules/minipass/dist/esm/index.js index b5fa4513c9083..5df55461e3d49 100644 --- a/node_modules/minipass/dist/esm/index.js +++ b/node_modules/minipass/dist/esm/index.js @@ -120,7 +120,7 @@ class PipeProxyErrors extends Pipe { } constructor(src, dest, opts) { super(src, dest, opts); - this.proxyErrors = er => dest.emit('error', er); + this.proxyErrors = (er) => this.dest.emit('error', er); src.on('error', this.proxyErrors); } } @@ -930,6 +930,7 @@ export class Minipass extends EventEmitter { [Symbol.asyncIterator]() { return this; }, + [Symbol.asyncDispose]: async () => { }, }; } /** @@ -967,6 +968,7 @@ export class Minipass extends EventEmitter { [Symbol.iterator]() { return this; }, + [Symbol.dispose]: () => { }, }; } /** diff --git a/node_modules/minipass/package.json b/node_modules/minipass/package.json index 771969b028546..800f215cb02c0 100644 --- a/node_modules/minipass/package.json +++ b/node_modules/minipass/package.json @@ -1,13 +1,14 @@ { "name": "minipass", - "version": "7.1.2", + "version": "7.1.3", "description": "minimal implementation of a PassThrough stream", "main": "./dist/commonjs/index.js", "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js", "type": "module", "tshy": { "selfLink": false, - "main": true, + "compiler": "tsgo", "exports": { "./package.json": "./package.json", ".": "./src/index.ts" @@ -54,14 +55,14 @@ }, "devDependencies": { "@types/end-of-stream": "^1.4.2", - "@types/node": "^20.1.2", + "@types/node": "^25.2.3", "end-of-stream": "^1.4.0", "node-abort-controller": "^3.1.1", - "prettier": "^2.6.2", - "tap": "^19.0.0", + "prettier": "^3.8.1", + "tap": "^21.6.1", "through2": "^2.0.3", - "tshy": "^1.14.0", - "typedoc": "^0.25.1" + "tshy": "^3.3.2", + "typedoc": "^0.28.17" }, "repository": "https://github.com/isaacs/minipass", "keywords": [ @@ -69,14 +70,8 @@ "stream" ], "author": "Isaac Z. Schlueter (http://blog.izs.me/)", - "license": "ISC", + "license": "BlueOak-1.0.0", "engines": { "node": ">=16 || 14 >=14.17" - }, - "tap": { - "typecheck": true, - "include": [ - "test/*.ts" - ] } } diff --git a/node_modules/minizlib/LICENSE b/node_modules/minizlib/LICENSE index ffce7383f53e7..49f7efe431c9e 100644 --- a/node_modules/minizlib/LICENSE +++ b/node_modules/minizlib/LICENSE @@ -2,9 +2,9 @@ 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. +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"), diff --git a/node_modules/minizlib/constants.js b/node_modules/minizlib/constants.js deleted file mode 100644 index 641ebc73129bf..0000000000000 --- a/node_modules/minizlib/constants.js +++ /dev/null @@ -1,115 +0,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 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)) diff --git a/node_modules/minizlib/dist/commonjs/constants.js b/node_modules/minizlib/dist/commonjs/constants.js new file mode 100644 index 0000000000000..dfc2c1957bfc9 --- /dev/null +++ b/node_modules/minizlib/dist/commonjs/constants.js @@ -0,0 +1,123 @@ +"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 \ No newline at end of file diff --git a/node_modules/minizlib/dist/commonjs/index.js b/node_modules/minizlib/dist/commonjs/index.js new file mode 100644 index 0000000000000..78c6536baf6be --- /dev/null +++ b/node_modules/minizlib/dist/commonjs/index.js @@ -0,0 +1,416 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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.ZstdDecompress = exports.ZstdCompress = exports.BrotliDecompress = exports.BrotliCompress = 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 realZlib = __importStar(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 desc = Object.getOwnPropertyDescriptor(buffer_1.Buffer, 'concat'); +const noop = (args) => args; +const passthroughBufferConcat = desc?.writable === true || desc?.set !== undefined + ? (makeNoOp) => { + buffer_1.Buffer.concat = makeNoOp ? noop : OriginalBufferConcat; + } + : (_) => { }; +const _superWrite = Symbol('_superWrite'); +class ZlibError extends Error { + code; + errno; + constructor(err, origin) { + super('zlib: ' + err.message, { cause: err }); + 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, origin ?? 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 */ + //@ts-ignore + if (typeof realZlib[mode] !== 'function') { + throw new TypeError('Compression method not supported: ' + mode); + } + // 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.constructor); + } + 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. + passthroughBufferConcat(true); + 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 + passthroughBufferConcat(false); + } + 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() + passthroughBufferConcat(false); + this.#onError(new ZlibError(err, this.write)); + } + 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, this.write))); + 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); + } +} +class BrotliCompress extends Brotli { + constructor(opts) { + super(opts, 'BrotliCompress'); + } +} +exports.BrotliCompress = BrotliCompress; +class BrotliDecompress extends Brotli { + constructor(opts) { + super(opts, 'BrotliDecompress'); + } +} +exports.BrotliDecompress = BrotliDecompress; +class Zstd extends ZlibBase { + constructor(opts, mode) { + opts = opts || {}; + opts.flush = opts.flush || constants_js_1.constants.ZSTD_e_continue; + opts.finishFlush = opts.finishFlush || constants_js_1.constants.ZSTD_e_end; + opts.fullFlushFlag = constants_js_1.constants.ZSTD_e_flush; + super(opts, mode); + } +} +class ZstdCompress extends Zstd { + constructor(opts) { + super(opts, 'ZstdCompress'); + } +} +exports.ZstdCompress = ZstdCompress; +class ZstdDecompress extends Zstd { + constructor(opts) { + super(opts, 'ZstdDecompress'); + } +} +exports.ZstdDecompress = ZstdDecompress; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/minizlib/dist/commonjs/package.json b/node_modules/minizlib/dist/commonjs/package.json new file mode 100644 index 0000000000000..5bbefffbabee3 --- /dev/null +++ b/node_modules/minizlib/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/minizlib/dist/esm/constants.js b/node_modules/minizlib/dist/esm/constants.js new file mode 100644 index 0000000000000..7faf40be5068d --- /dev/null +++ b/node_modules/minizlib/dist/esm/constants.js @@ -0,0 +1,117 @@ +// 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.map \ No newline at end of file diff --git a/node_modules/minizlib/dist/esm/index.js b/node_modules/minizlib/dist/esm/index.js new file mode 100644 index 0000000000000..b70ba1f2cd84f --- /dev/null +++ b/node_modules/minizlib/dist/esm/index.js @@ -0,0 +1,363 @@ +import assert from 'assert'; +import { Buffer } from 'buffer'; +import { Minipass } from 'minipass'; +import * as realZlib from 'zlib'; +import { constants } from './constants.js'; +export { constants } from './constants.js'; +const OriginalBufferConcat = Buffer.concat; +const desc = Object.getOwnPropertyDescriptor(Buffer, 'concat'); +const noop = (args) => args; +const passthroughBufferConcat = desc?.writable === true || desc?.set !== undefined + ? (makeNoOp) => { + Buffer.concat = makeNoOp ? noop : OriginalBufferConcat; + } + : (_) => { }; +const _superWrite = Symbol('_superWrite'); +export class ZlibError extends Error { + code; + errno; + constructor(err, origin) { + super('zlib: ' + err.message, { cause: err }); + 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, origin ?? 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 */ + //@ts-ignore + if (typeof realZlib[mode] !== 'function') { + throw new TypeError('Compression method not supported: ' + mode); + } + // 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.constructor); + } + 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. + passthroughBufferConcat(true); + 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 + passthroughBufferConcat(false); + } + 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() + passthroughBufferConcat(false); + this.#onError(new ZlibError(err, this.write)); + } + 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, this.write))); + 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'); + } +} +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'); + } +} +class Zstd extends ZlibBase { + constructor(opts, mode) { + opts = opts || {}; + opts.flush = opts.flush || constants.ZSTD_e_continue; + opts.finishFlush = opts.finishFlush || constants.ZSTD_e_end; + opts.fullFlushFlag = constants.ZSTD_e_flush; + super(opts, mode); + } +} +export class ZstdCompress extends Zstd { + constructor(opts) { + super(opts, 'ZstdCompress'); + } +} +export class ZstdDecompress extends Zstd { + constructor(opts) { + super(opts, 'ZstdDecompress'); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/minizlib/dist/esm/package.json b/node_modules/minizlib/dist/esm/package.json new file mode 100644 index 0000000000000..3dbc1ca591c05 --- /dev/null +++ b/node_modules/minizlib/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/minizlib/index.js b/node_modules/minizlib/index.js deleted file mode 100644 index fbaf69e19f209..0000000000000 --- a/node_modules/minizlib/index.js +++ /dev/null @@ -1,348 +0,0 @@ -'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. - writeReturn = this[_superWrite](Buffer.from(result[0])) - for (let i = 1; i < result.length; i++) { - writeReturn = this[_superWrite](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') - } - } -} diff --git a/node_modules/minizlib/node_modules/minipass/LICENSE b/node_modules/minizlib/node_modules/minipass/LICENSE deleted file mode 100644 index bf1dece2e1f12..0000000000000 --- a/node_modules/minizlib/node_modules/minipass/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/minizlib/node_modules/minipass/index.js b/node_modules/minizlib/node_modules/minipass/index.js deleted file mode 100644 index e8797aab6cc27..0000000000000 --- a/node_modules/minizlib/node_modules/minipass/index.js +++ /dev/null @@ -1,649 +0,0 @@ -'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 - )) - } -} diff --git a/node_modules/minizlib/node_modules/minipass/package.json b/node_modules/minizlib/node_modules/minipass/package.json deleted file mode 100644 index 548d03fa6d5d4..0000000000000 --- a/node_modules/minizlib/node_modules/minipass/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/minizlib/package.json b/node_modules/minizlib/package.json index 98825a549f3fd..dceaed923d3db 100644 --- a/node_modules/minizlib/package.json +++ b/node_modules/minizlib/package.json @@ -1,17 +1,20 @@ { "name": "minizlib", - "version": "2.1.2", + "version": "3.1.0", "description": "A small fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding.", - "main": "index.js", + "main": "./dist/commonjs/index.js", "dependencies": { - "minipass": "^3.0.0", - "yallist": "^4.0.0" + "minipass": "^7.1.2" }, "scripts": { - "test": "tap test/*.js --100 -J", + "prepare": "tshy", + "pretest": "npm run prepare", + "test": "tap", "preversion": "npm test", "postversion": "npm publish", - "postpublish": "git push origin --all; git push origin --tags" + "prepublishOnly": "git push origin --follow-tags", + "format": "prettier --write . --loglevel warn", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" }, "repository": { "type": "git", @@ -30,13 +33,48 @@ "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "license": "MIT", "devDependencies": { - "tap": "^14.6.9" + "@types/node": "^24.5.2", + "tap": "^21.1.0", + "tshy": "^3.0.2", + "typedoc": "^0.28.1" }, "files": [ - "index.js", - "constants.js" + "dist" ], "engines": { - "node": ">= 8" - } + "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" + }, + "module": "./dist/esm/index.js" } diff --git a/node_modules/mkdirp/LICENSE b/node_modules/mkdirp/LICENSE deleted file mode 100644 index 13fcd15f0e0be..0000000000000 --- a/node_modules/mkdirp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -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. diff --git a/node_modules/mkdirp/bin/cmd.js b/node_modules/mkdirp/bin/cmd.js deleted file mode 100755 index 6e0aa8dc4667b..0000000000000 --- a/node_modules/mkdirp/bin/cmd.js +++ /dev/null @@ -1,68 +0,0 @@ -#!/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) - }) diff --git a/node_modules/mkdirp/index.js b/node_modules/mkdirp/index.js deleted file mode 100644 index ad7a16c9f45d9..0000000000000 --- a/node_modules/mkdirp/index.js +++ /dev/null @@ -1,31 +0,0 @@ -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 diff --git a/node_modules/mkdirp/lib/find-made.js b/node_modules/mkdirp/lib/find-made.js deleted file mode 100644 index 022e492c085da..0000000000000 --- a/node_modules/mkdirp/lib/find-made.js +++ /dev/null @@ -1,29 +0,0 @@ -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} diff --git a/node_modules/mkdirp/lib/mkdirp-manual.js b/node_modules/mkdirp/lib/mkdirp-manual.js deleted file mode 100644 index 2eb18cd64eb79..0000000000000 --- a/node_modules/mkdirp/lib/mkdirp-manual.js +++ /dev/null @@ -1,64 +0,0 @@ -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} diff --git a/node_modules/mkdirp/lib/mkdirp-native.js b/node_modules/mkdirp/lib/mkdirp-native.js deleted file mode 100644 index c7a6b69800f62..0000000000000 --- a/node_modules/mkdirp/lib/mkdirp-native.js +++ /dev/null @@ -1,39 +0,0 @@ -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} diff --git a/node_modules/mkdirp/lib/opts-arg.js b/node_modules/mkdirp/lib/opts-arg.js deleted file mode 100644 index 2fa4833faacc7..0000000000000 --- a/node_modules/mkdirp/lib/opts-arg.js +++ /dev/null @@ -1,23 +0,0 @@ -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 diff --git a/node_modules/mkdirp/lib/path-arg.js b/node_modules/mkdirp/lib/path-arg.js deleted file mode 100644 index cc07de5a6f992..0000000000000 --- a/node_modules/mkdirp/lib/path-arg.js +++ /dev/null @@ -1,29 +0,0 @@ -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 diff --git a/node_modules/mkdirp/lib/use-native.js b/node_modules/mkdirp/lib/use-native.js deleted file mode 100644 index 079361de19fd8..0000000000000 --- a/node_modules/mkdirp/lib/use-native.js +++ /dev/null @@ -1,10 +0,0 @@ -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} diff --git a/node_modules/mkdirp/package.json b/node_modules/mkdirp/package.json deleted file mode 100644 index 2913ed09bddd6..0000000000000 --- a/node_modules/mkdirp/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "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" - ] -} diff --git a/node_modules/mute-stream/package.json b/node_modules/mute-stream/package.json index 37b2f5070ed69..c3bf320c9c6ca 100644 --- a/node_modules/mute-stream/package.json +++ b/node_modules/mute-stream/package.json @@ -1,24 +1,26 @@ { "name": "mute-stream", - "version": "1.0.0", + "version": "4.0.0", "main": "lib/index.js", "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.11.0", - "tap": "^16.3.0" + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0" }, "scripts": { - "test": "tap", - "lint": "eslint \"**/*.js\"", + "test": "node --test './test/**/*.js'", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" + "lintfix": "npm run eslint -- --fix", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test:node20": "node --test test", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'" }, "repository": { "type": "git", - "url": "https://github.com/npm/mute-stream.git" + "url": "git+https://github.com/npm/mute-stream.git" }, "keywords": [ "mute", @@ -32,21 +34,14 @@ "bin/", "lib/" ], - "tap": { - "statements": 70, - "branches": 60, - "functions": 81, - "lines": 70, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.11.0" + "version": "5.0.0", + "publish": true, + "testRunner": "node:test", + "latestCiVersion": 24 } } diff --git a/node_modules/negotiator/HISTORY.md b/node_modules/negotiator/HISTORY.md index a9a544914c43b..63d537d3f6811 100644 --- a/node_modules/negotiator/HISTORY.md +++ b/node_modules/negotiator/HISTORY.md @@ -1,3 +1,9 @@ +1.0.0 / 2024-08-31 +================== + + * Drop support for node <18 + * Added an option preferred encodings array #59 + 0.6.3 / 2022-01-22 ================== diff --git a/node_modules/negotiator/index.js b/node_modules/negotiator/index.js index 4788264b16c9f..4f51315d6af4b 100644 --- a/node_modules/negotiator/index.js +++ b/node_modules/negotiator/index.js @@ -44,13 +44,14 @@ Negotiator.prototype.charsets = function charsets(available) { return preferredCharsets(this.request.headers['accept-charset'], available); }; -Negotiator.prototype.encoding = function encoding(available) { - var set = this.encodings(available); +Negotiator.prototype.encoding = function encoding(available, opts) { + var set = this.encodings(available, opts); return set && set[0]; }; -Negotiator.prototype.encodings = function encodings(available) { - return preferredEncodings(this.request.headers['accept-encoding'], available); +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) { diff --git a/node_modules/negotiator/lib/encoding.js b/node_modules/negotiator/lib/encoding.js index 8432cd77b8a96..9ebb633d67743 100644 --- a/node_modules/negotiator/lib/encoding.js +++ b/node_modules/negotiator/lib/encoding.js @@ -96,7 +96,7 @@ function parseEncoding(str, i) { */ function getEncodingPriority(encoding, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; + 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); @@ -123,6 +123,7 @@ function specify(encoding, spec, index) { } return { + encoding: encoding, i: index, o: spec.i, q: spec.q, @@ -135,14 +136,34 @@ function specify(encoding, spec, index) { * @public */ -function preferredEncodings(accept, provided) { +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(compareSpecs) + .sort(comparator) .map(getFullEncoding); } @@ -151,7 +172,7 @@ function preferredEncodings(accept, provided) { }); // sorted list of accepted encodings - return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) { + return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) { return provided[priorities.indexOf(priority)]; }); } @@ -162,7 +183,7 @@ function preferredEncodings(accept, provided) { */ function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i); } /** diff --git a/node_modules/negotiator/lib/mediaType.js b/node_modules/negotiator/lib/mediaType.js index 67309dd75f1b6..8e402ea88394c 100644 --- a/node_modules/negotiator/lib/mediaType.js +++ b/node_modules/negotiator/lib/mediaType.js @@ -69,7 +69,7 @@ function parseMediaType(str, i) { // get the value, unwrapping quotes var value = val && val[0] === '"' && val[val.length - 1] === '"' - ? val.substr(1, val.length - 2) + ? val.slice(1, -1) : val; if (key === 'q') { @@ -238,8 +238,8 @@ function splitKeyValuePair(str) { if (index === -1) { key = str; } else { - key = str.substr(0, index); - val = str.substr(index + 1); + key = str.slice(0, index); + val = str.slice(index + 1); } return [key, val]; diff --git a/node_modules/negotiator/package.json b/node_modules/negotiator/package.json index 297635f6d3417..e4bdc1ef4f748 100644 --- a/node_modules/negotiator/package.json +++ b/node_modules/negotiator/package.json @@ -1,7 +1,7 @@ { "name": "negotiator", "description": "HTTP content negotiation", - "version": "0.6.3", + "version": "1.0.0", "contributors": [ "Douglas Christopher Wilson ", "Federico Romero ", @@ -36,6 +36,7 @@ "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" } diff --git a/node_modules/node-gyp/.release-please-manifest.json b/node_modules/node-gyp/.release-please-manifest.json index 1842506cfa97f..139a159133195 100644 --- a/node_modules/node-gyp/.release-please-manifest.json +++ b/node_modules/node-gyp/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "10.1.0" + ".": "13.0.0" } diff --git a/node_modules/node-gyp/CODE_OF_CONDUCT.md b/node_modules/node-gyp/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000..4c211405596cb --- /dev/null +++ b/node_modules/node-gyp/CODE_OF_CONDUCT.md @@ -0,0 +1,4 @@ +# 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) diff --git a/node_modules/node-gyp/CONTRIBUTING.md b/node_modules/node-gyp/CONTRIBUTING.md index 5b977898f104b..618fb6ae9e03a 100644 --- a/node_modules/node-gyp/CONTRIBUTING.md +++ b/node_modules/node-gyp/CONTRIBUTING.md @@ -1,5 +1,13 @@ # Contributing to node-gyp +## Making changes to gyp-next + +Changes in the subfolder `gyp/` should be submitted to the +[`gyp-next`][] repository first. The `gyp/` folder is regularly +synced from [`gyp-next`][] with GitHub Actions workflow +[`update-gyp-next.yml`](.github/workflows/update-gyp-next.yml), +and any changes in this folder would be overridden by the workflow. + ## Code of Conduct Please read the @@ -32,3 +40,5 @@ By making a contribution to this project, I certify that: 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. + +[`gyp-next`]: https://github.com/nodejs/gyp-next diff --git a/node_modules/node-gyp/addon.gypi b/node_modules/node-gyp/addon.gypi index b4ac369acb4f1..4f112df81c771 100644 --- a/node_modules/node-gyp/addon.gypi +++ b/node_modules/node-gyp/addon.gypi @@ -179,7 +179,7 @@ '-loleaut32.lib', '-luuid.lib', '-lodbc32.lib', - '-lDelayImp.lib', + '-ldelayimp.lib', '-l"<(node_lib_file)"' ], 'msvs_disabled_warnings': [ @@ -195,7 +195,7 @@ '_FILE_OFFSET_BITS=64' ], }], - [ 'OS in "freebsd openbsd netbsd solaris android" or \ + [ 'OS in "freebsd openbsd netbsd solaris android openharmony" or \ (OS=="linux" and target_arch!="ia32")', { 'cflags': [ '-fPIC' ], }], diff --git a/node_modules/node-gyp/bin/node-gyp.js b/node_modules/node-gyp/bin/node-gyp.js index f8317b47b3414..5393a5c8e1e71 100755 --- a/node_modules/node-gyp/bin/node-gyp.js +++ b/node_modules/node-gyp/bin/node-gyp.js @@ -125,6 +125,13 @@ function errorMessage () { log.error('cwd', process.cwd()) log.error('node -v', process.version) log.error('node-gyp -v', 'v' + prog.package.version) + // print the npm package version + for (const env of ['npm_package_name', 'npm_package_version']) { + const value = process.env[env] + if (value != null) { + log.error(`$${env}`, value) + } + } } function issueMessage () { diff --git a/node_modules/node-gyp/commitlint.config.mjs b/node_modules/node-gyp/commitlint.config.mjs new file mode 100644 index 0000000000000..2291173ef3bdf --- /dev/null +++ b/node_modules/node-gyp/commitlint.config.mjs @@ -0,0 +1,3 @@ +export default { + extends: ['@commitlint/config-conventional'] +}; diff --git a/node_modules/node-gyp/eslint.config.js b/node_modules/node-gyp/eslint.config.js new file mode 100644 index 0000000000000..5212dc93d5304 --- /dev/null +++ b/node_modules/node-gyp/eslint.config.js @@ -0,0 +1,3 @@ +'use strict' + +module.exports = require('neostandard')({}) diff --git a/node_modules/node-gyp/gyp/.release-please-manifest.json b/node_modules/node-gyp/gyp/.release-please-manifest.json new file mode 100644 index 0000000000000..762fc35f4ce7a --- /dev/null +++ b/node_modules/node-gyp/gyp/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "0.22.2" +} diff --git a/node_modules/node-gyp/gyp/data/ninja/build.ninja b/node_modules/node-gyp/gyp/data/ninja/build.ninja new file mode 100644 index 0000000000000..2400dbb1f0dab --- /dev/null +++ b/node_modules/node-gyp/gyp/data/ninja/build.ninja @@ -0,0 +1,4 @@ +rule cc + command = cc $in $out + +build my.out: cc my.in diff --git a/node_modules/node-gyp/gyp/docs/GypVsCMake.md b/node_modules/node-gyp/gyp/docs/GypVsCMake.md new file mode 100644 index 0000000000000..6d659a6123b66 --- /dev/null +++ b/node_modules/node-gyp/gyp/docs/GypVsCMake.md @@ -0,0 +1,116 @@ +# 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 +``` diff --git a/node_modules/node-gyp/gyp/docs/Hacking.md b/node_modules/node-gyp/gyp/docs/Hacking.md new file mode 100644 index 0000000000000..156d485b5b82d --- /dev/null +++ b/node_modules/node-gyp/gyp/docs/Hacking.md @@ -0,0 +1,46 @@ +# 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 +$ 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 environment 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. diff --git a/node_modules/node-gyp/gyp/docs/InputFormatReference.md b/node_modules/node-gyp/gyp/docs/InputFormatReference.md new file mode 100644 index 0000000000000..4b114f2debca4 --- /dev/null +++ b/node_modules/node-gyp/gyp/docs/InputFormatReference.md @@ -0,0 +1,1083 @@ +# 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 + * library\_dirs + * 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 + 'library_dirs': ['lib'], # 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'], + 'library_dirs': ['../build/lib'], + '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']`. diff --git a/node_modules/node-gyp/gyp/docs/LanguageSpecification.md b/node_modules/node-gyp/gyp/docs/LanguageSpecification.md new file mode 100644 index 0000000000000..f8fff097ab73f --- /dev/null +++ b/node_modules/node-gyp/gyp/docs/LanguageSpecification.md @@ -0,0 +1,430 @@ +# 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 preprocessor 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. `conditions` sections are processed shortly after loading +`.gyp` files, and `target_conditions` 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? diff --git a/node_modules/node-gyp/gyp/docs/Testing.md b/node_modules/node-gyp/gyp/docs/Testing.md new file mode 100644 index 0000000000000..a52031e88819a --- /dev/null +++ b/node_modules/node-gyp/gyp/docs/Testing.md @@ -0,0 +1,450 @@ +# 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`-terminated 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`-terminated 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`-terminated 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`. diff --git a/node_modules/node-gyp/gyp/docs/UserDocumentation.md b/node_modules/node-gyp/gyp/docs/UserDocumentation.md new file mode 100644 index 0000000000000..b9d412e1c847b --- /dev/null +++ b/node_modules/node-gyp/gyp/docs/UserDocumentation.md @@ -0,0 +1,965 @@ +# 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 variables. 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. + +**Preferred**: 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 appropriate `.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 itself, 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 diff --git a/node_modules/node-gyp/gyp/gyp_main.py b/node_modules/node-gyp/gyp/gyp_main.py index f23dcdf882d1b..bf16987485146 100755 --- a/node_modules/node-gyp/gyp/gyp_main.py +++ b/node_modules/node-gyp/gyp/gyp_main.py @@ -5,8 +5,8 @@ # found in the LICENSE file. import os -import sys import subprocess +import sys def IsCygwin(): diff --git a/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py b/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py index bc0e93d07f890..9149f404a5ade 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py @@ -32,20 +32,20 @@ def cmp(x, y): 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() + Args: + name: Target name. + seed: Seed for SHA-256 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 SHA-256 signature for the seed and name. + d = hashlib.sha256((str(seed) + str(name)).encode("utf-8")).hexdigest().upper() # Convert most of the signature to GUID form (discard the rest) guid = ( "{" @@ -78,15 +78,15 @@ class MSVSFolder(MSVSSolutionEntry): 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. - """ + 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: @@ -128,19 +128,19 @@ def __init__( ): """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 - """ + 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 @@ -195,16 +195,16 @@ def __init__( ): """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. - """ + 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 @@ -230,9 +230,9 @@ def __init__( def Write(self, writer=gyp.common.WriteOnDiff): """Writes the solution file to disk. - Raises: - IndexError: An entry appears multiple times. - """ + 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[:] diff --git a/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py b/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py index 629f3f61b4819..17bb2bbdb8a55 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py @@ -4,7 +4,7 @@ """Visual Studio project reader/writer.""" -import gyp.easy_xml as easy_xml +from gyp import easy_xml # ------------------------------------------------------------------------------ @@ -15,19 +15,19 @@ class Tool: def __init__(self, name, attrs=None): """Initializes the tool. - Args: - name: Tool name. - attrs: Dict of tool attributes; may be None. - """ + 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. - """ + Returns: + A new xml.dom.Element for the tool. + """ return ["Tool", self._attrs] @@ -37,10 +37,10 @@ class Filter: def __init__(self, name, contents=None): """Initializes the folder. - Args: - name: Filter (folder) name. - contents: List of filenames and/or Filter objects contained. - """ + Args: + name: Filter (folder) name. + contents: List of filenames and/or Filter objects contained. + """ self.name = name self.contents = list(contents or []) @@ -54,13 +54,13 @@ class 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'] - """ + 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 @@ -84,21 +84,21 @@ def __init__(self, project_path, version, name, guid=None, platforms=None): def AddToolFile(self, path): """Adds a tool file to the project. - Args: - path: Relative path from project to tool file. - """ + 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: - """ + 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 = {} @@ -122,23 +122,23 @@ def _GetSpecForConfiguration(self, config_type, config_name, attrs, tools): 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. - """ + 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. + 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. - """ + Will call itself recursively, if the files list contains Filter objects. + """ for f in files: if isinstance(f, Filter): node = ["Filter", {"Name": f.name}] @@ -151,13 +151,13 @@ def _AddFilesToNode(self, parent, files): def AddFiles(self, files): """Adds files to the project. - Args: - files: A list of Filter objects and/or relative paths to files. + 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. - """ + 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. @@ -165,15 +165,15 @@ def AddFiles(self, files): 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. + 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(). - """ + 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: diff --git a/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py b/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py index 93633dbca133c..155fc3a1cbc69 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py @@ -35,10 +35,10 @@ 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. - """ + 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 @@ -48,11 +48,11 @@ def __init__(self, msvs_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. + This only defines the tool. Each setting also needs to be added. - Args: - tool: The _Tool object 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] = {} @@ -70,35 +70,35 @@ class _Type: def ValidateMSVS(self, value): """Verifies that the value is legal for MSVS. - Args: - value: the value to check for this type. + Args: + value: the value to check for this type. - Raises: - ValueError if value is not valid for MSVS. - """ + 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. + Args: + value: the value to check for this type. - Raises: - ValueError if value is not valid for MSBuild. - """ + 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. + Args: + value: the MSVS value to convert. - Returns: - the MSBuild equivalent. + Returns: + the MSBuild equivalent. - Raises: - ValueError if value is not valid. - """ + Raises: + ValueError if value is not valid. + """ return value @@ -171,22 +171,22 @@ def ValidateMSBuild(self, value): int(value, self._msbuild_base) def ConvertToMSBuild(self, value): - msbuild_format = (self._msbuild_base == 10) and "%d" or "0x%04x" + 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'. + 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. - """ + 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) @@ -234,23 +234,23 @@ def ConvertToMSBuild(self, value): 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. - """ + 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. - """ + 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) @@ -272,13 +272,13 @@ def _MovedAndRenamed( ): """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. - """ + 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, {}) @@ -293,11 +293,11 @@ def _Translate(value, msbuild_settings): 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. - """ + 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. @@ -310,11 +310,11 @@ def _Translate(unused_value, unused_msbuild_settings): 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. - """ + 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. @@ -328,11 +328,11 @@ def _Translate(value, msbuild_settings): 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 - """ + 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": @@ -384,20 +384,19 @@ def _Translate(value, msbuild_settings): 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. + 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. - """ + 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: + if m := re.match(_EXCLUDED_SUFFIX_RE, setting): root_setting = m.group(1) unrecognized = root_setting not in settings @@ -409,11 +408,11 @@ def _ValidateExclusionSetting(setting, settings, error_msg, stderr=sys.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. + 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. - """ + This list is probably not exhaustive. Add as needed. + """ if "$" in s: s = fix_vc_macro_slashes_regex.sub(r"\1", s) return s @@ -422,8 +421,8 @@ def FixVCMacroSlashes(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. - """ + This list is probably not exhaustive. Add as needed. + """ if "$" in s: replace_map = { "$(ConfigurationName)": "$(Configuration)", @@ -445,16 +444,16 @@ def ConvertVCMacrosToMSBuild(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. + 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. - """ + 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: @@ -493,36 +492,36 @@ def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr): 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. - """ + 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. - """ + 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. + 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. - """ + 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] @@ -638,7 +637,9 @@ def _ValidateSettings(validators, settings, stderr): ), ) # /RTC1 _Same( - _compile, "BrowseInformation", _Enumeration(["false", "true", "true"]) # /FR + _compile, + "BrowseInformation", + _Enumeration(["false", "true", "true"]), # /FR ) # /Fr _Same( _compile, @@ -696,7 +697,9 @@ def _ValidateSettings(validators, settings, stderr): _Enumeration(["false", "Sync", "Async"], new=["SyncCThrow"]), # /EHsc # /EHa ) # /EHs _Same( - _compile, "FavorSizeOrSpeed", _Enumeration(["Neither", "Speed", "Size"]) # /Ot + _compile, + "FavorSizeOrSpeed", + _Enumeration(["Neither", "Speed", "Size"]), # /Ot ) # /Os _Same( _compile, @@ -793,6 +796,8 @@ def _ValidateSettings(validators, settings, stderr): _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 @@ -907,7 +912,9 @@ def _ValidateSettings(validators, settings, stderr): ) # /MACHINE:X64 _Same( - _link, "AssemblyDebug", _Enumeration(["", "true", "false"]) # /ASSEMBLYDEBUG + _link, + "AssemblyDebug", + _Enumeration(["", "true", "false"]), # /ASSEMBLYDEBUG ) # /ASSEMBLYDEBUG:DISABLE _Same( _link, @@ -1157,17 +1164,23 @@ def _ValidateSettings(validators, settings, stderr): _MSBuildOnly(_midl, "ApplicationConfigurationMode", _boolean) # /app_config _MSBuildOnly(_midl, "ClientStubFile", _file_name) # /cstub _MSBuildOnly( - _midl, "GenerateClientFiles", _Enumeration([], new=["Stub", "None"]) # /client stub + _midl, + "GenerateClientFiles", + _Enumeration([], new=["Stub", "None"]), # /client stub ) # /client none _MSBuildOnly( - _midl, "GenerateServerFiles", _Enumeration([], new=["Stub", "None"]) # /client stub + _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 + _midl, + "TypeLibFormat", + _Enumeration([], new=["NewFormat", "OldFormat"]), # /newtlb ) # /oldtlb diff --git a/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py b/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py index 6ca09687ad7f1..0e661995fbcd9 100755 --- a/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py @@ -7,10 +7,10 @@ """Unit tests for the MSVSSettings.py file.""" import unittest -import gyp.MSVSSettings as MSVSSettings - from io import StringIO +from gyp import MSVSSettings + class TestSequenceFunctions(unittest.TestCase): def setUp(self): @@ -1143,47 +1143,47 @@ def testConvertToMSBuildSettings_full_synthetic(self): 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. + 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)', - """ + 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", @@ -1346,8 +1346,7 @@ def testConvertToMSBuildSettings_actual(self): "EmbedManifest": "false", "GenerateCatalogFiles": "true", "InputResourceManifests": "asfsfdafs", - "ManifestResourceFile": - "$(IntDir)\\$(TargetFileName).embed.manifest.resfdsf", + "ManifestResourceFile": "$(IntDir)\\$(TargetFileName).embed.manifest.resfdsf", # noqa: E501 "OutputManifestFile": "$(TargetPath).manifestdfs", "RegistrarScriptFile": "sdfsfd", "ReplacementsFile": "sdffsd", @@ -1531,8 +1530,7 @@ def testConvertToMSBuildSettings_actual(self): "LinkIncremental": "", }, "ManifestResourceCompile": { - "ResourceOutputFileName": - "$(IntDir)$(TargetFileName).embed.manifest.resfdsf" + "ResourceOutputFileName": "$(IntDir)$(TargetFileName).embed.manifest.resfdsf" # noqa: E501 }, } self.maxDiff = 9999 # on failure display a long diff diff --git a/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py b/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py index 2e5c811bdde32..61ca37c12d09d 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py @@ -4,7 +4,7 @@ """Visual Studio project reader/writer.""" -import gyp.easy_xml as easy_xml +from gyp import easy_xml class Writer: @@ -13,10 +13,10 @@ class 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. - """ + 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"] @@ -26,14 +26,14 @@ def AddCustomBuildRule( ): """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. - """ + 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", { diff --git a/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py b/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py index e580c00fb76d3..b93613bd1d2e4 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py @@ -8,19 +8,18 @@ import re import socket # for gethostname -import gyp.easy_xml as easy_xml - +from gyp import 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.""" + 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. @@ -59,11 +58,11 @@ class 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. - """ + 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 @@ -72,9 +71,9 @@ def __init__(self, user_file_path, version, name): def AddConfig(self, name): """Adds a configuration to the project. - Args: - name: Configuration name. - """ + Args: + name: Configuration name. + """ self.configurations[name] = ["Configuration", {"Name": name}] def AddDebugSettings( @@ -82,12 +81,12 @@ def AddDebugSettings( ): """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) - """ + 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]) diff --git a/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py b/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py index 36bb782bd319a..5a1b4ae3198d6 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py @@ -7,7 +7,6 @@ import copy import os - # A dictionary mapping supported target types to extensions. TARGET_TYPE_EXT = { "executable": "exe", @@ -30,13 +29,13 @@ def _GetLargePdbShimCcPath(): 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. - """ + 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: @@ -48,12 +47,12 @@ def _DeepCopySomeKeys(in_dict, keys): 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) - """ + 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) @@ -62,24 +61,24 @@ def _SuffixName(name, suffix): 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) - """ + 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. - """ + 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: @@ -129,22 +128,22 @@ def ShardTargets(target_list, 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. - """ + 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", {}) @@ -169,16 +168,16 @@ def _GetPdbPath(target_dict, config_name, vars): 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. + 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. - """ + 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: diff --git a/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py b/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py index 8d7f21e82dd2f..02e6e7ed9209c 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py @@ -5,11 +5,11 @@ """Handle version information related to Visual Stuio.""" import errno +import glob import os import re import subprocess import sys -import glob def JoinPath(*args): @@ -69,25 +69,25 @@ def UsesVcxproj(self): def ProjectExtension(self): """Returns the file extension for the project.""" - return self.uses_vcxproj and ".vcxproj" or ".vcproj" + 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. """ + """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.""" + 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" + environment.""" + assert target_arch in ("x86", "x64", "arm64"), "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 @@ -109,8 +109,16 @@ def _SetupScriptInternal(self, target_arch): ) # 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" + host_arch = ( + "amd64" + if is_host_arch_x64 + else ( + "arm64" + if os.environ.get("PROCESSOR_ARCHITECTURE") == "ARM64" + else "x86" + ) + ) + msvc_target_arch = {"x64": "amd64"}.get(target_arch, target_arch) arg = host_arch if host_arch != msvc_target_arch: arg += "_" + msvc_target_arch @@ -154,16 +162,16 @@ def SetupScript(self, target_arch): 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. + 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. - """ + 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 @@ -184,20 +192,20 @@ def _RegistryQueryBase(sysdir, key, value): 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. + 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. + 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. - """ + 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) @@ -212,14 +220,15 @@ def _RegistryQuery(key, value=None): 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 + 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 # noqa: PLC0415 + try: root, subkey = key.split("\\", 1) assert root == "HKLM" # Only need HKLM for now. @@ -232,17 +241,17 @@ def _RegistryGetValueUsingWinReg(key, value): 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. - """ + 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: @@ -262,13 +271,25 @@ def _RegistryGetValue(key, value): 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. - """ + 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 = { + "2026": VisualStudioVersion( + "2026", + "Visual Studio 2026", + solution_version="12.00", + project_version="18.0", + flat_sln=False, + uses_vcxproj=True, + path=path, + sdk_based=sdk_based, + default_toolset="v145", + compatible_sdks=["v8.1", "v10.0"], + ), "2022": VisualStudioVersion( "2022", "Visual Studio 2022", @@ -435,22 +456,22 @@ def _ConvertToCygpath(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. - """ + 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", @@ -461,6 +482,7 @@ def _DetectVisualStudioVersions(versions_to_check, force_express): "15.0": "2017", "16.0": "2019", "17.0": "2022", + "18.0": "2026", } versions = [] for version in versions_to_check: @@ -527,16 +549,27 @@ def _DetectVisualStudioVersions(versions_to_check, force_express): 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. - """ + 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"), + "auto": ( + "18.0", + "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",), @@ -551,9 +584,9 @@ def SelectVisualStudioVersion(version="auto", allow_fallback=True): "2017": ("15.0",), "2019": ("16.0",), "2022": ("17.0",), + "2026": ("18.0",), } - override_path = os.environ.get("GYP_MSVS_OVERRIDE_PATH") - if override_path: + if override_path := os.environ.get("GYP_MSVS_OVERRIDE_PATH"): msvs_version = os.environ.get("GYP_MSVS_VERSION") if not msvs_version: raise ValueError( diff --git a/node_modules/node-gyp/gyp/pylib/gyp/__init__.py b/node_modules/node-gyp/gyp/pylib/gyp/__init__.py index d6cc01307d997..c0a2637e94770 100755 --- a/node_modules/node-gyp/gyp/pylib/gyp/__init__.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/__init__.py @@ -4,17 +4,19 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +from __future__ import annotations -import copy -import gyp.input import argparse +import copy import os.path import re import shlex import sys import traceback -from gyp.common import GypError +from importlib.metadata import version +import gyp.input +from gyp.common import GypError # Default debug modes for GYP debug = {} @@ -25,6 +27,20 @@ DEBUG_INCLUDES = "includes" +def EscapeForCString(string: bytes | str) -> str: + if isinstance(string, str): + string = string.encode(encoding="utf8") + + backslash_or_double_quote = {ord("\\"), ord('"')} + result = "" + for char in string: + if char in backslash_or_double_quote or not 32 <= char < 127: + result += "\\%03o" % char + else: + result += chr(char) + return result + + def DebugOutput(mode, message, *args): if "all" in gyp.debug or mode in gyp.debug: ctx = ("unknown", 0, "unknown") @@ -63,11 +79,11 @@ def Load( 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. - """ + 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 = {} @@ -101,23 +117,24 @@ def Load( # 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(): + 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") - ), + 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"]), + product_dir_abs = os.path.join( + output_dir, default_variables["CONFIGURATION_NAME"] ) + default_variables.setdefault("PRODUCT_DIR_ABS", product_dir_abs) + default_variables.setdefault( + "PRODUCT_DIR_ABS_CSTR", EscapeForCString(product_dir_abs) + ) + # 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): @@ -170,10 +187,10 @@ def Load( 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. - """ + 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) @@ -192,8 +209,7 @@ def NameValueListToDict(name_value_list): def ShlexEnv(env_name): - flags = os.environ.get(env_name, []) - if flags: + if flags := os.environ.get(env_name) or []: flags = shlex.split(flags) return flags @@ -207,13 +223,13 @@ def FormatOpt(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. - """ + 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): @@ -229,14 +245,14 @@ def RegenerateAppendFlag(flag, values, predicate, env_name, options): 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.) + 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. + 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. - """ + 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) @@ -253,7 +269,7 @@ def Noop(value): for name, metadata in options._regeneration_metadata.items(): opt = metadata["opt"] value = getattr(options, name) - value_predicate = metadata["type"] == "path" and FixPath or Noop + value_predicate = (metadata["type"] == "path" and FixPath) or Noop action = metadata["action"] env_name = metadata["env_name"] if action == "append": @@ -294,15 +310,15 @@ def __init__(self, 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 - """ + 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"] @@ -330,7 +346,7 @@ def parse_args(self, *args): def gyp_main(args): my_name = os.path.basename(sys.argv[0]) - usage = "usage: %(prog)s [options ...] [build_file ...]" + usage = "%(prog)s [options ...] [build_file ...]" parser = RegeneratableOptionParser(usage=usage.replace("%s", "%(prog)s")) parser.add_argument( @@ -348,7 +364,7 @@ def gyp_main(args): action="store", env_name="GYP_CONFIG_DIR", default=None, - help="The location for configuration files like " "include.gypi.", + help="The location for configuration files like include.gypi.", ) parser.add_argument( "-d", @@ -476,8 +492,7 @@ def gyp_main(args): options, build_files_arg = parser.parse_args(args) if options.version: - import pkg_resources - print(f"v{pkg_resources.get_distribution('gyp-next').version}") + print(f"v{version('gyp-next')}") return 0 build_files = build_files_arg @@ -512,19 +527,18 @@ def gyp_main(args): # 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", []) + generate_formats = os.environ.get("GYP_GENERATORS") or [] if generate_formats: generate_formats = re.split(r"[\s,]", generate_formats) if generate_formats: options.formats = generate_formats + # Nothing in the variable, default based on platform. + elif sys.platform == "darwin": + options.formats = ["xcode"] + elif sys.platform in ("win32", "cygwin"): + options.formats = ["msvs"] 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"] + options.formats = ["make"] if not options.generator_output and options.use_environment: g_o = os.environ.get("GYP_GENERATOR_OUTPUT") @@ -683,7 +697,7 @@ def main(args): return 1 -# NOTE: setuptools generated console_scripts calls function with no arguments +# NOTE: console_scripts calls this function with no arguments def script_main(): return main(sys.argv[1:]) diff --git a/node_modules/node-gyp/gyp/pylib/gyp/common.py b/node_modules/node-gyp/gyp/pylib/gyp/common.py index b73a0c55b1e34..223ce47b0032f 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/common.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/common.py @@ -6,10 +6,10 @@ import filecmp import os.path import re -import tempfile -import sys +import shlex import subprocess - +import sys +import tempfile from collections.abc import MutableSet @@ -31,10 +31,8 @@ def __call__(self, *args): 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 + to the user. The main entry point will catch and display this. + """ def ExceptionAppend(e, msg): @@ -49,9 +47,9 @@ def ExceptionAppend(e, msg): def FindQualifiedTargets(target, qualified_list): """ - Given a list of qualified targets, return the qualified targets for the - specified |target|. - """ + 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] @@ -116,7 +114,7 @@ def BuildFile(fully_qualified_target): 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.""" + and finally falling back to a default value.""" for var in var_list: if var in os.environ: return os.environ[var] @@ -179,11 +177,11 @@ def RelativePath(path, relative_to, follow_path_symlink=True): @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. + 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. - """ + 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 @@ -263,12 +261,12 @@ def UnrelativePath(path, relative_to): 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. - """ + 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) @@ -283,9 +281,9 @@ def EncodePOSIXShellArgument(argument): 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. - """ + 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: @@ -313,14 +311,12 @@ def DeepDependencyTargets(target_dicts, roots): def BuildFileTargets(target_list, build_file): - """From a target_list, returns the subset from the specified 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. - """ + """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 @@ -329,12 +325,12 @@ def AllTargets(target_list, target_dicts, build_file): 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). - """ + 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.""" @@ -423,7 +419,70 @@ def EnsureDirExists(path): pass -def GetFlavor(params): +def GetCompilerPredefines(): # -> dict + cmd = [] + defines = {} + + # 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 defines + + 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 + except subprocess.CalledProcessError as e: + print( + "Warning: failed to get compiler predefines\n" + "cmd: %s\n" + "status: %d" % (e.cmd, e.returncode), + file=sys.stderr, + ) + return defines + finally: + os.unlink(input) + else: + input = "/dev/null" + real_cmd = [*cmd, "-dM", "-E", "-x", "c", input] + try: + stdout = subprocess.run( + real_cmd, shell=False, capture_output=True, check=True + ).stdout + except subprocess.CalledProcessError as e: + print( + "Warning: failed to get compiler predefines\n" + "cmd: %s\n" + "status: %d" % (e.cmd, e.returncode), + file=sys.stderr, + ) + return 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", @@ -431,8 +490,6 @@ def GetFlavor(params): "darwin": "mac", } - if "flavor" in params: - return params["flavor"] if sys.platform in flavors: return flavors[sys.platform] if sys.platform.startswith("sunos"): @@ -453,9 +510,22 @@ def GetFlavor(params): return "linux" +def GetFlavor(params): + if "flavor" in params: + return params["flavor"] + + defines = GetCompilerPredefines() + 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|.""" + to |out_path|.""" # aix and solaris just need flock emulation. mac and win use more complicated # support scripts. prefix = { @@ -511,7 +581,8 @@ def uniquer(seq, idfun=lambda x: x): # Based on http://code.activestate.com/recipes/576694/. -class OrderedSet(MutableSet): +class OrderedSet(MutableSet): # noqa: PLW1641 + # TODO (cclauss): Fix eq-without-hash ruff rule PLW1641 def __init__(self, iterable=None): self.end = end = [] end += [None, end, end] # sentinel node for doubly linked list @@ -589,24 +660,24 @@ def __str__(self): 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'] - """ + 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() diff --git a/node_modules/node-gyp/gyp/pylib/gyp/common_test.py b/node_modules/node-gyp/gyp/pylib/gyp/common_test.py index 05344085ad3b1..b5988816c04a2 100755 --- a/node_modules/node-gyp/gyp/pylib/gyp/common_test.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/common_test.py @@ -6,9 +6,13 @@ """Unit tests for the common.py file.""" -import gyp.common -import unittest +import os +import subprocess import sys +import unittest +from unittest.mock import MagicMock, patch + +import gyp.common class TestTopologicallySorted(unittest.TestCase): @@ -24,9 +28,12 @@ def test_Valid(self): def GetEdge(node): return tuple(graph[node]) - self.assertEqual( - gyp.common.TopologicallySorted(graph.keys(), GetEdge), ["a", "c", "d", "b"] - ) + 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.""" @@ -58,7 +65,7 @@ def tearDown(self): def assertFlavor(self, expected, argument, param): sys.platform = argument - self.assertEqual(expected, gyp.common.GetFlavor(param)) + assert expected == gyp.common.GetFlavor(param) def test_platform_default(self): self.assertFlavor("freebsd", "freebsd9", {}) @@ -73,6 +80,107 @@ def test_platform_default(self): 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_GetCompilerPredefines(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, throws=False): + with patch("subprocess.run") as mock_run: + expected_input = "temp.c" if sys.platform == "win32" else "/dev/null" + if throws: + mock_run.side_effect = subprocess.CalledProcessError( + returncode=1, + cmd=[*expected_cmd, "-dM", "-E", "-x", "c", expected_input], + ) + else: + mock_process = MagicMock() + mock_process.returncode = 0 + mock_process.stdout = TestGetFlavor.MockCommunicate(defines_stdout) + mock_run.return_value = mock_process + with patch.dict(os.environ, env): + try: + defines = gyp.common.GetCompilerPredefines() + except Exception as e: + self.fail(f"GetCompilerPredefines raised an exception: {e}") + flavor = gyp.common.GetFlavor({}) + if env.get("CC_target") or env.get("CC"): + 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] + + [defines0, _] = mock_run({"CC": "cl.exe"}, "", ["cl.exe"], True) + assert defines0 == {} + + [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 defines2 == {"__wasm__": "1", "__wasi__": "1"} + 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 defines3 == {"__wasm__": "1"} + assert flavor3 == "wasm" + + [defines4, flavor4] = mock_run( + {"CC_target": "/emsdk/upstream/emscripten/emcc"}, + "#define __EMSCRIPTEN__ 1\n", + ["/emsdk/upstream/emscripten/emcc"], + ) + assert defines4 == {"__EMSCRIPTEN__": "1"} + 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 defines5 == {"__wasm__": "1", "__wasi__": "1", "_REENTRANT": "1"} + 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 defines6 == {"__wasm__": "1", "__wasi__": "1"} + assert flavor6 == "wasi" + if __name__ == "__main__": unittest.main() diff --git a/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py b/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py index 02567b251446d..a5d95153eca72 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py @@ -2,51 +2,51 @@ # 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 +import os +import re +import sys 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. - """ + """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: @@ -58,14 +58,14 @@ def XmlToString(content, encoding="utf-8", pretty=False): 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. - """ + """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 @@ -107,16 +107,17 @@ def _ConstructContentList(xml_parts, specification, pretty, level=0): 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. +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. - """ + 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") @@ -157,7 +158,7 @@ def WriteXmlIfChanged(content, path, encoding="utf-8", pretty=False, def _XmlEscape(value, attr=False): - """ Escape a string for inclusion in XML.""" + """Escape a string for inclusion in XML.""" def replace(match): m = match.string[match.start() : match.end()] diff --git a/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py b/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py index 2d9b15210dc12..29f5dad5a6e90 100755 --- a/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py @@ -4,13 +4,13 @@ # 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. """ +"""Unit tests for the easy_xml.py file.""" -import gyp.easy_xml as easy_xml import unittest - from io import StringIO +from gyp import easy_xml + class TestSequenceFunctions(unittest.TestCase): def setUp(self): diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py index 1334f2fca9967..420c4e49ebc19 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py @@ -62,12 +62,12 @@ then the "all" target includes "b1" and "b2". """ - -import gyp.common import json import os import posixpath +import gyp.common + debug = False found_dependency_string = "Found dependency" @@ -129,8 +129,8 @@ def _ToGypPath(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|.""" + string if the path shouldn't be considered. See _AddSources() for a + description of |base_path_components|.""" depth = 0 while path.startswith("../"): depth += 1 @@ -150,14 +150,14 @@ def _ResolveParent(path, base_path_components): 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.""" + 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("$"): + if not len(source) or source.startswith(("!!!", "$")): continue # variable expansion may lead to //. org_source = source @@ -217,23 +217,23 @@ def _ExtractSources(target, target_dict, toplevel_dir): 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.""" + 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() @@ -253,8 +253,8 @@ def __init__(self, name): class Config: """Details what we're looking for - files: set of files to search for - targets: see file description for details.""" + files: set of files to search for + targets: see file description for details.""" def __init__(self): self.files = [] @@ -264,7 +264,7 @@ def __init__(self): def Init(self, params): """Initializes Config. This is a separate method as it raises an exception - if there is a parse error.""" + if there is a parse error.""" generator_flags = params.get("generator_flags", {}) config_path = generator_flags.get("config_path", None) if not config_path: @@ -288,8 +288,8 @@ def Init(self, params): 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.""" + 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) @@ -318,8 +318,8 @@ def _WasBuildFileModified(build_file, data, files, toplevel_dir): 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.""" + 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) @@ -339,13 +339,13 @@ def _DoesTargetTypeRequireBuild(target_dict): 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.""" + . 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 = {} @@ -378,9 +378,10 @@ def _GenerateTargets(data, target_list, target_dicts, toplevel_dir, files, build 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"} - ) + 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: @@ -426,9 +427,9 @@ def _GenerateTargets(data, target_list, target_dicts, toplevel_dir, files, build 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.""" + . 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 {}, [] @@ -445,15 +446,15 @@ def _GetUnqualifiedToTargetMapping(all_targets, 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.""" + 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} - ): + if target.match_status in { + MATCH_STATUS_MATCHES, + MATCH_STATUS_MATCHES_BY_DEPENDENCY, + }: return True for dep in target.deps: if _DoesTargetDependOnMatchingTargets(dep): @@ -466,9 +467,9 @@ def _DoesTargetDependOnMatchingTargets(target): 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.""" + 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: @@ -479,11 +480,11 @@ def _GetTargetsDependingOnMatchingTargets(possible_targets): 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.""" + 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 @@ -536,8 +537,8 @@ def _AddCompileTargets(target, roots, add_if_no_ancestor, result): 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.""" + 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) @@ -591,7 +592,7 @@ def _WriteOutput(params, **values): def _WasGypIncludeFileModified(params, files): """Returns true if one of the files in |files| is in the set of included - files.""" + files.""" if params["options"].includes: for include in params["options"].includes: if _ToGypPath(os.path.normpath(include)) in files: @@ -607,7 +608,7 @@ def _NamesNotIn(names, mapping): def _LookupTargets(names, mapping): """Returns a list of the mapping[name] for each value in |names| that is in - |mapping|.""" + |mapping|.""" return [mapping[name] for name in names if name in mapping] @@ -699,7 +700,7 @@ def find_matching_test_target_names(self): ) & 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. + # 'all' is subsequently added to the matching names below. matching_test_targets = list( set(matching_test_targets) & set(test_targets_no_all) ) @@ -747,7 +748,7 @@ def GenerateOutput(target_list, target_dicts, data, params): if not config.files: raise Exception( - "Must specify files to analyze via config_path generator " "flag" + "Must specify files to analyze via config_path generator flag" ) toplevel_dir = _ToGypPath(os.path.abspath(params["options"].toplevel_dir)) diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py index 9a796702142e3..5d5cae2afbf66 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py @@ -15,13 +15,14 @@ # 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 +import gyp +import gyp.common +from gyp.generator import make # Reuse global functions from make backend. + generator_default_variables = { "OS": "android", "EXECUTABLE_PREFIX": "", @@ -176,9 +177,7 @@ def Write( 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_MODULE_TARGET_ARCH := $(TARGET_$(GYP_VAR_PREFIX)ARCH)") self.WriteLn("LOCAL_SDK_VERSION := %s" % sdk_version) # Grab output directories; needed for Actions and Rules. @@ -379,7 +378,7 @@ def WriteRules(self, rules, extra_sources, extra_outputs): 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_root, _rule_source_ext) = os.path.splitext( rule_source_basename ) @@ -587,11 +586,11 @@ def WriteSources(self, spec, configs, extra_sources): 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: + if ( + "$(gyp_shared_intermediate_dir)" in source + or "$(gyp_intermediate_dir)" in source + or (IsCPPExtension(ext) and ext != local_cpp_extension) + ): extra_sources.append(source) else: local_files.append(os.path.normpath(os.path.join(self.path, source))) @@ -730,19 +729,17 @@ def ComputeOutput(self, spec): path = "$($(GYP_HOST_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)" else: path = "$($(GYP_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)" + # Other targets just get built into their intermediate dir. + elif self.toolset == "host": + path = ( + "$(call intermediates-dir-for,%s,%s,true,," + "$(GYP_HOST_VAR_PREFIX))" % (self.android_class, self.android_module) + ) 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 = ( - "$(call intermediates-dir-for," - f"{self.android_class},{self.android_module},,,$(GYP_VAR_PREFIX))" - ) + 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)) @@ -769,7 +766,7 @@ def ExtractIncludesFromCFlags(self, 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. + A tuple of lists: (clean_cflags, include_paths). "-I.." is trimmed. """ clean_cflags = [] include_paths = [] @@ -901,8 +898,7 @@ def WriteTarget( if self.type != "none": self.WriteTargetFlags(spec, configs, link_deps) - settings = spec.get("aosp_build_settings", {}) - if settings: + if settings := spec.get("aosp_build_settings", {}): self.WriteLn("### Set directly by aosp_build_settings.") for k, v in settings.items(): if isinstance(v, list): @@ -1003,9 +999,9 @@ def LocalPathify(self, 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} !)" + 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): @@ -1047,9 +1043,9 @@ def CalculateMakefilePath(build_file, base_name): 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." + 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 ) @@ -1069,9 +1065,9 @@ def CalculateMakefilePath(build_file, base_name): 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." + 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") diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py index 320a891aa8adc..dc9ea39acb7fc 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py @@ -28,11 +28,11 @@ CMakeLists.txt file. """ - import multiprocessing import os import signal import subprocess + import gyp.common import gyp.xcode_emulation @@ -96,11 +96,11 @@ def Linkable(filename): 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 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): @@ -113,10 +113,10 @@ def NormjoinPathForceCMakeSource(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. - """ + 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)) @@ -125,19 +125,19 @@ def NormjoinPath(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 + 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 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 - """ + 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('"', '\\"') @@ -236,25 +236,25 @@ def __init__(self, command, modifier, property_modifier): 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: '.' - """ + 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. - """ + 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}" @@ -336,14 +336,14 @@ def NormjoinRulePathForceCMakeSource(base_path, rel_path, rule_source): 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. - """ + 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"]) @@ -454,13 +454,13 @@ def WriteRules(target_name, rules, extra_sources, extra_deps, path_to_gyp, outpu 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. - """ + 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. @@ -584,26 +584,26 @@ def CreateCMakeTargetFullName(qualified_target): 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. + 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. + 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. - """ + 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() + self.cmake_target_base_names_conflicting = set() cmake_target_base_names_seen = set() for qualified_target in target_list: @@ -612,11 +612,11 @@ def __init__(self, target_list): 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) + self.cmake_target_base_names_conflicting.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: + if base_name in self.cmake_target_base_names_conflicting: return CreateCMakeTargetFullName(qualified_target) return base_name @@ -809,8 +809,7 @@ def WriteTarget( # 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: + if (library_dirs := config.get("library_dirs")) is not None: output.write("link_directories(") for library_dir in library_dirs: output.write(" ") @@ -1294,8 +1293,7 @@ def CallGenerateOutputForConfig(arglist): def GenerateOutput(target_list, target_dicts, data, params): - user_config = params.get("generator_flags", {}).get("config", None) - if user_config: + if user_config := params.get("generator_flags", {}).get("config", None): GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]["configurations"] diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py index 0ffa3bb5980fe..1361aeca48d0c 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py @@ -2,11 +2,12 @@ # 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 +import gyp.common +import gyp.xcode_emulation + generator_additional_non_configuration_keys = [] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] @@ -99,7 +100,7 @@ def resolve(filename): 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( + build_file, _target_name, _toolset = gyp.common.ParseQualifiedTarget( qualified_target ) if IsMac(params): @@ -108,10 +109,14 @@ def GenerateOutput(target_list, target_dicts, data, params): cwd = os.path.dirname(build_file) AddCommandsForTarget(cwd, target, params, per_config_commands) + output_dir = None try: - output_dir = params["options"].generator_output - except (AttributeError, KeyError): - output_dir = params["generator_flags"].get("output_dir", "out") + # 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) diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py index 99d5c1fd69db3..c919674024e69 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py @@ -3,11 +3,12 @@ # found in the LICENSE file. +import json import os + import gyp import gyp.common import gyp.msvs_emulation -import json generator_supports_multiple_toolsets = True @@ -55,7 +56,7 @@ def CalculateVariables(default_variables, params): def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by - gyp).""" + gyp).""" generator_flags = params.get("generator_flags", {}) if generator_flags.get("adjust_static_libraries", False): global generator_wants_static_library_dependencies_adjusted diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py index 52aeae6050990..685cd08c964b9 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py @@ -17,14 +17,15 @@ This generator has no automated tests, so expect it to be broken. """ -from xml.sax.saxutils import escape import os.path +import shlex import subprocess +import xml.etree.ElementTree as ET +from xml.sax.saxutils import escape + import gyp import gyp.common import gyp.msvs_emulation -import shlex -import xml.etree.ElementTree as ET generator_wants_static_library_dependencies_adjusted = False @@ -68,7 +69,7 @@ def CalculateVariables(default_variables, params): def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by - gyp).""" + gyp).""" generator_flags = params.get("generator_flags", {}) if generator_flags.get("adjust_static_libraries", False): global generator_wants_static_library_dependencies_adjusted @@ -85,10 +86,10 @@ def GetAllIncludeDirectories( ): """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. - """ + 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 = [] @@ -177,11 +178,11 @@ def GetAllIncludeDirectories( 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. - """ + 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", {}) @@ -201,10 +202,10 @@ def GetCompilerPath(target_list, data, options): 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. - """ + 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 = {} @@ -372,8 +373,8 @@ 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.""" + 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") @@ -450,8 +451,7 @@ def GenerateOutput(target_list, target_dicts, data, params): 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: + if user_config := params.get("generator_flags", {}).get("config", None): GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]["configurations"] diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py index 4171704c47a4b..89af24a201b10 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py @@ -30,10 +30,9 @@ to change. """ - -import gyp.common import pprint +import gyp.common # These variables should just be spit back out as variable references. _generator_identity_variables = [ @@ -74,7 +73,7 @@ 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] + [input_file, _target] = gyp.common.ParseQualifiedTarget(qualified_target)[0:2] if input_file[-4:] != ".gyp": continue diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py index 625b6d65ca1a6..72d22ff32b92d 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py @@ -13,11 +13,9 @@ 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 = [ @@ -51,7 +49,7 @@ def GenerateOutput(target_list, target_dicts, data, params): # locals are available, and identify gypsh. banner = ( f"Python {sys.version} on {sys.platform}\nlocals.keys() = " - f"{repr(sorted(locals.keys()))}\ngypsh" + f"{sorted(locals.keys())!r}\ngypsh" ) code.interact(banner, local=locals) diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py index 1b9974948e4de..16b6f4e80b119 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py @@ -22,16 +22,17 @@ # the side to keep the files readable. +import hashlib 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": "", @@ -77,7 +78,7 @@ def CalculateVariables(default_variables, params): # Copy additional generator configuration data from Xcode, which is shared # by the Mac Make generator. - import gyp.generator.xcode as xcode_generator + import gyp.generator.xcode as xcode_generator # noqa: PLC0415 global generator_additional_non_configuration_keys generator_additional_non_configuration_keys = getattr( @@ -207,7 +208,7 @@ def CalculateGeneratorInputInfo(params): LINK_COMMANDS_MAC = """\ quiet_cmd_alink = LIBTOOL-STATIC $@ -cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) +cmd_alink = rm -f $@ && %(python)s 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) @@ -217,7 +218,7 @@ def CalculateGeneratorInputInfo(params): 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 +""" % {"python": sys.executable} # noqa: E501 LINK_COMMANDS_ANDROID = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ @@ -378,7 +379,7 @@ def CalculateGeneratorInputInfo(params): CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS) LINK.target ?= %(LINK.target)s LDFLAGS.target ?= $(LDFLAGS) -AR.target ?= $(AR) +AR.target ?= %(AR.target)s PLI.target ?= %(PLI.target)s # C++ apps need to be linked with g++. @@ -442,13 +443,27 @@ def CalculateGeneratorInputInfo(params): 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). -sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) +# 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 'y| |\n|' $(depfile).raw |\ +# 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) @@ -600,14 +615,14 @@ def CalculateGeneratorInputInfo(params): # 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) $< "$@" +cmd_mac_tool = %(python)s gyp-mac-tool $(4) $< "$@" quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ -cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) +cmd_mac_package_framework = %(python)s 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 +""" % {"python": sys.executable} # noqa: E501 def WriteRootHeaderSuffixRules(writer): @@ -725,6 +740,12 @@ def QuoteIfNecessary(string): 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) @@ -775,7 +796,7 @@ def __init__(self, generator_flags, flavor): self.suffix_rules_objdir2 = {} # Generate suffix rules for all compilable extensions. - for ext in COMPILABLE_EXTENSIONS: + for ext, value in COMPILABLE_EXTENSIONS.items(): # Suffix rules for source folder. self.suffix_rules_srcdir.update( { @@ -784,7 +805,7 @@ def __init__(self, generator_flags, flavor): $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD \t@$(call do_cmd,%s,1) """ - % (ext, COMPILABLE_EXTENSIONS[ext]) + % (ext, value) ) } ) @@ -797,7 +818,7 @@ def __init__(self, generator_flags, flavor): $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD \t@$(call do_cmd,%s,1) """ - % (ext, COMPILABLE_EXTENSIONS[ext]) + % (ext, value) ) } ) @@ -808,7 +829,7 @@ def __init__(self, generator_flags, flavor): $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD \t@$(call do_cmd,%s,1) """ - % (ext, COMPILABLE_EXTENSIONS[ext]) + % (ext, value) ) } ) @@ -859,7 +880,7 @@ def Write( self.output = self.ComputeMacBundleOutput(spec) self.output_binary = self.ComputeMacBundleBinaryOutput(spec) else: - self.output = self.output_binary = self.ComputeOutput(spec) + self.output = self.output_binary = replace_sep(self.ComputeOutput(spec)) self.is_standalone_static_library = bool( spec.get("standalone_static_library", 0) @@ -985,7 +1006,7 @@ def WriteSubMake(self, output_filename, makefile_path, targets, build_dir): # sub-project dir (see test/subdirectory/gyptest-subdir-all.py). self.WriteLn( "export builddir_name ?= %s" - % os.path.join(os.path.dirname(output_filename), build_dir) + % replace_sep(os.path.join(os.path.dirname(output_filename), build_dir)) ) self.WriteLn(".PHONY: all") self.WriteLn("all:") @@ -1148,7 +1169,7 @@ def WriteRules( 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_root, _rule_source_ext) = os.path.splitext( rule_source_basename ) @@ -1426,9 +1447,7 @@ def WriteSources( 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("# Add to the list of files we specially track dependencies for.") self.WriteLn("all_deps += $(OBJS)") self.WriteLn() @@ -1437,7 +1456,7 @@ def WriteSources( self.WriteMakeRule( ["$(OBJS)"], deps, - comment="Make sure our dependencies are built " "before any of us.", + comment="Make sure our dependencies are built before any of us.", order_only=True, ) @@ -1448,12 +1467,11 @@ def WriteSources( self.WriteMakeRule( ["$(OBJS)"], extra_outputs, - comment="Make sure our actions/rules run " "before any of us.", + comment="Make sure our actions/rules run before any of us.", order_only=True, ) - pchdeps = precompiled_header.GetObjDependencies(compilable, objs) - if pchdeps: + if pchdeps := precompiled_header.GetObjDependencies(compilable, objs): self.WriteLn("# Dependencies from obj files to their precompiled headers") for source, obj, gch in pchdeps: self.WriteLn(f"{obj}: {gch}") @@ -1486,7 +1504,8 @@ def WriteSources( "$(OBJS): GYP_OBJCFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " - "%s " % precompiled_header.GetInclude("m") + "%s " + % precompiled_header.GetInclude("m") + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE)) " "$(CFLAGS_OBJC_$(BUILDTYPE))" @@ -1495,7 +1514,8 @@ def WriteSources( "$(OBJS): GYP_OBJCXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " - "%s " % precompiled_header.GetInclude("mm") + "%s " + % precompiled_header.GetInclude("mm") + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE)) " "$(CFLAGS_OBJCC_$(BUILDTYPE))" @@ -1587,8 +1607,7 @@ def ComputeOutputBasename(self, spec): target_prefix = spec.get("product_prefix", target_prefix) target = spec.get("product_name", target) - product_ext = spec.get("product_extension") - if product_ext: + if product_ext := spec.get("product_extension"): target_ext = "." + product_ext return target_prefix + target + target_ext @@ -1686,7 +1705,7 @@ def WriteTarget( self.WriteMakeRule( extra_outputs, deps, - comment=("Preserve order dependency of " "special output on deps."), + comment=("Preserve order dependency of special output on deps."), order_only=True, ) @@ -1725,7 +1744,8 @@ def WriteTarget( # 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", []) + if library_dirs := config.get("library_dirs", []): + library_dirs = [Sourceify(self.Absolutify(i)) for i in library_dirs] ldflags += [("-L%s" % library_dir) for library_dir in library_dirs] self.WriteList(ldflags, "LDFLAGS_%s" % configname) if self.flavor == "mac": @@ -1766,13 +1786,13 @@ def WriteTarget( # using ":=". self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv()) - for configname in target_postbuilds: + for configname, value in target_postbuilds.items(): self.WriteLn( "%s: TARGET_POSTBUILDS_%s := %s" % ( QuoteSpaces(self.output), configname, - gyp.common.EncodePOSIXShellList(target_postbuilds[configname]), + gyp.common.EncodePOSIXShellList(value), ) ) @@ -1821,7 +1841,7 @@ def WriteTarget( # 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 + # on every build (expensive, especially with postbuilds), explicitly # update the time on the framework directory. self.WriteLn("\t@touch -c %s" % QuoteSpaces(self.output)) @@ -1831,7 +1851,7 @@ def WriteTarget( "on the bundle, not the binary (target '%s')" % self.target ) assert "product_dir" not in spec, ( - "Postbuilds do not work with " "custom product_dir" + "Postbuilds do not work with custom product_dir" ) if self.type == "executable": @@ -1868,7 +1888,7 @@ def WriteTarget( self.flavor not in ("mac", "openbsd", "netbsd", "win") and not self.is_standalone_static_library ): - if self.flavor in ("linux", "android"): + if self.flavor in ("linux", "android", "openharmony"): self.WriteMakeRule( [self.output_binary], link_deps, @@ -1882,21 +1902,20 @@ def WriteTarget( part_of_all, postbuilds=postbuilds, ) + elif self.flavor in ("linux", "android", "openharmony"): + self.WriteMakeRule( + [self.output_binary], + link_deps, + actions=["$(call create_archive,$@,$^)"], + ) 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, - ) + self.WriteDoCmd( + [self.output_binary], + link_deps, + "alink", + part_of_all, + postbuilds=postbuilds, + ) elif self.type == "shared_library": self.WriteLn( "%s: LD_INPUTS := %s" @@ -2063,7 +2082,7 @@ def WriteList(self, value_list, variable=None, prefix="", quoter=QuoteIfNecessar """ values = "" if value_list: - value_list = [quoter(prefix + value) for value in 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") @@ -2150,7 +2169,7 @@ def WriteMakeRule( # - The multi-output rule will have an do-nothing recipe. # Hash the target name to avoid generating overlong filenames. - cmddigest = hashlib.sha1( + cmddigest = hashlib.sha256( (command or self.target).encode("utf-8") ).hexdigest() intermediate = "%s.intermediate" % cmddigest @@ -2369,9 +2388,15 @@ def WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files) "\t$(call do_cmd,regen_makefile)\n\n" % { "makefile_name": makefile_name, - "deps": " ".join(SourceifyAndQuoteSpaces(bf) for bf in build_files), - "cmd": gyp.common.EncodePOSIXShellList( - [gyp_binary, "-fmake"] + gyp.RegenerateFlags(options) + build_files_args + "deps": replace_sep( + " ".join(sorted(SourceifyAndQuoteSpaces(bf) for bf in build_files)) + ), + "cmd": replace_sep( + gyp.common.EncodePOSIXShellList( + [gyp_binary, "-fmake"] + + gyp.RegenerateFlags(options) + + build_files_args + ) ), } ) @@ -2435,36 +2460,55 @@ def CalculateMakefilePath(build_file, base_name): makefile_path = os.path.join( options.toplevel_dir, options.generator_output, makefile_name ) - srcdir = gyp.common.RelativePath(srcdir, options.generator_output) + 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_LINUX, + "link_commands": link_commands, "extra_commands": "", "srcdir": srcdir, "copy_archive_args": copy_archive_arguments, "makedep_args": makedep_arguments, - "CC.target": GetEnvironFallback(("CC_target", "CC"), "$(CC)"), - "AR.target": GetEnvironFallback(("AR_target", "AR"), "$(AR)"), - "CXX.target": GetEnvironFallback(("CXX_target", "CXX"), "$(CXX)"), - "LINK.target": GetEnvironFallback(("LINK_target", "LINK"), "$(LINK)"), - "PLI.target": GetEnvironFallback(("PLI_target", "PLI"), "pli"), - "CC.host": GetEnvironFallback(("CC_host", "CC"), "gcc"), - "AR.host": GetEnvironFallback(("AR_host", "AR"), "ar"), - "CXX.host": GetEnvironFallback(("CXX_host", "CXX"), "g++"), - "LINK.host": GetEnvironFallback(("LINK_host", "LINK"), "$(CXX.host)"), - "PLI.host": GetEnvironFallback(("PLI_host", "PLI"), "pli"), + "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" + flock_command = "%s gyp-mac-tool flock" % sys.executable header_params.update( { "flock": flock_command, @@ -2514,7 +2558,7 @@ def CalculateMakefilePath(build_file, base_name): header_params.update( { "copy_archive_args": copy_archive_arguments, - "flock": "./gyp-flock-tool flock", + "flock": "%s gyp-flock-tool flock" % sys.executable, "flock_index": 2, } ) @@ -2530,7 +2574,7 @@ def CalculateMakefilePath(build_file, base_name): { "copy_archive_args": copy_archive_arguments, "link_commands": LINK_COMMANDS_AIX, - "flock": "./gyp-flock-tool flock", + "flock": "%s gyp-flock-tool flock" % sys.executable, "flock_index": 2, } ) @@ -2540,7 +2584,7 @@ def CalculateMakefilePath(build_file, base_name): { "copy_archive_args": copy_archive_arguments, "link_commands": LINK_COMMANDS_OS400, - "flock": "./gyp-flock-tool flock", + "flock": "%s gyp-flock-tool flock" % sys.executable, "flock_index": 2, } ) diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py index 6f0f8c1ab64c9..42bee33d9b63d 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py @@ -9,22 +9,21 @@ 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 - +from gyp import ( + MSVSNew, + MSVSProject, + MSVSSettings, + MSVSToolFile, + MSVSUserFile, + MSVSUtil, + MSVSVersion, + easy_xml, +) +from gyp.common import GypError, OrderedSet # Regular expression for validating Visual Studio GUIDs. If the GUID # contains lowercase hex letters, MSVS will be fine. However, @@ -137,15 +136,15 @@ def _GetDomainAndUserName(): 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. + 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 + Arguments: + source: The path to be normalize.d - Returns: - The normalized path. - """ + Returns: + The normalized path. + """ normalized = os.path.normpath(source) if source.count("$") == normalized.count("$"): source = normalized @@ -155,11 +154,11 @@ def _NormalizedSource(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. - """ + Arguments: + path: The path to convert, may contain / etc. + Returns: + The path with all slashes made into backslashes. + """ if ( fixpath_prefix and path @@ -180,12 +179,12 @@ def _FixPath(path, separator="\\"): 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:") + 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:", "C:")) def _FixPaths(paths, separator="\\"): @@ -198,22 +197,22 @@ def _ConvertSourcesToFilterHierarchy( ): """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'])] - """ + 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 = [] @@ -276,7 +275,7 @@ def _ToolAppend(tools, tool_name, setting, value, only_if_unset=False): 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: + if isinstance(value, str): value = value.replace("/", "\\") else: value = [i.replace("/", "\\") for i in value] @@ -288,7 +287,7 @@ def _ToolSetOrAppend(tools, tool_name, setting, value, only_if_unset=False): if tool.get(setting): if only_if_unset: return - if type(tool[setting]) == list and type(value) == list: + if isinstance(tool[setting], list) and isinstance(value, list): tool[setting] += value else: raise TypeError( @@ -362,7 +361,6 @@ def _ConfigWindowsTargetPlatformVersion(config_data, version): 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" @@ -426,8 +424,7 @@ def _BuildCommandLineForRuleRaw( # 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:] + 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] @@ -460,17 +457,17 @@ def _BuildCommandLineForRule(spec, rule, has_input_path, 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 - """ + 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 @@ -497,15 +494,15 @@ def _AddCustomBuildToolForMSVS( ): """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 - """ + 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( @@ -527,12 +524,12 @@ def _AddCustomBuildToolForMSVS( 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. - """ + 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() @@ -560,12 +557,12 @@ def _AddAccumulatedActionsToMSVS(p, spec, actions_dict): 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. - """ + 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] ) @@ -581,24 +578,24 @@ def _RuleExpandPath(path, input_file): 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. - """ + 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. - """ + 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() @@ -614,13 +611,13 @@ def _RuleInputsAndOutputs(rule, trigger_file): 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 - """ + 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"] @@ -659,14 +656,14 @@ def _Cygwinify(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. - """ + 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. @@ -744,17 +741,17 @@ def _GenerateExternalRules(rules, output_dir, spec, sources, options, actions_to 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. + 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. + Args: + s: The string to be escaped. - Returns: - The escaped string. - """ + Returns: + The escaped string. + """ s = s.replace("%", "%%") return s @@ -765,17 +762,17 @@ def _EscapeEnvironmentVariableExpansion(s): 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. + 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. - """ + Args: + s: the string to be escaped. + Returns: + the escaped string. + """ def _Replace(match): # For a literal quote, CommandLineToArgv requires an odd number of @@ -796,24 +793,24 @@ def _Replace(match): 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. - """ + 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 @@ -860,7 +857,7 @@ def _EscapeCommandLineArgumentForMSBuild(s): """Escapes a Windows command-line argument for use by MSBuild.""" def _Replace(match): - return (len(match.group(1)) / 2 * 4) * "\\" + '\\"' + return (len(match.group(1)) // 2 * 4) * "\\" + '\\"' # Escape all quotes so that they are interpreted literally. s = quote_replacer_regex2.sub(_Replace, s) @@ -897,15 +894,15 @@ def _GenerateRulesForMSVS( ): """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 - """ + 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))] @@ -947,12 +944,12 @@ def _AdjustSourcesForRules(rules, sources, excluded_sources, is_msbuild): 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. - """ + 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] @@ -964,14 +961,14 @@ def _GetDefaultConfiguration(spec): 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. - """ + 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. @@ -990,13 +987,13 @@ def _GetGuidOfProject(proj_path, spec): 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. - """ + 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") @@ -1010,14 +1007,14 @@ def _GetMsbuildToolsetOfProject(proj_path, spec, version): 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. - """ + 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. @@ -1033,12 +1030,12 @@ def _GenerateProject(project, options, version, generator_flags, spec): 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. - """ + 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) @@ -1095,11 +1092,11 @@ def _GenerateMSVSProject(project, options, version, generator_flags): 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. - """ + 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"]: @@ -1111,14 +1108,14 @@ def _GetUniquePlatforms(spec): 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. - """ + 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"]) @@ -1128,14 +1125,14 @@ def _CreateMSVSUserFile(proj_path, version, spec): def _GetMSVSConfigurationType(spec, build_file): """Returns the configuration type for this project. - It's a number defined by Microsoft. May raise an exception. + 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. - """ + 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 @@ -1162,17 +1159,17 @@ def _GetMSVSConfigurationType(spec, build_file): 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. - """ + 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) @@ -1252,12 +1249,12 @@ def _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config): 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. - """ + 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( @@ -1276,12 +1273,12 @@ def _GetIncludeDirs(config): 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. - """ + 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) @@ -1291,11 +1288,11 @@ def _GetLibraryDirs(config): 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. - """ + 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). @@ -1317,14 +1314,14 @@ def _GetLibraries(spec): 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. + 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) - """ + 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 = "" @@ -1356,17 +1353,16 @@ def _GetOutputFilePathAndTool(spec, msbuild): 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: + 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 + """ + if target_extension := spec.get("product_extension"): return "." + target_extension return None @@ -1374,12 +1370,12 @@ def _GetOutputTargetExt(spec): 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. - """ + 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) @@ -1413,17 +1409,17 @@ def _GetModuleDefinition(spec): 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. - """ + 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 isinstance(value, list): if ( tool == "VCLinkerTool" and setting == "AdditionalDependencies" ) or setting == "AdditionalOptions": @@ -1440,15 +1436,15 @@ def _ConvertToolsToExpectedForm(tools): 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. - """ + 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) @@ -1489,18 +1485,18 @@ def _AddNormalizedSources(sources_set, 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. - """ + 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() @@ -1530,19 +1526,19 @@ def _AdjustSourcesAndConvertToFilterHierarchy( ): """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) - """ + 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. @@ -1670,7 +1666,7 @@ def _HandlePreCompiledHeaders(p, sources, spec): p.AddFileConfig( source, _ConfigFullName(config_name, config), {}, tools=[tool] ) - basename, extension = os.path.splitext(source) + _basename, extension = os.path.splitext(source) if extension == ".c": extensions_excluded_from_precompile = [".cc", ".cpp", ".cxx"] else: @@ -1681,7 +1677,7 @@ def DisableForSourceTree(source_tree): if isinstance(source, MSVSProject.Filter): DisableForSourceTree(source.contents) else: - basename, extension = os.path.splitext(source) + _basename, extension = os.path.splitext(source) if extension in extensions_excluded_from_precompile: for config_name, config in spec["configurations"].items(): tool = MSVSProject.Tool( @@ -1779,8 +1775,8 @@ def _GetCopies(spec): 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}' + f'mkdir {full_dst} 2>nul & cd "{_FixPath(base_dir)}" ' + f'&& xcopy /e /f /y "{outer_dir}" {full_dst}' ) copies.append( ( @@ -1816,7 +1812,7 @@ def _DictsToFolders(base_path, bucket, flat): # Convert to folders recursively. children = [] for folder, contents in bucket.items(): - if type(contents) == dict: + if isinstance(contents, dict): folder_children = _DictsToFolders( os.path.join(base_path, folder), contents, flat ) @@ -1838,9 +1834,13 @@ 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": + if ( + isinstance(node, dict) + and len(node) == 1 + and next(iter(node)) == parent + ".vcproj" + ): return node[next(iter(node))] - if type(node) != dict: + if not isinstance(node, dict): return node for child in node: node[child] = _CollapseSingles(child, node[child]) @@ -1860,7 +1860,7 @@ def _GatherSolutionFolders(sln_projects, project_objects, flat): # 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: + while len(root) == 1 and isinstance(root[next(iter(root))], dict): root = root[next(iter(root))] # Collapse singles. root = _CollapseSingles("", root) @@ -1896,9 +1896,8 @@ def _GetPlatformOverridesOfProject(spec): for config_name, c in spec["configurations"].items(): config_fullname = _ConfigFullName(config_name, c) platform = c.get("msvs_target_platform", _ConfigPlatform(c)) - fixed_config_fullname = ( - f"{_ConfigBaseName(config_name, _ConfigPlatform(c))}|{platform}" - ) + 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 @@ -1908,14 +1907,14 @@ def _GetPlatformOverridesOfProject(spec): 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. - """ + 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 = {} @@ -1959,15 +1958,15 @@ def _CreateProjectObjects(target_list, target_dicts, options, msvs_version): 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. - """ + 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"): @@ -2078,12 +2077,12 @@ def CalculateGeneratorInputInfo(params): 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. - """ + 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"] @@ -2177,14 +2176,14 @@ def _GenerateMSBuildFiltersFile( ): """Generate the filters file. - This file is used by Visual Studio to organize the presentation of source - files into folders. + 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. - """ + 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( @@ -2225,14 +2224,14 @@ def _AppendFiltersForMSBuild( ): """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. - """ + 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. @@ -2276,13 +2275,13 @@ def _MapFileToMsBuildSourceType( ): """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. + 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) - """ + 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: @@ -2370,22 +2369,22 @@ def _GenerateRulesForMSBuild( 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. - """ + 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"] @@ -2507,7 +2506,7 @@ def _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules): rule_name = rule.rule_name target_outputs = "%%(%s.Outputs)" % rule_name target_inputs = ( - "%%(%s.Identity);%%(%s.AdditionalDependencies);" "$(MSBuildProjectFile)" + "%%(%s.Identity);%%(%s.AdditionalDependencies);$(MSBuildProjectFile)" ) % (rule_name, rule_name) rule_inputs = "%%(%s.Identity)" % rule_name extension_condition = ( @@ -2910,7 +2909,7 @@ def _GetConfigurationCondition(name, settings, spec): def _GetMSBuildProjectConfigurations(configurations, spec): group = ["ItemGroup", {"Label": "ProjectConfigurations"}] - for (name, settings) in sorted(configurations.items()): + for name, settings in sorted(configurations.items()): configuration, platform = _GetConfigurationAndPlatform(name, settings, spec) designation = f"{configuration}|{platform}" group.append( @@ -3004,10 +3003,11 @@ def _GetMSBuildConfigurationDetails(spec, build_file): vctools_version = msbuild_attributes.get("VCToolsVersion") config_type = msbuild_attributes.get("ConfigurationType") _AddConditionalProperty(properties, condition, "ConfigurationType", config_type) - spectre_mitigation = msbuild_attributes.get('SpectreMitigation') + spectre_mitigation = msbuild_attributes.get("SpectreMitigation") if spectre_mitigation: - _AddConditionalProperty(properties, condition, "SpectreMitigation", - spectre_mitigation) + _AddConditionalProperty( + properties, condition, "SpectreMitigation", spectre_mitigation + ) if config_type == "Driver": _AddConditionalProperty(properties, condition, "DriverType", "WDM") _AddConditionalProperty( @@ -3100,9 +3100,7 @@ def _ConvertMSVSBuildAttributes(spec, config, build_file): 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": + elif a == "SpectreMitigation" or a == "VCToolsVersion": msbuild_attributes[a] = msvs_attributes[a] else: print("Warning: Do not know how to convert MSVS attribute " + a) @@ -3169,8 +3167,7 @@ def _GetMSBuildAttributes(spec, config, build_file): "windows_driver": "Link", "static_library": "Lib", } - msbuild_tool = msbuild_tool_map.get(spec["type"]) - if msbuild_tool: + if msbuild_tool := msbuild_tool_map.get(spec["type"]): msbuild_settings = config["finalized_msbuild_settings"] out_file = msbuild_settings[msbuild_tool].get("OutputFile") if out_file: @@ -3187,8 +3184,7 @@ def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file): # 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: + if cygwin_dirs := spec.get("msvs_cygwin_dirs", ["."])[0]: 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 @@ -3199,7 +3195,7 @@ def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file): new_paths = "$(ExecutablePath);" + ";".join(new_paths) properties = {} - for (name, configuration) in sorted(configurations.items()): + for name, configuration in sorted(configurations.items()): condition = _GetConfigurationCondition(name, configuration, spec) attributes = _GetMSBuildAttributes(spec, configuration, build_file) msbuild_settings = configuration["finalized_msbuild_settings"] @@ -3238,14 +3234,14 @@ def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file): 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. - """ + 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] @@ -3262,20 +3258,20 @@ def _AddConditionalProperty(properties, condition, name, value): 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. - """ + 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. + # Use a definition of edges such that user_of_variable -> used_variable. # This happens to be easier in this case, since a variable's # definition contains all variables it references in a single string. edges = set() @@ -3317,7 +3313,7 @@ def GetEdges(node): def _GetMSBuildToolSettingsSections(spec, configurations): groups = [] - for (name, configuration) in sorted(configurations.items()): + for name, configuration in sorted(configurations.items()): msbuild_settings = configuration["finalized_msbuild_settings"] group = [ "ItemDefinitionGroup", @@ -3373,7 +3369,6 @@ def _FinalizeMSBuildSettings(spec, 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 @@ -3411,8 +3406,12 @@ def _FinalizeMSBuildSettings(spec, configuration): msbuild_settings, "ClCompile", "DisableSpecificWarnings", disabled_warnings ) # Turn on precompiled headers if appropriate. - if precompiled_header: - precompiled_header = os.path.split(precompiled_header)[1] + if precompiled_header := configuration.get("msvs_precompiled_header"): + # While MSVC works with just file name eg. "v8_pch.h", ClangCL requires + # the full path eg. "tools/msvs/pch/v8_pch.h" to find the file. + # P.S. Only ClangCL defines msbuild_toolset, for MSVC it is None. + if configuration.get("msbuild_toolset") != "ClangCL": + precompiled_header = os.path.split(precompiled_header)[1] _ToolAppend(msbuild_settings, "ClCompile", "PrecompiledHeader", "Use") _ToolAppend( msbuild_settings, "ClCompile", "PrecompiledHeaderFile", precompiled_header @@ -3442,7 +3441,7 @@ def _FinalizeMSBuildSettings(spec, configuration): def _GetValueFormattedForMSBuild(tool_name, name, value): - if type(value) == list: + if isinstance(value, list): # For some settings, VS2010 does not automatically extends the settings # TODO(jeanluc) Is this what we want? if name in [ @@ -3473,25 +3472,24 @@ def _GetValueFormattedForMSBuild(tool_name, name, 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. + 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. - """ + 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) + elif "$" 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 @@ -3561,75 +3559,70 @@ def _AddSources2( 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", "" + elif 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"] ) - 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) + # 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): @@ -3827,15 +3820,15 @@ def _GenerateMSBuildProject(project, options, version, generator_flags, spec): 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. + 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. - """ + 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 ) @@ -3883,14 +3876,14 @@ def _GetMSBuildExtensionTargets(targets_files_of_rules): 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. + 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). - """ + 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(): diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py index e80b57f06a130..e3c4758696c40 100755 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py @@ -3,13 +3,13 @@ # 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. """ +"""Unit tests for the msvs.py file.""" -import gyp.generator.msvs as msvs import unittest - from io import StringIO +from gyp.generator import msvs + class TestSequenceFunctions(unittest.TestCase): def setUp(self): diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py index 8ba341e96d3f0..3ceaf470cec20 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py @@ -5,24 +5,24 @@ import collections import copy +import ctypes import hashlib import json import multiprocessing import os.path import re +import shutil import signal import subprocess import sys +from io import StringIO + import gyp import gyp.common import gyp.msvs_emulation -import gyp.MSVSUtil as MSVSUtil import gyp.xcode_emulation - -from io import StringIO - +from gyp import MSVSUtil, ninja_syntax from gyp.common import GetEnvironFallback -import gyp.ninja_syntax as ninja_syntax generator_default_variables = { "EXECUTABLE_PREFIX": "", @@ -246,7 +246,7 @@ def __init__( if flavor == "win": # See docstring of msvs_emulation.GenerateEnvironmentFiles(). self.win_env = {} - for arch in ("x86", "x64"): + for arch in ("x86", "x64", "arm64"): self.win_env[arch] = "environment." + arch # Relative path from build output dir to base dir. @@ -264,8 +264,7 @@ def ExpandSpecial(self, path, product_dir=None): dir. """ - PRODUCT_DIR = "$!PRODUCT_DIR" - if PRODUCT_DIR in path: + if (PRODUCT_DIR := "$!PRODUCT_DIR") in path: if product_dir: path = path.replace(PRODUCT_DIR, product_dir) else: @@ -273,8 +272,7 @@ def ExpandSpecial(self, path, product_dir=None): path = path.replace(PRODUCT_DIR + "\\", "") path = path.replace(PRODUCT_DIR, ".") - INTERMEDIATE_DIR = "$!INTERMEDIATE_DIR" - if INTERMEDIATE_DIR in path: + if (INTERMEDIATE_DIR := "$!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. @@ -811,9 +809,8 @@ def cygwin_munge(path): 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()) - ) + unique_name = hashlib.sha256(outputs[0].encode("utf-8")).hexdigest() + extra_bindings.append(("unique_name", unique_name)) self.ninja.build( outputs, @@ -1305,7 +1302,7 @@ def WritePchTargets(self, ninja_file, pch_commands): 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. """ + """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 @@ -1349,7 +1346,7 @@ def WriteLink(self, spec, config_name, config, link_deps, compile_deps): def WriteLinkForArch( self, ninja_file, spec, config_name, config, link_deps, compile_deps, arch=None ): - """Write out a link step. Fills out target.binary. """ + """Write out a link step. Fills out target.binary.""" command = { "executable": "link", "loadable_module": "solink_module", @@ -1464,7 +1461,7 @@ def WriteLinkForArch( # 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): + if is_executable and solibs: rpath = "lib/" if self.toolset != "target": rpath += self.toolset @@ -1554,7 +1551,7 @@ def WriteLinkForArch( if pdbname: output = [output, pdbname] - if len(solibs): + if solibs: extra_bindings.append( ("solibs", gyp.common.EncodePOSIXShellList(sorted(solibs))) ) @@ -1757,11 +1754,9 @@ def GetPostbuildCommand(self, spec, output, output_binary, is_command_start): + " && ".join([ninja_syntax.escape(command) for command in postbuilds]) ) command_string = ( - commands - + "); G=$$?; " + commands + "); G=$$?; " # Remove the final output if any postbuild failed. - "((exit $$G) || rm -rf %s) " % output - + "&& exit $$G)" + "((exit $$G) || rm -rf %s) " % output + "&& exit $$G)" ) if is_command_start: return "(" + command_string + " && " @@ -1950,7 +1945,8 @@ def WriteNewNinjaRule( ) else: rspfile_content = gyp.msvs_emulation.EncodeRspFileList( - args, win_shell_flags.quote) + args, win_shell_flags.quote + ) command = ( "%s gyp-win-tool action-wrapper $arch " % sys.executable + rspfile @@ -1996,7 +1992,7 @@ def CalculateVariables(default_variables, params): # Copy additional generator configuration data from Xcode, which is shared # by the Mac Ninja generator. - import gyp.generator.xcode as xcode_generator + import gyp.generator.xcode as xcode_generator # noqa: PLC0415 generator_additional_non_configuration_keys = getattr( xcode_generator, "generator_additional_non_configuration_keys", [] @@ -2019,7 +2015,7 @@ def CalculateVariables(default_variables, params): # Copy additional generator configuration data from VS, which is shared # by the Windows Ninja generator. - import gyp.generator.msvs as msvs_generator + import gyp.generator.msvs as msvs_generator # noqa: PLC0415 generator_additional_non_configuration_keys = getattr( msvs_generator, "generator_additional_non_configuration_keys", [] @@ -2076,20 +2072,17 @@ def OpenOutput(path, mode="w"): def CommandWithWrapper(cmd, wrappers, prog): - wrapper = wrappers.get(cmd, "") - if wrapper: + if wrapper := wrappers.get(cmd, ""): 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: + if pool_size := int(os.environ.get("GYP_LINK_CONCURRENCY") or 0): return pool_size if sys.platform in ("win32", "cygwin"): - import ctypes class MEMORYSTATUSEX(ctypes.Structure): _fields_ = [ @@ -2110,8 +2103,8 @@ class MEMORYSTATUSEX(ctypes.Structure): # 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))) + mem_limit = max(1, stat.ullTotalPhys // (5 * (2**30))) # total / 5GiB + hard_cap = max(1, int(os.environ.get("GYP_LINK_CONCURRENCY_MAX") or 2**32)) return min(mem_limit, hard_cap) elif sys.platform.startswith("linux"): if os.path.exists("/proc/meminfo"): @@ -2122,14 +2115,14 @@ class MEMORYSTATUSEX(ctypes.Structure): 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 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 + return max(1, avail_bytes // (4 * (2**30))) # total / 4GB except subprocess.CalledProcessError: return 1 else: @@ -2210,6 +2203,7 @@ 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" @@ -2305,8 +2299,7 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name 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: + if mac_toolchain_dir := generator_flags.get("mac_toolchain_dir", None): wrappers["LINK"] = "export DEVELOPER_DIR='%s' &&" % mac_toolchain_dir if flavor == "win": @@ -2346,6 +2339,7 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name master_ninja.variable("rc", "rc.exe") master_ninja.variable("ml_x86", "ml.exe") master_ninja.variable("ml_x64", "ml64.exe") + master_ninja.variable("ml_arm64", "armasm64.exe") master_ninja.variable("mt", "mt.exe") else: master_ninja.variable("ld", CommandWithWrapper("LINK", wrappers, ld)) @@ -2417,8 +2411,7 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name "cc_s", description="CC $out", command=( - "$cc $defines $includes $cflags $cflags_c " - "$cflags_pch_c -c $in -o $out" + "$cc $defines $includes $cflags $cflags_c $cflags_pch_c -c $in -o $out" ), ) master_ninja.rule( @@ -2529,11 +2522,10 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name "solink", description="SOLINK $lib", restat=True, - command=mtime_preserving_solink_base - % {"suffix": "@$link_file_list"}, + 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" + "-Wl,--whole-archive $in $solibs -Wl,--no-whole-archive $libs" ), pool="link_pool", ) @@ -2593,9 +2585,9 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name "alink", description="LIBTOOL-STATIC $out, POSTBUILDS", command="rm -f $out && " - "./gyp-mac-tool filter-libtool libtool $libtool_flags " + "%s gyp-mac-tool filter-libtool libtool $libtool_flags " "-static -o $out $in" - "$postbuilds", + "$postbuilds" % sys.executable, ) master_ninja.rule( "lipo", @@ -2682,7 +2674,7 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name master_ninja.rule( "link", description="LINK $out, POSTBUILDS", - command=("$ld $ldflags -o $out " "$in $solibs $libs$postbuilds"), + command=("$ld $ldflags -o $out $in $solibs $libs$postbuilds"), pool="link_pool", ) master_ninja.rule( @@ -2696,41 +2688,44 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name master_ninja.rule( "copy_infoplist", description="COPY INFOPLIST $in", - command="$env ./gyp-mac-tool copy-info-plist $in $out $binary $keys", + command="$env %s gyp-mac-tool copy-info-plist $in $out $binary $keys" + % sys.executable, ) master_ninja.rule( "merge_infoplist", description="MERGE INFOPLISTS $in", - command="$env ./gyp-mac-tool merge-info-plist $out $in", + command="$env %s gyp-mac-tool merge-info-plist $out $in" % sys.executable, ) master_ninja.rule( "compile_xcassets", description="COMPILE XCASSETS $in", - command="$env ./gyp-mac-tool compile-xcassets $keys $in", + command="$env %s gyp-mac-tool compile-xcassets $keys $in" % sys.executable, ) 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", + command="$env %(python)s gyp-mac-tool compile-ios-framework-header-map " + "$out $framework $in && $env %(python)s gyp-mac-tool " + "copy-ios-framework-headers $framework $copy_headers" + % {"python": sys.executable}, ) master_ninja.rule( "mac_tool", description="MACTOOL $mactool_cmd $in", - command="$env ./gyp-mac-tool $mactool_cmd $in $out $binary", + command="$env %s gyp-mac-tool $mactool_cmd $in $out $binary" + % sys.executable, ) master_ninja.rule( "package_framework", description="PACKAGE FRAMEWORK $out, POSTBUILDS", - command="./gyp-mac-tool package-framework $out $version$postbuilds " - "&& touch $out", + command="%s gyp-mac-tool package-framework $out $version$postbuilds " + "&& touch $out" % sys.executable, ) master_ninja.rule( "package_ios_framework", description="PACKAGE IOS FRAMEWORK $out, POSTBUILDS", - command="./gyp-mac-tool package-ios-framework $out $postbuilds " - "&& touch $out", + command="%s gyp-mac-tool package-ios-framework $out $postbuilds " + "&& touch $out" % sys.executable, ) if flavor == "win": master_ninja.rule( @@ -2808,7 +2803,7 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name 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() + hash_for_rules = hashlib.sha256(qualified_target_for_hash).hexdigest() base_path = os.path.dirname(build_file) obj = "obj" @@ -2878,6 +2873,35 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name 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"] diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py index 7d180685b21cf..8b590af8eb386 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py @@ -4,32 +4,43 @@ # 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. """ +"""Unit tests for the ninja.py file.""" import sys import unittest +from pathlib import Path -import gyp.generator.ninja as ninja +from gyp.generator import ninja +from gyp.MSVSVersion import SelectVisualStudioVersion + + +def _has_visual_studio(): + """Check if Visual Studio can be detected by gyp's registry-based detection.""" + if not sys.platform.startswith("win"): + return False + try: + SelectVisualStudioVersion("auto", allow_fallback=False) + return True + except ValueError: + return False class TestPrefixesAndSuffixes(unittest.TestCase): + @unittest.skipUnless( + _has_visual_studio(), + "requires Windows with a Visual Studio installation detected via the registry", + ) 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") - ) + writer = ninja.NinjaWriter( + "foo", "wee", ".", ".", "build.ninja", ".", "build.ninja", "win" + ) + spec = {"target_name": "wee"} + for key, ext in { + "executable": ".exe", + "shared_library": ".dll", + "static_library": ".lib", + }.items(): + self.assertTrue(writer.ComputeOutputFileName(spec, key).endswith(ext)) def test_BinaryNamesLinux(self): writer = ninja.NinjaWriter( @@ -50,6 +61,17 @@ def test_BinaryNamesLinux(self): 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() diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py index 1ac672c3876bd..db4b45d1a04d2 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py @@ -3,19 +3,19 @@ # found in the LICENSE file. -import filecmp -import gyp.common -import gyp.xcodeproj_file -import gyp.xcode_ninja import errno +import filecmp import os -import sys import posixpath import re import shutil import subprocess +import sys import tempfile +import gyp.common +import gyp.xcode_ninja +import gyp.xcodeproj_file # Project files generated by this module will use _intermediate_var as a # custom Xcode setting whose value is a DerivedSources-like directory that's @@ -531,7 +531,7 @@ def AddSourceToTarget(source, type, pbxp, xct): library_extensions = ["a", "dylib", "framework", "o"] basename = posixpath.basename(source) - (root, ext) = posixpath.splitext(basename) + (_root, ext) = posixpath.splitext(basename) if ext: ext = ext[1:].lower() @@ -564,12 +564,12 @@ def AddHeaderToTarget(header, pbxp, xct, is_public): 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. - """ + 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: @@ -592,9 +592,9 @@ def ExpandXcodeVariables(string, expansions): 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).""" + 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) @@ -679,9 +679,9 @@ def GenerateOutput(target_list, target_dicts, data, params): 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["LastTestingUpgradeCheck"] = ( + upgrade_check_project_version + ) project_attributes["LastSwiftUpdateCheck"] = upgrade_check_project_version pbxp.SetProperty("attributes", project_attributes) @@ -696,7 +696,7 @@ def GenerateOutput(target_list, target_dicts, data, params): xcode_targets = {} xcode_target_to_target_dict = {} for qualified_target in target_list: - [build_file, target_name, toolset] = gyp.common.ParseQualifiedTarget( + [build_file, target_name, _toolset] = gyp.common.ParseQualifiedTarget( qualified_target ) @@ -734,8 +734,7 @@ def GenerateOutput(target_list, target_dicts, data, params): "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+extension+bundle": "com.apple.product-type.watchkit-extension", # noqa: E501 "executable+watch+bundle": "com.apple.product-type.application.watchapp", "mac_kernel_extension+bundle": "com.apple.product-type.kernel-extension", } @@ -780,8 +779,7 @@ def GenerateOutput(target_list, target_dicts, data, params): type_bundle_key += "+watch+extension+bundle" elif is_watch_app: assert is_bundle, ( - "ios_watch_app flag requires mac_bundle " - "(target %s)" % target_name + "ios_watch_app flag requires mac_bundle (target %s)" % target_name ) type_bundle_key += "+watch+bundle" elif is_bundle: @@ -793,7 +791,7 @@ def GenerateOutput(target_list, target_dicts, data, params): except KeyError as e: gyp.common.ExceptionAppend( e, - "-- unknown product type while " "writing target %s" % target_name, + "-- unknown product type while writing target %s" % target_name, ) raise else: @@ -959,7 +957,7 @@ def GenerateOutput(target_list, target_dicts, data, params): # 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 + # variables. This is a low-priority problem and is not a # show-stopper. rules_by_ext = {} for rule in spec_rules: @@ -1103,7 +1101,7 @@ def GenerateOutput(target_list, target_dicts, data, params): eol = " \\" makefile.write(f" {concrete_output}{eol}\n") - for (rule_source, concrete_outputs, message, action) in zip( + for rule_source, concrete_outputs, message, action in zip( rule["rule_sources"], concrete_outputs_by_rule_source, messages, @@ -1217,7 +1215,7 @@ def GenerateOutput(target_list, target_dicts, data, params): # Add "sources". for source in spec.get("sources", []): - (source_root, source_extension) = posixpath.splitext(source) + (_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. @@ -1229,7 +1227,7 @@ def GenerateOutput(target_list, target_dicts, data, params): # it's a bundle of any type. if is_bundle: for resource in tgt_mac_bundle_resources: - (resource_root, resource_extension) = posixpath.splitext(resource) + (_resource_root, resource_extension) = posixpath.splitext(resource) if resource_extension[1:] not in rules_by_ext: AddResourceToTarget(resource, pbxp, xct) else: diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py index 49772d1f4d810..bfd8c587a3175 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py @@ -4,11 +4,12 @@ # 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. """ +"""Unit tests for the xcode.py file.""" -import gyp.generator.xcode as xcode -import unittest import sys +import unittest + +from gyp.generator import xcode class TestEscapeXcodeDefine(unittest.TestCase): diff --git a/node_modules/node-gyp/gyp/pylib/gyp/input.py b/node_modules/node-gyp/gyp/pylib/gyp/input.py index 0b56c72750e6c..f3a5e168f2075 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/input.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/input.py @@ -4,9 +4,6 @@ import ast - -import gyp.common -import gyp.simple_copy import multiprocessing import os.path import re @@ -16,10 +13,13 @@ import sys import threading import traceback -from gyp.common import GypError -from gyp.common import OrderedSet + from packaging.version import Version +import gyp.common +import gyp.simple_copy +from gyp.common import GypError, OrderedSet + # A list of types that are treated as linkable. linkable_types = [ "executable", @@ -139,21 +139,21 @@ def IsPathSection(section): 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. + 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. + 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. + 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. - """ + 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 = [] @@ -171,10 +171,10 @@ def GetIncludedBuildFiles(build_file_path, aux_data, included=None): 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. - """ + 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) @@ -242,7 +242,7 @@ def LoadOneBuildFile(build_file_path, data, aux_data, includes, is_target, check gyp.common.ExceptionAppend(e, "while reading " + build_file_path) raise - if type(build_file_data) is not dict: + if not isinstance(build_file_data, dict): raise GypError("%s does not evaluate to a dictionary." % build_file_path) data[build_file_path] = build_file_data @@ -303,20 +303,20 @@ def LoadBuildFileIncludesIntoDict( # Recurse into subdictionaries. for k, v in subdict.items(): - if type(v) is dict: + if isinstance(v, dict): LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, None, check) - elif type(v) is list: + elif isinstance(v, 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: + if isinstance(item, dict): LoadBuildFileIncludesIntoDict( item, sublist_path, data, aux_data, None, check ) - elif type(item) is list: + elif isinstance(item, list): LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data, check) @@ -350,9 +350,9 @@ def ProcessToolsetsInDict(data): data["targets"] = new_target_list if "conditions" in data: for condition in data["conditions"]: - if type(condition) is list: + if isinstance(condition, list): for condition_dict in condition[1:]: - if type(condition_dict) is dict: + if isinstance(condition_dict, dict): ProcessToolsetsInDict(condition_dict) @@ -508,9 +508,9 @@ def CallLoadTargetBuildFile( ): """Wrapper around LoadTargetBuildFile for parallel processing. - This wrapper is used when LoadTargetBuildFile is executed in - a worker process. - """ + This wrapper is used when LoadTargetBuildFile is executed in + a worker process. + """ try: signal.signal(signal.SIGINT, signal.SIG_IGN) @@ -559,10 +559,10 @@ class ParallelProcessingError(Exception): 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. - """ + 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. @@ -584,8 +584,7 @@ def __init__(self): self.error = False def LoadTargetBuildFileCallback(self, result): - """Handle the results of running LoadTargetBuildFile in another process. - """ + """Handle the results of running LoadTargetBuildFile in another process.""" self.condition.acquire() if not result: self.error = True @@ -692,9 +691,9 @@ def FindEnclosingBracketGroup(input_str): 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: + The canonical form is such that str(int(string)) == string. + """ + if isinstance(string, 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. @@ -744,7 +743,7 @@ def IsStrCanonicalInt(string): def FixupPlatformCommand(cmd): if sys.platform == "win32": - if type(cmd) is list: + if isinstance(cmd, list): cmd = [re.sub("^cat ", "type ", cmd[0])] + cmd[1:] else: cmd = re.sub("^cat ", "type ", cmd) @@ -870,7 +869,9 @@ def ExpandVariables(input, phase, variables, build_file): # 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(" ") + contents_list = ( + contents if isinstance(contents, list) else contents.split(" ") + ) replacement = contents_list[0] if os.path.isabs(replacement): raise GypError('| cannot handle absolute paths, got "%s"' % replacement) @@ -933,7 +934,6 @@ def ExpandVariables(input, phase, variables, build_file): os.chdir(build_file_dir) sys.path.append(os.getcwd()) try: - parsed_contents = shlex.split(contents) try: py_module = __import__(parsed_contents[0]) @@ -964,7 +964,7 @@ def ExpandVariables(input, phase, variables, build_file): stdout=subprocess.PIPE, shell=use_shell, cwd=build_file_dir, - check=False + check=False, ) except Exception as e: raise GypError( @@ -989,29 +989,26 @@ def ExpandVariables(input, phase, variables, build_file): ) 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 - ) + elif 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: - replacement = variables[contents] + 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: + if isinstance(replacement, list): for item in replacement: if isinstance(item, bytes) and not isinstance(item, str): item = item.decode("utf-8") # done on Python 3 only @@ -1042,7 +1039,7 @@ def ExpandVariables(input, phase, variables, build_file): # 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 isinstance(replacement, list): # If it's already a list, make a copy. output = replacement[:] else: @@ -1051,7 +1048,7 @@ def ExpandVariables(input, phase, variables, build_file): else: # Expanding in string context. encoded_replacement = "" - if type(replacement) is list: + if isinstance(replacement, 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. # @@ -1073,7 +1070,7 @@ def ExpandVariables(input, phase, variables, build_file): if output == input: gyp.DebugOutput( gyp.DEBUG_VARIABLES, - "Found only identity matches on %r, avoiding infinite " "recursion.", + "Found only identity matches on %r, avoiding infinite recursion.", output, ) else: @@ -1081,8 +1078,8 @@ def ExpandVariables(input, phase, variables, build_file): # 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: + if isinstance(output, list): + if output and isinstance(output[0], list): # Leave output alone if it's a list of lists. # We don't want such lists to be stringified. pass @@ -1097,7 +1094,7 @@ def ExpandVariables(input, phase, variables, build_file): output = ExpandVariables(output, phase, variables, build_file) # Convert all strings that are canonically-represented integers into integers. - if type(output) is list: + if isinstance(output, list): for index, outstr in enumerate(output): if IsStrCanonicalInt(outstr): output[index] = int(outstr) @@ -1114,8 +1111,8 @@ def ExpandVariables(input, phase, variables, build_file): 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: + that nothing should be used.""" + if not isinstance(condition, 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 @@ -1133,18 +1130,18 @@ def EvalCondition(condition, conditions_key, phase, variables, build_file): while i < len(condition): cond_expr = condition[i] true_dict = condition[i + 1] - if type(true_dict) is not dict: + if not isinstance(true_dict, dict): raise GypError( - f"{conditions_key} {cond_expr} must be followed by a dictionary, not " - f"{type(true_dict)}" + 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: + if len(condition) > i + 2 and isinstance(condition[i + 2], dict): false_dict = condition[i + 2] i = i + 3 if i != len(condition): raise GypError( - f"{conditions_key} {cond_expr} has {len(condition) - i} " - "unexpected trailing items" + f"{conditions_key} {cond_expr} has " + f"{len(condition) - i} unexpected trailing items" ) else: false_dict = None @@ -1159,7 +1156,7 @@ def EvalCondition(condition, conditions_key, phase, variables, build_file): 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.""" + 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 @@ -1239,7 +1236,7 @@ def ProcessConditionsInDict(the_dict, phase, variables, build_file): ) if merge_dict is not None: - # Expand variables and nested conditinals in the merge_dict before + # Expand variables and nested conditionals in the merge_dict before # merging it. ProcessVariablesAndConditionsInDict( merge_dict, phase, variables, build_file @@ -1289,10 +1286,10 @@ def ProcessVariablesAndConditionsInDict( ): """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. - """ + 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. @@ -1320,7 +1317,7 @@ def ProcessVariablesAndConditionsInDict( for key, value in the_dict.items(): # Skip "variables", which was already processed if present. - if key != "variables" and type(value) is str: + if key != "variables" and isinstance(value, str): expanded = ExpandVariables(value, phase, variables, build_file) if type(expanded) not in (str, int): raise ValueError( @@ -1383,21 +1380,21 @@ def ProcessVariablesAndConditionsInDict( 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: + if key == "variables" or isinstance(value, str): continue - if type(value) is dict: + if isinstance(value, 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: + elif isinstance(value, 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: + elif not isinstance(value, int): raise TypeError("Unknown type " + value.__class__.__name__ + " for " + key) @@ -1406,17 +1403,17 @@ def ProcessVariablesAndConditionsInList(the_list, phase, variables, build_file): index = 0 while index < len(the_list): item = the_list[index] - if type(item) is dict: + if isinstance(item, 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: + elif isinstance(item, list): ProcessVariablesAndConditionsInList(item, phase, variables, build_file) - elif type(item) is str: + elif isinstance(item, str): expanded = ExpandVariables(item, phase, variables, build_file) if type(expanded) in (str, int): the_list[index] = expanded - elif type(expanded) is list: + elif isinstance(expanded, list): the_list[index : index + 1] = expanded index += len(expanded) @@ -1431,7 +1428,7 @@ def ProcessVariablesAndConditionsInList(the_list, phase, variables, build_file): + " at " + index ) - elif type(item) is not int: + elif not isinstance(item, int): raise TypeError( "Unknown type " + item.__class__.__name__ + " at index " + index ) @@ -1441,15 +1438,15 @@ def ProcessVariablesAndConditionsInList(the_list, phase, variables, build_file): 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. - """ + |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"]: @@ -1467,13 +1464,13 @@ def BuildTargetsDict(data): 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. - """ + |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 ("", "!", "/") @@ -1516,18 +1513,18 @@ def QualifyDependencies(targets): 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. + 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. + 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. - """ + 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) @@ -1573,14 +1570,10 @@ def ExpandWildcardDependencies(targets, data): 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} - ): + if dependency_target not in {"*", dependency_target_name}: continue dependency_target_toolset = dependency_target_dict["toolset"] - if ( - dependency_toolset not in {"*", dependency_target_toolset} - ): + if dependency_toolset not in {"*", dependency_target_toolset}: continue dependency = gyp.common.QualifiedTarget( dependency_build_file, @@ -1601,7 +1594,7 @@ def Unify(items): def RemoveDuplicateDependencies(targets): """Makes sure every dependency appears only once in all targets's dependency - lists.""" + lists.""" for target_name, target_dict in targets.items(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) @@ -1617,25 +1610,21 @@ def Filter(items, item): def RemoveSelfDependencies(targets): """Remove self dependencies from targets that have the prune_self_dependency - variable set.""" + 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) + targets[t].get("variables", {}).get("prune_self_dependency", 0) ): - target_dict[dependency_key] = Filter( - dependencies, target_name - ) + target_dict[dependency_key] = Filter(dependencies, target_name) def RemoveLinkDependenciesFromNoneTargets(targets): """Remove dependencies having the 'link_dependency' attribute from the 'none' - targets.""" + targets.""" for target_name, target_dict in targets.items(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) @@ -1651,11 +1640,11 @@ def RemoveLinkDependenciesFromNoneTargets(targets): 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. - """ + 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 @@ -1721,8 +1710,8 @@ def ExtractNodeRef(node): def FindCycles(self): """ - Returns a list of cycles in the graph, where each cycle is its own list. - """ + Returns a list of cycles in the graph, where each cycle is its own list. + """ results = [] visited = set() @@ -1753,21 +1742,21 @@ def DirectDependencies(self, dependencies=None): 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. - """ + 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 = [] @@ -1795,9 +1784,9 @@ def _AddImportedDependencies(self, targets, dependencies=None): 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 that a dependency has advertised settings should be exported + through the dependency for. + """ dependencies = self.DirectDependencies(dependencies) return self._AddImportedDependencies(targets, dependencies) @@ -1823,19 +1812,19 @@ def _LinkDependenciesInternal( self, targets, include_shared_libraries, dependencies=None, initial=True ): """Returns an OrderedSet of dependency targets that are linked - into this target. + 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. + 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. + 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 |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. @@ -1917,9 +1906,9 @@ def _LinkDependenciesInternal( def DependenciesForLinkSettings(self, targets): """ - Returns a list of dependency targets whose link_settings should be merged - into this target. - """ + 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 @@ -1932,8 +1921,8 @@ def DependenciesForLinkSettings(self, targets): def DependenciesToLinkAgainst(self, targets): """ - Returns a list of dependency targets that are linked into this target. - """ + Returns a list of dependency targets that are linked into this target. + """ return self._LinkDependenciesInternal(targets, True) @@ -2232,18 +2221,18 @@ def is_in_set_or_list(x, s, items): # 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("-")): + if not (isinstance(item, 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: + elif isinstance(item, 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: + elif isinstance(item, 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 @@ -2312,12 +2301,12 @@ def MergeDicts(to, fro, to_file, fro_file): to[k] = MakePathRelative(to_file, fro_file, v) else: to[k] = v - elif type(v) is dict: + elif isinstance(v, 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: + elif isinstance(v, 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. # @@ -2361,7 +2350,7 @@ def MergeDicts(to, fro, to_file, fro_file): # 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: + elif not isinstance(to[list_base], list): # This may not have been checked above if merging in a list with an # extension character. raise TypeError( @@ -2446,7 +2435,7 @@ def SetUpConfigurations(target, target_dict): merged_configurations = {} configs = target_dict["configurations"] - for (configuration, old_configuration_dict) in configs.items(): + for configuration, old_configuration_dict in configs.items(): # Skip abstract configurations (saves work only). if old_configuration_dict.get("abstract"): continue @@ -2454,7 +2443,7 @@ def SetUpConfigurations(target, target_dict): # Get the inheritance relationship right by making a copy of the target # dict. new_configuration_dict = {} - for (key, target_val) in target_dict.items(): + 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: @@ -2468,11 +2457,8 @@ def SetUpConfigurations(target, target_dict): 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 - ] - + for configuration, value in merged_configurations.items(): + target_dict["configurations"][configuration] = value # Now drop all the abstract ones. configs = target_dict["configurations"] target_dict["configurations"] = { @@ -2505,25 +2491,25 @@ def SetUpConfigurations(target, target_dict): 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". - """ + 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 @@ -2536,11 +2522,13 @@ def ProcessListFiltersInDict(name, the_dict): 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: + if not isinstance(value, list): raise ValueError( name + " key " + key + " must be list, not " + value.__class__.__name__ ) @@ -2553,7 +2541,7 @@ def ProcessListFiltersInDict(name, the_dict): del_lists.append(key) continue - if type(the_dict[list_key]) is not list: + if not isinstance(the_dict[list_key], list): value = the_dict[list_key] raise ValueError( name @@ -2666,29 +2654,29 @@ def ProcessListFiltersInDict(name, the_dict): # Now recurse into subdicts and lists that may contain dicts. for key, value in the_dict.items(): - if type(value) is dict: + if isinstance(value, dict): ProcessListFiltersInDict(key, value) - elif type(value) is list: + elif isinstance(value, list): ProcessListFiltersInList(key, value) def ProcessListFiltersInList(name, the_list): for item in the_list: - if type(item) is dict: + if isinstance(item, dict): ProcessListFiltersInDict(name, item) - elif type(item) is list: + elif isinstance(item, 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. + Arguments: + target: string, name of target. + target_dict: dict, target spec. - Raises an exception on error. - """ + Raises an exception on error. + """ VALID_TARGET_TYPES = ( "executable", "loadable_module", @@ -2716,14 +2704,14 @@ def ValidateTargetType(target, target_dict): 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. + 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'. - """ + 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. @@ -2735,9 +2723,7 @@ def ValidateRulesInTarget(target, target_dict, extra_sources_for_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}" - ) + raise GypError(f"rule {rule_name} exists in duplicate, target {target}") rule_names[rule_name] = rule rule_extension = rule["extension"] @@ -2771,7 +2757,7 @@ def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules): 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) + (_source_root, source_extension) = os.path.splitext(source) if source_extension.startswith("."): source_extension = source_extension[1:] if source_extension == rule_extension: @@ -2786,7 +2772,7 @@ def ValidateRunAsInTarget(target, target_dict, build_file): run_as = target_dict.get("run_as") if not run_as: return - if type(run_as) is not dict: + if not isinstance(run_as, dict): raise GypError( "The 'run_as' in target %s from file %s should be a " "dictionary." % (target_name, build_file) @@ -2797,19 +2783,19 @@ def ValidateRunAsInTarget(target, target_dict, build_file): "The 'run_as' in target %s from file %s must have an " "'action' section." % (target_name, build_file) ) - if type(action) is not list: + if not isinstance(action, 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: + if working_directory and not isinstance(working_directory, 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: + if environment and not isinstance(environment, dict): raise GypError( "The 'environment' for 'run_as' in target %s " "in file %s should be a dictionary." % (target_name, build_file) @@ -2836,33 +2822,31 @@ def ValidateActionsInTarget(target, target_dict, build_file): def TurnIntIntoStrInDict(the_dict): - """Given dict the_dict, recursively converts all integers into strings. - """ + """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: + if isinstance(v, int): v = str(v) the_dict[k] = v - elif type(v) is dict: + elif isinstance(v, dict): TurnIntIntoStrInDict(v) - elif type(v) is list: + elif isinstance(v, list): TurnIntIntoStrInList(v) - if type(k) is int: + if isinstance(k, int): del the_dict[k] the_dict[str(k)] = v def TurnIntIntoStrInList(the_list): - """Given list the_list, recursively converts all integers into strings. - """ + """Given list the_list, recursively converts all integers into strings.""" for index, item in enumerate(the_list): - if type(item) is int: + if isinstance(item, int): the_list[index] = str(item) - elif type(item) is dict: + elif isinstance(item, dict): TurnIntIntoStrInDict(item) - elif type(item) is list: + elif isinstance(item, list): TurnIntIntoStrInList(item) @@ -2903,9 +2887,9 @@ def PruneUnwantedTargets(targets, flat_list, dependency_nodes, root_targets, dat 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'. - """ + 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: @@ -3017,8 +3001,8 @@ def Load( 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] + for key, value in tmp_dict.items(): + target_dict[key] = value # Make sure every dependency appears at most once. RemoveDuplicateDependencies(targets) diff --git a/node_modules/node-gyp/gyp/pylib/gyp/input_test.py b/node_modules/node-gyp/gyp/pylib/gyp/input_test.py index a18f72e9ebb0a..ff8c8fbecc3e5 100755 --- a/node_modules/node-gyp/gyp/pylib/gyp/input_test.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/input_test.py @@ -6,9 +6,10 @@ """Unit tests for the input.py file.""" -import gyp.input import unittest +import gyp.input + class TestFindCycles(unittest.TestCase): def setUp(self): diff --git a/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py b/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py index 59647c9a89034..4c38f0586c4c2 100755 --- a/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py @@ -8,7 +8,6 @@ These functions are executed via gyp-mac-tool when using the Makefile generator. """ - import fcntl import fnmatch import glob @@ -25,14 +24,13 @@ def main(args): executor = MacTool() - exit_code = executor.Dispatch(args) - if exit_code is not None: + if (exit_code := executor.Dispatch(args)) 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.""" + executed directly, or dispatched from an argument list.""" def Dispatch(self, args): """Dispatches a string command to a method.""" @@ -48,7 +46,7 @@ def _CommandifyName(self, name_string): def ExecCopyBundleResource(self, source, dest, convert_to_binary): """Copies a resource file to the bundle/Resources directory, performing any - necessary compilation on each resource.""" + necessary compilation on each resource.""" convert_to_binary = convert_to_binary == "True" extension = os.path.splitext(source)[1].lower() if os.path.isdir(source): @@ -59,9 +57,7 @@ def ExecCopyBundleResource(self, source, dest, convert_to_binary): if os.path.exists(dest): shutil.rmtree(dest) shutil.copytree(source, dest) - elif extension == ".xib": - return self._CopyXIBFile(source, dest) - elif extension == ".storyboard": + elif extension in {".xib", ".storyboard"}: return self._CopyXIBFile(source, dest) elif extension == ".strings" and not convert_to_binary: self._CopyStringsFile(source, dest) @@ -70,7 +66,7 @@ def ExecCopyBundleResource(self, source, dest, convert_to_binary): os.unlink(dest) shutil.copy(source, dest) - if convert_to_binary and extension in (".plist", ".strings"): + if convert_to_binary and extension in {".plist", ".strings"}: self._ConvertToBinary(dest) def _CopyXIBFile(self, source, dest): @@ -144,7 +140,7 @@ def _CopyStringsFile(self, source, dest): # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing # semicolon in dictionary. # on invalid files. Do the same kind of validation. - import CoreFoundation + import CoreFoundation # noqa: PLC0415 with open(source, "rb") as in_file: s = in_file.read() @@ -158,17 +154,15 @@ def _CopyStringsFile(self, source, dest): 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.""" + 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"): + if header.startswith((b"\xfe\xff", b"\xff\xfe")): return "UTF-16" - elif header.startswith(b"\xFF\xFE"): - return "UTF-16" - elif header.startswith(b"\xEF\xBB\xBF"): + elif header.startswith(b"\xef\xbb\xbf"): return "UTF-8" else: return None @@ -259,9 +253,9 @@ def ExecFlock(self, lockfile, *cmd_list): def ExecFilterLibtool(self, *cmd_list): """Calls libtool and filters out '/path/to/libtool: file: foo.o has no - symbols'.""" + symbols'.""" libtool_re = re.compile( - r"^.*libtool: (?:for architecture: \S* )?" r"file: .* has no symbols$" + r"^.*libtool: (?:for architecture: \S* )?file: .* has no symbols$" ) libtool_re5 = re.compile( r"^.*libtool: warning for library: " @@ -308,7 +302,7 @@ def ExecPackageIosFramework(self, framework): def ExecPackageFramework(self, framework, version): """Takes a path to Something.framework and the Current version of that and - sets up all the symlinks.""" + 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] @@ -337,7 +331,7 @@ def ExecPackageFramework(self, framework, version): def _Relink(self, dest, link): """Creates a symlink to |dest| named |link|. If |link| already exists, - it is overwritten.""" + it is overwritten.""" if os.path.lexists(link): os.remove(link) os.symlink(dest, link) @@ -362,14 +356,14 @@ def ExecCopyIosFrameworkHeaders(self, framework, *copy_headers): 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. + 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. - """ + Note that 'actool' does not create the Assets.car file if the asset + catalogs does not contains imageset. + """ command_line = [ "xcrun", "actool", @@ -442,13 +436,13 @@ def ExecMergeInfoPlist(self, output, *inputs): 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. - """ + 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() ) @@ -467,16 +461,16 @@ def ExecCodeSignBundle(self, key, entitlements, provisioning, path, preserve): 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 + 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. - """ + 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 ) @@ -492,24 +486,24 @@ def _InstallProvisioningProfile(self, profile, bundle_identifier): 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. + 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 + 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. + 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. - """ + Raises: + SystemExit: if no .mobileprovision can be used to sign the bundle. + """ profiles_dir = os.path.join( os.environ["HOME"], "Library", "MobileDevice", "Provisioning Profiles" ) @@ -551,18 +545,18 @@ def _FindProvisioningProfile(self, profile, bundle_identifier): # 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)) + selected_key = max(valid_provisioning_profiles, key=len) 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 + Args: + profile_path: string, path to the .mobileprovision file - Returns: - Content of the plist embedded in the provisioning profile as a dictionary. - """ + 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] @@ -585,16 +579,16 @@ def _MergePlist(self, merged_plist, plist): 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). + 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 + Args: + plist_path: string, path to a plist file, in XML or binary format - Returns: - Content of the plist as a dictionary. - """ + 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 @@ -610,13 +604,13 @@ def _LoadPlistMaybeBinary(self, plist_path): 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 + 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. - """ + Returns: + Dictionary of substitutions to apply when generating Entitlements.plist. + """ return { "CFBundleIdentifier": bundle_identifier, "AppIdentifierPrefix": app_identifier_prefix, @@ -625,9 +619,9 @@ def _GetSubstitutions(self, bundle_identifier, 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. - """ + 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"] ) @@ -637,19 +631,19 @@ def _GetCFBundleIdentifier(self): 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". + 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 + 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. - """ + 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" @@ -669,15 +663,15 @@ def _InstallEntitlements(self, entitlements, substitutions, overrides): 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 + 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. - """ + 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) @@ -696,15 +690,15 @@ def NextGreaterPowerOf2(x): 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. + 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 - """ + 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 diff --git a/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py b/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py index 847d1b8dc1d4d..f1c1581981e3d 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py @@ -7,15 +7,15 @@ build systems, primarily ninja. """ -import collections import os import re import subprocess import sys +from collections import namedtuple -from gyp.common import OrderedSet import gyp.MSVSUtil import gyp.MSVSVersion +from gyp.common import OrderedSet windows_quoter_regex = re.compile(r'(\\*)"') @@ -74,8 +74,7 @@ def EncodeRspFileList(args, quote_cmd): 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:])) + return program + " " + " ".join(QuoteForRspFile(arg, quote_cmd) for arg in args[1:]) def _GenericRetrieve(root, default, path): @@ -247,9 +246,7 @@ def GetExtension(self): the target type. """ ext = self.spec.get("product_extension", None) - if ext: - return ext - return gyp.MSVSUtil.TARGET_TYPE_EXT.get(self.spec["type"], "") + return ext or 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 @@ -625,8 +622,7 @@ def GetDefFile(self, gyp_to_build_path): 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: + if def_file := self.GetDefFile(gyp_to_build_path): ldflags.append('/DEF:"%s"' % def_file) def GetPGDName(self, config, expand_special): @@ -674,14 +670,11 @@ def GetLdflags( ) ld("DelayLoadDLLs", prefix="/DELAYLOAD:") ld("TreatLinkerWarningAsErrors", prefix="/WX", map={"true": "", "false": ":NO"}) - out = self.GetOutputName(config, expand_special) - if out: + if out := self.GetOutputName(config, expand_special): ldflags.append("/OUT:" + out) - pdb = self.GetPDBName(config, expand_special, output_name + ".pdb") - if pdb: + if pdb := self.GetPDBName(config, expand_special, output_name + ".pdb"): ldflags.append("/PDB:" + pdb) - pgd = self.GetPGDName(config, expand_special) - if pgd: + if pgd := self.GetPGDName(config, expand_special): ldflags.append("/PGD:" + pgd) map_file = self.GetMapFileName(config, expand_special) ld("GenerateMapFile", map={"true": "/MAP:" + map_file if map_file else "/MAP"}) @@ -830,14 +823,15 @@ def _GetLdManifestFlags( ("VCLinkerTool", "UACUIAccess"), config, default="false" ) + level = execution_level_map[execution_level] inner = f""" - + -""" # noqa: E501 +""" else: inner = "" @@ -932,21 +926,24 @@ def BuildCygwinBashCommandLine(self, args, path_to_base): ) return cmd - RuleShellFlags = collections.namedtuple("RuleShellFlags", ["cygwin", "quote"]) + RuleShellFlags = namedtuple("RuleShellFlags", ["cygwin", "quote"]) # noqa: PYI024 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 + 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" + 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): @@ -1134,8 +1131,7 @@ def _ExtractImportantEnvironment(output_of_set): for required in ("SYSTEMROOT", "TEMP", "TMP"): if required not in env: raise Exception( - 'Environment variable "%s" ' - "required to be set to valid path" % required + 'Environment variable "%s" required to be set to valid path' % required ) return env @@ -1178,7 +1174,7 @@ def GenerateEnvironmentFiles( 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") + archs = ("x86", "x64", "arm64") if generator_flags.get("ninja_use_custom_environment_files", 0): cl_paths = {} for arch in archs: diff --git a/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py b/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py index 729cec0636273..2b9100f3e1ba8 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py @@ -17,15 +17,15 @@ class Error(Exception): 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.""" + 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) + f"Unsupported type {type(x)} for deepcopy. Use copy.deepcopy " + + "or expand simple_copy support." ) diff --git a/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py b/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py index 171d7295747fc..43665577bddda 100755 --- a/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py @@ -9,13 +9,12 @@ 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 subprocess import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) @@ -27,18 +26,17 @@ def main(args): executor = WinTool() - exit_code = executor.Dispatch(args) - if exit_code is not None: + if (exit_code := executor.Dispatch(args)) 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.""" + 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.""" + shared one.""" if len(args) < 1: raise Exception("Not enough arguments") @@ -115,9 +113,9 @@ def _on_error(fn, path, excinfo): 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. - """ + ' 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) @@ -159,10 +157,10 @@ def ExecLinkWithManifests( mt, rc, intermediate_manifest, - *manifests + *manifests, ): """A wrapper for handling creating a manifest resource and then executing - a link command.""" + 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 @@ -246,8 +244,8 @@ def dump(filename): 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).""" + (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 @@ -260,8 +258,8 @@ def ExecManifestWrapper(self, arch, *args): 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).""" + |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( @@ -271,8 +269,8 @@ def ExecManifestToRc(self, arch, *args): 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. - """ + quietable via command line flags. + """ args = ( ["midl", "/nologo"] + list(flags) @@ -328,7 +326,7 @@ def ExecAsmWrapper(self, arch, *args): def ExecRcWrapper(self, arch, *args): """Filter logo banner from invocations of rc.exe. Older versions of RC - don't support the /nologo flag.""" + don't support the /nologo flag.""" env = self._GetEnv(arch) popen = subprocess.Popen( args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT @@ -345,7 +343,7 @@ def ExecRcWrapper(self, arch, *args): 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.""" + 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. @@ -358,7 +356,7 @@ def ExecActionWrapper(self, arch, rspfile, *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.""" + build selected C/C++ files.""" project_dir = os.path.relpath(project_dir, BASE_DIR) selected_files = selected_files.split(";") ninja_targets = [ diff --git a/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py b/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py index 29caf1ce7fbb9..d13eaa9af240b 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py @@ -7,15 +7,15 @@ 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 + +import gyp.common from gyp.common import GypError # Populated lazily by XcodeVersion, for efficiency, and to fix an issue when @@ -30,7 +30,7 @@ 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).""" + 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 @@ -39,10 +39,10 @@ def XcodeArchsVariableMapping(archs, archs_including_64_bit=None): 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. - """ + 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_]*\)$") @@ -81,8 +81,8 @@ def _ExpandArchs(self, archs, sdkroot): 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).""" + 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 = [] @@ -95,24 +95,24 @@ def ActiveArchs(self, archs, valid_archs, sdkroot): 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. + 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 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 "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). + 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.""" + 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 @@ -189,8 +189,8 @@ def __init__(self, spec): 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.""" + 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: @@ -255,13 +255,13 @@ def _IsIosWatchApp(self): def GetFrameworkVersion(self): """Returns the framework version of the current target. Only valid for - bundles.""" + 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.""" + valid for bundles.""" assert self._IsBundle() if self.spec["type"] in ("loadable_module", "shared_library"): default_wrapper_extension = { @@ -296,13 +296,13 @@ def GetFullProductName(self): def GetWrapperName(self): """Returns the directory name of the bundle represented by this target. - Only valid for bundles.""" + 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.""" + Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles.""" if self.isIOS: return self.GetWrapperName() assert self._IsBundle() @@ -316,7 +316,7 @@ def GetBundleContentsFolderPath(self): def GetBundleResourceFolder(self): """Returns the qualified path to the bundle's resource folder. E.g. - Chromium.app/Contents/Resources. Only valid for bundles.""" + Chromium.app/Contents/Resources. Only valid for bundles.""" assert self._IsBundle() if self.isIOS: return self.GetBundleContentsFolderPath() @@ -324,7 +324,7 @@ def GetBundleResourceFolder(self): def GetBundleExecutableFolderPath(self): """Returns the qualified path to the bundle's executables folder. E.g. - Chromium.app/Contents/MacOS. Only valid for bundles.""" + Chromium.app/Contents/MacOS. Only valid for bundles.""" assert self._IsBundle() if self.spec["type"] in ("shared_library") or self.isIOS: return self.GetBundleContentsFolderPath() @@ -333,25 +333,25 @@ def GetBundleExecutableFolderPath(self): 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.""" + 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.""" + 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.""" + 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.""" + Chromium.app/Contents/SharedSupport. Only valid for bundles.""" assert self._IsBundle() if self.spec["type"] == "shared_library": return self.GetBundleResourceFolder() @@ -360,19 +360,19 @@ def GetBundleSharedSupportFolderPath(self): def GetBundlePlugInsFolderPath(self): """Returns the qualified path to the bundle's plugins folder. E.g, - Chromium.app/Contents/PlugIns. Only valid for bundles.""" + 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.""" + 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.""" + Chromium.app/Contents/Info.plist. Only valid for bundles.""" assert self._IsBundle() if ( self.spec["type"] in ("executable", "loadable_module") @@ -438,7 +438,7 @@ def GetMachOType(self): 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.""" + E.g. Chromium.app/Contents/MacOS/Chromium. Only valid for bundles.""" assert self._IsBundle() return os.path.join( self.GetBundleExecutableFolderPath(), self.GetExecutableName() @@ -469,19 +469,16 @@ def _GetStandaloneExecutablePrefix(self): def _GetStandaloneBinaryPath(self): """Returns the name of the non-bundle binary represented by this target. - E.g. hello_world. Only valid for non-bundles.""" + E.g. hello_world. Only valid for non-bundles.""" assert not self._IsBundle() - assert self.spec["type"] in ( + assert self.spec["type"] in { "executable", "shared_library", "static_library", "loadable_module", - ), ("Unexpected type %s" % self.spec["type"]) + }, "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 self.spec["type"] in {"loadable_module", "shared_library", "static_library"}: if target[:3] == "lib": target = target[3:] @@ -492,7 +489,7 @@ def _GetStandaloneBinaryPath(self): def GetExecutableName(self): """Returns the executable name of the bundle represented by this target. - E.g. Chromium.""" + E.g. Chromium.""" if self._IsBundle(): return self.spec.get("product_name", self.spec["target_name"]) else: @@ -500,7 +497,7 @@ def GetExecutableName(self): 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.""" + represented by this target. E.g. Chromium.app/Contents/MacOS/Chromium.""" if self._IsBundle(): return self._GetBundleBinaryPath() else: @@ -523,7 +520,7 @@ def _GetSdkVersionInfoItem(self, sdk, infoitem): # most sensible route and should still do the right thing. try: return GetStdoutQuiet(["xcrun", "--sdk", sdk, infoitem]) - except GypError: + except (GypError, OSError): pass def _SdkRoot(self, configname): @@ -570,7 +567,7 @@ def _AppendPlatformVersionMinFlags(self, lst): def GetCflags(self, configname, arch=None): """Returns flags that need to be added to .c, .cc, .m, and .mm - compilations.""" + compilations.""" # This functions (and the similar ones below) do not offer complete # emulation of all xcode_settings keys. They're implemented on demand. @@ -579,7 +576,8 @@ def GetCflags(self, configname, arch=None): sdk_root = self._SdkPath() if "SDKROOT" in self._Settings() and sdk_root: - cflags.append("-isysroot %s" % sdk_root) + cflags.append("-isysroot") + cflags.append(sdk_root) if self.header_map_path: cflags.append("-I%s" % self.header_map_path) @@ -664,7 +662,8 @@ def GetCflags(self, configname, arch=None): # TODO: Supporting fat binaries will be annoying. self._WarnUnimplemented("ARCHS") archs = ["i386"] - cflags.append("-arch " + archs[0]) + cflags.append("-arch") + cflags.append(archs[0]) if archs[0] in ("i386", "x86_64"): if self._Test("GCC_ENABLE_SSE3_EXTENSIONS", "YES", default="NO"): @@ -863,7 +862,7 @@ def GetInstallName(self): 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.""" + gyp-directory-relative to build-directory-relative.""" # This list is expanded on demand. # They get matched as: # -exported_symbols_list file @@ -895,13 +894,13 @@ def _MapLinkerFlagFilename(self, ldflag, gyp_to_build_path): 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. - """ + 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 = [] @@ -924,17 +923,15 @@ def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None): self._AppendPlatformVersionMinFlags(ldflags) if "SDKROOT" in self._Settings() and self._SdkPath(): - ldflags.append("-isysroot " + 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 " - + "-Wl," - + gyp_to_build_path(self._Settings()["ORDER_FILE"]) - ) + 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: @@ -946,7 +943,9 @@ def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None): # TODO: Supporting fat binaries will be annoying. self._WarnUnimplemented("ARCHS") archs = ["i386"] - ldflags.append("-arch " + archs[0]) + # 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 @@ -954,7 +953,8 @@ def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None): install_name = self.GetInstallName() if install_name and self.spec["type"] != "loadable_module": - ldflags.append("-install_name " + install_name.replace(" ", r"\ ")) + 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) @@ -971,7 +971,8 @@ def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None): platform_root = self._XcodePlatformPath(configname) if sdk_root and platform_root: ldflags.append("-F" + platform_root + "/Developer/Library/Frameworks/") - ldflags.append("-framework XCTest") + ldflags.append("-framework") + ldflags.append("XCTest") is_extension = self._IsIosAppExtension() or self._IsIosWatchKitExtension() if sdk_root and is_extension: @@ -987,7 +988,8 @@ def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None): + "/System/Library/PrivateFrameworks/PlugInKit.framework/PlugInKit" ) else: - ldflags.append("-e _NSExtensionMain") + ldflags.append("-e") + ldflags.append("_NSExtensionMain") ldflags.append("-fapplication-extension") self._Appendf(ldflags, "CLANG_CXX_LIBRARY", "-stdlib=%s") @@ -998,9 +1000,9 @@ def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None): 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. - """ + Args: + configname: The name of the configuration to get ld flags for. + """ self.configname = configname libtoolflags = [] @@ -1013,7 +1015,7 @@ def GetLibtoolflags(self, configname): 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.""" + whose values are the same across all configurations.""" first_pass = True result = {} for configname in sorted(self.xcode_settings.keys()): @@ -1036,7 +1038,7 @@ def GetPerConfigSetting(self, setting, configname, default=None): 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.""" + has the same value in all configurations and throws otherwise.""" is_first_pass = True result = None for configname in sorted(self.xcode_settings.keys()): @@ -1054,15 +1056,14 @@ def GetPerTargetSetting(self, setting, default=None): 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.""" + 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() @@ -1089,8 +1090,8 @@ def _GetStripPostbuilds(self, configname, output_binary, quiet): 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.""" + 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. @@ -1111,7 +1112,7 @@ def _GetDebugInfoPostbuilds(self, configname, output, output_binary, quiet): 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.""" + 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 @@ -1119,11 +1120,10 @@ def _GetTargetPostbuilds(self, configname, output, output_binary, quiet=False): 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.""" + 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()) + (self.isIOS and (self.spec["type"] == "executable" or self._IsXCTest())) or self.IsIosFramework() ): return [] @@ -1169,8 +1169,9 @@ def _GetIOSPostbuilds(self, configname, output_binary): # Then re-sign everything with 'preserve=True' postbuilds.extend( [ - '%s code-sign-bundle "%s" "%s" "%s" "%s" %s' + '%s %s code-sign-bundle "%s" "%s" "%s" "%s" %s' % ( + sys.executable, os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"), key, settings.get("CODE_SIGN_ENTITLEMENTS", ""), @@ -1185,8 +1186,9 @@ def _GetIOSPostbuilds(self, configname, output_binary): for target in targets: postbuilds.extend( [ - '%s code-sign-bundle "%s" "%s" "%s" "%s" %s' + '%s %s code-sign-bundle "%s" "%s" "%s" "%s" %s' % ( + sys.executable, os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"), key, settings.get("CODE_SIGN_ENTITLEMENTS", ""), @@ -1199,8 +1201,9 @@ def _GetIOSPostbuilds(self, configname, output_binary): postbuilds.extend( [ - '%s code-sign-bundle "%s" "%s" "%s" "%s" %s' + '%s %s code-sign-bundle "%s" "%s" "%s" "%s" %s' % ( + sys.executable, os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"), key, settings.get("CODE_SIGN_ENTITLEMENTS", ""), @@ -1234,7 +1237,7 @@ def AddImplicitPostbuilds( self, configname, output, output_binary, postbuilds=[], quiet=False ): """Returns a list of shell commands that should run before and after - |postbuilds|.""" + |postbuilds|.""" assert output_binary is not None pre = self._GetTargetPostbuilds(configname, output, output_binary, quiet) post = self._GetIOSPostbuilds(configname, output_binary) @@ -1270,8 +1273,8 @@ def _AdjustLibrary(self, library, config_name=None): def AdjustLibraries(self, libraries, config_name=None): """Transforms entries like 'Cocoa.framework' in libraries into entries like - '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc. - """ + '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc. + """ libraries = [self._AdjustLibrary(library, config_name) for library in libraries] return libraries @@ -1336,20 +1339,19 @@ def GetExtraPlistItems(self, configname=None): 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. - """ + 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: + if default_sdk_root := XcodeSettings._sdk_root_cache.get(default_sdk_path): return default_sdk_root try: all_sdks = GetStdout(["xcodebuild", "-showsdks"]) - except GypError: + except (GypError, OSError): # If xcodebuild fails, there will be no valid SDKs return "" for line in all_sdks.splitlines(): @@ -1365,39 +1367,39 @@ def _DefaultSdkRoot(self): 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. - """ + 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'). - """ + 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 @@ -1442,9 +1444,9 @@ def _Gch(self, lang, arch): 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]|.""" + 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 [] @@ -1465,8 +1467,8 @@ def GetObjDependencies(self, sources, objs, arch=None): def GetPchBuildCommands(self, arch=None): """Returns [(path_to_gch, language_flag, language, header)]. - |path_to_gch| and |header| are relative to the build directory. - """ + |path_to_gch| and |header| are relative to the build directory. + """ if not self.header or not self.compile_headers: return [] return [ @@ -1503,7 +1505,8 @@ def XcodeVersion(): 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 + except (GypError, OSError): + # 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!") @@ -1531,26 +1534,28 @@ def CLTVersion(): FROM_XCODE_PKG_ID = "com.apple.pkg.DeveloperToolsCLI" MAVERICKS_PKG_ID = "com.apple.pkg.CLTools_Executables" - regex = re.compile("version: (?P.+)") + regex = re.compile(r"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: + if m := re.search(regex, output): + return m.groupdict()["version"] + except (GypError, OSError): 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: + if m := re.search(regex, output): + return m.groupdict()["version"] + except (GypError, OSError): 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.""" + 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: @@ -1560,7 +1565,7 @@ def GetStdoutQuiet(cmdlist): 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.""" + 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: @@ -1571,9 +1576,9 @@ def GetStdout(cmdlist): 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. - """ + 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. @@ -1588,9 +1593,9 @@ def MergeGlobalXcodeSettingsToSpec(global_dict, spec): 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.""" + 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 @@ -1607,14 +1612,14 @@ def IsMacBundle(flavor, spec): 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. - """ + 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 @@ -1645,24 +1650,24 @@ def GetMacBundleResources(product_dir, xcode_settings, resources): 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| 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, [], {} @@ -1700,18 +1705,18 @@ 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. - """ + 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 {} @@ -1765,27 +1770,25 @@ def _GetXcodeEnv( ) env["CONTENTS_FOLDER_PATH"] = xcode_settings.GetBundleContentsFolderPath() env["EXECUTABLE_FOLDER_PATH"] = xcode_settings.GetBundleExecutableFolderPath() - env[ - "UNLOCALIZED_RESOURCES_FOLDER_PATH" - ] = xcode_settings.GetBundleResourceFolder() + 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["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: + if install_name := xcode_settings.GetInstallName(): env["LD_DYLIB_INSTALL_NAME"] = install_name - install_name_base = xcode_settings.GetInstallNameBase() - if install_name_base: + if install_name_base := xcode_settings.GetInstallNameBase(): env["DYLIB_INSTALL_NAME_BASE"] = install_name_base xcode_version, _ = XcodeVersion() if xcode_version >= "0500" and not env.get("SDKROOT"): @@ -1813,8 +1816,8 @@ def _GetXcodeEnv( 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}. - """ + 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) @@ -1830,9 +1833,9 @@ def _NormalizeEnvVarReferences(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.""" + 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) @@ -1842,18 +1845,18 @@ def ExpandEnvVars(string, expansions): 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]. + 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. - """ + 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. + # Use a definition of edges such that user_of_variable -> used_variable. # 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. @@ -1887,7 +1890,7 @@ def GetSortedXcodeEnv( def GetSpecPostbuildCommands(spec, quiet=False): """Returns the list of postbuilds explicitly defined on |spec|, in a form - executable by a shell.""" + executable by a shell.""" postbuilds = [] for postbuild in spec.get("postbuilds", []): if not quiet: @@ -1901,7 +1904,7 @@ def GetSpecPostbuildCommands(spec, quiet=False): def _HasIOSTarget(targets): """Returns true if any target contains the iOS specific key - IPHONEOS_DEPLOYMENT_TARGET.""" + 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"): @@ -1911,7 +1914,7 @@ def _HasIOSTarget(targets): 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.""" + 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"] @@ -1927,7 +1930,7 @@ def _AddIOSDeviceConfigurations(targets): def CloneConfigurationForDeviceAndEmulator(target_dicts): """If |target_dicts| contains any iOS targets, automatically create -iphoneos - targets for iOS device builds.""" + targets for iOS device builds.""" if _HasIOSTarget(target_dicts): return _AddIOSDeviceConfigurations(target_dicts) return target_dicts diff --git a/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation_test.py b/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation_test.py new file mode 100644 index 0000000000000..03cbbaea84601 --- /dev/null +++ b/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation_test.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 + +"""Unit tests for the xcode_emulation.py file.""" + +import sys +import unittest + +from gyp.xcode_emulation import XcodeSettings + + +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() diff --git a/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py b/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py index bb74eacbeaf4a..a133fdbe8b4f5 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py @@ -13,15 +13,16 @@ """ import errno -import gyp.generator.ninja import os import re import xml.sax.saxutils +import gyp.generator.ninja + 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) + """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: @@ -56,7 +57,7 @@ def _WriteWorkspace(main_gyp, sources_gyp, params): def _TargetFromSpec(old_spec, params): - """ Create fake target for xcode-ninja wrapper. """ + """Create fake target for xcode-ninja wrapper.""" # Determine ninja top level build dir (e.g. /path/to/out). ninja_toplevel = None jobs = 0 @@ -69,12 +70,11 @@ def _TargetFromSpec(old_spec, params): 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: + if product_extension := old_spec.get("product_extension"): ninja_target["product_extension"] = product_extension ninja_target["toolset"] = old_spec.get("toolset") ninja_target["default_configuration"] = old_spec.get("default_configuration") @@ -102,9 +102,9 @@ def _TargetFromSpec(old_spec, params): new_xcode_settings[key] = old_xcode_settings[key] ninja_target["configurations"][config] = {} - ninja_target["configurations"][config][ - "xcode_settings" - ] = new_xcode_settings + 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) @@ -137,13 +137,13 @@ def _TargetFromSpec(old_spec, params): 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. - """ + 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): @@ -154,7 +154,6 @@ def IsValidTargetForWrapper(target_extras, executable_target_pattern, spec): 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): @@ -166,14 +165,14 @@ def IsValidTargetForWrapper(target_extras, executable_target_pattern, spec): 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. - """ + 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: diff --git a/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py b/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py index 33c667c266bf6..2004518dcbce9 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py @@ -74,7 +74,7 @@ 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 +compiler flags for each. These flags can be modified in the Xcode application in the "Build" tab of a File Info window. When a project is open in the Xcode application, Xcode will rewrite it. As @@ -137,14 +137,15 @@ 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 +from functools import cmp_to_key +from operator import attrgetter + +import gyp.common def cmp(x, y): @@ -175,15 +176,14 @@ def cmp(x, y): 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') - """ + 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: + if source_group_match := _path_leading_variable.match(input_path): source_tree = source_group_match.group(1) output_path = source_group_match.group(3) # This may be None. else: @@ -200,70 +200,70 @@ def ConvertVariablesToShellSyntax(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. - """ + 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 @@ -305,12 +305,12 @@ def __repr__(self): 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. - """ + 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(): @@ -359,9 +359,9 @@ def Copy(self): 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. - """ + 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 @@ -377,20 +377,19 @@ def Name(self): def Comment(self): """Return a comment string for the object. - Most objects just use their name as the comment, but PBXProject uses - different values. + 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. - """ + 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: + if (name := self.Name()) is not None: hashables.append(name) hashables.extend(self._hashables) @@ -403,26 +402,26 @@ def HashablesForChild(self): 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. + 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 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. - """ + 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. - """ + 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): @@ -430,7 +429,7 @@ def _HashUpdate(hash, data): hash.update(data) if seed_hash is None: - seed_hash = hashlib.sha1() + seed_hash = hashlib.sha256() hash = seed_hash.copy() @@ -460,13 +459,12 @@ def _HashUpdate(hash, data): 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): + for index in range(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. - """ + """Verifies that no two objects have the same ID. Checks all descendants.""" ids = {} descendants = self.Descendants() @@ -489,7 +487,7 @@ def Children(self): children = [] for property, attributes in self._schema.items(): - (is_list, property_type, is_strong) = attributes[0:3] + (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]) @@ -499,8 +497,8 @@ def Children(self): def Descendants(self): """Returns a list of all of this object's descendants, including this - object. - """ + object. + """ children = self.Children() descendants = [self] @@ -516,8 +514,8 @@ def PBXProjectAncestor(self): def _EncodeComment(self, comment): """Encodes a comment to be placed in the project file output, mimicking - Xcode behavior. - """ + Xcode behavior. + """ # This mimics Xcode behavior by wrapping the comment in "/*" and "*/". If # the string already contains a "*/", it is turned into "(*)/". This keeps @@ -544,8 +542,8 @@ def _EncodeTransform(self, match): def _EncodeString(self, value): """Encodes a string to be placed in the project file output, mimicking - Xcode behavior. - """ + 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 @@ -586,18 +584,18 @@ def _XCPrint(self, file, 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. + 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. + _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. - """ + If flatten_list is True, single-element lists will be transformed into + strings. + """ printable = "" comment = None @@ -658,12 +656,12 @@ def _XCPrintableValue(self, tabs, value, flatten_list=False): def _XCKVPrint(self, file, tabs, key, value): """Prints a key and value, members of an XCObject's _properties dictionary, - to file. + 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. - """ + 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 instead of a newline. + """ if self._should_print_single_line: printable = "" @@ -721,8 +719,8 @@ def _XCKVPrint(self, file, tabs, key, value): def Print(self, file=sys.stdout): """Prints a reprentation of this object to file, adhering to Xcode output - formatting. - """ + formatting. + """ self.VerifyHasRequiredProperties() @@ -760,15 +758,15 @@ def Print(self, file=sys.stdout): 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. + 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 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 @@ -781,7 +779,7 @@ def UpdateProperties(self, properties, do_copy=False): # 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: + if not isinstance(value, list): raise TypeError( property + " of " @@ -791,7 +789,7 @@ def UpdateProperties(self, properties, do_copy=False): ) for item in value: if not isinstance(item, property_type) and not ( - isinstance(item, str) and property_type == str + isinstance(item, str) and isinstance(property_type, str) ): # Accept unicode where str is specified. str is treated as # UTF-8-encoded. @@ -806,7 +804,7 @@ def UpdateProperties(self, properties, do_copy=False): + item.__class__.__name__ ) elif not isinstance(value, property_type) and not ( - isinstance(value, str) and property_type == str + isinstance(value, str) and isinstance(property_type, str) ): # Accept unicode where str is specified. str is treated as # UTF-8-encoded. @@ -909,23 +907,23 @@ def AppendProperty(self, key, value): def VerifyHasRequiredProperties(self): """Ensure that all properties identified as required by the schema are - set. - """ + 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] + (_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.""" + 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] + (_is_list, _property_type, _is_strong, is_required) = attributes[0:4] if ( is_required and len(attributes) >= 5 @@ -943,7 +941,7 @@ def _SetDefaultsFromSchema(self): class XCHierarchicalElement(XCObject): """Abstract base for PBXGroup and PBXFileReference. Not represented in a - project file.""" + 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 @@ -1009,27 +1007,27 @@ def Name(self): 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. - """ + 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 @@ -1050,8 +1048,7 @@ def Hashables(self): # 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: + if (path := self.PathFromSourceTreeAndPath()) is not None: components = path.split(posixpath.sep) for component in components: hashables.append(self.__class__.__name__ + ".path") @@ -1159,12 +1156,12 @@ def FullPath(self): 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. - """ + 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( @@ -1283,20 +1280,20 @@ def GetChildByRemoteObject(self, remote_object): 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 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 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. - """ + 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 @@ -1381,15 +1378,15 @@ def AddOrGetFileByPath(self, path, 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. + 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. - """ + 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: @@ -1407,19 +1404,19 @@ def AddOrGetVariantGroupByNameAndPath(self, name, path): 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. - """ + 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, @@ -1619,7 +1616,7 @@ def __init__(self, properties=None, id=None, parent=None): prop_name = "lastKnownFileType" else: basename = posixpath.basename(self._properties["path"]) - (root, ext) = posixpath.splitext(basename) + (_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 @@ -1640,7 +1637,6 @@ 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 @@ -1719,16 +1715,16 @@ def DefaultConfiguration(self): def HasBuildSetting(self, key): """Determines the state of a build setting in all XCBuildConfiguration - child objects. + 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 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 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. - """ + 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 @@ -1754,9 +1750,9 @@ def HasBuildSetting(self, key): 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. - """ + 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?) @@ -1766,39 +1762,37 @@ def GetBuildSetting(self, key): configuration_value = configuration.GetBuildSetting(key) if value is None: value = configuration_value - else: - if value != configuration_value: - raise ValueError("Variant values for " + key) + elif 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. - """ + 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. - """ + 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. - """ + objects. + """ for configuration in self._properties["buildConfigurations"]: configuration.DelBuildSetting(key) def SetBaseConfiguration(self, value): - """Sets the build configuration in all child XCBuildConfiguration objects. - """ + """Sets the build configuration in all child XCBuildConfiguration objects.""" for configuration in self._properties["buildConfigurations"]: configuration.SetBaseConfiguration(value) @@ -1838,14 +1832,14 @@ def Hashables(self): class XCBuildPhase(XCObject): """Abstract base for build phase classes. Not represented in a project - file. + 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). - """ + 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 @@ -1884,8 +1878,8 @@ def FileGroup(self, path): 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 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) @@ -1894,28 +1888,28 @@ def _AddPathToDict(self, pbxbuildfile, path): 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. - """ + 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"] @@ -1924,14 +1918,13 @@ def _AddBuildFileToDicts(self, pbxbuildfile, path=None): # It's best when the caller provides the path. if isinstance(xcfilelikeelement, PBXVariantGroup): paths.append(path) + # If the caller didn't provide a path, there can be either multiple + # paths (PBXVariantGroup) or one. + elif isinstance(xcfilelikeelement, PBXVariantGroup): + for variant in xcfilelikeelement._properties["children"]: + paths.append(variant.FullPath()) 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()) + 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 @@ -2017,7 +2010,7 @@ def Name(self): return "Frameworks" def FileGroup(self, path): - (root, ext) = posixpath.splitext(path) + (_root, ext) = posixpath.splitext(path) if ext != "": ext = ext[1:].lower() if ext == "o": @@ -2107,12 +2100,11 @@ def FileGroup(self, 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 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: + if path_tree_match := self.path_tree_re.search(path): 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] @@ -2184,9 +2176,7 @@ def SetDestination(self, path): subfolder = 0 relative_path = path[1:] else: - raise ValueError( - f"Can't use path {path} in a {self.__class__.__name__}" - ) + raise ValueError(f"Can't use path {path} in a {self.__class__.__name__}") self._properties["dstPath"] = relative_path self._properties["dstSubfolderSpec"] = subfolder @@ -2536,9 +2526,9 @@ def __init__( # 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._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", "") @@ -2546,9 +2536,10 @@ def __init__( force_extension = suffix[1:] if ( - self._properties["productType"] in { + self._properties["productType"] + in { "com.apple.product-type-bundle.unit.test", - "com.apple.product-type-bundle.ui-testing" + "com.apple.product-type-bundle.ui-testing", } ) and force_extension is None: force_extension = suffix[1:] @@ -2700,10 +2691,8 @@ def AddDependency(self, other): other._properties["productType"] == static_library_type or ( ( - other._properties["productType"] in { - shared_library_type, - framework_type - } + other._properties["productType"] + in {shared_library_type, framework_type} ) and ( (not other.HasBuildSetting("MACH_O_TYPE")) @@ -2712,7 +2701,6 @@ def AddDependency(self, other): ) ) ): - file_ref = other.GetProperty("productReference") pbxproject = self.PBXProjectAncestor() @@ -2738,13 +2726,13 @@ class PBXProject(XCContainerPortal): # 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. - """ + 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( @@ -2839,17 +2827,17 @@ def ProjectsGroup(self): 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. + 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). - """ + 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. @@ -2875,11 +2863,11 @@ def RootGroupForPath(self, path): def AddOrGetFileInRootGroup(self, path): """Returns a PBXFileReference corresponding to path in the correct group - according to RootGroupForPath's heuristics. + according to RootGroupForPath's heuristics. - If an existing PBXFileReference for path exists, it will be returned. - Otherwise, one will be created and returned. - """ + 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) @@ -2929,17 +2917,17 @@ def SortGroups(self): def AddOrGetProjectReference(self, other_pbxproject): """Add a reference to another project file (via PBXProject object) to this - one. + 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. + 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 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"] = [] @@ -2991,10 +2979,10 @@ def AddOrGetProjectReference(self, other_pbxproject): # Xcode seems to sort this list case-insensitively self._properties["projectReferences"] = sorted( self._properties["projectReferences"], - key=lambda x: x["ProjectRef"].Name().lower() + key=lambda x: x["ProjectRef"].Name().lower(), ) else: - # The link already exists. Pull out the relevnt data. + # The link already exists. Pull out the relevant data. project_ref_dict = self._other_pbxprojects[other_pbxproject] product_group = project_ref_dict["ProductGroup"] project_ref = project_ref_dict["ProjectRef"] @@ -3016,11 +3004,8 @@ def _AllSymrootsUnique(self, target, inherit_unique_symroot): # 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 + 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 @@ -3124,7 +3109,8 @@ def CompareProducts(x, y, remote_products): product_group._properties["children"] = sorted( product_group._properties["children"], key=cmp_to_key( - lambda x, y, rp=remote_products: CompareProducts(x, y, rp)), + lambda x, y, rp=remote_products: CompareProducts(x, y, rp) + ), ) @@ -3158,9 +3144,7 @@ def Print(self, file=sys.stdout): self._XCPrint(file, 0, "{ ") else: self._XCPrint(file, 0, "{\n") - for property, value in sorted( - self._properties.items() - ): + for property, value in sorted(self._properties.items()): if property == "objects": self._PrintObjects(file) else: @@ -3186,9 +3170,7 @@ def _PrintObjects(self, file): 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") - ): + for object in sorted(objects_by_class[class_name], key=attrgetter("id")): object.Print(file) self._XCPrint(file, 0, "/* End " + class_name + " section */\n") diff --git a/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py b/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py index 530196366946d..d7e3b5a95604f 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py @@ -9,7 +9,6 @@ TODO(bradnelson): Consider dropping this when we drop XP support. """ - import xml.dom.minidom diff --git a/node_modules/node-gyp/gyp/pylib/packaging/_elffile.py b/node_modules/node-gyp/gyp/pylib/packaging/_elffile.py index 6fb19b30bb53c..cb33e10556ba1 100644 --- a/node_modules/node-gyp/gyp/pylib/packaging/_elffile.py +++ b/node_modules/node-gyp/gyp/pylib/packaging/_elffile.py @@ -48,8 +48,7 @@ def __init__(self, f: IO[bytes]) -> None: ident = self._read("16B") except struct.error: raise ELFInvalid("unable to parse identification") - magic = bytes(ident[:4]) - if magic != b"\x7fELF": + if (magic := bytes(ident[:4])) != b"\x7fELF": raise ELFInvalid(f"invalid magic: {magic!r}") self.capacity = ident[4] # Format for program header (bitness). diff --git a/node_modules/node-gyp/gyp/pylib/packaging/markers.py b/node_modules/node-gyp/gyp/pylib/packaging/markers.py index 8b98fca7233be..7e4d150208eec 100644 --- a/node_modules/node-gyp/gyp/pylib/packaging/markers.py +++ b/node_modules/node-gyp/gyp/pylib/packaging/markers.py @@ -166,8 +166,7 @@ def _evaluate_markers(markers: MarkerList, environment: Dict[str, str]) -> bool: def format_full_version(info: "sys._version_info") -> str: version = "{0.major}.{0.minor}.{0.micro}".format(info) - kind = info.releaselevel - if kind != "final": + if (kind := info.releaselevel) != "final": version += kind[0] + str(info.serial) return version diff --git a/node_modules/node-gyp/gyp/pylib/packaging/metadata.py b/node_modules/node-gyp/gyp/pylib/packaging/metadata.py index fb274930799da..38fa645b4c950 100644 --- a/node_modules/node-gyp/gyp/pylib/packaging/metadata.py +++ b/node_modules/node-gyp/gyp/pylib/packaging/metadata.py @@ -21,27 +21,10 @@ 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 - +from typing import Literal, TypedDict try: - ExceptionGroup + ExceptionGroup # Added in Python 3.11+ except NameError: # pragma: no cover class ExceptionGroup(Exception): # noqa: N818 @@ -145,7 +128,7 @@ class RawMetadata(TypedDict, total=False): # Metadata 2.3 - PEP 685 # No new fields were added in PEP 685, just some edge case were - # tightened up to provide better interoptability. + # tightened up to provide better interoperability. _STRING_FIELDS = { @@ -206,10 +189,10 @@ def _parse_project_urls(data: List[str]) -> Dict[str, str]: # 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 + # The other potential 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 + # thing we can, which is treat the field as unparsable 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 @@ -222,8 +205,8 @@ def _parse_project_urls(data: List[str]) -> Dict[str, str]: 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. + # is unparsable, and we can just add the whole thing to our + # unparsable data and stop processing it. raise KeyError("duplicate labels in project urls") urls[label] = url @@ -433,7 +416,7 @@ def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[st 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. + # throw it in our unparsable data and move on. else: unparsed[name] = value @@ -450,7 +433,7 @@ def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[st else: if payload: # Check to see if we've already got a description, if so then both - # it, and this body move to unparseable. + # it, and this body move to unparsable. if "description" in raw: description_header = cast(str, raw.pop("description")) unparsed.setdefault("description", []).extend( @@ -504,7 +487,7 @@ def __set_name__(self, _owner: "Metadata", name: str) -> None: 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(). + # 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__ @@ -591,8 +574,7 @@ def _process_description_content_type(self, value: str) -> str: f"{{field}} must be one of {list(content_types)}, not {value!r}" ) - charset = parameters.get("charset", "UTF-8") - if charset != "UTF-8": + if (charset := parameters.get("charset", "UTF-8")) != "UTF-8": raise self._invalid_metadata( f"{{field}} can only specify the UTF-8 charset, not {list(charset)}" ) diff --git a/node_modules/node-gyp/gyp/pylib/packaging/tags.py b/node_modules/node-gyp/gyp/pylib/packaging/tags.py index 37f33b1ef849e..f1da2b96d39c1 100644 --- a/node_modules/node-gyp/gyp/pylib/packaging/tags.py +++ b/node_modules/node-gyp/gyp/pylib/packaging/tags.py @@ -127,10 +127,8 @@ def _normalize_string(string: str) -> str: 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) + return len(python_version) > 1 def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]: @@ -146,17 +144,7 @@ def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]: 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: + if debug: # Debug builds can also load "normal" extension modules. # We can also assume no UCS-4 or pymalloc requirement. abis.append(f"cp{version}") diff --git a/node_modules/node-gyp/gyp/pyproject.toml b/node_modules/node-gyp/gyp/pyproject.toml index 7183e07d3c2cd..487cb75002d2e 100644 --- a/node_modules/node-gyp/gyp/pyproject.toml +++ b/node_modules/node-gyp/gyp/pyproject.toml @@ -4,32 +4,33 @@ build-backend = "setuptools.build_meta" [project] name = "gyp-next" -version = "0.16.1" +version = "0.22.2" 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" -# The Python module "packaging" is vendored in the "pylib/packaging" directory to support Python >= 3.12. -# dependencies = ["packaging>=23.1"] # Uncomment this line if the vendored version is removed. +license = "BSD-3-Clause" +license-files = ["LICENSE"] +requires-python = ">=3.9" +dependencies = ["packaging>=24.0", "setuptools>=77.0.3"] 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", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] [project.optional-dependencies] -dev = ["flake8", "ruff", "pytest"] +dev = ["pytest", "ruff"] [project.scripts] gyp = "gyp:script_main" @@ -38,7 +39,11 @@ gyp = "gyp:script_main" "Homepage" = "https://github.com/nodejs/gyp-next" [tool.ruff] -lint.select = [ +extend-exclude = ["pylib/packaging"] +line-length = 88 + +[tool.ruff.lint] +select = [ "C4", # flake8-comprehensions "C90", # McCabe cyclomatic complexity "DTZ", # flake8-datetimez @@ -87,28 +92,20 @@ lint.select = [ # "T20", # flake8-print # "TRY", # tryceratops ] -lint.ignore = [ - "E721", - "PLC1901", - "PLR0402", +ignore = [ "PLR1714", - "PLR2004", - "PLR5501", "PLW0603", "PLW2901", - "PYI024", "RUF005", "RUF012", "UP031", ] -extend-exclude = ["pylib/packaging"] -line-length = 88 -target-version = "py37" [tool.ruff.lint.mccabe] max-complexity = 101 [tool.ruff.lint.pylint] +allow-magic-value-types = ["float", "int", "str"] max-args = 11 max-branches = 108 max-returns = 10 diff --git a/node_modules/node-gyp/gyp/release-please-config.json b/node_modules/node-gyp/gyp/release-please-config.json new file mode 100644 index 0000000000000..b6cad32a2dd0e --- /dev/null +++ b/node_modules/node-gyp/gyp/release-please-config.json @@ -0,0 +1,11 @@ +{ + "last-release-sha": "78756421b0d7bb335992a9c7d26ba3cc8b619708", + "packages": { + ".": { + "release-type": "python", + "package-name": "gyp-next", + "bump-minor-pre-major": true, + "include-component-in-tag": false + } + } +} diff --git a/node_modules/node-gyp/gyp/test_gyp.py b/node_modules/node-gyp/gyp/test_gyp.py index b7bb956b8ed58..70c81ae8ca3bf 100755 --- a/node_modules/node-gyp/gyp/test_gyp.py +++ b/node_modules/node-gyp/gyp/test_gyp.py @@ -5,7 +5,6 @@ """gyptest.py -- test runner for GYP tests.""" - import argparse import os import platform @@ -148,13 +147,13 @@ def print_configuration_info(): print("Test configuration:") if sys.platform == "darwin": sys.path.append(os.path.abspath("test/lib")) - import TestMac + import TestMac # noqa: PLC0415 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 + import gyp.MSVSVersion # noqa: PLC0415 print(" Win %s %s\n" % platform.win32_ver()[0:2]) print(" MSVS %s" % gyp.MSVSVersion.SelectVisualStudioVersion().Description()) diff --git a/node_modules/node-gyp/lib/build.js b/node_modules/node-gyp/lib/build.js index 6b8d84d3ede34..00a0abe691adc 100644 --- a/node_modules/node-gyp/lib/build.js +++ b/node_modules/node-gyp/lib/build.js @@ -1,8 +1,9 @@ 'use strict' -const fs = require('graceful-fs').promises +const gracefulFs = require('graceful-fs') +const fs = gracefulFs.promises const path = require('path') -const { glob } = require('glob') +const { glob } = require('tinyglobby') const log = require('./log') const which = require('which') const win = process.platform === 'win32' @@ -83,61 +84,70 @@ async function build (gyp, argv) { */ async function findSolutionFile () { - const files = await glob('build/*.sln') + const files = await glob('build/*.sln', { expandDirectories: false }) if (files.length === 0) { - throw new Error('Could not find *.sln file. Did you run "configure"?') + if (gracefulFs.existsSync('build/Makefile') || + (await glob('build/*.mk', { expandDirectories: false })).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() + await doWhich(true) } /** * Uses node-which to locate the msbuild / make executable. */ - async function doWhich () { + async function doWhich (msvs) { // On Windows use msbuild provided by node-gyp configure - if (win) { + 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() + 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() + await doBuild(msvs) } /** * Actually spawn the process and compile the module. */ - async function doBuild () { + async function doBuild (msvs) { // Enable Verbose build const verbose = log.logger.isVisible('verbose') let j - if (!win && verbose) { + if (!msvs && verbose) { argv.push('V=1') } - if (win && !verbose) { + if (msvs && !verbose) { argv.push('/clp:Verbosity=minimal') } - if (win) { + if (msvs) { // Turn off the Microsoft logo on Windows argv.push('/nologo') + // No lingering msbuild processes and open file handles + argv.push('/nodeReuse:false') } // Specify the build type, Release by default - if (win) { + 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. @@ -153,7 +163,7 @@ async function build (gyp, argv) { if (!isNaN(j) && j > 0) { argv.push('/m:' + j) } else if (jobs.toUpperCase() === 'MAX') { - argv.push('/m:' + require('os').cpus().length) + argv.push('/m:' + require('os').availableParallelism()) } } } else { @@ -168,12 +178,12 @@ async function build (gyp, argv) { argv.push(j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('--jobs') - argv.push(require('os').cpus().length) + argv.push(require('os').availableParallelism()) } } } - if (win) { + if (msvs) { // did the user specify their own .sln file? const hasSln = argv.some(function (arg) { return path.extname(arg) === '.sln' @@ -202,7 +212,7 @@ async function build (gyp, 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 }) + await fs.rm(buildBinsDir, { recursive: true, maxRetries: 3 }) } if (code !== 0) { diff --git a/node_modules/node-gyp/lib/clean.js b/node_modules/node-gyp/lib/clean.js index 523f8016caece..479c374f10fa2 100644 --- a/node_modules/node-gyp/lib/clean.js +++ b/node_modules/node-gyp/lib/clean.js @@ -8,7 +8,7 @@ async function clean (gyp, argv) { const buildDir = 'build' log.verbose('clean', 'removing "%s" directory', buildDir) - await fs.rm(buildDir, { recursive: true, force: true }) + await fs.rm(buildDir, { recursive: true, force: true, maxRetries: 3 }) } module.exports = clean diff --git a/node_modules/node-gyp/lib/configure.js b/node_modules/node-gyp/lib/configure.js index e4b8c94e3d259..ee672cfbf26c2 100644 --- a/node_modules/node-gyp/lib/configure.js +++ b/node_modules/node-gyp/lib/configure.js @@ -92,8 +92,28 @@ async function configure (gyp, argv) { log.verbose( 'build dir', '"build" dir needed to be created?', isNew ? 'Yes' : 'No' ) - const vsInfo = win ? await findVisualStudio(release.semver, gyp.opts['msvs-version']) : null - return createConfigFile(vsInfo) + 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) { diff --git a/node_modules/node-gyp/lib/create-config-gypi.js b/node_modules/node-gyp/lib/create-config-gypi.js index d598dea6e2e7f..d471da5169092 100644 --- a/node_modules/node-gyp/lib/create-config-gypi.js +++ b/node_modules/node-gyp/lib/create-config-gypi.js @@ -96,6 +96,14 @@ async function getCurrentConfigGypi ({ gyp, nodeDir, vsInfo, python }) { } } variables.msbuild_path = vsInfo.msBuild + if (config.variables.clang === 1) { + config.variables.clang = 0 + } + // disable LTO for addon builds. node release builds may enable (thin) LTO, + // which leaks clang/lld-only flags like -flto=thin and /opt:lldltojobs into + // addons built with the default MSVC toolchain, which rejects those flags + variables.enable_lto = 'false' + variables.enable_thin_lto = 'false' } // loop through the rest of the opts and add the unknown ones as variables. diff --git a/node_modules/node-gyp/lib/download.js b/node_modules/node-gyp/lib/download.js index ed0aa37f44116..dfaca798cf827 100644 --- a/node_modules/node-gyp/lib/download.js +++ b/node_modules/node-gyp/lib/download.js @@ -1,4 +1,5 @@ -const fetch = require('make-fetch-happen') +const { Readable } = require('stream') +const { Agent, EnvHttpProxyAgent, RetryAgent, fetch } = require('undici') const { promises: fs } = require('graceful-fs') const log = require('./log') @@ -10,19 +11,65 @@ async function download (gyp, url) { 'User-Agent': `node-gyp v${gyp.version} (node ${process.version})`, Connection: 'keep-alive' }, - proxy: gyp.opts.proxy, - noProxy: gyp.opts.noproxy + dispatcher: await createDispatcher(gyp) } - const cafile = gyp.opts.cafile - if (cafile) { - requestOpts.ca = await readCAFile(cafile) + let res + try { + res = await fetch(url, requestOpts) + } catch (err) { + // Built-in fetch wraps low-level errors in "TypeError: fetch failed" with + // the underlying error on .cause. Callers inspect .code (e.g. ENOTFOUND). + if (err.cause) { + throw err.cause + } + throw err } - const res = await fetch(url, requestOpts) log.http(res.status, res.url) - return res + const body = res.body ? Readable.fromWeb(res.body) : Readable.from([]) + return { + status: res.status, + url: res.url, + body, + text: async () => { + let data = '' + body.setEncoding('utf8') + for await (const chunk of body) { + data += chunk + } + return data + } + } +} + +async function createDispatcher (gyp) { + const env = process.env + const hasProxyEnv = env.http_proxy || env.HTTP_PROXY || env.https_proxy || env.HTTPS_PROXY + if (!gyp.opts.proxy && !gyp.opts.cafile && !hasProxyEnv) { + return new RetryAgent(new Agent(), { maxRetries: 3 }) + } + + const opts = {} + if (gyp.opts.cafile) { + const ca = await readCAFile(gyp.opts.cafile) + // EnvHttpProxyAgent forwards opts to both its internal Agent (direct) and + // ProxyAgent (proxied). Agent reads TLS config from `connect`; ProxyAgent + // reads it from `requestTls` (origin) / `proxyTls` (proxy). Set all three + // so the custom CA is applied regardless of which path a request takes. + opts.connect = { ca } + opts.requestTls = { ca } + opts.proxyTls = { ca } + } + if (gyp.opts.proxy) { + opts.httpProxy = gyp.opts.proxy + opts.httpsProxy = gyp.opts.proxy + } + if (gyp.opts.noproxy) { + opts.noProxy = gyp.opts.noproxy + } + return new RetryAgent(new EnvHttpProxyAgent(opts), { maxRetries: 3 }) } async function readCAFile (filename) { diff --git a/node_modules/node-gyp/lib/find-python.js b/node_modules/node-gyp/lib/find-python.js index a71c00c2b65bc..273b5957b4992 100644 --- a/node_modules/node-gyp/lib/find-python.js +++ b/node_modules/node-gyp/lib/find-python.js @@ -86,14 +86,10 @@ class PythonFinder { { before: () => { if (!this.configPython) { - this.addLog( - 'Python is not set from command line or npm configuration') + this.addLog('--python was not set on the command line') 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}"`) + this.addLog(`--python=${this.configPython} was set on the command line`) }, check: () => this.checkCommand(this.configPython) }, @@ -295,8 +291,6 @@ class PythonFinder { `- 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', '**********************************************************' diff --git a/node_modules/node-gyp/lib/find-visualstudio.js b/node_modules/node-gyp/lib/find-visualstudio.js index 8c5ae96127504..efb8b02a59155 100644 --- a/node_modules/node-gyp/lib/find-visualstudio.js +++ b/node_modules/node-gyp/lib/find-visualstudio.js @@ -30,7 +30,7 @@ class VisualStudioFinder { this.configVersionYear = null this.configPath = null if (this.configMsvsVersion) { - this.addLog('msvs_version was set from command line or npm config') + this.addLog(`--msvs_version=${this.configMsvsVersion} was set on the command line`) if (this.configMsvsVersion.match(/^\d{4}$/)) { this.configVersionYear = parseInt(this.configMsvsVersion, 10) this.addLog( @@ -41,7 +41,7 @@ class VisualStudioFinder { `- looking for Visual Studio installed in "${this.configPath}"`) } } else { - this.addLog('msvs_version not set from command line or npm config') + this.addLog('--msvs_version was not set on the command line') } if (process.env.VCINSTALLDIR) { @@ -54,8 +54,10 @@ class VisualStudioFinder { } const checks = [ + () => this.findVisualStudio2019OrNewerFromSpecifiedLocation(), () => this.findVisualStudio2019OrNewerUsingSetupModule(), () => this.findVisualStudio2019OrNewer(), + () => this.findVisualStudio2017FromSpecifiedLocation(), () => this.findVisualStudio2017UsingSetupModule(), () => this.findVisualStudio2017(), () => this.findVisualStudio2015(), @@ -116,8 +118,51 @@ class VisualStudioFinder { throw new Error('Could not find any Visual Studio installation to use') } + async findVisualStudio2019OrNewerFromSpecifiedLocation () { + return this.findVSFromSpecifiedLocation([2019, 2022, 2026]) + } + + 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', + 'Microsoft.VisualStudio.Component.VC.Tools.ARM64', + // 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]) + return this.findNewVSUsingSetupModule([2019, 2022, 2026]) } async findVisualStudio2017UsingSetupModule () { @@ -178,7 +223,7 @@ class VisualStudioFinder { // Invoke the PowerShell script to get information about Visual Studio 2019 // or newer installations async findVisualStudio2019OrNewer () { - return this.findNewVS([2019, 2022]) + return this.findNewVS([2019, 2022, 2026]) } // Invoke the PowerShell script to get information about Visual Studio 2017 @@ -202,7 +247,7 @@ class VisualStudioFinder { 'Unrestricted', '-NoProfile', '-Command', - '&{Add-Type -Path \'' + csFile + '\';' + '[VisualStudioConfiguration.Main]::PrintJson()}' + '&{Add-Type -IgnoreWarnings -Path \'' + csFile + '\';' + '[VisualStudioConfiguration.Main]::PrintJson()}' ] this.log.silly('Running', ps, psArgs) @@ -321,7 +366,7 @@ class VisualStudioFinder { // Helper - process version information getVersionInfo (info) { - const match = /^(\d+)\.(\d+)\..*/.exec(info.version) + const match = /^(\d+)\.(\d+)(?:\..*)?/.exec(info.version) if (!match) { this.log.silly('- failed to parse version:', info.version) return {} @@ -344,6 +389,10 @@ class VisualStudioFinder { ret.versionYear = 2022 return ret } + if (ret.versionMajor === 18) { + ret.versionYear = 2026 + return ret + } this.log.silly('- unsupported version:', ret.versionMajor) return {} } @@ -363,7 +412,11 @@ class VisualStudioFinder { return path.join(info.path, 'MSBuild', '15.0', 'Bin', 'MSBuild.exe') } if (versionYear === 2019) { - return msbuildPath + if (process.arch === 'arm64' && this.msBuildPathExists(msbuildPathArm64)) { + return msbuildPathArm64 + } else { + return msbuildPath + } } } /** @@ -381,12 +434,21 @@ class VisualStudioFinder { // Helper - process toolset information getToolset (info, versionYear) { - const pkg = 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64' + const vcToolsArm64 = 'VC.Tools.ARM64' + const pkgArm64 = `Microsoft.VisualStudio.Component.${vcToolsArm64}` + const vcToolsX64 = 'VC.Tools.x86.x64' + const pkgX64 = `Microsoft.VisualStudio.Component.${vcToolsX64}` 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) { + if (process.arch === 'arm64' && info.packages.includes(pkgArm64)) { + this.log.silly(`- found ${vcToolsArm64}`) + } else if (info.packages.includes(pkgX64)) { + if (process.arch === 'arm64') { + this.addLog(`- found ${vcToolsX64} on ARM64 platform. Expect less performance and/or link failure with ARM64 binary.`) + } else { + this.log.silly(`- found ${vcToolsX64}`) + } + } else if (info.packages.includes(express)) { this.log.silly('- found Visual Studio Express (looking for toolset)') } else { return null @@ -398,6 +460,8 @@ class VisualStudioFinder { return 'v142' } else if (versionYear === 2022) { return 'v143' + } else if (versionYear === 2026) { + return 'v145' } this.log.silly('- invalid versionYear:', versionYear) return null diff --git a/node_modules/node-gyp/lib/install.js b/node_modules/node-gyp/lib/install.js index 7196a316296fb..3580cdd003b21 100644 --- a/node_modules/node-gyp/lib/install.js +++ b/node_modules/node-gyp/lib/install.js @@ -198,12 +198,12 @@ async function install (gyp, argv) { } // download the tarball and extract! - // Ommited on Windows if only new node.lib is required + // Omitted on Windows if only new node.lib is required - // on Windows there can be file errors from tar if parallel installs + // 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 + const tarExtractDir = await fs.mkdtemp(path.join(os.tmpdir(), 'node-gyp-tmp-')) try { if (shouldDownloadTarball) { @@ -277,17 +277,13 @@ async function install (gyp, argv) { } // copy over the files from the temp tarball extract directory to devDir - if (tarExtractDir !== devDir) { - await copyDirectory(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') - } + try { + // try to cleanup temp dir + await fs.rm(tarExtractDir, { recursive: true, maxRetries: 3 }) + } catch { + log.warn('failed to clean up temp tarball extract directory') } } diff --git a/node_modules/node-gyp/lib/log.js b/node_modules/node-gyp/lib/log.js index 6841719abab5a..36fa2487f5ce1 100644 --- a/node_modules/node-gyp/lib/log.js +++ b/node_modules/node-gyp/lib/log.js @@ -1,12 +1,11 @@ 'use strict' -const procLog = require('proc-log') +const { log } = require('proc-log') const { format } = require('util') // helper to emit log messages with a predefined prefix -const logLevels = Object.keys(procLog).filter((k) => typeof procLog[k] === 'function') -const withPrefix = (prefix) => logLevels.reduce((acc, level) => { - acc[level] = (...args) => procLog[level](prefix, ...args) +const withPrefix = (prefix) => log.LEVELS.reduce((acc, level) => { + acc[level] = (...args) => log[level](prefix, ...args) return acc }, {}) @@ -78,7 +77,7 @@ class Logger { this.#levels = new Map(this.#levels.map((level, index) => [level.id, { ...level, index }])) this.level = 'info' this.stream = stream - procLog.pause() + log.pause() } get stream () { @@ -165,5 +164,5 @@ module.exports = { logger: new Logger(NULL_LOGGER ? null : process.stderr), stdout: NULL_LOGGER ? () => {} : (...args) => console.log(...args), withPrefix, - ...procLog + ...log } diff --git a/node_modules/node-gyp/lib/node-gyp.js b/node_modules/node-gyp/lib/node-gyp.js index 5e25bf996f8b2..dafce99d49e35 100644 --- a/node_modules/node-gyp/lib/node-gyp.js +++ b/node_modules/node-gyp/lib/node-gyp.js @@ -122,31 +122,42 @@ class Gyp extends EventEmitter { } // 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 { + // npm will set environment variables in the following forms: + // - `npm_config_` for values from npm's own config. Setting arbitrary + // options on npm's config was deprecated in npm v11 but node-gyp still + // supports it for backwards compatibility. + // See https://github.com/nodejs/node-gyp/issues/3156 + // - `npm_package_config_node_gyp_` for values from the `config` object + // in package.json. This is the preferred way to set options for node-gyp + // since npm v11. The `node_gyp_` prefix is used to avoid conflicts with + // other tools. + // The `npm_package_config_node_gyp_` prefix will take precedence over + // `npm_config_` keys. + const npmConfigPrefix = /^npm_config_/i + const npmPackageConfigPrefix = /^npm_package_config_node_gyp_/i + + const configEnvKeys = Object.keys(process.env) + .filter((k) => npmConfigPrefix.test(k) || npmPackageConfigPrefix.test(k)) + // sort so that npm_package_config_node_gyp_ keys come last and will override + .sort((a) => npmConfigPrefix.test(a) ? -1 : 1) + + for (const key of configEnvKeys) { // 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) { + const name = npmConfigPrefix.test(key) + ? key.replace(npmConfigPrefix, '') + : key.replace(npmPackageConfigPrefix, '') + // 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 - } + // and convert to lowercase + this.opts[name.replaceAll('_', '-').toLowerCase()] = process.env[key] } - }) + } if (this.opts.loglevel) { log.logger.level = this.opts.loglevel + delete this.opts.loglevel } log.resume() } diff --git a/node_modules/node-gyp/lib/process-release.js b/node_modules/node-gyp/lib/process-release.js index c9a319dfadd2b..75f3fc136a35b 100644 --- a/node_modules/node-gyp/lib/process-release.js +++ b/node_modules/node-gyp/lib/process-release.js @@ -1,9 +1,6 @@ -/* eslint-disable n/no-deprecated-api */ - 'use strict' const semver = require('semver') -const url = require('url') const path = require('path') const log = require('./log') @@ -74,11 +71,11 @@ function processRelease (argv, gyp, defaultVersion, defaultRelease) { } else { distBaseUrl = 'https://nodejs.org/dist' } - distBaseUrl += '/v' + version + '/' + distBaseUrl = new URL(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, './') + baseUrl = new URL('./', 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) @@ -96,28 +93,28 @@ function processRelease (argv, gyp, defaultVersion, defaultRelease) { // 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') + tarballUrl = new URL(name + '-v' + version + (canGetHeaders ? '-headers' : '') + '.tar.gz', baseUrl).href } return { version, semver: versionSemver, name, - baseUrl, + baseUrl: baseUrl.href, tarballUrl, - shasumsUrl: url.resolve(baseUrl, 'SHASUMS256.txt'), + shasumsUrl: new URL('SHASUMS256.txt', baseUrl).href, versionDir: (name !== 'node' ? name + '-' : '') + version, ia32: { - libUrl: libUrl32, - libPath: normalizePath(path.relative(url.parse(baseUrl).path, url.parse(libUrl32).path)) + libUrl: libUrl32.href, + libPath: normalizePath(path.relative(baseUrl.pathname, libUrl32.pathname)) }, x64: { - libUrl: libUrl64, - libPath: normalizePath(path.relative(url.parse(baseUrl).path, url.parse(libUrl64).path)) + libUrl: libUrl64.href, + libPath: normalizePath(path.relative(baseUrl.pathname, libUrl64.pathname)) }, arm64: { - libUrl: libUrlArm64, - libPath: normalizePath(path.relative(url.parse(baseUrl).path, url.parse(libUrlArm64).path)) + libUrl: libUrlArm64.href, + libPath: normalizePath(path.relative(baseUrl.pathname, libUrlArm64.pathname)) } } } @@ -127,20 +124,21 @@ function normalizePath (p) { } function resolveLibUrl (name, defaultUrl, arch, versionMajor) { - const base = url.resolve(defaultUrl, './') - const hasLibUrl = bitsre.test(defaultUrl) || (versionMajor === 3 && bitsreV3.test(defaultUrl)) + if (!defaultUrl.pathname) defaultUrl = new URL(defaultUrl) + const base = new URL('./', defaultUrl) + const hasLibUrl = bitsre.test(defaultUrl.pathname) || (versionMajor === 3 && bitsreV3.test(defaultUrl.pathname)) if (!hasLibUrl) { // let's assume it's a baseUrl then if (versionMajor >= 1) { - return url.resolve(base, 'win-' + arch + '/' + name + '.lib') + return new URL('win-' + arch + '/' + name + '.lib', base) } // 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') + return new URL((arch === 'x86' ? '' : arch + '/') + name + '.lib', base) } // 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 + '/') + return new URL(defaultUrl.pathname.replace(versionMajor === 3 ? bitsreV3 : bitsre, '/win-' + arch + '/'), defaultUrl) } module.exports = processRelease diff --git a/node_modules/node-gyp/lib/remove.js b/node_modules/node-gyp/lib/remove.js index 7efdb01a662e7..55736f71d97c5 100644 --- a/node_modules/node-gyp/lib/remove.js +++ b/node_modules/node-gyp/lib/remove.js @@ -36,7 +36,7 @@ async function remove (gyp, argv) { throw err } - await fs.rm(versionPath, { recursive: true, force: true }) + await fs.rm(versionPath, { recursive: true, force: true, maxRetries: 3 }) } module.exports = remove diff --git a/node_modules/node-gyp/node_modules/proc-log/LICENSE b/node_modules/node-gyp/node_modules/proc-log/LICENSE deleted file mode 100644 index 83837797202b7..0000000000000 --- a/node_modules/node-gyp/node_modules/proc-log/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/node-gyp/node_modules/proc-log/lib/index.js b/node_modules/node-gyp/node_modules/proc-log/lib/index.js deleted file mode 100644 index 7c5dfad3b7ba3..0000000000000 --- a/node_modules/node-gyp/node_modules/proc-log/lib/index.js +++ /dev/null @@ -1,23 +0,0 @@ -// emits 'log' events on the process -const LEVELS = [ - 'notice', - 'error', - 'warn', - 'info', - 'verbose', - 'http', - 'silly', - 'pause', - 'resume', -] - -const log = level => (...args) => process.emit('log', level, ...args) - -const logger = {} -for (const level of LEVELS) { - logger[level] = log(level) -} - -logger.LEVELS = LEVELS - -module.exports = logger diff --git a/node_modules/node-gyp/node_modules/proc-log/package.json b/node_modules/node-gyp/node_modules/proc-log/package.json deleted file mode 100644 index d335fa965ace5..0000000000000 --- a/node_modules/node-gyp/node_modules/proc-log/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "proc-log", - "version": "3.0.0", - "files": [ - "bin/", - "lib/" - ], - "main": "lib/index.js", - "description": "just emit 'log' events on the process object", - "repository": { - "type": "git", - "url": "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": "eslint \"**/*.js\"", - "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "template-oss-apply": "template-oss-apply --force" - }, - "devDependencies": { - "@npmcli/eslint-config": "^3.0.1", - "@npmcli/template-oss": "4.5.1", - "tap": "^16.0.1" - }, - "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.5.1" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/node-gyp/package.json b/node_modules/node-gyp/package.json index 95f012fa5daf7..cc11fc65e8b97 100644 --- a/node_modules/node-gyp/package.json +++ b/node_modules/node-gyp/package.json @@ -11,7 +11,7 @@ "bindings", "gyp" ], - "version": "10.1.0", + "version": "13.0.0", "installVersion": 11, "author": "Nathan Rajlich (http://tootallnate.net)", "repository": { @@ -24,28 +24,31 @@ "dependencies": { "env-paths": "^2.2.0", "exponential-backoff": "^3.1.1", - "glob": "^10.3.10", "graceful-fs": "^4.2.6", - "make-fetch-happen": "^13.0.0", - "nopt": "^7.0.0", - "proc-log": "^3.0.0", + "nopt": "^10.0.0", + "proc-log": "^7.0.0", "semver": "^7.3.5", - "tar": "^6.1.2", - "which": "^4.0.0" + "tar": "^7.5.4", + "tinyglobby": "^0.2.12", + "undici": "^6.25.0", + "which": "^7.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "devDependencies": { + "@commitlint/cli": "^21.0.2", + "@commitlint/config-conventional": "^21.0.2", "bindings": "^1.5.0", - "cross-env": "^7.0.3", - "mocha": "^10.2.0", - "nan": "^2.14.2", - "require-inject": "^1.4.4", - "standard": "^17.0.0" + "cross-env": "^10.1.0", + "eslint": "^9.39.1", + "mocha": "^11.7.5", + "nan": "^2.23.1", + "neostandard": "^0.13.0", + "require-inject": "^1.4.4" }, "scripts": { - "lint": "standard \"*/*.js\" \"test/**/*.js\" \".github/**/*.js\"", - "test": "cross-env NODE_GYP_NULL_LOGGER=true mocha --timeout 15000 test/test-download.js test/test-*" + "lint": "eslint \"*/*.js\" \"test/**/*.js\" \".github/**/*.js\"", + "test": "cross-env NODE_GYP_NULL_LOGGER=true mocha --timeout 30000 test/test-download.js test/test-*" } } diff --git a/node_modules/node-gyp/src/win_delay_load_hook.cc b/node_modules/node-gyp/src/win_delay_load_hook.cc index 169f8029f10fd..63e197706d466 100644 --- a/node_modules/node-gyp/src/win_delay_load_hook.cc +++ b/node_modules/node-gyp/src/win_delay_load_hook.cc @@ -28,7 +28,9 @@ static FARPROC WINAPI load_exe_hook(unsigned int event, DelayLoadInfo* info) { if (_stricmp(info->szDll, HOST_BINARY) != 0) return NULL; - m = GetModuleHandle(NULL); + // try for libnode.dll to compat node.js that using 'vcbuild.bat dll' + m = GetModuleHandle(TEXT("libnode.dll")); + if (m == NULL) m = GetModuleHandle(NULL); return (FARPROC) m; } diff --git a/node_modules/nopt/lib/debug.js b/node_modules/nopt/lib/debug.js deleted file mode 100644 index 544ab382ca85c..0000000000000 --- a/node_modules/nopt/lib/debug.js +++ /dev/null @@ -1,5 +0,0 @@ -/* istanbul ignore next */ -module.exports = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG - // eslint-disable-next-line no-console - ? (...a) => console.error(...a) - : () => {} diff --git a/node_modules/nopt/lib/nopt-lib.js b/node_modules/nopt/lib/nopt-lib.js index d3d1de0255ba9..2030f651ca8d8 100644 --- a/node_modules/nopt/lib/nopt-lib.js +++ b/node_modules/nopt/lib/nopt-lib.js @@ -1,5 +1,4 @@ const abbrev = require('abbrev') -const debug = require('./debug') const defaultTypeDefs = require('./type-defs') const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k) @@ -25,12 +24,12 @@ function nopt (args, { types, shorthands, typeDefs, - invalidHandler, + invalidHandler, // opt is configured but its value does not validate against given type + unknownHandler, // opt is not configured + abbrevHandler, // opt is being expanded via abbrev typeDefault, dynamicTypes, } = {}) { - debug(types, shorthands, args, typeDefs) - const data = {} const argv = { remain: [], @@ -38,7 +37,9 @@ function nopt (args, { original: args.slice(0), } - parse(args, data, argv.remain, { typeDefs, types, dynamicTypes, shorthands }) + parse(args, data, argv.remain, { + typeDefs, types, dynamicTypes, shorthands, unknownHandler, abbrevHandler, + }) // now data is full clean(data, { types, dynamicTypes, typeDefs, invalidHandler, typeDefault }) @@ -85,7 +86,6 @@ function clean (data, { return } let val = data[k] - debug('val=%j', val) const isArray = Array.isArray(val) let [hasType, rawType] = getType(k, { types, dynamicTypes }) let type = rawType @@ -102,12 +102,9 @@ function clean (data, { 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' && @@ -115,12 +112,9 @@ function clean (data, { || (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) } } @@ -144,32 +138,24 @@ function clean (data, { 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]) }) } @@ -195,21 +181,21 @@ function validate (data, k, val, type, { typeDefs } = {}) { } // 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. + // NaN is poisonous, it 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 } @@ -218,7 +204,6 @@ function validate (data, k, val, type, { typeDefs } = {}) { 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) ? @@ -234,7 +219,6 @@ function validate (data, k, val, type, { typeDefs } = {}) { } } } - debug('OK? %j (%j %j %j)', ok, k, val, types[types.length - 1]) if (!ok) { delete data[k] @@ -247,21 +231,18 @@ function parse (args, data, remain, { typeDefs = {}, shorthands = {}, dynamicTypes, + unknownHandler, + abbrevHandler, } = {}) { 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. @@ -282,8 +263,7 @@ function parse (args, data, remain, { // 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) + const shRes = resolveShort(arg, shortAbbr, abbrevs, { shorthands, abbrevHandler }) if (shRes) { args.splice.apply(args, [i, 1].concat(shRes)) if (arg !== shRes[0]) { @@ -298,7 +278,11 @@ function parse (args, data, remain, { arg = arg.slice(3) } - if (abbrevs[arg]) { + // abbrev includes the original full string in its abbrev list + if (abbrevs[arg] && abbrevs[arg] !== arg) { + if (abbrevHandler) { + abbrevHandler(arg, abbrevs[arg]) + } arg = abbrevs[arg] } @@ -331,6 +315,18 @@ function parse (args, data, remain, { (argType === null || isTypeArray && ~argType.indexOf(null))) + if (typeof argType === 'undefined') { + // la is going to unexpectedly be parsed outside the context of this arg + const hangingLa = !hadEq && la && !la?.startsWith('-') && !['true', 'false'].includes(la) + if (unknownHandler) { + if (hangingLa) { + unknownHandler(arg, la) + } else { + unknownHandler(arg) + } + } + } + if (isBool) { // just set and move along val = !no @@ -413,14 +409,13 @@ const singleCharacters = (arg, shorthands) => { 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 { abbrevHandler, types = {}, shorthands = {} } = rest.length ? rest.pop() : {} const shortAbbr = rest[0] ?? abbrev(Object.keys(shorthands)) const abbrevs = rest[1] ?? abbrev(Object.keys(types)) @@ -457,7 +452,11 @@ function resolveShort (arg, ...rest) { } // if it's an abbr for a shorthand, then use that + // exact match has already happened so we don't need to account for that here if (shortAbbr[arg]) { + if (abbrevHandler) { + abbrevHandler(arg, shortAbbr[arg]) + } arg = shortAbbr[arg] } diff --git a/node_modules/nopt/lib/nopt.js b/node_modules/nopt/lib/nopt.js index 37f01a08783f8..c9d9e82027411 100644 --- a/node_modules/nopt/lib/nopt.js +++ b/node_modules/nopt/lib/nopt.js @@ -1,10 +1,8 @@ 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. +// 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 @@ -18,6 +16,8 @@ function nopt (types, shorthands, args = process.argv, slice = 2) { shorthands: shorthands || {}, typeDefs: exports.typeDefs, invalidHandler: exports.invalidHandler, + unknownHandler: exports.unknownHandler, + abbrevHandler: exports.abbrevHandler, }) } @@ -26,5 +26,7 @@ function clean (data, types, typeDefs = exports.typeDefs) { types: types || {}, typeDefs, invalidHandler: exports.invalidHandler, + unknownHandler: exports.unknownHandler, + abbrevHandler: exports.abbrevHandler, }) } diff --git a/node_modules/nopt/lib/type-defs.js b/node_modules/nopt/lib/type-defs.js index 608352ee248cc..4e5e5a37ae163 100644 --- a/node_modules/nopt/lib/type-defs.js +++ b/node_modules/nopt/lib/type-defs.js @@ -1,8 +1,7 @@ -const url = require('url') -const path = require('path') -const Stream = require('stream').Stream -const os = require('os') -const debug = require('./debug') +const os = require('node:os') +const path = require('node:path') +const { Stream } = require('node:stream') +const { URL } = require('node:url') function validateString (data, k, val) { data[k] = String(val) @@ -31,7 +30,6 @@ function validatePath (data, k, val) { } function validateNumber (data, k, val) { - debug('validate Number %j %j %j', k, val, isNaN(val)) if (isNaN(val)) { return false } @@ -40,7 +38,6 @@ function validateNumber (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 } @@ -63,13 +60,11 @@ function validateBoolean (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) { + const parsed = URL.parse(String(val)) + if (!parsed) { return false } - data[k] = val.href + data[k] = parsed.href } function validateStream (data, k, val) { @@ -82,7 +77,7 @@ function validateStream (data, k, val) { module.exports = { String: { type: String, validate: validateString }, Boolean: { type: Boolean, validate: validateBoolean }, - url: { type: url, validate: validateUrl }, + url: { type: URL, validate: validateUrl }, Number: { type: Number, validate: validateNumber }, path: { type: path, validate: validatePath }, Stream: { type: Stream, validate: validateStream }, diff --git a/node_modules/nopt/package.json b/node_modules/nopt/package.json index 37b770ad48771..db57f7ef29201 100644 --- a/node_modules/nopt/package.json +++ b/node_modules/nopt/package.json @@ -1,17 +1,20 @@ { "name": "nopt", - "version": "7.2.1", + "version": "10.0.1", "description": "Option parsing for Node, supporting types, shorthands, etc. Used by npm.", "author": "GitHub Inc.", "main": "lib/nopt.js", "scripts": { - "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test": "node --test './test/**/*.js'", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" + "lintfix": "npm run eslint -- --fix", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test:node20": "node --test test", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'" }, "repository": { "type": "git", @@ -22,30 +25,26 @@ }, "license": "ISC", "dependencies": { - "abbrev": "^2.0.0" + "abbrev": "^5.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.3.0" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.0" }, "files": [ "bin/", "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "windowsCI": false, - "version": "4.22.0", - "publish": true + "version": "5.1.0", + "publish": true, + "testRunner": "node:test", + "latestCiVersion": 24, + "updateNpm": false } } diff --git a/node_modules/normalize-package-data/LICENSE b/node_modules/normalize-package-data/LICENSE deleted file mode 100644 index 19d1364a8ac08..0000000000000 --- a/node_modules/normalize-package-data/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/normalize-package-data/lib/extract_description.js b/node_modules/normalize-package-data/lib/extract_description.js deleted file mode 100644 index 631966b5f29af..0000000000000 --- a/node_modules/normalize-package-data/lib/extract_description.js +++ /dev/null @@ -1,24 +0,0 @@ -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() -} diff --git a/node_modules/normalize-package-data/lib/fixer.js b/node_modules/normalize-package-data/lib/fixer.js deleted file mode 100644 index 1c30cad65e6cb..0000000000000 --- a/node_modules/normalize-package-data/lib/fixer.js +++ /dev/null @@ -1,475 +0,0 @@ -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] - } - }) -} diff --git a/node_modules/normalize-package-data/lib/make_warning.js b/node_modules/normalize-package-data/lib/make_warning.js deleted file mode 100644 index 3be9c86539952..0000000000000 --- a/node_modules/normalize-package-data/lib/make_warning.js +++ /dev/null @@ -1,22 +0,0 @@ -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) -} diff --git a/node_modules/normalize-package-data/lib/normalize.js b/node_modules/normalize-package-data/lib/normalize.js deleted file mode 100644 index e806f110315aa..0000000000000 --- a/node_modules/normalize-package-data/lib/normalize.js +++ /dev/null @@ -1,48 +0,0 @@ -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) -} diff --git a/node_modules/normalize-package-data/lib/safe_format.js b/node_modules/normalize-package-data/lib/safe_format.js deleted file mode 100644 index 5fc888e5450cd..0000000000000 --- a/node_modules/normalize-package-data/lib/safe_format.js +++ /dev/null @@ -1,11 +0,0 @@ -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) -} diff --git a/node_modules/normalize-package-data/lib/typos.json b/node_modules/normalize-package-data/lib/typos.json deleted file mode 100644 index 7f9dd283b30ff..0000000000000 --- a/node_modules/normalize-package-data/lib/typos.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "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" } -} diff --git a/node_modules/normalize-package-data/lib/warning_messages.json b/node_modules/normalize-package-data/lib/warning_messages.json deleted file mode 100644 index 4890f506ed965..0000000000000 --- a/node_modules/normalize-package-data/lib/warning_messages.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "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." -} diff --git a/node_modules/normalize-package-data/package.json b/node_modules/normalize-package-data/package.json deleted file mode 100644 index 04a7647abe65c..0000000000000 --- a/node_modules/normalize-package-data/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "normalize-package-data", - "version": "6.0.2", - "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": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint", - "postsnap": "npm run lintfix --", - "postlint": "template-oss-check", - "snap": "tap", - "template-oss-apply": "template-oss-apply --force" - }, - "dependencies": { - "hosted-git-info": "^7.0.0", - "semver": "^7.3.5", - "validate-npm-package-license": "^3.0.4" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.1" - }, - "files": [ - "bin/", - "lib/" - ], - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": "true" - }, - "tap": { - "branches": 86, - "functions": 92, - "lines": 86, - "statements": 86, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/npm-audit-report/package.json b/node_modules/npm-audit-report/package.json index 492071c1faf90..0789ac1bde3d3 100644 --- a/node_modules/npm-audit-report/package.json +++ b/node_modules/npm-audit-report/package.json @@ -1,16 +1,17 @@ { "name": "npm-audit-report", - "version": "5.0.0", + "version": "8.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": "eslint \"**/*.js\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint" + "lintfix": "npm run eslint -- --fix", + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "check-coverage": true, @@ -29,8 +30,8 @@ "author": "GitHub Inc.", "license": "ISC", "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.14.1", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0", "chalk": "^5.2.0", "tap": "^16.0.0" }, @@ -40,7 +41,7 @@ }, "repository": { "type": "git", - "url": "https://github.com/npm/npm-audit-report.git" + "url": "git+https://github.com/npm/npm-audit-report.git" }, "bugs": { "url": "https://github.com/npm/npm-audit-report/issues" @@ -51,10 +52,11 @@ "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.14.1" + "version": "5.0.0", + "publish": true } } diff --git a/node_modules/npm-bundled/package.json b/node_modules/npm-bundled/package.json deleted file mode 100644 index 2744ca6af67fc..0000000000000 --- a/node_modules/npm-bundled/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "npm-bundled", - "version": "3.0.1", - "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": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "mutate-fs": "^2.1.1", - "tap": "^16.3.0" - }, - "scripts": { - "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" - }, - "files": [ - "bin/", - "lib/" - ], - "dependencies": { - "npm-normalize-package-bin": "^3.0.0" - }, - "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.22.0", - "publish": true - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/npm-install-checks/lib/current-env.js b/node_modules/npm-install-checks/lib/current-env.js new file mode 100644 index 0000000000000..31f154aac59b3 --- /dev/null +++ b/node_modules/npm-install-checks/lib/current-env.js @@ -0,0 +1,91 @@ +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, +} diff --git a/node_modules/npm-install-checks/lib/dev-engines.js b/node_modules/npm-install-checks/lib/dev-engines.js new file mode 100644 index 0000000000000..2c483349ae70a --- /dev/null +++ b/node_modules/npm-install-checks/lib/dev-engines.js @@ -0,0 +1,145 @@ +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 "devEngines.${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 devEngines.${engine}`), { + errors: depErrors, + engine, + isWarn: onFail === 'warn', + isError: onFail === 'error', + current: currentEngine, + required: dependencyAsAuthored, + }) + + errors.push(err) + } + } + return errors +} + +module.exports = { + checkDevEngines, +} diff --git a/node_modules/npm-install-checks/lib/index.js b/node_modules/npm-install-checks/lib/index.js index 545472b61dc60..7170292087308 100644 --- a/node_modules/npm-install-checks/lib/index.js +++ b/node_modules/npm-install-checks/lib/index.js @@ -1,4 +1,6 @@ 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 @@ -20,44 +22,29 @@ const checkEngine = (target, npmVer, nodeVer, force = false) => { } } -const isMusl = (file) => file.includes('libc.musl-') || file.includes('ld-musl-') - const checkPlatform = (target, force = false, environment = {}) => { if (force) { return } - const platform = environment.os || process.platform - const arch = environment.cpu || process.arch - const osOk = target.os ? checkList(platform, target.os) : true - const cpuOk = target.cpu ? checkList(arch, target.cpu) : true + const os = environment.os || currentEnv.os() + const cpu = environment.cpu || currentEnv.cpu() + const libc = environment.libc || currentEnv.libc(os) - let libcOk = true - let libcFamily = null - if (target.libc) { - // libc checks only work in linux, any value is a failure if we aren't - if (environment.libc) { - libcOk = checkList(environment.libc, target.libc) - } else if (platform !== 'linux') { - libcOk = false - } else { - const report = process.report.getReport() - if (report.header?.glibcVersionRuntime) { - libcFamily = 'glibc' - } else if (Array.isArray(report.sharedObjects) && report.sharedObjects.some(isMusl)) { - libcFamily = 'musl' - } - libcOk = libcFamily ? checkList(libcFamily, target.libc) : false - } + 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: platform, - cpu: arch, - libc: libcFamily, + os, + cpu, + libc, }, required: { os: target.os, @@ -98,4 +85,6 @@ const checkList = (value, list) => { module.exports = { checkEngine, checkPlatform, + checkDevEngines, + currentEnv, } diff --git a/node_modules/npm-install-checks/package.json b/node_modules/npm-install-checks/package.json index 11a3b87750e25..c97e2e63c7659 100644 --- a/node_modules/npm-install-checks/package.json +++ b/node_modules/npm-install-checks/package.json @@ -1,28 +1,29 @@ { "name": "npm-install-checks", - "version": "6.3.0", + "version": "9.0.0", "description": "Check the engines and platform fields in package.json", "main": "lib/index.js", "dependencies": { "semver": "^7.1.1" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.19.0", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.1.0", "tap": "^16.0.1" }, "scripts": { "test": "tap", - "lint": "eslint \"**/*.js\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "posttest": "npm run lint" + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", - "url": "https://github.com/npm/npm-install-checks.git" + "url": "git+https://github.com/npm/npm-install-checks.git" }, "keywords": [ "npm,", @@ -34,12 +35,12 @@ "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "author": "GitHub Inc.", "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.19.0", + "version": "5.1.0", "publish": "true" }, "tap": { diff --git a/node_modules/npm-normalize-package-bin/package.json b/node_modules/npm-normalize-package-bin/package.json deleted file mode 100644 index 5ea50dc2a47ba..0000000000000 --- a/node_modules/npm-normalize-package-bin/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "npm-normalize-package-bin", - "version": "3.0.1", - "description": "Turn any flavor of allowable package.json bin into a normalized object", - "main": "lib/index.js", - "repository": { - "type": "git", - "url": "https://github.com/npm/npm-normalize-package-bin.git" - }, - "author": "GitHub Inc.", - "license": "ISC", - "scripts": { - "test": "tap", - "snap": "tap", - "lint": "eslint \"**/*.js\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.14.1", - "tap": "^16.3.0" - }, - "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.14.1", - "publish": "true" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/npm-package-arg/lib/npa.js b/node_modules/npm-package-arg/lib/npa.js index 6a3f07da929d8..a25c0a5368941 100644 --- a/node_modules/npm-package-arg/lib/npa.js +++ b/node_modules/npm-package-arg/lib/npa.js @@ -1,22 +1,24 @@ 'use strict' -module.exports = npa -module.exports.resolve = resolve -module.exports.toPurl = toPurl -module.exports.Result = Result -const { URL } = require('url') +const isWindows = process.platform === 'win32' + +const { URL } = require('node:url') +// We need to use path/win32 so that we get consistent results in tests, but this also means we need to manually convert backslashes to forward slashes when generating file: urls with paths. +const path = isWindows ? require('node:path/win32') : require('node:path') +const { homedir } = require('node:os') 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 isFileType = /[.](?:tgz|tar\.gz|tar)$/i +const isPortNumber = /:[0-9]+(\/|$)/i +const isWindowsFile = /^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/ +const isPosixFile = /^(?:[.]|~[/]|[/]|[a-zA-Z]:)/ +const defaultRegistry = 'https://registry.npmjs.org' function npa (arg, where) { let name @@ -30,13 +32,14 @@ function npa (arg, where) { return npa(arg.raw, where || arg.where) } } - const nameEndsAt = arg[0] === '@' ? arg.slice(1).indexOf('@') + 1 : arg.indexOf('@') + const nameEndsAt = arg.indexOf('@', 1) // Skip possible leading @ 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))) { + // eslint-disable-next-line max-len + } else if (!namePart.startsWith('@') && (hasSlashes.test(namePart) || isFileType.test(namePart))) { spec = arg } else if (nameEndsAt > 0) { name = namePart @@ -53,7 +56,25 @@ function npa (arg, where) { return resolve(name, spec, where, arg) } -const isFilespec = isWindows ? /^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/ : /^(?:[.]|~[/]|[/]|[a-zA-Z]:)/ +function isFileSpec (spec) { + if (!spec) { + return false + } + if (spec.toLowerCase().startsWith('file:')) { + return true + } + if (isWindows) { + return isWindowsFile.test(spec) + } + return isPosixFile.test(spec) +} + +function isAliasSpec (spec) { + if (!spec) { + return false + } + return spec.toLowerCase().startsWith('npm:') +} function resolve (name, spec, where, arg) { const res = new Result({ @@ -64,12 +85,16 @@ function resolve (name, spec, where, arg) { }) if (name) { - res.setName(name) + res.name = name + } + + if (!where) { + where = process.cwd() } - if (spec && (isFilespec.test(spec) || /^file:/i.test(spec))) { + if (isFileSpec(spec)) { return fromFile(res, where) - } else if (spec && /^npm:/i.test(spec)) { + } else if (isAliasSpec(spec)) { return fromAlias(res, where) } @@ -81,15 +106,13 @@ function resolve (name, spec, where, arg) { return fromHostedGit(res, hosted) } else if (spec && isURL.test(spec)) { return fromURL(res) - } else if (spec && (hasSlashes.test(spec) || isFilename.test(spec))) { + } else if (spec && (hasSlashes.test(spec) || isFileType.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) @@ -127,60 +150,62 @@ function invalidPurlType (type, raw) { 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 +class Result { + constructor (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 } - 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 -} + // TODO move this to a getter/setter in a semver major + setName (name) { + const valid = validatePackageName(name) + if (!valid.validForOldPackages) { + throw invalidPackageName(name, valid, this.raw) + } -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 } - 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) + toString () { + 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 } - return full.length ? full.join('@') : this.raw -} -Result.prototype.toJSON = function () { - const result = Object.assign({}, this) - delete result.hosted - return result + toJSON () { + const result = Object.assign({}, this) + delete result.hosted + return result + } } // sets res.gitCommittish, res.gitRange, and res.gitSubdir @@ -227,25 +252,67 @@ function setGitAttrs (res, committish) { } } -function fromFile (res, where) { - if (!where) { - where = process.cwd() +// Taken from: EncodePathChars and lookup_table in src/node_url.cc +// url.pathToFileURL only returns absolute references. We can't use it to encode paths. +// encodeURI mangles windows paths. We can't use it to encode paths. +// Under the hood, url.pathToFileURL does a limited set of encoding, with an extra windows step, and then calls path.resolve. +// The encoding node does without path.resolve is not available outside of the source, so we are recreating it here. +const encodedPathChars = new Map([ + ['\0', '%00'], + ['\t', '%09'], + ['\n', '%0A'], + ['\r', '%0D'], + [' ', '%20'], + ['"', '%22'], + ['#', '%23'], + ['%', '%25'], + ['?', '%3F'], + ['[', '%5B'], + ['\\', isWindows ? '/' : '%5C'], + [']', '%5D'], + ['^', '%5E'], + ['|', '%7C'], + ['~', '%7E'], +]) + +function pathToFileURL (str) { + let result = '' + for (let i = 0; i < str.length; i++) { + result = `${result}${encodedPathChars.get(str[i]) ?? str[i]}` } - res.type = isFilename.test(res.rawSpec) ? 'file' : 'directory' + if (result.startsWith('file:')) { + return result + } + return `file:${result}` +} + +function fromFile (res, where) { + res.type = isFileType.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 rawSpec = pathToFileURL(res.rawSpec) + + if (rawSpec.startsWith('file:/')) { + // XXX backwards compatibility lack of compliance with RFC 8089 + + // turn file://path into file:/path + if (/^file:\/\/[^/]/.test(rawSpec)) { + rawSpec = `file:/${rawSpec.slice(5)}` + } + + // turn file:/../path into file:../path + // for 1 or 3 leading slashes (2 is already ruled out from handling file:// explicitly above) + if (/^\/{1,3}\.\.?(\/|$)/.test(rawSpec.slice(5))) { + rawSpec = rawSpec.replace(/^file:\/{1,3}/, 'file:') + } + } - let specUrl let resolvedUrl - const prefix = (!/^file:/.test(res.rawSpec) ? 'file:' : '') - const rawWithPrefix = prefix + res.rawSpec - let rawNoPrefix = rawWithPrefix.replace(/^file:/, '') + let specUrl try { - resolvedUrl = new URL(rawWithPrefix, `file://${path.resolve(where)}/`) - specUrl = new URL(rawWithPrefix) + // always put the '/' on "where", or else file:foo from /path/to/bar goes to /path/to/foo, when we want it to be /path/to/bar/foo + resolvedUrl = new URL(rawSpec, `${pathToFileURL(path.resolve(where))}/`) + specUrl = new URL(rawSpec) } catch (originalError) { const er = new Error('Invalid file: URL, must comply with RFC 8089') throw Object.assign(er, { @@ -256,24 +323,6 @@ function fromFile (res, where) { }) } - // 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) @@ -287,13 +336,21 @@ function fromFile (res, where) { if (/^\/~(\/|$)/.test(specPath)) { res.saveSpec = `file:${specPath.substr(1)}` resolvedPath = path.resolve(homedir(), specPath.substr(3)) - } else if (!path.isAbsolute(rawNoPrefix)) { + } else if (!path.isAbsolute(rawSpec.slice(5))) { res.saveSpec = `file:${path.relative(where, resolvedPath)}` } else { res.saveSpec = `file:${path.resolve(resolvedPath)}` } res.fetchSpec = path.resolve(where, resolvedPath) + // re-normalize the slashes in saveSpec due to node:path/win32 behavior in windows + res.saveSpec = res.saveSpec.split('\\').join('/') + // Ignoring because this only happens in windows + /* istanbul ignore next */ + if (res.saveSpec.startsWith('file://')) { + // normalization of \\win32\root paths can cause a double / which we don't want + res.saveSpec = `file:/${res.saveSpec.slice(7)}` + } return res } @@ -324,7 +381,9 @@ function fromURL (res) { // 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) - if (matched && !matched[1].match(/:[0-9]+\/?.*$/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] @@ -380,6 +439,10 @@ function fromAlias (res, where) { 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' @@ -409,3 +472,8 @@ function fromRegistry (res) { } return res } + +module.exports = npa +module.exports.resolve = resolve +module.exports.toPurl = toPurl +module.exports.Result = Result diff --git a/node_modules/npm-package-arg/package.json b/node_modules/npm-package-arg/package.json index c4cee1f928e89..692d59c75528e 100644 --- a/node_modules/npm-package-arg/package.json +++ b/node_modules/npm-package-arg/package.json @@ -1,6 +1,6 @@ { "name": "npm-package-arg", - "version": "11.0.2", + "version": "14.0.0", "description": "Parse the things that can be arguments to `npm install`", "main": "./lib/npa.js", "directories": { @@ -11,30 +11,31 @@ "lib/" ], "dependencies": { - "hosted-git-info": "^7.0.0", - "proc-log": "^4.0.0", + "hosted-git-info": "^10.1.0", + "proc-log": "^7.0.0", "semver": "^7.3.5", - "validate-npm-package-name": "^5.0.0" + "validate-npm-package-name": "^8.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.3", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.1.0", "tap": "^16.0.1" }, "scripts": { "test": "tap", "snap": "tap", "npmclilint": "npmcli-lint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", - "url": "https://github.com/npm/npm-package-arg.git" + "url": "git+https://github.com/npm/npm-package-arg.git" }, "author": "GitHub Inc.", "license": "ISC", @@ -43,10 +44,9 @@ }, "homepage": "https://github.com/npm/npm-package-arg", "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "tap": { - "branches": 97, "nyc-arg": [ "--exclude", "tap-snapshots/**" @@ -54,7 +54,7 @@ }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.3", + "version": "5.1.0", "publish": true } } diff --git a/node_modules/npm-packlist/lib/index.js b/node_modules/npm-packlist/lib/index.js index 985f11ee3f738..4ff84b796b7c3 100644 --- a/node_modules/npm-packlist/lib/index.js +++ b/node_modules/npm-packlist/lib/index.js @@ -1,11 +1,14 @@ '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') +const { globSync } = require('glob') +const { readFileSync: readFile } = require('node:fs') +const { basename, dirname, extname, join, relative, resolve, sep } = require('node:path') +const { log } = require('proc-log') // symbols used to represent synthetic rule sets const defaultRules = Symbol('npm-packlist.rules.default') +const globalRules = Symbol('npm-packlist.rules.global') const strictRules = Symbol('npm-packlist.rules.strict') // There may be others, but :?|<> are handled by node-tar @@ -82,20 +85,32 @@ class PackWalker extends IgnoreWalker { 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 || [ + // globalRules belongs on the root walker only. Child walkers reach it through + // parent.filterEntry, where package.json rules can still override it; reapplying + // globalRules at the child level would defeat that override. + ignoreFiles: opts?.ignoreFiles || (opts?.parent ? [ defaultRules, 'package.json', '.npmignore', '.gitignore', strictRules, - ], + ] : [ + defaultRules, + globalRules, + 'package.json', + '.npmignore', + '.gitignore', + strictRules, + ]), } super(options) + this.isPackage = options.isPackage this.seen = options.seen || new Set() this.tree = tree - this.requiredFiles = options.requiredFiles || [] + this.globalIgnoreFile = options.globalIgnoreFile || null + this.globalIgnoreRules = options.globalIgnoreRules || null const additionalDefaults = [] if (options.prefix && options.workspaces) { @@ -122,13 +137,34 @@ class PackWalker extends IgnoreWalker { // go ahead and inject the default rules now this.injectRules(defaultRules, [...defaults, ...additionalDefaults]) + // inject the global rules from the user's ignore file. positioned between + // defaultRules and package.json so an explicit entry in the package "files" + // field can still override. only the root walker carries globalRules in its + // ignoreFiles list; child walkers see global exclusions via parent.filterEntry, + // which is what lets the package.json `!/path/**` override win. + if (this.globalIgnoreRules === null && this.globalIgnoreFile) { + try { + this.globalIgnoreRules = readFile(this.globalIgnoreFile, { encoding: 'utf8' }) + } catch (err) { + // istanbul ignore next -- only ENOENT is expected here + if (err.code !== 'ENOENT') { + throw err + } + this.globalIgnoreRules = '' + } + } + if (this.globalIgnoreRules) { + this.injectRules(globalRules, [this.globalIgnoreRules]) + // istanbul ignore else -- globalIgnoreRules without a filename only happens when + // a caller pre-populates rules directly instead of going through globalIgnoreFile + if (this.globalIgnoreFile) { + log.silly('global-ignore-file', `applied rules from ${this.globalIgnoreFile}`) + } + } + 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}`), - ]) + // if this instance is not a package, then place some strict default rules + this.injectRules(strictRules, [...strictDefaults]) } } @@ -168,6 +204,11 @@ class PackWalker extends IgnoreWalker { } else if (this.ignoreRules['.npmignore']) { // .npmignore means no .gitignore this.ignoreRules['.gitignore'] = null + } else if (this.ignoreRules['.gitignore'] && !this.ignoreRules['.npmignore'] && !this.parent) { + log.warn( + 'gitignore-fallback', + 'No .npmignore file found, using .gitignore for file exclusion. Consider creating a .npmignore file to explicitly control published files.' + ) } return super.filterEntries() @@ -227,15 +268,6 @@ class PackWalker extends IgnoreWalker { 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), } } @@ -273,6 +305,7 @@ class PackWalker extends IgnoreWalker { browser, files, main, + patchedDependencies, } = this.tree.package // rules in these arrays are inverted since they are patterns we want to _not_ ignore @@ -288,45 +321,62 @@ class PackWalker extends IgnoreWalker { '/node_modules', '.npmrc', '/package-lock.json', + '/npm-shrinkwrap.json', '/yarn.lock', '/pnpm-lock.yaml', + '/bun.lockb', + '/bun.lock', + '/.npm-extension.mjs', + '/.npm-extension.cjs', ] // 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) + for (const entry of files) { + const isNegation = entry.startsWith('!') + // normalize: strip leading `!`s, `./`, a single leading `/`, and trailing slashes. + // trailing slashes confuse glob; the leading forms are equivalent to their stripped versions for glob expansion. + const pattern = (isNegation ? entry.replace(/^!+/, '') : entry) + .replace(/^\.?\//, '') + .replace(/\/+$/, '') + if (!pattern) { + continue } - if (file.endsWith('/*')) { - file += '*' - } - const inverse = `!${file}` + + // expand the entry as a glob against the package root. + // literal paths (e.g. `lib`, `lib/foo.js`) are valid globs and resolve to themselves; + // patterns (e.g. `dist-*`, `**/*.js`) resolve to all matching entries; + // typos and non-existent entries resolve to nothing. + let matches = [] 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}/**`) + matches = globSync(pattern, { cwd: this.path, withFileTypes: true, dot: true }) + } catch { + // unparseable globs produce no matches and drop silently. + // (Pre-v11 instead fell through to push the raw entry as an ignore-walk pattern rule; we deliberately don't preserve that.) + } + + // a positive entry produces `!path` rules (un-ignore from the surrounding `*` deny-all); a negation produces `path` rules (re-ignore them). + // directory matches expand to also include their contents; this is documented `files[]` behavior, not a glob hack. + const prefix = isNegation ? '' : '!' + for (const match of matches) { + const rel = match.relativePosix() + // istanbul ignore next -- defensive: glob with withFileTypes returns the cwd as an entry with an empty relative path; skip it. + if (!rel) { + continue + } + if (match.isDirectory()) { + ignores.push(`${prefix}/${rel}`) + ignores.push(`${prefix}/${rel}/**`) + continue + } + // istanbul ignore else -- non-file-non-dir matches (sockets, fifos, broken symlinks) drop silently. + if (match.isFile()) { + ignores.push(`${prefix}/${rel}`) } - // 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 + // we prepend a '*' to exclude everything, followed by our inverted file rules which now mean to include those this.injectRules('package.json', ['*', ...ignores]) } @@ -347,6 +397,32 @@ class PackWalker extends IgnoreWalker { } } + // patch files declared in patchedDependencies are project-local fixes and must never ship. + // patchedDependencies is root-only state, so this applies only to the package being packed. + // each declared patch file is force-excluded even when it was added via "files". + // only the exact files are excluded, never their directory, so a shared dir keeps its other contents. + if (this.tree.isProjectRoot && patchedDependencies && typeof patchedDependencies === 'object') { + for (const patchPath of Object.values(patchedDependencies)) { + if (typeof patchPath !== 'string') { + continue + } + const rel = normalizePath(patchPath).replace(/^\.?\//, '').replace(/\/+$/, '') + // skip absolute paths or paths that escape the package root, which are never packed anyway + if (!rel || rel.startsWith('/') || rel === '..' || rel.startsWith('../') || rel.includes('/../')) { + continue + } + // warn when a "files" entry pulled the patch file in, either directly or via its directory + const parentGlob = `!/${normalizePath(dirname(rel))}/**` + if (files && (ignores.includes(`!/${rel}`) || ignores.includes(parentGlob))) { + log.warn( + 'patched-dependencies', + `excluding "${rel}" from the package tarball: patch files in patchedDependencies must not be published` + ) + } + strict.push(`/${rel}`) + } + } + // and now we add all of the strict rules to our synthetic file this.injectRules(strictRules, strict, callback) } diff --git a/node_modules/ignore-walk/LICENSE b/node_modules/npm-packlist/node_modules/ignore-walk/LICENSE similarity index 100% rename from node_modules/ignore-walk/LICENSE rename to node_modules/npm-packlist/node_modules/ignore-walk/LICENSE diff --git a/node_modules/ignore-walk/lib/index.js b/node_modules/npm-packlist/node_modules/ignore-walk/lib/index.js similarity index 100% rename from node_modules/ignore-walk/lib/index.js rename to node_modules/npm-packlist/node_modules/ignore-walk/lib/index.js diff --git a/node_modules/npm-packlist/node_modules/ignore-walk/package.json b/node_modules/npm-packlist/node_modules/ignore-walk/package.json new file mode 100644 index 0000000000000..0b11aa50e828c --- /dev/null +++ b/node_modules/npm-packlist/node_modules/ignore-walk/package.json @@ -0,0 +1,64 @@ +{ + "name": "ignore-walk", + "version": "9.0.0", + "description": "Nested/recursive `.gitignore`/`.npmignore` parsing and filtering.", + "main": "lib/index.js", + "devDependencies": { + "@npmcli/eslint-config": "^5.0.0", + "@npmcli/template-oss": "5.0.0", + "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": "^10.0.3" + }, + "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": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "5.0.0", + "content": "scripts/template-oss", + "publish": "true" + } +} diff --git a/node_modules/npm-packlist/package.json b/node_modules/npm-packlist/package.json index 8c3a16e741ad3..ae5c4fc596a56 100644 --- a/node_modules/npm-packlist/package.json +++ b/node_modules/npm-packlist/package.json @@ -1,13 +1,15 @@ { "name": "npm-packlist", - "version": "8.0.2", + "version": "11.3.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": "^6.0.4" + "glob": "^13.0.6", + "ignore-walk": "^9.0.0", + "proc-log": "^7.0.0" }, "author": "GitHub Inc.", "license": "ISC", @@ -16,9 +18,9 @@ "lib/" ], "devDependencies": { - "@npmcli/arborist": "^6.0.0 || ^6.0.0-pre.0", - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.2", + "@npmcli/arborist": "^9.0.0", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.1", "mutate-fs": "^2.1.1", "tap": "^16.0.1" }, @@ -27,16 +29,16 @@ "posttest": "npm run lint", "snap": "tap", "postsnap": "npm run lintfix --", - "eslint": "eslint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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": "https://github.com/npm/npm-packlist.git" + "url": "git+https://github.com/npm/npm-packlist.git" }, "tap": { "test-env": [ @@ -51,11 +53,12 @@ ] }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.2", - "publish": true + "version": "5.1.1", + "publish": true, + "updateNpm": false } } diff --git a/node_modules/npm-pick-manifest/lib/index.js b/node_modules/npm-pick-manifest/lib/index.js index 82807971844bf..985c78df7a9bf 100644 --- a/node_modules/npm-pick-manifest/lib/index.js +++ b/node_modules/npm-pick-manifest/lib/index.js @@ -93,13 +93,10 @@ const pickManifest = (packument, wanted, opts) => { 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 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 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 { @@ -117,9 +114,7 @@ const pickManifest = (packument, wanted, opts) => { // 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. + // 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 })) && diff --git a/node_modules/npm-pick-manifest/node_modules/npm-normalize-package-bin/LICENSE b/node_modules/npm-pick-manifest/node_modules/npm-normalize-package-bin/LICENSE new file mode 100644 index 0000000000000..19cec97b18468 --- /dev/null +++ b/node_modules/npm-pick-manifest/node_modules/npm-normalize-package-bin/LICENSE @@ -0,0 +1,15 @@ +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. diff --git a/node_modules/npm-pick-manifest/node_modules/npm-normalize-package-bin/lib/index.js b/node_modules/npm-pick-manifest/node_modules/npm-normalize-package-bin/lib/index.js new file mode 100644 index 0000000000000..3cb8478cf6e2f --- /dev/null +++ b/node_modules/npm-pick-manifest/node_modules/npm-normalize-package-bin/lib/index.js @@ -0,0 +1,64 @@ +// 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 diff --git a/node_modules/npm-pick-manifest/node_modules/npm-normalize-package-bin/package.json b/node_modules/npm-pick-manifest/node_modules/npm-normalize-package-bin/package.json new file mode 100644 index 0000000000000..1d0d821b7a2ce --- /dev/null +++ b/node_modules/npm-pick-manifest/node_modules/npm-normalize-package-bin/package.json @@ -0,0 +1,42 @@ +{ + "name": "npm-normalize-package-bin", + "version": "6.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": "node --test './test/**/*.js'", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "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}\"", + "test:node20": "node --test test", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'" + }, + "devDependencies": { + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0" + }, + "files": [ + "bin/", + "lib/" + ], + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "5.0.0", + "publish": "true", + "testRunner": "node:test", + "latestCiVersion": 24 + } +} diff --git a/node_modules/npm-pick-manifest/package.json b/node_modules/npm-pick-manifest/package.json index 4c0dd50630def..766b0b8d43a02 100644 --- a/node_modules/npm-pick-manifest/package.json +++ b/node_modules/npm-pick-manifest/package.json @@ -1,6 +1,6 @@ { "name": "npm-pick-manifest", - "version": "9.1.0", + "version": "12.0.0", "description": "Resolves a matching manifest from a package metadata document according to standard npm semver resolution rules.", "main": "./lib", "files": [ @@ -9,13 +9,16 @@ ], "scripts": { "coverage": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "test": "tap", + "lint": "npm run eslint", + "test": "node --test './test/**/*.js'", "posttest": "npm run lint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "template-oss-apply": "template-oss-apply --force" + "lintfix": "npm run eslint -- --fix", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test:node20": "node --test test", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'" }, "repository": { "type": "git", @@ -29,29 +32,23 @@ "author": "GitHub Inc.", "license": "ISC", "dependencies": { - "npm-install-checks": "^6.0.0", - "npm-normalize-package-bin": "^3.0.0", - "npm-package-arg": "^11.0.0", + "npm-install-checks": "^9.0.0", + "npm-normalize-package-bin": "^6.0.0", + "npm-package-arg": "^14.0.0", "semver": "^7.3.5" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.1" - }, - "tap": { - "check-coverage": true, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.1.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true + "version": "5.1.0", + "publish": true, + "testRunner": "node:test", + "latestCiVersion": 24 } } diff --git a/node_modules/npm-profile/lib/index.js b/node_modules/npm-profile/lib/index.js index 69e4e49b1fcdd..0a8a706f44a01 100644 --- a/node_modules/npm-profile/lib/index.js +++ b/node_modules/npm-profile/lib/index.js @@ -18,24 +18,6 @@ const login = async (opener, prompter, opts = {}) => { } } -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, {}) @@ -49,6 +31,33 @@ const isValidUrl = u => { } } +// npm's web-login response names the canonical npmjs registry in `doneUrl`, which a proxy/mirror forwards verbatim. +// The poll would then hit npmjs.org instead of the proxy that holds the session, so rewrite only that npmjs host to the configured registry origin, preserving the path prefix and query string. +// Any other done host is left untouched, since a non-npmjs canonical host cannot be inferred here and may be served intentionally. +const CANONICAL_REGISTRY_HOST = 'registry.npmjs.org' + +// doneUrl is already validated by isValidUrl and registry is the origin a prior +// POST /-/v1/login succeeded against, so both parse cleanly here. +const replaceDoneUrlOrigin = (doneUrl, registry) => { + if (!registry) { + return doneUrl + } + const done = new URL(doneUrl) + if (done.hostname !== CANONICAL_REGISTRY_HOST) { + return doneUrl + } + const reg = new URL(registry) + done.protocol = reg.protocol + done.host = reg.host + const prefix = reg.pathname.replace(/\/$/, '') + if (prefix && prefix !== '/' && + done.pathname !== prefix && + !done.pathname.startsWith(prefix + '/')) { + done.pathname = prefix + done.pathname + } + return done.href +} + const webAuth = async (opener, opts, body) => { try { const res = await fetch('/-/v1/login', { @@ -65,7 +74,7 @@ const webAuth = async (opener, opts, body) => { throw new WebLoginInvalidResponse('POST', res, content) } - return await webAuthOpener(opener, loginUrl, doneUrl, opts) + return await webAuthOpener(opener, loginUrl, replaceDoneUrlOrigin(doneUrl, opts.registry), opts) } catch (er) { if ((er.statusCode >= 400 && er.statusCode <= 499) || er.statusCode === 500) { throw new WebLoginNotSupported('POST', { @@ -119,7 +128,7 @@ const webAuthCheckLogin = async (doneUrl, opts, { signal } = {}) => { if (res.status === 202) { const retry = +res.headers.get('retry-after') * 1000 if (retry > 0) { - await timers.setTimeout(retry, null, { ref: false, signal }) + await timers.setTimeout(retry, null, { signal }) } return webAuthCheckLogin(doneUrl, opts, { signal }) } @@ -139,25 +148,6 @@ const putCouch = async (path, username, body, opts) => { 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}`, @@ -262,12 +252,9 @@ class WebLoginNotSupported extends HttpErrorBase { } module.exports = { - adduserCouch, loginCouch, - adduserWeb, loginWeb, login, - adduser, get, set, listTokens, diff --git a/node_modules/npm-profile/package.json b/node_modules/npm-profile/package.json index ff93911716fa7..9b4e5a24b57a0 100644 --- a/node_modules/npm-profile/package.json +++ b/node_modules/npm-profile/package.json @@ -1,37 +1,38 @@ { "name": "npm-profile", - "version": "10.0.0", + "version": "13.0.1", "description": "Library for updating an npmjs.com profile", "keywords": [], "author": "GitHub Inc.", "license": "ISC", "dependencies": { - "npm-registry-fetch": "^17.0.1", - "proc-log": "^4.0.0" + "npm-registry-fetch": "^20.0.0", + "proc-log": "^7.0.0" }, "main": "./lib/index.js", "repository": { "type": "git", - "url": "https://github.com/npm/npm-profile.git" + "url": "git+https://github.com/npm/npm-profile.git" }, "files": [ "bin/", "lib/" ], "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.4", - "nock": "^13.2.4", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.1", + "nock": "^13.5.6", "tap": "^16.0.1" }, "scripts": { "posttest": "npm run lint", "test": "tap", "snap": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "template-oss-apply": "template-oss-apply --force" + "lintfix": "npm run eslint -- --fix", + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "check-coverage": true, @@ -41,11 +42,11 @@ ] }, "engines": { - "node": ">=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.4", + "version": "5.1.1", "publish": true } } diff --git a/node_modules/npm-registry-fetch/lib/check-response.js b/node_modules/npm-registry-fetch/lib/check-response.js index 65eea2963b0b4..2f183082ab2ce 100644 --- a/node_modules/npm-registry-fetch/lib/check-response.js +++ b/node_modules/npm-registry-fetch/lib/check-response.js @@ -48,10 +48,18 @@ function logRequest (method, res, startTime) { const cacheStr = cacheStatus ? ` (cache ${cacheStatus})` : '' const urlStr = cleanUrl(res.url) - log.http( - 'fetch', - `${method.toUpperCase()} ${res.status} ${urlStr} ${elapsedTime}ms${attemptStr}${cacheStr}` - ) + // 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) { diff --git a/node_modules/npm-registry-fetch/lib/errors.js b/node_modules/npm-registry-fetch/lib/errors.js index 5bf6b012a24ef..1b828825efa65 100644 --- a/node_modules/npm-registry-fetch/lib/errors.js +++ b/node_modules/npm-registry-fetch/lib/errors.js @@ -38,13 +38,18 @@ class HttpErrorBase extends Error { class HttpErrorGeneral extends HttpErrorBase { constructor (method, res, body, spec) { super(method, res, body, spec) + let detail = '' + if (body && typeof body === 'object' && !Buffer.isBuffer(body)) { + const text = body.error || body.message || JSON.stringify(body) + if (text && text !== '{}') { + detail = ' - ' + text + } + } this.message = `${res.status} ${res.statusText} - ${ this.method.toUpperCase() } ${ this.spec || this.uri - }${ - (body && body.error) ? ' - ' + body.error : '' - }` + }${detail}` } } diff --git a/node_modules/npm-registry-fetch/lib/index.js b/node_modules/npm-registry-fetch/lib/index.js index 898c8125bfe0e..91d450f245f05 100644 --- a/node_modules/npm-registry-fetch/lib/index.js +++ b/node_modules/npm-registry-fetch/lib/index.js @@ -130,6 +130,7 @@ function regFetch (uri, /* istanbul ignore next */ opts_ = {}) { }, strictSSL: opts.strictSSL, timeout: opts.timeout || 30 * 1000, + signal: opts.signal, }).then(res => checkResponse({ method, uri, diff --git a/node_modules/npm-registry-fetch/node_modules/minipass-fetch/LICENSE b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/LICENSE new file mode 100644 index 0000000000000..3c3410cdc12ee --- /dev/null +++ b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/LICENSE @@ -0,0 +1,28 @@ +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 diff --git a/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/abort-error.js b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/abort-error.js new file mode 100644 index 0000000000000..b18f643269e37 --- /dev/null +++ b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/abort-error.js @@ -0,0 +1,17 @@ +'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 diff --git a/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/blob.js b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/blob.js new file mode 100644 index 0000000000000..121b1730102e7 --- /dev/null +++ b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/blob.js @@ -0,0 +1,97 @@ +'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 diff --git a/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/body.js b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/body.js new file mode 100644 index 0000000000000..f38ee807ca287 --- /dev/null +++ b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/body.js @@ -0,0 +1,360 @@ +'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 'iconv-lite' +let decode +try { + decode = require('iconv-lite').decode +} 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 () { + /* istanbul ignore if */ + if (typeof decode !== 'function') { + throw new Error('The package `iconv-lite` must be installed to use the textConverted() function') + } + 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) => { + 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 diff --git a/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/headers.js b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/headers.js new file mode 100644 index 0000000000000..dd6e854d5ba39 --- /dev/null +++ b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/headers.js @@ -0,0 +1,267 @@ +'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 diff --git a/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/index.js b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/index.js new file mode 100644 index 0000000000000..f0f4bb66dbb67 --- /dev/null +++ b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/index.js @@ -0,0 +1,376 @@ +'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 + res.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 diff --git a/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/request.js b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/request.js new file mode 100644 index 0000000000000..054439e669910 --- /dev/null +++ b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/request.js @@ -0,0 +1,282 @@ +'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 }, +}) diff --git a/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/response.js b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/response.js new file mode 100644 index 0000000000000..54cb52db3594a --- /dev/null +++ b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/lib/response.js @@ -0,0 +1,90 @@ +'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 }, +}) diff --git a/node_modules/npm-registry-fetch/node_modules/minipass-fetch/package.json b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/package.json new file mode 100644 index 0000000000000..9b64fa5be8be2 --- /dev/null +++ b/node_modules/npm-registry-fetch/node_modules/minipass-fetch/package.json @@ -0,0 +1,70 @@ +{ + "name": "minipass-fetch", + "version": "6.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": "5.0.0", + "@ungap/url-search-params": "^0.2.2", + "abort-controller": "^3.0.0", + "abortcontroller-polyfill": "~1.7.3", + "form-data": "^4.0.0", + "iconv-lite": "^0.7.2", + "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": "^2.0.0", + "minizlib": "^3.0.1" + }, + "optionalDependencies": { + "iconv-lite": "^0.7.2" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/npm/minipass-fetch.git" + }, + "keywords": [ + "fetch", + "minipass", + "node-fetch", + "window.fetch" + ], + "files": [ + "bin/", + "lib/" + ], + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "5.0.0", + "publish": "true" + } +} diff --git a/node_modules/npm-registry-fetch/package.json b/node_modules/npm-registry-fetch/package.json index 07ea620d15317..12fc0fcae48f0 100644 --- a/node_modules/npm-registry-fetch/package.json +++ b/node_modules/npm-registry-fetch/package.json @@ -1,6 +1,6 @@ { "name": "npm-registry-fetch", - "version": "17.1.0", + "version": "20.0.1", "description": "Fetch-based http client for use with npm registry APIs", "main": "lib", "files": [ @@ -8,9 +8,9 @@ "lib/" ], "scripts": { - "eslint": "eslint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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", @@ -31,22 +31,22 @@ "author": "GitHub Inc.", "license": "ISC", "dependencies": { - "@npmcli/redact": "^2.0.0", + "@npmcli/redact": "^5.0.0", "jsonparse": "^1.3.1", - "make-fetch-happen": "^13.0.0", + "make-fetch-happen": "^16.0.0", "minipass": "^7.0.2", - "minipass-fetch": "^3.0.0", - "minizlib": "^2.1.2", - "npm-package-arg": "^11.0.0", - "proc-log": "^4.0.0" + "minipass-fetch": "^6.0.0", + "minizlib": "^3.0.1", + "npm-package-arg": "^14.0.0", + "proc-log": "^7.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "cacache": "^18.0.0", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.0", + "cacache": "^21.0.0", "nock": "^13.2.4", "require-inject": "^1.4.4", - "ssri": "^10.0.0", + "ssri": "^14.0.0", "tap": "^16.0.1" }, "tap": { @@ -58,11 +58,11 @@ ] }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.0", "publish": "true" } } diff --git a/node_modules/npm-user-validate/package.json b/node_modules/npm-user-validate/package.json index 15a1305356ef3..d18f7ffb14944 100644 --- a/node_modules/npm-user-validate/package.json +++ b/node_modules/npm-user-validate/package.json @@ -1,21 +1,23 @@ { "name": "npm-user-validate", - "version": "2.0.1", + "version": "5.0.0", "description": "User validations for npm", "main": "lib/index.js", "devDependencies": { - "@npmcli/eslint-config": "^4.0.1", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.3.2" + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0" }, "scripts": { - "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test": "node --test './test/**/*.js'", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" + "lintfix": "npm run eslint -- --fix", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'", + "test:node20": "node --test test" }, "repository": { "type": "git", @@ -33,17 +35,13 @@ "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] + "version": "5.0.0", + "publish": true, + "testRunner": "node:test", + "latestCiVersion": 24 } } diff --git a/node_modules/p-map/index.js b/node_modules/p-map/index.js index c11a28512a473..f713b9bf363b0 100644 --- a/node_modules/p-map/index.js +++ b/node_modules/p-map/index.js @@ -1,49 +1,107 @@ -'use strict'; -const AggregateError = require('aggregate-error'); - -module.exports = async ( +export default async function pMap( iterable, mapper, { - concurrency = Infinity, - stopOnError = true - } = {} -) => { - return new Promise((resolve, reject) => { + 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 === Infinity) && concurrency >= 1)) { + 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 iterator = iterable[Symbol.iterator](); + 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 next = () => { - if (isRejected) { + 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 = iterator.next(); + 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) { - if (!stopOnError && errors.length !== 0) { - reject(new AggregateError(errors)); - } else { + 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; @@ -51,31 +109,175 @@ module.exports = async ( resolvingCount++; + // Intentionally detached (async () => { try { const element = await nextItem.value; - result[index] = await mapper(element, index); + + 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--; - next(); + await next(); } catch (error) { if (stopOnError) { - isRejected = true; reject(error); } else { errors.push(error); resolvingCount--; - next(); + + // 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); + } } } })(); }; - for (let i = 0; i < concurrency; i++) { - next(); + // 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) { - 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 pendingPromisesCount = 0; + let isDone = false; + let index = 0; + + function trySpawn() { + if (isDone || !(pendingPromisesCount < concurrency && promises.length < backpressure)) { + return; + } + + pendingPromisesCount++; + + const promise = (async () => { + const {done, value} = await iterator.next(); + + if (done) { + pendingPromisesCount--; + return {done: true}; + } + + // Spawn if still below concurrency and backpressure limit + trySpawn(); + + try { + const returnValue = await mapper(await value, index++); + + pendingPromisesCount--; + + 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) { + pendingPromisesCount--; + 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'); diff --git a/node_modules/p-map/package.json b/node_modules/p-map/package.json index 042b1af553f2d..6401a2a6a51a9 100644 --- a/node_modules/p-map/package.json +++ b/node_modules/p-map/package.json @@ -1,6 +1,6 @@ { "name": "p-map", - "version": "4.0.0", + "version": "7.0.4", "description": "Map over promises concurrently", "license": "MIT", "repository": "sindresorhus/p-map", @@ -10,8 +10,14 @@ "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, + "type": "module", + "exports": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "sideEffects": false, "engines": { - "node": ">=10" + "node": ">=18" }, "scripts": { "test": "xo && ava && tsd" @@ -38,16 +44,14 @@ "parallel", "bluebird" ], - "dependencies": { - "aggregate-error": "^3.0.0" - }, "devDependencies": { - "ava": "^2.2.0", - "delay": "^4.1.0", - "in-range": "^2.0.0", - "random-int": "^2.0.0", - "time-span": "^3.1.0", - "tsd": "^0.7.4", - "xo": "^0.27.2" + "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" } } diff --git a/node_modules/package-json-from-dist/dist/commonjs/index.js b/node_modules/package-json-from-dist/dist/commonjs/index.js deleted file mode 100644 index 5cff210d855cb..0000000000000 --- a/node_modules/package-json-from-dist/dist/commonjs/index.js +++ /dev/null @@ -1,124 +0,0 @@ -"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 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); - const pkgName = pkgDir.startsWith('@') ? - pkgDir.split(node_path_1.sep).slice(0, 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 \ No newline at end of file diff --git a/node_modules/package-json-from-dist/dist/esm/index.js b/node_modules/package-json-from-dist/dist/esm/index.js deleted file mode 100644 index 0627645f9c35a..0000000000000 --- a/node_modules/package-json-from-dist/dist/esm/index.js +++ /dev/null @@ -1,119 +0,0 @@ -import { readFileSync } from 'node:fs'; -import { dirname, resolve, sep } from 'node:path'; -import { fileURLToPath } from 'node:url'; -const NM = `${sep}node_modules${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); - const pkgName = pkgDir.startsWith('@') ? - pkgDir.split(sep).slice(0, 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 \ No newline at end of file diff --git a/node_modules/package-json-from-dist/package.json b/node_modules/package-json-from-dist/package.json deleted file mode 100644 index 2d5526e87b7fa..0000000000000 --- a/node_modules/package-json-from-dist/package.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "name": "package-json-from-dist", - "version": "1.0.0", - "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 . --loglevel warn --ignore-path ../../.prettierignore --cache", - "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" -} diff --git a/node_modules/pacote/lib/dir.js b/node_modules/pacote/lib/dir.js index f3229b34e463a..f1d416fcfab0a 100644 --- a/node_modules/pacote/lib/dir.js +++ b/node_modules/pacote/lib/dir.js @@ -1,8 +1,11 @@ -const { resolve } = require('node:path') +const { resolve, join } = require('node:path') +const { mkdtemp, writeFile, rm } = require('node:fs/promises') +const { tmpdir } = require('node:os') const packlist = require('npm-packlist') const runScript = require('@npmcli/run-script') const tar = require('tar') const { Minipass } = require('minipass') +const PackageJson = require('@npmcli/package-json') const Fetcher = require('./fetcher.js') const FileFetcher = require('./file.js') const _ = require('./util/protected.js') @@ -32,6 +35,9 @@ class DirFetcher extends Fetcher { 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, @@ -39,6 +45,8 @@ class DirFetcher extends Fetcher { 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, @@ -61,7 +69,7 @@ class DirFetcher extends Fetcher { stream.resolved = this.resolved stream.integrity = this.integrity - const { prefix, workspaces } = this.opts + const { prefix, workspaces, globalIgnoreFile } = this.opts // run the prepare script, get the list of files, and tar it up // pipe to the stream, and proxy errors the chain. @@ -71,14 +79,66 @@ class DirFetcher extends Fetcher { const arb = new this.Arborist({ path: this.resolved }) this.tree = await arb.loadActual() } - return packlist(this.tree, { path: this.resolved, prefix, workspaces }) + return packlist(this.tree, { path: this.resolved, prefix, workspaces, globalIgnoreFile }) + }) + .then(async files => { + const { options, cleanup } = await this.#tarOptions() + const source = tar.c(options, files) + // the strip temp file must outlive content consumption, so clean up once the stream is done + source.once('end', cleanup) + source.once('error', cleanup) + return source.on('error', er => stream.emit('error', er)).pipe(stream) }) - .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 } + // Build the tar create options. + // When the packed package.json declares patchedDependencies, redirect it to a stripped copy so project-local patches never ship. + // Non-patched packs are unchanged. + async #tarOptions () { + const options = tarCreateOptions(this.package) + + // read package.json from disk after prepare so the strip reflects the actually-packed manifest. + const pkgJson = await PackageJson.load(this.resolved) + if (!('patchedDependencies' in pkgJson.content)) { + return { options, cleanup: () => {} } + } + + // serialize the package.json minus patchedDependencies, preserving its indent and newline. + // JSON.stringify ignores the indent and newline symbols @npmcli/package-json attaches to content. + delete pkgJson.content.patchedDependencies + const { content } = pkgJson + const indent = content[Symbol.for('indent')] + const newline = content[Symbol.for('newline')] + const stripped = `${JSON.stringify(content, null, indent)}\n`.replace(/\n/g, newline) + + // write the stripped copy to a temp dir, removing it if the write itself fails. + const dir = await mkdtemp(join(tmpdir(), 'pacote-pack-')) + const strippedPath = join(dir, 'package.json') + try { + await writeFile(strippedPath, stripped) + } catch (er) { + /* istanbul ignore next - writing to a freshly created temp dir is not deterministically failable */ + await rm(dir, { recursive: true, force: true }) + /* istanbul ignore next */ + throw er + } + const size = Buffer.byteLength(stripped) + + // point only the top-level package.json entry at the stripped copy; every other file is untouched. + // onWriteEntry runs before the tar header and the file's hardlink check, so size and nlink here are honored. + options.onWriteEntry = (entry) => { + if (entry.path === 'package.json') { + entry.absolute = strippedPath + entry.stat.size = size + entry.stat.nlink = 1 + } + } + + return { options, cleanup: () => rm(dir, { recursive: true, force: true }) } + } + manifest () { if (this.package) { return Promise.resolve(this.package) diff --git a/node_modules/pacote/lib/fetcher.js b/node_modules/pacote/lib/fetcher.js index cc2c2db70c697..20c0d67548a7d 100644 --- a/node_modules/pacote/lib/fetcher.js +++ b/node_modules/pacote/lib/fetcher.js @@ -10,7 +10,7 @@ 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 { promiseRetry } = require('@gar/promise-retry') const ssri = require('ssri') const tar = require('tar') const { Minipass } = require('minipass') @@ -118,6 +118,10 @@ class FetcherBase { // we need the actual things, not just the lockfile '--no-package-lock-only', '--no-dry-run', + // override npm_config_global from the parent process: this inner + // `npm install` is preparing deps inside a tmp git clone, and it + // must reify into that clone's cwd, never the outer global prefix. + '--global=false', ] } @@ -188,7 +192,15 @@ class FetcherBase { // private // Note: cacache will raise a EINTEGRITY error if the integrity doesn't match #tarballFromCache () { - return cacache.get.stream.byDigest(this.cache, this.integrity, this.opts) + 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] () { @@ -311,7 +323,7 @@ class FetcherBase { this.spec }. Extracting by manifest.`) } - return this.resolve().then(() => retry(tryAgain => + return this.resolve().then(() => promiseRetry(tryAgain => streamHandler(this.#istream(this[_.tarballFromResolved]())) .catch(streamErr => { // Most likely data integrity. A cache ENOENT error is unlikely @@ -461,26 +473,48 @@ const FileFetcher = require('./file.js') const DirFetcher = require('./dir.js') const RemoteFetcher = require('./remote.js') +// possible values for allow: 'all', 'root', 'none' +const canUse = ({ allow = 'all', isRoot = false, allowType, spec }) => { + if (allow === 'all') { + return true + } + if (allow !== 'none' && isRoot) { + return true + } + throw Object.assign( + new Error(`Fetching${allow === 'root' ? ' non-root' : ''} packages of type "${allowType}" have been disabled`), + { + code: `EALLOW${allowType.toUpperCase()}`, + package: spec.toString(), + } + ) +} + // 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': + canUse({ allow: opts.allowGit, isRoot: opts._isRoot, allowType: 'git', spec }) return new GitFetcher(spec, opts) case 'remote': + canUse({ allow: opts.allowRemote, isRoot: opts._isRoot, allowType: 'remote', spec }) return new RemoteFetcher(spec, opts) case 'version': case 'range': case 'tag': case 'alias': + canUse({ allow: opts.allowRegistry, isRoot: opts._isRoot, allowType: 'registry', spec }) return new RegistryFetcher(spec.subSpec || spec, opts) case 'file': + canUse({ allow: opts.allowFile, isRoot: opts._isRoot, allowType: 'file', spec }) return new FileFetcher(spec, opts) case 'directory': + canUse({ allow: opts.allowDirectory, isRoot: opts._isRoot, allowType: 'directory', spec }) return new DirFetcher(spec, opts) default: diff --git a/node_modules/pacote/lib/git.js b/node_modules/pacote/lib/git.js index 077193a86f026..198540ab8d35c 100644 --- a/node_modules/pacote/lib/git.js +++ b/node_modules/pacote/lib/git.js @@ -12,19 +12,27 @@ 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}$/ +const hashre = /^[a-f0-9]{40,64}$/ // 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.sshurl && !(h.https && (h.auth || h.default === 'https')) && 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+') +const checkoutError = (expected, found) => { + const err = new Error(`Commit mismatch: expected SHA ${expected} and cloned HEAD ${found}`) + err.code = 'EGITCHECKOUT' + err.sha = expected + err.head = found + return err +} + class GitFetcher extends Fetcher { constructor (spec, opts) { super(spec, opts) @@ -163,6 +171,11 @@ class GitFetcher extends Fetcher { return } + // honor ignoreScripts: spawning `npm install` here would run lifecycle scripts (install, preinstall, postinstall, prepare) from the cloned repo, defeating the caller's explicit opt-out. + if (this.opts.ignoreScripts) { + 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. @@ -245,9 +258,12 @@ class GitFetcher extends Fetcher { 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/)) { + }).extract(tmp).then(() => handler(`${tmp}${this.spec.gitSubdir || ''}`), er => { + // fall back to clone if the tarball download fails due to an + // HTTP error or if the response is not a valid tarball (e.g. + // a hosted provider returning an HTML sign-in page with 200) + if ((typeof er.statusCode === 'number' && er.statusCode >= 400) || + /^TAR_/.test(er.code)) { return this.#clone(handler, false) } else { throw er @@ -259,11 +275,15 @@ class GitFetcher extends Fetcher { h ? this.#cloneHosted(ref, tmp) : this.#cloneRepo(this.spec.fetchSpec, ref, tmp) ) + // if we already have a resolved sha ensure it doesn't change + if (this.resolvedSha && this.resolvedSha !== sha) { + throw checkoutError(this.resolvedSha, sha) + } this.resolvedSha = sha if (!this.resolved) { await this.#addGitSha(sha) } - return handler(tmp) + return handler(`${tmp}${this.spec.gitSubdir || ''}`) }) } diff --git a/node_modules/pacote/lib/registry.js b/node_modules/pacote/lib/registry.js index 1ecf4ee177349..f50b27956dbeb 100644 --- a/node_modules/pacote/lib/registry.js +++ b/node_modules/pacote/lib/registry.js @@ -229,7 +229,7 @@ class RegistryFetcher extends Fetcher { 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 attestationsUrl = new URL(attestationsPath, this.registry).href const res = await fetch(attestationsUrl, { ...this.opts, // disable integrity check for attestations json payload, we check the @@ -256,7 +256,10 @@ class RegistryFetcher extends Fetcher { const attestationKeyIds = bundles.map((b) => b.keyid).filter((k) => !!k) const attestationRegistryKeys = (this.registryKeys || []) .filter(key => attestationKeyIds.includes(key.keyid)) - if (!attestationRegistryKeys.length) { + // Only require registry keys when there are keyed attestations. + // Keyless (Sigstore/Fulcio) attestations embed their signing + // certificate in the bundle and don't need registry keys. + if (attestationKeyIds.length > 0 && !attestationRegistryKeys.length) { throw Object.assign(new Error( `${mani._id} has attestations but no corresponding public key(s) can be found` ), { code: 'EMISSINGSIGNATUREKEY' }) @@ -339,6 +342,7 @@ class RegistryFetcher extends Fetcher { } } mani._attestations = dist.attestations + mani._attestationBundles = attestations } else { mani._attestations = dist.attestations } diff --git a/node_modules/pacote/lib/util/add-git-sha.js b/node_modules/pacote/lib/util/add-git-sha.js index 843fe5b600caf..39893b4759887 100644 --- a/node_modules/pacote/lib/util/add-git-sha.js +++ b/node_modules/pacote/lib/util/add-git-sha.js @@ -3,12 +3,15 @@ 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) + const base = h.https && (h.auth || h.default === 'https') ? 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}` + // strip the committish with indexOf/slice to avoid a regexp redos + const hashIndex = spec.rawSpec.indexOf('#') + const base = hashIndex === -1 ? spec.rawSpec : spec.rawSpec.slice(0, hashIndex) + return `${base}#${sha}` } } diff --git a/node_modules/@sigstore/bundle/LICENSE b/node_modules/pacote/node_modules/@sigstore/bundle/LICENSE similarity index 100% rename from node_modules/@sigstore/bundle/LICENSE rename to node_modules/pacote/node_modules/@sigstore/bundle/LICENSE diff --git a/node_modules/@sigstore/bundle/dist/build.js b/node_modules/pacote/node_modules/@sigstore/bundle/dist/build.js similarity index 87% rename from node_modules/@sigstore/bundle/dist/build.js rename to node_modules/pacote/node_modules/@sigstore/bundle/dist/build.js index 65c71b100ad58..ade736407554c 100644 --- a/node_modules/@sigstore/bundle/dist/build.js +++ b/node_modules/pacote/node_modules/@sigstore/bundle/dist/build.js @@ -1,6 +1,7 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.toDSSEBundle = exports.toMessageSignatureBundle = void 0; +exports.toMessageSignatureBundle = toMessageSignatureBundle; +exports.toDSSEBundle = toDSSEBundle; /* Copyright 2023 The Sigstore Authors. @@ -21,9 +22,9 @@ const bundle_1 = require("./bundle"); // Message signature bundle - $case: 'messageSignature' function toMessageSignatureBundle(options) { return { - mediaType: options.singleCertificate - ? bundle_1.BUNDLE_V03_MEDIA_TYPE - : bundle_1.BUNDLE_V02_MEDIA_TYPE, + mediaType: options.certificateChain + ? bundle_1.BUNDLE_V02_MEDIA_TYPE + : bundle_1.BUNDLE_V03_MEDIA_TYPE, content: { $case: 'messageSignature', messageSignature: { @@ -37,13 +38,12 @@ function toMessageSignatureBundle(options) { verificationMaterial: toVerificationMaterial(options), }; } -exports.toMessageSignatureBundle = toMessageSignatureBundle; // DSSE envelope bundle - $case: 'dsseEnvelope' function toDSSEBundle(options) { return { - mediaType: options.singleCertificate - ? bundle_1.BUNDLE_V03_MEDIA_TYPE - : bundle_1.BUNDLE_V02_MEDIA_TYPE, + mediaType: options.certificateChain + ? bundle_1.BUNDLE_V02_MEDIA_TYPE + : bundle_1.BUNDLE_V03_MEDIA_TYPE, content: { $case: 'dsseEnvelope', dsseEnvelope: toEnvelope(options), @@ -51,7 +51,6 @@ function toDSSEBundle(options) { verificationMaterial: toVerificationMaterial(options), }; } -exports.toDSSEBundle = toDSSEBundle; function toEnvelope(options) { return { payloadType: options.artifactType, @@ -75,13 +74,7 @@ function toVerificationMaterial(options) { } function toKeyContent(options) { if (options.certificate) { - if (options.singleCertificate) { - return { - $case: 'certificate', - certificate: { rawBytes: options.certificate }, - }; - } - else { + if (options.certificateChain) { return { $case: 'x509CertificateChain', x509CertificateChain: { @@ -89,6 +82,12 @@ function toKeyContent(options) { }, }; } + else { + return { + $case: 'certificate', + certificate: { rawBytes: options.certificate }, + }; + } } else { return { diff --git a/node_modules/pacote/node_modules/@sigstore/bundle/dist/bundle.js b/node_modules/pacote/node_modules/@sigstore/bundle/dist/bundle.js new file mode 100644 index 0000000000000..eb67a0ddc17bb --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/bundle/dist/bundle.js @@ -0,0 +1,24 @@ +"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'; +} diff --git a/node_modules/pacote/node_modules/@sigstore/bundle/dist/error.js b/node_modules/pacote/node_modules/@sigstore/bundle/dist/error.js new file mode 100644 index 0000000000000..c02ff06fc552f --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/bundle/dist/error.js @@ -0,0 +1,26 @@ +"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 { + fields; + constructor(message, fields) { + super(message); + this.fields = fields; + } +} +exports.ValidationError = ValidationError; diff --git a/node_modules/@sigstore/bundle/dist/index.js b/node_modules/pacote/node_modules/@sigstore/bundle/dist/index.js similarity index 100% rename from node_modules/@sigstore/bundle/dist/index.js rename to node_modules/pacote/node_modules/@sigstore/bundle/dist/index.js diff --git a/node_modules/@sigstore/bundle/dist/serialized.js b/node_modules/pacote/node_modules/@sigstore/bundle/dist/serialized.js similarity index 100% rename from node_modules/@sigstore/bundle/dist/serialized.js rename to node_modules/pacote/node_modules/@sigstore/bundle/dist/serialized.js diff --git a/node_modules/@sigstore/bundle/dist/utility.js b/node_modules/pacote/node_modules/@sigstore/bundle/dist/utility.js similarity index 100% rename from node_modules/@sigstore/bundle/dist/utility.js rename to node_modules/pacote/node_modules/@sigstore/bundle/dist/utility.js diff --git a/node_modules/@sigstore/bundle/dist/validate.js b/node_modules/pacote/node_modules/@sigstore/bundle/dist/validate.js similarity index 98% rename from node_modules/@sigstore/bundle/dist/validate.js rename to node_modules/pacote/node_modules/@sigstore/bundle/dist/validate.js index 67079cd1f680a..21b8b5ee293ba 100644 --- a/node_modules/@sigstore/bundle/dist/validate.js +++ b/node_modules/pacote/node_modules/@sigstore/bundle/dist/validate.js @@ -1,6 +1,10 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.assertBundleLatest = exports.assertBundleV02 = exports.isBundleV01 = exports.assertBundleV01 = exports.assertBundle = void 0; +exports.assertBundle = assertBundle; +exports.assertBundleV01 = assertBundleV01; +exports.isBundleV01 = isBundleV01; +exports.assertBundleV02 = assertBundleV02; +exports.assertBundleLatest = assertBundleLatest; /* Copyright 2023 The Sigstore Authors. @@ -27,7 +31,6 @@ function assertBundle(b) { throw new error_1.ValidationError('invalid bundle', invalidValues); } } -exports.assertBundle = assertBundle; // Asserts that the given bundle conforms to the v0.1 bundle format. function assertBundleV01(b) { const invalidValues = []; @@ -37,7 +40,6 @@ function assertBundleV01(b) { throw new error_1.ValidationError('invalid v0.1 bundle', invalidValues); } } -exports.assertBundleV01 = assertBundleV01; // Type guard to determine if Bundle is a v0.1 bundle. function isBundleV01(b) { try { @@ -48,7 +50,6 @@ function isBundleV01(b) { return false; } } -exports.isBundleV01 = isBundleV01; // Asserts that the given bundle conforms to the v0.2 bundle format. function assertBundleV02(b) { const invalidValues = []; @@ -58,7 +59,6 @@ function assertBundleV02(b) { throw new error_1.ValidationError('invalid v0.2 bundle', invalidValues); } } -exports.assertBundleV02 = assertBundleV02; // Asserts that the given bundle conforms to the newest (0.3) bundle format. function assertBundleLatest(b) { const invalidValues = []; @@ -69,7 +69,6 @@ function assertBundleLatest(b) { throw new error_1.ValidationError('invalid bundle', invalidValues); } } -exports.assertBundleLatest = assertBundleLatest; function validateBundleBase(b) { const invalidValues = []; // Media type validation @@ -192,6 +191,7 @@ function validateInclusionProof(b) { // 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'); } diff --git a/node_modules/pacote/node_modules/@sigstore/bundle/package.json b/node_modules/pacote/node_modules/@sigstore/bundle/package.json new file mode 100644 index 0000000000000..cb7650a8babc0 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/bundle/package.json @@ -0,0 +1,35 @@ +{ + "name": "@sigstore/bundle", + "version": "5.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.5.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } +} diff --git a/node_modules/@sigstore/core/LICENSE b/node_modules/pacote/node_modules/@sigstore/core/LICENSE similarity index 100% rename from node_modules/@sigstore/core/LICENSE rename to node_modules/pacote/node_modules/@sigstore/core/LICENSE diff --git a/node_modules/@sigstore/core/dist/asn1/error.js b/node_modules/pacote/node_modules/@sigstore/core/dist/asn1/error.js similarity index 100% rename from node_modules/@sigstore/core/dist/asn1/error.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/asn1/error.js diff --git a/node_modules/@sigstore/core/dist/asn1/index.js b/node_modules/pacote/node_modules/@sigstore/core/dist/asn1/index.js similarity index 100% rename from node_modules/@sigstore/core/dist/asn1/index.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/asn1/index.js diff --git a/node_modules/@sigstore/core/dist/asn1/length.js b/node_modules/pacote/node_modules/@sigstore/core/dist/asn1/length.js similarity index 97% rename from node_modules/@sigstore/core/dist/asn1/length.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/asn1/length.js index 36fdaf5b9777f..cb7ebf09dbefa 100644 --- a/node_modules/@sigstore/core/dist/asn1/length.js +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/asn1/length.js @@ -15,7 +15,8 @@ See the License for the specific language governing permissions and limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); -exports.encodeLength = exports.decodeLength = void 0; +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 @@ -44,7 +45,6 @@ function decodeLength(stream) { } return len; } -exports.decodeLength = decodeLength; // Translates the supplied value to a DER-encoded length. function encodeLength(len) { if (len < 128) { @@ -60,4 +60,3 @@ function encodeLength(len) { } return Buffer.from([0x80 | bytes.length, ...bytes]); } -exports.encodeLength = encodeLength; diff --git a/node_modules/@sigstore/core/dist/asn1/obj.js b/node_modules/pacote/node_modules/@sigstore/core/dist/asn1/obj.js similarity index 99% rename from node_modules/@sigstore/core/dist/asn1/obj.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/asn1/obj.js index 5f9ac9cdbc493..2dc90d6ac9b8d 100644 --- a/node_modules/@sigstore/core/dist/asn1/obj.js +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/asn1/obj.js @@ -22,6 +22,9 @@ const length_1 = require("./length"); const parse_1 = require("./parse"); const tag_1 = require("./tag"); class ASN1Obj { + tag; + subs; + value; constructor(tag, value, subs) { this.tag = tag; this.value = value; diff --git a/node_modules/pacote/node_modules/@sigstore/core/dist/asn1/parse.js b/node_modules/pacote/node_modules/@sigstore/core/dist/asn1/parse.js new file mode 100644 index 0000000000000..7fbb42632c60e --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/asn1/parse.js @@ -0,0 +1,124 @@ +"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; +} diff --git a/node_modules/@sigstore/core/dist/asn1/tag.js b/node_modules/pacote/node_modules/@sigstore/core/dist/asn1/tag.js similarity index 98% rename from node_modules/@sigstore/core/dist/asn1/tag.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/asn1/tag.js index 84dd938d049aa..ebb4dd562353f 100644 --- a/node_modules/@sigstore/core/dist/asn1/tag.js +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/asn1/tag.js @@ -37,6 +37,9 @@ const TAG_CLASS = { }; // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-tag-bytes class ASN1Tag { + number; + constructed; + class; constructor(enc) { // Bits 0 through 4 are the tag number this.number = enc & 0x1f; diff --git a/node_modules/@sigstore/core/dist/crypto.js b/node_modules/pacote/node_modules/@sigstore/core/dist/crypto.js similarity index 81% rename from node_modules/@sigstore/core/dist/crypto.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/crypto.js index dbe65b165d357..8d8110ee42347 100644 --- a/node_modules/@sigstore/core/dist/crypto.js +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/crypto.js @@ -3,7 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.bufferEqual = exports.verify = exports.hash = exports.digest = exports.createPublicKey = void 0; +exports.createPublicKey = createPublicKey; +exports.digest = digest; +exports.verify = verify; +exports.bufferEqual = bufferEqual; /* Copyright 2023 The Sigstore Authors. @@ -20,16 +23,23 @@ See the License for the specific language governing permissions and limitations under the License. */ const crypto_1 = __importDefault(require("crypto")); -const SHA256_ALGORITHM = 'sha256'; function createPublicKey(key, type = 'spki') { if (typeof key === 'string') { - return crypto_1.default.createPublicKey(key); + if (key.startsWith('-----')) { + return crypto_1.default.createPublicKey(key); + } + else { + return crypto_1.default.createPublicKey({ + key: Buffer.from(key, 'base64'), + format: 'der', + type: type, + }); + } } else { return crypto_1.default.createPublicKey({ key, format: 'der', type: type }); } } -exports.createPublicKey = createPublicKey; function digest(algorithm, ...data) { const hash = crypto_1.default.createHash(algorithm); for (const d of data) { @@ -37,16 +47,6 @@ function digest(algorithm, ...data) { } return hash.digest(); } -exports.digest = digest; -// TODO: deprecate this in favor of digest() -function hash(...data) { - const hash = crypto_1.default.createHash(SHA256_ALGORITHM); - for (const d of data) { - hash.update(d); - } - return hash.digest(); -} -exports.hash = hash; 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. @@ -58,7 +58,6 @@ function verify(data, key, signature, algorithm) { return false; } } -exports.verify = verify; function bufferEqual(a, b) { try { return crypto_1.default.timingSafeEqual(a, b); @@ -68,4 +67,3 @@ function bufferEqual(a, b) { return false; } } -exports.bufferEqual = bufferEqual; diff --git a/node_modules/pacote/node_modules/@sigstore/core/dist/dsse.js b/node_modules/pacote/node_modules/@sigstore/core/dist/dsse.js new file mode 100644 index 0000000000000..9dcc2649198c1 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/dsse.js @@ -0,0 +1,29 @@ +"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 typeBytes = Buffer.from(payloadType, 'utf-8'); + return Buffer.concat([ + Buffer.from(`${PAE_PREFIX} ${typeBytes.length} `, 'ascii'), + typeBytes, + Buffer.from(` ${payload.length} `, 'ascii'), + payload, + ]); +} diff --git a/node_modules/pacote/node_modules/@sigstore/core/dist/encoding.js b/node_modules/pacote/node_modules/@sigstore/core/dist/encoding.js new file mode 100644 index 0000000000000..7113af66db4c2 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/encoding.js @@ -0,0 +1,27 @@ +"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); +} diff --git a/node_modules/pacote/node_modules/@sigstore/core/dist/index.js b/node_modules/pacote/node_modules/@sigstore/core/dist/index.js new file mode 100644 index 0000000000000..49859d84db756 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/index.js @@ -0,0 +1,66 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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; } }); diff --git a/node_modules/pacote/node_modules/@sigstore/core/dist/json.js b/node_modules/pacote/node_modules/@sigstore/core/dist/json.js new file mode 100644 index 0000000000000..7808d033b98cc --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/json.js @@ -0,0 +1,60 @@ +"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; +} diff --git a/node_modules/pacote/node_modules/@sigstore/core/dist/oid.js b/node_modules/pacote/node_modules/@sigstore/core/dist/oid.js new file mode 100644 index 0000000000000..4438ac9bdca98 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/oid.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SHA2_HASH_ALGOS = exports.RSA_SIGNATURE_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.RSA_SIGNATURE_ALGOS = { + '1.2.840.113549.1.1.14': 'sha224', + '1.2.840.113549.1.1.11': 'sha256', + '1.2.840.113549.1.1.12': 'sha384', + '1.2.840.113549.1.1.13': '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', +}; diff --git a/node_modules/@sigstore/core/dist/pem.js b/node_modules/pacote/node_modules/@sigstore/core/dist/pem.js similarity index 97% rename from node_modules/@sigstore/core/dist/pem.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/pem.js index f35bc3835bbd1..f1241d28d586e 100644 --- a/node_modules/@sigstore/core/dist/pem.js +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/pem.js @@ -1,6 +1,7 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromDER = exports.toDER = void 0; +exports.toDER = toDER; +exports.fromDER = fromDER; /* Copyright 2023 The Sigstore Authors. @@ -28,7 +29,6 @@ function toDER(certificate) { }); return Buffer.from(der, 'base64'); } -exports.toDER = toDER; // 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. @@ -41,4 +41,3 @@ function fromDER(certificate, type = 'CERTIFICATE') { .join('\n') .concat('\n'); } -exports.fromDER = fromDER; diff --git a/node_modules/@sigstore/core/dist/rfc3161/error.js b/node_modules/pacote/node_modules/@sigstore/core/dist/rfc3161/error.js similarity index 100% rename from node_modules/@sigstore/core/dist/rfc3161/error.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/rfc3161/error.js diff --git a/node_modules/@sigstore/core/dist/rfc3161/index.js b/node_modules/pacote/node_modules/@sigstore/core/dist/rfc3161/index.js similarity index 100% rename from node_modules/@sigstore/core/dist/rfc3161/index.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/rfc3161/index.js diff --git a/node_modules/pacote/node_modules/@sigstore/core/dist/rfc3161/timestamp.js b/node_modules/pacote/node_modules/@sigstore/core/dist/rfc3161/timestamp.js new file mode 100644 index 0000000000000..a7034526ecbce --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/rfc3161/timestamp.js @@ -0,0 +1,212 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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 { + root; + 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; diff --git a/node_modules/pacote/node_modules/@sigstore/core/dist/rfc3161/tstinfo.js b/node_modules/pacote/node_modules/@sigstore/core/dist/rfc3161/tstinfo.js new file mode 100644 index 0000000000000..91213529b6605 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/rfc3161/tstinfo.js @@ -0,0 +1,72 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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 { + root; + 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; diff --git a/node_modules/@sigstore/core/dist/stream.js b/node_modules/pacote/node_modules/@sigstore/core/dist/stream.js similarity index 95% rename from node_modules/@sigstore/core/dist/stream.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/stream.js index 0a24f8582eb23..c69b3097a2dd2 100644 --- a/node_modules/@sigstore/core/dist/stream.js +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/stream.js @@ -19,14 +19,17 @@ limitations under the License. class StreamError extends Error { } class ByteStream { + static BLOCK_SIZE = 1024; + buf; + view; + start = 0; constructor(buffer) { - this.start = 0; if (buffer) { this.buf = buffer; this.view = Buffer.from(buffer); } else { - this.buf = new ArrayBuffer(0); + this.buf = Buffer.alloc(0); this.view = Buffer.from(this.buf); } } @@ -103,7 +106,7 @@ class ByteStream { } } realloc(size) { - const newArray = new ArrayBuffer(size); + const newArray = Buffer.alloc(size); const newView = Buffer.from(newArray); // Copy the old buffer into the new one newView.set(this.view); @@ -112,4 +115,3 @@ class ByteStream { } } exports.ByteStream = ByteStream; -ByteStream.BLOCK_SIZE = 1024; diff --git a/node_modules/@sigstore/core/dist/x509/cert.js b/node_modules/pacote/node_modules/@sigstore/core/dist/x509/cert.js similarity index 88% rename from node_modules/@sigstore/core/dist/x509/cert.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/x509/cert.js index 16c0c40d858d8..0e1126ba4a298 100644 --- a/node_modules/@sigstore/core/dist/x509/cert.js +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/x509/cert.js @@ -15,13 +15,23 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( }) : 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 __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); Object.defineProperty(exports, "__esModule", { value: true }); exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0; /* @@ -51,6 +61,7 @@ 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 { + root; constructor(asn1) { this.root = asn1; } @@ -89,6 +100,9 @@ class X509Certificate { } get signatureAlgorithm() { const oid = this.signatureAlgorithmObj.subs[0].toOID(); + if (oid_1.RSA_SIGNATURE_ALGOS[oid]) { + return oid_1.RSA_SIGNATURE_ALGOS[oid]; + } return oid_1.ECDSA_SIGNATURE_ALGOS[oid]; } get signatureValue() { @@ -97,13 +111,15 @@ class X509Certificate { } get subjectAltName() { const ext = this.extSubjectAltName; - return ext?.uri || ext?.rfc822Name; + 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]; - return extSeq?.subs || /* istanbul ignore next */ []; + /* istanbul ignore next */ + return extSeq?.subs || []; } get extKeyUsage() { const ext = this.findExtension(EXTENSION_OID_KEY_USAGE); @@ -134,9 +150,12 @@ class X509Certificate { get isCA() { const ca = this.extBasicConstraints?.isCA || false; // If the KeyUsage extension is present, keyCertSign must be set + /* istanbul ignore else */ if (this.extKeyUsage) { - ca && this.extKeyUsage.keyCertSign; + return ca && this.extKeyUsage.keyCertSign; } + // TODO: test coverage for this case + /* istanbul ignore next */ return ca; } extension(oid) { diff --git a/node_modules/@sigstore/core/dist/x509/ext.js b/node_modules/pacote/node_modules/@sigstore/core/dist/x509/ext.js similarity index 99% rename from node_modules/@sigstore/core/dist/x509/ext.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/x509/ext.js index 1d481261b0aa6..10f37fe256efe 100644 --- a/node_modules/@sigstore/core/dist/x509/ext.js +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/x509/ext.js @@ -5,6 +5,7 @@ const stream_1 = require("../stream"); const sct_1 = require("./sct"); // https://www.rfc-editor.org/rfc/rfc5280#section-4.1 class X509Extension { + root; constructor(asn1) { this.root = asn1; } diff --git a/node_modules/@sigstore/core/dist/x509/index.js b/node_modules/pacote/node_modules/@sigstore/core/dist/x509/index.js similarity index 100% rename from node_modules/@sigstore/core/dist/x509/index.js rename to node_modules/pacote/node_modules/@sigstore/core/dist/x509/index.js diff --git a/node_modules/pacote/node_modules/@sigstore/core/dist/x509/sct.js b/node_modules/pacote/node_modules/@sigstore/core/dist/x509/sct.js new file mode 100644 index 0000000000000..338e3478fd45e --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/core/dist/x509/sct.js @@ -0,0 +1,158 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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 { + version; + logID; + timestamp; + extensions; + hashAlgorithm; + signatureAlgorithm; + signature; + 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; diff --git a/node_modules/pacote/node_modules/@sigstore/core/package.json b/node_modules/pacote/node_modules/@sigstore/core/package.json new file mode 100644 index 0000000000000..e53a81c8ba290 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/core/package.json @@ -0,0 +1,31 @@ +{ + "name": "@sigstore/core", + "version": "4.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": "^22.22.2 || ^24.15.0 || >=26.0.0" + } +} diff --git a/node_modules/@sigstore/sign/LICENSE b/node_modules/pacote/node_modules/@sigstore/sign/LICENSE similarity index 100% rename from node_modules/@sigstore/sign/LICENSE rename to node_modules/pacote/node_modules/@sigstore/sign/LICENSE diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/base.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/base.js new file mode 100644 index 0000000000000..e231c663fffc1 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/base.js @@ -0,0 +1,52 @@ +"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 { + signer; + witnesses; + 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; + } +} diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/bundle.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/bundle.js new file mode 100644 index 0000000000000..34b1d12f2b44c --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/bundle.js @@ -0,0 +1,81 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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, + }); +} diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/dsse.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/dsse.js new file mode 100644 index 0000000000000..95c8d31c29fc3 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/dsse.js @@ -0,0 +1,47 @@ +"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 { + certificateChain; + 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 ?? '', + }; +} diff --git a/node_modules/@sigstore/sign/dist/bundler/index.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/index.js similarity index 100% rename from node_modules/@sigstore/sign/dist/bundler/index.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/index.js diff --git a/node_modules/@sigstore/sign/dist/bundler/message.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/message.js similarity index 100% rename from node_modules/@sigstore/sign/dist/bundler/message.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/bundler/message.js diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/config.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/config.js new file mode 100644 index 0000000000000..dcb2b240cec53 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/config.js @@ -0,0 +1,143 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bundleBuilderFromSigningConfig = bundleBuilderFromSigningConfig; +/* +Copyright 2025 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 dsse_1 = require("./bundler/dsse"); +const message_1 = require("./bundler/message"); +const signer_1 = require("./signer"); +const witness_1 = require("./witness"); +const MAX_CA_API_VERSION = 1; +const MAX_TLOG_API_VERSION = 2; +const MAX_TSA_API_VERSION = 1; +const DEFAULT_TIMEOUT = 5000; +const DEFAULT_REKORV2_TIMEOUT = 20000; +const DEFAULT_RETRY = { retries: 2 }; +// Creates a BundleBuilder based on the provided SigningConfig +function bundleBuilderFromSigningConfig(options) { + const { signingConfig, identityProvider, bundleType } = options; + const fetchOptions = options.fetchOptions || { + timeout: DEFAULT_TIMEOUT, + retry: DEFAULT_RETRY, + }; + const signer = fulcioSignerFromConfig(signingConfig, identityProvider, fetchOptions); + const witnesses = witnessesFromConfig(signingConfig, fetchOptions); + switch (bundleType) { + case 'messageSignature': + return new message_1.MessageSignatureBundleBuilder({ signer, witnesses }); + case 'dsseEnvelope': + return new dsse_1.DSSEBundleBuilder({ signer, witnesses }); + } +} +function fulcioSignerFromConfig(signingConfig, identityProvider, fetchOptions) { + const service = certAuthorityService(signingConfig); + return new signer_1.FulcioSigner({ + fulcioBaseURL: service.url, + identityProvider: identityProvider, + timeout: fetchOptions.timeout, + retry: fetchOptions.retry, + }); +} +function witnessesFromConfig(signingConfig, fetchOptions) { + const witnesses = []; + if (signingConfig.rekorTlogConfig) { + if (signingConfig.rekorTlogConfig.selector !== protobuf_specs_1.ServiceSelector.ANY) { + throw new Error('Unsupported Rekor TLog selector in signing configuration'); + } + const tlog = tlogService(signingConfig); + witnesses.push(new witness_1.RekorWitness({ + rekorBaseURL: tlog.url, + majorApiVersion: tlog.majorApiVersion, + retry: fetchOptions.retry, + timeout: + // Ensure Rekor V2 has at least a 20 second timeout + tlog.majorApiVersion === 1 + ? fetchOptions.timeout + : Math.min(fetchOptions.timeout || + /* istanbul ignore next */ DEFAULT_TIMEOUT, DEFAULT_REKORV2_TIMEOUT), + })); + } + if (signingConfig.tsaConfig) { + if (signingConfig.tsaConfig.selector !== protobuf_specs_1.ServiceSelector.ANY) { + throw new Error('Unsupported TSA selector in signing configuration'); + } + const tsa = tsaService(signingConfig); + witnesses.push(new witness_1.TSAWitness({ + tsaBaseURL: tsa.url, + retry: fetchOptions.retry, + timeout: fetchOptions.timeout, + })); + } + return witnesses; +} +// Returns the first valid CA service from the signing configuration +function certAuthorityService(signingConfig) { + const compatibleCAs = filterServicesByMaxAPIVersion(signingConfig.caUrls, MAX_CA_API_VERSION); + const sortedCAs = sortServicesByStartDate(compatibleCAs); + if (sortedCAs.length === 0) { + throw new Error('No valid CA services found in signing configuration'); + } + return sortedCAs[0]; +} +// Returns the first valid TLog service from the signing configuration +function tlogService(signingConfig) { + const compatibleTLogs = filterServicesByMaxAPIVersion(signingConfig.rekorTlogUrls, MAX_TLOG_API_VERSION); + const sortedTLogs = sortServicesByStartDate(compatibleTLogs); + if (sortedTLogs.length === 0) { + throw new Error('No valid TLogs found in signing configuration'); + } + return sortedTLogs[0]; +} +// Returns the first valid TSA service from the signing configuration +function tsaService(signingConfig) { + const compatibleTSAs = filterServicesByMaxAPIVersion(signingConfig.tsaUrls, MAX_TSA_API_VERSION); + const sortedTSAs = sortServicesByStartDate(compatibleTSAs); + if (sortedTSAs.length === 0) { + throw new Error('No valid TSAs found in signing configuration'); + } + return sortedTSAs[0]; +} +// Returns the services sorted by start date (most recent first), filtering out +// any services that have an end date in the past +function sortServicesByStartDate(services) { + const now = new Date(); + // Filter out any services that have an end date in the past + const validServices = services.filter((service) => { + // If there's no end date, the service is still valid + if (!service.validFor?.end) { + return true; + } + // Keep services whose end date is in the future or present + return service.validFor.end >= now; + }); + return validServices.sort((a, b) => { + /* istanbul ignore next */ + const aStart = a.validFor?.start?.getTime() ?? 0; + /* istanbul ignore next */ + const bStart = b.validFor?.start?.getTime() ?? 0; + // Sort descending (most recent first) + return bStart - aStart; + }); +} +// Returns a filtered list of services whose major API version is less than or +// equal to the specified version +function filterServicesByMaxAPIVersion(services, apiVersion) { + // Filter out any services with a major API version greater than the specified version + return services.filter((service) => { + return service.majorApiVersion <= apiVersion; + }); +} diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/error.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/error.js new file mode 100644 index 0000000000000..125522ac84b0e --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/error.js @@ -0,0 +1,41 @@ +"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 { + code; + cause; + 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, + }); +} diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/external/error.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/external/error.js new file mode 100644 index 0000000000000..fd00afa835da4 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/external/error.js @@ -0,0 +1,28 @@ +"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 { + statusCode; + location; + constructor({ status, message, location, }) { + super(`(${status}) ${message}`); + this.statusCode = status; + this.location = location; + } +} +exports.HTTPError = HTTPError; diff --git a/node_modules/@sigstore/sign/dist/external/fetch.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/external/fetch.js similarity index 91% rename from node_modules/@sigstore/sign/dist/external/fetch.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/external/fetch.js index b2d81bde7be16..9f65c8a7607fd 100644 --- a/node_modules/@sigstore/sign/dist/external/fetch.js +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/external/fetch.js @@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.fetchWithRetry = void 0; +exports.fetchWithRetry = fetchWithRetry; /* Copyright 2023 The Sigstore Authors. @@ -19,15 +19,15 @@ 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 promise_retry_1 = require("@gar/promise-retry"); 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) => { + return (0, promise_retry_1.promiseRetry)(async (retry, attemptNum) => { const method = options.method || 'POST'; const headers = { [HTTP2_HEADER_USER_AGENT]: util_1.ua.getUserAgent(), @@ -58,14 +58,13 @@ async function fetchWithRetry(url, options) { } }, retryOpts(options.retry)); } -exports.fetchWithRetry = fetchWithRetry; // 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); + 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 { diff --git a/node_modules/@sigstore/sign/dist/external/fulcio.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/external/fulcio.js similarity index 99% rename from node_modules/@sigstore/sign/dist/external/fulcio.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/external/fulcio.js index de6a1ad9f9e79..20904fc34e454 100644 --- a/node_modules/@sigstore/sign/dist/external/fulcio.js +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/external/fulcio.js @@ -21,6 +21,7 @@ const fetch_1 = require("./fetch"); * Fulcio API client. */ class Fulcio { + options; constructor(options) { this.options = options; } diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/external/rekor-v2.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/external/rekor-v2.js new file mode 100644 index 0000000000000..c35cb99c8fac8 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/external/rekor-v2.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RekorV2 = void 0; +/* +Copyright 2025 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"); +const protobuf_specs_1 = require("@sigstore/protobuf-specs"); +const v2_1 = require("@sigstore/protobuf-specs/rekor/v2"); +/** + * Rekor API client. + */ +class RekorV2 { + options; + constructor(options) { + this.options = options; + } + async createEntry(proposedEntry) { + const { baseURL, timeout, retry } = this.options; + const url = `${baseURL}/api/v2/log/entries`; + const response = await (0, fetch_1.fetchWithRetry)(url, { + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + }, + body: JSON.stringify(v2_1.CreateEntryRequest.toJSON(proposedEntry)), + timeout, + retry, + }); + return response.json().then((data) => protobuf_specs_1.TransparencyLogEntry.fromJSON(data)); + } +} +exports.RekorV2 = RekorV2; diff --git a/node_modules/@sigstore/sign/dist/external/rekor.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/external/rekor.js similarity index 99% rename from node_modules/@sigstore/sign/dist/external/rekor.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/external/rekor.js index bb59a126e032f..1a990d5fcea41 100644 --- a/node_modules/@sigstore/sign/dist/external/rekor.js +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/external/rekor.js @@ -21,6 +21,7 @@ const fetch_1 = require("./fetch"); * Rekor API client. */ class Rekor { + options; constructor(options) { this.options = options; } diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/external/tsa.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/external/tsa.js new file mode 100644 index 0000000000000..a15dcc6f3c4f0 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/external/tsa.js @@ -0,0 +1,44 @@ +"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 { + options; + constructor(options) { + this.options = options; + } + async createTimestamp(request) { + const { baseURL, timeout, retry } = this.options; + // Account for the fact that the TSA URL may already include the full + // path if the client was initalized from a `SigningConfig` service entry + // (which always uses the full URL). + const url = new URL(baseURL).pathname === '/' + ? `${baseURL}/api/v1/timestamp` + : baseURL; + 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; diff --git a/node_modules/@sigstore/sign/dist/identity/ci.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/identity/ci.js similarity index 99% rename from node_modules/@sigstore/sign/dist/identity/ci.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/identity/ci.js index d79133952b605..318ef01b68e3e 100644 --- a/node_modules/@sigstore/sign/dist/identity/ci.js +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/identity/ci.js @@ -28,6 +28,7 @@ const providers = [getGHAToken, getEnv]; * one that resolves. */ class CIContextProvider { + audience; /* istanbul ignore next */ constructor(audience = 'sigstore') { this.audience = audience; diff --git a/node_modules/@sigstore/sign/dist/identity/index.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/identity/index.js similarity index 100% rename from node_modules/@sigstore/sign/dist/identity/index.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/identity/index.js diff --git a/node_modules/@sigstore/sign/dist/identity/provider.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/identity/provider.js similarity index 100% rename from node_modules/@sigstore/sign/dist/identity/provider.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/identity/provider.js diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/index.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/index.js new file mode 100644 index 0000000000000..02fae0589e508 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/index.js @@ -0,0 +1,19 @@ +"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.bundleBuilderFromSigningConfig = 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 config_1 = require("./config"); +Object.defineProperty(exports, "bundleBuilderFromSigningConfig", { enumerable: true, get: function () { return config_1.bundleBuilderFromSigningConfig; } }); +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; } }); diff --git a/node_modules/@sigstore/sign/dist/signer/fulcio/ca.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/signer/fulcio/ca.js similarity index 96% rename from node_modules/@sigstore/sign/dist/signer/fulcio/ca.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/signer/fulcio/ca.js index 81b421eabadb2..5919631473436 100644 --- a/node_modules/@sigstore/sign/dist/signer/fulcio/ca.js +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/signer/fulcio/ca.js @@ -19,6 +19,7 @@ limitations under the License. const error_1 = require("../../error"); const fulcio_1 = require("../../external/fulcio"); class CAClient { + fulcio; constructor(options) { this.fulcio = new fulcio_1.Fulcio({ baseURL: options.fulcioBaseURL, @@ -35,7 +36,6 @@ class CAClient { const cert = resp.signedCertificateEmbeddedSct ? resp.signedCertificateEmbeddedSct : resp.signedCertificateDetachedSct; - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return cert.chain.certificates; } catch (err) { diff --git a/node_modules/@sigstore/sign/dist/signer/fulcio/ephemeral.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/signer/fulcio/ephemeral.js similarity index 77% rename from node_modules/@sigstore/sign/dist/signer/fulcio/ephemeral.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/signer/fulcio/ephemeral.js index 481aa5c3579a2..fe63d31071881 100644 --- a/node_modules/@sigstore/sign/dist/signer/fulcio/ephemeral.js +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/signer/fulcio/ephemeral.js @@ -1,7 +1,4 @@ "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; /* @@ -19,23 +16,24 @@ 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 crypto_1 = 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 { + keypair; constructor() { - this.keypair = crypto_1.default.generateKeyPairSync(EC_KEYPAIR_TYPE, { + this.keypair = (0, crypto_1.generateKeyPairSync)(EC_KEYPAIR_TYPE, { namedCurve: P256_CURVE, }); } async sign(data) { - const signature = crypto_1.default.sign(null, data, this.keypair.privateKey); + const signature = (0, crypto_1.sign)('sha256', data, this.keypair.privateKey); const publicKey = this.keypair.publicKey .export({ format: 'pem', type: 'spki' }) - .toString('ascii'); + .toString(); return { signature: signature, key: { $case: 'publicKey', publicKey }, diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/signer/fulcio/index.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/signer/fulcio/index.js new file mode 100644 index 0000000000000..6df16a83af778 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/signer/fulcio/index.js @@ -0,0 +1,90 @@ +"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 { + ca; + identityProvider; + keyHolder; + 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; diff --git a/node_modules/@sigstore/sign/dist/signer/index.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/signer/index.js similarity index 100% rename from node_modules/@sigstore/sign/dist/signer/index.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/signer/index.js diff --git a/node_modules/@sigstore/sign/dist/signer/signer.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/signer/signer.js similarity index 100% rename from node_modules/@sigstore/sign/dist/signer/signer.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/signer/signer.js diff --git a/node_modules/@sigstore/sign/dist/types/fetch.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/types/fetch.js similarity index 100% rename from node_modules/@sigstore/sign/dist/types/fetch.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/types/fetch.js diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/util/index.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/util/index.js new file mode 100644 index 0000000000000..436630cfbbf19 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/util/index.js @@ -0,0 +1,59 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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")); diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/util/oidc.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/util/oidc.js new file mode 100644 index 0000000000000..a9a3b10d3f61a --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/util/oidc.js @@ -0,0 +1,35 @@ +"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])); + if (payload.email) { + if (!payload.email_verified) { + throw new Error('JWT email not verified by issuer'); + } + return payload.email; + } + if (payload.sub) { + return payload.sub; + } + else { + throw new Error('JWT subject not found'); + } +} diff --git a/node_modules/@sigstore/sign/dist/util/ua.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/util/ua.js similarity index 95% rename from node_modules/@sigstore/sign/dist/util/ua.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/util/ua.js index c142330eb8338..b15ff2070fb9f 100644 --- a/node_modules/@sigstore/sign/dist/util/ua.js +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/util/ua.js @@ -23,7 +23,6 @@ const os_1 = __importDefault(require("os")); // Format User-Agent: / () // source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent const getUserAgent = () => { - // eslint-disable-next-line @typescript-eslint/no-var-requires const packageVersion = require('../../package.json').version; const nodeVersion = process.version; const platformName = os_1.default.platform(); diff --git a/node_modules/@sigstore/sign/dist/witness/index.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/index.js similarity index 100% rename from node_modules/@sigstore/sign/dist/witness/index.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/witness/index.js diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tlog/client.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tlog/client.js new file mode 100644 index 0000000000000..8d13c45124e0b --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tlog/client.js @@ -0,0 +1,92 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TLogV2Client = exports.TLogClient = void 0; +/* +Copyright 2025 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"); +const rekor_v2_1 = require("../../external/rekor-v2"); +class TLogClient { + rekor; + fetchOnConflict; + 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); +} +class TLogV2Client { + rekor; + constructor(options) { + this.rekor = new rekor_v2_1.RekorV2({ + baseURL: options.rekorBaseURL, + retry: options.retry, + timeout: options.timeout, + }); + } + async createEntry(createEntryRequest) { + let entry; + try { + entry = await this.rekor.createEntry(createEntryRequest); + } + catch (err) { + (0, error_1.internalError)(err, 'TLOG_CREATE_ENTRY_ERROR', 'error creating tlog entry'); + } + if (entry.logId === undefined || entry.kindVersion === undefined) { + (0, error_1.internalError)(new Error('invalid tlog entry'), 'TLOG_CREATE_ENTRY_ERROR', 'error creating tlog entry'); + } + return { + ...entry, + logId: entry.logId, + kindVersion: entry.kindVersion, + }; + } +} +exports.TLogV2Client = TLogV2Client; diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tlog/entry.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tlog/entry.js new file mode 100644 index 0000000000000..0563406b5d875 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tlog/entry.js @@ -0,0 +1,197 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toProposedEntry = toProposedEntry; +exports.toCreateEntryRequest = toCreateEntryRequest; +/* +Copyright 2025 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 protobuf_specs_1 = require("@sigstore/protobuf-specs"); +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'); +} +function toCreateEntryRequest(content, publicKey) { + switch (content.$case) { + case 'dsseEnvelope': + return toCreateEntryRequestDSSE(content.dsseEnvelope, publicKey); + case 'messageSignature': + return toCreateEntryRequestMessageSignature(content.messageSignature, publicKey); + } +} +function toCreateEntryRequestDSSE(envelope, publicKey) { + return { + spec: { + $case: 'dsseRequestV002', + dsseRequestV002: { + envelope: envelope, + verifiers: [ + { + // TODO: We need to add support of passing the key details in the + // signature bundle. For now we're hardcoding the key details here. + keyDetails: protobuf_specs_1.PublicKeyDetails.PKIX_ECDSA_P256_SHA_256, + verifier: { + $case: 'x509Certificate', + x509Certificate: { + rawBytes: util_1.pem.toDER(publicKey), + }, + }, + }, + ], + }, + }, + }; +} +function toCreateEntryRequestMessageSignature(messageSignature, publicKey) { + return { + spec: { + $case: 'hashedRekordRequestV002', + hashedRekordRequestV002: { + digest: messageSignature.messageDigest.digest, + signature: { + content: messageSignature.signature, + verifier: { + // TODO: We need to add support of passing the key details in the + // signature bundle. For now we're hardcoding the key details here. + keyDetails: protobuf_specs_1.PublicKeyDetails.PKIX_ECDSA_P256_SHA_256, + verifier: { + $case: 'x509Certificate', + x509Certificate: { + rawBytes: util_1.pem.toDER(publicKey), + }, + }, + }, + }, + }, + }, + }; +} diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tlog/index.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tlog/index.js new file mode 100644 index 0000000000000..5a2e71a1c2911 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tlog/index.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0; +/* +Copyright 2025 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 { + tlogV1; + tlogV2; + entryType; + majorApiVersion; + constructor(options) { + this.entryType = options.entryType; + this.majorApiVersion = options.majorApiVersion || 1; + this.tlogV1 = new client_1.TLogClient({ + ...options, + rekorBaseURL: options.rekorBaseURL || /* istanbul ignore next */ exports.DEFAULT_REKOR_URL, + }); + this.tlogV2 = new client_1.TLogV2Client({ + ...options, + rekorBaseURL: options.rekorBaseURL || /* istanbul ignore next */ exports.DEFAULT_REKOR_URL, + }); + } + async testify(content, publicKey) { + let tlogEntry; + if (this.majorApiVersion === 2) { + const request = (0, entry_1.toCreateEntryRequest)(content, publicKey); + tlogEntry = await this.tlogV2.createEntry(request); + } + else { + const proposedEntry = (0, entry_1.toProposedEntry)(content, publicKey, this.entryType); + const entry = await this.tlogV1.createEntry(proposedEntry); + tlogEntry = toTransparencyLogEntry(entry); + } + return { tlogEntries: [tlogEntry] }; + } +} +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 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, + }, + }; +} diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tsa/client.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tsa/client.js new file mode 100644 index 0000000000000..97bfb5b883e3a --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tsa/client.js @@ -0,0 +1,47 @@ +"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 { + tsa; + 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; diff --git a/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tsa/index.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tsa/index.js new file mode 100644 index 0000000000000..07a34b46cf113 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/tsa/index.js @@ -0,0 +1,45 @@ +"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 { + tsa; + 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; + } +} diff --git a/node_modules/@sigstore/sign/dist/witness/witness.js b/node_modules/pacote/node_modules/@sigstore/sign/dist/witness/witness.js similarity index 100% rename from node_modules/@sigstore/sign/dist/witness/witness.js rename to node_modules/pacote/node_modules/@sigstore/sign/dist/witness/witness.js diff --git a/node_modules/pacote/node_modules/@sigstore/sign/package.json b/node_modules/pacote/node_modules/@sigstore/sign/package.json new file mode 100644 index 0000000000000..353f2e9c9acaf --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/sign/package.json @@ -0,0 +1,45 @@ +{ + "name": "@sigstore/sign", + "version": "5.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.13.0", + "@sigstore/rekor-types": "^5.0.0", + "@types/make-fetch-happen": "^10.0.4" + }, + "dependencies": { + "@gar/promise-retry": "^1.0.2", + "@sigstore/bundle": "^5.0.0", + "@sigstore/core": "^4.0.0", + "@sigstore/protobuf-specs": "^0.5.0", + "make-fetch-happen": "^16.0.0", + "proc-log": "^7.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } +} diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/bundle/dsse.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/bundle/dsse.js new file mode 100644 index 0000000000000..7ee255401b177 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/bundle/dsse.js @@ -0,0 +1,44 @@ +"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 { + env; + 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; diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/bundle/index.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/bundle/index.js new file mode 100644 index 0000000000000..cba2a65704c95 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/bundle/index.js @@ -0,0 +1,59 @@ +"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) { + if (entry.integratedTime && entry.integratedTime !== '0') { + timestamps.push({ + $case: 'transparency-log', + tlogEntry: entry, + }); + } + } + for (const ts of timestampVerificationData?.rfc3161Timestamps ?? []) { + timestamps.push({ + $case: 'timestamp-authority', + timestamp: core_1.RFC3161Timestamp.parse(Buffer.from(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(Buffer.from(bundle.verificationMaterial.content.x509CertificateChain + .certificates[0].rawBytes)), + }; + case 'certificate': + return { + $case: 'certificate', + certificate: core_1.X509Certificate.parse(Buffer.from(bundle.verificationMaterial.content.certificate.rawBytes)), + }; + } +} diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/bundle/message.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/bundle/message.js new file mode 100644 index 0000000000000..13cb5c27a02ac --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/bundle/message.js @@ -0,0 +1,54 @@ +"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"); +const protobuf_specs_1 = require("@sigstore/protobuf-specs"); +// Map from the Sigstore protobuf HashAlgorithm enum to +// the string values used by the Node.js crypto module. +const HASH_ALGORITHM_MAP = { + [protobuf_specs_1.HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED]: 'sha256', + [protobuf_specs_1.HashAlgorithm.SHA2_256]: 'sha256', + [protobuf_specs_1.HashAlgorithm.SHA2_384]: 'sha384', + [protobuf_specs_1.HashAlgorithm.SHA2_512]: 'sha512', + [protobuf_specs_1.HashAlgorithm.SHA3_256]: 'sha3-256', + [protobuf_specs_1.HashAlgorithm.SHA3_384]: 'sha3-384', +}; +class MessageSignatureContent { + signature; + messageDigest; + artifact; + hashAlgorithm; + constructor(messageSignature, artifact) { + this.signature = messageSignature.signature; + this.messageDigest = messageSignature.messageDigest.digest; + this.artifact = artifact; + this.hashAlgorithm = + HASH_ALGORITHM_MAP[messageSignature.messageDigest.algorithm] ?? + /* istanbul ignore next */ 'sha256'; + } + 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, this.hashAlgorithm); + } +} +exports.MessageSignatureContent = MessageSignatureContent; diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/error.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/error.js new file mode 100644 index 0000000000000..e6d72c2335618 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/error.js @@ -0,0 +1,34 @@ +"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 { + code; + cause; /* eslint-disable-line @typescript-eslint/no-explicit-any */ + 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; diff --git a/node_modules/@sigstore/verify/dist/index.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/index.js similarity index 100% rename from node_modules/@sigstore/verify/dist/index.js rename to node_modules/pacote/node_modules/@sigstore/verify/dist/index.js diff --git a/node_modules/@sigstore/verify/dist/key/certificate.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/key/certificate.js similarity index 92% rename from node_modules/@sigstore/verify/dist/key/certificate.js rename to node_modules/pacote/node_modules/@sigstore/verify/dist/key/certificate.js index c9140dd98d58a..a5611c6824bda 100644 --- a/node_modules/@sigstore/verify/dist/key/certificate.js +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/key/certificate.js @@ -1,15 +1,13 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.CertificateChainVerifier = exports.verifyCertificateChain = void 0; +exports.CertificateChainVerifier = void 0; +exports.verifyCertificateChain = verifyCertificateChain; const error_1 = require("../error"); const trust_1 = require("../trust"); -function verifyCertificateChain(leaf, certificateAuthorities) { +function verifyCertificateChain(timestamp, 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, - }); + // timestamp + const cas = (0, trust_1.filterCertAuthorities)(certificateAuthorities, timestamp); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ let error; for (const ca of cas) { @@ -17,6 +15,7 @@ function verifyCertificateChain(leaf, certificateAuthorities) { const verifier = new CertificateChainVerifier({ trustedCerts: ca.certChain, untrustedCert: leaf, + timestamp, }); return verifier.verify(); } @@ -32,8 +31,11 @@ function verifyCertificateChain(leaf, certificateAuthorities) { cause: error, }); } -exports.verifyCertificateChain = verifyCertificateChain; class CertificateChainVerifier { + untrustedCert; + trustedCerts; + localCerts; + timestamp; constructor(opts) { this.untrustedCert = opts.untrustedCert; this.trustedCerts = opts.trustedCerts; @@ -41,12 +43,20 @@ class CertificateChainVerifier { ...opts.trustedCerts, opts.untrustedCert, ]); + this.timestamp = opts.timestamp; } verify() { // Construct certificate path from leaf to root const certificatePath = this.sort(); // Perform validation checks on each certificate in the path this.checkPath(certificatePath); + const validForDate = certificatePath.every((cert) => cert.validForDate(this.timestamp)); + if (!validForDate) { + throw new error_1.VerificationError({ + code: 'CERTIFICATE_ERROR', + message: 'certificate is not valid or expired at the specified date', + }); + } // Return verified certificate path return certificatePath; } @@ -117,6 +127,7 @@ class CertificateChainVerifier { // or issuer/subject. Potential issuers are added to the result array. this.localCerts.forEach((possibleIssuer) => { if (keyIdentifier) { + /* istanbul ignore else */ if (possibleIssuer.extSubjectKeyID) { if (possibleIssuer.extSubjectKeyID.keyIdentifier.equals(keyIdentifier)) { issuers.push(possibleIssuer); diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/key/index.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/key/index.js new file mode 100644 index 0000000000000..880ad04bd235d --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/key/index.js @@ -0,0 +1,75 @@ +"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 + let path = []; + timestamps.forEach((timestamp) => { + path = (0, certificate_1.verifyCertificateChain)(timestamp, leaf, trustMaterial.certificateAuthorities); + }); + 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 oids = cert.extensions.map((ext) => { + const oid = ext.subs[0].toOID(); + return { + oid: { id: oid.split('.').map(Number) }, + value: ext.subs[ext.subs.length - 1].value, + }; + }); + const identity = { + extensions: { issuer }, + subjectAlternativeName: cert.subjectAltName, + oids, + }; + return { + key: core_1.crypto.createPublicKey(cert.publicKey), + identity, + }; +} diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/key/sct.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/key/sct.js new file mode 100644 index 0000000000000..8eca48738096e --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/key/sct.js @@ -0,0 +1,78 @@ +"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; + }); +} diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/policy.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/policy.js new file mode 100644 index 0000000000000..b08d083a296fb --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/policy.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifySubjectAlternativeName = verifySubjectAlternativeName; +exports.verifyExtensions = verifyExtensions; +exports.verifyOIDs = verifyOIDs; +const error_1 = require("./error"); +// Verifies that the signer's SAN matches the policy identity. The +// policyIdentity is treated as a JavaScript regular expression pattern and +// tested against the full signerIdentity string. For exact matching, use +// anchored patterns (e.g. '^user@example\\.com$'). +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]}`, + }); + } + } +} +function verifyOIDs(policyOIDs, signerOIDs = []) { + for (const policyOID of policyOIDs) { + const match = signerOIDs.find((signerOID) => oidEquals(policyOID.oid?.id, signerOID.oid?.id) && + policyOID.value.equals(signerOID.value)); + if (!match) { + /* istanbul ignore next */ + const oid = policyOID.oid?.id.join('.') ?? ''; + throw new error_1.PolicyError({ + code: 'UNTRUSTED_SIGNER_ERROR', + message: `invalid certificate extension - missing OID ${oid}`, + }); + } + } +} +function oidEquals(a, b) { + /* istanbul ignore if */ + if (a === undefined || b === undefined) { + return false; + } + return a.length === b.length && a.every((v, i) => v === b[i]); +} diff --git a/node_modules/@sigstore/verify/dist/shared.types.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/shared.types.js similarity index 100% rename from node_modules/@sigstore/verify/dist/shared.types.js rename to node_modules/pacote/node_modules/@sigstore/verify/dist/shared.types.js diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/timestamp/index.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/timestamp/index.js new file mode 100644 index 0000000000000..603e559831a9d --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/timestamp/index.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getTSATimestamp = getTSATimestamp; +exports.getTLogTimestamp = getTLogTimestamp; +const tsa_1 = require("./tsa"); +function getTSATimestamp(timestamp, data, timestampAuthorities) { + (0, tsa_1.verifyRFC3161Timestamp)(timestamp, data, timestampAuthorities); + return { + type: 'timestamp-authority', + logID: timestamp.signerSerialNumber, + timestamp: timestamp.signingTime, + }; +} +function getTLogTimestamp(entry) { + // Only entries with an inclusion promise provide a verifiable timestamp + if (!entry.inclusionPromise) { + return undefined; + } + return { + type: 'transparency-log', + logID: entry.logId.keyId, + timestamp: new Date(Number(entry.integratedTime) * 1000), + }; +} diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/timestamp/tsa.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/timestamp/tsa.js new file mode 100644 index 0000000000000..0da4a3de8247f --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/timestamp/tsa.js @@ -0,0 +1,63 @@ +"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, 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, + timestamp: signingTime, + }).verify(); + } + catch (e) { + throw new error_1.VerificationError({ + code: 'TIMESTAMP_ERROR', + message: 'invalid certificate chain', + }); + } + // 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)); +} diff --git a/node_modules/@sigstore/verify/dist/timestamp/checkpoint.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/checkpoint.js similarity index 87% rename from node_modules/@sigstore/verify/dist/timestamp/checkpoint.js rename to node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/checkpoint.js index 04a87383f0fd1..220c5639b4c38 100644 --- a/node_modules/@sigstore/verify/dist/timestamp/checkpoint.js +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/checkpoint.js @@ -1,8 +1,9 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.verifyCheckpoint = void 0; +exports.LogCheckpoint = void 0; +exports.verifyCheckpoint = verifyCheckpoint; /* -Copyright 2023 The Sigstore Authors. +Copyright 2025 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. @@ -18,7 +19,6 @@ 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: @@ -37,40 +37,29 @@ const SIGNATURE_REGEX = /\u2014 (\S+) (\S+)\n/g; // 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)) { + if (!verifySignedNote(signedNote, tlogs)) { 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', - }); - } + return checkpoint; } -exports.verifyCheckpoint = verifyCheckpoint; // 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) => { + return signedNote.signatures.some((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)); + const tlog = tlogs.find((tlog) => core_1.crypto.bufferEqual(tlog.logID.subarray(0, 4), signature.keyHint) && + tlog.baseURL.match(signature.name) // Match the name to the base URL of the tlog + ); if (!tlog) { return false; } @@ -81,6 +70,8 @@ function verifySignedNote(signedNote, tlogs) { // 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 { + note; + signatures; constructor(note, signatures) { this.note = note; this.signatures = signatures; @@ -135,6 +126,10 @@ class SignedNote { // See: // https://github.com/transparency-dev/formats/blob/main/log/README.md#checkpoint-body class LogCheckpoint { + origin; + logSize; + logHash; + rest; constructor(origin, logSize, logHash, rest) { this.origin = origin; this.logSize = logSize; @@ -156,3 +151,4 @@ class LogCheckpoint { return new LogCheckpoint(origin, logSize, rootHash, rest); } } +exports.LogCheckpoint = LogCheckpoint; diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/dsse.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/dsse.js new file mode 100644 index 0000000000000..e438459dac80d --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/dsse.js @@ -0,0 +1,106 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DSSE_API_VERSION_V1 = void 0; +exports.verifyDSSETLogBody = verifyDSSETLogBody; +exports.verifyDSSETLogBodyV2 = verifyDSSETLogBodyV2; +/* +Copyright 2025 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"); +exports.DSSE_API_VERSION_V1 = '0.0.1'; +// Compare the given dsse tlog entry to the given bundle +function verifyDSSETLogBody(tlogEntry, content) { + switch (tlogEntry.apiVersion) { + case exports.DSSE_API_VERSION_V1: + return verifyDSSE001TLogBody(tlogEntry, content); + default: + throw new error_1.VerificationError({ + code: 'TLOG_BODY_ERROR', + message: `unsupported dsse version: ${tlogEntry.apiVersion}`, + }); + } +} +// Compare the given dsse tlog entry to the given bundle. This function is +// specifically for Rekor V2 entries. +function verifyDSSETLogBodyV2(tlogEntry, content) { + const spec = tlogEntry.spec?.spec; + if (!spec) { + throw new error_1.VerificationError({ + code: 'TLOG_BODY_ERROR', + message: `missing dsse spec`, + }); + } + switch (spec.$case) { + case 'dsseV002': + return verifyDSSE002TLogBody(spec.dsseV002, content); + default: + throw new error_1.VerificationError({ + code: 'TLOG_BODY_ERROR', + message: `unsupported version: ${spec.$case}`, + }); + } +} +// 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', + }); + } +} +// Compare the given dsse v0.0.2 tlog entry to the given DSSE envelope. +function verifyDSSE002TLogBody(spec, content) { + // Ensure the bundle's DSSE only contains a single signature + if (spec.signatures?.length !== 1) { + throw new error_1.VerificationError({ + code: 'TLOG_BODY_ERROR', + message: 'signature count mismatch', + }); + } + const tlogSig = spec.signatures[0].content; + // Ensure that the signature in the bundle's DSSE matches tlog entry + if (!content.compareSignature(tlogSig)) + 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 = spec.payloadHash?.digest || Buffer.from(''); + if (!content.compareDigest(tlogHash)) { + throw new error_1.VerificationError({ + code: 'TLOG_BODY_ERROR', + message: 'DSSE payload hash mismatch', + }); + } +} diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/hashedrekord.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/hashedrekord.js new file mode 100644 index 0000000000000..97dfcc9edc305 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/hashedrekord.js @@ -0,0 +1,94 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HASHEDREKORD_API_VERSION_V1 = void 0; +exports.verifyHashedRekordTLogBody = verifyHashedRekordTLogBody; +exports.verifyHashedRekordTLogBodyV2 = verifyHashedRekordTLogBodyV2; +/* +Copyright 2025 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"); +exports.HASHEDREKORD_API_VERSION_V1 = '0.0.1'; +// Compare the given hashedrekord tlog entry to the given bundle +function verifyHashedRekordTLogBody(tlogEntry, content) { + switch (tlogEntry.apiVersion) { + case exports.HASHEDREKORD_API_VERSION_V1: + return verifyHashedrekord001TLogBody(tlogEntry, content); + default: + throw new error_1.VerificationError({ + code: 'TLOG_BODY_ERROR', + message: `unsupported hashedrekord version: ${tlogEntry.apiVersion}`, + }); + } +} +// Compare the given hashedrekor tlog entry to the given bundle. This function is +// specifically for Rekor V2 entries. +function verifyHashedRekordTLogBodyV2(tlogEntry, content) { + const spec = tlogEntry.spec?.spec; + if (!spec) { + throw new error_1.VerificationError({ + code: 'TLOG_BODY_ERROR', + message: `missing dsse spec`, + }); + } + switch (spec.$case) { + case 'hashedRekordV002': + return verifyHashedrekord002TLogBody(spec.hashedRekordV002, content); + default: + throw new error_1.VerificationError({ + code: 'TLOG_BODY_ERROR', + message: `unsupported version: ${spec.$case}`, + }); + } +} +// 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', + }); + } +} +// Compare the given hashedrekord v0.0.2 tlog entry to the given message +// signature +function verifyHashedrekord002TLogBody(spec, content) { + // Ensure that the bundles message signature matches the tlog entry + const tlogSig = spec.signature?.content || Buffer.from(''); + if (!content.compareSignature(tlogSig)) { + throw new error_1.VerificationError({ + code: 'TLOG_BODY_ERROR', + message: 'signature mismatch', + }); + } + // Ensure that the bundle's message digest matches the tlog entry + const tlogHash = spec.data?.digest || Buffer.from(''); + if (!content.compareDigest(tlogHash)) { + throw new error_1.VerificationError({ + code: 'TLOG_BODY_ERROR', + message: 'digest mismatch', + }); + } +} diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/index.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/index.js new file mode 100644 index 0000000000000..6c244fa37e908 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/index.js @@ -0,0 +1,92 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifyTLogBody = verifyTLogBody; +exports.verifyTLogInclusion = verifyTLogInclusion; +/* +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 v2_1 = require("@sigstore/protobuf-specs/rekor/v2"); +const error_1 = require("../error"); +const dsse_1 = require("./dsse"); +const hashedrekord_1 = require("./hashedrekord"); +const intoto_1 = require("./intoto"); +const checkpoint_1 = require("./checkpoint"); +const merkle_1 = require("./merkle"); +const set_1 = require("./set"); +// 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')); + // validate body + 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 (kind) { + case 'dsse': + // Rekor V1 and V2 use incompatible types so we need to branch here based on version + if (version == dsse_1.DSSE_API_VERSION_V1) { + return (0, dsse_1.verifyDSSETLogBody)(body, sigContent); + } + else { + const entryRekorV2 = v2_1.Entry.fromJSON(body); + return (0, dsse_1.verifyDSSETLogBodyV2)(entryRekorV2, sigContent); + } + case 'intoto': + return (0, intoto_1.verifyIntotoTLogBody)(body, sigContent); + case 'hashedrekord': + // Rekor V1 and V2 use incompatible types so we need to branch here based on version + if (version == hashedrekord_1.HASHEDREKORD_API_VERSION_V1) { + return (0, hashedrekord_1.verifyHashedRekordTLogBody)(body, sigContent); + } + else { + const entryRekorV2 = v2_1.Entry.fromJSON(body); + return (0, hashedrekord_1.verifyHashedRekordTLogBodyV2)(entryRekorV2, sigContent); + } + /* istanbul ignore next */ + default: + throw new error_1.VerificationError({ + code: 'TLOG_BODY_ERROR', + message: `unsupported kind: ${kind}`, + }); + } +} +function verifyTLogInclusion(entry, tlogAuthorities) { + let inclusionVerified = false; + if (isTLogEntryWithInclusionPromise(entry)) { + (0, set_1.verifyTLogSET)(entry, tlogAuthorities); + inclusionVerified = true; + } + if (isTLogEntryWithInclusionProof(entry)) { + const checkpoint = (0, checkpoint_1.verifyCheckpoint)(entry, tlogAuthorities); + (0, merkle_1.verifyMerkleInclusion)(entry, checkpoint); + inclusionVerified = true; + } + if (!inclusionVerified) { + throw new error_1.VerificationError({ + code: 'TLOG_MISSING_INCLUSION_ERROR', + message: 'inclusion could not be verified', + }); + } + return; +} +function isTLogEntryWithInclusionPromise(entry) { + return entry.inclusionPromise !== undefined; +} +function isTLogEntryWithInclusionProof(entry) { + return entry.inclusionProof !== undefined; +} diff --git a/node_modules/@sigstore/verify/dist/tlog/intoto.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/intoto.js similarity index 98% rename from node_modules/@sigstore/verify/dist/tlog/intoto.js rename to node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/intoto.js index 74c7f50d763e1..9096ae9418cc3 100644 --- a/node_modules/@sigstore/verify/dist/tlog/intoto.js +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/intoto.js @@ -1,6 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.verifyIntotoTLogBody = void 0; +exports.verifyIntotoTLogBody = verifyIntotoTLogBody; /* Copyright 2023 The Sigstore Authors. @@ -29,7 +29,6 @@ function verifyIntotoTLogBody(tlogEntry, content) { }); } } -exports.verifyIntotoTLogBody = verifyIntotoTLogBody; // 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 diff --git a/node_modules/@sigstore/verify/dist/timestamp/merkle.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/merkle.js similarity index 91% rename from node_modules/@sigstore/verify/dist/timestamp/merkle.js rename to node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/merkle.js index 9895d01b7abc0..fbebeffd1ba7b 100644 --- a/node_modules/@sigstore/verify/dist/timestamp/merkle.js +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/merkle.js @@ -1,6 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.verifyMerkleInclusion = void 0; +exports.verifyMerkleInclusion = verifyMerkleInclusion; /* Copyright 2023 The Sigstore Authors. @@ -20,10 +20,10 @@ 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) { +function verifyMerkleInclusion(entry, checkpoint) { const inclusionProof = entry.inclusionProof; const logIndex = BigInt(inclusionProof.logIndex); - const treeSize = BigInt(inclusionProof.treeSize); + const treeSize = BigInt(checkpoint.logSize); if (logIndex < 0n || logIndex >= treeSize) { throw new error_1.VerificationError({ code: 'TLOG_INCLUSION_PROOF_ERROR', @@ -46,14 +46,13 @@ function verifyMerkleInclusion(entry) { // 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)) { + if (!core_1.crypto.bufferEqual(calculatedHash, checkpoint.logHash)) { throw new error_1.VerificationError({ code: 'TLOG_INCLUSION_PROOF_ERROR', message: 'calculated root hash does not match inclusion proof', }); } } -exports.verifyMerkleInclusion = verifyMerkleInclusion; // 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 @@ -98,8 +97,8 @@ function bitLength(n) { // Hashing logic according to RFC6962. // https://datatracker.ietf.org/doc/html/rfc6962#section-2 function hashChildren(left, right) { - return core_1.crypto.hash(RFC6962_NODE_HASH_PREFIX, left, right); + return core_1.crypto.digest('sha256', RFC6962_NODE_HASH_PREFIX, left, right); } function hashLeaf(leaf) { - return core_1.crypto.hash(RFC6962_LEAF_HASH_PREFIX, leaf); + return core_1.crypto.digest('sha256', RFC6962_LEAF_HASH_PREFIX, leaf); } diff --git a/node_modules/@sigstore/verify/dist/timestamp/set.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/set.js similarity index 98% rename from node_modules/@sigstore/verify/dist/timestamp/set.js rename to node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/set.js index a6357c06999cb..5d3f47bb88746 100644 --- a/node_modules/@sigstore/verify/dist/timestamp/set.js +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/tlog/set.js @@ -1,6 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.verifyTLogSET = void 0; +exports.verifyTLogSET = verifyTLogSET; /* Copyright 2023 The Sigstore Authors. @@ -46,7 +46,6 @@ function verifyTLogSET(entry, tlogs) { }); } } -exports.verifyTLogSET = verifyTLogSET; // Returns a properly formatted "VerificationPayload" for one of the // transaction log entires in the given bundle which can be used for SET // verification. diff --git a/node_modules/@sigstore/verify/dist/trust/filter.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/trust/filter.js similarity index 80% rename from node_modules/@sigstore/verify/dist/trust/filter.js rename to node_modules/pacote/node_modules/@sigstore/verify/dist/trust/filter.js index c09d055913c4c..98bd25cd70e59 100644 --- a/node_modules/@sigstore/verify/dist/trust/filter.js +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/trust/filter.js @@ -1,12 +1,12 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.filterTLogAuthorities = exports.filterCertAuthorities = void 0; -function filterCertAuthorities(certAuthorities, criteria) { +exports.filterCertAuthorities = filterCertAuthorities; +exports.filterTLogAuthorities = filterTLogAuthorities; +function filterCertAuthorities(certAuthorities, timestamp) { return certAuthorities.filter((ca) => { - return (ca.validFor.start <= criteria.start && ca.validFor.end >= criteria.end); + return ca.validFor.start <= timestamp && ca.validFor.end >= timestamp; }); } -exports.filterCertAuthorities = filterCertAuthorities; // 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) { @@ -21,4 +21,3 @@ function filterTLogAuthorities(tlogAuthorities, criteria) { criteria.targetDate <= tlog.validFor.end); }); } -exports.filterTLogAuthorities = filterTLogAuthorities; diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/trust/index.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/trust/index.js new file mode 100644 index 0000000000000..2823f5f7d4b93 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/trust/index.js @@ -0,0 +1,90 @@ +"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'; + /* istanbul ignore next */ + return { + baseURL: tlogInstance.baseUrl, + logID: tlogInstance.checkpointKeyId + ? tlogInstance.checkpointKeyId.keyId + : 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(Buffer.from(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); + }, + }; + }; +} diff --git a/node_modules/@sigstore/verify/dist/trust/trust.types.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/trust/trust.types.js similarity index 100% rename from node_modules/@sigstore/verify/dist/trust/trust.types.js rename to node_modules/pacote/node_modules/@sigstore/verify/dist/trust/trust.types.js diff --git a/node_modules/pacote/node_modules/@sigstore/verify/dist/verifier.js b/node_modules/pacote/node_modules/@sigstore/verify/dist/verifier.js new file mode 100644 index 0000000000000..eeba4128fabe3 --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/dist/verifier.js @@ -0,0 +1,160 @@ +"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 { + trustMaterial; + options; + constructor(trustMaterial, options = {}) { + this.trustMaterial = trustMaterial; + this.options = { + ctlogThreshold: options.ctlogThreshold ?? 1, + tlogThreshold: options.tlogThreshold ?? 1, + timestampThreshold: options.timestampThreshold ?? options.tsaThreshold ?? 1, + 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) { + const timestamps = []; + for (const timestamp of entity.timestamps) { + switch (timestamp.$case) { + case 'timestamp-authority': + timestamps.push((0, timestamp_1.getTSATimestamp)(timestamp.timestamp, entity.signature.signature, this.trustMaterial.timestampAuthorities)); + break; + case 'transparency-log': { + const result = (0, timestamp_1.getTLogTimestamp)(timestamp.tlogEntry); + /* istanbul ignore else */ + if (result) { + timestamps.push(result); + } + break; + } + } + } + // Check for duplicate timestamps + if (containsDupes(timestamps)) { + throw new error_1.VerificationError({ + code: 'TIMESTAMP_ERROR', + message: 'duplicate timestamp', + }); + } + if (timestamps.length < this.options.timestampThreshold) { + throw new error_1.VerificationError({ + code: 'TIMESTAMP_ERROR', + message: `expected ${this.options.timestampThreshold} timestamps, got ${timestamps.length}`, + }); + } + 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 }) { + let tlogCount = 0; + tlogEntries.forEach((entry) => { + tlogCount++; + (0, tlog_1.verifyTLogInclusion)(entry, this.trustMaterial.tlogs); + (0, tlog_1.verifyTLogBody)(entry, content); + }); + if (tlogCount < this.options.tlogThreshold) { + throw new error_1.VerificationError({ + code: 'TLOG_ERROR', + message: `expected ${this.options.tlogThreshold} tlog entries, got ${tlogCount}`, + }); + } + } + // 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 + /* istanbul ignore else */ + if (policy.subjectAlternativeName) { + (0, policy_1.verifySubjectAlternativeName)(policy.subjectAlternativeName, identity.subjectAlternativeName); + } + // Check that the extensions of the signer match the policy + /* istanbul ignore else */ + if (policy.extensions) { + (0, policy_1.verifyExtensions)(policy.extensions, identity.extensions); + } + // Check that the OIDs of the signer match the policy + /* istanbul ignore if */ + if (policy.oids) { + (0, policy_1.verifyOIDs)(policy.oids, identity.oids); + } + } +} +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; +} diff --git a/node_modules/pacote/node_modules/@sigstore/verify/package.json b/node_modules/pacote/node_modules/@sigstore/verify/package.json new file mode 100644 index 0000000000000..74a839dddfc1d --- /dev/null +++ b/node_modules/pacote/node_modules/@sigstore/verify/package.json @@ -0,0 +1,36 @@ +{ + "name": "@sigstore/verify", + "version": "4.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/bundle": "^5.0.0", + "@sigstore/core": "^4.0.0", + "@sigstore/protobuf-specs": "^0.5.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } +} diff --git a/node_modules/sigstore/LICENSE b/node_modules/pacote/node_modules/sigstore/LICENSE similarity index 100% rename from node_modules/sigstore/LICENSE rename to node_modules/pacote/node_modules/sigstore/LICENSE diff --git a/node_modules/pacote/node_modules/sigstore/dist/config.js b/node_modules/pacote/node_modules/sigstore/dist/config.js new file mode 100644 index 0000000000000..373149fe22fb7 --- /dev/null +++ b/node_modules/pacote/node_modules/sigstore/dist/config.js @@ -0,0 +1,126 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_TIMEOUT = exports.DEFAULT_RETRY = void 0; +exports.createBundleBuilder = createBundleBuilder; +exports.createKeyFinder = createKeyFinder; +exports.createVerificationPolicy = createVerificationPolicy; +/* +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 sign_1 = require("@sigstore/sign"); +const verify_1 = require("@sigstore/verify"); +exports.DEFAULT_RETRY = { retries: 2 }; +exports.DEFAULT_TIMEOUT = 5000; +function createBundleBuilder(bundleType, options) { + const bundlerOptions = { + signer: initSigner(options), + witnesses: initWitnesses(options), + }; + switch (bundleType) { + case 'messageSignature': + return new sign_1.MessageSignatureBundleBuilder(bundlerOptions); + case 'dsseEnvelope': + return new sign_1.DSSEBundleBuilder({ + ...bundlerOptions, + certificateChain: options.legacyCompatibility, + }); + } +} +// Translates the public KeySelector type into the KeyFinderFunc type needed by +// the verifier. +function createKeyFinder(keySelector) { + return (hint) => { + const key = keySelector(hint); + if (!key) { + throw new verify_1.VerificationError({ + code: 'PUBLIC_KEY_ERROR', + message: `key not found: ${hint}`, + }); + } + return { + publicKey: core_1.crypto.createPublicKey(key), + validFor: () => true, + }; + }; +} +function createVerificationPolicy(options) { + const policy = {}; + const san = options.certificateIdentityEmail || options.certificateIdentityURI; + if (san) { + policy.subjectAlternativeName = san; + } + if (options.certificateIssuer) { + policy.extensions = { issuer: options.certificateIssuer }; + } + if (options.certificateOIDs) { + policy.oids = Object.entries(options.certificateOIDs).map(([oid, value]) => ({ + oid: { id: oid.split('.').map(Number) }, + value: Buffer.from(value), + })); + } + return policy; +} +// Instantiate the FulcioSigner based on the supplied options. +function initSigner(options) { + return new sign_1.FulcioSigner({ + fulcioBaseURL: options.fulcioURL, + identityProvider: options.identityProvider || initIdentityProvider(options), + retry: options.retry ?? exports.DEFAULT_RETRY, + timeout: options.timeout ?? exports.DEFAULT_TIMEOUT, + }); +} +// Instantiate an identity provider based on the supplied options. If an +// explicit identity token is provided, use that. Otherwise, use the CI +// context provider. +function initIdentityProvider(options) { + const token = options.identityToken; + if (token) { + /* istanbul ignore next */ + return { getToken: () => Promise.resolve(token) }; + } + else { + return new sign_1.CIContextProvider('sigstore'); + } +} +// Instantiate a collection of witnesses based on the supplied options. +function initWitnesses(options) { + const witnesses = []; + if (isRekorEnabled(options)) { + witnesses.push(new sign_1.RekorWitness({ + rekorBaseURL: options.rekorURL, + entryType: options.legacyCompatibility ? 'intoto' : 'dsse', + fetchOnConflict: false, + retry: options.retry ?? exports.DEFAULT_RETRY, + timeout: options.timeout ?? exports.DEFAULT_TIMEOUT, + })); + } + if (isTSAEnabled(options)) { + witnesses.push(new sign_1.TSAWitness({ + tsaBaseURL: options.tsaServerURL, + retry: options.retry ?? exports.DEFAULT_RETRY, + timeout: options.timeout ?? exports.DEFAULT_TIMEOUT, + })); + } + return witnesses; +} +// Type assertion to ensure that Rekor is enabled +function isRekorEnabled(options) { + return options.tlogUpload !== false; +} +// Type assertion to ensure that TSA is enabled +function isTSAEnabled(options) { + return options.tsaServerURL !== undefined; +} diff --git a/node_modules/sigstore/dist/index.js b/node_modules/pacote/node_modules/sigstore/dist/index.js similarity index 100% rename from node_modules/sigstore/dist/index.js rename to node_modules/pacote/node_modules/sigstore/dist/index.js diff --git a/node_modules/sigstore/dist/sigstore.js b/node_modules/pacote/node_modules/sigstore/dist/sigstore.js similarity index 81% rename from node_modules/sigstore/dist/sigstore.js rename to node_modules/pacote/node_modules/sigstore/dist/sigstore.js index 3f6d895f84168..f7d79ed880588 100644 --- a/node_modules/sigstore/dist/sigstore.js +++ b/node_modules/pacote/node_modules/sigstore/dist/sigstore.js @@ -15,15 +15,28 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( }) : 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 __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); Object.defineProperty(exports, "__esModule", { value: true }); -exports.createVerifier = exports.verify = exports.attest = exports.sign = void 0; +exports.sign = sign; +exports.attest = attest; +exports.verify = verify; +exports.createVerifier = createVerifier; /* Copyright 2023 The Sigstore Authors. @@ -50,7 +63,6 @@ options = {}) { const bundle = await bundler.create({ data: payload }); return (0, bundle_1.bundleToJSON)(bundle); } -exports.sign = sign; async function attest(payload, payloadType, /* istanbul ignore next */ options = {}) { @@ -58,7 +70,6 @@ options = {}) { const bundle = await bundler.create({ data: payload, type: payloadType }); return (0, bundle_1.bundleToJSON)(bundle); } -exports.attest = attest; async function verify(bundle, dataOrOptions, options) { let data; if (Buffer.isBuffer(dataOrOptions)) { @@ -67,9 +78,9 @@ async function verify(bundle, dataOrOptions, options) { else { options = dataOrOptions; } - return createVerifier(options).then((verifier) => verifier.verify(bundle, data)); + const verifier = await createVerifier(options); + return verifier.verify(bundle, data); } -exports.verify = verify; async function createVerifier( /* istanbul ignore next */ options = {}) { @@ -95,9 +106,7 @@ options = {}) { verify: (bundle, payload) => { const deserializedBundle = (0, bundle_1.bundleFromJSON)(bundle); const signedEntity = (0, verify_1.toSignedEntity)(deserializedBundle, payload); - verifier.verify(signedEntity, policy); - return; + return verifier.verify(signedEntity, policy); }, }; } -exports.createVerifier = createVerifier; diff --git a/node_modules/pacote/node_modules/sigstore/package.json b/node_modules/pacote/node_modules/sigstore/package.json new file mode 100644 index 0000000000000..c32bfefa3e231 --- /dev/null +++ b/node_modules/pacote/node_modules/sigstore/package.json @@ -0,0 +1,47 @@ +{ + "name": "sigstore", + "version": "5.0.0", + "description": "code-signing for npm packages", + "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/client#readme", + "publishConfig": { + "provenance": true + }, + "devDependencies": { + "@sigstore/jest": "^0.0.0", + "@sigstore/mock": "^0.13.0", + "@sigstore/rekor-types": "^5.0.0", + "@tufjs/repo-mock": "^5.0.0", + "@types/make-fetch-happen": "^10.0.4" + }, + "dependencies": { + "@sigstore/bundle": "^5.0.0", + "@sigstore/core": "^4.0.0", + "@sigstore/protobuf-specs": "^0.5.0", + "@sigstore/sign": "^5.0.0", + "@sigstore/tuf": "^5.0.0", + "@sigstore/verify": "^4.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } +} diff --git a/node_modules/pacote/package.json b/node_modules/pacote/package.json index caadaf2db50c8..2e544354ef85d 100644 --- a/node_modules/pacote/package.json +++ b/node_modules/pacote/package.json @@ -1,6 +1,6 @@ { "name": "pacote", - "version": "18.0.6", + "version": "22.0.0", "description": "JavaScript package downloader", "author": "GitHub Inc.", "bin": { @@ -11,11 +11,12 @@ "scripts": { "test": "tap", "snap": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "timeout": 300, @@ -25,13 +26,14 @@ ] }, "devDependencies": { - "@npmcli/arborist": "^7.1.0", - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "hosted-git-info": "^7.0.0", + "@npmcli/arborist": "^9.0.2", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.0", + "hosted-git-info": "^10.1.1", "mutate-fs": "^2.1.1", "nock": "^13.2.4", "npm-registry-mock": "^1.3.2", + "rimraf": "^6.0.1", "tap": "^16.0.1" }, "files": [ @@ -44,26 +46,26 @@ "git" ], "dependencies": { - "@npmcli/git": "^5.0.0", - "@npmcli/installed-package-contents": "^2.0.1", - "@npmcli/package-json": "^5.1.0", - "@npmcli/promise-spawn": "^7.0.0", - "@npmcli/run-script": "^8.0.0", - "cacache": "^18.0.0", + "@gar/promise-retry": "^1.0.0", + "@npmcli/git": "^8.0.0", + "@npmcli/installed-package-contents": "^5.0.0", + "@npmcli/package-json": "^8.0.0", + "@npmcli/promise-spawn": "^10.0.0", + "@npmcli/run-script": "^11.0.0", + "cacache": "^21.0.1", "fs-minipass": "^3.0.0", "minipass": "^7.0.2", - "npm-package-arg": "^11.0.0", - "npm-packlist": "^8.0.0", - "npm-pick-manifest": "^9.0.0", - "npm-registry-fetch": "^17.0.0", - "proc-log": "^4.0.0", - "promise-retry": "^2.0.1", - "sigstore": "^2.2.0", - "ssri": "^10.0.0", - "tar": "^6.1.11" + "npm-package-arg": "^14.0.0", + "npm-packlist": "^11.2.0", + "npm-pick-manifest": "^12.0.0", + "npm-registry-fetch": "^20.0.1", + "proc-log": "^7.0.0", + "sigstore": "^5.0.0", + "ssri": "^14.0.0", + "tar": "^7.4.3" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "repository": { "type": "git", @@ -71,8 +73,9 @@ }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.0", "windowsCI": false, - "publish": "true" + "publish": "true", + "updateNpm": false } } diff --git a/node_modules/parse-conflict-json/package.json b/node_modules/parse-conflict-json/package.json index 32584d3e6401b..9da656e103cb1 100644 --- a/node_modules/parse-conflict-json/package.json +++ b/node_modules/parse-conflict-json/package.json @@ -1,6 +1,6 @@ { "name": "parse-conflict-json", - "version": "3.0.1", + "version": "6.0.0", "description": "Parse a JSON string that has git merge conflicts, resolving if possible", "author": "GitHub Inc.", "license": "ISC", @@ -8,11 +8,12 @@ "scripts": { "test": "tap", "snap": "tap", - "lint": "eslint \"**/*.js\"", + "lint": "npm run eslint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "check-coverage": true, @@ -22,28 +23,29 @@ ] }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.12.0", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.1.0", "tap": "^16.0.1" }, "dependencies": { - "json-parse-even-better-errors": "^3.0.0", + "json-parse-even-better-errors": "^6.0.0", "just-diff": "^6.0.0", "just-diff-apply": "^5.2.0" }, "repository": { "type": "git", - "url": "https://github.com/npm/parse-conflict-json.git" + "url": "git+https://github.com/npm/parse-conflict-json.git" }, "files": [ "bin/", "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.12.0" + "version": "5.1.0", + "publish": true } } diff --git a/node_modules/path-key/index.js b/node_modules/path-key/index.js deleted file mode 100644 index 0cf6415d60938..0000000000000 --- a/node_modules/path-key/index.js +++ /dev/null @@ -1,16 +0,0 @@ -'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; diff --git a/node_modules/path-key/license b/node_modules/path-key/license deleted file mode 100644 index e7af2f77107d7..0000000000000 --- a/node_modules/path-key/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/path-key/package.json b/node_modules/path-key/package.json deleted file mode 100644 index c8cbd383afc95..0000000000000 --- a/node_modules/path-key/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/path-scurry/dist/commonjs/index.js b/node_modules/path-scurry/dist/commonjs/index.js index 555de62f04c90..112f732d69a3f 100644 --- a/node_modules/path-scurry/dist/commonjs/index.js +++ b/node_modules/path-scurry/dist/commonjs/index.js @@ -99,7 +99,7 @@ const entToType = (s) => s.isFile() ? IFREG : s.isFIFO() ? IFIFO : UNKNOWN; // normalize unicode path names -const normalizeCache = new Map(); +const normalizeCache = new lru_cache_1.LRUCache({ max: 2 ** 12 }); const normalize = (s) => { const c = normalizeCache.get(s); if (c) @@ -108,7 +108,7 @@ const normalize = (s) => { normalizeCache.set(s, n); return n; }; -const normalizeNocaseCache = new Map(); +const normalizeNocaseCache = new lru_cache_1.LRUCache({ max: 2 ** 12 }); const normalizeNocase = (s) => { const c = normalizeNocaseCache.get(s); if (c) @@ -299,13 +299,17 @@ class PathBase { get parentPath() { return (this.parent || this).fullpath(); } + /* c8 ignore start */ /** * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively, * this property refers to the *parent* path, not the path object itself. + * + * @deprecated */ get path() { return this.parentPath; } + /* c8 ignore stop */ /** * Do not create new Path objects directly. They should always be accessed * via the PathScurry class or other methods on the Path class. diff --git a/node_modules/path-scurry/dist/esm/index.js b/node_modules/path-scurry/dist/esm/index.js index 3b11b819faece..dc7cae493aa50 100644 --- a/node_modules/path-scurry/dist/esm/index.js +++ b/node_modules/path-scurry/dist/esm/index.js @@ -73,7 +73,7 @@ const entToType = (s) => s.isFile() ? IFREG : s.isFIFO() ? IFIFO : UNKNOWN; // normalize unicode path names -const normalizeCache = new Map(); +const normalizeCache = new LRUCache({ max: 2 ** 12 }); const normalize = (s) => { const c = normalizeCache.get(s); if (c) @@ -82,7 +82,7 @@ const normalize = (s) => { normalizeCache.set(s, n); return n; }; -const normalizeNocaseCache = new Map(); +const normalizeNocaseCache = new LRUCache({ max: 2 ** 12 }); const normalizeNocase = (s) => { const c = normalizeNocaseCache.get(s); if (c) @@ -271,13 +271,17 @@ export class PathBase { get parentPath() { return (this.parent || this).fullpath(); } + /* c8 ignore start */ /** * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively, * this property refers to the *parent* path, not the path object itself. + * + * @deprecated */ get path() { return this.parentPath; } + /* c8 ignore stop */ /** * Do not create new Path objects directly. They should always be accessed * via the PathScurry class or other methods on the Path class. diff --git a/node_modules/path-scurry/package.json b/node_modules/path-scurry/package.json index e1766157894c8..68123fb70f16b 100644 --- a/node_modules/path-scurry/package.json +++ b/node_modules/path-scurry/package.json @@ -1,6 +1,6 @@ { "name": "path-scurry", - "version": "1.11.1", + "version": "2.0.2", "description": "walk paths fast and efficiently", "author": "Isaac Z. Schlueter (https://blog.izs.me)", "main": "./dist/commonjs/index.js", @@ -31,41 +31,23 @@ "presnap": "npm run prepare", "test": "tap", "snap": "tap", - "format": "prettier --write . --loglevel warn", + "format": "prettier --write . --log-level 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", + "@nodelib/fs.walk": "^3.0.1", + "@types/node": "^25.3.0", "mkdirp": "^3.0.0", - "prettier": "^3.2.5", - "rimraf": "^5.0.1", - "tap": "^18.7.2", + "prettier": "^3.3.2", + "rimraf": "^6.1.3", + "tap": "^21.6.1", "ts-node": "^10.9.2", - "tshy": "^1.14.0", - "typedoc": "^0.25.12", - "typescript": "^5.4.3" - }, - "tap": { - "typecheck": true + "tshy": "^3.3.2", + "typedoc": "^0.28.17" }, "engines": { - "node": ">=16 || 14 >=14.18" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -75,8 +57,8 @@ "url": "git+https://github.com/isaacs/path-scurry" }, "dependencies": { - "lru-cache": "^10.2.0", - "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" }, "tshy": { "selfLink": false, @@ -85,5 +67,6 @@ ".": "./src/index.ts" } }, - "types": "./dist/commonjs/index.d.ts" + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js" } diff --git a/node_modules/postcss-selector-parser/API.md b/node_modules/postcss-selector-parser/API.md index 64459e3376fba..e564830b66b04 100644 --- a/node_modules/postcss-selector-parser/API.md +++ b/node_modules/postcss-selector-parser/API.md @@ -254,7 +254,7 @@ if (next && next.type !== 'combinator') { } ``` -### `node.replaceWith(node)` +### `node.replaceWith(node[,...nodeN])` Replace a node with another. @@ -267,6 +267,8 @@ attr.replaceWith(className); Arguments: * `node`: The node to substitute the original with. +... +* `nodeN`: The node to substitute the original with. ### `node.remove()` @@ -531,7 +533,7 @@ Arguments: * `node`: The node to add. -### `container.insertBefore(old, new)` & `container.insertAfter(old, new)` +### `container.insertBefore(old, new[, ...newNodes])` & `container.insertAfter(old, new[, ...newNodes])` Add a node before or after an existing node in a container: @@ -786,7 +788,7 @@ 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://api.postcss.org/Container.html#error)). +([documentation](http://postcss.org/api/#container-error)). #### Async Error Example diff --git a/node_modules/postcss-selector-parser/dist/parser.js b/node_modules/postcss-selector-parser/dist/parser.js index 144f91f730099..e36af64dbd338 100644 --- a/node_modules/postcss-selector-parser/dist/parser.js +++ b/node_modules/postcss-selector-parser/dist/parser.js @@ -485,7 +485,7 @@ var Parser = /*#__PURE__*/function () { } // 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) { + 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; @@ -548,7 +548,7 @@ var Parser = /*#__PURE__*/function () { 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(' ')) { + } else if (_space2[0] === ' ' && _rawSpace2[0] === ' ') { spaces.after = _space2.slice(1); raws.spaces.after = _rawSpace2.slice(1); } else { diff --git a/node_modules/postcss-selector-parser/dist/selectors/container.js b/node_modules/postcss-selector-parser/dist/selectors/container.js index 8600c544ebb1d..84755cbd541a2 100644 --- a/node_modules/postcss-selector-parser/dist/selectors/container.js +++ b/node_modules/postcss-selector-parser/dist/selectors/container.js @@ -33,6 +33,9 @@ var Container = /*#__PURE__*/function (_Node) { _proto.prepend = function prepend(selector) { selector.parent = this; this.nodes.unshift(selector); + for (var id in this.indexes) { + this.indexes[id]++; + } return this; }; _proto.at = function at(index) { @@ -69,29 +72,39 @@ var Container = /*#__PURE__*/function (_Node) { return this.removeAll(); }; _proto.insertAfter = function insertAfter(oldNode, newNode) { + var _this$nodes; newNode.parent = this; var oldIndex = this.index(oldNode); - this.nodes.splice(oldIndex + 1, 0, newNode); + var resetNode = []; + for (var i = 2; i < arguments.length; i++) { + resetNode.push(arguments[i]); + } + (_this$nodes = this.nodes).splice.apply(_this$nodes, [oldIndex + 1, 0, newNode].concat(resetNode)); newNode.parent = this; var index; for (var id in this.indexes) { index = this.indexes[id]; - if (oldIndex <= index) { - this.indexes[id] = index + 1; + if (oldIndex < index) { + this.indexes[id] = index + arguments.length - 1; } } return this; }; _proto.insertBefore = function insertBefore(oldNode, newNode) { + var _this$nodes2; newNode.parent = this; var oldIndex = this.index(oldNode); - this.nodes.splice(oldIndex, 0, newNode); + var resetNode = []; + for (var i = 2; i < arguments.length; i++) { + resetNode.push(arguments[i]); + } + (_this$nodes2 = this.nodes).splice.apply(_this$nodes2, [oldIndex, 0, newNode].concat(resetNode)); newNode.parent = this; var index; for (var id in this.indexes) { index = this.indexes[id]; - if (index <= oldIndex) { - this.indexes[id] = index + 1; + if (index >= oldIndex) { + this.indexes[id] = index + arguments.length - 1; } } return this; @@ -117,7 +130,7 @@ var Container = /*#__PURE__*/function (_Node) { * 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. diff --git a/node_modules/postcss-selector-parser/package.json b/node_modules/postcss-selector-parser/package.json index 0a1bc95700dbb..c4f057c915bfd 100644 --- a/node_modules/postcss-selector-parser/package.json +++ b/node_modules/postcss-selector-parser/package.json @@ -1,6 +1,6 @@ { "name": "postcss-selector-parser", - "version": "6.1.0", + "version": "7.1.1", "devDependencies": { "@babel/cli": "^7.11.6", "@babel/core": "^7.11.6", @@ -11,7 +11,7 @@ "@babel/register": "^7.11.5", "ava": "^5.1.0", "babel-plugin-add-module-exports": "^1.0.4", - "coveralls": "^3.1.0", + "coveralls-next": "^4.2.1", "del-cli": "^5.0.0", "eslint": "^8.28.0", "eslint-plugin-import": "^2.26.0", @@ -39,6 +39,7 @@ "lintfix": "eslint --fix src", "report": "nyc report --reporter=html", "test": "nyc ava src/__tests__/*.mjs", + "test:node22": "nyc ava src/__tests__/*.mjs --node-arguments=--no-experimental-detect-module", "testone": "ava" }, "dependencies": { diff --git a/node_modules/proc-log/lib/index.js b/node_modules/proc-log/lib/index.js index 86d90861078da..94515ad9139c6 100644 --- a/node_modules/proc-log/lib/index.js +++ b/node_modules/proc-log/lib/index.js @@ -122,10 +122,15 @@ module.exports = { end: 'end', read: 'read', }, - start: function (fn) { - process.emit('input', 'start') + start: function (...args) { + // Support callback for backwards compatibility and pass additional args to event + let fn + if (typeof args[0] === 'function') { + fn = args.shift() + } + process.emit('input', 'start', ...args) function end () { - return process.emit('input', 'end') + return process.emit('input', 'end', ...args) } if (typeof fn === 'function') { const res = fn() @@ -137,8 +142,8 @@ module.exports = { } return end }, - end: function () { - return process.emit('input', 'end') + end: function (...args) { + return process.emit('input', 'end', ...args) }, read: function (...args) { let resolve, reject diff --git a/node_modules/proc-log/package.json b/node_modules/proc-log/package.json index 4ab89102ecc9b..1d298804641fe 100644 --- a/node_modules/proc-log/package.json +++ b/node_modules/proc-log/package.json @@ -1,6 +1,6 @@ { "name": "proc-log", - "version": "4.2.0", + "version": "7.0.0", "files": [ "bin/", "lib/" @@ -9,7 +9,7 @@ "description": "just emit 'log' events on the process object", "repository": { "type": "git", - "url": "https://github.com/npm/proc-log.git" + "url": "git+https://github.com/npm/proc-log.git" }, "author": "GitHub Inc.", "license": "ISC", @@ -18,22 +18,23 @@ "snap": "tap", "posttest": "npm run lint", "postsnap": "eslint index.js test/*.js --fix", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "template-oss-apply": "template-oss-apply --force" + "lintfix": "npm run eslint -- --fix", + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.3", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0", "tap": "^16.0.1" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.3", + "version": "5.0.0", "publish": true }, "tap": { diff --git a/node_modules/proggy/package.json b/node_modules/proggy/package.json index 4940fc9d002a6..351e53c4fc1c5 100644 --- a/node_modules/proggy/package.json +++ b/node_modules/proggy/package.json @@ -1,6 +1,6 @@ { "name": "proggy", - "version": "2.0.0", + "version": "4.0.0", "files": [ "bin/", "lib/" @@ -9,7 +9,7 @@ "description": "Progress bar updates at a distance", "repository": { "type": "git", - "url": "https://github.com/npm/proggy.git" + "url": "git+https://github.com/npm/proggy.git" }, "author": "GitHub Inc.", "license": "ISC", @@ -18,17 +18,18 @@ "posttest": "npm run lint", "snap": "tap", "postsnap": "eslint lib test --fix", - "lint": "eslint \"**/*.js\"", + "lint": "npm run eslint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "template-oss-apply": "template-oss-apply --force" + "lintfix": "npm run eslint -- --fix", + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { - "@npmcli/eslint-config": "^3.0.1", - "@npmcli/template-oss": "4.5.1", + "@npmcli/eslint-config": "^5.0.0", + "@npmcli/template-oss": "4.27.1", "chalk": "^4.1.2", "cli-progress": "^3.10.0", - "npmlog": "^6.0.1", + "npmlog": "^7.0.0", "tap": "^16.0.1" }, "tap": { @@ -39,10 +40,11 @@ ] }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "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.5.1" + "version": "4.27.1", + "publish": true } } diff --git a/node_modules/promise-call-limit/dist/commonjs/index.js b/node_modules/promise-call-limit/dist/commonjs/index.js index 6ce5cfcef9559..b32a85bb11aa3 100644 --- a/node_modules/promise-call-limit/dist/commonjs/index.js +++ b/node_modules/promise-call-limit/dist/commonjs/index.js @@ -29,8 +29,8 @@ const os = __importStar(require("node:os")); // 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) +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; diff --git a/node_modules/promise-call-limit/dist/esm/index.js b/node_modules/promise-call-limit/dist/esm/index.js index 030099929b348..fe709db7fc04c 100644 --- a/node_modules/promise-call-limit/dist/esm/index.js +++ b/node_modules/promise-call-limit/dist/esm/index.js @@ -3,8 +3,8 @@ import * as os from 'node:os'; // 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) +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; diff --git a/node_modules/promise-call-limit/package.json b/node_modules/promise-call-limit/package.json index a3aa548d6538a..ab14595366e22 100644 --- a/node_modules/promise-call-limit/package.json +++ b/node_modules/promise-call-limit/package.json @@ -1,6 +1,6 @@ { "name": "promise-call-limit", - "version": "3.0.1", + "version": "3.0.2", "files": [ "dist" ], @@ -18,16 +18,17 @@ "test": "tap", "preversion": "npm test", "postversion": "npm publish", - "prepublishOnly": "git push origin --follow-tags" + "prepublishOnly": "git push origin --follow-tags", + "format": "prettier --write . --log-level warn --cache" }, "devDependencies": { - "prettier": "^3.2.1", - "tap": "^18.6.1", - "tshy": "^1.8.2", - "format": "prettier --write . --loglevel warn --ignore-path ../../.prettierignore --cache", - "typedoc": "typedoc" + "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, @@ -62,5 +63,6 @@ }, "main": "./dist/commonjs/index.js", "types": "./dist/commonjs/index.d.ts", - "type": "module" + "type": "module", + "module": "./dist/esm/index.js" } diff --git a/node_modules/promise-inflight/LICENSE b/node_modules/promise-inflight/LICENSE deleted file mode 100644 index 83e7c4c62903d..0000000000000 --- a/node_modules/promise-inflight/LICENSE +++ /dev/null @@ -1,14 +0,0 @@ -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. - diff --git a/node_modules/promise-inflight/inflight.js b/node_modules/promise-inflight/inflight.js deleted file mode 100644 index ce054d34be859..0000000000000 --- a/node_modules/promise-inflight/inflight.js +++ /dev/null @@ -1,36 +0,0 @@ -'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] - } -} diff --git a/node_modules/promise-inflight/package.json b/node_modules/promise-inflight/package.json deleted file mode 100644 index 0d8930c5b6d49..0000000000000 --- a/node_modules/promise-inflight/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "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" -} diff --git a/node_modules/promise-retry/LICENSE b/node_modules/promise-retry/LICENSE deleted file mode 100644 index db5e914de1f58..0000000000000 --- a/node_modules/promise-retry/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -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. diff --git a/node_modules/promise-retry/index.js b/node_modules/promise-retry/index.js deleted file mode 100644 index 5df48ae91602d..0000000000000 --- a/node_modules/promise-retry/index.js +++ /dev/null @@ -1,52 +0,0 @@ -'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; diff --git a/node_modules/promise-retry/package.json b/node_modules/promise-retry/package.json deleted file mode 100644 index 6842de823fd19..0000000000000 --- a/node_modules/promise-retry/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/promise-retry/test/test.js b/node_modules/promise-retry/test/test.js deleted file mode 100644 index 466b0991e0f55..0000000000000 --- a/node_modules/promise-retry/test/test.js +++ /dev/null @@ -1,263 +0,0 @@ -'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'); - }); - }); -}); diff --git a/node_modules/promzard/package.json b/node_modules/promzard/package.json index 71b0ed439a440..85081356fa9d5 100644 --- a/node_modules/promzard/package.json +++ b/node_modules/promzard/package.json @@ -2,28 +2,29 @@ "author": "GitHub Inc.", "name": "promzard", "description": "prompting wizardly", - "version": "1.0.2", + "version": "4.0.0", "repository": { "url": "git+https://github.com/npm/promzard.git", "type": "git" }, "dependencies": { - "read": "^3.0.1" + "read": "^6.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.1.0", "tap": "^16.3.0" }, "main": "lib/index.js", "scripts": { "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "posttest": "npm run lint" + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "license": "ISC", "files": [ @@ -31,11 +32,11 @@ "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.0", "publish": true }, "tap": { diff --git a/node_modules/proxy-agent-negotiate/dist/index.js b/node_modules/proxy-agent-negotiate/dist/index.js new file mode 100644 index 0000000000000..a6f7219533f50 --- /dev/null +++ b/node_modules/proxy-agent-negotiate/dist/index.js @@ -0,0 +1,35 @@ +export function createNegotiateAuth() { + return async ({ response, scheme }) => { + if (scheme.toLowerCase() !== 'negotiate') { + throw new Error(`Expected Negotiate scheme but got "${scheme}"`); + } + let kerberos; + try { + kerberos = await import('kerberos'); + } + catch { + throw new Error('The "kerberos" package is required for Negotiate proxy authentication. ' + + 'Install it with: npm install kerberos'); + } + const proxyAuthenticate = response.headers['proxy-authenticate'] || ''; + const challengeHeader = Array.isArray(proxyAuthenticate) + ? proxyAuthenticate[0] + : proxyAuthenticate; + const serverToken = typeof challengeHeader === 'string' && challengeHeader.includes(' ') + ? challengeHeader.split(' ').slice(1).join(' ') + : undefined; + const client = await kerberos.initializeClient('HTTP@proxy', { + mechOID: kerberos.GSS_MECH_OID_SPNEGO, + }); + const token = await client.step(serverToken || ''); + if (!token) { + throw new Error('Kerberos client.step() returned no token'); + } + return { + headers: { + 'Proxy-Authorization': `Negotiate ${token}`, + }, + }; + }; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/proxy-agent-negotiate/package.json b/node_modules/proxy-agent-negotiate/package.json new file mode 100644 index 0000000000000..2e5697a36a8a0 --- /dev/null +++ b/node_modules/proxy-agent-negotiate/package.json @@ -0,0 +1,47 @@ +{ + "name": "proxy-agent-negotiate", + "version": "1.1.0", + "type": "module", + "description": "Negotiate/SPNEGO proxy authentication for proxy-agents", + "exports": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "https://github.com/TooTallNate/proxy-agents.git", + "directory": "packages/negotiate" + }, + "keywords": [ + "proxy", + "negotiate", + "kerberos", + "spnego", + "authentication" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "devDependencies": { + "@types/node": "^22.13.0", + "typescript": "^5.1.6", + "tsconfig": "0.0.0" + }, + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "kerberos": "^2.0.0" + }, + "peerDependenciesMeta": { + "kerberos": { + "optional": true + } + }, + "scripts": { + "build": "tsc", + "pack": "node ../../scripts/pack.mjs" + } +} \ No newline at end of file diff --git a/node_modules/read-cmd-shim/package.json b/node_modules/read-cmd-shim/package.json deleted file mode 100644 index 401ee3d7101f1..0000000000000 --- a/node_modules/read-cmd-shim/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "read-cmd-shim", - "version": "4.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": "^3.0.1", - "@npmcli/template-oss": "4.5.1", - "cmd-shim": "^5.0.0", - "rimraf": "^3.0.0", - "tap": "^16.0.1" - }, - "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" - }, - "tap": { - "check-coverage": true, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "repository": { - "type": "git", - "url": "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": "^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.5.1" - } -} diff --git a/node_modules/read-package-json-fast/LICENSE b/node_modules/read-package-json-fast/LICENSE deleted file mode 100644 index 20a4762540923..0000000000000 --- a/node_modules/read-package-json-fast/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/read-package-json-fast/lib/index.js b/node_modules/read-package-json-fast/lib/index.js deleted file mode 100644 index beb089db8d53e..0000000000000 --- a/node_modules/read-package-json-fast/lib/index.js +++ /dev/null @@ -1,141 +0,0 @@ -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 diff --git a/node_modules/read-package-json-fast/package.json b/node_modules/read-package-json-fast/package.json deleted file mode 100644 index 4964bb0a934cb..0000000000000 --- a/node_modules/read-package-json-fast/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "read-package-json-fast", - "version": "3.0.2", - "description": "Like read-package-json, but faster", - "main": "lib/index.js", - "author": "GitHub Inc.", - "license": "ISC", - "scripts": { - "test": "tap", - "snap": "tap", - "lint": "eslint \"**/*.js\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.11.0", - "tap": "^16.3.0" - }, - "dependencies": { - "json-parse-even-better-errors": "^3.0.0", - "npm-normalize-package-bin": "^3.0.0" - }, - "repository": { - "type": "git", - "url": "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.11.0" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/read/dist/commonjs/read.js b/node_modules/read/dist/commonjs/read.js index bab433d8a1155..744a5f3bf4baf 100644 --- a/node_modules/read/dist/commonjs/read.js +++ b/node_modules/read/dist/commonjs/read.js @@ -3,10 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.read = void 0; +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, }) { +async function read({ default: def, input = process.stdin, output = process.stdout, completer, prompt = '', silent, timeout, edit, terminal, replace, history, }) { if (typeof def !== 'undefined' && typeof def !== 'string' && typeof def !== 'number') { @@ -34,7 +34,7 @@ async function read({ default: def, input = process.stdin, output = process.stdo m.pipe(output, { end: false }); output = m; return new Promise((resolve, reject) => { - const rl = (0, readline_1.createInterface)({ input, output, terminal, completer }); + const rl = (0, readline_1.createInterface)({ input, output, terminal, completer, history }); // TODO: add tests for timeout /* c8 ignore start */ const timer = timeout && setTimeout(() => onError(new Error('timed out')), timeout); @@ -91,5 +91,4 @@ async function read({ default: def, input = process.stdin, output = process.stdo /* c8 ignore stop */ }); } -exports.read = read; //# sourceMappingURL=read.js.map \ No newline at end of file diff --git a/node_modules/read/dist/esm/read.js b/node_modules/read/dist/esm/read.js index 716d394c876ac..672be49ae88a7 100644 --- a/node_modules/read/dist/esm/read.js +++ b/node_modules/read/dist/esm/read.js @@ -1,6 +1,6 @@ import Mute from 'mute-stream'; import { createInterface } from 'readline'; -export async function read({ default: def, input = process.stdin, output = process.stdout, completer, prompt = '', silent, timeout, edit, terminal, replace, }) { +export async function read({ default: def, input = process.stdin, output = process.stdout, completer, prompt = '', silent, timeout, edit, terminal, replace, history, }) { if (typeof def !== 'undefined' && typeof def !== 'string' && typeof def !== 'number') { @@ -28,7 +28,7 @@ export async function read({ default: def, input = process.stdin, output = proce m.pipe(output, { end: false }); output = m; return new Promise((resolve, reject) => { - const rl = createInterface({ input, output, terminal, completer }); + const rl = createInterface({ input, output, terminal, completer, history }); // TODO: add tests for timeout /* c8 ignore start */ const timer = timeout && setTimeout(() => onError(new Error('timed out')), timeout); diff --git a/node_modules/read/package.json b/node_modules/read/package.json index 799362f40f152..80049fa3ab9ec 100644 --- a/node_modules/read/package.json +++ b/node_modules/read/package.json @@ -1,6 +1,6 @@ { "name": "read", - "version": "3.0.1", + "version": "6.0.0", "exports": { "./package.json": "./package.json", ".": { @@ -22,66 +22,52 @@ } }, "dependencies": { - "mute-stream": "^1.0.0" + "mute-stream": "^4.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.2", - "@npmcli/template-oss": "4.20.0", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.1.0", "@types/mute-stream": "^0.0.4", - "@types/tap": "^15.0.11", - "@typescript-eslint/parser": "^6.11.0", - "c8": "^8.0.1", - "eslint-import-resolver-typescript": "^3.6.1", - "tap": "^16.3.9", - "ts-node": "^10.9.1", - "tshy": "^1.8.0", - "typescript": "^5.2.2" + "@typescript-eslint/parser": "^8.0.1", + "eslint-import-resolver-typescript": "^4.3.2", + "tshy": "^4.1.1", + "typescript": "^6.0.3" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "author": "GitHub Inc.", "description": "read(1) for node programs", "repository": { "type": "git", - "url": "https://github.com/npm/read.git" + "url": "git+https://github.com/npm/read.git" }, "license": "ISC", "scripts": { "prepare": "tshy", - "pretest": "npm run prepare", - "presnap": "npm run prepare", - "test": "c8 tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test": "node --experimental-strip-types --no-warnings --test './test/*.ts'", + "snap": "node --experimental-strip-types --no-warnings --test --test-update-snapshots './test/*.ts'", + "test:cover": "node --experimental-strip-types --no-warnings --test --experimental-test-coverage './test/*.ts'", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "c8 tap", - "posttest": "npm run lint" + "lintfix": "npm run eslint -- --fix", + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.20.0", + "version": "5.1.0", "publish": true, "typescript": true, + "updateNpm": false, + "testRunner": "node:test", "content": "./scripts/template-oss" }, "main": "./dist/commonjs/read.js", "types": "./dist/commonjs/read.d.ts", - "tap": { - "coverage": false, - "node-arg": [ - "--no-warnings", - "--loader", - "ts-node/esm" - ], - "ts": false, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, "files": [ "dist/" - ] + ], + "module": "./dist/esm/read.js" } diff --git a/node_modules/retry/License b/node_modules/retry/License deleted file mode 100644 index 0b58de379fb30..0000000000000 --- a/node_modules/retry/License +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2011: -Tim Koschützki (tim@debuggable.com) -Felix Geisendörfer (felix@debuggable.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. diff --git a/node_modules/retry/Makefile b/node_modules/retry/Makefile deleted file mode 100644 index 1968d8ff8b07b..0000000000000 --- a/node_modules/retry/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -SHELL := /bin/bash - -release-major: test - npm version major -m "Release %s" - git push - npm publish - -release-minor: test - npm version minor -m "Release %s" - git push - npm publish - -release-patch: test - npm version patch -m "Release %s" - git push - npm publish - -.PHONY: test release-major release-minor release-patch diff --git a/node_modules/retry/equation.gif b/node_modules/retry/equation.gif deleted file mode 100644 index 97107237ba19f..0000000000000 Binary files a/node_modules/retry/equation.gif and /dev/null differ diff --git a/node_modules/retry/example/dns.js b/node_modules/retry/example/dns.js deleted file mode 100644 index 446729b6f9af6..0000000000000 --- a/node_modules/retry/example/dns.js +++ /dev/null @@ -1,31 +0,0 @@ -var dns = require('dns'); -var retry = require('../lib/retry'); - -function faultTolerantResolve(address, cb) { - var opts = { - retries: 2, - factor: 2, - minTimeout: 1 * 1000, - maxTimeout: 2 * 1000, - randomize: true - }; - var operation = retry.operation(opts); - - operation.attempt(function(currentAttempt) { - dns.resolve(address, function(err, addresses) { - if (operation.retry(err)) { - return; - } - - cb(operation.mainError(), operation.errors(), addresses); - }); - }); -} - -faultTolerantResolve('nodejs.org', function(err, errors, addresses) { - console.warn('err:'); - console.log(err); - - console.warn('addresses:'); - console.log(addresses); -}); \ No newline at end of file diff --git a/node_modules/retry/example/stop.js b/node_modules/retry/example/stop.js deleted file mode 100644 index e1ceafeebafc5..0000000000000 --- a/node_modules/retry/example/stop.js +++ /dev/null @@ -1,40 +0,0 @@ -var retry = require('../lib/retry'); - -function attemptAsyncOperation(someInput, cb) { - var opts = { - retries: 2, - factor: 2, - minTimeout: 1 * 1000, - maxTimeout: 2 * 1000, - randomize: true - }; - var operation = retry.operation(opts); - - operation.attempt(function(currentAttempt) { - failingAsyncOperation(someInput, function(err, result) { - - if (err && err.message === 'A fatal error') { - operation.stop(); - return cb(err); - } - - if (operation.retry(err)) { - return; - } - - cb(operation.mainError(), operation.errors(), result); - }); - }); -} - -attemptAsyncOperation('test input', function(err, errors, result) { - console.warn('err:'); - console.log(err); - - console.warn('result:'); - console.log(result); -}); - -function failingAsyncOperation(input, cb) { - return setImmediate(cb.bind(null, new Error('A fatal error'))); -} diff --git a/node_modules/retry/index.js b/node_modules/retry/index.js deleted file mode 100644 index ee62f3a112c28..0000000000000 --- a/node_modules/retry/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/retry'); \ No newline at end of file diff --git a/node_modules/retry/lib/retry.js b/node_modules/retry/lib/retry.js deleted file mode 100644 index dcb5768072794..0000000000000 --- a/node_modules/retry/lib/retry.js +++ /dev/null @@ -1,100 +0,0 @@ -var RetryOperation = require('./retry_operation'); - -exports.operation = function(options) { - var timeouts = exports.timeouts(options); - return new RetryOperation(timeouts, { - forever: options && options.forever, - unref: options && options.unref, - maxRetryTime: options && options.maxRetryTime - }); -}; - -exports.timeouts = function(options) { - if (options instanceof Array) { - return [].concat(options); - } - - var opts = { - retries: 10, - factor: 2, - minTimeout: 1 * 1000, - maxTimeout: Infinity, - randomize: false - }; - for (var key in options) { - opts[key] = options[key]; - } - - if (opts.minTimeout > opts.maxTimeout) { - throw new Error('minTimeout is greater than maxTimeout'); - } - - var timeouts = []; - for (var i = 0; i < opts.retries; i++) { - timeouts.push(this.createTimeout(i, opts)); - } - - if (options && options.forever && !timeouts.length) { - timeouts.push(this.createTimeout(i, opts)); - } - - // sort the array numerically ascending - timeouts.sort(function(a,b) { - return a - b; - }); - - return timeouts; -}; - -exports.createTimeout = function(attempt, opts) { - var random = (opts.randomize) - ? (Math.random() + 1) - : 1; - - var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt)); - timeout = Math.min(timeout, opts.maxTimeout); - - return timeout; -}; - -exports.wrap = function(obj, options, methods) { - if (options instanceof Array) { - methods = options; - options = null; - } - - if (!methods) { - methods = []; - for (var key in obj) { - if (typeof obj[key] === 'function') { - methods.push(key); - } - } - } - - for (var i = 0; i < methods.length; i++) { - var method = methods[i]; - var original = obj[method]; - - obj[method] = function retryWrapper(original) { - var op = exports.operation(options); - var args = Array.prototype.slice.call(arguments, 1); - var callback = args.pop(); - - args.push(function(err) { - if (op.retry(err)) { - return; - } - if (err) { - arguments[0] = op.mainError(); - } - callback.apply(this, arguments); - }); - - op.attempt(function() { - original.apply(obj, args); - }); - }.bind(obj, original); - obj[method].options = options; - } -}; diff --git a/node_modules/retry/lib/retry_operation.js b/node_modules/retry/lib/retry_operation.js deleted file mode 100644 index 1e564696fe7e0..0000000000000 --- a/node_modules/retry/lib/retry_operation.js +++ /dev/null @@ -1,158 +0,0 @@ -function RetryOperation(timeouts, options) { - // Compatibility for the old (timeouts, retryForever) signature - if (typeof options === 'boolean') { - options = { forever: options }; - } - - this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); - this._timeouts = timeouts; - this._options = options || {}; - this._maxRetryTime = options && options.maxRetryTime || Infinity; - this._fn = null; - this._errors = []; - this._attempts = 1; - this._operationTimeout = null; - this._operationTimeoutCb = null; - this._timeout = null; - this._operationStart = null; - - if (this._options.forever) { - this._cachedTimeouts = this._timeouts.slice(0); - } -} -module.exports = RetryOperation; - -RetryOperation.prototype.reset = function() { - this._attempts = 1; - this._timeouts = this._originalTimeouts; -} - -RetryOperation.prototype.stop = function() { - if (this._timeout) { - clearTimeout(this._timeout); - } - - this._timeouts = []; - this._cachedTimeouts = null; -}; - -RetryOperation.prototype.retry = function(err) { - if (this._timeout) { - clearTimeout(this._timeout); - } - - if (!err) { - return false; - } - var currentTime = new Date().getTime(); - if (err && currentTime - this._operationStart >= this._maxRetryTime) { - this._errors.unshift(new Error('RetryOperation timeout occurred')); - return false; - } - - this._errors.push(err); - - var timeout = this._timeouts.shift(); - if (timeout === undefined) { - if (this._cachedTimeouts) { - // retry forever, only keep last error - this._errors.splice(this._errors.length - 1, this._errors.length); - this._timeouts = this._cachedTimeouts.slice(0); - timeout = this._timeouts.shift(); - } else { - return false; - } - } - - var self = this; - var timer = setTimeout(function() { - self._attempts++; - - if (self._operationTimeoutCb) { - self._timeout = setTimeout(function() { - self._operationTimeoutCb(self._attempts); - }, self._operationTimeout); - - if (self._options.unref) { - self._timeout.unref(); - } - } - - self._fn(self._attempts); - }, timeout); - - if (this._options.unref) { - timer.unref(); - } - - return true; -}; - -RetryOperation.prototype.attempt = function(fn, timeoutOps) { - this._fn = fn; - - if (timeoutOps) { - if (timeoutOps.timeout) { - this._operationTimeout = timeoutOps.timeout; - } - if (timeoutOps.cb) { - this._operationTimeoutCb = timeoutOps.cb; - } - } - - var self = this; - if (this._operationTimeoutCb) { - this._timeout = setTimeout(function() { - self._operationTimeoutCb(); - }, self._operationTimeout); - } - - this._operationStart = new Date().getTime(); - - this._fn(this._attempts); -}; - -RetryOperation.prototype.try = function(fn) { - console.log('Using RetryOperation.try() is deprecated'); - this.attempt(fn); -}; - -RetryOperation.prototype.start = function(fn) { - console.log('Using RetryOperation.start() is deprecated'); - this.attempt(fn); -}; - -RetryOperation.prototype.start = RetryOperation.prototype.try; - -RetryOperation.prototype.errors = function() { - return this._errors; -}; - -RetryOperation.prototype.attempts = function() { - return this._attempts; -}; - -RetryOperation.prototype.mainError = function() { - if (this._errors.length === 0) { - return null; - } - - var counts = {}; - var mainError = null; - var mainErrorCount = 0; - - for (var i = 0; i < this._errors.length; i++) { - var error = this._errors[i]; - var message = error.message; - var count = (counts[message] || 0) + 1; - - counts[message] = count; - - if (count >= mainErrorCount) { - mainError = error; - mainErrorCount = count; - } - } - - return mainError; -}; diff --git a/node_modules/retry/package.json b/node_modules/retry/package.json deleted file mode 100644 index 73c7259707aee..0000000000000 --- a/node_modules/retry/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "author": "Tim Koschützki (http://debuggable.com/)", - "name": "retry", - "description": "Abstraction for exponential and custom retry strategies for failed operations.", - "license": "MIT", - "version": "0.12.0", - "homepage": "https://github.com/tim-kos/node-retry", - "repository": { - "type": "git", - "url": "git://github.com/tim-kos/node-retry.git" - }, - "directories": { - "lib": "./lib" - }, - "main": "index", - "engines": { - "node": ">= 4" - }, - "dependencies": {}, - "devDependencies": { - "fake": "0.2.0", - "istanbul": "^0.4.5", - "tape": "^4.8.0" - }, - "scripts": { - "test": "./node_modules/.bin/istanbul cover ./node_modules/tape/bin/tape ./test/integration/*.js", - "release:major": "env SEMANTIC=major npm run release", - "release:minor": "env SEMANTIC=minor npm run release", - "release:patch": "env SEMANTIC=patch npm run release", - "release": "npm version ${SEMANTIC:-patch} -m \"Release %s\" && git push && git push --tags && npm publish" - } -} diff --git a/node_modules/retry/test/common.js b/node_modules/retry/test/common.js deleted file mode 100644 index 224720696ebac..0000000000000 --- a/node_modules/retry/test/common.js +++ /dev/null @@ -1,10 +0,0 @@ -var common = module.exports; -var path = require('path'); - -var rootDir = path.join(__dirname, '..'); -common.dir = { - lib: rootDir + '/lib' -}; - -common.assert = require('assert'); -common.fake = require('fake'); \ No newline at end of file diff --git a/node_modules/retry/test/integration/test-forever.js b/node_modules/retry/test/integration/test-forever.js deleted file mode 100644 index b41307cb529f1..0000000000000 --- a/node_modules/retry/test/integration/test-forever.js +++ /dev/null @@ -1,24 +0,0 @@ -var common = require('../common'); -var assert = common.assert; -var retry = require(common.dir.lib + '/retry'); - -(function testForeverUsesFirstTimeout() { - var operation = retry.operation({ - retries: 0, - minTimeout: 100, - maxTimeout: 100, - forever: true - }); - - operation.attempt(function(numAttempt) { - console.log('>numAttempt', numAttempt); - var err = new Error("foo"); - if (numAttempt == 10) { - operation.stop(); - } - - if (operation.retry(err)) { - return; - } - }); -})(); diff --git a/node_modules/retry/test/integration/test-retry-operation.js b/node_modules/retry/test/integration/test-retry-operation.js deleted file mode 100644 index e351bb683ed44..0000000000000 --- a/node_modules/retry/test/integration/test-retry-operation.js +++ /dev/null @@ -1,258 +0,0 @@ -var common = require('../common'); -var assert = common.assert; -var fake = common.fake.create(); -var retry = require(common.dir.lib + '/retry'); - -(function testReset() { - var error = new Error('some error'); - var operation = retry.operation([1, 2, 3]); - var attempts = 0; - - var finalCallback = fake.callback('finalCallback'); - fake.expectAnytime(finalCallback); - - var expectedFinishes = 1; - var finishes = 0; - - var fn = function() { - operation.attempt(function(currentAttempt) { - attempts++; - assert.equal(currentAttempt, attempts); - if (operation.retry(error)) { - return; - } - - finishes++ - assert.equal(expectedFinishes, finishes); - assert.strictEqual(attempts, 4); - assert.strictEqual(operation.attempts(), attempts); - assert.strictEqual(operation.mainError(), error); - - if (finishes < 2) { - attempts = 0; - expectedFinishes++; - operation.reset(); - fn() - } else { - finalCallback(); - } - }); - }; - - fn(); -})(); - -(function testErrors() { - var operation = retry.operation(); - - var error = new Error('some error'); - var error2 = new Error('some other error'); - operation._errors.push(error); - operation._errors.push(error2); - - assert.deepEqual(operation.errors(), [error, error2]); -})(); - -(function testMainErrorReturnsMostFrequentError() { - var operation = retry.operation(); - var error = new Error('some error'); - var error2 = new Error('some other error'); - - operation._errors.push(error); - operation._errors.push(error2); - operation._errors.push(error); - - assert.strictEqual(operation.mainError(), error); -})(); - -(function testMainErrorReturnsLastErrorOnEqualCount() { - var operation = retry.operation(); - var error = new Error('some error'); - var error2 = new Error('some other error'); - - operation._errors.push(error); - operation._errors.push(error2); - - assert.strictEqual(operation.mainError(), error2); -})(); - -(function testAttempt() { - var operation = retry.operation(); - var fn = new Function(); - - var timeoutOpts = { - timeout: 1, - cb: function() {} - }; - operation.attempt(fn, timeoutOpts); - - assert.strictEqual(fn, operation._fn); - assert.strictEqual(timeoutOpts.timeout, operation._operationTimeout); - assert.strictEqual(timeoutOpts.cb, operation._operationTimeoutCb); -})(); - -(function testRetry() { - var error = new Error('some error'); - var operation = retry.operation([1, 2, 3]); - var attempts = 0; - - var finalCallback = fake.callback('finalCallback'); - fake.expectAnytime(finalCallback); - - var fn = function() { - operation.attempt(function(currentAttempt) { - attempts++; - assert.equal(currentAttempt, attempts); - if (operation.retry(error)) { - return; - } - - assert.strictEqual(attempts, 4); - assert.strictEqual(operation.attempts(), attempts); - assert.strictEqual(operation.mainError(), error); - finalCallback(); - }); - }; - - fn(); -})(); - -(function testRetryForever() { - var error = new Error('some error'); - var operation = retry.operation({ retries: 3, forever: true }); - var attempts = 0; - - var finalCallback = fake.callback('finalCallback'); - fake.expectAnytime(finalCallback); - - var fn = function() { - operation.attempt(function(currentAttempt) { - attempts++; - assert.equal(currentAttempt, attempts); - if (attempts !== 6 && operation.retry(error)) { - return; - } - - assert.strictEqual(attempts, 6); - assert.strictEqual(operation.attempts(), attempts); - assert.strictEqual(operation.mainError(), error); - finalCallback(); - }); - }; - - fn(); -})(); - -(function testRetryForeverNoRetries() { - var error = new Error('some error'); - var delay = 50 - var operation = retry.operation({ - retries: null, - forever: true, - minTimeout: delay, - maxTimeout: delay - }); - - var attempts = 0; - var startTime = new Date().getTime(); - - var finalCallback = fake.callback('finalCallback'); - fake.expectAnytime(finalCallback); - - var fn = function() { - operation.attempt(function(currentAttempt) { - attempts++; - assert.equal(currentAttempt, attempts); - if (attempts !== 4 && operation.retry(error)) { - return; - } - - var endTime = new Date().getTime(); - var minTime = startTime + (delay * 3); - var maxTime = minTime + 20 // add a little headroom for code execution time - assert(endTime >= minTime) - assert(endTime < maxTime) - assert.strictEqual(attempts, 4); - assert.strictEqual(operation.attempts(), attempts); - assert.strictEqual(operation.mainError(), error); - finalCallback(); - }); - }; - - fn(); -})(); - -(function testStop() { - var error = new Error('some error'); - var operation = retry.operation([1, 2, 3]); - var attempts = 0; - - var finalCallback = fake.callback('finalCallback'); - fake.expectAnytime(finalCallback); - - var fn = function() { - operation.attempt(function(currentAttempt) { - attempts++; - assert.equal(currentAttempt, attempts); - - if (attempts === 2) { - operation.stop(); - - assert.strictEqual(attempts, 2); - assert.strictEqual(operation.attempts(), attempts); - assert.strictEqual(operation.mainError(), error); - finalCallback(); - } - - if (operation.retry(error)) { - return; - } - }); - }; - - fn(); -})(); - -(function testMaxRetryTime() { - var error = new Error('some error'); - var maxRetryTime = 30; - var operation = retry.operation({ - minTimeout: 1, - maxRetryTime: maxRetryTime - }); - var attempts = 0; - - var finalCallback = fake.callback('finalCallback'); - fake.expectAnytime(finalCallback); - - var longAsyncFunction = function (wait, callback){ - setTimeout(callback, wait); - }; - - var fn = function() { - var startTime = new Date().getTime(); - operation.attempt(function(currentAttempt) { - attempts++; - assert.equal(currentAttempt, attempts); - - if (attempts !== 2) { - if (operation.retry(error)) { - return; - } - } else { - var curTime = new Date().getTime(); - longAsyncFunction(maxRetryTime - (curTime - startTime - 1), function(){ - if (operation.retry(error)) { - assert.fail('timeout should be occurred'); - return; - } - - assert.strictEqual(operation.mainError(), error); - finalCallback(); - }); - } - }); - }; - - fn(); -})(); diff --git a/node_modules/retry/test/integration/test-retry-wrap.js b/node_modules/retry/test/integration/test-retry-wrap.js deleted file mode 100644 index 3d2b6bfa6436d..0000000000000 --- a/node_modules/retry/test/integration/test-retry-wrap.js +++ /dev/null @@ -1,101 +0,0 @@ -var common = require('../common'); -var assert = common.assert; -var fake = common.fake.create(); -var retry = require(common.dir.lib + '/retry'); - -function getLib() { - return { - fn1: function() {}, - fn2: function() {}, - fn3: function() {} - }; -} - -(function wrapAll() { - var lib = getLib(); - retry.wrap(lib); - assert.equal(lib.fn1.name, 'bound retryWrapper'); - assert.equal(lib.fn2.name, 'bound retryWrapper'); - assert.equal(lib.fn3.name, 'bound retryWrapper'); -}()); - -(function wrapAllPassOptions() { - var lib = getLib(); - retry.wrap(lib, {retries: 2}); - assert.equal(lib.fn1.name, 'bound retryWrapper'); - assert.equal(lib.fn2.name, 'bound retryWrapper'); - assert.equal(lib.fn3.name, 'bound retryWrapper'); - assert.equal(lib.fn1.options.retries, 2); - assert.equal(lib.fn2.options.retries, 2); - assert.equal(lib.fn3.options.retries, 2); -}()); - -(function wrapDefined() { - var lib = getLib(); - retry.wrap(lib, ['fn2', 'fn3']); - assert.notEqual(lib.fn1.name, 'bound retryWrapper'); - assert.equal(lib.fn2.name, 'bound retryWrapper'); - assert.equal(lib.fn3.name, 'bound retryWrapper'); -}()); - -(function wrapDefinedAndPassOptions() { - var lib = getLib(); - retry.wrap(lib, {retries: 2}, ['fn2', 'fn3']); - assert.notEqual(lib.fn1.name, 'bound retryWrapper'); - assert.equal(lib.fn2.name, 'bound retryWrapper'); - assert.equal(lib.fn3.name, 'bound retryWrapper'); - assert.equal(lib.fn2.options.retries, 2); - assert.equal(lib.fn3.options.retries, 2); -}()); - -(function runWrappedWithoutError() { - var callbackCalled; - var lib = {method: function(a, b, callback) { - assert.equal(a, 1); - assert.equal(b, 2); - assert.equal(typeof callback, 'function'); - callback(); - }}; - retry.wrap(lib); - lib.method(1, 2, function() { - callbackCalled = true; - }); - assert.ok(callbackCalled); -}()); - -(function runWrappedSeveralWithoutError() { - var callbacksCalled = 0; - var lib = { - fn1: function (a, callback) { - assert.equal(a, 1); - assert.equal(typeof callback, 'function'); - callback(); - }, - fn2: function (a, callback) { - assert.equal(a, 2); - assert.equal(typeof callback, 'function'); - callback(); - } - }; - retry.wrap(lib, {}, ['fn1', 'fn2']); - lib.fn1(1, function() { - callbacksCalled++; - }); - lib.fn2(2, function() { - callbacksCalled++; - }); - assert.equal(callbacksCalled, 2); -}()); - -(function runWrappedWithError() { - var callbackCalled; - var lib = {method: function(callback) { - callback(new Error('Some error')); - }}; - retry.wrap(lib, {retries: 1}); - lib.method(function(err) { - callbackCalled = true; - assert.ok(err instanceof Error); - }); - assert.ok(!callbackCalled); -}()); diff --git a/node_modules/retry/test/integration/test-timeouts.js b/node_modules/retry/test/integration/test-timeouts.js deleted file mode 100644 index 7206b0fb0b01d..0000000000000 --- a/node_modules/retry/test/integration/test-timeouts.js +++ /dev/null @@ -1,69 +0,0 @@ -var common = require('../common'); -var assert = common.assert; -var retry = require(common.dir.lib + '/retry'); - -(function testDefaultValues() { - var timeouts = retry.timeouts(); - - assert.equal(timeouts.length, 10); - assert.equal(timeouts[0], 1000); - assert.equal(timeouts[1], 2000); - assert.equal(timeouts[2], 4000); -})(); - -(function testDefaultValuesWithRandomize() { - var minTimeout = 5000; - var timeouts = retry.timeouts({ - minTimeout: minTimeout, - randomize: true - }); - - assert.equal(timeouts.length, 10); - assert.ok(timeouts[0] > minTimeout); - assert.ok(timeouts[1] > timeouts[0]); - assert.ok(timeouts[2] > timeouts[1]); -})(); - -(function testPassedTimeoutsAreUsed() { - var timeoutsArray = [1000, 2000, 3000]; - var timeouts = retry.timeouts(timeoutsArray); - assert.deepEqual(timeouts, timeoutsArray); - assert.notStrictEqual(timeouts, timeoutsArray); -})(); - -(function testTimeoutsAreWithinBoundaries() { - var minTimeout = 1000; - var maxTimeout = 10000; - var timeouts = retry.timeouts({ - minTimeout: minTimeout, - maxTimeout: maxTimeout - }); - for (var i = 0; i < timeouts; i++) { - assert.ok(timeouts[i] >= minTimeout); - assert.ok(timeouts[i] <= maxTimeout); - } -})(); - -(function testTimeoutsAreIncremental() { - var timeouts = retry.timeouts(); - var lastTimeout = timeouts[0]; - for (var i = 0; i < timeouts; i++) { - assert.ok(timeouts[i] > lastTimeout); - lastTimeout = timeouts[i]; - } -})(); - -(function testTimeoutsAreIncrementalForFactorsLessThanOne() { - var timeouts = retry.timeouts({ - retries: 3, - factor: 0.5 - }); - - var expected = [250, 500, 1000]; - assert.deepEqual(expected, timeouts); -})(); - -(function testRetries() { - var timeouts = retry.timeouts({retries: 2}); - assert.strictEqual(timeouts.length, 2); -})(); diff --git a/node_modules/semver/bin/semver.js b/node_modules/semver/bin/semver.js index f62b566f74bc6..9ae8aadb95fbd 100755 --- a/node_modules/semver/bin/semver.js +++ b/node_modules/semver/bin/semver.js @@ -3,6 +3,8 @@ // Exits successfully and prints matching version(s) if // any supplied version is valid and passes all tests. +'use strict' + const argv = process.argv.slice(2) let versions = [] @@ -44,6 +46,7 @@ const main = () => { a = a.slice(0, indexOfEqualSign) argv.unshift(value) } + switch (a) { case '-rv': case '-rev': case '--rev': case '--reverse': reverse = true @@ -58,14 +61,10 @@ const main = () => { versions.push(argv.shift()) break case '-i': case '--inc': case '--increment': - switch (argv[0]) { - case 'major': case 'minor': case 'patch': case 'prerelease': - case 'premajor': case 'preminor': case 'prepatch': - inc = argv.shift() - break - default: - inc = 'patch' - break + if (semver.RELEASE_TYPES.includes(argv[0]) || (argv[0] === 'release')) { + inc = { value: argv.shift(), maybeErrantValue: null, option: a } + } else { + inc = { value: 'patch', maybeErrantValue: argv[0], option: a } } break case '--preid': @@ -99,10 +98,18 @@ const main = () => { options = parseOptions({ loose, includePrerelease, rtl }) + if ( + inc && + versions.includes(inc.maybeErrantValue) && + !semver.valid(inc.maybeErrantValue, options) + ) { + console.warn(`Invalid value for ${inc.option}; defaulting to 'patch'. This may become a failure in future major versions.`) + } + versions = versions.map((v) => { return coerce ? (semver.coerce(v, options) || { version: v }).version : v }).filter((v) => { - return semver.valid(v) + return semver.valid(v, options) }) if (!versions.length) { return fail() @@ -122,7 +129,7 @@ const main = () => { versions .sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options)) .map(v => semver.clean(v, options)) - .map(v => inc ? semver.inc(v, inc, options, identifier, identifierBase) : v) + .map(v => inc ? semver.inc(v, inc.value, options, identifier, identifierBase) : v) .forEach(v => console.log(v)) } @@ -149,7 +156,7 @@ Options: -i --increment [] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, - prepatch, or prerelease. Default level is 'patch'. + prepatch, prerelease, or release. Default level is 'patch'. Only one version may be specified. --preid diff --git a/node_modules/semver/classes/comparator.js b/node_modules/semver/classes/comparator.js index 3d39c0eef7802..647c1f0976fd7 100644 --- a/node_modules/semver/classes/comparator.js +++ b/node_modules/semver/classes/comparator.js @@ -1,3 +1,5 @@ +'use strict' + const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { diff --git a/node_modules/semver/classes/index.js b/node_modules/semver/classes/index.js index 5e3f5c9b19cef..91c24ec4a7264 100644 --- a/node_modules/semver/classes/index.js +++ b/node_modules/semver/classes/index.js @@ -1,3 +1,5 @@ +'use strict' + module.exports = { SemVer: require('./semver.js'), Range: require('./range.js'), diff --git a/node_modules/semver/classes/range.js b/node_modules/semver/classes/range.js index 117b45a2b8e05..766d505a22691 100644 --- a/node_modules/semver/classes/range.js +++ b/node_modules/semver/classes/range.js @@ -1,3 +1,7 @@ +'use strict' + +const SPACE_CHARACTERS = /\s+/g + // hoisted class for cyclic dependency class Range { constructor (range, options) { @@ -18,7 +22,7 @@ class Range { // just put it in the set and return this.raw = range.value this.set = [[range]] - this.format() + this.formatted = undefined return this } @@ -29,10 +33,7 @@ class Range { // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. - this.raw = range - .trim() - .split(/\s+/) - .join(' ') + this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') // First, split on || this.set = this.raw @@ -66,14 +67,29 @@ class Range { } } - this.format() + this.formatted = undefined + } + + get range () { + if (this.formatted === undefined) { + this.formatted = '' + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += '||' + } + const comps = this.set[i] + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += ' ' + } + this.formatted += comps[k].toString().trim() + } + } + } + return this.formatted } format () { - this.range = this.set - .map((comps) => comps.join(' ').trim()) - .join('||') - .trim() return this.range } @@ -82,6 +98,9 @@ class Range { } parseRange (range) { + // strip build metadata so it can't bleed into the version + range = range.replace(BUILDSTRIPRE, '') + // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = @@ -207,6 +226,7 @@ const debug = require('../internal/debug') const SemVer = require('./semver') const { safeRe: re, + src, t, comparatorTrimReplace, tildeTrimReplace, @@ -214,6 +234,9 @@ const { } = require('../internal/re') const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants') +// unbounded global build-metadata stripper used by parseRange +const BUILDSTRIPRE = new RegExp(src[t.BUILD], 'g') + const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' @@ -239,6 +262,7 @@ const isSatisfiable = (comparators, options) => { // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { + comp = comp.replace(re[t.BUILD], '') debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) @@ -253,6 +277,11 @@ const parseComparator = (comp, options) => { const isX = id => !id || id.toLowerCase() === 'x' || id === '*' +const invalidXRangeOrder = (M, m, p) => ( + (isX(M) && !isX(m)) || + (isX(m) && p && !isX(p)) +) + // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 @@ -349,10 +378,10 @@ const replaceCaret = (comp, options) => { if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0` + } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0` + } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p @@ -378,6 +407,10 @@ const replaceXRange = (comp, options) => { const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) + if (invalidXRangeOrder(M, m, p)) { + return comp + } + const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) diff --git a/node_modules/semver/classes/semver.js b/node_modules/semver/classes/semver.js index 13e66ce441569..5438127208dbf 100644 --- a/node_modules/semver/classes/semver.js +++ b/node_modules/semver/classes/semver.js @@ -1,16 +1,34 @@ +'use strict' + const debug = require('../internal/debug') const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') const { safeRe: re, t } = require('../internal/re') const parseOptions = require('../internal/parse-options') const { compareIdentifiers } = require('../internal/identifiers') + +const isPrereleaseIdentifier = (prerelease, identifier) => { + const identifiers = identifier.split('.') + if (identifiers.length > prerelease.length) { + return false + } + + for (let i = 0; i < identifiers.length; i++) { + if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) { + return false + } + } + + return true +} + class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { + version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version @@ -109,11 +127,25 @@ class SemVer { other = new SemVer(other, this.options) } - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) + if (this.major < other.major) { + return -1 + } + if (this.major > other.major) { + return 1 + } + if (this.minor < other.minor) { + return -1 + } + if (this.minor > other.minor) { + return 1 + } + if (this.patch < other.patch) { + return -1 + } + if (this.patch > other.patch) { + return 1 + } + return 0 } comparePre (other) { @@ -176,6 +208,19 @@ class SemVer { // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { + if (release.startsWith('pre')) { + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + // Avoid an invalid semver results + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]) + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`) + } + } + } + switch (release) { case 'premajor': this.prerelease.length = 0 @@ -206,6 +251,12 @@ class SemVer { } this.inc('pre', identifier, identifierBase) break + case 'release': + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`) + } + this.prerelease.length = 0 + break case 'major': // If this is a pre-major version, bump up to the same major version. @@ -249,10 +300,6 @@ class SemVer { case 'pre': { const base = Number(identifierBase) ? 1 : 0 - if (!identifier && identifierBase === false) { - throw new Error('invalid increment argument: identifier is empty') - } - if (this.prerelease.length === 0) { this.prerelease = [base] } else { @@ -278,8 +325,9 @@ class SemVer { if (identifierBase === false) { prerelease = [identifier] } - if (compareIdentifiers(this.prerelease[0], identifier) === 0) { - if (isNaN(this.prerelease[1])) { + if (isPrereleaseIdentifier(this.prerelease, identifier)) { + const prereleaseBase = this.prerelease[identifier.split('.').length] + if (isNaN(prereleaseBase)) { this.prerelease = prerelease } } else { diff --git a/node_modules/semver/functions/clean.js b/node_modules/semver/functions/clean.js index 811fe6b82cb73..79703d6316617 100644 --- a/node_modules/semver/functions/clean.js +++ b/node_modules/semver/functions/clean.js @@ -1,3 +1,5 @@ +'use strict' + const parse = require('./parse') const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) diff --git a/node_modules/semver/functions/cmp.js b/node_modules/semver/functions/cmp.js index 40119094747dd..77487dcaac5f5 100644 --- a/node_modules/semver/functions/cmp.js +++ b/node_modules/semver/functions/cmp.js @@ -1,3 +1,5 @@ +'use strict' + const eq = require('./eq') const neq = require('./neq') const gt = require('./gt') diff --git a/node_modules/semver/functions/coerce.js b/node_modules/semver/functions/coerce.js index b378dcea4e5a7..cfe027599516f 100644 --- a/node_modules/semver/functions/coerce.js +++ b/node_modules/semver/functions/coerce.js @@ -1,3 +1,5 @@ +'use strict' + const SemVer = require('../classes/semver') const parse = require('./parse') const { safeRe: re, t } = require('../internal/re') diff --git a/node_modules/semver/functions/compare-build.js b/node_modules/semver/functions/compare-build.js index 9eb881bef0fdd..99157cf3d105e 100644 --- a/node_modules/semver/functions/compare-build.js +++ b/node_modules/semver/functions/compare-build.js @@ -1,3 +1,5 @@ +'use strict' + const SemVer = require('../classes/semver') const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) diff --git a/node_modules/semver/functions/compare-loose.js b/node_modules/semver/functions/compare-loose.js index 4881fbe00250c..75316346a81cb 100644 --- a/node_modules/semver/functions/compare-loose.js +++ b/node_modules/semver/functions/compare-loose.js @@ -1,3 +1,5 @@ +'use strict' + const compare = require('./compare') const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose diff --git a/node_modules/semver/functions/compare.js b/node_modules/semver/functions/compare.js index 748b7afa514a9..63d8090c626ce 100644 --- a/node_modules/semver/functions/compare.js +++ b/node_modules/semver/functions/compare.js @@ -1,3 +1,5 @@ +'use strict' + const SemVer = require('../classes/semver') const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) diff --git a/node_modules/semver/functions/diff.js b/node_modules/semver/functions/diff.js index fc224e302c0e4..c99ab51cc5716 100644 --- a/node_modules/semver/functions/diff.js +++ b/node_modules/semver/functions/diff.js @@ -1,3 +1,5 @@ +'use strict' + const parse = require('./parse.js') const diff = (version1, version2) => { @@ -27,20 +29,13 @@ const diff = (version1, version2) => { return 'major' } - // Otherwise it can be determined by checking the high version - - if (highVersion.patch) { - // anything higher than a patch bump would result in the wrong version + // If the main part has no difference + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return 'minor' + } return 'patch' } - - if (highVersion.minor) { - // anything higher than a minor bump would result in the wrong version - return 'minor' - } - - // bumping major/minor/patch all have same result - return 'major' } // add the `pre` prefix if we are going to a prerelease version @@ -58,7 +53,7 @@ const diff = (version1, version2) => { return prefix + 'patch' } - // high and low are preleases + // high and low are prereleases return 'prerelease' } diff --git a/node_modules/semver/functions/eq.js b/node_modules/semver/functions/eq.js index 271fed976f34a..5f0eead1169fe 100644 --- a/node_modules/semver/functions/eq.js +++ b/node_modules/semver/functions/eq.js @@ -1,3 +1,5 @@ +'use strict' + const compare = require('./compare') const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq diff --git a/node_modules/semver/functions/gt.js b/node_modules/semver/functions/gt.js index d9b2156d8b56c..84a57ddff50a0 100644 --- a/node_modules/semver/functions/gt.js +++ b/node_modules/semver/functions/gt.js @@ -1,3 +1,5 @@ +'use strict' + const compare = require('./compare') const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt diff --git a/node_modules/semver/functions/gte.js b/node_modules/semver/functions/gte.js index 5aeaa634707a0..7c52bdf2529ad 100644 --- a/node_modules/semver/functions/gte.js +++ b/node_modules/semver/functions/gte.js @@ -1,3 +1,5 @@ +'use strict' + const compare = require('./compare') const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte diff --git a/node_modules/semver/functions/inc.js b/node_modules/semver/functions/inc.js index 7670b1bea1a49..ff999e9d04d7f 100644 --- a/node_modules/semver/functions/inc.js +++ b/node_modules/semver/functions/inc.js @@ -1,3 +1,5 @@ +'use strict' + const SemVer = require('../classes/semver') const inc = (version, release, options, identifier, identifierBase) => { diff --git a/node_modules/semver/functions/lt.js b/node_modules/semver/functions/lt.js index b440ab7d4212d..2fb32a0e63c9a 100644 --- a/node_modules/semver/functions/lt.js +++ b/node_modules/semver/functions/lt.js @@ -1,3 +1,5 @@ +'use strict' + const compare = require('./compare') const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt diff --git a/node_modules/semver/functions/lte.js b/node_modules/semver/functions/lte.js index 6dcc956505584..da9ee8f4e4404 100644 --- a/node_modules/semver/functions/lte.js +++ b/node_modules/semver/functions/lte.js @@ -1,3 +1,5 @@ +'use strict' + const compare = require('./compare') const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte diff --git a/node_modules/semver/functions/major.js b/node_modules/semver/functions/major.js index 4283165e9d271..e6d08dc20cf20 100644 --- a/node_modules/semver/functions/major.js +++ b/node_modules/semver/functions/major.js @@ -1,3 +1,5 @@ +'use strict' + const SemVer = require('../classes/semver') const major = (a, loose) => new SemVer(a, loose).major module.exports = major diff --git a/node_modules/semver/functions/minor.js b/node_modules/semver/functions/minor.js index 57b3455f827ba..9e70ffda19223 100644 --- a/node_modules/semver/functions/minor.js +++ b/node_modules/semver/functions/minor.js @@ -1,3 +1,5 @@ +'use strict' + const SemVer = require('../classes/semver') const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor diff --git a/node_modules/semver/functions/neq.js b/node_modules/semver/functions/neq.js index f944c01576973..84326b7733610 100644 --- a/node_modules/semver/functions/neq.js +++ b/node_modules/semver/functions/neq.js @@ -1,3 +1,5 @@ +'use strict' + const compare = require('./compare') const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq diff --git a/node_modules/semver/functions/parse.js b/node_modules/semver/functions/parse.js index 459b3b17375c8..d544d33a7e93c 100644 --- a/node_modules/semver/functions/parse.js +++ b/node_modules/semver/functions/parse.js @@ -1,3 +1,5 @@ +'use strict' + const SemVer = require('../classes/semver') const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { diff --git a/node_modules/semver/functions/patch.js b/node_modules/semver/functions/patch.js index 63afca2524fca..7675162f1742a 100644 --- a/node_modules/semver/functions/patch.js +++ b/node_modules/semver/functions/patch.js @@ -1,3 +1,5 @@ +'use strict' + const SemVer = require('../classes/semver') const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch diff --git a/node_modules/semver/functions/prerelease.js b/node_modules/semver/functions/prerelease.js index 06aa13248ae65..b8fe1db5049a2 100644 --- a/node_modules/semver/functions/prerelease.js +++ b/node_modules/semver/functions/prerelease.js @@ -1,3 +1,5 @@ +'use strict' + const parse = require('./parse') const prerelease = (version, options) => { const parsed = parse(version, options) diff --git a/node_modules/semver/functions/rcompare.js b/node_modules/semver/functions/rcompare.js index 0ac509e79dc8c..8e1c222b2ffc2 100644 --- a/node_modules/semver/functions/rcompare.js +++ b/node_modules/semver/functions/rcompare.js @@ -1,3 +1,5 @@ +'use strict' + const compare = require('./compare') const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare diff --git a/node_modules/semver/functions/rsort.js b/node_modules/semver/functions/rsort.js index 82404c5cfe026..5d3d20096844b 100644 --- a/node_modules/semver/functions/rsort.js +++ b/node_modules/semver/functions/rsort.js @@ -1,3 +1,5 @@ +'use strict' + const compareBuild = require('./compare-build') const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort diff --git a/node_modules/semver/functions/satisfies.js b/node_modules/semver/functions/satisfies.js index 50af1c199b6ca..a0264a222ac82 100644 --- a/node_modules/semver/functions/satisfies.js +++ b/node_modules/semver/functions/satisfies.js @@ -1,3 +1,5 @@ +'use strict' + const Range = require('../classes/range') const satisfies = (version, range, options) => { try { diff --git a/node_modules/semver/functions/sort.js b/node_modules/semver/functions/sort.js index 4d10917aba8e5..edb24b1dc3324 100644 --- a/node_modules/semver/functions/sort.js +++ b/node_modules/semver/functions/sort.js @@ -1,3 +1,5 @@ +'use strict' + const compareBuild = require('./compare-build') const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort diff --git a/node_modules/semver/functions/truncate.js b/node_modules/semver/functions/truncate.js new file mode 100644 index 0000000000000..8314e4e922a41 --- /dev/null +++ b/node_modules/semver/functions/truncate.js @@ -0,0 +1,48 @@ +'use strict' + +const parse = require('./parse') +const constants = require('../internal/constants') +const SemVer = require('../classes/semver') + +const truncate = (version, truncation, options) => { + if (!constants.RELEASE_TYPES.includes(truncation)) { + return null + } + + const clonedVersion = cloneInputVersion(version, options) + return clonedVersion && doTruncation(clonedVersion, truncation) +} + +const cloneInputVersion = (version, options) => { + const versionStringToParse = ( + version instanceof SemVer ? version.version : version + ) + + return parse(versionStringToParse, options) +} + +const doTruncation = (version, truncation) => { + if (isPrerelease(truncation)) { + return version.version + } + + version.prerelease = [] + + switch (truncation) { + case 'major': + version.minor = 0 + version.patch = 0 + break + case 'minor': + version.patch = 0 + break + } + + return version.format() +} + +const isPrerelease = (type) => { + return type.startsWith('pre') +} + +module.exports = truncate diff --git a/node_modules/semver/functions/valid.js b/node_modules/semver/functions/valid.js index f27bae10731c0..0db67edcb5952 100644 --- a/node_modules/semver/functions/valid.js +++ b/node_modules/semver/functions/valid.js @@ -1,3 +1,5 @@ +'use strict' + const parse = require('./parse') const valid = (version, options) => { const v = parse(version, options) diff --git a/node_modules/semver/index.js b/node_modules/semver/index.js index 86d42ac16a840..bc1f608ceaad3 100644 --- a/node_modules/semver/index.js +++ b/node_modules/semver/index.js @@ -1,3 +1,5 @@ +'use strict' + // just pre-load all the stuff that index.js lazily exports const internalRe = require('./internal/re') const constants = require('./internal/constants') @@ -26,6 +28,7 @@ const gte = require('./functions/gte') const lte = require('./functions/lte') const cmp = require('./functions/cmp') const coerce = require('./functions/coerce') +const truncate = require('./functions/truncate') const Comparator = require('./classes/comparator') const Range = require('./classes/range') const satisfies = require('./functions/satisfies') @@ -64,6 +67,7 @@ module.exports = { lte, cmp, coerce, + truncate, Comparator, Range, satisfies, diff --git a/node_modules/semver/internal/constants.js b/node_modules/semver/internal/constants.js index 94be1c570277a..6d1db9154331d 100644 --- a/node_modules/semver/internal/constants.js +++ b/node_modules/semver/internal/constants.js @@ -1,3 +1,5 @@ +'use strict' + // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' diff --git a/node_modules/semver/internal/debug.js b/node_modules/semver/internal/debug.js index 1c00e1369aa2a..20d1e9dceea90 100644 --- a/node_modules/semver/internal/debug.js +++ b/node_modules/semver/internal/debug.js @@ -1,3 +1,5 @@ +'use strict' + const debug = ( typeof process === 'object' && process.env && diff --git a/node_modules/semver/internal/identifiers.js b/node_modules/semver/internal/identifiers.js index e612d0a3d8361..d053472dd58b3 100644 --- a/node_modules/semver/internal/identifiers.js +++ b/node_modules/semver/internal/identifiers.js @@ -1,5 +1,11 @@ +'use strict' + const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { + if (typeof a === 'number' && typeof b === 'number') { + return a === b ? 0 : a < b ? -1 : 1 + } + const anum = numeric.test(a) const bnum = numeric.test(b) diff --git a/node_modules/semver/internal/lrucache.js b/node_modules/semver/internal/lrucache.js index 6d89ec948d0f1..b8bf5262a0505 100644 --- a/node_modules/semver/internal/lrucache.js +++ b/node_modules/semver/internal/lrucache.js @@ -1,3 +1,5 @@ +'use strict' + class LRUCache { constructor () { this.max = 1000 diff --git a/node_modules/semver/internal/parse-options.js b/node_modules/semver/internal/parse-options.js index 10d64ce06d3c5..5295454130d42 100644 --- a/node_modules/semver/internal/parse-options.js +++ b/node_modules/semver/internal/parse-options.js @@ -1,3 +1,5 @@ +'use strict' + // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) diff --git a/node_modules/semver/internal/re.js b/node_modules/semver/internal/re.js index fd8920e7baa71..2ec2c22c972d3 100644 --- a/node_modules/semver/internal/re.js +++ b/node_modules/semver/internal/re.js @@ -1,3 +1,5 @@ +'use strict' + const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, @@ -10,6 +12,7 @@ exports = module.exports = {} const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] +const safeSrc = exports.safeSrc = [] const t = exports.t = {} let R = 0 @@ -42,6 +45,7 @@ const createToken = (name, value, isGlobal) => { debug(name, index, value) t[name] = index src[index] = value + safeSrc[index] = safe re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } @@ -74,12 +78,14 @@ createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. +// Non-numeric identifiers include numeric identifiers but can be longer. +// Therefore non-numeric identifiers must go first. -createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`) +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIER]})`) -createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`) +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version @@ -130,7 +136,7 @@ createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Note that "x.x" is a valid xRange identifier, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) diff --git a/node_modules/semver/package.json b/node_modules/semver/package.json index cb8def45184df..ddedbf7bdaba6 100644 --- a/node_modules/semver/package.json +++ b/node_modules/semver/package.json @@ -1,20 +1,21 @@ { "name": "semver", - "version": "7.6.2", + "version": "7.8.4", "description": "The semantic version parser used by npm.", "main": "index.js", "scripts": { "test": "tap", "snap": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.0.0", "benchmark": "^2.1.4", "tap": "^16.0.0" }, @@ -51,7 +52,7 @@ "author": "GitHub Inc.", "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.0.0", "engines": ">=10", "distPaths": [ "classes/", diff --git a/node_modules/semver/preload.js b/node_modules/semver/preload.js index 947cd4f7917ff..e6c47b9b051d9 100644 --- a/node_modules/semver/preload.js +++ b/node_modules/semver/preload.js @@ -1,2 +1,4 @@ +'use strict' + // XXX remove in v8 or beyond module.exports = require('./index.js') diff --git a/node_modules/semver/range.bnf b/node_modules/semver/range.bnf index d4c6ae0d76c9a..a7a4bc3783112 100644 --- a/node_modules/semver/range.bnf +++ b/node_modules/semver/range.bnf @@ -10,7 +10,8 @@ nr ::= '0' | [1-9] ( [0-9] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ +pre ::= prepart ( '.' prepart ) * +prepart ::= nr | alphanumid +build ::= buildid ( '.' buildid ) * +alphanumid ::= ( [0-9] ) * [A-Za-z-] [-0-9A-Za-z] * +buildid ::= [-0-9A-Za-z]+ diff --git a/node_modules/semver/ranges/gtr.js b/node_modules/semver/ranges/gtr.js index db7e35599dd56..0e7601f693554 100644 --- a/node_modules/semver/ranges/gtr.js +++ b/node_modules/semver/ranges/gtr.js @@ -1,3 +1,5 @@ +'use strict' + // Determine if version is greater than all the versions possible in the range. const outside = require('./outside') const gtr = (version, range, options) => outside(version, range, '>', options) diff --git a/node_modules/semver/ranges/intersects.js b/node_modules/semver/ranges/intersects.js index e0e9b7ce000e4..917be7e4293d2 100644 --- a/node_modules/semver/ranges/intersects.js +++ b/node_modules/semver/ranges/intersects.js @@ -1,3 +1,5 @@ +'use strict' + const Range = require('../classes/range') const intersects = (r1, r2, options) => { r1 = new Range(r1, options) diff --git a/node_modules/semver/ranges/ltr.js b/node_modules/semver/ranges/ltr.js index 528a885ebdfcd..aa5e568ec279d 100644 --- a/node_modules/semver/ranges/ltr.js +++ b/node_modules/semver/ranges/ltr.js @@ -1,3 +1,5 @@ +'use strict' + const outside = require('./outside') // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) diff --git a/node_modules/semver/ranges/max-satisfying.js b/node_modules/semver/ranges/max-satisfying.js index 6e3d993c67860..01fe5ae383715 100644 --- a/node_modules/semver/ranges/max-satisfying.js +++ b/node_modules/semver/ranges/max-satisfying.js @@ -1,3 +1,5 @@ +'use strict' + const SemVer = require('../classes/semver') const Range = require('../classes/range') diff --git a/node_modules/semver/ranges/min-satisfying.js b/node_modules/semver/ranges/min-satisfying.js index 9b60974e2253a..af89c8ef43269 100644 --- a/node_modules/semver/ranges/min-satisfying.js +++ b/node_modules/semver/ranges/min-satisfying.js @@ -1,3 +1,5 @@ +'use strict' + const SemVer = require('../classes/semver') const Range = require('../classes/range') const minSatisfying = (versions, range, options) => { diff --git a/node_modules/semver/ranges/min-version.js b/node_modules/semver/ranges/min-version.js index 350e1f78368ea..09a65aa36fd51 100644 --- a/node_modules/semver/ranges/min-version.js +++ b/node_modules/semver/ranges/min-version.js @@ -1,3 +1,5 @@ +'use strict' + const SemVer = require('../classes/semver') const Range = require('../classes/range') const gt = require('../functions/gt') diff --git a/node_modules/semver/ranges/outside.js b/node_modules/semver/ranges/outside.js index ae99b10a5b9e6..ca7442120798e 100644 --- a/node_modules/semver/ranges/outside.js +++ b/node_modules/semver/ranges/outside.js @@ -1,3 +1,5 @@ +'use strict' + const SemVer = require('../classes/semver') const Comparator = require('../classes/comparator') const { ANY } = Comparator diff --git a/node_modules/semver/ranges/simplify.js b/node_modules/semver/ranges/simplify.js index 618d5b6273551..262732e670d7d 100644 --- a/node_modules/semver/ranges/simplify.js +++ b/node_modules/semver/ranges/simplify.js @@ -1,3 +1,5 @@ +'use strict' + // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. diff --git a/node_modules/semver/ranges/subset.js b/node_modules/semver/ranges/subset.js index 1e5c26837c047..a949832329003 100644 --- a/node_modules/semver/ranges/subset.js +++ b/node_modules/semver/ranges/subset.js @@ -1,3 +1,5 @@ +'use strict' + const Range = require('../classes/range.js') const Comparator = require('../classes/comparator.js') const { ANY } = Comparator @@ -36,7 +38,7 @@ const compare = require('../functions/compare.js') // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false -// - If GT.semver has a prerelease, and not in prerelease mode +// - If LT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true @@ -172,7 +174,7 @@ const simpleSubset = (sub, dom, options) => { if (higher === c && higher !== gt) { return false } - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + } else if (gt.operator === '>=' && !c.test(gt.semver)) { return false } } @@ -190,7 +192,7 @@ const simpleSubset = (sub, dom, options) => { if (lower === c && lower !== lt) { return false } - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + } else if (lt.operator === '<=' && !c.test(lt.semver)) { return false } } diff --git a/node_modules/semver/ranges/to-comparators.js b/node_modules/semver/ranges/to-comparators.js index 6c8bc7e6f15a4..5be251961acbd 100644 --- a/node_modules/semver/ranges/to-comparators.js +++ b/node_modules/semver/ranges/to-comparators.js @@ -1,3 +1,5 @@ +'use strict' + const Range = require('../classes/range') // Mostly just for testing and legacy API reasons diff --git a/node_modules/semver/ranges/valid.js b/node_modules/semver/ranges/valid.js index 365f35689d358..cc6b0e9f68f95 100644 --- a/node_modules/semver/ranges/valid.js +++ b/node_modules/semver/ranges/valid.js @@ -1,3 +1,5 @@ +'use strict' + const Range = require('../classes/range') const validRange = (range, options) => { try { diff --git a/node_modules/shebang-command/index.js b/node_modules/shebang-command/index.js deleted file mode 100644 index f35db30851c77..0000000000000 --- a/node_modules/shebang-command/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; -const shebangRegex = require('shebang-regex'); - -module.exports = (string = '') => { - const match = string.match(shebangRegex); - - if (!match) { - return null; - } - - const [path, argument] = match[0].replace(/#! ?/, '').split(' '); - const binary = path.split('/').pop(); - - if (binary === 'env') { - return argument; - } - - return argument ? `${binary} ${argument}` : binary; -}; diff --git a/node_modules/shebang-command/license b/node_modules/shebang-command/license deleted file mode 100644 index db6bc32cc7c44..0000000000000 --- a/node_modules/shebang-command/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Kevin Mårtensson (github.com/kevva) - -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. diff --git a/node_modules/shebang-command/package.json b/node_modules/shebang-command/package.json deleted file mode 100644 index 18e3c04638cb6..0000000000000 --- a/node_modules/shebang-command/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "shebang-command", - "version": "2.0.0", - "description": "Get the command from a shebang", - "license": "MIT", - "repository": "kevva/shebang-command", - "author": { - "name": "Kevin Mårtensson", - "email": "kevinmartensson@gmail.com", - "url": "github.com/kevva" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava" - }, - "files": [ - "index.js" - ], - "keywords": [ - "cmd", - "command", - "parse", - "shebang" - ], - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "devDependencies": { - "ava": "^2.3.0", - "xo": "^0.24.0" - } -} diff --git a/node_modules/shebang-regex/index.js b/node_modules/shebang-regex/index.js deleted file mode 100644 index 63fc4a0b67890..0000000000000 --- a/node_modules/shebang-regex/index.js +++ /dev/null @@ -1,2 +0,0 @@ -'use strict'; -module.exports = /^#!(.*)/; diff --git a/node_modules/shebang-regex/license b/node_modules/shebang-regex/license deleted file mode 100644 index e7af2f77107d7..0000000000000 --- a/node_modules/shebang-regex/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/shebang-regex/package.json b/node_modules/shebang-regex/package.json deleted file mode 100644 index 00ab30feeefe8..0000000000000 --- a/node_modules/shebang-regex/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "shebang-regex", - "version": "3.0.0", - "description": "Regular expression for matching a shebang line", - "license": "MIT", - "repository": "sindresorhus/shebang-regex", - "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": [ - "regex", - "regexp", - "shebang", - "match", - "test", - "line" - ], - "devDependencies": { - "ava": "^1.4.1", - "tsd": "^0.7.2", - "xo": "^0.24.0" - } -} diff --git a/node_modules/sigstore/dist/config.js b/node_modules/sigstore/dist/config.js deleted file mode 100644 index b4f0eea74fa4b..0000000000000 --- a/node_modules/sigstore/dist/config.js +++ /dev/null @@ -1,116 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createVerificationPolicy = exports.createKeyFinder = exports.createBundleBuilder = exports.DEFAULT_TIMEOUT = exports.DEFAULT_RETRY = 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"); -const sign_1 = require("@sigstore/sign"); -const verify_1 = require("@sigstore/verify"); -exports.DEFAULT_RETRY = { retries: 2 }; -exports.DEFAULT_TIMEOUT = 5000; -function createBundleBuilder(bundleType, options) { - const bundlerOptions = { - signer: initSigner(options), - witnesses: initWitnesses(options), - }; - switch (bundleType) { - case 'messageSignature': - return new sign_1.MessageSignatureBundleBuilder(bundlerOptions); - case 'dsseEnvelope': - return new sign_1.DSSEBundleBuilder(bundlerOptions); - } -} -exports.createBundleBuilder = createBundleBuilder; -// Translates the public KeySelector type into the KeyFinderFunc type needed by -// the verifier. -function createKeyFinder(keySelector) { - return (hint) => { - const key = keySelector(hint); - if (!key) { - throw new verify_1.VerificationError({ - code: 'PUBLIC_KEY_ERROR', - message: `key not found: ${hint}`, - }); - } - return { - publicKey: core_1.crypto.createPublicKey(key), - validFor: () => true, - }; - }; -} -exports.createKeyFinder = createKeyFinder; -function createVerificationPolicy(options) { - const policy = {}; - const san = options.certificateIdentityEmail || options.certificateIdentityURI; - if (san) { - policy.subjectAlternativeName = san; - } - if (options.certificateIssuer) { - policy.extensions = { issuer: options.certificateIssuer }; - } - return policy; -} -exports.createVerificationPolicy = createVerificationPolicy; -// Instantiate the FulcioSigner based on the supplied options. -function initSigner(options) { - return new sign_1.FulcioSigner({ - fulcioBaseURL: options.fulcioURL, - identityProvider: options.identityProvider || initIdentityProvider(options), - retry: options.retry ?? exports.DEFAULT_RETRY, - timeout: options.timeout ?? exports.DEFAULT_TIMEOUT, - }); -} -// Instantiate an identity provider based on the supplied options. If an -// explicit identity token is provided, use that. Otherwise, use the CI -// context provider. -function initIdentityProvider(options) { - const token = options.identityToken; - if (token) { - /* istanbul ignore next */ - return { getToken: () => Promise.resolve(token) }; - } - else { - return new sign_1.CIContextProvider('sigstore'); - } -} -// Instantiate a collection of witnesses based on the supplied options. -function initWitnesses(options) { - const witnesses = []; - if (isRekorEnabled(options)) { - witnesses.push(new sign_1.RekorWitness({ - rekorBaseURL: options.rekorURL, - fetchOnConflict: false, - retry: options.retry ?? exports.DEFAULT_RETRY, - timeout: options.timeout ?? exports.DEFAULT_TIMEOUT, - })); - } - if (isTSAEnabled(options)) { - witnesses.push(new sign_1.TSAWitness({ - tsaBaseURL: options.tsaServerURL, - retry: options.retry ?? exports.DEFAULT_RETRY, - timeout: options.timeout ?? exports.DEFAULT_TIMEOUT, - })); - } - return witnesses; -} -// Type assertion to ensure that Rekor is enabled -function isRekorEnabled(options) { - return options.tlogUpload !== false; -} -// Type assertion to ensure that TSA is enabled -function isTSAEnabled(options) { - return options.tsaServerURL !== undefined; -} diff --git a/node_modules/sigstore/package.json b/node_modules/sigstore/package.json deleted file mode 100644 index fa8744bf304a3..0000000000000 --- a/node_modules/sigstore/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "sigstore", - "version": "2.3.1", - "description": "code-signing for npm packages", - "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/client#readme", - "publishConfig": { - "provenance": true - }, - "devDependencies": { - "@sigstore/rekor-types": "^2.0.0", - "@sigstore/jest": "^0.0.0", - "@sigstore/mock": "^0.7.4", - "@tufjs/repo-mock": "^2.0.1", - "@types/make-fetch-happen": "^10.0.4" - }, - "dependencies": { - "@sigstore/bundle": "^2.3.2", - "@sigstore/core": "^1.0.0", - "@sigstore/protobuf-specs": "^0.3.2", - "@sigstore/sign": "^2.3.2", - "@sigstore/tuf": "^2.3.4", - "@sigstore/verify": "^1.2.1" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } -} diff --git a/node_modules/socks-proxy-agent/dist/index.js b/node_modules/socks-proxy-agent/dist/index.js index a9b5db2d61f57..4c74bea208b08 100644 --- a/node_modules/socks-proxy-agent/dist/index.js +++ b/node_modules/socks-proxy-agent/dist/index.js @@ -1,39 +1,22 @@ -"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]; } }; +import { SocksClient } from 'socks'; +import { Agent } from 'agent-base'; +import createDebug from 'debug'; +import * as dns from 'dns'; +import * as net from 'net'; +import * as tls from 'tls'; +import { URL } from 'url'; +const debug = createDebug('socks-proxy-agent'); +const setServernameFromNonIpHost = (options) => { + if (options.servername === undefined && + options.host && + !net.isIP(options.host)) { + return { + ...options, + servername: options.host, + }; } - 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 }; + return options; }; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SocksProxyAgent = void 0; -const socks_1 = require("socks"); -const agent_base_1 = require("agent-base"); -const debug_1 = __importDefault(require("debug")); -const dns = __importStar(require("dns")); -const tls = __importStar(require("tls")); -const url_1 = require("url"); -const debug = (0, debug_1.default)('socks-proxy-agent'); function parseSocksURL(url) { let lookup = false; let type = 5; @@ -85,13 +68,14 @@ function parseSocksURL(url) { } return { lookup, proxy }; } -class SocksProxyAgent extends agent_base_1.Agent { +export class SocksProxyAgent extends Agent { constructor(uri, opts) { super(opts); - const url = typeof uri === 'string' ? new url_1.URL(uri) : uri; + const url = typeof uri === 'string' ? new URL(uri) : uri; const { proxy, lookup } = parseSocksURL(url); this.shouldLookup = lookup; this.proxy = proxy; + this.proxyUrl = url.href; this.timeout = opts?.timeout ?? null; this.socketOptions = opts?.socketOptions ?? null; } @@ -110,12 +94,14 @@ class SocksProxyAgent extends agent_base_1.Agent { // Client-side DNS resolution for "4" and "5" socks proxy versions. host = await new Promise((resolve, reject) => { // Use the request's custom lookup, if one was configured: - lookupFn(host, {}, (err, res) => { + lookupFn(host, {}, (err, address) => { if (err) { reject(err); } else { - resolve(res); + resolve(typeof address === 'string' + ? address + : address[0].address); } }); }); @@ -139,8 +125,9 @@ class SocksProxyAgent extends agent_base_1.Agent { tlsSocket.destroy(); }; debug('Creating socks proxy connection: %o', socksOpts); - const { socket } = await socks_1.SocksClient.createConnection(socksOpts); + const { socket } = await SocksClient.createConnection(socksOpts); debug('Successfully created socks proxy connection'); + req.emit('proxy', { proxy: this.proxyUrl, socket }); if (timeout !== null) { socket.setTimeout(timeout); socket.on('timeout', () => cleanup()); @@ -149,11 +136,9 @@ class SocksProxyAgent extends agent_base_1.Agent { // The proxy is connecting to a TLS server, so upgrade // this socket connection to a TLS connection. debug('Upgrading socket connection to TLS'); - const servername = opts.servername || opts.host; const tlsSocket = tls.connect({ - ...omit(opts, 'host', 'path', 'port'), + ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'), socket, - servername, }); tlsSocket.once('error', (error) => { debug('Socket TLS error', error.message); @@ -171,7 +156,6 @@ SocksProxyAgent.protocols = [ 'socks5', 'socks5h', ]; -exports.SocksProxyAgent = SocksProxyAgent; function omit(obj, ...keys) { const ret = {}; let key; diff --git a/node_modules/socks-proxy-agent/node_modules/agent-base/LICENSE b/node_modules/socks-proxy-agent/node_modules/agent-base/LICENSE new file mode 100644 index 0000000000000..008728cb51847 --- /dev/null +++ b/node_modules/socks-proxy-agent/node_modules/agent-base/LICENSE @@ -0,0 +1,22 @@ +(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. \ No newline at end of file diff --git a/node_modules/socks-proxy-agent/node_modules/agent-base/dist/helpers.js b/node_modules/socks-proxy-agent/node_modules/agent-base/dist/helpers.js new file mode 100644 index 0000000000000..42c6ed2a0fed0 --- /dev/null +++ b/node_modules/socks-proxy-agent/node_modules/agent-base/dist/helpers.js @@ -0,0 +1,37 @@ +import * as http from 'http'; +import * as https from 'https'; +export 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); +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export 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; + } +} +export 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; +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/socks-proxy-agent/node_modules/agent-base/dist/index.js b/node_modules/socks-proxy-agent/node_modules/agent-base/dist/index.js new file mode 100644 index 0000000000000..15aa6e9d74593 --- /dev/null +++ b/node_modules/socks-proxy-agent/node_modules/agent-base/dist/index.js @@ -0,0 +1,146 @@ +import * as net from 'net'; +import * as http from 'http'; +import { Agent as HttpsAgent } from 'https'; +export * from './helpers.js'; +const INTERNAL = Symbol('AgentBaseInternalState'); +export 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 = this.isSecureEndpoint(options); + if (secureEndpoint) { + return HttpsAgent.prototype.getName.call(this, options); + } + 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 (typeof socket + .addRequest === 'function') { + try { + 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; + } + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/socks-proxy-agent/node_modules/agent-base/package.json b/node_modules/socks-proxy-agent/node_modules/agent-base/package.json new file mode 100644 index 0000000000000..8ef80c2bb094f --- /dev/null +++ b/node_modules/socks-proxy-agent/node_modules/agent-base/package.json @@ -0,0 +1,46 @@ +{ + "name": "agent-base", + "version": "9.0.0", + "type": "module", + "description": "Turn a function into an `http.Agent` instance", + "exports": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "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/node": "^22.13.0", + "@types/semver": "^7.3.13", + "@types/ws": "^8.5.4", + "async-listen": "^3.0.0", + "typescript": "^5.1.6", + "ws": "^8.13.0", + "tsconfig": "0.0.0" + }, + "engines": { + "node": ">= 20" + }, + "scripts": { + "build": "tsc", + "test": "vitest", + "lint": "eslint . --ext .ts", + "pack": "node ../../scripts/pack.mjs" + } +} \ No newline at end of file diff --git a/node_modules/socks-proxy-agent/package.json b/node_modules/socks-proxy-agent/package.json index ae0e373fa7738..3f24cb9a53855 100644 --- a/node_modules/socks-proxy-agent/package.json +++ b/node_modules/socks-proxy-agent/package.json @@ -1,9 +1,12 @@ { "name": "socks-proxy-agent", - "version": "8.0.4", + "version": "10.1.0", + "type": "module", "description": "A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS", - "main": "./dist/index.js", - "types": "./dist/index.d.ts", + "exports": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, "files": [ "dist" ], @@ -107,35 +110,32 @@ "socks5h" ], "dependencies": { - "agent-base": "^7.1.1", "debug": "^4.3.4", - "socks": "^2.8.3" + "socks": "^2.8.3", + "agent-base": "9.0.0" }, "devDependencies": { "@types/async-retry": "^1.4.5", "@types/debug": "^4.1.7", "@types/dns2": "^2.0.3", - "@types/jest": "^29.5.1", - "@types/node": "^14.18.45", + "@types/node": "^22.13.0", "async-listen": "^3.0.0", "async-retry": "^1.3.3", "cacheable-lookup": "^6.1.0", "dns2": "^2.1.0", - "jest": "^29.5.0", - "socksv5": "github:TooTallNate/socksv5#fix/dstSock-close-event", - "ts-jest": "^29.1.0", - "typescript": "^5.0.4", - "proxy": "2.2.0", + "socksv5": "github:TooTallNate/socksv5#d937368b28e929396166d77a06d387a4a902bd51", + "typescript": "^5.1.6", + "proxy": "4.1.0", "tsconfig": "0.0.0" }, "engines": { - "node": ">= 14" + "node": ">= 20" }, "license": "MIT", "scripts": { "build": "tsc", - "test": "jest --env node --verbose --bail test/test.ts", - "test-e2e": "jest --env node --verbose --bail test/e2e.test.ts", + "test": "vitest --exclude test/e2e.test.ts", + "test-e2e": "vitest run test/e2e.test.ts", "lint": "eslint . --ext .ts", "pack": "node ../../scripts/pack.mjs" } diff --git a/node_modules/socks/build/common/helpers.js b/node_modules/socks/build/common/helpers.js index 1ae44e4159a15..f0fcaf043d604 100644 --- a/node_modules/socks/build/common/helpers.js +++ b/node_modules/socks/build/common/helpers.js @@ -104,6 +104,7 @@ function validateCustomProxyAuth(proxy, options) { function isValidSocksRemoteHost(remoteHost) { return (remoteHost && typeof remoteHost.host === 'string' && + Buffer.byteLength(remoteHost.host) < 256 && typeof remoteHost.port === 'number' && remoteHost.port >= 0 && remoteHost.port <= 65535); @@ -130,7 +131,7 @@ function isValidTimeoutValue(value) { function ipv4ToInt32(ip) { const address = new ip_address_1.Address4(ip); // Convert the IPv4 address parts to an integer - return address.toArray().reduce((acc, part) => (acc << 8) + part, 0); + return address.toArray().reduce((acc, part) => (acc << 8) + part, 0) >>> 0; } exports.ipv4ToInt32 = ipv4ToInt32; function int32ToIpv4(int32) { diff --git a/node_modules/socks/package.json b/node_modules/socks/package.json index 5cc2a6836072e..078e21216b782 100644 --- a/node_modules/socks/package.json +++ b/node_modules/socks/package.json @@ -1,14 +1,14 @@ { "name": "socks", "private": false, - "version": "2.8.3", + "version": "2.8.9", "description": "Fully featured SOCKS proxy client supporting SOCKSv4, SOCKSv4a, and SOCKSv5. Includes Bind and Associate functionality.", "main": "build/index.js", "typings": "typings/index.d.ts", "homepage": "https://github.com/JoshGlazebrook/socks/", "repository": { "type": "git", - "url": "https://github.com/JoshGlazebrook/socks.git" + "url": "git+https://github.com/JoshGlazebrook/socks.git" }, "bugs": { "url": "https://github.com/JoshGlazebrook/socks/issues" @@ -44,7 +44,7 @@ "typescript": "^5.3.3" }, "dependencies": { - "ip-address": "^9.0.5", + "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" }, "scripts": { diff --git a/node_modules/spdx-correct/LICENSE b/node_modules/spdx-correct/LICENSE deleted file mode 100644 index d645695673349..0000000000000 --- a/node_modules/spdx-correct/LICENSE +++ /dev/null @@ -1,202 +0,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 [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. diff --git a/node_modules/spdx-correct/index.js b/node_modules/spdx-correct/index.js deleted file mode 100644 index 4d9037e0cc435..0000000000000 --- a/node_modules/spdx-correct/index.js +++ /dev/null @@ -1,386 +0,0 @@ -/* -Copyright spdx-correct.js contributors - -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 parse = require('spdx-expression-parse') -var spdxLicenseIds = require('spdx-license-ids') - -function valid (string) { - try { - parse(string) - return true - } catch (error) { - return false - } -} - -// Sorting function that orders the given array of transpositions such -// that a transposition with the longer pattern comes before a transposition -// with a shorter pattern. This is to prevent e.g. the transposition -// ["General Public License", "GPL"] from matching to "Lesser General Public License" -// before a longer and more accurate transposition ["Lesser General Public License", "LGPL"] -// has a chance to be recognized. -function sortTranspositions(a, b) { - var length = b[0].length - a[0].length - if (length !== 0) return length - return a[0].toUpperCase().localeCompare(b[0].toUpperCase()) -} - -// Common transpositions of license identifier acronyms -var transpositions = [ - ['APGL', 'AGPL'], - ['Gpl', 'GPL'], - ['GLP', 'GPL'], - ['APL', 'Apache'], - ['ISD', 'ISC'], - ['GLP', 'GPL'], - ['IST', 'ISC'], - ['Claude', 'Clause'], - [' or later', '+'], - [' International', ''], - ['GNU', 'GPL'], - ['GUN', 'GPL'], - ['+', ''], - ['GNU GPL', 'GPL'], - ['GNU LGPL', 'LGPL'], - ['GNU/GPL', 'GPL'], - ['GNU GLP', 'GPL'], - ['GNU LESSER GENERAL PUBLIC LICENSE', 'LGPL'], - ['GNU Lesser General Public License', 'LGPL'], - ['GNU LESSER GENERAL PUBLIC LICENSE', 'LGPL-2.1'], - ['GNU Lesser General Public License', 'LGPL-2.1'], - ['LESSER GENERAL PUBLIC LICENSE', 'LGPL'], - ['Lesser General Public License', 'LGPL'], - ['LESSER GENERAL PUBLIC LICENSE', 'LGPL-2.1'], - ['Lesser General Public License', 'LGPL-2.1'], - ['GNU General Public License', 'GPL'], - ['Gnu public license', 'GPL'], - ['GNU Public License', 'GPL'], - ['GNU GENERAL PUBLIC LICENSE', 'GPL'], - ['MTI', 'MIT'], - ['Mozilla Public License', 'MPL'], - ['Universal Permissive License', 'UPL'], - ['WTH', 'WTF'], - ['WTFGPL', 'WTFPL'], - ['-License', ''] -].sort(sortTranspositions) - -var TRANSPOSED = 0 -var CORRECT = 1 - -// Simple corrections to nearly valid identifiers. -var transforms = [ - // e.g. 'mit' - function (argument) { - return argument.toUpperCase() - }, - // e.g. 'MIT ' - function (argument) { - return argument.trim() - }, - // e.g. 'M.I.T.' - function (argument) { - return argument.replace(/\./g, '') - }, - // e.g. 'Apache- 2.0' - function (argument) { - return argument.replace(/\s+/g, '') - }, - // e.g. 'CC BY 4.0'' - function (argument) { - return argument.replace(/\s+/g, '-') - }, - // e.g. 'LGPLv2.1' - function (argument) { - return argument.replace('v', '-') - }, - // e.g. 'Apache 2.0' - function (argument) { - return argument.replace(/,?\s*(\d)/, '-$1') - }, - // e.g. 'GPL 2' - function (argument) { - return argument.replace(/,?\s*(\d)/, '-$1.0') - }, - // e.g. 'Apache Version 2.0' - function (argument) { - return argument - .replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2') - }, - // e.g. 'Apache Version 2' - function (argument) { - return argument - .replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2.0') - }, - // e.g. 'ZLIB' - function (argument) { - return argument[0].toUpperCase() + argument.slice(1) - }, - // e.g. 'MPL/2.0' - function (argument) { - return argument.replace('/', '-') - }, - // e.g. 'Apache 2' - function (argument) { - return argument - .replace(/\s*V\s*(\d)/, '-$1') - .replace(/(\d)$/, '$1.0') - }, - // e.g. 'GPL-2.0', 'GPL-3.0' - function (argument) { - if (argument.indexOf('3.0') !== -1) { - return argument + '-or-later' - } else { - return argument + '-only' - } - }, - // e.g. 'GPL-2.0-' - function (argument) { - return argument + 'only' - }, - // e.g. 'GPL2' - function (argument) { - return argument.replace(/(\d)$/, '-$1.0') - }, - // e.g. 'BSD 3' - function (argument) { - return argument.replace(/(-| )?(\d)$/, '-$2-Clause') - }, - // e.g. 'BSD clause 3' - function (argument) { - return argument.replace(/(-| )clause(-| )(\d)/, '-$3-Clause') - }, - // e.g. 'New BSD license' - function (argument) { - return argument.replace(/\b(Modified|New|Revised)(-| )?BSD((-| )License)?/i, 'BSD-3-Clause') - }, - // e.g. 'Simplified BSD license' - function (argument) { - return argument.replace(/\bSimplified(-| )?BSD((-| )License)?/i, 'BSD-2-Clause') - }, - // e.g. 'Free BSD license' - function (argument) { - return argument.replace(/\b(Free|Net)(-| )?BSD((-| )License)?/i, 'BSD-2-Clause-$1BSD') - }, - // e.g. 'Clear BSD license' - function (argument) { - return argument.replace(/\bClear(-| )?BSD((-| )License)?/i, 'BSD-3-Clause-Clear') - }, - // e.g. 'Old BSD License' - function (argument) { - return argument.replace(/\b(Old|Original)(-| )?BSD((-| )License)?/i, 'BSD-4-Clause') - }, - // e.g. 'BY-NC-4.0' - function (argument) { - return 'CC-' + argument - }, - // e.g. 'BY-NC' - function (argument) { - return 'CC-' + argument + '-4.0' - }, - // e.g. 'Attribution-NonCommercial' - function (argument) { - return argument - .replace('Attribution', 'BY') - .replace('NonCommercial', 'NC') - .replace('NoDerivatives', 'ND') - .replace(/ (\d)/, '-$1') - .replace(/ ?International/, '') - }, - // e.g. 'Attribution-NonCommercial' - function (argument) { - return 'CC-' + - argument - .replace('Attribution', 'BY') - .replace('NonCommercial', 'NC') - .replace('NoDerivatives', 'ND') - .replace(/ (\d)/, '-$1') - .replace(/ ?International/, '') + - '-4.0' - } -] - -var licensesWithVersions = spdxLicenseIds - .map(function (id) { - var match = /^(.*)-\d+\.\d+$/.exec(id) - return match - ? [match[0], match[1]] - : [id, null] - }) - .reduce(function (objectMap, item) { - var key = item[1] - objectMap[key] = objectMap[key] || [] - objectMap[key].push(item[0]) - return objectMap - }, {}) - -var licensesWithOneVersion = Object.keys(licensesWithVersions) - .map(function makeEntries (key) { - return [key, licensesWithVersions[key]] - }) - .filter(function identifySoleVersions (item) { - return ( - // Licenses has just one valid version suffix. - item[1].length === 1 && - item[0] !== null && - // APL will be considered Apache, rather than APL-1.0 - item[0] !== 'APL' - ) - }) - .map(function createLastResorts (item) { - return [item[0], item[1][0]] - }) - -licensesWithVersions = undefined - -// If all else fails, guess that strings containing certain substrings -// meant to identify certain licenses. -var lastResorts = [ - ['UNLI', 'Unlicense'], - ['WTF', 'WTFPL'], - ['2 CLAUSE', 'BSD-2-Clause'], - ['2-CLAUSE', 'BSD-2-Clause'], - ['3 CLAUSE', 'BSD-3-Clause'], - ['3-CLAUSE', 'BSD-3-Clause'], - ['AFFERO', 'AGPL-3.0-or-later'], - ['AGPL', 'AGPL-3.0-or-later'], - ['APACHE', 'Apache-2.0'], - ['ARTISTIC', 'Artistic-2.0'], - ['Affero', 'AGPL-3.0-or-later'], - ['BEER', 'Beerware'], - ['BOOST', 'BSL-1.0'], - ['BSD', 'BSD-2-Clause'], - ['CDDL', 'CDDL-1.1'], - ['ECLIPSE', 'EPL-1.0'], - ['FUCK', 'WTFPL'], - ['GNU', 'GPL-3.0-or-later'], - ['LGPL', 'LGPL-3.0-or-later'], - ['GPLV1', 'GPL-1.0-only'], - ['GPL-1', 'GPL-1.0-only'], - ['GPLV2', 'GPL-2.0-only'], - ['GPL-2', 'GPL-2.0-only'], - ['GPL', 'GPL-3.0-or-later'], - ['MIT +NO-FALSE-ATTRIBS', 'MITNFA'], - ['MIT', 'MIT'], - ['MPL', 'MPL-2.0'], - ['X11', 'X11'], - ['ZLIB', 'Zlib'] -].concat(licensesWithOneVersion).sort(sortTranspositions) - -var SUBSTRING = 0 -var IDENTIFIER = 1 - -var validTransformation = function (identifier) { - for (var i = 0; i < transforms.length; i++) { - var transformed = transforms[i](identifier).trim() - if (transformed !== identifier && valid(transformed)) { - return transformed - } - } - return null -} - -var validLastResort = function (identifier) { - var upperCased = identifier.toUpperCase() - for (var i = 0; i < lastResorts.length; i++) { - var lastResort = lastResorts[i] - if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) { - return lastResort[IDENTIFIER] - } - } - return null -} - -var anyCorrection = function (identifier, check) { - for (var i = 0; i < transpositions.length; i++) { - var transposition = transpositions[i] - var transposed = transposition[TRANSPOSED] - if (identifier.indexOf(transposed) > -1) { - var corrected = identifier.replace( - transposed, - transposition[CORRECT] - ) - var checked = check(corrected) - if (checked !== null) { - return checked - } - } - } - return null -} - -module.exports = function (identifier, options) { - options = options || {} - var upgrade = options.upgrade === undefined ? true : !!options.upgrade - function postprocess (value) { - return upgrade ? upgradeGPLs(value) : value - } - var validArugment = ( - typeof identifier === 'string' && - identifier.trim().length !== 0 - ) - if (!validArugment) { - throw Error('Invalid argument. Expected non-empty string.') - } - identifier = identifier.trim() - if (valid(identifier)) { - return postprocess(identifier) - } - var noPlus = identifier.replace(/\+$/, '').trim() - if (valid(noPlus)) { - return postprocess(noPlus) - } - var transformed = validTransformation(identifier) - if (transformed !== null) { - return postprocess(transformed) - } - transformed = anyCorrection(identifier, function (argument) { - if (valid(argument)) { - return argument - } - return validTransformation(argument) - }) - if (transformed !== null) { - return postprocess(transformed) - } - transformed = validLastResort(identifier) - if (transformed !== null) { - return postprocess(transformed) - } - transformed = anyCorrection(identifier, validLastResort) - if (transformed !== null) { - return postprocess(transformed) - } - return null -} - -function upgradeGPLs (value) { - if ([ - 'GPL-1.0', 'LGPL-1.0', 'AGPL-1.0', - 'GPL-2.0', 'LGPL-2.0', 'AGPL-2.0', - 'LGPL-2.1' - ].indexOf(value) !== -1) { - return value + '-only' - } else if ([ - 'GPL-1.0+', 'GPL-2.0+', 'GPL-3.0+', - 'LGPL-2.0+', 'LGPL-2.1+', 'LGPL-3.0+', - 'AGPL-1.0+', 'AGPL-3.0+' - ].indexOf(value) !== -1) { - return value.replace(/\+$/, '-or-later') - } else if (['GPL-3.0', 'LGPL-3.0', 'AGPL-3.0'].indexOf(value) !== -1) { - return value + '-or-later' - } else { - return value - } -} diff --git a/node_modules/spdx-correct/node_modules/spdx-expression-parse/AUTHORS b/node_modules/spdx-correct/node_modules/spdx-expression-parse/AUTHORS deleted file mode 100644 index 257a76b9484c1..0000000000000 --- a/node_modules/spdx-correct/node_modules/spdx-expression-parse/AUTHORS +++ /dev/null @@ -1,4 +0,0 @@ -C. Scott Ananian (http://cscott.net) -Kyle E. Mitchell (https://kemitchell.com) -Shinnosuke Watanabe -Antoine Motet diff --git a/node_modules/spdx-correct/node_modules/spdx-expression-parse/LICENSE b/node_modules/spdx-correct/node_modules/spdx-expression-parse/LICENSE deleted file mode 100644 index 831618eaba6c8..0000000000000 --- a/node_modules/spdx-correct/node_modules/spdx-expression-parse/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License - -Copyright (c) 2015 Kyle E. Mitchell & other authors listed in AUTHORS - -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. diff --git a/node_modules/spdx-correct/node_modules/spdx-expression-parse/index.js b/node_modules/spdx-correct/node_modules/spdx-expression-parse/index.js deleted file mode 100644 index 52fab560aea70..0000000000000 --- a/node_modules/spdx-correct/node_modules/spdx-expression-parse/index.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict' - -var scan = require('./scan') -var parse = require('./parse') - -module.exports = function (source) { - return parse(scan(source)) -} diff --git a/node_modules/spdx-correct/node_modules/spdx-expression-parse/package.json b/node_modules/spdx-correct/node_modules/spdx-expression-parse/package.json deleted file mode 100644 index c9edc9f939cdf..0000000000000 --- a/node_modules/spdx-correct/node_modules/spdx-expression-parse/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "spdx-expression-parse", - "description": "parse SPDX license expressions", - "version": "3.0.1", - "author": "Kyle E. Mitchell (https://kemitchell.com)", - "files": [ - "AUTHORS", - "index.js", - "parse.js", - "scan.js" - ], - "dependencies": { - "spdx-exceptions": "^2.1.0", - "spdx-license-ids": "^3.0.0" - }, - "devDependencies": { - "defence-cli": "^3.0.1", - "replace-require-self": "^1.0.0", - "standard": "^14.1.0" - }, - "keywords": [ - "SPDX", - "law", - "legal", - "license", - "metadata", - "package", - "package.json", - "standards" - ], - "license": "MIT", - "repository": "jslicense/spdx-expression-parse.js", - "scripts": { - "lint": "standard", - "test:readme": "defence -i javascript README.md | replace-require-self | node", - "test:suite": "node test.js", - "test": "npm run test:suite && npm run test:readme" - } -} diff --git a/node_modules/spdx-correct/node_modules/spdx-expression-parse/parse.js b/node_modules/spdx-correct/node_modules/spdx-expression-parse/parse.js deleted file mode 100644 index 5a00b45c5799c..0000000000000 --- a/node_modules/spdx-correct/node_modules/spdx-expression-parse/parse.js +++ /dev/null @@ -1,138 +0,0 @@ -'use strict' - -// The ABNF grammar in the spec is totally ambiguous. -// -// This parser follows the operator precedence defined in the -// `Order of Precedence and Parentheses` section. - -module.exports = function (tokens) { - var index = 0 - - function hasMore () { - return index < tokens.length - } - - function token () { - return hasMore() ? tokens[index] : null - } - - function next () { - if (!hasMore()) { - throw new Error() - } - index++ - } - - function parseOperator (operator) { - var t = token() - if (t && t.type === 'OPERATOR' && operator === t.string) { - next() - return t.string - } - } - - function parseWith () { - if (parseOperator('WITH')) { - var t = token() - if (t && t.type === 'EXCEPTION') { - next() - return t.string - } - throw new Error('Expected exception after `WITH`') - } - } - - function parseLicenseRef () { - // TODO: Actually, everything is concatenated into one string - // for backward-compatibility but it could be better to return - // a nice structure. - var begin = index - var string = '' - var t = token() - if (t.type === 'DOCUMENTREF') { - next() - string += 'DocumentRef-' + t.string + ':' - if (!parseOperator(':')) { - throw new Error('Expected `:` after `DocumentRef-...`') - } - } - t = token() - if (t.type === 'LICENSEREF') { - next() - string += 'LicenseRef-' + t.string - return { license: string } - } - index = begin - } - - function parseLicense () { - var t = token() - if (t && t.type === 'LICENSE') { - next() - var node = { license: t.string } - if (parseOperator('+')) { - node.plus = true - } - var exception = parseWith() - if (exception) { - node.exception = exception - } - return node - } - } - - function parseParenthesizedExpression () { - var left = parseOperator('(') - if (!left) { - return - } - - var expr = parseExpression() - - if (!parseOperator(')')) { - throw new Error('Expected `)`') - } - - return expr - } - - function parseAtom () { - return ( - parseParenthesizedExpression() || - parseLicenseRef() || - parseLicense() - ) - } - - function makeBinaryOpParser (operator, nextParser) { - return function parseBinaryOp () { - var left = nextParser() - if (!left) { - return - } - - if (!parseOperator(operator)) { - return left - } - - var right = parseBinaryOp() - if (!right) { - throw new Error('Expected expression') - } - return { - left: left, - conjunction: operator.toLowerCase(), - right: right - } - } - } - - var parseAnd = makeBinaryOpParser('AND', parseAtom) - var parseExpression = makeBinaryOpParser('OR', parseAnd) - - var node = parseExpression() - if (!node || hasMore()) { - throw new Error('Syntax error') - } - return node -} diff --git a/node_modules/spdx-correct/node_modules/spdx-expression-parse/scan.js b/node_modules/spdx-correct/node_modules/spdx-expression-parse/scan.js deleted file mode 100644 index b74fce2e2c663..0000000000000 --- a/node_modules/spdx-correct/node_modules/spdx-expression-parse/scan.js +++ /dev/null @@ -1,131 +0,0 @@ -'use strict' - -var licenses = [] - .concat(require('spdx-license-ids')) - .concat(require('spdx-license-ids/deprecated')) -var exceptions = require('spdx-exceptions') - -module.exports = function (source) { - var index = 0 - - function hasMore () { - return index < source.length - } - - // `value` can be a regexp or a string. - // If it is recognized, the matching source string is returned and - // the index is incremented. Otherwise `undefined` is returned. - function read (value) { - if (value instanceof RegExp) { - var chars = source.slice(index) - var match = chars.match(value) - if (match) { - index += match[0].length - return match[0] - } - } else { - if (source.indexOf(value, index) === index) { - index += value.length - return value - } - } - } - - function skipWhitespace () { - read(/[ ]*/) - } - - function operator () { - var string - var possibilities = ['WITH', 'AND', 'OR', '(', ')', ':', '+'] - for (var i = 0; i < possibilities.length; i++) { - string = read(possibilities[i]) - if (string) { - break - } - } - - if (string === '+' && index > 1 && source[index - 2] === ' ') { - throw new Error('Space before `+`') - } - - return string && { - type: 'OPERATOR', - string: string - } - } - - function idstring () { - return read(/[A-Za-z0-9-.]+/) - } - - function expectIdstring () { - var string = idstring() - if (!string) { - throw new Error('Expected idstring at offset ' + index) - } - return string - } - - function documentRef () { - if (read('DocumentRef-')) { - var string = expectIdstring() - return { type: 'DOCUMENTREF', string: string } - } - } - - function licenseRef () { - if (read('LicenseRef-')) { - var string = expectIdstring() - return { type: 'LICENSEREF', string: string } - } - } - - function identifier () { - var begin = index - var string = idstring() - - if (licenses.indexOf(string) !== -1) { - return { - type: 'LICENSE', - string: string - } - } else if (exceptions.indexOf(string) !== -1) { - return { - type: 'EXCEPTION', - string: string - } - } - - index = begin - } - - // Tries to read the next token. Returns `undefined` if no token is - // recognized. - function parseToken () { - // Ordering matters - return ( - operator() || - documentRef() || - licenseRef() || - identifier() - ) - } - - var tokens = [] - while (hasMore()) { - skipWhitespace() - if (!hasMore()) { - break - } - - var token = parseToken() - if (!token) { - throw new Error('Unexpected `' + source[index] + - '` at offset ' + index) - } - - tokens.push(token) - } - return tokens -} diff --git a/node_modules/spdx-correct/package.json b/node_modules/spdx-correct/package.json deleted file mode 100644 index d77615638be66..0000000000000 --- a/node_modules/spdx-correct/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "spdx-correct", - "description": "correct invalid SPDX expressions", - "version": "3.2.0", - "dependencies": { - "spdx-expression-parse": "^3.0.0", - "spdx-license-ids": "^3.0.0" - }, - "devDependencies": { - "defence-cli": "^3.0.1", - "replace-require-self": "^1.0.0", - "standard": "^14.3.4", - "standard-markdown": "^6.0.0", - "tape": "^5.0.1" - }, - "files": [ - "index.js" - ], - "keywords": [ - "SPDX", - "law", - "legal", - "license", - "metadata" - ], - "license": "Apache-2.0", - "repository": "jslicense/spdx-correct.js", - "scripts": { - "lint": "standard && standard-markdown README.md", - "test": "defence README.md | replace-require-self | node && node test.js" - } -} diff --git a/node_modules/spdx-license-ids/deprecated.json b/node_modules/spdx-license-ids/deprecated.json index 278531e40c613..4f70a14c7469d 100644 --- a/node_modules/spdx-license-ids/deprecated.json +++ b/node_modules/spdx-license-ids/deprecated.json @@ -19,6 +19,7 @@ "LGPL-2.0", "LGPL-2.1", "LGPL-3.0", + "Net-SNMP", "Nunit", "StandardML-NJ", "bzip2-1.0.5", diff --git a/node_modules/spdx-license-ids/index.json b/node_modules/spdx-license-ids/index.json index c7686a710d61d..f51552687007b 100644 --- a/node_modules/spdx-license-ids/index.json +++ b/node_modules/spdx-license-ids/index.json @@ -12,6 +12,7 @@ "AGPL-1.0-or-later", "AGPL-3.0-only", "AGPL-3.0-or-later", + "ALGLIB-Documentation", "AMD-newlib", "AMDPLPA", "AML", @@ -33,6 +34,7 @@ "Adobe-Display-PostScript", "Adobe-Glyph", "Adobe-Utopia", + "Advanced-Cryptics-Dictionary", "Afmparse", "Aladdin", "Apache-1.0", @@ -44,12 +46,16 @@ "Artistic-1.0-Perl", "Artistic-1.0-cl8", "Artistic-2.0", + "Artistic-dist", + "Aspell-RU", + "BOLA-1.1", "BSD-1-Clause", "BSD-2-Clause", "BSD-2-Clause-Darwin", "BSD-2-Clause-Patent", "BSD-2-Clause-Views", "BSD-2-Clause-first-lines", + "BSD-2-Clause-pkgconf-disclaimer", "BSD-3-Clause", "BSD-3-Clause-Attribution", "BSD-3-Clause-Clear", @@ -62,6 +68,7 @@ "BSD-3-Clause-No-Nuclear-Warranty", "BSD-3-Clause-Open-MPI", "BSD-3-Clause-Sun", + "BSD-3-Clause-Tso", "BSD-3-Clause-acpica", "BSD-3-Clause-flex", "BSD-4-Clause", @@ -72,6 +79,7 @@ "BSD-Advertising-Acknowledgement", "BSD-Attribution-HPND-disclaimer", "BSD-Inferno-Nettverk", + "BSD-Mark-Modifications", "BSD-Protection", "BSD-Source-Code", "BSD-Source-beginning-file", @@ -89,12 +97,15 @@ "Bitstream-Vera", "BlueOak-1.0.0", "Boehm-GC", + "Boehm-GC-without-fee", "Borceux", "Brian-Gladman-2-Clause", "Brian-Gladman-3-Clause", + "Buddy", "C-UDA-1.0", "CAL-1.0", "CAL-1.0-Combined-Work-Exception", + "CAPEC-tou", "CATOSL-1.1", "CC-BY-1.0", "CC-BY-2.0", @@ -148,6 +159,8 @@ "CC-BY-SA-3.0-IGO", "CC-BY-SA-4.0", "CC-PDDC", + "CC-PDM-1.0", + "CC-SA-1.0", "CC0-1.0", "CDDL-1.0", "CDDL-1.1", @@ -187,6 +200,7 @@ "Cornell-Lossless-JPEG", "Cronyx", "Crossword", + "CryptoSwift", "CrystalStacker", "Cube", "D-FSL-1.0", @@ -197,6 +211,10 @@ "DRL-1.0", "DRL-1.1", "DSDP", + "DocBook-DTD", + "DocBook-Schema", + "DocBook-Stylesheet", + "DocBook-XML", "Dotseqn", "ECL-1.0", "ECL-2.0", @@ -205,6 +223,9 @@ "EPICS", "EPL-1.0", "EPL-2.0", + "ESA-PL-permissive-2.4", + "ESA-PL-strong-copyleft-2.4", + "ESA-PL-weak-copyleft-2.4", "EUDatagrid", "EUPL-1.0", "EUPL-1.1", @@ -219,7 +240,10 @@ "FSFAP-no-warranty-disclaimer", "FSFUL", "FSFULLR", + "FSFULLRSD", "FSFULLRWD", + "FSL-1.1-ALv2", + "FSL-1.1-MIT", "FTL", "Fair", "Ferguson-Twofish", @@ -255,11 +279,14 @@ "GPL-2.0-or-later", "GPL-3.0-only", "GPL-3.0-or-later", + "Game-Programming-Gems", "Giftware", "Glide", "Glulxe", "Graphics-Gems", "Gutmann", + "HDF5", + "HIDAPI", "HP-1986", "HP-1989", "HPND", @@ -270,7 +297,9 @@ "HPND-Kevlin-Henney", "HPND-MIT-disclaimer", "HPND-Markus-Kuhn", + "HPND-Netrek", "HPND-Pbmplus", + "HPND-SMC", "HPND-UC", "HPND-UC-export-US", "HPND-doc", @@ -285,6 +314,7 @@ "HPND-sell-variant", "HPND-sell-variant-MIT-disclaimer", "HPND-sell-variant-MIT-disclaimer-rev", + "HPND-sell-variant-critical-systems", "HTMLTIDY", "HaskellReport", "Hippocratic-2.1", @@ -297,10 +327,12 @@ "IPL-1.0", "ISC", "ISC-Veillard", + "ISO-permission", "ImageMagick", "Imlib2", "Info-ZIP", "Inner-Net-2.0", + "InnoSetup", "Intel", "Intel-ACPI", "Interbase-1.0", @@ -345,12 +377,15 @@ "Linux-man-pages-copyleft-2-para", "Linux-man-pages-copyleft-var", "Lucida-Bitmap-Fonts", + "MIPS", "MIT", "MIT-0", "MIT-CMU", + "MIT-Click", "MIT-Festival", "MIT-Khronos-old", "MIT-Modern-Variant", + "MIT-STK", "MIT-Wu", "MIT-advertising", "MIT-enna", @@ -359,6 +394,7 @@ "MIT-testregex", "MITNFA", "MMIXware", + "MMPL-1.0.1", "MPEG-SSG", "MPL-1.0", "MPL-1.1", @@ -390,6 +426,7 @@ "NGPL", "NICTA-1.0", "NIST-PD", + "NIST-PD-TNT", "NIST-PD-fallback", "NIST-Software", "NLOD-1.0", @@ -400,10 +437,10 @@ "NPL-1.1", "NPOSL-3.0", "NRL", + "NTIA-PD", "NTP", "NTP-0", "Naumen", - "Net-SNMP", "NetCDF", "Newsletr", "Nokia", @@ -449,12 +486,15 @@ "OPL-1.0", "OPL-UK-3.0", "OPUBL-1.0", + "OSC-1.0", "OSET-PL-2.1", "OSL-1.0", "OSL-1.1", "OSL-2.0", "OSL-2.1", "OSL-3.0", + "OSSP", + "OpenMDW-1.0", "OpenPBS-2.3", "OpenSSL", "OpenSSL-standalone", @@ -465,6 +505,7 @@ "PHP-3.01", "PPL", "PSF-2.0", + "ParaType-Free-Font-1.3", "Parity-6.0.0", "Parity-7.0.0", "Pixar", @@ -485,6 +526,7 @@ "RSCPL", "Rdisc", "Ruby", + "Ruby-pty", "SAX-PD", "SAX-PD-2.0", "SCEA", @@ -492,25 +534,30 @@ "SGI-B-1.1", "SGI-B-2.0", "SGI-OpenGL", + "SGMLUG-PM", "SGP4", "SHL-0.5", "SHL-0.51", "SISSL", "SISSL-1.2", "SL", + "SMAIL-GPL", "SMLNJ", "SMPPL", "SNIA", + "SOFA", "SPL-1.0", "SSH-OpenSSH", "SSH-short", "SSLeay-standalone", "SSPL-1.0", + "SUL-1.0", "SWL", "Saxpath", "SchemeReport", "Sendmail", "Sendmail-8.23", + "Sendmail-Open-Source-1.1", "SimPL-2.0", "Sleepycat", "Soundex", @@ -535,30 +582,42 @@ "TTYP0", "TU-Berlin-1.0", "TU-Berlin-2.0", + "TekHVC", "TermReadKey", + "ThirdEye", + "TrustedQSL", "UCAR", "UCL-1.0", "UMich-Merit", "UPL-1.0", "URT-RLE", + "Ubuntu-font-1.0", + "UnRAR", "Unicode-3.0", "Unicode-DFS-2015", "Unicode-DFS-2016", "Unicode-TOU", "UnixCrypt", "Unlicense", + "Unlicense-libtelnet", + "Unlicense-libwhirlpool", "VOSTROM", "VSL-1.0", "Vim", + "Vixie-Cron", "W3C", "W3C-19980720", "W3C-20150513", + "WTFNMFPL", "WTFPL", "Watcom-1.0", "Widget-Workshop", + "WordNet", "Wsuipa", "X11", "X11-distribute-modifications-variant", + "X11-no-permit-persons", + "X11-swapped", "XFree86-1.1", "XSkat", "Xdebug-1.03", @@ -577,6 +636,7 @@ "Zimbra-1.4", "Zlib", "any-OSI", + "any-OSI-perl-modules", "bcrypt-Solar-Designer", "blessing", "bzip2-1.0.6", @@ -593,10 +653,14 @@ "etalab-2.0", "fwlw", "gSOAP-1.3b", + "generic-xts", "gnuplot", "gtkbook", "hdparm", + "hyphen-bulgarian", "iMatix", + "jove", + "libpng-1.6.35", "libpng-2.0", "libselinux-1.0", "libtiff", @@ -604,10 +668,12 @@ "lsof", "magaz", "mailprio", + "man2html", "metamail", "mpi-permissive", "mpich2", "mplus", + "ngrep", "pkgconf", "pnmstitch", "psfrag", @@ -621,6 +687,7 @@ "threeparttable", "ulem", "w3m", + "wwl", "xinetd", "xkeyboard-config-Zinoviev", "xlock", diff --git a/node_modules/spdx-license-ids/package.json b/node_modules/spdx-license-ids/package.json index 5f5ed9554f257..9c9ba083889a7 100644 --- a/node_modules/spdx-license-ids/package.json +++ b/node_modules/spdx-license-ids/package.json @@ -1,14 +1,14 @@ { "name": "spdx-license-ids", - "version": "3.0.18", + "version": "3.0.23", "description": "A list of SPDX license identifiers", "repository": "jslicense/spdx-license-ids", "author": "Shinnosuke Watanabe (https://github.com/shinnn)", "license": "CC0-1.0", "scripts": { "build": "node build.js", - "pretest": "eslint .", "latest": "node latest.js", + "pretest": "npm run build", "test": "node test.js" }, "files": [ @@ -25,15 +25,5 @@ "json", "array", "oss" - ], - "devDependencies": { - "@shinnn/eslint-config": "^7.0.0", - "eslint": "^8.49.0", - "eslint-formatter-codeframe": "^7.32.1", - "rmfr": "^2.0.0", - "tape": "^5.6.6" - }, - "eslintConfig": { - "extends": "@shinnn" - } + ] } diff --git a/node_modules/sprintf-js/CONTRIBUTORS.md b/node_modules/sprintf-js/CONTRIBUTORS.md deleted file mode 100644 index a16608e936a72..0000000000000 --- a/node_modules/sprintf-js/CONTRIBUTORS.md +++ /dev/null @@ -1,26 +0,0 @@ -Alexander Rose [@arose](https://github.com/arose) -Alexandru Mărășteanu [@alexei](https://github.com/alexei) -Andras [@andrasq](https://github.com/andrasq) -Benoit Giannangeli [@giann](https://github.com/giann) -Branden Visser [@mrvisser](https://github.com/mrvisser) -David Baird -daurnimator [@daurnimator](https://github.com/daurnimator) -Doug Beck [@beck](https://github.com/beck) -Dzmitry Litskalau [@litmit](https://github.com/litmit) -Fred Ludlow [@fredludlow](https://github.com/fredludlow) -Hans Pufal -Henry [@alograg](https://github.com/alograg) -Johnny Shields [@johnnyshields](https://github.com/johnnyshields) -Kamal Abdali -Matt Simerson [@msimerson](https://github.com/msimerson) -Maxime Robert [@marob](https://github.com/marob) -MeriemKhelifi [@MeriemKhelifi](https://github.com/MeriemKhelifi) -Michael Schramm [@wodka](https://github.com/wodka) -Nazar Mokrynskyi [@nazar-pc](https://github.com/nazar-pc) -Oliver Salzburg [@oliversalzburg](https://github.com/oliversalzburg) -Pablo [@ppollono](https://github.com/ppollono) -Rabehaja Stevens [@RABEHAJA-STEVENS](https://github.com/RABEHAJA-STEVENS) -Raphael Pigulla [@pigulla](https://github.com/pigulla) -rebeccapeltz [@rebeccapeltz](https://github.com/rebeccapeltz) -Stefan Tingström [@stingstrom](https://github.com/stingstrom) -Tim Gates [@timgates42](https://github.com/timgates42) diff --git a/node_modules/sprintf-js/LICENSE b/node_modules/sprintf-js/LICENSE deleted file mode 100644 index 83f832a2ee282..0000000000000 --- a/node_modules/sprintf-js/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2007-present, Alexandru Mărășteanu -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 this software 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 AUTHORS OR COPYRIGHT HOLDERS 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 --git a/node_modules/sprintf-js/bower.json b/node_modules/sprintf-js/bower.json deleted file mode 100644 index d90a75989f7b0..0000000000000 --- a/node_modules/sprintf-js/bower.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "sprintf", - "description": "JavaScript sprintf implementation", - "version": "1.0.3", - "main": "src/sprintf.js", - "license": "BSD-3-Clause-Clear", - "keywords": ["sprintf", "string", "formatting"], - "authors": ["Alexandru Marasteanu (http://alexei.ro/)"], - "homepage": "https://github.com/alexei/sprintf.js", - "repository": { - "type": "git", - "url": "git://github.com/alexei/sprintf.js.git" - } -} diff --git a/node_modules/sprintf-js/demo/angular.html b/node_modules/sprintf-js/demo/angular.html deleted file mode 100644 index 3559efd763563..0000000000000 --- a/node_modules/sprintf-js/demo/angular.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - -
{{ "%+010d"|sprintf:-123 }}
-
{{ "%+010d"|vsprintf:[-123] }}
-
{{ "%+010d"|fmt:-123 }}
-
{{ "%+010d"|vfmt:[-123] }}
-
{{ "I've got %2$d apples and %1$d oranges."|fmt:4:2 }}
-
{{ "I've got %(apples)d apples and %(oranges)d oranges."|fmt:{apples: 2, oranges: 4} }}
- - - - diff --git a/node_modules/sprintf-js/dist/.gitattributes b/node_modules/sprintf-js/dist/.gitattributes deleted file mode 100644 index d35bca01c1201..0000000000000 --- a/node_modules/sprintf-js/dist/.gitattributes +++ /dev/null @@ -1,4 +0,0 @@ -#ignore all generated files from diff -#also skip line ending check -*.js -diff -text -*.map -diff -text diff --git a/node_modules/sprintf-js/dist/angular-sprintf.min.js b/node_modules/sprintf-js/dist/angular-sprintf.min.js deleted file mode 100644 index 5dff8c54337db..0000000000000 --- a/node_modules/sprintf-js/dist/angular-sprintf.min.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! sprintf-js v1.1.3 | Copyright (c) 2007-present, Alexandru Mărășteanu | BSD-3-Clause */ -!function(){"use strict";angular.module("sprintf",[]).filter("sprintf",function(){return function(){return sprintf.apply(null,arguments)}}).filter("fmt",["$filter",function(t){return t("sprintf")}]).filter("vsprintf",function(){return function(t,n){return vsprintf(t,n)}}).filter("vfmt",["$filter",function(t){return t("vsprintf")}])}(); -//# sourceMappingURL=angular-sprintf.min.js.map diff --git a/node_modules/sprintf-js/dist/sprintf.min.js b/node_modules/sprintf-js/dist/sprintf.min.js deleted file mode 100644 index ed09637ea3905..0000000000000 --- a/node_modules/sprintf-js/dist/sprintf.min.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! sprintf-js v1.1.3 | Copyright (c) 2007-present, Alexandru Mărășteanu | BSD-3-Clause */ -!function(){"use strict";var g={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function y(e){return function(e,t){var r,n,i,s,a,o,p,c,l,u=1,f=e.length,d="";for(n=0;n>>0).toString(8);break;case"s":r=String(r),r=s.precision?r.substring(0,s.precision):r;break;case"t":r=String(!!r),r=s.precision?r.substring(0,s.precision):r;break;case"T":r=Object.prototype.toString.call(r).slice(8,-1).toLowerCase(),r=s.precision?r.substring(0,s.precision):r;break;case"u":r=parseInt(r,10)>>>0;break;case"v":r=r.valueOf(),r=s.precision?r.substring(0,s.precision):r;break;case"x":r=(parseInt(r,10)>>>0).toString(16);break;case"X":r=(parseInt(r,10)>>>0).toString(16).toUpperCase()}g.json.test(s.type)?d+=r:(!g.number.test(s.type)||c&&!s.sign?l="":(l=c?"+":"-",r=r.toString().replace(g.sign,"")),o=s.pad_char?"0"===s.pad_char?"0":s.pad_char.charAt(1):" ",p=s.width-(l+r).length,a=s.width&&0 | <%= pkg.author %> | <%= pkg.license %> */\n", - sourceMap: true - }, - build: { - files: [ - { - src: "src/sprintf.js", - dest: "dist/sprintf.min.js" - }, - { - src: "src/angular-sprintf.js", - dest: "dist/angular-sprintf.min.js" - } - ] - } - }, - - watch: { - js: { - files: "src/*.js", - tasks: ["uglify"] - } - } - }) - - grunt.loadNpmTasks("grunt-contrib-uglify") - grunt.loadNpmTasks("grunt-contrib-watch") - - grunt.registerTask("default", ["uglify", "watch"]) -} diff --git a/node_modules/sprintf-js/package.json b/node_modules/sprintf-js/package.json deleted file mode 100644 index 1d3dcf3deef66..0000000000000 --- a/node_modules/sprintf-js/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "sprintf-js", - "version": "1.1.3", - "description": "JavaScript sprintf implementation", - "author": "Alexandru Mărășteanu ", - "main": "src/sprintf.js", - "scripts": { - "test": "mocha test/*.js", - "pretest": "npm run lint", - "lint": "eslint .", - "lint:fix": "eslint --fix ." - }, - "repository": { - "type": "git", - "url": "https://github.com/alexei/sprintf.js.git" - }, - "license": "BSD-3-Clause", - "readmeFilename": "README.md", - "devDependencies": { - "benchmark": "^2.1.4", - "eslint": "^5.10.0", - "gulp": "^3.9.1", - "gulp-benchmark": "^1.1.1", - "gulp-eslint": "^5.0.0", - "gulp-header": "^2.0.5", - "gulp-mocha": "^6.0.0", - "gulp-rename": "^1.4.0", - "gulp-sourcemaps": "^2.6.4", - "gulp-uglify": "^3.0.1", - "mocha": "^5.2.0" - }, - "overrides": { - "graceful-fs": "^4.2.11" - } -} diff --git a/node_modules/sprintf-js/src/angular-sprintf.js b/node_modules/sprintf-js/src/angular-sprintf.js deleted file mode 100644 index dbfdd65ab2508..0000000000000 --- a/node_modules/sprintf-js/src/angular-sprintf.js +++ /dev/null @@ -1,24 +0,0 @@ -/* global angular, sprintf, vsprintf */ - -!function() { - 'use strict' - - angular. - module('sprintf', []). - filter('sprintf', function() { - return function() { - return sprintf.apply(null, arguments) - } - }). - filter('fmt', ['$filter', function($filter) { - return $filter('sprintf') - }]). - filter('vsprintf', function() { - return function(format, argv) { - return vsprintf(format, argv) - } - }). - filter('vfmt', ['$filter', function($filter) { - return $filter('vsprintf') - }]) -}(); // eslint-disable-line diff --git a/node_modules/sprintf-js/src/sprintf.js b/node_modules/sprintf-js/src/sprintf.js deleted file mode 100644 index 65d6324645ef1..0000000000000 --- a/node_modules/sprintf-js/src/sprintf.js +++ /dev/null @@ -1,231 +0,0 @@ -/* global window, exports, define */ - -!function() { - 'use strict' - - var re = { - not_string: /[^s]/, - not_bool: /[^t]/, - not_type: /[^T]/, - not_primitive: /[^v]/, - number: /[diefg]/, - numeric_arg: /[bcdiefguxX]/, - json: /[j]/, - not_json: /[^j]/, - text: /^[^\x25]+/, - modulo: /^\x25{2}/, - placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, - key: /^([a-z_][a-z_\d]*)/i, - key_access: /^\.([a-z_][a-z_\d]*)/i, - index_access: /^\[(\d+)\]/, - sign: /^[+-]/ - } - - function sprintf(key) { - // `arguments` is not an array, but should be fine for this call - return sprintf_format(sprintf_parse(key), arguments) - } - - function vsprintf(fmt, argv) { - return sprintf.apply(null, [fmt].concat(argv || [])) - } - - function sprintf_format(parse_tree, argv) { - var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign - for (i = 0; i < tree_length; i++) { - if (typeof parse_tree[i] === 'string') { - output += parse_tree[i] - } - else if (typeof parse_tree[i] === 'object') { - ph = parse_tree[i] // convenience purposes only - if (ph.keys) { // keyword argument - arg = argv[cursor] - for (k = 0; k < ph.keys.length; k++) { - if (arg == undefined) { - throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1])) - } - arg = arg[ph.keys[k]] - } - } - else if (ph.param_no) { // positional argument (explicit) - arg = argv[ph.param_no] - } - else { // positional argument (implicit) - arg = argv[cursor++] - } - - if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) { - arg = arg() - } - - if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) { - throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg)) - } - - if (re.number.test(ph.type)) { - is_positive = arg >= 0 - } - - switch (ph.type) { - case 'b': - arg = parseInt(arg, 10).toString(2) - break - case 'c': - arg = String.fromCharCode(parseInt(arg, 10)) - break - case 'd': - case 'i': - arg = parseInt(arg, 10) - break - case 'j': - arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0) - break - case 'e': - arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential() - break - case 'f': - arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg) - break - case 'g': - arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg) - break - case 'o': - arg = (parseInt(arg, 10) >>> 0).toString(8) - break - case 's': - arg = String(arg) - arg = (ph.precision ? arg.substring(0, ph.precision) : arg) - break - case 't': - arg = String(!!arg) - arg = (ph.precision ? arg.substring(0, ph.precision) : arg) - break - case 'T': - arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase() - arg = (ph.precision ? arg.substring(0, ph.precision) : arg) - break - case 'u': - arg = parseInt(arg, 10) >>> 0 - break - case 'v': - arg = arg.valueOf() - arg = (ph.precision ? arg.substring(0, ph.precision) : arg) - break - case 'x': - arg = (parseInt(arg, 10) >>> 0).toString(16) - break - case 'X': - arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase() - break - } - if (re.json.test(ph.type)) { - output += arg - } - else { - if (re.number.test(ph.type) && (!is_positive || ph.sign)) { - sign = is_positive ? '+' : '-' - arg = arg.toString().replace(re.sign, '') - } - else { - sign = '' - } - pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ' - pad_length = ph.width - (sign + arg).length - pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '' - output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg) - } - } - } - return output - } - - var sprintf_cache = Object.create(null) - - function sprintf_parse(fmt) { - if (sprintf_cache[fmt]) { - return sprintf_cache[fmt] - } - - var _fmt = fmt, match, parse_tree = [], arg_names = 0 - while (_fmt) { - if ((match = re.text.exec(_fmt)) !== null) { - parse_tree.push(match[0]) - } - else if ((match = re.modulo.exec(_fmt)) !== null) { - parse_tree.push('%') - } - else if ((match = re.placeholder.exec(_fmt)) !== null) { - if (match[2]) { - arg_names |= 1 - var field_list = [], replacement_field = match[2], field_match = [] - if ((field_match = re.key.exec(replacement_field)) !== null) { - field_list.push(field_match[1]) - while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { - if ((field_match = re.key_access.exec(replacement_field)) !== null) { - field_list.push(field_match[1]) - } - else if ((field_match = re.index_access.exec(replacement_field)) !== null) { - field_list.push(field_match[1]) - } - else { - throw new SyntaxError('[sprintf] failed to parse named argument key') - } - } - } - else { - throw new SyntaxError('[sprintf] failed to parse named argument key') - } - match[2] = field_list - } - else { - arg_names |= 2 - } - if (arg_names === 3) { - throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported') - } - - parse_tree.push( - { - placeholder: match[0], - param_no: match[1], - keys: match[2], - sign: match[3], - pad_char: match[4], - align: match[5], - width: match[6], - precision: match[7], - type: match[8] - } - ) - } - else { - throw new SyntaxError('[sprintf] unexpected placeholder') - } - _fmt = _fmt.substring(match[0].length) - } - return sprintf_cache[fmt] = parse_tree - } - - /** - * export to either browser or node.js - */ - /* eslint-disable quote-props */ - if (typeof exports !== 'undefined') { - exports['sprintf'] = sprintf - exports['vsprintf'] = vsprintf - } - if (typeof window !== 'undefined') { - window['sprintf'] = sprintf - window['vsprintf'] = vsprintf - - if (typeof define === 'function' && define['amd']) { - define(function() { - return { - 'sprintf': sprintf, - 'vsprintf': vsprintf - } - }) - } - } - /* eslint-enable quote-props */ -}(); // eslint-disable-line diff --git a/node_modules/sprintf-js/test/test.js b/node_modules/sprintf-js/test/test.js deleted file mode 100644 index 6f57b2538c852..0000000000000 --- a/node_modules/sprintf-js/test/test.js +++ /dev/null @@ -1,82 +0,0 @@ -var assert = require("assert"), - sprintfjs = require("../src/sprintf.js"), - sprintf = sprintfjs.sprintf, - vsprintf = sprintfjs.vsprintf - -describe("sprintfjs", function() { - var pi = 3.141592653589793 - - it("should return formated strings for simple placeholders", function() { - assert.equal("%", sprintf("%%")) - assert.equal("10", sprintf("%b", 2)) - assert.equal("A", sprintf("%c", 65)) - assert.equal("2", sprintf("%d", 2)) - assert.equal("2", sprintf("%i", 2)) - assert.equal("2", sprintf("%d", "2")) - assert.equal("2", sprintf("%i", "2")) - assert.equal('{"foo":"bar"}', sprintf("%j", {foo: "bar"})) - assert.equal('["foo","bar"]', sprintf("%j", ["foo", "bar"])) - assert.equal("2e+0", sprintf("%e", 2)) - assert.equal("2", sprintf("%u", 2)) - assert.equal("4294967294", sprintf("%u", -2)) - assert.equal("2.2", sprintf("%f", 2.2)) - assert.equal("3.141592653589793", sprintf("%g", pi)) - assert.equal("10", sprintf("%o", 8)) - assert.equal("%s", sprintf("%s", "%s")) - assert.equal("ff", sprintf("%x", 255)) - assert.equal("FF", sprintf("%X", 255)) - assert.equal("Polly wants a cracker", sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants")) - assert.equal("Hello world!", sprintf("Hello %(who)s!", {"who": "world"})) - }) - - it("should return formated strings for complex placeholders", function() { - // sign - assert.equal("2", sprintf("%d", 2)) - assert.equal("-2", sprintf("%d", -2)) - assert.equal("+2", sprintf("%+d", 2)) - assert.equal("-2", sprintf("%+d", -2)) - assert.equal("2", sprintf("%i", 2)) - assert.equal("-2", sprintf("%i", -2)) - assert.equal("+2", sprintf("%+i", 2)) - assert.equal("-2", sprintf("%+i", -2)) - assert.equal("2.2", sprintf("%f", 2.2)) - assert.equal("-2.2", sprintf("%f", -2.2)) - assert.equal("+2.2", sprintf("%+f", 2.2)) - assert.equal("-2.2", sprintf("%+f", -2.2)) - assert.equal("-2.3", sprintf("%+.1f", -2.34)) - assert.equal("-0.0", sprintf("%+.1f", -0.01)) - assert.equal("3.14159", sprintf("%.6g", pi)) - assert.equal("3.14", sprintf("%.3g", pi)) - assert.equal("3", sprintf("%.1g", pi)) - assert.equal("-000000123", sprintf("%+010d", -123)) - assert.equal("______-123", sprintf("%+'_10d", -123)) - assert.equal("-234.34 123.2", sprintf("%f %f", -234.34, 123.2)) - - // padding - assert.equal("-0002", sprintf("%05d", -2)) - assert.equal("-0002", sprintf("%05i", -2)) - assert.equal(" <", sprintf("%5s", "<")) - assert.equal("0000<", sprintf("%05s", "<")) - assert.equal("____<", sprintf("%'_5s", "<")) - assert.equal("> ", sprintf("%-5s", ">")) - assert.equal(">0000", sprintf("%0-5s", ">")) - assert.equal(">____", sprintf("%'_-5s", ">")) - assert.equal("xxxxxx", sprintf("%5s", "xxxxxx")) - assert.equal("1234", sprintf("%02u", 1234)) - assert.equal(" -10.235", sprintf("%8.3f", -10.23456)) - assert.equal("-12.34 xxx", sprintf("%f %s", -12.34, "xxx")) - assert.equal('{\n "foo": "bar"\n}', sprintf("%2j", {foo: "bar"})) - assert.equal('[\n "foo",\n "bar"\n]', sprintf("%2j", ["foo", "bar"])) - - // precision - assert.equal("2.3", sprintf("%.1f", 2.345)) - assert.equal("xxxxx", sprintf("%5.5s", "xxxxxx")) - assert.equal(" x", sprintf("%5.1s", "xxxxxx")) - - }) - - it("should return formated strings for callbacks", function() { - assert.equal("foobar", sprintf("%s", function() { return "foobar" })) - assert.equal(Date.now(), sprintf("%s", Date.now)) // should pass... - }) -}) diff --git a/node_modules/ssri/lib/index.js b/node_modules/ssri/lib/index.js index 7d749ed480fb9..00102d6547246 100644 --- a/node_modules/ssri/lib/index.js +++ b/node_modules/ssri/lib/index.js @@ -5,14 +5,21 @@ const { Minipass } = require('minipass') const SPEC_ALGORITHMS = ['sha512', 'sha384', 'sha256'] const DEFAULT_ALGORITHMS = ['sha512'] +const NODE_HASHES = crypto.getHashes() -// TODO: this should really be a hardcoded list of algorithms we support, -// rather than [a-z0-9]. +// TODO: this should really be a hardcoded list of algorithms we support, rather than [a-z0-9]. const BASE64_REGEX = /^[a-z0-9+/]+(?:=?=?)$/i -const SRI_REGEX = /^([a-z0-9]+)-([^?]+)([?\S*]*)$/ +const SRI_REGEX = /^([a-z0-9]+)-([^?]+)(\?[?\S*]*)?$/ const STRICT_SRI_REGEX = /^([a-z0-9]+)-([A-Za-z0-9+/=]{44,88})(\?[\x21-\x7E]*)?$/ const VCHAR_REGEX = /^[\x21-\x7E]+$/ +// This is a Best Effort™ at a reasonable priority for hash algos +const DEFAULT_PRIORITY = [ + 'md5', 'whirlpool', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512', + // TODO - it's unclear _which_ of these Node will actually use as its name for the algorithm, so we guesswork it based on the OpenSSL names. + 'sha3', 'sha3-256', 'sha3-384', 'sha3-512', 'sha3_256', 'sha3_384', 'sha3_512', +].filter(algo => NODE_HASHES.includes(algo)) + const getOptString = options => options?.length ? `?${options.join('?')}` : '' class IntegrityStream extends Minipass { @@ -99,7 +106,6 @@ class IntegrityStream extends Minipass { // Integrity verification mode const match = this.goodSri && newSri.match(this.sri, this.opts) if (typeof this.expectedSize === 'number' && this.size !== this.expectedSize) { - /* eslint-disable-next-line max-len */ const err = new Error(`stream size mismatch when checking ${this.sri}.\n Wanted: ${this.expectedSize}\n Found: ${this.size}`) err.code = 'EBADSIZE' err.found = this.size @@ -107,7 +113,6 @@ class IntegrityStream extends Minipass { err.sri = this.sri this.emit('error', err) } else if (this.sri && !match) { - /* eslint-disable-next-line max-len */ const err = new Error(`${this.sri} integrity checksum failed when using ${this.algorithm}: wanted ${this.digests} but got ${newSri}. (${this.size} bytes)`) err.code = 'EINTEGRITY' err.found = newSri @@ -137,8 +142,7 @@ class Hash { const strict = opts?.strict this.source = hash.trim() - // set default values so that we make V8 happy to - // always see a familiar object template. + // set default values so that we make V8 happy to always see a familiar object template. this.digest = '' this.algorithm = '' this.options = [] @@ -156,6 +160,9 @@ class Hash { if (strict && !SPEC_ALGORITHMS.includes(match[1])) { return } + if (!NODE_HASHES.includes(match[1])) { + return + } this.algorithm = match[1] this.digest = match[2] @@ -198,15 +205,12 @@ class Hash { toString (opts) { if (opts?.strict) { - // Strict mode enforces the standard as close to the foot of the - // letter as it can. + // Strict mode enforces the standard as close to the foot of the letter as it can. if (!( // The spec has very restricted productions for algorithms. // https://www.w3.org/TR/CSP2/#source-list-syntax SPEC_ALGORITHMS.includes(this.algorithm) && - // Usually, if someone insists on using a "different" base64, we - // leave it as-is, since there's multiple standards, and the - // specified is not a URL-safe variant. + // Usually, if someone insists on using a "different" base64, we leave it as-is, since there are multiple standards, and the specified is not a URL-safe variant. // https://www.w3.org/TR/CSP2/#base64_value this.digest.match(BASE64_REGEX) && // Option syntax is strictly visual chars. @@ -300,8 +304,7 @@ class Integrity { return parse(this, { single: true }).hexDigest() } - // add additional hashes to an integrity value, but prevent - // *changing* an existing integrity hash. + // add additional hashes to an integrity value, but prevent *changing* an existing integrity hash. merge (integrity, opts) { const other = parse(integrity, opts) for (const algo in other) { @@ -323,33 +326,25 @@ class Integrity { return false } const algo = other.pickAlgorithm(opts, Object.keys(this)) - return ( - !!algo && - this[algo] && - other[algo] && - this[algo].find(hash => - other[algo].find(otherhash => - hash.digest === otherhash.digest - ) + return !!algo && this[algo].find(hash => + other[algo].find(otherhash => + hash.digest === otherhash.digest ) ) || false } - // Pick the highest priority algorithm present, optionally also limited to a - // set of hashes found in another integrity. When limiting it may return - // nothing. + // Pick the highest priority algorithm present, optionally also limited to a set of hashes found in another integrity. + // When limiting it may return nothing. pickAlgorithm (opts, hashes) { const pickAlgorithm = opts?.pickAlgorithm || getPrioritizedHash - const keys = Object.keys(this).filter(k => { - if (hashes?.length) { - return hashes.includes(k) - } - return true - }) + let keys = Object.keys(this) + if (hashes?.length) { + keys = keys.filter(k => hashes.includes(k)) + } if (keys.length) { return keys.reduce((acc, algo) => pickAlgorithm(acc, algo) || acc) } - // no intersection between this and hashes, + // no intersection between this and hashes return null } } @@ -380,7 +375,7 @@ function _parse (integrity, opts) { const hash = new Hash(string, opts) if (hash.algorithm && hash.digest) { const algo = hash.algorithm - if (!acc[algo]) { + if (!Object.keys(acc).includes(algo)) { acc[algo] = [] } acc[algo].push(hash) @@ -421,9 +416,7 @@ function fromData (data, opts) { `${algo}-${digest}${optString}`, opts ) - /* istanbul ignore else - it would be VERY strange if the string we - * just calculated with an algo did not have an algo or digest. - */ + // istanbul ignore else - it would be VERY strange if the string we just calculated with an algo did not have an algo or digest. if (hash.algorithm && hash.digest) { const hashAlgo = hash.algorithm if (!acc[hashAlgo]) { @@ -473,7 +466,6 @@ function checkData (data, sri, opts) { if (match || !(opts.error)) { return match } else if (typeof opts.size === 'number' && (data.length !== opts.size)) { - /* eslint-disable-next-line max-len */ const err = new Error(`data size mismatch when checking ${sri}.\n Wanted: ${opts.size}\n Found: ${data.length}`) err.code = 'EBADSIZE' err.found = data.length @@ -481,7 +473,6 @@ function checkData (data, sri, opts) { err.sri = sri throw err } else { - /* eslint-disable-next-line max-len */ const err = new Error(`Integrity checksum failed when using ${algorithm}: Wanted ${sri}, but got ${newSri}. (${data.length} bytes)`) err.code = 'EINTEGRITY' err.found = newSri @@ -538,20 +529,11 @@ function createIntegrity (opts) { digest: function () { const integrity = algorithms.reduce((acc, algo) => { const digest = hashes.shift().digest('base64') - const hash = new Hash( - `${algo}-${digest}${optString}`, - opts - ) - /* istanbul ignore else - it would be VERY strange if the hash we - * just calculated with an algo did not have an algo or digest. - */ - if (hash.algorithm && hash.digest) { - const hashAlgo = hash.algorithm - if (!acc[hashAlgo]) { - acc[hashAlgo] = [] - } - acc[hashAlgo].push(hash) + const hash = new Hash(`${algo}-${digest}${optString}`, opts) + if (!acc[hash.algorithm]) { + acc[hash.algorithm] = [] } + acc[hash.algorithm].push(hash) return acc }, new Integrity()) @@ -560,18 +542,6 @@ function createIntegrity (opts) { } } -const NODE_HASHES = crypto.getHashes() - -// This is a Best Effort™ at a reasonable priority for hash algos -const DEFAULT_PRIORITY = [ - 'md5', 'whirlpool', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512', - // TODO - it's unclear _which_ of these Node will actually use as its name - // for the algorithm, so we guesswork it based on the OpenSSL names. - 'sha3', - 'sha3-256', 'sha3-384', 'sha3-512', - 'sha3_256', 'sha3_384', 'sha3_512', -].filter(algo => NODE_HASHES.includes(algo)) - function getPrioritizedHash (algo1, algo2) { /* eslint-disable-next-line max-len */ return DEFAULT_PRIORITY.indexOf(algo1.toLowerCase()) >= DEFAULT_PRIORITY.indexOf(algo2.toLowerCase()) diff --git a/node_modules/ssri/package.json b/node_modules/ssri/package.json index 28395414e4643..c5126ce55ba3d 100644 --- a/node_modules/ssri/package.json +++ b/node_modules/ssri/package.json @@ -1,6 +1,6 @@ { "name": "ssri", - "version": "10.0.6", + "version": "14.0.0", "description": "Standard Subresource Integrity library -- parses, serializes, generates, and verifies integrity metadata according to the SRI spec.", "main": "lib/index.js", "files": [ @@ -11,20 +11,16 @@ "prerelease": "npm t", "postrelease": "npm publish", "posttest": "npm run lint", - "test": "tap", + "test": "node --test './test/**/*.js'", "coverage": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap" - }, - "tap": { - "check-coverage": true, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] + "lintfix": "npm run eslint -- --fix", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test:node20": "node --test test", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'" }, "repository": { "type": "git", @@ -50,16 +46,21 @@ "minipass": "^7.0.3" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.1" + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0", + "benchmark": "^2.1.4" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": "true" + "version": "5.0.0", + "publish": "true", + "allowPaths": [ + "benchmarks/" + ], + "testRunner": "node:test", + "latestVersion": 24 } } diff --git a/node_modules/string-width-cjs/index.js b/node_modules/string-width-cjs/index.js deleted file mode 100644 index f4d261a96a099..0000000000000 --- a/node_modules/string-width-cjs/index.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; -const stripAnsi = require('strip-ansi'); -const isFullwidthCodePoint = require('is-fullwidth-code-point'); -const emojiRegex = require('emoji-regex'); - -const stringWidth = string => { - if (typeof string !== 'string' || string.length === 0) { - return 0; - } - - string = stripAnsi(string); - - if (string.length === 0) { - return 0; - } - - string = string.replace(emojiRegex(), ' '); - - let width = 0; - - for (let i = 0; i < string.length; i++) { - const code = string.codePointAt(i); - - // Ignore control characters - if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { - continue; - } - - // Ignore combining characters - if (code >= 0x300 && code <= 0x36F) { - continue; - } - - // Surrogates - if (code > 0xFFFF) { - i++; - } - - width += isFullwidthCodePoint(code) ? 2 : 1; - } - - return width; -}; - -module.exports = stringWidth; -// TODO: remove this in the next major version -module.exports.default = stringWidth; diff --git a/node_modules/string-width-cjs/license b/node_modules/string-width-cjs/license deleted file mode 100644 index e7af2f77107d7..0000000000000 --- a/node_modules/string-width-cjs/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/string-width-cjs/package.json b/node_modules/string-width-cjs/package.json deleted file mode 100644 index 28ba7b4cae9bf..0000000000000 --- a/node_modules/string-width-cjs/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "string-width", - "version": "4.2.3", - "description": "Get the visual width of a string - the number of columns required to display it", - "license": "MIT", - "repository": "sindresorhus/string-width", - "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": [ - "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": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "devDependencies": { - "ava": "^1.4.1", - "tsd": "^0.7.1", - "xo": "^0.24.0" - } -} diff --git a/node_modules/string-width/index.js b/node_modules/string-width/index.js deleted file mode 100644 index f4d261a96a099..0000000000000 --- a/node_modules/string-width/index.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; -const stripAnsi = require('strip-ansi'); -const isFullwidthCodePoint = require('is-fullwidth-code-point'); -const emojiRegex = require('emoji-regex'); - -const stringWidth = string => { - if (typeof string !== 'string' || string.length === 0) { - return 0; - } - - string = stripAnsi(string); - - if (string.length === 0) { - return 0; - } - - string = string.replace(emojiRegex(), ' '); - - let width = 0; - - for (let i = 0; i < string.length; i++) { - const code = string.codePointAt(i); - - // Ignore control characters - if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { - continue; - } - - // Ignore combining characters - if (code >= 0x300 && code <= 0x36F) { - continue; - } - - // Surrogates - if (code > 0xFFFF) { - i++; - } - - width += isFullwidthCodePoint(code) ? 2 : 1; - } - - return width; -}; - -module.exports = stringWidth; -// TODO: remove this in the next major version -module.exports.default = stringWidth; diff --git a/node_modules/string-width/license b/node_modules/string-width/license deleted file mode 100644 index e7af2f77107d7..0000000000000 --- a/node_modules/string-width/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/string-width/package.json b/node_modules/string-width/package.json deleted file mode 100644 index 28ba7b4cae9bf..0000000000000 --- a/node_modules/string-width/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "string-width", - "version": "4.2.3", - "description": "Get the visual width of a string - the number of columns required to display it", - "license": "MIT", - "repository": "sindresorhus/string-width", - "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": [ - "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": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "devDependencies": { - "ava": "^1.4.1", - "tsd": "^0.7.1", - "xo": "^0.24.0" - } -} diff --git a/node_modules/strip-ansi-cjs/index.js b/node_modules/strip-ansi-cjs/index.js deleted file mode 100644 index 9a593dfcd1fd5..0000000000000 --- a/node_modules/strip-ansi-cjs/index.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; -const ansiRegex = require('ansi-regex'); - -module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; diff --git a/node_modules/strip-ansi-cjs/license b/node_modules/strip-ansi-cjs/license deleted file mode 100644 index e7af2f77107d7..0000000000000 --- a/node_modules/strip-ansi-cjs/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/strip-ansi-cjs/package.json b/node_modules/strip-ansi-cjs/package.json deleted file mode 100644 index 1a41108d42831..0000000000000 --- a/node_modules/strip-ansi-cjs/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "strip-ansi", - "version": "6.0.1", - "description": "Strip ANSI escape codes from a string", - "license": "MIT", - "repository": "chalk/strip-ansi", - "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": [ - "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": "^5.0.1" - }, - "devDependencies": { - "ava": "^2.4.0", - "tsd": "^0.10.0", - "xo": "^0.25.3" - } -} diff --git a/node_modules/strip-ansi/index.js b/node_modules/strip-ansi/index.js deleted file mode 100644 index 9a593dfcd1fd5..0000000000000 --- a/node_modules/strip-ansi/index.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; -const ansiRegex = require('ansi-regex'); - -module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; diff --git a/node_modules/strip-ansi/license b/node_modules/strip-ansi/license deleted file mode 100644 index e7af2f77107d7..0000000000000 --- a/node_modules/strip-ansi/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/strip-ansi/package.json b/node_modules/strip-ansi/package.json deleted file mode 100644 index 1a41108d42831..0000000000000 --- a/node_modules/strip-ansi/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "strip-ansi", - "version": "6.0.1", - "description": "Strip ANSI escape codes from a string", - "license": "MIT", - "repository": "chalk/strip-ansi", - "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": [ - "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": "^5.0.1" - }, - "devDependencies": { - "ava": "^2.4.0", - "tsd": "^0.10.0", - "xo": "^0.25.3" - } -} diff --git a/node_modules/supports-color/browser.js b/node_modules/supports-color/browser.js index 1ffde642ae2ea..f9008d8e71357 100644 --- a/node_modules/supports-color/browser.js +++ b/node_modules/supports-color/browser.js @@ -1,14 +1,19 @@ /* eslint-env browser */ +/* eslint-disable n/no-unsupported-features/node-builtins */ const level = (() => { - if (navigator.userAgentData) { + if (!('navigator' in globalThis)) { + return 0; + } + + if (globalThis.navigator.userAgentData) { const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium'); if (brand?.version > 93) { return 3; } } - if (/\b(Chrome|Chromium)\//.test(navigator.userAgent)) { + if (/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)) { return 1; } diff --git a/node_modules/supports-color/index.js b/node_modules/supports-color/index.js index 4ce0a2da8d224..906a6f9b83224 100644 --- a/node_modules/supports-color/index.js +++ b/node_modules/supports-color/index.js @@ -31,17 +31,29 @@ if ( } function envForceColor() { - if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === 'true') { - return 1; - } + if (!('FORCE_COLOR' in env)) { + return; + } - if (env.FORCE_COLOR === 'false') { - return 0; - } + if (env.FORCE_COLOR === 'true') { + return 1; + } + + if (env.FORCE_COLOR === 'false') { + return 0; + } + + if (env.FORCE_COLOR.length === 0) { + return 1; + } + + const level = Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); - return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); + if (![0, 1, 2, 3].includes(level)) { + return; } + + return level; } function translateLevel(level) { @@ -112,11 +124,11 @@ function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { } if ('CI' in env) { - if ('GITHUB_ACTIONS' in env || 'GITEA_ACTIONS' in env) { + if (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) { return 3; } - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + if (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } @@ -135,6 +147,14 @@ function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { return 3; } + if (env.TERM === 'xterm-ghostty') { + return 3; + } + + if (env.TERM === 'wezterm') { + return 3; + } + if ('TERM_PROGRAM' in env) { const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); diff --git a/node_modules/supports-color/package.json b/node_modules/supports-color/package.json index 738684722643c..8915597ab45a0 100644 --- a/node_modules/supports-color/package.json +++ b/node_modules/supports-color/package.json @@ -1,6 +1,6 @@ { "name": "supports-color", - "version": "9.4.0", + "version": "10.2.2", "description": "Detect whether a terminal supports color", "license": "MIT", "repository": "chalk/supports-color", @@ -12,15 +12,16 @@ }, "type": "module", "exports": { + "types": "./index.d.ts", "node": "./index.js", "default": "./browser.js" }, + "sideEffects": false, "engines": { - "node": ">=12" + "node": ">=18" }, "scripts": { - "//test": "xo && ava && tsd", - "test": "tsd" + "test": "xo && ava && tsd" }, "files": [ "index.js", @@ -51,10 +52,13 @@ "16m" ], "devDependencies": { - "@types/node": "^20.3.2", - "ava": "^5.3.1", - "import-fresh": "^3.3.0", - "tsd": "^0.18.0", - "xo": "^0.54.2" + "@types/node": "^22.10.2", + "ava": "^6.2.0", + "tsd": "^0.31.2", + "xo": "^0.60.0" + }, + "ava": { + "serial": true, + "workerThreads": false } } diff --git a/node_modules/tar/LICENSE b/node_modules/tar/LICENSE deleted file mode 100644 index 19129e315fe59..0000000000000 --- a/node_modules/tar/LICENSE +++ /dev/null @@ -1,15 +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. diff --git a/node_modules/tar/LICENSE.md b/node_modules/tar/LICENSE.md new file mode 100644 index 0000000000000..c5402b9577a8c --- /dev/null +++ b/node_modules/tar/LICENSE.md @@ -0,0 +1,55 @@ +# 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.*** diff --git a/node_modules/tar/dist/commonjs/create.js b/node_modules/tar/dist/commonjs/create.js new file mode 100644 index 0000000000000..5339c93f47ca8 --- /dev/null +++ b/node_modules/tar/dist/commonjs/create.js @@ -0,0 +1,82 @@ +"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).catch(er => p.emit('error', er)); + 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 (const file of files) { + 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).catch(er => p.emit('error', er)); + 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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/cwd-error.js b/node_modules/tar/dist/commonjs/cwd-error.js new file mode 100644 index 0000000000000..d703a7772be3a --- /dev/null +++ b/node_modules/tar/dist/commonjs/cwd-error.js @@ -0,0 +1,18 @@ +"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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/extract.js b/node_modules/tar/dist/commonjs/extract.js new file mode 100644 index 0000000000000..86deb304d8b01 --- /dev/null +++ b/node_modules/tar/dist/commonjs/extract.js @@ -0,0 +1,88 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/get-write-flag.js b/node_modules/tar/dist/commonjs/get-write-flag.js new file mode 100644 index 0000000000000..82d7d502aeb83 --- /dev/null +++ b/node_modules/tar/dist/commonjs/get-write-flag.js @@ -0,0 +1,32 @@ +"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_NOFOLLOW, 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; +const noFollowFlag = !isWindows && typeof O_NOFOLLOW === 'number' ? + O_NOFOLLOW | O_TRUNC | O_CREAT | O_WRONLY + : null; +exports.getWriteFlag = noFollowFlag !== null ? () => noFollowFlag + : !fMapEnabled ? () => 'w' + : (size) => (size < fMapLimit ? fMapFlag : 'w'); +//# sourceMappingURL=get-write-flag.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/header.js b/node_modules/tar/dist/commonjs/header.js new file mode 100644 index 0000000000000..d6e8f0ec34267 --- /dev/null +++ b/node_modules/tar/dist/commonjs/header.js @@ -0,0 +1,347 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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'); + } + // Decode the typeflag (independent of any pending PAX/GNU extended header) + // up front so we can tell whether THIS block is itself an intermediary + // extension header (PAX `x`/`g`, GNU long-name `L`, GNU long-link `K`). + // Per POSIX pax, a PAX extended header describes the *next file entry*, not + // the extension headers that may sit between it and that file. Applying the + // pending PAX overrides (notably `size`) to an intervening `L`/`K`/`x`/`g` + // header desynchronizes the stream relative to other tar implementations + // and enables tar interpretation-conflict / file-smuggling attacks. + const t = decString(buf, off + 156, 1); + const isNormalFS = types.normalFsTypes.has(t); + const exForFields = isNormalFS ? ex : undefined; + const gexForFields = isNormalFS ? gex : undefined; + this.path = exForFields?.path ?? decString(buf, off, 100); + this.mode = + exForFields?.mode ?? + gexForFields?.mode ?? + decNumber(buf, off + 100, 8); + this.uid = + exForFields?.uid ?? gexForFields?.uid ?? decNumber(buf, off + 108, 8); + this.gid = + exForFields?.gid ?? gexForFields?.gid ?? decNumber(buf, off + 116, 8); + this.size = + exForFields?.size ?? + gexForFields?.size ?? + decNumber(buf, off + 124, 12); + this.mtime = + exForFields?.mtime ?? + gexForFields?.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. Never slurp the pending + // extended-header fields onto an intermediary extension header. + if (gexForFields) + this.#slurp(gexForFields, true); + if (exForFields) + this.#slurp(exForFields); + // old tar versions marked dirs as a file with a trailing / + 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') { + /* c8 ignore start */ + this.uname = + exForFields?.uname ?? + gexForFields?.uname ?? + decString(buf, off + 265, 32); + this.gname = + exForFields?.gname ?? + gexForFields?.gname ?? + decString(buf, off + 297, 32); + this.devmaj = + exForFields?.devmaj ?? + gexForFields?.devmaj ?? + decNumber(buf, off + 329, 8) ?? + 0; + this.devmin = + exForFields?.devmin ?? + gexForFields?.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; + } + /* c8 ignore start */ + this.atime = ex?.atime ?? gex?.atime ?? decDate(buf, off + 476, 12); + this.ctime = ex?.ctime ?? gex?.ctime ?? decDate(buf, off + 488, 12); + /* c8 ignore stop */ + } + } + 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] = Number(this.#type.codePointAt(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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/index.js b/node_modules/tar/dist/commonjs/index.js new file mode 100644 index 0000000000000..bd975c77281b7 --- /dev/null +++ b/node_modules/tar/dist/commonjs/index.js @@ -0,0 +1,64 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/index.min.js b/node_modules/tar/dist/commonjs/index.min.js new file mode 100644 index 0000000000000..6bce016bcece4 --- /dev/null +++ b/node_modules/tar/dist/commonjs/index.min.js @@ -0,0 +1,4 @@ +"use strict";var d=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var We=d(F=>{"use strict";var Ro=F&&F.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(F,"__esModule",{value:!0});F.Minipass=F.isWritable=F.isReadable=F.isStream=void 0;var Br=typeof process=="object"&&process?process:{stdout:null,stderr:null},is=require("node:events"),jr=Ro(require("node:stream")),vo=require("node:string_decoder"),To=s=>!!s&&typeof s=="object"&&(s instanceof Zt||s instanceof jr.default||(0,F.isReadable)(s)||(0,F.isWritable)(s));F.isStream=To;var Do=s=>!!s&&typeof s=="object"&&s instanceof is.EventEmitter&&typeof s.pipe=="function"&&s.pipe!==jr.default.Writable.prototype.pipe;F.isReadable=Do;var Po=s=>!!s&&typeof s=="object"&&s instanceof is.EventEmitter&&typeof s.write=="function"&&typeof s.end=="function";F.isWritable=Po;var le=Symbol("EOF"),ue=Symbol("maybeEmitEnd"),_e=Symbol("emittedEnd"),xt=Symbol("emittingEnd"),dt=Symbol("emittedError"),jt=Symbol("closed"),zr=Symbol("read"),Ut=Symbol("flush"),kr=Symbol("flushChunk"),K=Symbol("encoding"),Ue=Symbol("decoder"),O=Symbol("flowing"),mt=Symbol("paused"),qe=Symbol("resume"),R=Symbol("buffer"),I=Symbol("pipes"),v=Symbol("bufferLength"),$i=Symbol("bufferPush"),qt=Symbol("bufferShift"),N=Symbol("objectMode"),y=Symbol("destroyed"),Xi=Symbol("error"),Qi=Symbol("emitData"),xr=Symbol("emitEnd"),Ji=Symbol("emitEnd2"),J=Symbol("async"),es=Symbol("abort"),Wt=Symbol("aborted"),pt=Symbol("signal"),Ne=Symbol("dataListeners"),x=Symbol("discarded"),_t=s=>Promise.resolve().then(s),No=s=>s(),Mo=s=>s==="end"||s==="finish"||s==="prefinish",Lo=s=>s instanceof ArrayBuffer||!!s&&typeof s=="object"&&s.constructor&&s.constructor.name==="ArrayBuffer"&&s.byteLength>=0,Ao=s=>!Buffer.isBuffer(s)&&ArrayBuffer.isView(s),Ht=class{src;dest;opts;ondrain;constructor(e,t,i){this.src=e,this.dest=t,this.opts=i,this.ondrain=()=>e[qe](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},ts=class extends Ht{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,i){super(e,t,i),this.proxyErrors=r=>this.dest.emit("error",r),e.on("error",this.proxyErrors)}},Io=s=>!!s.objectMode,Fo=s=>!s.objectMode&&!!s.encoding&&s.encoding!=="buffer",Zt=class extends is.EventEmitter{[O]=!1;[mt]=!1;[I]=[];[R]=[];[N];[K];[J];[Ue];[le]=!1;[_e]=!1;[xt]=!1;[jt]=!1;[dt]=null;[v]=0;[y]=!1;[pt];[Wt]=!1;[Ne]=0;[x]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Io(t)?(this[N]=!0,this[K]=null):Fo(t)?(this[K]=t.encoding,this[N]=!1):(this[N]=!1,this[K]=null),this[J]=!!t.async,this[Ue]=this[K]?new vo.StringDecoder(this[K]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[R]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[I]});let{signal:i}=t;i&&(this[pt]=i,i.aborted?this[es]():i.addEventListener("abort",()=>this[es]()))}get bufferLength(){return this[v]}get encoding(){return this[K]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[N]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[J]}set async(e){this[J]=this[J]||!!e}[es](){this[Wt]=!0,this.emit("abort",this[pt]?.reason),this.destroy(this[pt]?.reason)}get aborted(){return this[Wt]}set aborted(e){}write(e,t,i){if(this[Wt])return!1;if(this[le])throw new Error("write after end");if(this[y])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(i=t,t="utf8"),t||(t="utf8");let r=this[J]?_t:No;if(!this[N]&&!Buffer.isBuffer(e)){if(Ao(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(Lo(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[N]?(this[O]&&this[v]!==0&&this[Ut](!0),this[O]?this.emit("data",e):this[$i](e),this[v]!==0&&this.emit("readable"),i&&r(i),this[O]):e.length?(typeof e=="string"&&!(t===this[K]&&!this[Ue]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[K]&&(e=this[Ue].write(e)),this[O]&&this[v]!==0&&this[Ut](!0),this[O]?this.emit("data",e):this[$i](e),this[v]!==0&&this.emit("readable"),i&&r(i),this[O]):(this[v]!==0&&this.emit("readable"),i&&r(i),this[O])}read(e){if(this[y])return null;if(this[x]=!1,this[v]===0||e===0||e&&e>this[v])return this[ue](),null;this[N]&&(e=null),this[R].length>1&&!this[N]&&(this[R]=[this[K]?this[R].join(""):Buffer.concat(this[R],this[v])]);let t=this[zr](e||null,this[R][0]);return this[ue](),t}[zr](e,t){if(this[N])this[qt]();else{let i=t;e===i.length||e===null?this[qt]():typeof i=="string"?(this[R][0]=i.slice(e),t=i.slice(0,e),this[v]-=e):(this[R][0]=i.subarray(e),t=i.subarray(0,e),this[v]-=e)}return this.emit("data",t),!this[R].length&&!this[le]&&this.emit("drain"),t}end(e,t,i){return typeof e=="function"&&(i=e,e=void 0),typeof t=="function"&&(i=t,t="utf8"),e!==void 0&&this.write(e,t),i&&this.once("end",i),this[le]=!0,this.writable=!1,(this[O]||!this[mt])&&this[ue](),this}[qe](){this[y]||(!this[Ne]&&!this[I].length&&(this[x]=!0),this[mt]=!1,this[O]=!0,this.emit("resume"),this[R].length?this[Ut]():this[le]?this[ue]():this.emit("drain"))}resume(){return this[qe]()}pause(){this[O]=!1,this[mt]=!0,this[x]=!1}get destroyed(){return this[y]}get flowing(){return this[O]}get paused(){return this[mt]}[$i](e){this[N]?this[v]+=1:this[v]+=e.length,this[R].push(e)}[qt](){return this[N]?this[v]-=1:this[v]-=this[R][0].length,this[R].shift()}[Ut](e=!1){do;while(this[kr](this[qt]())&&this[R].length);!e&&!this[R].length&&!this[le]&&this.emit("drain")}[kr](e){return this.emit("data",e),this[O]}pipe(e,t){if(this[y])return e;this[x]=!1;let i=this[_e];return t=t||{},e===Br.stdout||e===Br.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,i?t.end&&e.end():(this[I].push(t.proxyErrors?new ts(this,e,t):new Ht(this,e,t)),this[J]?_t(()=>this[qe]()):this[qe]()),e}unpipe(e){let t=this[I].find(i=>i.dest===e);t&&(this[I].length===1?(this[O]&&this[Ne]===0&&(this[O]=!1),this[I]=[]):this[I].splice(this[I].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let i=super.on(e,t);if(e==="data")this[x]=!1,this[Ne]++,!this[I].length&&!this[O]&&this[qe]();else if(e==="readable"&&this[v]!==0)super.emit("readable");else if(Mo(e)&&this[_e])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[dt]){let r=t;this[J]?_t(()=>r.call(this,this[dt])):r.call(this,this[dt])}return i}removeListener(e,t){return this.off(e,t)}off(e,t){let i=super.off(e,t);return e==="data"&&(this[Ne]=this.listeners("data").length,this[Ne]===0&&!this[x]&&!this[I].length&&(this[O]=!1)),i}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Ne]=0,!this[x]&&!this[I].length&&(this[O]=!1)),t}get emittedEnd(){return this[_e]}[ue](){!this[xt]&&!this[_e]&&!this[y]&&this[R].length===0&&this[le]&&(this[xt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[jt]&&this.emit("close"),this[xt]=!1)}emit(e,...t){let i=t[0];if(e!=="error"&&e!=="close"&&e!==y&&this[y])return!1;if(e==="data")return!this[N]&&!i?!1:this[J]?(_t(()=>this[Qi](i)),!0):this[Qi](i);if(e==="end")return this[xr]();if(e==="close"){if(this[jt]=!0,!this[_e]&&!this[y])return!1;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(e==="error"){this[dt]=i,super.emit(Xi,i);let n=!this[pt]||this.listeners("error").length?super.emit("error",i):!1;return this[ue](),n}else if(e==="resume"){let n=super.emit("resume");return this[ue](),n}else if(e==="finish"||e==="prefinish"){let n=super.emit(e);return this.removeAllListeners(e),n}let r=super.emit(e,...t);return this[ue](),r}[Qi](e){for(let i of this[I])i.dest.write(e)===!1&&this.pause();let t=this[x]?!1:super.emit("data",e);return this[ue](),t}[xr](){return this[_e]?!1:(this[_e]=!0,this.readable=!1,this[J]?(_t(()=>this[Ji]()),!0):this[Ji]())}[Ji](){if(this[Ue]){let t=this[Ue].end();if(t){for(let i of this[I])i.dest.write(t);this[x]||super.emit("data",t)}}for(let t of this[I])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[N]||(e.dataLength=0);let t=this.promise();return this.on("data",i=>{e.push(i),this[N]||(e.dataLength+=i.length)}),await t,e}async concat(){if(this[N])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[K]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(y,()=>t(new Error("stream destroyed"))),this.on("error",i=>t(i)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[x]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[le])return t();let n,o,h=c=>{this.off("data",a),this.off("end",l),this.off(y,u),t(),o(c)},a=c=>{this.off("error",h),this.off("end",l),this.off(y,u),this.pause(),n({value:c,done:!!this[le]})},l=()=>{this.off("error",h),this.off("data",a),this.off(y,u),t(),n({done:!0,value:void 0})},u=()=>h(new Error("stream destroyed"));return new Promise((c,E)=>{o=E,n=c,this.once(y,u),this.once("error",h),this.once("end",l),this.once("data",a)})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[x]=!1;let e=!1,t=()=>(this.pause(),this.off(Xi,t),this.off(y,t),this.off("end",t),e=!0,{done:!0,value:void 0}),i=()=>{if(e)return t();let r=this.read();return r===null?t():{done:!1,value:r}};return this.once("end",t),this.once(Xi,t),this.once(y,t),{next:i,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[y])return e?this.emit("error",e):this.emit(y),this;this[y]=!0,this[x]=!0,this[R].length=0,this[v]=0;let t=this;return typeof t.close=="function"&&!this[jt]&&t.close(),e?this.emit("error",e):this.emit(y),this}static get isStream(){return F.isStream}};F.Minipass=Zt});var Ke=d(W=>{"use strict";var Ur=W&&W.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(W,"__esModule",{value:!0});W.WriteStreamSync=W.WriteStream=W.ReadStreamSync=W.ReadStream=void 0;var Co=Ur(require("events")),z=Ur(require("fs")),Bo=We(),zo=z.default.writev,ye=Symbol("_autoClose"),$=Symbol("_close"),wt=Symbol("_ended"),p=Symbol("_fd"),ss=Symbol("_finished"),fe=Symbol("_flags"),rs=Symbol("_flush"),hs=Symbol("_handleChunk"),ls=Symbol("_makeBuf"),Et=Symbol("_mode"),Gt=Symbol("_needDrain"),Ge=Symbol("_onerror"),Ye=Symbol("_onopen"),ns=Symbol("_onread"),He=Symbol("_onwrite"),Ee=Symbol("_open"),V=Symbol("_path"),we=Symbol("_pos"),ee=Symbol("_queue"),Ze=Symbol("_read"),os=Symbol("_readSize"),ce=Symbol("_reading"),yt=Symbol("_remain"),as=Symbol("_size"),Yt=Symbol("_write"),Me=Symbol("_writing"),Kt=Symbol("_defaultFlag"),Le=Symbol("_errored"),Vt=class extends Bo.Minipass{[Le]=!1;[p];[V];[os];[ce]=!1;[as];[yt];[ye];constructor(e,t){if(t=t||{},super(t),this.readable=!0,this.writable=!1,typeof e!="string")throw new TypeError("path must be a string");this[Le]=!1,this[p]=typeof t.fd=="number"?t.fd:void 0,this[V]=e,this[os]=t.readSize||16*1024*1024,this[ce]=!1,this[as]=typeof t.size=="number"?t.size:1/0,this[yt]=this[as],this[ye]=typeof t.autoClose=="boolean"?t.autoClose:!0,typeof this[p]=="number"?this[Ze]():this[Ee]()}get fd(){return this[p]}get path(){return this[V]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Ee](){z.default.open(this[V],"r",(e,t)=>this[Ye](e,t))}[Ye](e,t){e?this[Ge](e):(this[p]=t,this.emit("open",t),this[Ze]())}[ls](){return Buffer.allocUnsafe(Math.min(this[os],this[yt]))}[Ze](){if(!this[ce]){this[ce]=!0;let e=this[ls]();if(e.length===0)return process.nextTick(()=>this[ns](null,0,e));z.default.read(this[p],e,0,e.length,null,(t,i,r)=>this[ns](t,i,r))}}[ns](e,t,i){this[ce]=!1,e?this[Ge](e):this[hs](t,i)&&this[Ze]()}[$](){if(this[ye]&&typeof this[p]=="number"){let e=this[p];this[p]=void 0,z.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}[Ge](e){this[ce]=!0,this[$](),this.emit("error",e)}[hs](e,t){let i=!1;return this[yt]-=e,e>0&&(i=super.write(ethis[Ye](e,t))}[Ye](e,t){this[Kt]&&this[fe]==="r+"&&e&&e.code==="ENOENT"?(this[fe]="w",this[Ee]()):e?this[Ge](e):(this[p]=t,this.emit("open",t),this[Me]||this[rs]())}end(e,t){return e&&this.write(e,t),this[wt]=!0,!this[Me]&&!this[ee].length&&typeof this[p]=="number"&&this[He](null,0),this}write(e,t){return typeof e=="string"&&(e=Buffer.from(e,t)),this[wt]?(this.emit("error",new Error("write() after end()")),!1):this[p]===void 0||this[Me]||this[ee].length?(this[ee].push(e),this[Gt]=!0,!1):(this[Me]=!0,this[Yt](e),!0)}[Yt](e){z.default.write(this[p],e,0,e.length,this[we],(t,i)=>this[He](t,i))}[He](e,t){e?this[Ge](e):(this[we]!==void 0&&typeof t=="number"&&(this[we]+=t),this[ee].length?this[rs]():(this[Me]=!1,this[wt]&&!this[ss]?(this[ss]=!0,this[$](),this.emit("finish")):this[Gt]&&(this[Gt]=!1,this.emit("drain"))))}[rs](){if(this[ee].length===0)this[wt]&&this[He](null,0);else if(this[ee].length===1)this[Yt](this[ee].pop());else{let e=this[ee];this[ee]=[],zo(this[p],e,this[we],(t,i)=>this[He](t,i))}}[$](){if(this[ye]&&typeof this[p]=="number"){let e=this[p];this[p]=void 0,z.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}};W.WriteStream=$t;var cs=class extends $t{[Ee](){let e;if(this[Kt]&&this[fe]==="r+")try{e=z.default.openSync(this[V],this[fe],this[Et])}catch(t){if(t?.code==="ENOENT")return this[fe]="w",this[Ee]();throw t}else e=z.default.openSync(this[V],this[fe],this[Et]);this[Ye](null,e)}[$](){if(this[ye]&&typeof this[p]=="number"){let e=this[p];this[p]=void 0,z.default.closeSync(e),this.emit("close")}}[Yt](e){let t=!0;try{this[He](null,z.default.writeSync(this[p],e,0,e.length,this[we])),t=!1}finally{if(t)try{this[$]()}catch{}}}};W.WriteStreamSync=cs});var Xt=d(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.dealias=b.isNoFile=b.isFile=b.isAsync=b.isSync=b.isAsyncNoFile=b.isSyncNoFile=b.isAsyncFile=b.isSyncFile=void 0;var ko=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"]]),xo=s=>!!s.sync&&!!s.file;b.isSyncFile=xo;var jo=s=>!s.sync&&!!s.file;b.isAsyncFile=jo;var Uo=s=>!!s.sync&&!s.file;b.isSyncNoFile=Uo;var qo=s=>!s.sync&&!s.file;b.isAsyncNoFile=qo;var Wo=s=>!!s.sync;b.isSync=Wo;var Ho=s=>!s.sync;b.isAsync=Ho;var Zo=s=>!!s.file;b.isFile=Zo;var Go=s=>!s.file;b.isNoFile=Go;var Yo=s=>{let e=ko.get(s);return e||s},Ko=(s={})=>{if(!s)return{};let e={};for(let[t,i]of Object.entries(s)){let r=Yo(t);e[r]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e};b.dealias=Ko});var Ve=d(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.makeCommand=void 0;var bt=Xt(),Vo=(s,e,t,i,r)=>Object.assign((n=[],o,h)=>{Array.isArray(n)&&(o=n,n={}),typeof o=="function"&&(h=o,o=void 0),o=o?Array.from(o):[];let a=(0,bt.dealias)(n);if(r?.(a,o),(0,bt.isSyncFile)(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return s(a,o)}else if((0,bt.isAsyncFile)(a)){let l=e(a,o);return h?l.then(()=>h(),h):l}else if((0,bt.isSyncNoFile)(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return t(a,o)}else if((0,bt.isAsyncNoFile)(a)){if(typeof h=="function")throw new TypeError("callback only supported with file option");return i(a,o)}throw new Error("impossible options??")},{syncFile:s,asyncFile:e,syncNoFile:t,asyncNoFile:i,validate:r});Qt.makeCommand=Vo});var fs=d($e=>{"use strict";var $o=$e&&$e.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty($e,"__esModule",{value:!0});$e.constants=void 0;var Xo=$o(require("zlib")),Qo=Xo.default.constants||{ZLIB_VERNUM:4736};$e.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:1/0,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},Qo))});var Ds=d(f=>{"use strict";var Jo=f&&f.__createBinding||(Object.create?(function(s,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(s,i,r)}):(function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]})),ea=f&&f.__setModuleDefault||(Object.create?(function(s,e){Object.defineProperty(s,"default",{enumerable:!0,value:e})}):function(s,e){s.default=e}),ta=f&&f.__importStar||(function(){var s=function(e){return s=Object.getOwnPropertyNames||function(t){var i=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[i.length]=r);return i},s(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=s(e),r=0;rs,ds=Wr?.writable===!0||Wr?.set!==void 0?s=>{Ae.Buffer.concat=s?oa:na}:s=>{},Ie=Symbol("_superWrite"),Fe=class extends Error{code;errno;constructor(e,t){super("zlib: "+e.message,{cause:e}),this.code=e.code,this.errno=e.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+e.message,Error.captureStackTrace(this,t??this.constructor)}get name(){return"ZlibError"}};f.ZlibError=Fe;var ms=Symbol("flushFlag"),St=class extends sa.Minipass{#e=!1;#i=!1;#s;#n;#r;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#s}constructor(e,t){if(!e||typeof e!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(e),this.#s=e.flush??0,this.#n=e.finishFlush??0,this.#r=e.fullFlushFlag??0,typeof qr[t]!="function")throw new TypeError("Compression method not supported: "+t);try{this.#t=new qr[t](e)}catch(i){throw new Fe(i,this.constructor)}this.#o=i=>{this.#e||(this.#e=!0,this.close(),this.emit("error",i))},this.#t?.on("error",i=>this.#o(new Fe(i))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return(0,ps.default)(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(e){this.ended||(typeof e!="number"&&(e=this.#r),this.write(Object.assign(Ae.Buffer.alloc(0),{[ms]:e})))}end(e,t,i){return typeof e=="function"&&(i=e,t=void 0,e=void 0),typeof t=="function"&&(i=t,t=void 0),e&&(t?this.write(e,t):this.write(e)),this.flush(this.#n),this.#i=!0,super.end(i)}get ended(){return this.#i}[Ie](e){return super.write(e)}write(e,t,i){if(typeof t=="function"&&(i=t,t="utf8"),typeof e=="string"&&(e=Ae.Buffer.from(e,t)),this.#e)return;(0,ps.default)(this.#t,"zlib binding closed");let r=this.#t._handle,n=r.close;r.close=()=>{};let o=this.#t.close;this.#t.close=()=>{},ds(!0);let h;try{let l=typeof e[ms]=="number"?e[ms]:this.#s;h=this.#t._processChunk(e,l),ds(!1)}catch(l){ds(!1),this.#o(new Fe(l,this.write))}finally{this.#t&&(this.#t._handle=r,r.close=n,this.#t.close=o,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",l=>this.#o(new Fe(l,this.write)));let a;if(h)if(Array.isArray(h)&&h.length>0){let l=h[0];a=this[Ie](Ae.Buffer.from(l));for(let u=1;u{typeof r=="function"&&(n=r,r=this.flushFlag),this.flush(r),n?.()};try{this.handle.params(e,t)}finally{this.handle.flush=i}this.handle&&(this.#e=e,this.#i=t)}}}};f.Zlib=ie;var _s=class extends ie{constructor(e){super(e,"Deflate")}};f.Deflate=_s;var ws=class extends ie{constructor(e){super(e,"Inflate")}};f.Inflate=ws;var ys=class extends ie{#e;constructor(e){super(e,"Gzip"),this.#e=e&&!!e.portable}[Ie](e){return this.#e?(this.#e=!1,e[9]=255,super[Ie](e)):super[Ie](e)}};f.Gzip=ys;var Es=class extends ie{constructor(e){super(e,"Gunzip")}};f.Gunzip=Es;var bs=class extends ie{constructor(e){super(e,"DeflateRaw")}};f.DeflateRaw=bs;var Ss=class extends ie{constructor(e){super(e,"InflateRaw")}};f.InflateRaw=Ss;var gs=class extends ie{constructor(e){super(e,"Unzip")}};f.Unzip=gs;var Jt=class extends St{constructor(e,t){e=e||{},e.flush=e.flush||te.constants.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||te.constants.BROTLI_OPERATION_FINISH,e.fullFlushFlag=te.constants.BROTLI_OPERATION_FLUSH,super(e,t)}},Os=class extends Jt{constructor(e){super(e,"BrotliCompress")}};f.BrotliCompress=Os;var Rs=class extends Jt{constructor(e){super(e,"BrotliDecompress")}};f.BrotliDecompress=Rs;var ei=class extends St{constructor(e,t){e=e||{},e.flush=e.flush||te.constants.ZSTD_e_continue,e.finishFlush=e.finishFlush||te.constants.ZSTD_e_end,e.fullFlushFlag=te.constants.ZSTD_e_flush,super(e,t)}},vs=class extends ei{constructor(e){super(e,"ZstdCompress")}};f.ZstdCompress=vs;var Ts=class extends ei{constructor(e){super(e,"ZstdDecompress")}};f.ZstdDecompress=Ts});var Gr=d(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.parse=Xe.encode=void 0;var aa=(s,e)=>{if(Number.isSafeInteger(s))s<0?la(s,e):ha(s,e);else throw Error("cannot encode number outside of javascript safe integer range");return e};Xe.encode=aa;var ha=(s,e)=>{e[0]=128;for(var t=e.length;t>1;t--)e[t-1]=s&255,s=Math.floor(s/256)},la=(s,e)=>{e[0]=255;var t=!1;s=s*-1;for(var i=e.length;i>1;i--){var r=s&255;s=Math.floor(s/256),t?e[i-1]=Hr(r):r===0?e[i-1]=0:(t=!0,e[i-1]=Zr(r))}},ua=s=>{let e=s[0],t=e===128?fa(s.subarray(1,s.length)):e===255?ca(s):null;if(t===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(t))throw Error("parsed number outside of javascript safe integer range");return t};Xe.parse=ua;var ca=s=>{for(var e=s.length,t=0,i=!1,r=e-1;r>-1;r--){var n=Number(s[r]),o;i?o=Hr(n):n===0?o=n:(i=!0,o=Zr(n)),o!==0&&(t-=o*Math.pow(256,e-r-1))}return t},fa=s=>{for(var e=s.length,t=0,i=e-1;i>-1;i--){var r=Number(s[i]);r!==0&&(t+=r*Math.pow(256,e-i-1))}return t},Hr=s=>(255^s)&255,Zr=s=>(255^s)+1&255});var Ps=d(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.code=C.name=C.normalFsTypes=C.isName=C.isCode=void 0;var da=s=>C.name.has(s);C.isCode=da;var ma=s=>C.code.has(s);C.isName=ma;C.normalFsTypes=new Set(["0","","1","2","3","4","5","6","7","D"]);C.name=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]);C.code=new Map(Array.from(C.name).map(s=>[s[1],s[0]]))});var et=d(se=>{"use strict";var pa=se&&se.__createBinding||(Object.create?(function(s,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(s,i,r)}):(function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]})),_a=se&&se.__setModuleDefault||(Object.create?(function(s,e){Object.defineProperty(s,"default",{enumerable:!0,value:e})}):function(s,e){s.default=e}),Yr=se&&se.__importStar||(function(){var s=function(e){return s=Object.getOwnPropertyNames||function(t){var i=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[i.length]=r);return i},s(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=s(e),r=0;r=t+512))throw new Error("need 512 bytes for header");let n=Ce(e,t+156,1),o=Je.normalFsTypes.has(n),h=o?i:void 0,a=o?r:void 0;if(this.path=h?.path??Ce(e,t,100),this.mode=h?.mode??a?.mode??be(e,t+100,8),this.uid=h?.uid??a?.uid??be(e,t+108,8),this.gid=h?.gid??a?.gid??be(e,t+116,8),this.size=h?.size??a?.size??be(e,t+124,12),this.mtime=h?.mtime??a?.mtime??Ns(e,t+136,12),this.cksum=be(e,t+148,12),a&&this.#i(a,!0),h&&this.#i(h),Je.isCode(n)&&(this.#e=n||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Ce(e,t+157,100),e.subarray(t+257,t+265).toString()==="ustar\x0000")if(this.uname=h?.uname??a?.uname??Ce(e,t+265,32),this.gname=h?.gname??a?.gname??Ce(e,t+297,32),this.devmaj=h?.devmaj??a?.devmaj??be(e,t+329,8)??0,this.devmin=h?.devmin??a?.devmin??be(e,t+337,8)??0,e[t+475]!==0){let u=Ce(e,t+345,155);this.path=u+"/"+this.path}else{let u=Ce(e,t+345,130);u&&(this.path=u+"/"+this.path),this.atime=i?.atime??r?.atime??Ns(e,t+476,12),this.ctime=i?.ctime??r?.ctime??Ns(e,t+488,12)}let l=256;for(let u=t;u!(r==null||i==="path"&&t||i==="linkpath"&&t||i==="global"))))}encode(e,t=0){if(e||(e=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(e.length>=t+512))throw new Error("need 512 bytes for header");let i=this.ctime||this.atime?130:155,r=wa(this.path||"",i),n=r[0],o=r[1];this.needPax=!!r[2],this.needPax=Be(e,t,100,n)||this.needPax,this.needPax=Se(e,t+100,8,this.mode)||this.needPax,this.needPax=Se(e,t+108,8,this.uid)||this.needPax,this.needPax=Se(e,t+116,8,this.gid)||this.needPax,this.needPax=Se(e,t+124,12,this.size)||this.needPax,this.needPax=Ms(e,t+136,12,this.mtime)||this.needPax,e[t+156]=Number(this.#e.codePointAt(0)),this.needPax=Be(e,t+157,100,this.linkpath)||this.needPax,e.write("ustar\x0000",t+257,8),this.needPax=Be(e,t+265,32,this.uname)||this.needPax,this.needPax=Be(e,t+297,32,this.gname)||this.needPax,this.needPax=Se(e,t+329,8,this.devmaj)||this.needPax,this.needPax=Se(e,t+337,8,this.devmin)||this.needPax,this.needPax=Be(e,t+345,i,o)||this.needPax,e[t+475]!==0?this.needPax=Be(e,t+345,155,o)||this.needPax:(this.needPax=Be(e,t+345,130,o)||this.needPax,this.needPax=Ms(e,t+476,12,this.atime)||this.needPax,this.needPax=Ms(e,t+488,12,this.ctime)||this.needPax);let h=256;for(let a=t;a{let i=s,r="",n,o=Qe.posix.parse(s).root||".";if(Buffer.byteLength(i)<100)n=[i,r,!1];else{r=Qe.posix.dirname(i),i=Qe.posix.basename(i);do Buffer.byteLength(i)<=100&&Buffer.byteLength(r)<=e?n=[i,r,!1]:Buffer.byteLength(i)>100&&Buffer.byteLength(r)<=e?n=[i.slice(0,99),r,!0]:(i=Qe.posix.join(Qe.posix.basename(r),i),r=Qe.posix.dirname(r));while(r!==o&&n===void 0);n||(n=[s.slice(0,99),"",!0])}return n},Ce=(s,e,t)=>s.subarray(e,e+t).toString("utf8").replace(/\0.*/,""),Ns=(s,e,t)=>ya(be(s,e,t)),ya=s=>s===void 0?void 0:new Date(s*1e3),be=(s,e,t)=>Number(s[e])&128?Kr.parse(s.subarray(e,e+t)):ba(s,e,t),Ea=s=>isNaN(s)?void 0:s,ba=(s,e,t)=>Ea(parseInt(s.subarray(e,e+t).toString("utf8").replace(/\0.*$/,"").trim(),8)),Sa={12:8589934591,8:2097151},Se=(s,e,t,i)=>i===void 0?!1:i>Sa[t]||i<0?(Kr.encode(i,s.subarray(e,e+t)),!0):(ga(s,e,t,i),!1),ga=(s,e,t,i)=>s.write(Oa(i,t),e,t,"ascii"),Oa=(s,e)=>Ra(Math.floor(s).toString(8),e),Ra=(s,e)=>(s.length===e-1?s:new Array(e-s.length-1).join("0")+s+" ")+"\0",Ms=(s,e,t,i)=>i===void 0?!1:Se(s,e,t,i.getTime()/1e3),va=new Array(156).join("\0"),Be=(s,e,t,i)=>i===void 0?!1:(s.write(i+va,e,t,"utf8"),i.length!==Buffer.byteLength(i)||i.length>t)});var ii=d(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.Pax=void 0;var Ta=require("node:path"),Da=et(),As=class s{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,t=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=t,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let t=Buffer.byteLength(e),i=512*Math.ceil(1+t/512),r=Buffer.allocUnsafe(i);for(let n=0;n<512;n++)r[n]=0;new Da.Header({path:("PaxHeader/"+(0,Ta.basename)(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:t,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(r),r.write(e,512,t,"utf8");for(let n=t+512;n=Math.pow(10,o)&&(o+=1),o+n+r}static parse(e,t,i=!1){return new s(Pa(Na(e),t),i)}};ti.Pax=As;var Pa=(s,e)=>e?Object.assign({},e,s):s,Na=s=>s.replace(/\n$/,"").split(` +`).reduce(Ma,Object.create(null)),Ma=(s,e)=>{let t=parseInt(e,10);if(t!==Buffer.byteLength(e)+1)return s;e=e.slice((t+" ").length);let i=e.split("="),r=i.shift();if(!r)return s;let n=r.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=i.join("=");return s[n]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(n)?new Date(Number(o)*1e3):/^[0-9]+$/.test(o)?+o:o,s}});var tt=d(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.normalizeWindowsPath=void 0;var La=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;si.normalizeWindowsPath=La!=="win32"?s=>s:s=>s&&s.replaceAll(/\\/g,"/")});var Fs=d(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.ReadEntry=void 0;var Aa=We(),ri=tt(),Is=class extends Aa.Minipass{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(e,t,i){switch(super({}),this.pause(),this.extended=t,this.globalExtended=i,this.header=e,this.remain=e.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=e.type,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=!0;break;default:this.ignore=!0}if(!e.path)throw new Error("no path provided for tar.ReadEntry");this.path=(0,ri.normalizeWindowsPath)(e.path),this.mode=e.mode,this.mode&&(this.mode=this.mode&4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=this.remain,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=e.linkpath?(0,ri.normalizeWindowsPath)(e.linkpath):void 0,this.uname=e.uname,this.gname=e.gname,t&&this.#e(t),i&&this.#e(i,!0)}write(e){let t=e.length;if(t>this.blockRemain)throw new Error("writing more to entry than is appropriate");let i=this.remain,r=this.blockRemain;return this.remain=Math.max(0,i-t),this.blockRemain=Math.max(0,r-t),this.ignore?!0:i>=t?super.write(e):super.write(e.subarray(0,i))}#e(e,t=!1){e.path&&(e.path=(0,ri.normalizeWindowsPath)(e.path)),e.linkpath&&(e.linkpath=(0,ri.normalizeWindowsPath)(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([i,r])=>!(r==null||i==="path"&&t))))}};ni.ReadEntry=Is});var ai=d(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.warnMethod=void 0;var Ia=(s,e,t,i={})=>{s.file&&(i.file=s.file),s.cwd&&(i.cwd=s.cwd),i.code=t instanceof Error&&t.code||e,i.tarCode=e,!s.strict&&i.recoverable!==!1?(t instanceof Error&&(i=Object.assign(t,i),t=t.message),s.emit("warn",e,t,i)):t instanceof Error?s.emit("error",Object.assign(t,i)):s.emit("error",Object.assign(new Error(`${e}: ${t}`),i))};oi.warnMethod=Ia});var pi=d(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.Parser=void 0;var Fa=require("events"),Cs=Ds(),Vr=et(),$r=ii(),Ca=Fs(),Ba=ai(),za=1024*1024,js=Buffer.from([31,139]),Us=Buffer.from([40,181,47,253]),ka=Math.max(js.length,Us.length),H=Symbol("state"),ze=Symbol("writeEntry"),de=Symbol("readEntry"),Bs=Symbol("nextEntry"),Xr=Symbol("processEntry"),re=Symbol("extendedHeader"),gt=Symbol("globalExtendedHeader"),ge=Symbol("meta"),Qr=Symbol("emitMeta"),_=Symbol("buffer"),me=Symbol("queue"),Oe=Symbol("ended"),zs=Symbol("emittedEnd"),ke=Symbol("emit"),S=Symbol("unzip"),hi=Symbol("consumeChunk"),li=Symbol("consumeChunkSub"),ks=Symbol("consumeBody"),Jr=Symbol("consumeMeta"),en=Symbol("consumeHeader"),Ot=Symbol("consuming"),xs=Symbol("bufferConcat"),ui=Symbol("maybeEnd"),it=Symbol("writing"),Re=Symbol("aborted"),ci=Symbol("onDone"),xe=Symbol("sawValidEntry"),fi=Symbol("sawNullBlock"),di=Symbol("sawEOF"),tn=Symbol("closeStream"),xa=()=>!0,qs=class extends Fa.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[me]=[];[_];[de];[ze];[H]="begin";[ge]="";[re];[gt];[Oe]=!1;[S];[Re]=!1;[xe];[fi]=!1;[di]=!1;[it]=!1;[Ot]=!1;[zs]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(ci,()=>{(this[H]==="begin"||this[xe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(ci,e.ondone):this.on(ci,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||za,this.filter=typeof e.filter=="function"?e.filter:xa;let t=e.file&&(e.file.endsWith(".tar.br")||e.file.endsWith(".tbr"));this.brotli=!(e.gzip||e.zstd)&&e.brotli!==void 0?e.brotli:t?void 0:!1;let i=e.file&&(e.file.endsWith(".tar.zst")||e.file.endsWith(".tzst"));this.zstd=!(e.gzip||e.brotli)&&e.zstd!==void 0?e.zstd:i?!0:void 0,this.on("end",()=>this[tn]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,i={}){(0,Ba.warnMethod)(this,e,t,i)}[en](e,t){this[xe]===void 0&&(this[xe]=!1);let i;try{i=new Vr.Header(e,t,this[re],this[gt])}catch(r){return this.warn("TAR_ENTRY_INVALID",r)}if(i.nullBlock)this[fi]?(this[di]=!0,this[H]==="begin"&&(this[H]="header"),this[ke]("eof")):(this[fi]=!0,this[ke]("nullBlock"));else if(this[fi]=!1,!i.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:i});else if(!i.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:i});else{let r=i.type;if(/^(Symbolic)?Link$/.test(r)&&!i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:i});else if(!/^(Symbolic)?Link$/.test(r)&&!/^(Global)?ExtendedHeader$/.test(r)&&i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:i});else{let n=this[ze]=new Ca.ReadEntry(i,this[re],this[gt]);if(!this[xe])if(n.remain){let o=()=>{n.invalid||(this[xe]=!0)};n.on("end",o)}else this[xe]=!0;n.meta?n.size>this.maxMetaEntrySize?(n.ignore=!0,this[ke]("ignoredEntry",n),this[H]="ignore",n.resume()):n.size>0&&(this[ge]="",n.on("data",o=>this[ge]+=o),this[H]="meta"):(this[re]=void 0,n.ignore=n.ignore||!this.filter(n.path,n),n.ignore?(this[ke]("ignoredEntry",n),this[H]=n.remain?"ignore":"header",n.resume()):(n.remain?this[H]="body":(this[H]="header",n.end()),this[de]?this[me].push(n):(this[me].push(n),this[Bs]())))}}}[tn](){queueMicrotask(()=>this.emit("close"))}[Xr](e){let t=!0;if(!e)this[de]=void 0,t=!1;else if(Array.isArray(e)){let[i,...r]=e;this.emit(i,...r)}else this[de]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[Bs]()),t=!1);return t}[Bs](){do;while(this[Xr](this[me].shift()));if(this[me].length===0){let e=this[de];!e||e.flowing||e.size===e.remain?this[it]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[ks](e,t){let i=this[ze];if(!i)throw new Error("attempt to consume body without entry??");let r=i.blockRemain??0,n=r>=e.length&&t===0?e:e.subarray(t,t+r);return i.write(n),i.blockRemain||(this[H]="header",this[ze]=void 0,i.end()),n.length}[Jr](e,t){let i=this[ze],r=this[ks](e,t);return!this[ze]&&i&&this[Qr](i),r}[ke](e,t,i){this[me].length===0&&!this[de]?this.emit(e,t,i):this[me].push([e,t,i])}[Qr](e){switch(this[ke]("meta",this[ge]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[re]=$r.Pax.parse(this[ge],this[re],!1);break;case"GlobalExtendedHeader":this[gt]=$r.Pax.parse(this[ge],this[gt],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[re]??Object.create(null);this[re]=t,t.path=this[ge].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[re]||Object.create(null);this[re]=t,t.linkpath=this[ge].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[Re]=!0,this.emit("abort",e),this.warn("TAR_ABORT",e,{recoverable:!1})}write(e,t,i){if(typeof t=="function"&&(i=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this[Re])return i?.(),!1;if((this[S]===void 0||this.brotli===void 0&&this[S]===!1)&&e){if(this[_]&&(e=Buffer.concat([this[_],e]),this[_]=void 0),e.lengththis[hi](u)),this[S].on("error",u=>this.abort(u)),this[S].on("end",()=>{this[Oe]=!0,this[hi]()}),this[it]=!0;let l=!!this[S][a?"end":"write"](e);return this[it]=!1,i?.(),l}}this[it]=!0,this[S]?this[S].write(e):this[hi](e),this[it]=!1;let n=this[me].length>0?!1:this[de]?this[de].flowing:!0;return!n&&this[me].length===0&&this[de]?.once("drain",()=>this.emit("drain")),i?.(),n}[xs](e){e&&!this[Re]&&(this[_]=this[_]?Buffer.concat([this[_],e]):e)}[ui](){if(this[Oe]&&!this[zs]&&!this[Re]&&!this[Ot]){this[zs]=!0;let e=this[ze];if(e&&e.blockRemain){let t=this[_]?this[_].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[_]&&e.write(this[_]),e.end()}this[ke](ci)}}[hi](e){if(this[Ot]&&e)this[xs](e);else if(!e&&!this[_])this[ui]();else if(e){if(this[Ot]=!0,this[_]){this[xs](e);let t=this[_];this[_]=void 0,this[li](t)}else this[li](e);for(;this[_]&&this[_]?.length>=512&&!this[Re]&&!this[di];){let t=this[_];this[_]=void 0,this[li](t)}this[Ot]=!1}(!this[_]||this[Oe])&&this[ui]()}[li](e){let t=0,i=e.length;for(;t+512<=i&&!this[Re]&&!this[di];)switch(this[H]){case"begin":case"header":this[en](e,t),t+=512;break;case"ignore":case"body":t+=this[ks](e,t);break;case"meta":t+=this[Jr](e,t);break;default:throw new Error("invalid state: "+this[H])}t{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.stripTrailingSlashes=void 0;var ja=s=>{let e=s.length-1,t=-1;for(;e>-1&&s.charAt(e)==="/";)t=e,e--;return t===-1?s:s.slice(0,t)};_i.stripTrailingSlashes=ja});var rt=d(B=>{"use strict";var Ua=B&&B.__createBinding||(Object.create?(function(s,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(s,i,r)}):(function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]})),qa=B&&B.__setModuleDefault||(Object.create?(function(s,e){Object.defineProperty(s,"default",{enumerable:!0,value:e})}):function(s,e){s.default=e}),Wa=B&&B.__importStar||(function(){var s=function(e){return s=Object.getOwnPropertyNames||function(t){var i=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[i.length]=r);return i},s(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=s(e),r=0;r{let e=s.onReadEntry;s.onReadEntry=e?t=>{e(t),t.resume()}:t=>t.resume()},Ka=(s,e)=>{let t=new Map(e.map(n=>[(0,Ws.stripTrailingSlashes)(n),!0])),i=s.filter,r=(n,o="")=>{let h=o||(0,sn.parse)(n).root||".",a;if(n===h)a=!1;else{let l=t.get(n);a=l!==void 0?l:r((0,sn.dirname)(n),h)}return t.set(n,a),a};s.filter=i?(n,o)=>i(n,o)&&r((0,Ws.stripTrailingSlashes)(n)):n=>r((0,Ws.stripTrailingSlashes)(n))};B.filesFilter=Ka;var Va=s=>{let e=new yi.Parser(s),t=s.file,i;try{i=st.default.openSync(t,"r");let r=st.default.fstatSync(i),n=s.maxReadSize||16*1024*1024;if(r.size{let t=new yi.Parser(s),i=s.maxReadSize||16*1024*1024,r=s.file;return new Promise((o,h)=>{t.on("error",h),t.on("end",o),st.default.stat(r,(a,l)=>{if(a)h(a);else{let u=new Za.ReadStream(r,{readSize:i,size:l.size});u.on("error",h),u.pipe(t)}})})};B.list=(0,Ga.makeCommand)(Va,$a,s=>new yi.Parser(s),s=>new yi.Parser(s),(s,e)=>{e?.length&&(0,B.filesFilter)(s,e),s.noResume||Ya(s)})});var rn=d(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.modeFix=void 0;var Xa=(s,e,t)=>(s&=4095,t&&(s=(s|384)&-19),e&&(s&256&&(s|=64),s&32&&(s|=8),s&4&&(s|=1)),s);Ei.modeFix=Xa});var Hs=d(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.stripAbsolutePath=void 0;var Qa=require("node:path"),{isAbsolute:Ja,parse:nn}=Qa.win32,eh=s=>{let e="",t=nn(s);for(;Ja(s)||t.root;){let i=s.charAt(0)==="/"&&s.slice(0,4)!=="//?/"?"/":t.root;s=s.slice(i.length),e+=i,t=nn(s)}return[e,s]};bi.stripAbsolutePath=eh});var Gs=d(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.decode=nt.encode=void 0;var Si=["|","<",">","?",":"],Zs=Si.map(s=>String.fromCodePoint(61440+Number(s.codePointAt(0)))),th=new Map(Si.map((s,e)=>[s,Zs[e]])),ih=new Map(Zs.map((s,e)=>[s,Si[e]])),sh=s=>Si.reduce((e,t)=>e.split(t).join(th.get(t)),s);nt.encode=sh;var rh=s=>Zs.reduce((e,t)=>e.split(t).join(ih.get(t)),s);nt.decode=rh});var sr=d(M=>{"use strict";var nh=M&&M.__createBinding||(Object.create?(function(s,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(s,i,r)}):(function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]})),oh=M&&M.__setModuleDefault||(Object.create?(function(s,e){Object.defineProperty(s,"default",{enumerable:!0,value:e})}):function(s,e){s.default=e}),ah=M&&M.__importStar||(function(){var s=function(e){return s=Object.getOwnPropertyNames||function(t){var i=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[i.length]=r);return i},s(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=s(e),r=0;re?(s=(0,ne.normalizeWindowsPath)(s).replace(/^\.(\/|$)/,""),(0,hh.stripTrailingSlashes)(e)+"/"+s):(0,ne.normalizeWindowsPath)(s),uh=16*1024*1024,an=Symbol("process"),hn=Symbol("file"),ln=Symbol("directory"),Ks=Symbol("symlink"),un=Symbol("hardlink"),Rt=Symbol("header"),gi=Symbol("read"),Vs=Symbol("lstat"),Oi=Symbol("onlstat"),$s=Symbol("onread"),Xs=Symbol("onreadlink"),Qs=Symbol("openfile"),Js=Symbol("onopenfile"),ve=Symbol("close"),Ri=Symbol("mode"),er=Symbol("awaitDrain"),Ys=Symbol("ondrain"),ae=Symbol("prefix"),vi=class extends fn.Minipass{path;portable;myuid=process.getuid&&process.getuid()||0;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;#e=!1;constructor(e,t={}){let i=(0,pn.dealias)(t);super(),this.path=(0,ne.normalizeWindowsPath)(e),this.portable=!!i.portable,this.maxReadSize=i.maxReadSize||uh,this.linkCache=i.linkCache||new Map,this.statCache=i.statCache||new Map,this.preservePaths=!!i.preservePaths,this.cwd=(0,ne.normalizeWindowsPath)(i.cwd||process.cwd()),this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.mtime=i.mtime,this.prefix=i.prefix?(0,ne.normalizeWindowsPath)(i.prefix):void 0,this.onWriteEntry=i.onWriteEntry,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let r=!1;if(!this.preservePaths){let[o,h]=(0,wn.stripAbsolutePath)(this.path);o&&typeof h=="string"&&(this.path=h,r=o)}this.win32=!!i.win32||process.platform==="win32",this.win32&&(this.path=lh.decode(this.path.replaceAll(/\\/g,"/")),e=e.replaceAll(/\\/g,"/")),this.absolute=(0,ne.normalizeWindowsPath)(i.absolute||on.default.resolve(this.cwd,e)),this.path===""&&(this.path="./"),r&&this.warn("TAR_ENTRY_INFO",`stripping ${r} from absolute path`,{entry:this,path:r+this.path});let n=this.statCache.get(this.absolute);n?this[Oi](n):this[Vs]()}warn(e,t,i={}){return(0,yn.warnMethod)(this,e,t,i)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[Vs](){oe.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[Oi](t)})}[Oi](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=ch(e),this.emit("stat",e),this[an]()}[an](){switch(this.type){case"File":return this[hn]();case"Directory":return this[ln]();case"SymbolicLink":return this[Ks]();default:return this.end()}}[Ri](e){return(0,mn.modeFix)(e,this.type==="Directory",this.portable)}[ae](e){return En(e,this.prefix)}[Rt](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new dn.Header({path:this[ae](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[ae](this.linkpath):this.linkpath,mode:this[Ri](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new _n.Pax({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[ae](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[ae](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let e=this.header?.block;if(!e)throw new Error("failed to encode header");super.write(e)}[ln](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Rt](),this.end()}[Ks](){oe.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[Xs](t)})}[Xs](e){this.linkpath=(0,ne.normalizeWindowsPath)(e),this[Rt](),this.end()}[un](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=(0,ne.normalizeWindowsPath)(on.default.relative(this.cwd,e)),this.stat.size=0,this[Rt](),this.end()}[hn](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let e=`${this.stat.dev}:${this.stat.ino}`,t=this.linkCache.get(e);if(t?.indexOf(this.cwd)===0)return this[un](t);this.linkCache.set(e,this.absolute)}if(this[Rt](),this.stat.size===0)return this.end();this[Qs]()}[Qs](){oe.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[Js](t)})}[Js](e){if(this.fd=e,this.#e)return this[ve]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let t=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(t),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[gi]()}[gi](){let{fd:e,buf:t,offset:i,length:r,pos:n}=this;if(e===void 0||t===void 0)throw new Error("cannot read file without first opening");oe.default.read(e,t,i,r,n,(o,h)=>{if(o)return this[ve](()=>this.emit("error",o));this[$s](h)})}[ve](e=()=>{}){this.fd!==void 0&&oe.default.close(this.fd,e)}[$s](e){if(e<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[ve](()=>this.emit("error",r))}if(e>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[ve](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(e===this.remain)for(let r=e;rthis[Ys]())}[er](e){this.once("drain",e)}write(e,t,i){if(typeof t=="function"&&(i=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this.blockRemaine?this.emit("error",e):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[gi]()}};M.WriteEntry=vi;var tr=class extends vi{sync=!0;[Vs](){this[Oi](oe.default.lstatSync(this.absolute))}[Ks](){this[Xs](oe.default.readlinkSync(this.absolute))}[Qs](){this[Js](oe.default.openSync(this.absolute,"r"))}[gi](){let e=!0;try{let{fd:t,buf:i,offset:r,length:n,pos:o}=this;if(t===void 0||i===void 0)throw new Error("fd and buf must be set in READ method");let h=oe.default.readSync(t,i,r,n,o);this[$s](h),e=!1}finally{if(e)try{this[ve](()=>{})}catch{}}}[er](e){e()}[ve](e=()=>{}){this.fd!==void 0&&oe.default.closeSync(this.fd),e()}};M.WriteEntrySync=tr;var ir=class extends fn.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(e,t,i={}){return(0,yn.warnMethod)(this,e,t,i)}constructor(e,t={}){let i=(0,pn.dealias)(t);super(),this.preservePaths=!!i.preservePaths,this.portable=!!i.portable,this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.onWriteEntry=i.onWriteEntry,this.readEntry=e;let{type:r}=e;if(r==="Unsupported")throw new Error("writing entry that should be ignored");this.type=r,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=i.prefix,this.path=(0,ne.normalizeWindowsPath)(e.path),this.mode=e.mode!==void 0?this[Ri](e.mode):void 0,this.uid=this.portable?void 0:e.uid,this.gid=this.portable?void 0:e.gid,this.uname=this.portable?void 0:e.uname,this.gname=this.portable?void 0:e.gname,this.size=e.size,this.mtime=this.noMtime?void 0:i.mtime||e.mtime,this.atime=this.portable?void 0:e.atime,this.ctime=this.portable?void 0:e.ctime,this.linkpath=e.linkpath!==void 0?(0,ne.normalizeWindowsPath)(e.linkpath):void 0,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let n=!1;if(!this.preservePaths){let[h,a]=(0,wn.stripAbsolutePath)(this.path);h&&typeof a=="string"&&(this.path=a,n=h)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.onWriteEntry?.(this),this.header=new dn.Header({path:this[ae](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[ae](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path}),this.header.encode()&&!this.noPax&&super.write(new _n.Pax({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[ae](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[ae](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),e.pipe(this)}[ae](e){return En(e,this.prefix)}[Ri](e){return(0,mn.modeFix)(e,this.type==="Directory",this.portable)}write(e,t,i){typeof t=="function"&&(i=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8"));let r=e.length;if(r>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=r,super.write(e,i)}end(e,t,i){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof e=="function"&&(i=e,t=void 0,e=void 0),typeof t=="function"&&(i=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t??"utf8")),i&&this.once("finish",i),e?super.end(e,i):super.end(i),this}};M.WriteEntryTar=ir;var ch=s=>s.isFile()?"File":s.isDirectory()?"Directory":s.isSymbolicLink()?"SymbolicLink":"Unsupported"});var bn=d(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.Node=at.Yallist=void 0;var rr=class s{tail;head;length=0;static create(e=[]){return new s(e)}constructor(e=[]){for(let t of e)this.push(t)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let t=e.next,i=e.prev;return t&&(t.prev=i),i&&(i.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,t}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let t=0,i=e.length;t1)i=t;else if(this.head)r=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=0;r;n++)i=e(i,r.value,n),r=r.next;return i}reduceReverse(e,t){let i,r=this.tail;if(arguments.length>1)i=t;else if(this.tail)r=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let n=this.length-1;r;n--)i=e(i,r.value,n),r=r.prev;return i}toArray(){let e=new Array(this.length);for(let t=0,i=this.head;i;t++)e[t]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let t=0,i=this.tail;i;t++)e[t]=i.value,i=i.prev;return e}slice(e=0,t=this.length){t<0&&(t+=this.length),e<0&&(e+=this.length);let i=new s;if(tthis.length&&(t=this.length);let r=this.head,n=0;for(n=0;r&&nthis.length&&(t=this.length);let r=this.length,n=this.tail;for(;n&&r>t;r--)n=n.prev;for(;n&&r>e;r--,n=n.prev)i.push(n.value);return i}splice(e,t=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let r=this.head;for(let o=0;r&&o{"use strict";var ph=L&&L.__createBinding||(Object.create?(function(s,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(s,i,r)}):(function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]})),_h=L&&L.__setModuleDefault||(Object.create?(function(s,e){Object.defineProperty(s,"default",{enumerable:!0,value:e})}):function(s,e){s.default=e}),wh=L&&L.__importStar||(function(){var s=function(e){return s=Object.getOwnPropertyNames||function(t){var i=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[i.length]=r);return i},s(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=s(e),r=0;r1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(e.gzip&&(typeof e.gzip!="object"&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new nr.Gzip(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new nr.BrotliCompress(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new nr.ZstdCompress(e.zstd)),!this.zip)throw new Error("impossible");let t=this.zip;t.on("data",i=>super.write(i)),t.on("end",()=>super.end()),t.on("drain",()=>this[hr]()),this.on("resume",()=>t.resume())}else this.on("drain",this[hr]);this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,e.mtime&&(this.mtime=e.mtime),this.filter=typeof e.filter=="function"?e.filter:()=>!0,this[X]=new Eh.Yallist,this[Q]=0,this.jobs=Number(e.jobs)||4,this[Dt]=!1,this[vt]=!1}[Tn](e){return super.write(e)}add(e){return this.write(e),this}end(e,t,i){return typeof e=="function"&&(i=e,e=void 0),typeof t=="function"&&(i=t,t=void 0),e&&this.add(e),this[vt]=!0,this[je](),i&&i(),this}write(e){if(this[vt])throw new Error("write after end");return typeof e=="string"?this[Pi](e):this[gn](e),this.flowing}[gn](e){let t=(0,lr.normalizeWindowsPath)(Rn.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let i=new Pt(e.path,t);i.entry=new ur.WriteEntryTar(e,this[ar](i)),i.entry.on("end",()=>this[or](i)),this[Q]+=1,this[X].push(i)}this[je]()}[Pi](e){let t=(0,lr.normalizeWindowsPath)(Rn.default.resolve(this.cwd,e));this[X].push(new Pt(e,t)),this[je]()}[cr](e){e.pending=!0,this[Q]+=1;let t=this.follow?"stat":"lstat";Ai.default[t](e.absolute,(i,r)=>{e.pending=!1,this[Q]-=1,i?this.emit("error",i):this[Di](e,r)})}[Di](e,t){if(this.statCache.set(e.absolute,t),e.stat=t,!this.filter(e.path,t))e.ignore=!0;else if(t.isFile()&&t.nlink>1&&!this.linkCache.get(`${t.dev}:${t.ino}`)&&!this.sync)if(e===this[Te])this[Ti](e);else{let i=`${t.dev}:${t.ino}`,r=this[Tt].get(i);r?r.push(e):this[Tt].set(i,[e]),e.pendingLink=!0,e.pending=!0}this[je]()}[fr](e){e.pending=!0,this[Q]+=1,Ai.default.readdir(e.absolute,(t,i)=>{if(e.pending=!1,this[Q]-=1,t)return this.emit("error",t);this[Ni](e,i)})}[Ni](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[je]()}[je](){if(!this[Dt]){this[Dt]=!0;for(let e=this[X].head;e&&this[Q]1){let i=`${t.dev}:${t.ino}`,r=this[Tt].get(i);if(r){this[Tt].delete(i);for(let n of r)n.pending=!1,this[Ti](n)}}this[je]()}[Ti](e){if(e.pending&&e.pendingLink&&e===this[Te]&&(e.pending=!1,e.pendingLink=!1),!e.pending){if(e.entry){e===this[Te]&&!e.piped&&this[Mi](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[Di](e,t):this[cr](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[Ni](e,t):this[fr](e),!e.readdir)return}if(e.entry=this[On](e),!e.entry){e.ignore=!0;return}e===this[Te]&&!e.piped&&this[Mi](e)}}}[ar](e){return{onwarn:(t,i,r)=>this.warn(t,i,r),noPax:this.noPax,cwd:this.cwd,absolute:e.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}}[On](e){this[Q]+=1;try{return new this[Li](e.path,this[ar](e)).on("end",()=>this[or](e)).on("error",i=>this.emit("error",i))}catch(t){this.emit("error",t)}}[hr](){this[Te]&&this[Te].entry&&this[Te].entry.resume()}[Mi](e){e.piped=!0,e.readdir&&e.readdir.forEach(r=>{let n=e.path,o=n==="./"?"":n.replace(/\/*$/,"/");this[Pi](o+r)});let t=e.entry,i=this.zip;if(!t)throw new Error("cannot pipe without source");i?t.on("data",r=>{i.write(r)||t.pause()}):t.on("data",r=>{super.write(r)||t.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(e,t,i={}){(0,bh.warnMethod)(this,e,t,i)}};L.Pack=Ii;var dr=class extends Ii{sync=!0;constructor(e){super(e),this[Li]=ur.WriteEntrySync}pause(){}resume(){}[cr](e){let t=this.follow?"statSync":"lstatSync";this[Di](e,Ai.default[t](e.absolute))}[fr](e){this[Ni](e,Ai.default.readdirSync(e.absolute))}[Mi](e){let t=e.entry,i=this.zip;if(e.readdir&&e.readdir.forEach(r=>{let n=e.path,o=n==="./"?"":n.replace(/\/*$/,"/");this[Pi](o+r)}),!t)throw new Error("Cannot pipe without source");i?t.on("data",r=>{i.write(r)}):t.on("data",r=>{super[Tn](r)})}};L.PackSync=dr});var mr=d(ht=>{"use strict";var Sh=ht&&ht.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ht,"__esModule",{value:!0});ht.create=void 0;var Dn=Ke(),Pn=Sh(require("node:path")),Nn=rt(),gh=Ve(),Ci=Fi(),Oh=(s,e)=>{let t=new Ci.PackSync(s),i=new Dn.WriteStreamSync(s.file,{mode:s.mode||438});t.pipe(i),Mn(t,e)},Rh=(s,e)=>{let t=new Ci.Pack(s),i=new Dn.WriteStream(s.file,{mode:s.mode||438});t.pipe(i);let r=new Promise((n,o)=>{i.on("error",o),i.on("close",n),t.on("error",o)});return Ln(t,e).catch(n=>t.emit("error",n)),r},Mn=(s,e)=>{e.forEach(t=>{t.charAt(0)==="@"?(0,Nn.list)({file:Pn.default.resolve(s.cwd,t.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>s.add(i)}):s.add(t)}),s.end()},Ln=async(s,e)=>{for(let t of e)t.charAt(0)==="@"?await(0,Nn.list)({file:Pn.default.resolve(String(s.cwd),t.slice(1)),noResume:!0,onReadEntry:i=>{s.add(i)}}):s.add(t);s.end()},vh=(s,e)=>{let t=new Ci.PackSync(s);return Mn(t,e),t},Th=(s,e)=>{let t=new Ci.Pack(s);return Ln(t,e).catch(i=>t.emit("error",i)),t};ht.create=(0,gh.makeCommand)(Oh,Rh,vh,Th,(s,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")})});var jn=d(lt=>{"use strict";var Dh=lt&<.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(lt,"__esModule",{value:!0});lt.getWriteFlag=void 0;var Fn=Dh(require("fs")),Ph=process.env.__FAKE_PLATFORM__||process.platform,Cn=Ph==="win32",{O_CREAT:Bn,O_NOFOLLOW:An,O_TRUNC:zn,O_WRONLY:kn}=Fn.default.constants,xn=Number(process.env.__FAKE_FS_O_FILENAME__)||Fn.default.constants.UV_FS_O_FILEMAP||0,Nh=Cn&&!!xn,Mh=512*1024,Lh=xn|zn|Bn|kn,In=!Cn&&typeof An=="number"?An|zn|Bn|kn:null;lt.getWriteFlag=In!==null?()=>In:Nh?s=>s"w"});var qn=d(he=>{"use strict";var Un=he&&he.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(he,"__esModule",{value:!0});he.chownrSync=he.chownr=void 0;var zi=Un(require("node:fs")),Nt=Un(require("node:path")),pr=(s,e,t)=>{try{return zi.default.lchownSync(s,e,t)}catch(i){if(i?.code!=="ENOENT")throw i}},Bi=(s,e,t,i)=>{zi.default.lchown(s,e,t,r=>{i(r&&r?.code!=="ENOENT"?r:null)})},Ah=(s,e,t,i,r)=>{if(e.isDirectory())(0,he.chownr)(Nt.default.resolve(s,e.name),t,i,n=>{if(n)return r(n);let o=Nt.default.resolve(s,e.name);Bi(o,t,i,r)});else{let n=Nt.default.resolve(s,e.name);Bi(n,t,i,r)}},Ih=(s,e,t,i)=>{zi.default.readdir(s,{withFileTypes:!0},(r,n)=>{if(r){if(r.code==="ENOENT")return i();if(r.code!=="ENOTDIR"&&r.code!=="ENOTSUP")return i(r)}if(r||!n.length)return Bi(s,e,t,i);let o=n.length,h=null,a=l=>{if(!h){if(l)return i(h=l);if(--o===0)return Bi(s,e,t,i)}};for(let l of n)Ah(s,l,e,t,a)})};he.chownr=Ih;var Fh=(s,e,t,i)=>{e.isDirectory()&&(0,he.chownrSync)(Nt.default.resolve(s,e.name),t,i),pr(Nt.default.resolve(s,e.name),t,i)},Ch=(s,e,t)=>{let i;try{i=zi.default.readdirSync(s,{withFileTypes:!0})}catch(r){let n=r;if(n?.code==="ENOENT")return;if(n?.code==="ENOTDIR"||n?.code==="ENOTSUP")return pr(s,e,t);throw n}for(let r of i)Fh(s,r,e,t);return pr(s,e,t)};he.chownrSync=Ch});var Wn=d(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.CwdError=void 0;var _r=class extends Error{path;code;syscall="chdir";constructor(e,t){super(`${t}: Cannot cd into '${e}'`),this.path=e,this.code=t}get name(){return"CwdError"}};ki.CwdError=_r});var yr=d(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.SymlinkError=void 0;var wr=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(e,t){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=e,this.path=t}get name(){return"SymlinkError"}};xi.SymlinkError=wr});var Kn=d(De=>{"use strict";var br=De&&De.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(De,"__esModule",{value:!0});De.mkdirSync=De.mkdir=void 0;var Hn=qn(),j=br(require("node:fs")),Bh=br(require("node:fs/promises")),ji=br(require("node:path")),Zn=Wn(),pe=tt(),Gn=yr(),zh=(s,e)=>{j.default.stat(s,(t,i)=>{(t||!i.isDirectory())&&(t=new Zn.CwdError(s,t?.code||"ENOTDIR")),e(t)})},kh=(s,e,t)=>{s=(0,pe.normalizeWindowsPath)(s);let i=e.umask??18,r=e.mode|448,n=(r&i)!==0,o=e.uid,h=e.gid,a=typeof o=="number"&&typeof h=="number"&&(o!==e.processUid||h!==e.processGid),l=e.preserve,u=e.unlink,c=(0,pe.normalizeWindowsPath)(e.cwd),E=(w,P)=>{w?t(w):P&&a?(0,Hn.chownr)(P,o,h,kt=>E(kt)):n?j.default.chmod(s,r,t):t()};if(s===c)return zh(s,E);if(l)return Bh.default.mkdir(s,{mode:r,recursive:!0}).then(w=>E(null,w??void 0),E);let A=(0,pe.normalizeWindowsPath)(ji.default.relative(c,s)).split("/");Er(c,A,r,u,c,void 0,E)};De.mkdir=kh;var Er=(s,e,t,i,r,n,o)=>{if(e.length===0)return o(null,n);let h=e.shift(),a=(0,pe.normalizeWindowsPath)(ji.default.resolve(s+"/"+h));j.default.mkdir(a,t,Yn(a,e,t,i,r,n,o))},Yn=(s,e,t,i,r,n,o)=>h=>{h?j.default.lstat(s,(a,l)=>{if(a)a.path=a.path&&(0,pe.normalizeWindowsPath)(a.path),o(a);else if(l.isDirectory())Er(s,e,t,i,r,n,o);else if(i)j.default.unlink(s,u=>{if(u)return o(u);j.default.mkdir(s,t,Yn(s,e,t,i,r,n,o))});else{if(l.isSymbolicLink())return o(new Gn.SymlinkError(s,s+"/"+e.join("/")));o(h)}}):(n=n||s,Er(s,e,t,i,r,n,o))},xh=s=>{let e=!1,t;try{e=j.default.statSync(s).isDirectory()}catch(i){t=i?.code}finally{if(!e)throw new Zn.CwdError(s,t??"ENOTDIR")}},jh=(s,e)=>{s=(0,pe.normalizeWindowsPath)(s);let t=e.umask??18,i=e.mode|448,r=(i&t)!==0,n=e.uid,o=e.gid,h=typeof n=="number"&&typeof o=="number"&&(n!==e.processUid||o!==e.processGid),a=e.preserve,l=e.unlink,u=(0,pe.normalizeWindowsPath)(e.cwd),c=w=>{w&&h&&(0,Hn.chownrSync)(w,n,o),r&&j.default.chmodSync(s,i)};if(s===u)return xh(u),c();if(a)return c(j.default.mkdirSync(s,{mode:i,recursive:!0})??void 0);let D=(0,pe.normalizeWindowsPath)(ji.default.relative(u,s)).split("/"),A;for(let w=D.shift(),P=u;w&&(P+="/"+w);w=D.shift()){P=(0,pe.normalizeWindowsPath)(ji.default.resolve(P));try{j.default.mkdirSync(P,i),A=A||P}catch{let kt=j.default.lstatSync(P);if(kt.isDirectory())continue;if(l){j.default.unlinkSync(P),j.default.mkdirSync(P,i),A=A||P;continue}else if(kt.isSymbolicLink())return new Gn.SymlinkError(P,P+"/"+D.join("/"))}}return c(A)};De.mkdirSync=jh});var $n=d(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.normalizeUnicode=void 0;var Sr=Object.create(null),Vn=1e4,ut=new Set,Uh=s=>{ut.has(s)?ut.delete(s):Sr[s]=s.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),ut.add(s);let e=Sr[s],t=ut.size-Vn;if(t>Vn/10){for(let i of ut)if(ut.delete(i),delete Sr[i],--t<=0)break}return e};Ui.normalizeUnicode=Uh});var Qn=d(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.PathReservations=void 0;var Xn=require("node:path"),qh=$n(),Wh=wi(),Hh=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Zh=Hh==="win32",Gh=s=>s.split("/").slice(0,-1).reduce((t,i)=>{let r=t.at(-1);return r!==void 0&&(i=(0,Xn.join)(r,i)),t.push(i||"/"),t},[]),gr=class{#e=new Map;#i=new Map;#s=new Set;reserve(e,t){e=Zh?["win32 parallelization disabled"]:e.map(r=>(0,Wh.stripTrailingSlashes)((0,Xn.join)((0,qh.normalizeUnicode)(r))));let i=new Set(e.map(r=>Gh(r)).reduce((r,n)=>r.concat(n)));this.#i.set(t,{dirs:i,paths:e});for(let r of e){let n=this.#e.get(r);n?n.push(t):this.#e.set(r,[t])}for(let r of i){let n=this.#e.get(r);if(!n)this.#e.set(r,[new Set([t])]);else{let o=n.at(-1);o instanceof Set?o.add(t):n.push(new Set([t]))}}return this.#r(t)}#n(e){let t=this.#i.get(e);if(!t)throw new Error("function does not have any path reservations");return{paths:t.paths.map(i=>this.#e.get(i)),dirs:[...t.dirs].map(i=>this.#e.get(i))}}check(e){let{paths:t,dirs:i}=this.#n(e);return t.every(r=>r&&r[0]===e)&&i.every(r=>r&&r[0]instanceof Set&&r[0].has(e))}#r(e){return this.#s.has(e)||!this.check(e)?!1:(this.#s.add(e),e(()=>this.#t(e)),!0)}#t(e){if(!this.#s.has(e))return!1;let t=this.#i.get(e);if(!t)throw new Error("invalid reservation");let{paths:i,dirs:r}=t,n=new Set;for(let o of i){let h=this.#e.get(o);if(!h||h?.[0]!==e)continue;let a=h[1];if(!a){this.#e.delete(o);continue}if(h.shift(),typeof a=="function")n.add(a);else for(let l of a)n.add(l)}for(let o of r){let h=this.#e.get(o),a=h?.[0];if(!(!h||!(a instanceof Set)))if(a.size===1&&h.length===1){this.#e.delete(o);continue}else if(a.size===1){h.shift();let l=h[0];typeof l=="function"&&n.add(l)}else a.delete(e)}return this.#s.delete(e),n.forEach(o=>this.#r(o)),!0}};qi.PathReservations=gr});var Jn=d(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});Wi.umask=void 0;var Yh=()=>process.umask();Wi.umask=Yh});var Ir=d(k=>{"use strict";var Kh=k&&k.__createBinding||(Object.create?(function(s,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(s,i,r)}):(function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]})),Vh=k&&k.__setModuleDefault||(Object.create?(function(s,e){Object.defineProperty(s,"default",{enumerable:!0,value:e})}):function(s,e){s.default=e}),lo=k&&k.__importStar||(function(){var s=function(e){return s=Object.getOwnPropertyNames||function(t){var i=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[i.length]=r);return i},s(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=s(e),r=0;r{if(!Bt)return m.default.unlink(s,e);let t=s+".DELETE."+(0,uo.randomBytes)(16).toString("hex");m.default.rename(s,t,i=>{if(i)return e(i);m.default.unlink(t,e)})},nl=s=>{if(!Bt)return m.default.unlinkSync(s);let e=s+".DELETE."+(0,uo.randomBytes)(16).toString("hex");m.default.renameSync(s,e),m.default.unlinkSync(e)},ho=(s,e,t)=>s!==void 0&&s===s>>>0?s:e!==void 0&&e===e>>>0?e:t,Gi=class extends Qh.Parser{[Rr]=!1;[Ct]=!1;[Hi]=0;reservations=new el.PathReservations;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(e={}){if(e.ondone=()=>{this[Rr]=!0,this[vr]()},super(e),this.transform=e.transform,this.chmod=!!e.chmod,typeof e.uid=="number"||typeof e.gid=="number"){if(typeof e.uid!="number"||typeof e.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(e.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=e.preserveOwner===void 0&&typeof e.uid!="number"?!!(process.getuid&&process.getuid()===0):!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:sl,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||Bt,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=(0,U.normalizeWindowsPath)(g.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:(0,tl.umask)():0,this.umask=typeof e.umask=="number"?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on("entry",t=>this[to](t))}warn(e,t,i={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(i.recoverable=!1),super.warn(e,t,i)}[vr](){this[Rr]&&this[Hi]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Or](e,t){let i=e[t],{type:r}=e;if(!i||this.preservePaths)return!0;let[n,o]=(0,Jh.stripAbsolutePath)(i),h=o.replaceAll(/\\/g,"/").split("/");if(h.includes("..")||Bt&&/^[a-z]:\.\.$/i.test(h[0]??"")){if(t==="path"||r==="Link")return this.warn("TAR_ENTRY_ERROR",`${t} contains '..'`,{entry:e,[t]:i}),!1;let a=g.default.posix.dirname(e.path),l=g.default.posix.normalize(g.default.posix.join(a,h.join("/")));if(l.startsWith("../")||l==="..")return this.warn("TAR_ENTRY_ERROR",`${t} escapes extraction directory`,{entry:e,[t]:i}),!1}return n&&(e[t]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute ${t}`,{entry:e,[t]:i})),!0}[oo](e){let t=(0,U.normalizeWindowsPath)(e.path),i=t.split("/");if(this.strip){if(i.length=this.strip)e.linkpath=r.slice(this.strip).join("/");else return!1}i.splice(0,this.strip),e.path=i.join("/")}if(isFinite(this.maxDepth)&&i.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:e,path:t,depth:i.length,maxDepth:this.maxDepth}),!1;if(!this[Or](e,"path")||!this[Or](e,"linkpath"))return!1;if(e.absolute=g.default.isAbsolute(e.path)?(0,U.normalizeWindowsPath)(g.default.resolve(e.path)):(0,U.normalizeWindowsPath)(g.default.resolve(this.cwd,e.path)),!this.preservePaths&&typeof e.absolute=="string"&&e.absolute.indexOf(this.cwd+"/")!==0&&e.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:e,path:(0,U.normalizeWindowsPath)(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!=="Directory"&&e.type!=="GNUDumpDir")return!1;if(this.win32){let{root:r}=g.default.win32.parse(String(e.absolute));e.absolute=r+eo.encode(String(e.absolute).slice(r.length));let{root:n}=g.default.win32.parse(e.path);e.path=n+eo.encode(e.path.slice(n.length))}return!0}[to](e){if(!this[oo](e))return e.resume();switch(Xh.default.equal(typeof e.absolute,"string"),e.type){case"Directory":case"GNUDumpDir":e.mode&&(e.mode=e.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Tr](e);default:return this[no](e)}}[T](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[ct](),t.resume())}[Pe](e,t,i){(0,fo.mkdir)((0,U.normalizeWindowsPath)(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t},i)}[At](e){return this.forceChown||this.preserveOwner&&(typeof e.uid=="number"&&e.uid!==this.processUid||typeof e.gid=="number"&&e.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[It](e){return ho(this.uid,e.uid,this.processUid)}[Ft](e){return ho(this.gid,e.gid,this.processGid)}[Pr](e,t){let i=typeof e.mode=="number"?e.mode&4095:this.fmode,r=new $h.WriteStream(String(e.absolute),{flags:(0,co.getWriteFlag)(e.size),mode:i,autoClose:!1});r.on("error",a=>{r.fd&&m.default.close(r.fd,()=>{}),r.write=()=>!0,this[T](a,e),t()});let n=1,o=a=>{if(a){r.fd&&m.default.close(r.fd,()=>{}),this[T](a,e),t();return}--n===0&&r.fd!==void 0&&m.default.close(r.fd,l=>{l?this[T](l,e):this[ct](),t()})};r.on("finish",()=>{let a=String(e.absolute),l=r.fd;if(typeof l=="number"&&e.mtime&&!this.noMtime){n++;let u=e.atime||new Date,c=e.mtime;m.default.futimes(l,u,c,E=>E?m.default.utimes(a,u,c,D=>o(D&&E)):o())}if(typeof l=="number"&&this[At](e)){n++;let u=this[It](e),c=this[Ft](e);typeof u=="number"&&typeof c=="number"&&m.default.fchown(l,u,c,E=>E?m.default.chown(a,u,c,D=>o(D&&E)):o())}o()});let h=this.transform&&this.transform(e)||e;h!==e&&(h.on("error",a=>{this[T](a,e),t()}),e.pipe(h)),h.pipe(r)}[Nr](e,t){let i=typeof e.mode=="number"?e.mode&4095:this.dmode;this[Pe](String(e.absolute),i,r=>{if(r){this[T](r,e),t();return}let n=1,o=()=>{--n===0&&(t(),this[ct](),e.resume())};e.mtime&&!this.noMtime&&(n++,m.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[At](e)&&(n++,m.default.chown(String(e.absolute),Number(this[It](e)),Number(this[Ft](e)),o)),o()})}[no](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[so](e,t){let i=(0,U.normalizeWindowsPath)(g.default.relative(this.cwd,g.default.resolve(g.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[Lt](e,this.cwd,i,()=>this[Zi](e,String(e.linkpath),"symlink",t),r=>{this[T](r,e),t()})}[ro](e,t){let i=(0,U.normalizeWindowsPath)(g.default.resolve(this.cwd,String(e.linkpath))),r=(0,U.normalizeWindowsPath)(String(e.linkpath)).split("/");this[Lt](e,this.cwd,r,()=>this[Zi](e,i,"link",t),n=>{this[T](n,e),t()})}[Lt](e,t,i,r,n){let o=i.shift();if(this.preservePaths||o===void 0)return r();let h=g.default.resolve(t,o);m.default.lstat(h,(a,l)=>{if(a)return r();if(l?.isSymbolicLink())return n(new mo.SymlinkError(h,g.default.resolve(h,i.join("/"))));this[Lt](e,h,i,r,n)})}[ao](){this[Hi]++}[ct](){this[Hi]--,this[vr]()}[Mr](e){this[ct](),e.resume()}[Dr](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!Bt}[Tr](e){this[ao]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,i=>this[io](e,i))}[io](e,t){let i=h=>{t(h)},r=()=>{this[Pe](this.cwd,this.dmode,h=>{if(h){this[T](h,e),i();return}this[Ct]=!0,n()})},n=()=>{if(e.absolute!==this.cwd){let h=(0,U.normalizeWindowsPath)(g.default.dirname(String(e.absolute)));if(h!==this.cwd)return this[Pe](h,this.dmode,a=>{if(a){this[T](a,e),i();return}o()})}o()},o=()=>{m.default.lstat(String(e.absolute),(h,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[Mr](e),i();return}if(h||this[Dr](e,a))return this[Z](null,e,i);if(a.isDirectory()){if(e.type==="Directory"){let l=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,u=c=>this[Z](c??null,e,i);return l?m.default.chmod(String(e.absolute),Number(e.mode),u):u()}if(e.absolute!==this.cwd)return m.default.rmdir(String(e.absolute),l=>this[Z](l??null,e,i))}if(e.absolute===this.cwd)return this[Z](null,e,i);rl(String(e.absolute),l=>this[Z](l??null,e,i))})};this[Ct]?n():r()}[Z](e,t,i){if(e){this[T](e,t),i();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[Pr](t,i);case"Link":return this[ro](t,i);case"SymbolicLink":return this[so](t,i);case"Directory":case"GNUDumpDir":return this[Nr](t,i)}}[Zi](e,t,i,r){m.default[i](t,String(e.absolute),n=>{n?this[T](n,e):(this[ct](),e.resume()),r()})}};k.Unpack=Gi;var Mt=s=>{try{return[null,s()]}catch(e){return[e,null]}},Lr=class extends Gi{sync=!0;[Z](e,t){return super[Z](e,t,()=>{})}[Tr](e){if(!this[Ct]){let n=this[Pe](this.cwd,this.dmode);if(n)return this[T](n,e);this[Ct]=!0}if(e.absolute!==this.cwd){let n=(0,U.normalizeWindowsPath)(g.default.dirname(String(e.absolute)));if(n!==this.cwd){let o=this[Pe](n,this.dmode);if(o)return this[T](o,e)}}let[t,i]=Mt(()=>m.default.lstatSync(String(e.absolute)));if(i&&(this.keep||this.newer&&i.mtime>(e.mtime??i.mtime)))return this[Mr](e);if(t||this[Dr](e,i))return this[Z](null,e);if(i.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(i.mode&4095)!==e.mode,[h]=o?Mt(()=>{m.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[Z](h,e)}let[n]=Mt(()=>m.default.rmdirSync(String(e.absolute)));this[Z](n,e)}let[r]=e.absolute===this.cwd?[]:Mt(()=>nl(String(e.absolute)));this[Z](r,e)}[Pr](e,t){let i=typeof e.mode=="number"?e.mode&4095:this.fmode,r=h=>{let a;try{m.default.closeSync(n)}catch(l){a=l}(h||a)&&this[T](h||a,e),t()},n;try{n=m.default.openSync(String(e.absolute),(0,co.getWriteFlag)(e.size),i)}catch(h){return r(h)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",h=>this[T](h,e)),e.pipe(o)),o.on("data",h=>{try{m.default.writeSync(n,h,0,h.length)}catch(a){r(a)}}),o.on("end",()=>{let h=null;if(e.mtime&&!this.noMtime){let a=e.atime||new Date,l=e.mtime;try{m.default.futimesSync(n,a,l)}catch(u){try{m.default.utimesSync(String(e.absolute),a,l)}catch{h=u}}}if(this[At](e)){let a=this[It](e),l=this[Ft](e);try{m.default.fchownSync(n,Number(a),Number(l))}catch(u){try{m.default.chownSync(String(e.absolute),Number(a),Number(l))}catch{h=h||u}}}r(h)})}[Nr](e,t){let i=typeof e.mode=="number"?e.mode&4095:this.dmode,r=this[Pe](String(e.absolute),i);if(r){this[T](r,e),t();return}if(e.mtime&&!this.noMtime)try{m.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[At](e))try{m.default.chownSync(String(e.absolute),Number(this[It](e)),Number(this[Ft](e)))}catch{}t(),e.resume()}[Pe](e,t){try{return(0,fo.mkdirSync)((0,U.normalizeWindowsPath)(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t})}catch(i){return i}}[Lt](e,t,i,r,n){if(this.preservePaths||i.length===0)return r();let o=t;for(let h of i){o=g.default.resolve(o,h);let[a,l]=Mt(()=>m.default.lstatSync(o));if(a)return r();if(l.isSymbolicLink())return n(new mo.SymlinkError(o,g.default.resolve(t,i.join("/"))))}r()}[Zi](e,t,i,r){let n=`${i}Sync`;try{m.default[n](t,String(e.absolute)),r(),e.resume()}catch(o){return this[T](o,e)}}};k.UnpackSync=Lr});var Fr=d(G=>{"use strict";var ol=G&&G.__createBinding||(Object.create?(function(s,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(s,i,r)}):(function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]})),al=G&&G.__setModuleDefault||(Object.create?(function(s,e){Object.defineProperty(s,"default",{enumerable:!0,value:e})}):function(s,e){s.default=e}),hl=G&&G.__importStar||(function(){var s=function(e){return s=Object.getOwnPropertyNames||function(t){var i=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[i.length]=r);return i},s(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=s(e),r=0;r{let e=new Yi.UnpackSync(s),t=s.file,i=_o.default.statSync(t),r=s.maxReadSize||16*1024*1024;new po.ReadStreamSync(t,{readSize:r,size:i.size}).pipe(e)},dl=(s,e)=>{let t=new Yi.Unpack(s),i=s.maxReadSize||16*1024*1024,r=s.file;return new Promise((o,h)=>{t.on("error",h),t.on("close",o),_o.default.stat(r,(a,l)=>{if(a)h(a);else{let u=new po.ReadStream(r,{readSize:i,size:l.size});u.on("error",h),u.pipe(t)}})})};G.extract=(0,cl.makeCommand)(fl,dl,s=>new Yi.UnpackSync(s),s=>new Yi.Unpack(s),(s,e)=>{e?.length&&(0,ul.filesFilter)(s,e)})});var Ki=d(ft=>{"use strict";var wo=ft&&ft.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ft,"__esModule",{value:!0});ft.replace=void 0;var yo=Ke(),q=wo(require("node:fs")),Eo=wo(require("node:path")),bo=et(),So=rt(),ml=Ve(),pl=Xt(),go=Fi(),_l=(s,e)=>{let t=new go.PackSync(s),i=!0,r,n;try{try{r=q.default.openSync(s.file,"r+")}catch(a){if(a?.code==="ENOENT")r=q.default.openSync(s.file,"w+");else throw a}let o=q.default.fstatSync(r),h=Buffer.alloc(512);e:for(n=0;no.size)break;n+=l,s.mtimeCache&&a.mtime&&s.mtimeCache.set(String(a.path),a.mtime)}i=!1,wl(s,t,n,r,e)}finally{if(i)try{q.default.closeSync(r)}catch{}}},wl=(s,e,t,i,r)=>{let n=new yo.WriteStreamSync(s.file,{fd:i,start:t});e.pipe(n),El(e,r)},yl=(s,e)=>{e=Array.from(e);let t=new go.Pack(s),i=(n,o,h)=>{let a=(D,A)=>{D?q.default.close(n,w=>h(D)):h(null,A)},l=0;if(o===0)return a(null,0);let u=0,c=Buffer.alloc(512),E=(D,A)=>{if(D||A===void 0)return a(D);if(u+=A,u<512&&A)return q.default.read(n,c,u,c.length-u,l+u,E);if(l===0&&c[0]===31&&c[1]===139)return a(new Error("cannot append to compressed archives"));if(u<512)return a(null,l);let w=new bo.Header(c);if(!w.cksumValid)return a(null,l);let P=512*Math.ceil((w.size??0)/512);if(l+P+512>o||(l+=P+512,l>=o))return a(null,l);s.mtimeCache&&w.mtime&&s.mtimeCache.set(String(w.path),w.mtime),u=0,q.default.read(n,c,0,512,l,E)};q.default.read(n,c,0,512,l,E)};return new Promise((n,o)=>{t.on("error",o);let h="r+",a=(l,u)=>{if(l&&l.code==="ENOENT"&&h==="r+")return h="w+",q.default.open(s.file,h,a);if(l||!u)return o(l);q.default.fstat(u,(c,E)=>{if(c)return q.default.close(u,()=>o(c));i(u,E.size,(D,A)=>{if(D)return o(D);let w=new yo.WriteStream(s.file,{fd:u,start:A});t.pipe(w),w.on("error",o),w.on("close",n),bl(t,e)})})};q.default.open(s.file,h,a)})},El=(s,e)=>{e.forEach(t=>{t.charAt(0)==="@"?(0,So.list)({file:Eo.default.resolve(s.cwd,t.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>s.add(i)}):s.add(t)}),s.end()},bl=async(s,e)=>{for(let t of e)t.charAt(0)==="@"?await(0,So.list)({file:Eo.default.resolve(String(s.cwd),t.slice(1)),noResume:!0,onReadEntry:i=>s.add(i)}):s.add(t);s.end()};ft.replace=(0,ml.makeCommand)(_l,yl,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(s,e)=>{if(!(0,pl.isFile)(s))throw new TypeError("file is required");if(s.gzip||s.brotli||s.zstd||s.file.endsWith(".br")||s.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!e?.length)throw new TypeError("no paths specified to add/replace")})});var Cr=d(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.update=void 0;var Sl=Ve(),zt=Ki();Vi.update=(0,Sl.makeCommand)(zt.replace.syncFile,zt.replace.asyncFile,zt.replace.syncNoFile,zt.replace.asyncNoFile,(s,e=[])=>{zt.replace.validate?.(s,e),gl(s)});var gl=s=>{let e=s.filter;s.mtimeCache||(s.mtimeCache=new Map),s.filter=e?(t,i)=>e(t,i)&&!((s.mtimeCache?.get(t)??i.mtime??0)>(i.mtime??0)):(t,i)=>!((s.mtimeCache?.get(t)??i.mtime??0)>(i.mtime??0))}});var Oo=exports&&exports.__createBinding||(Object.create?(function(s,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(s,i,r)}):(function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]})),Ol=exports&&exports.__setModuleDefault||(Object.create?(function(s,e){Object.defineProperty(s,"default",{enumerable:!0,value:e})}):function(s,e){s.default=e}),Y=exports&&exports.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Oo(e,s,t)},Rl=exports&&exports.__importStar||(function(){var s=function(e){return s=Object.getOwnPropertyNames||function(t){var i=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[i.length]=r);return i},s(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=s(e),r=0;r { + 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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/list.js b/node_modules/tar/dist/commonjs/list.js new file mode 100644 index 0000000000000..700030a0ac101 --- /dev/null +++ b/node_modules/tar/dist/commonjs/list.js @@ -0,0 +1,145 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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); + ret = m !== undefined ? m : 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 { + fd = node_fs_1.default.openSync(file, 'r'); + const stat = node_fs_1.default.fstatSync(fd); + const readSize = opt.maxReadSize || 16 * 1024 * 1024; + if (stat.size < readSize) { + const buf = Buffer.allocUnsafe(stat.size); + const read = node_fs_1.default.readSync(fd, buf, 0, stat.size, 0); + p.end(read === buf.byteLength ? buf : buf.subarray(0, read)); + } + else { + let pos = 0; + const buf = Buffer.allocUnsafe(readSize); + while (pos < stat.size) { + const bytesRead = node_fs_1.default.readSync(fd, buf, 0, readSize, pos); + if (bytesRead === 0) + break; + 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 { } + } + } +}; +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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/make-command.js b/node_modules/tar/dist/commonjs/make-command.js new file mode 100644 index 0000000000000..d6fc6c7e38e80 --- /dev/null +++ b/node_modules/tar/dist/commonjs/make-command.js @@ -0,0 +1,52 @@ +"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; + } + entries = !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); + return cb ? p.then(() => cb(), cb) : 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 */ + } + throw new Error('impossible options??'); + /* c8 ignore stop */ + }, { + syncFile, + asyncFile, + syncNoFile, + asyncNoFile, + validate, + }); +}; +exports.makeCommand = makeCommand; +//# sourceMappingURL=make-command.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/mkdir.js b/node_modules/tar/dist/commonjs/mkdir.js new file mode 100644 index 0000000000000..050e6bb2ab6c6 --- /dev/null +++ b/node_modules/tar/dist/commonjs/mkdir.js @@ -0,0 +1,187 @@ +"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 node_fs_1 = __importDefault(require("node:fs")); +const promises_1 = __importDefault(require("node:fs/promises")); +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 checkCwd = (dir, cb) => { + node_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 fs/promises.mkdir 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 cwd = (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.cwd); + const done = (er, created) => { + if (er) { + cb(er); + } + else { + if (created && doChown) { + (0, chownr_1.chownr)(created, uid, gid, er => done(er)); + } + else if (needChmod) { + node_fs_1.default.chmod(dir, mode, cb); + } + else { + cb(); + } + } + }; + if (dir === cwd) { + return checkCwd(dir, done); + } + if (preserve) { + return promises_1.default.mkdir(dir, { mode, recursive: true }).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, unlink, cwd, undefined, done); +}; +exports.mkdir = mkdir; +const mkdir_ = (base, parts, mode, unlink, cwd, created, cb) => { + if (parts.length === 0) { + return cb(null, created); + } + const p = parts.shift(); + const part = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(base + '/' + p)); + node_fs_1.default.mkdir(part, mode, onmkdir(part, parts, mode, unlink, cwd, created, cb)); +}; +const onmkdir = (part, parts, mode, unlink, cwd, created, cb) => (er) => { + if (er) { + node_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, unlink, cwd, created, cb); + } + else if (unlink) { + node_fs_1.default.unlink(part, er => { + if (er) { + return cb(er); + } + node_fs_1.default.mkdir(part, mode, onmkdir(part, parts, mode, 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, unlink, cwd, created, cb); + } +}; +const checkCwdSync = (dir) => { + let ok = false; + let code; + try { + ok = node_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 cwd = (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.cwd); + const done = (created) => { + if (created && doChown) { + (0, chownr_1.chownrSync)(created, uid, gid); + } + if (needChmod) { + node_fs_1.default.chmodSync(dir, mode); + } + }; + if (dir === cwd) { + checkCwdSync(cwd); + return done(); + } + if (preserve) { + return done(node_fs_1.default.mkdirSync(dir, { mode, recursive: true }) ?? undefined); + } + const sub = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.relative(cwd, dir)); + const parts = sub.split('/'); + let created; + 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)); + try { + node_fs_1.default.mkdirSync(part, mode); + created = created || part; + } + catch { + const st = node_fs_1.default.lstatSync(part); + if (st.isDirectory()) { + continue; + } + else if (unlink) { + node_fs_1.default.unlinkSync(part); + node_fs_1.default.mkdirSync(part, mode); + created = created || part; + 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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/mode-fix.js b/node_modules/tar/dist/commonjs/mode-fix.js new file mode 100644 index 0000000000000..49dd727961d29 --- /dev/null +++ b/node_modules/tar/dist/commonjs/mode-fix.js @@ -0,0 +1,29 @@ +"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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/normalize-unicode.js b/node_modules/tar/dist/commonjs/normalize-unicode.js new file mode 100644 index 0000000000000..5b0eaec8ccb49 --- /dev/null +++ b/node_modules/tar/dist/commonjs/normalize-unicode.js @@ -0,0 +1,38 @@ +"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); +// Limit the size of this. Very low-sophistication LRU cache +const MAX = 10000; +const cache = new Set(); +const normalizeUnicode = (s) => { + if (!cache.has(s)) { + // shake out identical accents and ligatures + normalizeCache[s] = s + .normalize('NFD') + .toLocaleLowerCase('en') + .toLocaleUpperCase('en'); + } + else { + cache.delete(s); + } + cache.add(s); + const ret = normalizeCache[s]; + let i = cache.size - MAX; + // only prune when we're 10% over the max + if (i > MAX / 10) { + for (const s of cache) { + cache.delete(s); + delete normalizeCache[s]; + if (--i <= 0) + break; + } + } + return ret; +}; +exports.normalizeUnicode = normalizeUnicode; +//# sourceMappingURL=normalize-unicode.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/normalize-windows-path.js b/node_modules/tar/dist/commonjs/normalize-windows-path.js new file mode 100644 index 0000000000000..dd87c2856558a --- /dev/null +++ b/node_modules/tar/dist/commonjs/normalize-windows-path.js @@ -0,0 +1,12 @@ +"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.replaceAll(/\\/g, '/'); +//# sourceMappingURL=normalize-windows-path.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/options.js b/node_modules/tar/dist/commonjs/options.js new file mode 100644 index 0000000000000..4cd06505bc72b --- /dev/null +++ b/node_modules/tar/dist/commonjs/options.js @@ -0,0 +1,66 @@ +"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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/pack.js b/node_modules/tar/dist/commonjs/pack.js new file mode 100644 index 0000000000000..5a4c37a766304 --- /dev/null +++ b/node_modules/tar/dist/commonjs/pack.js @@ -0,0 +1,544 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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; + pendingLink = 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 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 PENDINGLINKS = Symbol('pendingLinks'); +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 { + sync = false; + opt; + cwd; + maxReadSize; + preservePaths; + strict; + noPax; + prefix; + linkCache; + statCache; + file; + portable; + zip; + readdirCache; + noDirRecurse; + follow; + noMtime; + mtime; + filter; + jobs; + [WRITEENTRYCLASS]; + onWriteEntry; + // Note: we actually DO need a linked list here, because we + // shift() to update the head of the list where we start, but still + // while that happens, need to know what the next item in the queue + // will be. Since we do multiple jobs in parallel, it's not as simple + // as just an Array.shift(), since that would lose the information about + // the next job in the list. We could add a .next field on the PackJob + // class, but then we'd have to be tracking the tail of the queue the + // whole time, and Yallist just does that for us anyway. + [QUEUE]; + [PENDINGLINKS] = new Map(); + [JOBS] = 0; + [PROCESSING] = false; + [ENDED] = false; + constructor(opt = {}) { + 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 || opt.zstd) { + if ((opt.gzip ? 1 : 0) + (opt.brotli ? 1 : 0) + (opt.zstd ? 1 : 0) > + 1) { + throw new TypeError('gzip, brotli, zstd 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); + } + if (opt.zstd) { + if (typeof opt.zstd !== 'object') { + opt.zstd = {}; + } + this.zip = new zlib.ZstdCompress(opt.zstd); + } + /* 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 (typeof path === 'string') { + this[ADDFSENTRY](path); + } + else { + this[ADDTARENTRY](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; + } + else if (stat.isFile() && + stat.nlink > 1 && + !this.linkCache.get(`${stat.dev}:${stat.ino}`) && + !this.sync) { + // if it's not filtered, and it's a new File entry, and next anyway + // process right away in case any pending Link entries are about + // to try to link to it. + if (job === this[CURRENT]) { + this[PROCESSJOB](job); + } + else { + // if it's NOT the current entry, it needs to be deferred, + // so that the link target can be built first. + const key = `${stat.dev}:${stat.ino}`; + const pending = this[PENDINGLINKS].get(key); + if (pending) + pending.push(job); + else + this[PENDINGLINKS].set(key, [job]); + job.pendingLink = true; + job.pending = 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 === 0 && 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; + const { stat } = job; + if (stat && stat.isFile() && stat.nlink > 1) { + // might be a file with pending links + const key = `${stat.dev}:${stat.ino}`; + const pending = this[PENDINGLINKS].get(key); + if (pending) { + this[PENDINGLINKS].delete(key); + for (const job of pending) { + job.pending = false; + this[PROCESSJOB](job); + } + } + } + this[PROCESS](); + } + [PROCESSJOB](job) { + if (job.pending && job.pendingLink && job === this[CURRENT]) { + // At least one of the links to this file are not being included + // in the tarball, so we need to just proceed. + job.pending = false; + job.pendingLink = false; + } + 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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/package.json b/node_modules/tar/dist/commonjs/package.json new file mode 100644 index 0000000000000..5bbefffbabee3 --- /dev/null +++ b/node_modules/tar/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/tar/dist/commonjs/parse.js b/node_modules/tar/dist/commonjs/parse.js new file mode 100644 index 0000000000000..dd0f96127bb2f --- /dev/null +++ b/node_modules/tar/dist/commonjs/parse.js @@ -0,0 +1,610 @@ +"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 list 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 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 zstdHeader = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]); +const ZIP_HEADER_LEN = Math.max(gzipHeader.length, zstdHeader.length); +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; + zstd; + writable = true; + readable = false; + [QUEUE] = []; + [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.zstd) && opt.brotli !== undefined ? opt.brotli + : isTBR ? undefined + : false; + // zstd has magic bytes to identify it, but we also support explicit options + // and file extension detection + const isTZST = opt.file && + (opt.file.endsWith('.tar.zst') || opt.file.endsWith('.tzst')); + this.zstd = + !(opt.gzip || opt.brotli) && opt.zstd !== undefined ? opt.zstd + : isTZST ? true + : undefined; + // 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 === 0) { + // 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 === 0 && !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, zstd, or brotli compressed + 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 < ZIP_HEADER_LEN) { + 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; + } + } + // look for zstd header if gzip header not found + let isZstd = false; + if (this[UNZIP] === false && this.zstd !== false) { + isZstd = true; + for (let i = 0; i < zstdHeader.length; i++) { + if (chunk[i] !== zstdHeader[i]) { + isZstd = false; + break; + } + } + } + const maybeBrotli = this.brotli === undefined && !isZstd; + 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 || isZstd))) { + const ended = this[ENDED]; + this[ENDED] = false; + this[UNZIP] = + this[UNZIP] === undefined ? new minizlib_1.Unzip({}) + : isZstd ? new minizlib_1.ZstdDecompress({}) + : 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 > 0 ? false + : this[READENTRY] ? this[READENTRY].flowing + : true; + // if we have no queue, then that means a clogged READENTRY + if (!ret && this[QUEUE].length === 0) { + 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) { + this[BUFFER] = + this[BUFFER] ? + Buffer.concat([chunk.subarray(position), 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 || this.zstd === undefined) + chunk = chunk || Buffer.alloc(0); + if (chunk) + this.write(chunk); + this[MAYBEEND](); + } + } + return this; + } +} +exports.Parser = Parser; +//# sourceMappingURL=parse.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/path-reservations.js b/node_modules/tar/dist/commonjs/path-reservations.js new file mode 100644 index 0000000000000..68eeefbce6599 --- /dev/null +++ b/node_modules/tar/dist/commonjs/path-reservations.js @@ -0,0 +1,170 @@ +"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.at(-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))); + }); + 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.at(-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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/pax.js b/node_modules/tar/dist/commonjs/pax.js new file mode 100644 index 0000000000000..d30c0f3efbe9e --- /dev/null +++ b/node_modules/tar/dist/commonjs/pax.js @@ -0,0 +1,158 @@ +"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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/process-umask.js b/node_modules/tar/dist/commonjs/process-umask.js new file mode 100644 index 0000000000000..9256bcc56cdf5 --- /dev/null +++ b/node_modules/tar/dist/commonjs/process-umask.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.umask = void 0; +// separate file so I stop getting nagged in vim about deprecated API. +const umask = () => process.umask(); +exports.umask = umask; +//# sourceMappingURL=process-umask.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/read-entry.js b/node_modules/tar/dist/commonjs/read-entry.js new file mode 100644 index 0000000000000..655d7dbc0d357 --- /dev/null +++ b/node_modules/tar/dist/commonjs/read-entry.js @@ -0,0 +1,136 @@ +"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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/replace.js b/node_modules/tar/dist/commonjs/replace.js new file mode 100644 index 0000000000000..576a83981f7b9 --- /dev/null +++ b/node_modules/tar/dist/commonjs/replace.js @@ -0,0 +1,227 @@ +"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 { } + } + } +}; +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 || 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 (const file of files) { + 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.zstd || + 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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/strip-absolute-path.js b/node_modules/tar/dist/commonjs/strip-absolute-path.js new file mode 100644 index 0000000000000..bb7639c35a110 --- /dev/null +++ b/node_modules/tar/dist/commonjs/strip-absolute-path.js @@ -0,0 +1,29 @@ +"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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/strip-trailing-slashes.js b/node_modules/tar/dist/commonjs/strip-trailing-slashes.js new file mode 100644 index 0000000000000..6fa74ad6a4ac9 --- /dev/null +++ b/node_modules/tar/dist/commonjs/strip-trailing-slashes.js @@ -0,0 +1,18 @@ +"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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/symlink-error.js b/node_modules/tar/dist/commonjs/symlink-error.js new file mode 100644 index 0000000000000..cc19ac1a2e3c6 --- /dev/null +++ b/node_modules/tar/dist/commonjs/symlink-error.js @@ -0,0 +1,19 @@ +"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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/types.js b/node_modules/tar/dist/commonjs/types.js new file mode 100644 index 0000000000000..7cbcc17ef1918 --- /dev/null +++ b/node_modules/tar/dist/commonjs/types.js @@ -0,0 +1,70 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.code = exports.name = exports.normalFsTypes = 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; +/** + * types that are a normal file system entry, not metadata. + * + * These can be the subject of extended/globalExtended headers, long path + * names, long linkpath names, etc. + * + * Any other types are meta, and cannot be targetted by extended PAX headers. + */ +exports.normalFsTypes = new Set([ + '0', + '', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + 'D', +]); +// 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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/unpack.js b/node_modules/tar/dist/commonjs/unpack.js new file mode 100644 index 0000000000000..3df1031d84cbe --- /dev/null +++ b/node_modules/tar/dist/commonjs/unpack.js @@ -0,0 +1,932 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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_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 wc = __importStar(require("./winchars.js")); +const path_reservations_js_1 = require("./path-reservations.js"); +const symlink_error_js_1 = require("./symlink-error.js"); +const process_umask_js_1 = require("./process-umask.js"); +const ONENTRY = Symbol('onEntry'); +const CHECKFS = Symbol('checkFs'); +const CHECKFS2 = Symbol('checkFs2'); +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 ENSURE_NO_SYMLINK = Symbol('ensureNoSymlink'); +const UNSUPPORTED = Symbol('unsupported'); +const CHECKPATH = Symbol('checkPath'); +const STRIPABSOLUTEPATH = Symbol('stripAbsolutePath'); +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; +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; + 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.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 + this.preserveOwner = + opt.preserveOwner === undefined && typeof opt.uid !== 'number' ? + !!(process.getuid && process.getuid() === 0) + : !!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'); + } + } + // return false if we need to skip this file + // return true if the field was successfully sanitized + [STRIPABSOLUTEPATH](entry, field) { + const p = entry[field]; + const { type } = entry; + if (!p || this.preservePaths) + return true; + // strip off the root + const [root, stripped] = (0, strip_absolute_path_js_1.stripAbsolutePath)(p); + const parts = stripped.replaceAll(/\\/g, '/').split('/'); + if (parts.includes('..') || + /* c8 ignore next */ + (isWindows && /^[a-z]:\.\.$/i.test(parts[0] ?? ''))) { + // For linkpath, check if the resolved path escapes cwd rather than + // just rejecting any path with '..' - relative symlinks like + // '../sibling/file' are valid if they resolve within the cwd. + // For paths, they just simply may not ever use .. at all. + if (field === 'path' || type === 'Link') { + this.warn('TAR_ENTRY_ERROR', `${field} contains '..'`, { + entry, + [field]: p, + }); + // not ok! + return false; + } + // Resolve linkpath relative to the entry's directory. + // `path.posix` is safe to use because we're operating on + // tar paths, not a filesystem. + const entryDir = node_path_1.default.posix.dirname(entry.path); + const resolved = node_path_1.default.posix.normalize(node_path_1.default.posix.join(entryDir, parts.join('/'))); + // If the resolved path escapes (starts with ..), reject it + if (resolved.startsWith('../') || resolved === '..') { + this.warn('TAR_ENTRY_ERROR', `${field} escapes extraction directory`, { + entry, + [field]: p, + }); + return false; + } + } + if (root) { + // ok, but triggers warning about stripping root + entry[field] = String(stripped); + this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute ${field}`, { + entry, + [field]: p, + }); + } + return true; + } + // no IO, just string checking for absolute indicators + [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[STRIPABSOLUTEPATH](entry, 'path') || + !this[STRIPABSOLUTEPATH](entry, 'linkpath')) { + return false; + } + entry.absolute = + node_path_1.default.isAbsolute(entry.path) ? + (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(entry.path)) + : (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, + 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) { + const parts = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.relative(this.cwd, node_path_1.default.resolve(node_path_1.default.dirname(String(entry.absolute)), String(entry.linkpath)))).split('/'); + this[ENSURE_NO_SYMLINK](entry, this.cwd, parts, () => this[LINK](entry, String(entry.linkpath), 'symlink', done), er => { + this[ONERROR](er, entry); + done(); + }); + } + [HARDLINK](entry, done) { + const linkpath = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(this.cwd, String(entry.linkpath))); + const parts = (0, normalize_windows_path_js_1.normalizeWindowsPath)(String(entry.linkpath)).split('/'); + this[ENSURE_NO_SYMLINK](entry, this.cwd, parts, () => this[LINK](entry, linkpath, 'link', done), er => { + this[ONERROR](er, entry); + done(); + }); + } + [ENSURE_NO_SYMLINK](entry, cwd, parts, done, onError) { + const p = parts.shift(); + if (this.preservePaths || p === undefined) + return done(); + const t = node_path_1.default.resolve(cwd, p); + node_fs_1.default.lstat(t, (er, st) => { + if (er) + return done(); + if (st?.isSymbolicLink()) { + return onError(new symlink_error_js_1.SymlinkError(t, node_path_1.default.resolve(t, parts.join('/')))); + } + this[ENSURE_NO_SYMLINK](entry, t, parts, done, onError); + }); + } + [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)); + } + [CHECKFS2](entry, fullyDone) { + const done = (er) => { + 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) { + 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) { + 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); + /* c8 ignore start - This is only a problem if the file was successfully + * statted, BUT failed to open. Testing this is annoying, and we + * already have ample testint for other uses of oner() methods. + */ + } + catch (er) { + return oner(er); + } + /* c8 ignore stop */ + 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 { + 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 { + 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 { } + } + if (this[DOCHOWN](entry)) { + try { + node_fs_1.default.chownSync(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry))); + } + catch { } + } + 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, + cwd: this.cwd, + mode: mode, + }); + } + catch (er) { + return er; + } + } + [ENSURE_NO_SYMLINK](_entry, cwd, parts, done, onError) { + if (this.preservePaths || parts.length === 0) + return done(); + let t = cwd; + for (const p of parts) { + t = node_path_1.default.resolve(t, p); + const [er, st] = callSync(() => node_fs_1.default.lstatSync(t)); + if (er) + return done(); + if (st.isSymbolicLink()) { + return onError(new symlink_error_js_1.SymlinkError(t, node_path_1.default.resolve(cwd, parts.join('/')))); + } + } + done(); + } + [LINK](entry, linkpath, link, done) { + const linkSync = `${link}Sync`; + try { + node_fs_1.default[linkSync](linkpath, String(entry.absolute)); + done(); + entry.resume(); + } + catch (er) { + return this[ONERROR](er, entry); + } + } +} +exports.UnpackSync = UnpackSync; +//# sourceMappingURL=unpack.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/update.js b/node_modules/tar/dist/commonjs/update.js new file mode 100644 index 0000000000000..7687896f4bfee --- /dev/null +++ b/node_modules/tar/dist/commonjs/update.js @@ -0,0 +1,33 @@ +"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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/warn-method.js b/node_modules/tar/dist/commonjs/warn-method.js new file mode 100644 index 0000000000000..f25502776e36a --- /dev/null +++ b/node_modules/tar/dist/commonjs/warn-method.js @@ -0,0 +1,31 @@ +"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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/winchars.js b/node_modules/tar/dist/commonjs/winchars.js new file mode 100644 index 0000000000000..1ce09630d3df0 --- /dev/null +++ b/node_modules/tar/dist/commonjs/winchars.js @@ -0,0 +1,14 @@ +"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.fromCodePoint(0xf000 + Number(char.codePointAt(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 \ No newline at end of file diff --git a/node_modules/tar/dist/commonjs/write-entry.js b/node_modules/tar/dist/commonjs/write-entry.js new file mode 100644 index 0000000000000..db4fa77afe258 --- /dev/null +++ b/node_modules/tar/dist/commonjs/write-entry.js @@ -0,0 +1,698 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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.replaceAll(/\\/g, '/')); + p = p.replaceAll(/\\/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 { } + } + } + } + [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); + if (chunk) + super.end(chunk, cb); + else + 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.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/create.js b/node_modules/tar/dist/esm/create.js new file mode 100644 index 0000000000000..4e88751690d86 --- /dev/null +++ b/node_modules/tar/dist/esm/create.js @@ -0,0 +1,76 @@ +import { 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).catch(er => p.emit('error', er)); + 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 (const file of files) { + 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).catch(er => p.emit('error', er)); + 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.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/cwd-error.js b/node_modules/tar/dist/esm/cwd-error.js new file mode 100644 index 0000000000000..289a066b8e031 --- /dev/null +++ b/node_modules/tar/dist/esm/cwd-error.js @@ -0,0 +1,14 @@ +export 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 \ No newline at end of file diff --git a/node_modules/tar/dist/esm/extract.js b/node_modules/tar/dist/esm/extract.js new file mode 100644 index 0000000000000..2274feef26e78 --- /dev/null +++ b/node_modules/tar/dist/esm/extract.js @@ -0,0 +1,49 @@ +// 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 \ No newline at end of file diff --git a/node_modules/tar/dist/esm/get-write-flag.js b/node_modules/tar/dist/esm/get-write-flag.js new file mode 100644 index 0000000000000..73d574522d8b3 --- /dev/null +++ b/node_modules/tar/dist/esm/get-write-flag.js @@ -0,0 +1,26 @@ +// 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_NOFOLLOW, 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; +const noFollowFlag = !isWindows && typeof O_NOFOLLOW === 'number' ? + O_NOFOLLOW | O_TRUNC | O_CREAT | O_WRONLY + : null; +export const getWriteFlag = noFollowFlag !== null ? () => noFollowFlag + : !fMapEnabled ? () => 'w' + : (size) => (size < fMapLimit ? fMapFlag : 'w'); +//# sourceMappingURL=get-write-flag.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/header.js b/node_modules/tar/dist/esm/header.js new file mode 100644 index 0000000000000..fe8c09928e46c --- /dev/null +++ b/node_modules/tar/dist/esm/header.js @@ -0,0 +1,310 @@ +// 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'); + } + // Decode the typeflag (independent of any pending PAX/GNU extended header) + // up front so we can tell whether THIS block is itself an intermediary + // extension header (PAX `x`/`g`, GNU long-name `L`, GNU long-link `K`). + // Per POSIX pax, a PAX extended header describes the *next file entry*, not + // the extension headers that may sit between it and that file. Applying the + // pending PAX overrides (notably `size`) to an intervening `L`/`K`/`x`/`g` + // header desynchronizes the stream relative to other tar implementations + // and enables tar interpretation-conflict / file-smuggling attacks. + const t = decString(buf, off + 156, 1); + const isNormalFS = types.normalFsTypes.has(t); + const exForFields = isNormalFS ? ex : undefined; + const gexForFields = isNormalFS ? gex : undefined; + this.path = exForFields?.path ?? decString(buf, off, 100); + this.mode = + exForFields?.mode ?? + gexForFields?.mode ?? + decNumber(buf, off + 100, 8); + this.uid = + exForFields?.uid ?? gexForFields?.uid ?? decNumber(buf, off + 108, 8); + this.gid = + exForFields?.gid ?? gexForFields?.gid ?? decNumber(buf, off + 116, 8); + this.size = + exForFields?.size ?? + gexForFields?.size ?? + decNumber(buf, off + 124, 12); + this.mtime = + exForFields?.mtime ?? + gexForFields?.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. Never slurp the pending + // extended-header fields onto an intermediary extension header. + if (gexForFields) + this.#slurp(gexForFields, true); + if (exForFields) + this.#slurp(exForFields); + // old tar versions marked dirs as a file with a trailing / + 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') { + /* c8 ignore start */ + this.uname = + exForFields?.uname ?? + gexForFields?.uname ?? + decString(buf, off + 265, 32); + this.gname = + exForFields?.gname ?? + gexForFields?.gname ?? + decString(buf, off + 297, 32); + this.devmaj = + exForFields?.devmaj ?? + gexForFields?.devmaj ?? + decNumber(buf, off + 329, 8) ?? + 0; + this.devmin = + exForFields?.devmin ?? + gexForFields?.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; + } + /* c8 ignore start */ + this.atime = ex?.atime ?? gex?.atime ?? decDate(buf, off + 476, 12); + this.ctime = ex?.ctime ?? gex?.ctime ?? decDate(buf, off + 488, 12); + /* c8 ignore stop */ + } + } + 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] = Number(this.#type.codePointAt(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.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/index.js b/node_modules/tar/dist/esm/index.js new file mode 100644 index 0000000000000..1bac6415c8d73 --- /dev/null +++ b/node_modules/tar/dist/esm/index.js @@ -0,0 +1,20 @@ +export * 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 \ No newline at end of file diff --git a/node_modules/tar/dist/esm/index.min.js b/node_modules/tar/dist/esm/index.min.js new file mode 100644 index 0000000000000..57c1c7a4df9a8 --- /dev/null +++ b/node_modules/tar/dist/esm/index.min.js @@ -0,0 +1,4 @@ +var Mr=Object.defineProperty;var Br=(s,t)=>{for(var e in t)Mr(s,e,{get:t[e],enumerable:!0})};import $r from"events";import I from"fs";import{EventEmitter as Li}from"node:events";import As from"node:stream";import{StringDecoder as Pr}from"node:string_decoder";var xs=typeof process=="object"&&process?process:{stdout:null,stderr:null},zr=s=>!!s&&typeof s=="object"&&(s instanceof A||s instanceof As||Ur(s)||Hr(s)),Ur=s=>!!s&&typeof s=="object"&&s instanceof Li&&typeof s.pipe=="function"&&s.pipe!==As.Writable.prototype.pipe,Hr=s=>!!s&&typeof s=="object"&&s instanceof Li&&typeof s.write=="function"&&typeof s.end=="function",q=Symbol("EOF"),Q=Symbol("maybeEmitEnd"),rt=Symbol("emittedEnd"),Le=Symbol("emittingEnd"),qt=Symbol("emittedError"),Ne=Symbol("closed"),Ls=Symbol("read"),De=Symbol("flush"),Ns=Symbol("flushChunk"),z=Symbol("encoding"),Mt=Symbol("decoder"),g=Symbol("flowing"),Qt=Symbol("paused"),Bt=Symbol("resume"),b=Symbol("buffer"),D=Symbol("pipes"),_=Symbol("bufferLength"),gi=Symbol("bufferPush"),Ae=Symbol("bufferShift"),L=Symbol("objectMode"),w=Symbol("destroyed"),bi=Symbol("error"),_i=Symbol("emitData"),Ds=Symbol("emitEnd"),Oi=Symbol("emitEnd2"),Z=Symbol("async"),Ti=Symbol("abort"),Ie=Symbol("aborted"),Jt=Symbol("signal"),Rt=Symbol("dataListeners"),F=Symbol("discarded"),jt=s=>Promise.resolve().then(s),Wr=s=>s(),Gr=s=>s==="end"||s==="finish"||s==="prefinish",Zr=s=>s instanceof ArrayBuffer||!!s&&typeof s=="object"&&s.constructor&&s.constructor.name==="ArrayBuffer"&&s.byteLength>=0,Yr=s=>!Buffer.isBuffer(s)&&ArrayBuffer.isView(s),Fe=class{src;dest;opts;ondrain;constructor(t,e,i){this.src=t,this.dest=e,this.opts=i,this.ondrain=()=>t[Bt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},xi=class extends Fe{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,i){super(t,e,i),this.proxyErrors=r=>this.dest.emit("error",r),t.on("error",this.proxyErrors)}},Kr=s=>!!s.objectMode,Vr=s=>!s.objectMode&&!!s.encoding&&s.encoding!=="buffer",A=class extends Li{[g]=!1;[Qt]=!1;[D]=[];[b]=[];[L];[z];[Z];[Mt];[q]=!1;[rt]=!1;[Le]=!1;[Ne]=!1;[qt]=null;[_]=0;[w]=!1;[Jt];[Ie]=!1;[Rt]=0;[F]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Kr(e)?(this[L]=!0,this[z]=null):Vr(e)?(this[z]=e.encoding,this[L]=!1):(this[L]=!1,this[z]=null),this[Z]=!!e.async,this[Mt]=this[z]?new Pr(this[z]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[b]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[D]});let{signal:i}=e;i&&(this[Jt]=i,i.aborted?this[Ti]():i.addEventListener("abort",()=>this[Ti]()))}get bufferLength(){return this[_]}get encoding(){return this[z]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[L]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Z]}set async(t){this[Z]=this[Z]||!!t}[Ti](){this[Ie]=!0,this.emit("abort",this[Jt]?.reason),this.destroy(this[Jt]?.reason)}get aborted(){return this[Ie]}set aborted(t){}write(t,e,i){if(this[Ie])return!1;if(this[q])throw new Error("write after end");if(this[w])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(i=e,e="utf8"),e||(e="utf8");let r=this[Z]?jt:Wr;if(!this[L]&&!Buffer.isBuffer(t)){if(Yr(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Zr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[L]?(this[g]&&this[_]!==0&&this[De](!0),this[g]?this.emit("data",t):this[gi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):t.length?(typeof t=="string"&&!(e===this[z]&&!this[Mt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[z]&&(t=this[Mt].write(t)),this[g]&&this[_]!==0&&this[De](!0),this[g]?this.emit("data",t):this[gi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):(this[_]!==0&&this.emit("readable"),i&&r(i),this[g])}read(t){if(this[w])return null;if(this[F]=!1,this[_]===0||t===0||t&&t>this[_])return this[Q](),null;this[L]&&(t=null),this[b].length>1&&!this[L]&&(this[b]=[this[z]?this[b].join(""):Buffer.concat(this[b],this[_])]);let e=this[Ls](t||null,this[b][0]);return this[Q](),e}[Ls](t,e){if(this[L])this[Ae]();else{let i=e;t===i.length||t===null?this[Ae]():typeof i=="string"?(this[b][0]=i.slice(t),e=i.slice(0,t),this[_]-=t):(this[b][0]=i.subarray(t),e=i.subarray(0,t),this[_]-=t)}return this.emit("data",e),!this[b].length&&!this[q]&&this.emit("drain"),e}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e="utf8"),t!==void 0&&this.write(t,e),i&&this.once("end",i),this[q]=!0,this.writable=!1,(this[g]||!this[Qt])&&this[Q](),this}[Bt](){this[w]||(!this[Rt]&&!this[D].length&&(this[F]=!0),this[Qt]=!1,this[g]=!0,this.emit("resume"),this[b].length?this[De]():this[q]?this[Q]():this.emit("drain"))}resume(){return this[Bt]()}pause(){this[g]=!1,this[Qt]=!0,this[F]=!1}get destroyed(){return this[w]}get flowing(){return this[g]}get paused(){return this[Qt]}[gi](t){this[L]?this[_]+=1:this[_]+=t.length,this[b].push(t)}[Ae](){return this[L]?this[_]-=1:this[_]-=this[b][0].length,this[b].shift()}[De](t=!1){do;while(this[Ns](this[Ae]())&&this[b].length);!t&&!this[b].length&&!this[q]&&this.emit("drain")}[Ns](t){return this.emit("data",t),this[g]}pipe(t,e){if(this[w])return t;this[F]=!1;let i=this[rt];return e=e||{},t===xs.stdout||t===xs.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,i?e.end&&t.end():(this[D].push(e.proxyErrors?new xi(this,t,e):new Fe(this,t,e)),this[Z]?jt(()=>this[Bt]()):this[Bt]()),t}unpipe(t){let e=this[D].find(i=>i.dest===t);e&&(this[D].length===1?(this[g]&&this[Rt]===0&&(this[g]=!1),this[D]=[]):this[D].splice(this[D].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let i=super.on(t,e);if(t==="data")this[F]=!1,this[Rt]++,!this[D].length&&!this[g]&&this[Bt]();else if(t==="readable"&&this[_]!==0)super.emit("readable");else if(Gr(t)&&this[rt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[qt]){let r=e;this[Z]?jt(()=>r.call(this,this[qt])):r.call(this,this[qt])}return i}removeListener(t,e){return this.off(t,e)}off(t,e){let i=super.off(t,e);return t==="data"&&(this[Rt]=this.listeners("data").length,this[Rt]===0&&!this[F]&&!this[D].length&&(this[g]=!1)),i}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Rt]=0,!this[F]&&!this[D].length&&(this[g]=!1)),e}get emittedEnd(){return this[rt]}[Q](){!this[Le]&&!this[rt]&&!this[w]&&this[b].length===0&&this[q]&&(this[Le]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ne]&&this.emit("close"),this[Le]=!1)}emit(t,...e){let i=e[0];if(t!=="error"&&t!=="close"&&t!==w&&this[w])return!1;if(t==="data")return!this[L]&&!i?!1:this[Z]?(jt(()=>this[_i](i)),!0):this[_i](i);if(t==="end")return this[Ds]();if(t==="close"){if(this[Ne]=!0,!this[rt]&&!this[w])return!1;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[qt]=i,super.emit(bi,i);let n=!this[Jt]||this.listeners("error").length?super.emit("error",i):!1;return this[Q](),n}else if(t==="resume"){let n=super.emit("resume");return this[Q](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let r=super.emit(t,...e);return this[Q](),r}[_i](t){for(let i of this[D])i.dest.write(t)===!1&&this.pause();let e=this[F]?!1:super.emit("data",t);return this[Q](),e}[Ds](){return this[rt]?!1:(this[rt]=!0,this.readable=!1,this[Z]?(jt(()=>this[Oi]()),!0):this[Oi]())}[Oi](){if(this[Mt]){let e=this[Mt].end();if(e){for(let i of this[D])i.dest.write(e);this[F]||super.emit("data",e)}}for(let e of this[D])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[L]||(t.dataLength=0);let e=this.promise();return this.on("data",i=>{t.push(i),this[L]||(t.dataLength+=i.length)}),await e,t}async concat(){if(this[L])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[z]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(w,()=>e(new Error("stream destroyed"))),this.on("error",i=>e(i)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[F]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[q])return e();let n,o,a=d=>{this.off("data",h),this.off("end",l),this.off(w,c),e(),o(d)},h=d=>{this.off("error",a),this.off("end",l),this.off(w,c),this.pause(),n({value:d,done:!!this[q]})},l=()=>{this.off("error",a),this.off("data",h),this.off(w,c),e(),n({done:!0,value:void 0})},c=()=>a(new Error("stream destroyed"));return new Promise((d,S)=>{o=S,n=d,this.once(w,c),this.once("error",a),this.once("end",l),this.once("data",h)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[F]=!1;let t=!1,e=()=>(this.pause(),this.off(bi,e),this.off(w,e),this.off("end",e),t=!0,{done:!0,value:void 0}),i=()=>{if(t)return e();let r=this.read();return r===null?e():{done:!1,value:r}};return this.once("end",e),this.once(bi,e),this.once(w,e),{next:i,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[w])return t?this.emit("error",t):this.emit(w),this;this[w]=!0,this[F]=!0,this[b].length=0,this[_]=0;let e=this;return typeof e.close=="function"&&!this[Ne]&&e.close(),t?this.emit("error",t):this.emit(w),this}static get isStream(){return zr}};var Xr=I.writev,ot=Symbol("_autoClose"),H=Symbol("_close"),te=Symbol("_ended"),m=Symbol("_fd"),Ni=Symbol("_finished"),j=Symbol("_flags"),Di=Symbol("_flush"),Ci=Symbol("_handleChunk"),ki=Symbol("_makeBuf"),ie=Symbol("_mode"),Ce=Symbol("_needDrain"),Ut=Symbol("_onerror"),Ht=Symbol("_onopen"),Ai=Symbol("_onread"),Pt=Symbol("_onwrite"),ht=Symbol("_open"),U=Symbol("_path"),nt=Symbol("_pos"),Y=Symbol("_queue"),zt=Symbol("_read"),Ii=Symbol("_readSize"),J=Symbol("_reading"),ee=Symbol("_remain"),Fi=Symbol("_size"),ke=Symbol("_write"),gt=Symbol("_writing"),ve=Symbol("_defaultFlag"),bt=Symbol("_errored"),_t=class extends A{[bt]=!1;[m];[U];[Ii];[J]=!1;[Fi];[ee];[ot];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[bt]=!1,this[m]=typeof e.fd=="number"?e.fd:void 0,this[U]=t,this[Ii]=e.readSize||16*1024*1024,this[J]=!1,this[Fi]=typeof e.size=="number"?e.size:1/0,this[ee]=this[Fi],this[ot]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[m]=="number"?this[zt]():this[ht]()}get fd(){return this[m]}get path(){return this[U]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[ht](){I.open(this[U],"r",(t,e)=>this[Ht](t,e))}[Ht](t,e){t?this[Ut](t):(this[m]=e,this.emit("open",e),this[zt]())}[ki](){return Buffer.allocUnsafe(Math.min(this[Ii],this[ee]))}[zt](){if(!this[J]){this[J]=!0;let t=this[ki]();if(t.length===0)return process.nextTick(()=>this[Ai](null,0,t));I.read(this[m],t,0,t.length,null,(e,i,r)=>this[Ai](e,i,r))}}[Ai](t,e,i){this[J]=!1,t?this[Ut](t):this[Ci](e,i)&&this[zt]()}[H](){if(this[ot]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ut](t){this[J]=!0,this[H](),this.emit("error",t)}[Ci](t,e){let i=!1;return this[ee]-=t,t>0&&(i=super.write(tthis[Ht](t,e))}[Ht](t,e){this[ve]&&this[j]==="r+"&&t&&t.code==="ENOENT"?(this[j]="w",this[ht]()):t?this[Ut](t):(this[m]=e,this.emit("open",e),this[gt]||this[Di]())}end(t,e){return t&&this.write(t,e),this[te]=!0,!this[gt]&&!this[Y].length&&typeof this[m]=="number"&&this[Pt](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[te]?(this.emit("error",new Error("write() after end()")),!1):this[m]===void 0||this[gt]||this[Y].length?(this[Y].push(t),this[Ce]=!0,!1):(this[gt]=!0,this[ke](t),!0)}[ke](t){I.write(this[m],t,0,t.length,this[nt],(e,i)=>this[Pt](e,i))}[Pt](t,e){t?this[Ut](t):(this[nt]!==void 0&&typeof e=="number"&&(this[nt]+=e),this[Y].length?this[Di]():(this[gt]=!1,this[te]&&!this[Ni]?(this[Ni]=!0,this[H](),this.emit("finish")):this[Ce]&&(this[Ce]=!1,this.emit("drain"))))}[Di](){if(this[Y].length===0)this[te]&&this[Pt](null,0);else if(this[Y].length===1)this[ke](this[Y].pop());else{let t=this[Y];this[Y]=[],Xr(this[m],t,this[nt],(e,i)=>this[Pt](e,i))}}[H](){if(this[ot]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Wt=class extends tt{[ht](){let t;if(this[ve]&&this[j]==="r+")try{t=I.openSync(this[U],this[j],this[ie])}catch(e){if(e?.code==="ENOENT")return this[j]="w",this[ht]();throw e}else t=I.openSync(this[U],this[j],this[ie]);this[Ht](null,t)}[H](){if(this[ot]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}[ke](t){let e=!0;try{this[Pt](null,I.writeSync(this[m],t,0,t.length,this[nt])),e=!1}finally{if(e)try{this[H]()}catch{}}}};import hr from"node:path";import Kt from"node:fs";import{dirname as Nn,parse as Dn}from"path";var qr=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"]]),Is=s=>!!s.sync&&!!s.file,Fs=s=>!s.sync&&!!s.file,Cs=s=>!!s.sync&&!s.file,ks=s=>!s.sync&&!s.file;var vs=s=>!!s.file;var Qr=s=>{let t=qr.get(s);return t||s},se=(s={})=>{if(!s)return{};let t={};for(let[e,i]of Object.entries(s)){let r=Qr(e);t[r]=i}return t.chmod===void 0&&t.noChmod===!1&&(t.chmod=!0),delete t.noChmod,t};var K=(s,t,e,i,r)=>Object.assign((n=[],o,a)=>{Array.isArray(n)&&(o=n,n={}),typeof o=="function"&&(a=o,o=void 0),o=o?Array.from(o):[];let h=se(n);if(r?.(h,o),Is(h)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return s(h,o)}else if(Fs(h)){let l=t(h,o);return a?l.then(()=>a(),a):l}else if(Cs(h)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return e(h,o)}else if(ks(h)){if(typeof a=="function")throw new TypeError("callback only supported with file option");return i(h,o)}throw new Error("impossible options??")},{syncFile:s,asyncFile:t,syncNoFile:e,asyncNoFile:i,validate:r});import{EventEmitter as On}from"events";import Pi from"assert";import{Buffer as Ot}from"buffer";import*as Ms from"zlib";import Jr from"zlib";var jr=Jr.constants||{ZLIB_VERNUM:4736},M=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:1/0,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},jr));var tn=Ot.concat,Bs=Object.getOwnPropertyDescriptor(Ot,"concat"),en=s=>s,Mi=Bs?.writable===!0||Bs?.set!==void 0?s=>{Ot.concat=s?en:tn}:s=>{},Tt=Symbol("_superWrite"),Gt=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},Bi=Symbol("flushFlag"),re=class extends A{#t=!1;#i=!1;#s;#n;#r;#e;#o;get sawError(){return this.#t}get handle(){return this.#e}get flushFlag(){return this.#s}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#s=t.flush??0,this.#n=t.finishFlush??0,this.#r=t.fullFlushFlag??0,typeof Ms[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#e=new Ms[e](t)}catch(i){throw new Gt(i,this.constructor)}this.#o=i=>{this.#t||(this.#t=!0,this.close(),this.emit("error",i))},this.#e?.on("error",i=>this.#o(new Gt(i))),this.once("end",()=>this.close)}close(){this.#e&&(this.#e.close(),this.#e=void 0,this.emit("close"))}reset(){if(!this.#t)return Pi(this.#e,"zlib binding closed"),this.#e.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#r),this.write(Object.assign(Ot.alloc(0),{[Bi]:t})))}end(t,e,i){return typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#n),this.#i=!0,super.end(i)}get ended(){return this.#i}[Tt](t){return super.write(t)}write(t,e,i){if(typeof e=="function"&&(i=e,e="utf8"),typeof t=="string"&&(t=Ot.from(t,e)),this.#t)return;Pi(this.#e,"zlib binding closed");let r=this.#e._handle,n=r.close;r.close=()=>{};let o=this.#e.close;this.#e.close=()=>{},Mi(!0);let a;try{let l=typeof t[Bi]=="number"?t[Bi]:this.#s;a=this.#e._processChunk(t,l),Mi(!1)}catch(l){Mi(!1),this.#o(new Gt(l,this.write))}finally{this.#e&&(this.#e._handle=r,r.close=n,this.#e.close=o,this.#e.removeAllListeners("error"))}this.#e&&this.#e.on("error",l=>this.#o(new Gt(l,this.write)));let h;if(a)if(Array.isArray(a)&&a.length>0){let l=a[0];h=this[Tt](Ot.from(l));for(let c=1;c{typeof r=="function"&&(n=r,r=this.flushFlag),this.flush(r),n?.()};try{this.handle.params(t,e)}finally{this.handle.flush=i}this.handle&&(this.#t=t,this.#i=e)}}}};var Pe=class extends Be{#t;constructor(t){super(t,"Gzip"),this.#t=t&&!!t.portable}[Tt](t){return this.#t?(this.#t=!1,t[9]=255,super[Tt](t)):super[Tt](t)}};var ze=class extends Be{constructor(t){super(t,"Unzip")}},Ue=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||M.BROTLI_OPERATION_FINISH,t.fullFlushFlag=M.BROTLI_OPERATION_FLUSH,super(t,e)}},He=class extends Ue{constructor(t){super(t,"BrotliCompress")}},We=class extends Ue{constructor(t){super(t,"BrotliDecompress")}},Ge=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.ZSTD_e_continue,t.finishFlush=t.finishFlush||M.ZSTD_e_end,t.fullFlushFlag=M.ZSTD_e_flush,super(t,e)}},Ze=class extends Ge{constructor(t){super(t,"ZstdCompress")}},Ye=class extends Ge{constructor(t){super(t,"ZstdDecompress")}};import{posix as Zt}from"node:path";var Ps=(s,t)=>{if(Number.isSafeInteger(s))s<0?nn(s,t):rn(s,t);else throw Error("cannot encode number outside of javascript safe integer range");return t},rn=(s,t)=>{t[0]=128;for(var e=t.length;e>1;e--)t[e-1]=s&255,s=Math.floor(s/256)},nn=(s,t)=>{t[0]=255;var e=!1;s=s*-1;for(var i=t.length;i>1;i--){var r=s&255;s=Math.floor(s/256),e?t[i-1]=Us(r):r===0?t[i-1]=0:(e=!0,t[i-1]=Hs(r))}},zs=s=>{let t=s[0],e=t===128?hn(s.subarray(1,s.length)):t===255?on(s):null;if(e===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(e))throw Error("parsed number outside of javascript safe integer range");return e},on=s=>{for(var t=s.length,e=0,i=!1,r=t-1;r>-1;r--){var n=Number(s[r]),o;i?o=Us(n):n===0?o=n:(i=!0,o=Hs(n)),o!==0&&(e-=o*Math.pow(256,t-r-1))}return e},hn=s=>{for(var t=s.length,e=0,i=t-1;i>-1;i--){var r=Number(s[i]);r!==0&&(e+=r*Math.pow(256,t-i-1))}return e},Us=s=>(255^s)&255,Hs=s=>(255^s)+1&255;var Ui={};Br(Ui,{code:()=>Ke,isCode:()=>ne,isName:()=>ln,name:()=>oe,normalFsTypes:()=>zi});var ne=s=>oe.has(s),ln=s=>Ke.has(s),zi=new Set(["0","","1","2","3","4","5","6","7","D"]),oe=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),Ke=new Map(Array.from(oe).map(s=>[s[1],s[0]]));var C=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#t="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,i,r){Buffer.isBuffer(t)?this.decode(t,e||0,i,r):t&&this.#i(t)}decode(t,e,i,r){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=xt(t,e+156,1),o=zi.has(n),a=o?i:void 0,h=o?r:void 0;if(this.path=a?.path??xt(t,e,100),this.mode=a?.mode??h?.mode??at(t,e+100,8),this.uid=a?.uid??h?.uid??at(t,e+108,8),this.gid=a?.gid??h?.gid??at(t,e+116,8),this.size=a?.size??h?.size??at(t,e+124,12),this.mtime=a?.mtime??h?.mtime??Hi(t,e+136,12),this.cksum=at(t,e+148,12),h&&this.#i(h,!0),a&&this.#i(a),ne(n)&&(this.#t=n||"0"),this.#t==="0"&&this.path.slice(-1)==="/"&&(this.#t="5"),this.#t==="5"&&(this.size=0),this.linkpath=xt(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=a?.uname??h?.uname??xt(t,e+265,32),this.gname=a?.gname??h?.gname??xt(t,e+297,32),this.devmaj=a?.devmaj??h?.devmaj??at(t,e+329,8)??0,this.devmin=a?.devmin??h?.devmin??at(t,e+337,8)??0,t[e+475]!==0){let c=xt(t,e+345,155);this.path=c+"/"+this.path}else{let c=xt(t,e+345,130);c&&(this.path=c+"/"+this.path),this.atime=i?.atime??r?.atime??Hi(t,e+476,12),this.ctime=i?.ctime??r?.ctime??Hi(t,e+488,12)}let l=256;for(let c=e;c!(r==null||i==="path"&&e||i==="linkpath"&&e||i==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#t==="Unsupported"&&(this.#t="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let i=this.ctime||this.atime?130:155,r=cn(this.path||"",i),n=r[0],o=r[1];this.needPax=!!r[2],this.needPax=Lt(t,e,100,n)||this.needPax,this.needPax=lt(t,e+100,8,this.mode)||this.needPax,this.needPax=lt(t,e+108,8,this.uid)||this.needPax,this.needPax=lt(t,e+116,8,this.gid)||this.needPax,this.needPax=lt(t,e+124,12,this.size)||this.needPax,this.needPax=Wi(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#t.codePointAt(0)),this.needPax=Lt(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Lt(t,e+265,32,this.uname)||this.needPax,this.needPax=Lt(t,e+297,32,this.gname)||this.needPax,this.needPax=lt(t,e+329,8,this.devmaj)||this.needPax,this.needPax=lt(t,e+337,8,this.devmin)||this.needPax,this.needPax=Lt(t,e+345,i,o)||this.needPax,t[e+475]!==0?this.needPax=Lt(t,e+345,155,o)||this.needPax:(this.needPax=Lt(t,e+345,130,o)||this.needPax,this.needPax=Wi(t,e+476,12,this.atime)||this.needPax,this.needPax=Wi(t,e+488,12,this.ctime)||this.needPax);let a=256;for(let h=e;h{let i=s,r="",n,o=Zt.parse(s).root||".";if(Buffer.byteLength(i)<100)n=[i,r,!1];else{r=Zt.dirname(i),i=Zt.basename(i);do Buffer.byteLength(i)<=100&&Buffer.byteLength(r)<=t?n=[i,r,!1]:Buffer.byteLength(i)>100&&Buffer.byteLength(r)<=t?n=[i.slice(0,99),r,!0]:(i=Zt.join(Zt.basename(r),i),r=Zt.dirname(r));while(r!==o&&n===void 0);n||(n=[s.slice(0,99),"",!0])}return n},xt=(s,t,e)=>s.subarray(t,t+e).toString("utf8").replace(/\0.*/,""),Hi=(s,t,e)=>fn(at(s,t,e)),fn=s=>s===void 0?void 0:new Date(s*1e3),at=(s,t,e)=>Number(s[t])&128?zs(s.subarray(t,t+e)):un(s,t,e),dn=s=>isNaN(s)?void 0:s,un=(s,t,e)=>dn(parseInt(s.subarray(t,t+e).toString("utf8").replace(/\0.*$/,"").trim(),8)),mn={12:8589934591,8:2097151},lt=(s,t,e,i)=>i===void 0?!1:i>mn[e]||i<0?(Ps(i,s.subarray(t,t+e)),!0):(pn(s,t,e,i),!1),pn=(s,t,e,i)=>s.write(En(i,e),t,e,"ascii"),En=(s,t)=>wn(Math.floor(s).toString(8),t),wn=(s,t)=>(s.length===t-1?s:new Array(t-s.length-1).join("0")+s+" ")+"\0",Wi=(s,t,e,i)=>i===void 0?!1:lt(s,t,e,i.getTime()/1e3),Sn=new Array(156).join("\0"),Lt=(s,t,e,i)=>i===void 0?!1:(s.write(i+Sn,t,e,"utf8"),i.length!==Buffer.byteLength(i)||i.length>e);import{basename as yn}from"node:path";var ct=class s{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,e=!1){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=e,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let e=Buffer.byteLength(t),i=512*Math.ceil(1+e/512),r=Buffer.allocUnsafe(i);for(let n=0;n<512;n++)r[n]=0;new C({path:("PaxHeader/"+yn(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:e,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(r),r.write(t,512,e,"utf8");for(let n=e+512;n=Math.pow(10,o)&&(o+=1),o+n+r}static parse(t,e,i=!1){return new s(Rn(gn(t),e),i)}},Rn=(s,t)=>t?Object.assign({},t,s):s,gn=s=>s.replace(/\n$/,"").split(` +`).reduce(bn,Object.create(null)),bn=(s,t)=>{let e=parseInt(t,10);if(e!==Buffer.byteLength(t)+1)return s;t=t.slice((e+" ").length);let i=t.split("="),r=i.shift();if(!r)return s;let n=r.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=i.join("=");return s[n]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(n)?new Date(Number(o)*1e3):/^[0-9]+$/.test(o)?+o:o,s};var _n=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,f=_n!=="win32"?s=>s:s=>s&&s.replaceAll(/\\/g,"/");var Ve=class extends A{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,i){switch(super({}),this.pause(),this.extended=e,this.globalExtended=i,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,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=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=f(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?f(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#t(e),i&&this.#t(i,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let i=this.remain,r=this.blockRemain;return this.remain=Math.max(0,i-e),this.blockRemain=Math.max(0,r-e),this.ignore?!0:i>=e?super.write(t):super.write(t.subarray(0,i))}#t(t,e=!1){t.path&&(t.path=f(t.path)),t.linkpath&&(t.linkpath=f(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,r])=>!(r==null||i==="path"&&e))))}};var Nt=(s,t,e,i={})=>{s.file&&(i.file=s.file),s.cwd&&(i.cwd=s.cwd),i.code=e instanceof Error&&e.code||t,i.tarCode=t,!s.strict&&i.recoverable!==!1?(e instanceof Error&&(i=Object.assign(e,i),e=e.message),s.emit("warn",t,e,i)):e instanceof Error?s.emit("error",Object.assign(e,i)):s.emit("error",Object.assign(new Error(`${t}: ${e}`),i))};var Tn=1024*1024,Vi=Buffer.from([31,139]),$i=Buffer.from([40,181,47,253]),xn=Math.max(Vi.length,$i.length),B=Symbol("state"),Dt=Symbol("writeEntry"),et=Symbol("readEntry"),Gi=Symbol("nextEntry"),Ws=Symbol("processEntry"),V=Symbol("extendedHeader"),he=Symbol("globalExtendedHeader"),ft=Symbol("meta"),Gs=Symbol("emitMeta"),p=Symbol("buffer"),it=Symbol("queue"),dt=Symbol("ended"),Zi=Symbol("emittedEnd"),At=Symbol("emit"),y=Symbol("unzip"),$e=Symbol("consumeChunk"),Xe=Symbol("consumeChunkSub"),Yi=Symbol("consumeBody"),Zs=Symbol("consumeMeta"),Ys=Symbol("consumeHeader"),ae=Symbol("consuming"),Ki=Symbol("bufferConcat"),qe=Symbol("maybeEnd"),Yt=Symbol("writing"),ut=Symbol("aborted"),Qe=Symbol("onDone"),It=Symbol("sawValidEntry"),Je=Symbol("sawNullBlock"),je=Symbol("sawEOF"),Ks=Symbol("closeStream"),Ln=()=>!0,st=class extends On{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[it]=[];[p];[et];[Dt];[B]="begin";[ft]="";[V];[he];[dt]=!1;[y];[ut]=!1;[It];[Je]=!1;[je]=!1;[Yt]=!1;[ae]=!1;[Zi]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Qe,()=>{(this[B]==="begin"||this[It]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Qe,t.ondone):this.on(Qe,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Tn,this.filter=typeof t.filter=="function"?t.filter:Ln;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let i=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:i?!0:void 0,this.on("end",()=>this[Ks]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,i={}){Nt(this,t,e,i)}[Ys](t,e){this[It]===void 0&&(this[It]=!1);let i;try{i=new C(t,e,this[V],this[he])}catch(r){return this.warn("TAR_ENTRY_INVALID",r)}if(i.nullBlock)this[Je]?(this[je]=!0,this[B]==="begin"&&(this[B]="header"),this[At]("eof")):(this[Je]=!0,this[At]("nullBlock"));else if(this[Je]=!1,!i.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:i});else if(!i.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:i});else{let r=i.type;if(/^(Symbolic)?Link$/.test(r)&&!i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:i});else if(!/^(Symbolic)?Link$/.test(r)&&!/^(Global)?ExtendedHeader$/.test(r)&&i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:i});else{let n=this[Dt]=new Ve(i,this[V],this[he]);if(!this[It])if(n.remain){let o=()=>{n.invalid||(this[It]=!0)};n.on("end",o)}else this[It]=!0;n.meta?n.size>this.maxMetaEntrySize?(n.ignore=!0,this[At]("ignoredEntry",n),this[B]="ignore",n.resume()):n.size>0&&(this[ft]="",n.on("data",o=>this[ft]+=o),this[B]="meta"):(this[V]=void 0,n.ignore=n.ignore||!this.filter(n.path,n),n.ignore?(this[At]("ignoredEntry",n),this[B]=n.remain?"ignore":"header",n.resume()):(n.remain?this[B]="body":(this[B]="header",n.end()),this[et]?this[it].push(n):(this[it].push(n),this[Gi]())))}}}[Ks](){queueMicrotask(()=>this.emit("close"))}[Ws](t){let e=!0;if(!t)this[et]=void 0,e=!1;else if(Array.isArray(t)){let[i,...r]=t;this.emit(i,...r)}else this[et]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Gi]()),e=!1);return e}[Gi](){do;while(this[Ws](this[it].shift()));if(this[it].length===0){let t=this[et];!t||t.flowing||t.size===t.remain?this[Yt]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Yi](t,e){let i=this[Dt];if(!i)throw new Error("attempt to consume body without entry??");let r=i.blockRemain??0,n=r>=t.length&&e===0?t:t.subarray(e,e+r);return i.write(n),i.blockRemain||(this[B]="header",this[Dt]=void 0,i.end()),n.length}[Zs](t,e){let i=this[Dt],r=this[Yi](t,e);return!this[Dt]&&i&&this[Gs](i),r}[At](t,e,i){this[it].length===0&&!this[et]?this.emit(t,e,i):this[it].push([t,e,i])}[Gs](t){switch(this[At]("meta",this[ft]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[V]=ct.parse(this[ft],this[V],!1);break;case"GlobalExtendedHeader":this[he]=ct.parse(this[ft],this[he],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[V]??Object.create(null);this[V]=e,e.path=this[ft].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[V]||Object.create(null);this[V]=e,e.linkpath=this[ft].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[ut]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,i){if(typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[ut])return i?.(),!1;if((this[y]===void 0||this.brotli===void 0&&this[y]===!1)&&t){if(this[p]&&(t=Buffer.concat([this[p],t]),this[p]=void 0),t.lengththis[$e](c)),this[y].on("error",c=>this.abort(c)),this[y].on("end",()=>{this[dt]=!0,this[$e]()}),this[Yt]=!0;let l=!!this[y][h?"end":"write"](t);return this[Yt]=!1,i?.(),l}}this[Yt]=!0,this[y]?this[y].write(t):this[$e](t),this[Yt]=!1;let n=this[it].length>0?!1:this[et]?this[et].flowing:!0;return!n&&this[it].length===0&&this[et]?.once("drain",()=>this.emit("drain")),i?.(),n}[Ki](t){t&&!this[ut]&&(this[p]=this[p]?Buffer.concat([this[p],t]):t)}[qe](){if(this[dt]&&!this[Zi]&&!this[ut]&&!this[ae]){this[Zi]=!0;let t=this[Dt];if(t&&t.blockRemain){let e=this[p]?this[p].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[p]&&t.write(this[p]),t.end()}this[At](Qe)}}[$e](t){if(this[ae]&&t)this[Ki](t);else if(!t&&!this[p])this[qe]();else if(t){if(this[ae]=!0,this[p]){this[Ki](t);let e=this[p];this[p]=void 0,this[Xe](e)}else this[Xe](t);for(;this[p]&&this[p]?.length>=512&&!this[ut]&&!this[je];){let e=this[p];this[p]=void 0,this[Xe](e)}this[ae]=!1}(!this[p]||this[dt])&&this[qe]()}[Xe](t){let e=0,i=t.length;for(;e+512<=i&&!this[ut]&&!this[je];)switch(this[B]){case"begin":case"header":this[Ys](t,e),e+=512;break;case"ignore":case"body":e+=this[Yi](t,e);break;case"meta":e+=this[Zs](t,e);break;default:throw new Error("invalid state: "+this[B])}e{let t=s.length-1,e=-1;for(;t>-1&&s.charAt(t)==="/";)e=t,t--;return e===-1?s:s.slice(0,e)};var An=s=>{let t=s.onReadEntry;s.onReadEntry=t?e=>{t(e),e.resume()}:e=>e.resume()},Xi=(s,t)=>{let e=new Map(t.map(n=>[mt(n),!0])),i=s.filter,r=(n,o="")=>{let a=o||Dn(n).root||".",h;if(n===a)h=!1;else{let l=e.get(n);h=l!==void 0?l:r(Nn(n),a)}return e.set(n,h),h};s.filter=i?(n,o)=>i(n,o)&&r(mt(n)):n=>r(mt(n))},In=s=>{let t=new st(s),e=s.file,i;try{i=Kt.openSync(e,"r");let r=Kt.fstatSync(i),n=s.maxReadSize||16*1024*1024;if(r.size{let e=new st(s),i=s.maxReadSize||16*1024*1024,r=s.file;return new Promise((o,a)=>{e.on("error",a),e.on("end",o),Kt.stat(r,(h,l)=>{if(h)a(h);else{let c=new _t(r,{readSize:i,size:l.size});c.on("error",a),c.pipe(e)}})})},Ft=K(In,Fn,s=>new st(s),s=>new st(s),(s,t)=>{t?.length&&Xi(s,t),s.noResume||An(s)});import ui from"fs";import $ from"fs";import qs from"path";var qi=(s,t,e)=>(s&=4095,e&&(s=(s|384)&-19),t&&(s&256&&(s|=64),s&32&&(s|=8),s&4&&(s|=1)),s);import{win32 as Cn}from"node:path";var{isAbsolute:kn,parse:Vs}=Cn,le=s=>{let t="",e=Vs(s);for(;kn(s)||e.root;){let i=s.charAt(0)==="/"&&s.slice(0,4)!=="//?/"?"/":e.root;s=s.slice(i.length),t+=i,e=Vs(s)}return[t,s]};var ti=["|","<",">","?",":"],Qi=ti.map(s=>String.fromCodePoint(61440+Number(s.codePointAt(0)))),vn=new Map(ti.map((s,t)=>[s,Qi[t]])),Mn=new Map(Qi.map((s,t)=>[s,ti[t]])),Ji=s=>ti.reduce((t,e)=>t.split(e).join(vn.get(e)),s),$s=s=>Qi.reduce((t,e)=>t.split(e).join(Mn.get(e)),s);var er=(s,t)=>t?(s=f(s).replace(/^\.(\/|$)/,""),mt(t)+"/"+s):f(s),Bn=16*1024*1024,Qs=Symbol("process"),Js=Symbol("file"),js=Symbol("directory"),ts=Symbol("symlink"),tr=Symbol("hardlink"),ce=Symbol("header"),ei=Symbol("read"),es=Symbol("lstat"),ii=Symbol("onlstat"),is=Symbol("onread"),ss=Symbol("onreadlink"),rs=Symbol("openfile"),ns=Symbol("onopenfile"),pt=Symbol("close"),si=Symbol("mode"),os=Symbol("awaitDrain"),ji=Symbol("ondrain"),X=Symbol("prefix"),fe=class extends A{path;portable;myuid=process.getuid&&process.getuid()||0;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;#t=!1;constructor(t,e={}){let i=se(e);super(),this.path=f(t),this.portable=!!i.portable,this.maxReadSize=i.maxReadSize||Bn,this.linkCache=i.linkCache||new Map,this.statCache=i.statCache||new Map,this.preservePaths=!!i.preservePaths,this.cwd=f(i.cwd||process.cwd()),this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.mtime=i.mtime,this.prefix=i.prefix?f(i.prefix):void 0,this.onWriteEntry=i.onWriteEntry,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let r=!1;if(!this.preservePaths){let[o,a]=le(this.path);o&&typeof a=="string"&&(this.path=a,r=o)}this.win32=!!i.win32||process.platform==="win32",this.win32&&(this.path=$s(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=f(i.absolute||qs.resolve(this.cwd,t)),this.path===""&&(this.path="./"),r&&this.warn("TAR_ENTRY_INFO",`stripping ${r} from absolute path`,{entry:this,path:r+this.path});let n=this.statCache.get(this.absolute);n?this[ii](n):this[es]()}warn(t,e,i={}){return Nt(this,t,e,i)}emit(t,...e){return t==="error"&&(this.#t=!0),super.emit(t,...e)}[es](){$.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[ii](e)})}[ii](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Pn(t),this.emit("stat",t),this[Qs]()}[Qs](){switch(this.type){case"File":return this[Js]();case"Directory":return this[js]();case"SymbolicLink":return this[ts]();default:return this.end()}}[si](t){return qi(t,this.type==="Directory",this.portable)}[X](t){return er(t,this.prefix)}[ce](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new C({path:this[X](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[X](this.linkpath):this.linkpath,mode:this[si](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new ct({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[X](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[X](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[js](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[ce](),this.end()}[ts](){$.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[ss](e)})}[ss](t){this.linkpath=f(t),this[ce](),this.end()}[tr](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=f(qs.relative(this.cwd,t)),this.stat.size=0,this[ce](),this.end()}[Js](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[tr](e);this.linkCache.set(t,this.absolute)}if(this[ce](),this.stat.size===0)return this.end();this[rs]()}[rs](){$.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[ns](e)})}[ns](t){if(this.fd=t,this.#t)return this[pt]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[ei]()}[ei](){let{fd:t,buf:e,offset:i,length:r,pos:n}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");$.read(t,e,i,r,n,(o,a)=>{if(o)return this[pt](()=>this.emit("error",o));this[is](a)})}[pt](t=()=>{}){this.fd!==void 0&&$.close(this.fd,t)}[is](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[pt](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[pt](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;rthis[ji]())}[os](t){this.once("drain",t)}write(t,e,i){if(typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemaint?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[ei]()}},ri=class extends fe{sync=!0;[es](){this[ii]($.lstatSync(this.absolute))}[ts](){this[ss]($.readlinkSync(this.absolute))}[rs](){this[ns]($.openSync(this.absolute,"r"))}[ei](){let t=!0;try{let{fd:e,buf:i,offset:r,length:n,pos:o}=this;if(e===void 0||i===void 0)throw new Error("fd and buf must be set in READ method");let a=$.readSync(e,i,r,n,o);this[is](a),t=!1}finally{if(t)try{this[pt](()=>{})}catch{}}}[os](t){t()}[pt](t=()=>{}){this.fd!==void 0&&$.closeSync(this.fd),t()}},ni=class extends A{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(t,e,i={}){return Nt(this,t,e,i)}constructor(t,e={}){let i=se(e);super(),this.preservePaths=!!i.preservePaths,this.portable=!!i.portable,this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.onWriteEntry=i.onWriteEntry,this.readEntry=t;let{type:r}=t;if(r==="Unsupported")throw new Error("writing entry that should be ignored");this.type=r,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=i.prefix,this.path=f(t.path),this.mode=t.mode!==void 0?this[si](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:i.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?f(t.linkpath):void 0,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let n=!1;if(!this.preservePaths){let[a,h]=le(this.path);a&&typeof h=="string"&&(this.path=h,n=a)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new C({path:this[X](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[X](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path}),this.header.encode()&&!this.noPax&&super.write(new ct({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[X](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[X](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),t.pipe(this)}[X](t){return er(t,this.prefix)}[si](t){return qi(t,this.type==="Directory",this.portable)}write(t,e,i){typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let r=t.length;if(r>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=r,super.write(t,i)}end(t,e,i){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),i&&this.once("finish",i),t?super.end(t,i):super.end(i),this}},Pn=s=>s.isFile()?"File":s.isDirectory()?"Directory":s.isSymbolicLink()?"SymbolicLink":"Unsupported";var oi=class s{tail;head;length=0;static create(t=[]){return new s(t)}constructor(t=[]){for(let e of t)this.push(e)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let e=t.next,i=t.prev;return e&&(e.prev=i),i&&(i.next=e),t===this.head&&(this.head=e),t===this.tail&&(this.tail=i),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,e}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let e=this.head;t.list=this,t.next=e,e&&(e.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let e=this.tail;t.list=this,t.prev=e,e&&(e.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let e=0,i=t.length;e1)i=e;else if(this.head)r=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=0;r;n++)i=t(i,r.value,n),r=r.next;return i}reduceReverse(t,e){let i,r=this.tail;if(arguments.length>1)i=e;else if(this.tail)r=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let n=this.length-1;r;n--)i=t(i,r.value,n),r=r.prev;return i}toArray(){let t=new Array(this.length);for(let e=0,i=this.head;i;e++)t[e]=i.value,i=i.next;return t}toArrayReverse(){let t=new Array(this.length);for(let e=0,i=this.tail;i;e++)t[e]=i.value,i=i.prev;return t}slice(t=0,e=this.length){e<0&&(e+=this.length),t<0&&(t+=this.length);let i=new s;if(ethis.length&&(e=this.length);let r=this.head,n=0;for(n=0;r&&nthis.length&&(e=this.length);let r=this.length,n=this.tail;for(;n&&r>e;r--)n=n.prev;for(;n&&r>t;r--,n=n.prev)i.push(n.value);return i}splice(t,e=0,...i){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let r=this.head;for(let o=0;r&&o1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new Pe(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new He(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Ze(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",i=>super.write(i)),e.on("end",()=>super.end()),e.on("drain",()=>this[ls]()),this.on("resume",()=>e.resume())}else this.on("drain",this[ls]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[W]=new oi,this[G]=0,this.jobs=Number(t.jobs)||4,this[pe]=!1,this[ue]=!1}[or](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e=void 0),t&&this.add(t),this[ue]=!0,this[Ct](),i&&i(),this}write(t){if(this[ue])throw new Error("write after end");return typeof t=="string"?this[li](t):this[sr](t),this.flowing}[sr](t){let e=f(nr.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let i=new mi(t.path,e);i.entry=new ni(t,this[as](i)),i.entry.on("end",()=>this[hs](i)),this[G]+=1,this[W].push(i)}this[Ct]()}[li](t){let e=f(nr.resolve(this.cwd,t));this[W].push(new mi(t,e)),this[Ct]()}[cs](t){t.pending=!0,this[G]+=1;let e=this.follow?"stat":"lstat";ui[e](t.absolute,(i,r)=>{t.pending=!1,this[G]-=1,i?this.emit("error",i):this[ai](t,r)})}[ai](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[Et])this[hi](t);else{let i=`${e.dev}:${e.ino}`,r=this[me].get(i);r?r.push(t):this[me].set(i,[t]),t.pendingLink=!0,t.pending=!0}this[Ct]()}[fs](t){t.pending=!0,this[G]+=1,ui.readdir(t.absolute,(e,i)=>{if(t.pending=!1,this[G]-=1,e)return this.emit("error",e);this[ci](t,i)})}[ci](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Ct]()}[Ct](){if(!this[pe]){this[pe]=!0;for(let t=this[W].head;t&&this[G]1){let i=`${e.dev}:${e.ino}`,r=this[me].get(i);if(r){this[me].delete(i);for(let n of r)n.pending=!1,this[hi](n)}}this[Ct]()}[hi](t){if(t.pending&&t.pendingLink&&t===this[Et]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[Et]&&!t.piped&&this[fi](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[ai](t,e):this[cs](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[ci](t,e):this[fs](t),!t.readdir)return}if(t.entry=this[rr](t),!t.entry){t.ignore=!0;return}t===this[Et]&&!t.piped&&this[fi](t)}}}[as](t){return{onwarn:(e,i,r)=>this.warn(e,i,r),noPax:this.noPax,cwd:this.cwd,absolute:t.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}}[rr](t){this[G]+=1;try{return new this[di](t.path,this[as](t)).on("end",()=>this[hs](t)).on("error",i=>this.emit("error",i))}catch(e){this.emit("error",e)}}[ls](){this[Et]&&this[Et].entry&&this[Et].entry.resume()}[fi](t){t.piped=!0,t.readdir&&t.readdir.forEach(r=>{let n=t.path,o=n==="./"?"":n.replace(/\/*$/,"/");this[li](o+r)});let e=t.entry,i=this.zip;if(!e)throw new Error("cannot pipe without source");i?e.on("data",r=>{i.write(r)||e.pause()}):e.on("data",r=>{super.write(r)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,i={}){Nt(this,t,e,i)}},kt=class extends wt{sync=!0;constructor(t){super(t),this[di]=ri}pause(){}resume(){}[cs](t){let e=this.follow?"statSync":"lstatSync";this[ai](t,ui[e](t.absolute))}[fs](t){this[ci](t,ui.readdirSync(t.absolute))}[fi](t){let e=t.entry,i=this.zip;if(t.readdir&&t.readdir.forEach(r=>{let n=t.path,o=n==="./"?"":n.replace(/\/*$/,"/");this[li](o+r)}),!e)throw new Error("Cannot pipe without source");i?e.on("data",r=>{i.write(r)}):e.on("data",r=>{super[or](r)})}};var Wn=(s,t)=>{let e=new kt(s),i=new Wt(s.file,{mode:s.mode||438});e.pipe(i),ar(e,t)},Gn=(s,t)=>{let e=new wt(s),i=new tt(s.file,{mode:s.mode||438});e.pipe(i);let r=new Promise((n,o)=>{i.on("error",o),i.on("close",n),e.on("error",o)});return lr(e,t).catch(n=>e.emit("error",n)),r},ar=(s,t)=>{t.forEach(e=>{e.charAt(0)==="@"?Ft({file:hr.resolve(s.cwd,e.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>s.add(i)}):s.add(e)}),s.end()},lr=async(s,t)=>{for(let e of t)e.charAt(0)==="@"?await Ft({file:hr.resolve(String(s.cwd),e.slice(1)),noResume:!0,onReadEntry:i=>{s.add(i)}}):s.add(e);s.end()},Zn=(s,t)=>{let e=new kt(s);return ar(e,t),e},Yn=(s,t)=>{let e=new wt(s);return lr(e,t).catch(i=>e.emit("error",i)),e},Kn=K(Wn,Gn,Zn,Yn,(s,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")});import kr from"node:fs";import no from"node:assert";import{randomBytes as Cr}from"node:crypto";import u from"node:fs";import R from"node:path";import dr from"fs";var Vn=process.env.__FAKE_PLATFORM__||process.platform,ur=Vn==="win32",{O_CREAT:mr,O_NOFOLLOW:cr,O_TRUNC:pr,O_WRONLY:Er}=dr.constants,wr=Number(process.env.__FAKE_FS_O_FILENAME__)||dr.constants.UV_FS_O_FILEMAP||0,$n=ur&&!!wr,Xn=512*1024,qn=wr|pr|mr|Er,fr=!ur&&typeof cr=="number"?cr|pr|mr|Er:null,ds=fr!==null?()=>fr:$n?s=>s"w";import Ei from"node:fs";import Ee from"node:path";var us=(s,t,e)=>{try{return Ei.lchownSync(s,t,e)}catch(i){if(i?.code!=="ENOENT")throw i}},pi=(s,t,e,i)=>{Ei.lchown(s,t,e,r=>{i(r&&r?.code!=="ENOENT"?r:null)})},Qn=(s,t,e,i,r)=>{if(t.isDirectory())ms(Ee.resolve(s,t.name),e,i,n=>{if(n)return r(n);let o=Ee.resolve(s,t.name);pi(o,e,i,r)});else{let n=Ee.resolve(s,t.name);pi(n,e,i,r)}},ms=(s,t,e,i)=>{Ei.readdir(s,{withFileTypes:!0},(r,n)=>{if(r){if(r.code==="ENOENT")return i();if(r.code!=="ENOTDIR"&&r.code!=="ENOTSUP")return i(r)}if(r||!n.length)return pi(s,t,e,i);let o=n.length,a=null,h=l=>{if(!a){if(l)return i(a=l);if(--o===0)return pi(s,t,e,i)}};for(let l of n)Qn(s,l,t,e,h)})},Jn=(s,t,e,i)=>{t.isDirectory()&&ps(Ee.resolve(s,t.name),e,i),us(Ee.resolve(s,t.name),e,i)},ps=(s,t,e)=>{let i;try{i=Ei.readdirSync(s,{withFileTypes:!0})}catch(r){let n=r;if(n?.code==="ENOENT")return;if(n?.code==="ENOTDIR"||n?.code==="ENOTSUP")return us(s,t,e);throw n}for(let r of i)Jn(s,r,t,e);return us(s,t,e)};import k from"node:fs";import jn from"node:fs/promises";import wi from"node:path";var we=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}};var St=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}};var to=(s,t)=>{k.stat(s,(e,i)=>{(e||!i.isDirectory())&&(e=new we(s,e?.code||"ENOTDIR")),t(e)})},Sr=(s,t,e)=>{s=f(s);let i=t.umask??18,r=t.mode|448,n=(r&i)!==0,o=t.uid,a=t.gid,h=typeof o=="number"&&typeof a=="number"&&(o!==t.processUid||a!==t.processGid),l=t.preserve,c=t.unlink,d=f(t.cwd),S=(E,x)=>{E?e(E):x&&h?ms(x,o,a,xe=>S(xe)):n?k.chmod(s,r,e):e()};if(s===d)return to(s,S);if(l)return jn.mkdir(s,{mode:r,recursive:!0}).then(E=>S(null,E??void 0),S);let N=f(wi.relative(d,s)).split("/");Es(d,N,r,c,d,void 0,S)},Es=(s,t,e,i,r,n,o)=>{if(t.length===0)return o(null,n);let a=t.shift(),h=f(wi.resolve(s+"/"+a));k.mkdir(h,e,yr(h,t,e,i,r,n,o))},yr=(s,t,e,i,r,n,o)=>a=>{a?k.lstat(s,(h,l)=>{if(h)h.path=h.path&&f(h.path),o(h);else if(l.isDirectory())Es(s,t,e,i,r,n,o);else if(i)k.unlink(s,c=>{if(c)return o(c);k.mkdir(s,e,yr(s,t,e,i,r,n,o))});else{if(l.isSymbolicLink())return o(new St(s,s+"/"+t.join("/")));o(a)}}):(n=n||s,Es(s,t,e,i,r,n,o))},eo=s=>{let t=!1,e;try{t=k.statSync(s).isDirectory()}catch(i){e=i?.code}finally{if(!t)throw new we(s,e??"ENOTDIR")}},Rr=(s,t)=>{s=f(s);let e=t.umask??18,i=t.mode|448,r=(i&e)!==0,n=t.uid,o=t.gid,a=typeof n=="number"&&typeof o=="number"&&(n!==t.processUid||o!==t.processGid),h=t.preserve,l=t.unlink,c=f(t.cwd),d=E=>{E&&a&&ps(E,n,o),r&&k.chmodSync(s,i)};if(s===c)return eo(c),d();if(h)return d(k.mkdirSync(s,{mode:i,recursive:!0})??void 0);let T=f(wi.relative(c,s)).split("/"),N;for(let E=T.shift(),x=c;E&&(x+="/"+E);E=T.shift()){x=f(wi.resolve(x));try{k.mkdirSync(x,i),N=N||x}catch{let xe=k.lstatSync(x);if(xe.isDirectory())continue;if(l){k.unlinkSync(x),k.mkdirSync(x,i),N=N||x;continue}else if(xe.isSymbolicLink())return new St(x,x+"/"+T.join("/"))}}return d(N)};import{join as _r}from"node:path";var ws=Object.create(null),gr=1e4,Vt=new Set,br=s=>{Vt.has(s)?Vt.delete(s):ws[s]=s.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Vt.add(s);let t=ws[s],e=Vt.size-gr;if(e>gr/10){for(let i of Vt)if(Vt.delete(i),delete ws[i],--e<=0)break}return t};var io=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,so=io==="win32",ro=s=>s.split("/").slice(0,-1).reduce((e,i)=>{let r=e.at(-1);return r!==void 0&&(i=_r(r,i)),e.push(i||"/"),e},[]),Si=class{#t=new Map;#i=new Map;#s=new Set;reserve(t,e){t=so?["win32 parallelization disabled"]:t.map(r=>mt(_r(br(r))));let i=new Set(t.map(r=>ro(r)).reduce((r,n)=>r.concat(n)));this.#i.set(e,{dirs:i,paths:t});for(let r of t){let n=this.#t.get(r);n?n.push(e):this.#t.set(r,[e])}for(let r of i){let n=this.#t.get(r);if(!n)this.#t.set(r,[new Set([e])]);else{let o=n.at(-1);o instanceof Set?o.add(e):n.push(new Set([e]))}}return this.#r(e)}#n(t){let e=this.#i.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(i=>this.#t.get(i)),dirs:[...e.dirs].map(i=>this.#t.get(i))}}check(t){let{paths:e,dirs:i}=this.#n(t);return e.every(r=>r&&r[0]===t)&&i.every(r=>r&&r[0]instanceof Set&&r[0].has(t))}#r(t){return this.#s.has(t)||!this.check(t)?!1:(this.#s.add(t),t(()=>this.#e(t)),!0)}#e(t){if(!this.#s.has(t))return!1;let e=this.#i.get(t);if(!e)throw new Error("invalid reservation");let{paths:i,dirs:r}=e,n=new Set;for(let o of i){let a=this.#t.get(o);if(!a||a?.[0]!==t)continue;let h=a[1];if(!h){this.#t.delete(o);continue}if(a.shift(),typeof h=="function")n.add(h);else for(let l of h)n.add(l)}for(let o of r){let a=this.#t.get(o),h=a?.[0];if(!(!a||!(h instanceof Set)))if(h.size===1&&a.length===1){this.#t.delete(o);continue}else if(h.size===1){a.shift();let l=a[0];typeof l=="function"&&n.add(l)}else h.delete(t)}return this.#s.delete(t),n.forEach(o=>this.#r(o)),!0}};var Or=()=>process.umask();var Tr=Symbol("onEntry"),gs=Symbol("checkFs"),xr=Symbol("checkFs2"),bs=Symbol("isReusable"),P=Symbol("makeFs"),_s=Symbol("file"),Os=Symbol("directory"),Ri=Symbol("link"),Lr=Symbol("symlink"),Nr=Symbol("hardlink"),ye=Symbol("ensureNoSymlink"),Dr=Symbol("unsupported"),Ar=Symbol("checkPath"),Ss=Symbol("stripAbsolutePath"),yt=Symbol("mkdir"),O=Symbol("onError"),yi=Symbol("pending"),Ir=Symbol("pend"),$t=Symbol("unpend"),ys=Symbol("ended"),Rs=Symbol("maybeClose"),Ts=Symbol("skip"),Re=Symbol("doChown"),ge=Symbol("uid"),be=Symbol("gid"),_e=Symbol("checkedCwd"),oo=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Oe=oo==="win32",ho=1024,ao=(s,t)=>{if(!Oe)return u.unlink(s,t);let e=s+".DELETE."+Cr(16).toString("hex");u.rename(s,e,i=>{if(i)return t(i);u.unlink(e,t)})},lo=s=>{if(!Oe)return u.unlinkSync(s);let t=s+".DELETE."+Cr(16).toString("hex");u.renameSync(s,t),u.unlinkSync(t)},Fr=(s,t,e)=>s!==void 0&&s===s>>>0?s:t!==void 0&&t===t>>>0?t:e,Xt=class extends st{[ys]=!1;[_e]=!1;[yi]=0;reservations=new Si;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[ys]=!0,this[Rs]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&process.getuid()===0):!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:ho,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Oe,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=f(R.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:Or():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Tr](e))}warn(t,e,i={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(i.recoverable=!1),super.warn(t,e,i)}[Rs](){this[ys]&&this[yi]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Ss](t,e){let i=t[e],{type:r}=t;if(!i||this.preservePaths)return!0;let[n,o]=le(i),a=o.replaceAll(/\\/g,"/").split("/");if(a.includes("..")||Oe&&/^[a-z]:\.\.$/i.test(a[0]??"")){if(e==="path"||r==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:i}),!1;let h=R.posix.dirname(t.path),l=R.posix.normalize(R.posix.join(h,a.join("/")));if(l.startsWith("../")||l==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:i}),!1}return n&&(t[e]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute ${e}`,{entry:t,[e]:i})),!0}[Ar](t){let e=f(t.path),i=e.split("/");if(this.strip){if(i.length=this.strip)t.linkpath=r.slice(this.strip).join("/");else return!1}i.splice(0,this.strip),t.path=i.join("/")}if(isFinite(this.maxDepth)&&i.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:i.length,maxDepth:this.maxDepth}),!1;if(!this[Ss](t,"path")||!this[Ss](t,"linkpath"))return!1;if(t.absolute=R.isAbsolute(t.path)?f(R.resolve(t.path)):f(R.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:f(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:r}=R.win32.parse(String(t.absolute));t.absolute=r+Ji(String(t.absolute).slice(r.length));let{root:n}=R.win32.parse(t.path);t.path=n+Ji(t.path.slice(n.length))}return!0}[Tr](t){if(!this[Ar](t))return t.resume();switch(no.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[gs](t);default:return this[Dr](t)}}[O](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[$t](),e.resume())}[yt](t,e,i){Sr(f(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},i)}[Re](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[ge](t){return Fr(this.uid,t.uid,this.processUid)}[be](t){return Fr(this.gid,t.gid,this.processGid)}[_s](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,r=new tt(String(t.absolute),{flags:ds(t.size),mode:i,autoClose:!1});r.on("error",h=>{r.fd&&u.close(r.fd,()=>{}),r.write=()=>!0,this[O](h,t),e()});let n=1,o=h=>{if(h){r.fd&&u.close(r.fd,()=>{}),this[O](h,t),e();return}--n===0&&r.fd!==void 0&&u.close(r.fd,l=>{l?this[O](l,t):this[$t](),e()})};r.on("finish",()=>{let h=String(t.absolute),l=r.fd;if(typeof l=="number"&&t.mtime&&!this.noMtime){n++;let c=t.atime||new Date,d=t.mtime;u.futimes(l,c,d,S=>S?u.utimes(h,c,d,T=>o(T&&S)):o())}if(typeof l=="number"&&this[Re](t)){n++;let c=this[ge](t),d=this[be](t);typeof c=="number"&&typeof d=="number"&&u.fchown(l,c,d,S=>S?u.chown(h,c,d,T=>o(T&&S)):o())}o()});let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",h=>{this[O](h,t),e()}),t.pipe(a)),a.pipe(r)}[Os](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.dmode;this[yt](String(t.absolute),i,r=>{if(r){this[O](r,t),e();return}let n=1,o=()=>{--n===0&&(e(),this[$t](),t.resume())};t.mtime&&!this.noMtime&&(n++,u.utimes(String(t.absolute),t.atime||new Date,t.mtime,o)),this[Re](t)&&(n++,u.chown(String(t.absolute),Number(this[ge](t)),Number(this[be](t)),o)),o()})}[Dr](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Lr](t,e){let i=f(R.relative(this.cwd,R.resolve(R.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[ye](t,this.cwd,i,()=>this[Ri](t,String(t.linkpath),"symlink",e),r=>{this[O](r,t),e()})}[Nr](t,e){let i=f(R.resolve(this.cwd,String(t.linkpath))),r=f(String(t.linkpath)).split("/");this[ye](t,this.cwd,r,()=>this[Ri](t,i,"link",e),n=>{this[O](n,t),e()})}[ye](t,e,i,r,n){let o=i.shift();if(this.preservePaths||o===void 0)return r();let a=R.resolve(e,o);u.lstat(a,(h,l)=>{if(h)return r();if(l?.isSymbolicLink())return n(new St(a,R.resolve(a,i.join("/"))));this[ye](t,a,i,r,n)})}[Ir](){this[yi]++}[$t](){this[yi]--,this[Rs]()}[Ts](t){this[$t](),t.resume()}[bs](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Oe}[gs](t){this[Ir]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,i=>this[xr](t,i))}[xr](t,e){let i=a=>{e(a)},r=()=>{this[yt](this.cwd,this.dmode,a=>{if(a){this[O](a,t),i();return}this[_e]=!0,n()})},n=()=>{if(t.absolute!==this.cwd){let a=f(R.dirname(String(t.absolute)));if(a!==this.cwd)return this[yt](a,this.dmode,h=>{if(h){this[O](h,t),i();return}o()})}o()},o=()=>{u.lstat(String(t.absolute),(a,h)=>{if(h&&(this.keep||this.newer&&h.mtime>(t.mtime??h.mtime))){this[Ts](t),i();return}if(a||this[bs](t,h))return this[P](null,t,i);if(h.isDirectory()){if(t.type==="Directory"){let l=this.chmod&&t.mode&&(h.mode&4095)!==t.mode,c=d=>this[P](d??null,t,i);return l?u.chmod(String(t.absolute),Number(t.mode),c):c()}if(t.absolute!==this.cwd)return u.rmdir(String(t.absolute),l=>this[P](l??null,t,i))}if(t.absolute===this.cwd)return this[P](null,t,i);ao(String(t.absolute),l=>this[P](l??null,t,i))})};this[_e]?n():r()}[P](t,e,i){if(t){this[O](t,e),i();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[_s](e,i);case"Link":return this[Nr](e,i);case"SymbolicLink":return this[Lr](e,i);case"Directory":case"GNUDumpDir":return this[Os](e,i)}}[Ri](t,e,i,r){u[i](e,String(t.absolute),n=>{n?this[O](n,t):(this[$t](),t.resume()),r()})}},Se=s=>{try{return[null,s()]}catch(t){return[t,null]}},Te=class extends Xt{sync=!0;[P](t,e){return super[P](t,e,()=>{})}[gs](t){if(!this[_e]){let n=this[yt](this.cwd,this.dmode);if(n)return this[O](n,t);this[_e]=!0}if(t.absolute!==this.cwd){let n=f(R.dirname(String(t.absolute)));if(n!==this.cwd){let o=this[yt](n,this.dmode);if(o)return this[O](o,t)}}let[e,i]=Se(()=>u.lstatSync(String(t.absolute)));if(i&&(this.keep||this.newer&&i.mtime>(t.mtime??i.mtime)))return this[Ts](t);if(e||this[bs](t,i))return this[P](null,t);if(i.isDirectory()){if(t.type==="Directory"){let o=this.chmod&&t.mode&&(i.mode&4095)!==t.mode,[a]=o?Se(()=>{u.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[P](a,t)}let[n]=Se(()=>u.rmdirSync(String(t.absolute)));this[P](n,t)}let[r]=t.absolute===this.cwd?[]:Se(()=>lo(String(t.absolute)));this[P](r,t)}[_s](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,r=a=>{let h;try{u.closeSync(n)}catch(l){h=l}(a||h)&&this[O](a||h,t),e()},n;try{n=u.openSync(String(t.absolute),ds(t.size),i)}catch(a){return r(a)}let o=this.transform&&this.transform(t)||t;o!==t&&(o.on("error",a=>this[O](a,t)),t.pipe(o)),o.on("data",a=>{try{u.writeSync(n,a,0,a.length)}catch(h){r(h)}}),o.on("end",()=>{let a=null;if(t.mtime&&!this.noMtime){let h=t.atime||new Date,l=t.mtime;try{u.futimesSync(n,h,l)}catch(c){try{u.utimesSync(String(t.absolute),h,l)}catch{a=c}}}if(this[Re](t)){let h=this[ge](t),l=this[be](t);try{u.fchownSync(n,Number(h),Number(l))}catch(c){try{u.chownSync(String(t.absolute),Number(h),Number(l))}catch{a=a||c}}}r(a)})}[Os](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.dmode,r=this[yt](String(t.absolute),i);if(r){this[O](r,t),e();return}if(t.mtime&&!this.noMtime)try{u.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Re](t))try{u.chownSync(String(t.absolute),Number(this[ge](t)),Number(this[be](t)))}catch{}e(),t.resume()}[yt](t,e){try{return Rr(f(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(i){return i}}[ye](t,e,i,r,n){if(this.preservePaths||i.length===0)return r();let o=e;for(let a of i){o=R.resolve(o,a);let[h,l]=Se(()=>u.lstatSync(o));if(h)return r();if(l.isSymbolicLink())return n(new St(o,R.resolve(e,i.join("/"))))}r()}[Ri](t,e,i,r){let n=`${i}Sync`;try{u[n](e,String(t.absolute)),r(),t.resume()}catch(o){return this[O](o,t)}}};var co=s=>{let t=new Te(s),e=s.file,i=kr.statSync(e),r=s.maxReadSize||16*1024*1024;new Me(e,{readSize:r,size:i.size}).pipe(t)},fo=(s,t)=>{let e=new Xt(s),i=s.maxReadSize||16*1024*1024,r=s.file;return new Promise((o,a)=>{e.on("error",a),e.on("close",o),kr.stat(r,(h,l)=>{if(h)a(h);else{let c=new _t(r,{readSize:i,size:l.size});c.on("error",a),c.pipe(e)}})})},uo=K(co,fo,s=>new Te(s),s=>new Xt(s),(s,t)=>{t?.length&&Xi(s,t)});import v from"node:fs";import vr from"node:path";var mo=(s,t)=>{let e=new kt(s),i=!0,r,n;try{try{r=v.openSync(s.file,"r+")}catch(h){if(h?.code==="ENOENT")r=v.openSync(s.file,"w+");else throw h}let o=v.fstatSync(r),a=Buffer.alloc(512);t:for(n=0;no.size)break;n+=l,s.mtimeCache&&h.mtime&&s.mtimeCache.set(String(h.path),h.mtime)}i=!1,po(s,e,n,r,t)}finally{if(i)try{v.closeSync(r)}catch{}}},po=(s,t,e,i,r)=>{let n=new Wt(s.file,{fd:i,start:e});t.pipe(n),wo(t,r)},Eo=(s,t)=>{t=Array.from(t);let e=new wt(s),i=(n,o,a)=>{let h=(T,N)=>{T?v.close(n,E=>a(T)):a(null,N)},l=0;if(o===0)return h(null,0);let c=0,d=Buffer.alloc(512),S=(T,N)=>{if(T||N===void 0)return h(T);if(c+=N,c<512&&N)return v.read(n,d,c,d.length-c,l+c,S);if(l===0&&d[0]===31&&d[1]===139)return h(new Error("cannot append to compressed archives"));if(c<512)return h(null,l);let E=new C(d);if(!E.cksumValid)return h(null,l);let x=512*Math.ceil((E.size??0)/512);if(l+x+512>o||(l+=x+512,l>=o))return h(null,l);s.mtimeCache&&E.mtime&&s.mtimeCache.set(String(E.path),E.mtime),c=0,v.read(n,d,0,512,l,S)};v.read(n,d,0,512,l,S)};return new Promise((n,o)=>{e.on("error",o);let a="r+",h=(l,c)=>{if(l&&l.code==="ENOENT"&&a==="r+")return a="w+",v.open(s.file,a,h);if(l||!c)return o(l);v.fstat(c,(d,S)=>{if(d)return v.close(c,()=>o(d));i(c,S.size,(T,N)=>{if(T)return o(T);let E=new tt(s.file,{fd:c,start:N});e.pipe(E),E.on("error",o),E.on("close",n),So(e,t)})})};v.open(s.file,a,h)})},wo=(s,t)=>{t.forEach(e=>{e.charAt(0)==="@"?Ft({file:vr.resolve(s.cwd,e.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>s.add(i)}):s.add(e)}),s.end()},So=async(s,t)=>{for(let e of t)e.charAt(0)==="@"?await Ft({file:vr.resolve(String(s.cwd),e.slice(1)),noResume:!0,onReadEntry:i=>s.add(i)}):s.add(e);s.end()},vt=K(mo,Eo,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(s,t)=>{if(!vs(s))throw new TypeError("file is required");if(s.gzip||s.brotli||s.zstd||s.file.endsWith(".br")||s.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")});var yo=K(vt.syncFile,vt.asyncFile,vt.syncNoFile,vt.asyncNoFile,(s,t=[])=>{vt.validate?.(s,t),Ro(s)}),Ro=s=>{let t=s.filter;s.mtimeCache||(s.mtimeCache=new Map),s.filter=t?(e,i)=>t(e,i)&&!((s.mtimeCache?.get(e)??i.mtime??0)>(i.mtime??0)):(e,i)=>!((s.mtimeCache?.get(e)??i.mtime??0)>(i.mtime??0))};export{C as Header,wt as Pack,mi as PackJob,kt as PackSync,st as Parser,ct as Pax,Ve as ReadEntry,Xt as Unpack,Te as UnpackSync,fe as WriteEntry,ri as WriteEntrySync,ni as WriteEntryTar,Kn as c,Kn as create,uo as extract,Xi as filesFilter,Ft as list,vt as r,vt as replace,Ft as t,Ui as types,yo as u,yo as update,uo as x}; +//# sourceMappingURL=index.min.js.map diff --git a/node_modules/tar/dist/esm/large-numbers.js b/node_modules/tar/dist/esm/large-numbers.js new file mode 100644 index 0000000000000..4f2f7e5f14fc1 --- /dev/null +++ b/node_modules/tar/dist/esm/large-numbers.js @@ -0,0 +1,94 @@ +// 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 \ No newline at end of file diff --git a/node_modules/tar/dist/esm/list.js b/node_modules/tar/dist/esm/list.js new file mode 100644 index 0000000000000..4c3af58192ece --- /dev/null +++ b/node_modules/tar/dist/esm/list.js @@ -0,0 +1,105 @@ +// 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); + ret = m !== undefined ? m : 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 { + fd = fs.openSync(file, 'r'); + const stat = fs.fstatSync(fd); + const readSize = opt.maxReadSize || 16 * 1024 * 1024; + if (stat.size < readSize) { + const buf = Buffer.allocUnsafe(stat.size); + const read = fs.readSync(fd, buf, 0, stat.size, 0); + p.end(read === buf.byteLength ? buf : buf.subarray(0, read)); + } + else { + let pos = 0; + const buf = Buffer.allocUnsafe(readSize); + while (pos < stat.size) { + const bytesRead = fs.readSync(fd, buf, 0, readSize, pos); + if (bytesRead === 0) + break; + pos += bytesRead; + p.write(buf.subarray(0, bytesRead)); + } + p.end(); + } + } + finally { + if (typeof fd === 'number') { + try { + fs.closeSync(fd); + /* c8 ignore next */ + } + catch { } + } + } +}; +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.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/make-command.js b/node_modules/tar/dist/esm/make-command.js new file mode 100644 index 0000000000000..b915bc04b74ba --- /dev/null +++ b/node_modules/tar/dist/esm/make-command.js @@ -0,0 +1,48 @@ +import { 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; + } + entries = !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); + return cb ? p.then(() => cb(), cb) : 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 */ + } + throw new Error('impossible options??'); + /* c8 ignore stop */ + }, { + syncFile, + asyncFile, + syncNoFile, + asyncNoFile, + validate, + }); +}; +//# sourceMappingURL=make-command.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/mkdir.js b/node_modules/tar/dist/esm/mkdir.js new file mode 100644 index 0000000000000..7679907aba19f --- /dev/null +++ b/node_modules/tar/dist/esm/mkdir.js @@ -0,0 +1,179 @@ +import { chownr, chownrSync } from 'chownr'; +import fs from 'node:fs'; +import fsp from 'node:fs/promises'; +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 checkCwd = (dir, cb) => { + fs.stat(dir, (er, st) => { + if (er || !st.isDirectory()) { + er = new CwdError(dir, er?.code || 'ENOTDIR'); + } + cb(er); + }); +}; +/** + * Wrapper around fs/promises.mkdir 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 cwd = normalizeWindowsPath(opt.cwd); + const done = (er, created) => { + if (er) { + cb(er); + } + else { + if (created && doChown) { + chownr(created, uid, gid, er => done(er)); + } + else if (needChmod) { + fs.chmod(dir, mode, cb); + } + else { + cb(); + } + } + }; + if (dir === cwd) { + return checkCwd(dir, done); + } + if (preserve) { + return fsp.mkdir(dir, { mode, recursive: true }).then(made => done(null, made ?? undefined), // oh, ts + done); + } + const sub = normalizeWindowsPath(path.relative(cwd, dir)); + const parts = sub.split('/'); + mkdir_(cwd, parts, mode, unlink, cwd, undefined, done); +}; +const mkdir_ = (base, parts, mode, unlink, cwd, created, cb) => { + if (parts.length === 0) { + return cb(null, created); + } + const p = parts.shift(); + const part = normalizeWindowsPath(path.resolve(base + '/' + p)); + fs.mkdir(part, mode, onmkdir(part, parts, mode, unlink, cwd, created, cb)); +}; +const onmkdir = (part, parts, mode, 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, unlink, cwd, created, cb); + } + else if (unlink) { + fs.unlink(part, er => { + if (er) { + return cb(er); + } + fs.mkdir(part, mode, onmkdir(part, parts, mode, 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, unlink, cwd, created, cb); + } +}; +const checkCwdSync = (dir) => { + let ok = false; + let code; + 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 cwd = normalizeWindowsPath(opt.cwd); + const done = (created) => { + if (created && doChown) { + chownrSync(created, uid, gid); + } + if (needChmod) { + fs.chmodSync(dir, mode); + } + }; + if (dir === cwd) { + checkCwdSync(cwd); + return done(); + } + if (preserve) { + return done(fs.mkdirSync(dir, { mode, recursive: true }) ?? undefined); + } + const sub = normalizeWindowsPath(path.relative(cwd, dir)); + const parts = sub.split('/'); + let created; + for (let p = parts.shift(), part = cwd; p && (part += '/' + p); p = parts.shift()) { + part = normalizeWindowsPath(path.resolve(part)); + try { + fs.mkdirSync(part, mode); + created = created || part; + } + catch { + const st = fs.lstatSync(part); + if (st.isDirectory()) { + continue; + } + else if (unlink) { + fs.unlinkSync(part); + fs.mkdirSync(part, mode); + created = created || part; + continue; + } + else if (st.isSymbolicLink()) { + return new SymlinkError(part, part + '/' + parts.join('/')); + } + } + } + return done(created); +}; +//# sourceMappingURL=mkdir.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/mode-fix.js b/node_modules/tar/dist/esm/mode-fix.js new file mode 100644 index 0000000000000..5fd3bb88c1cb2 --- /dev/null +++ b/node_modules/tar/dist/esm/mode-fix.js @@ -0,0 +1,25 @@ +export 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 \ No newline at end of file diff --git a/node_modules/tar/dist/esm/normalize-unicode.js b/node_modules/tar/dist/esm/normalize-unicode.js new file mode 100644 index 0000000000000..8fa17f5b9ce97 --- /dev/null +++ b/node_modules/tar/dist/esm/normalize-unicode.js @@ -0,0 +1,34 @@ +// 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); +// Limit the size of this. Very low-sophistication LRU cache +const MAX = 10000; +const cache = new Set(); +export const normalizeUnicode = (s) => { + if (!cache.has(s)) { + // shake out identical accents and ligatures + normalizeCache[s] = s + .normalize('NFD') + .toLocaleLowerCase('en') + .toLocaleUpperCase('en'); + } + else { + cache.delete(s); + } + cache.add(s); + const ret = normalizeCache[s]; + let i = cache.size - MAX; + // only prune when we're 10% over the max + if (i > MAX / 10) { + for (const s of cache) { + cache.delete(s); + delete normalizeCache[s]; + if (--i <= 0) + break; + } + } + return ret; +}; +//# sourceMappingURL=normalize-unicode.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/normalize-windows-path.js b/node_modules/tar/dist/esm/normalize-windows-path.js new file mode 100644 index 0000000000000..bde0c962344a3 --- /dev/null +++ b/node_modules/tar/dist/esm/normalize-windows-path.js @@ -0,0 +1,9 @@ +// 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.replaceAll(/\\/g, '/'); +//# sourceMappingURL=normalize-windows-path.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/options.js b/node_modules/tar/dist/esm/options.js new file mode 100644 index 0000000000000..a006d36c23c92 --- /dev/null +++ b/node_modules/tar/dist/esm/options.js @@ -0,0 +1,54 @@ +// 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 \ No newline at end of file diff --git a/node_modules/tar/dist/esm/pack.js b/node_modules/tar/dist/esm/pack.js new file mode 100644 index 0000000000000..ec441138051c9 --- /dev/null +++ b/node_modules/tar/dist/esm/pack.js @@ -0,0 +1,502 @@ +// 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; + pendingLink = 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 { warnMethod } from './warn-method.js'; +const EOF = Buffer.alloc(1024); +const ONSTAT = Symbol('onStat'); +const ENDED = Symbol('ended'); +const QUEUE = Symbol('queue'); +const PENDINGLINKS = Symbol('pendingLinks'); +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 { + sync = false; + opt; + cwd; + maxReadSize; + preservePaths; + strict; + noPax; + prefix; + linkCache; + statCache; + file; + portable; + zip; + readdirCache; + noDirRecurse; + follow; + noMtime; + mtime; + filter; + jobs; + [WRITEENTRYCLASS]; + onWriteEntry; + // Note: we actually DO need a linked list here, because we + // shift() to update the head of the list where we start, but still + // while that happens, need to know what the next item in the queue + // will be. Since we do multiple jobs in parallel, it's not as simple + // as just an Array.shift(), since that would lose the information about + // the next job in the list. We could add a .next field on the PackJob + // class, but then we'd have to be tracking the tail of the queue the + // whole time, and Yallist just does that for us anyway. + [QUEUE]; + [PENDINGLINKS] = new Map(); + [JOBS] = 0; + [PROCESSING] = false; + [ENDED] = false; + constructor(opt = {}) { + 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 || opt.zstd) { + if ((opt.gzip ? 1 : 0) + (opt.brotli ? 1 : 0) + (opt.zstd ? 1 : 0) > + 1) { + throw new TypeError('gzip, brotli, zstd 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); + } + if (opt.zstd) { + if (typeof opt.zstd !== 'object') { + opt.zstd = {}; + } + this.zip = new zlib.ZstdCompress(opt.zstd); + } + /* 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 (typeof path === 'string') { + this[ADDFSENTRY](path); + } + else { + this[ADDTARENTRY](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; + } + else if (stat.isFile() && + stat.nlink > 1 && + !this.linkCache.get(`${stat.dev}:${stat.ino}`) && + !this.sync) { + // if it's not filtered, and it's a new File entry, and next anyway + // process right away in case any pending Link entries are about + // to try to link to it. + if (job === this[CURRENT]) { + this[PROCESSJOB](job); + } + else { + // if it's NOT the current entry, it needs to be deferred, + // so that the link target can be built first. + const key = `${stat.dev}:${stat.ino}`; + const pending = this[PENDINGLINKS].get(key); + if (pending) + pending.push(job); + else + this[PENDINGLINKS].set(key, [job]); + job.pendingLink = true; + job.pending = 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 === 0 && 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; + const { stat } = job; + if (stat && stat.isFile() && stat.nlink > 1) { + // might be a file with pending links + const key = `${stat.dev}:${stat.ino}`; + const pending = this[PENDINGLINKS].get(key); + if (pending) { + this[PENDINGLINKS].delete(key); + for (const job of pending) { + job.pending = false; + this[PROCESSJOB](job); + } + } + } + this[PROCESS](); + } + [PROCESSJOB](job) { + if (job.pending && job.pendingLink && job === this[CURRENT]) { + // At least one of the links to this file are not being included + // in the tarball, so we need to just proceed. + job.pending = false; + job.pendingLink = false; + } + 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 \ No newline at end of file diff --git a/node_modules/tar/dist/esm/package.json b/node_modules/tar/dist/esm/package.json new file mode 100644 index 0000000000000..3dbc1ca591c05 --- /dev/null +++ b/node_modules/tar/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/tar/dist/esm/parse.js b/node_modules/tar/dist/esm/parse.js new file mode 100644 index 0000000000000..cc359359c95d3 --- /dev/null +++ b/node_modules/tar/dist/esm/parse.js @@ -0,0 +1,606 @@ +// 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 list 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, ZstdDecompress } from 'minizlib'; +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 zstdHeader = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]); +const ZIP_HEADER_LEN = Math.max(gzipHeader.length, zstdHeader.length); +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; + zstd; + writable = true; + readable = false; + [QUEUE] = []; + [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.zstd) && opt.brotli !== undefined ? opt.brotli + : isTBR ? undefined + : false; + // zstd has magic bytes to identify it, but we also support explicit options + // and file extension detection + const isTZST = opt.file && + (opt.file.endsWith('.tar.zst') || opt.file.endsWith('.tzst')); + this.zstd = + !(opt.gzip || opt.brotli) && opt.zstd !== undefined ? opt.zstd + : isTZST ? true + : undefined; + // 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 === 0) { + // 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 === 0 && !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, zstd, or brotli compressed + 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 < ZIP_HEADER_LEN) { + 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; + } + } + // look for zstd header if gzip header not found + let isZstd = false; + if (this[UNZIP] === false && this.zstd !== false) { + isZstd = true; + for (let i = 0; i < zstdHeader.length; i++) { + if (chunk[i] !== zstdHeader[i]) { + isZstd = false; + break; + } + } + } + const maybeBrotli = this.brotli === undefined && !isZstd; + 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 || isZstd))) { + const ended = this[ENDED]; + this[ENDED] = false; + this[UNZIP] = + this[UNZIP] === undefined ? new Unzip({}) + : isZstd ? new ZstdDecompress({}) + : 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 > 0 ? false + : this[READENTRY] ? this[READENTRY].flowing + : true; + // if we have no queue, then that means a clogged READENTRY + if (!ret && this[QUEUE].length === 0) { + 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) { + this[BUFFER] = + this[BUFFER] ? + Buffer.concat([chunk.subarray(position), 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 || this.zstd === undefined) + chunk = chunk || Buffer.alloc(0); + if (chunk) + this.write(chunk); + this[MAYBEEND](); + } + } + return this; + } +} +//# sourceMappingURL=parse.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/path-reservations.js b/node_modules/tar/dist/esm/path-reservations.js new file mode 100644 index 0000000000000..117f6bead9408 --- /dev/null +++ b/node_modules/tar/dist/esm/path-reservations.js @@ -0,0 +1,166 @@ +// 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.at(-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))); + }); + 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.at(-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.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/pax.js b/node_modules/tar/dist/esm/pax.js new file mode 100644 index 0000000000000..832808f344da5 --- /dev/null +++ b/node_modules/tar/dist/esm/pax.js @@ -0,0 +1,154 @@ +import { 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.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/process-umask.js b/node_modules/tar/dist/esm/process-umask.js new file mode 100644 index 0000000000000..c6748e2e253c4 --- /dev/null +++ b/node_modules/tar/dist/esm/process-umask.js @@ -0,0 +1,3 @@ +// separate file so I stop getting nagged in vim about deprecated API. +export const umask = () => process.umask(); +//# sourceMappingURL=process-umask.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/read-entry.js b/node_modules/tar/dist/esm/read-entry.js new file mode 100644 index 0000000000000..ef11b01368f11 --- /dev/null +++ b/node_modules/tar/dist/esm/read-entry.js @@ -0,0 +1,132 @@ +import { 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 \ No newline at end of file diff --git a/node_modules/tar/dist/esm/replace.js b/node_modules/tar/dist/esm/replace.js new file mode 100644 index 0000000000000..77c878ac3a560 --- /dev/null +++ b/node_modules/tar/dist/esm/replace.js @@ -0,0 +1,221 @@ +// 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 { } + } + } +}; +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 || 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 (const file of files) { + 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.zstd || + 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 \ No newline at end of file diff --git a/node_modules/tar/dist/esm/strip-absolute-path.js b/node_modules/tar/dist/esm/strip-absolute-path.js new file mode 100644 index 0000000000000..cce5ff80b00db --- /dev/null +++ b/node_modules/tar/dist/esm/strip-absolute-path.js @@ -0,0 +1,25 @@ +// 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 \ No newline at end of file diff --git a/node_modules/tar/dist/esm/strip-trailing-slashes.js b/node_modules/tar/dist/esm/strip-trailing-slashes.js new file mode 100644 index 0000000000000..ace4218a7547b --- /dev/null +++ b/node_modules/tar/dist/esm/strip-trailing-slashes.js @@ -0,0 +1,14 @@ +// 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.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/symlink-error.js b/node_modules/tar/dist/esm/symlink-error.js new file mode 100644 index 0000000000000..d31766e2e0afa --- /dev/null +++ b/node_modules/tar/dist/esm/symlink-error.js @@ -0,0 +1,15 @@ +export 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.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/types.js b/node_modules/tar/dist/esm/types.js new file mode 100644 index 0000000000000..c33a6a4c5e14b --- /dev/null +++ b/node_modules/tar/dist/esm/types.js @@ -0,0 +1,65 @@ +export const isCode = (c) => name.has(c); +export const isName = (c) => code.has(c); +/** + * types that are a normal file system entry, not metadata. + * + * These can be the subject of extended/globalExtended headers, long path + * names, long linkpath names, etc. + * + * Any other types are meta, and cannot be targetted by extended PAX headers. + */ +export const normalFsTypes = new Set([ + '0', + '', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + 'D', +]); +// 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 \ No newline at end of file diff --git a/node_modules/tar/dist/esm/unpack.js b/node_modules/tar/dist/esm/unpack.js new file mode 100644 index 0000000000000..46c53db2ad57c --- /dev/null +++ b/node_modules/tar/dist/esm/unpack.js @@ -0,0 +1,891 @@ +// 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 { normalizeWindowsPath } from './normalize-windows-path.js'; +import { Parser } from './parse.js'; +import { stripAbsolutePath } from './strip-absolute-path.js'; +import * as wc from './winchars.js'; +import { PathReservations } from './path-reservations.js'; +import { SymlinkError } from './symlink-error.js'; +import { umask } from './process-umask.js'; +const ONENTRY = Symbol('onEntry'); +const CHECKFS = Symbol('checkFs'); +const CHECKFS2 = Symbol('checkFs2'); +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 ENSURE_NO_SYMLINK = Symbol('ensureNoSymlink'); +const UNSUPPORTED = Symbol('unsupported'); +const CHECKPATH = Symbol('checkPath'); +const STRIPABSOLUTEPATH = Symbol('stripAbsolutePath'); +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; +export class Unpack extends Parser { + [ENDED] = false; + [CHECKED_CWD] = false; + [PENDING] = 0; + reservations = new PathReservations(); + transform; + writable = true; + readable = false; + 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.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 + this.preserveOwner = + opt.preserveOwner === undefined && typeof opt.uid !== 'number' ? + !!(process.getuid && process.getuid() === 0) + : !!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'); + } + } + // return false if we need to skip this file + // return true if the field was successfully sanitized + [STRIPABSOLUTEPATH](entry, field) { + const p = entry[field]; + const { type } = entry; + if (!p || this.preservePaths) + return true; + // strip off the root + const [root, stripped] = stripAbsolutePath(p); + const parts = stripped.replaceAll(/\\/g, '/').split('/'); + if (parts.includes('..') || + /* c8 ignore next */ + (isWindows && /^[a-z]:\.\.$/i.test(parts[0] ?? ''))) { + // For linkpath, check if the resolved path escapes cwd rather than + // just rejecting any path with '..' - relative symlinks like + // '../sibling/file' are valid if they resolve within the cwd. + // For paths, they just simply may not ever use .. at all. + if (field === 'path' || type === 'Link') { + this.warn('TAR_ENTRY_ERROR', `${field} contains '..'`, { + entry, + [field]: p, + }); + // not ok! + return false; + } + // Resolve linkpath relative to the entry's directory. + // `path.posix` is safe to use because we're operating on + // tar paths, not a filesystem. + const entryDir = path.posix.dirname(entry.path); + const resolved = path.posix.normalize(path.posix.join(entryDir, parts.join('/'))); + // If the resolved path escapes (starts with ..), reject it + if (resolved.startsWith('../') || resolved === '..') { + this.warn('TAR_ENTRY_ERROR', `${field} escapes extraction directory`, { + entry, + [field]: p, + }); + return false; + } + } + if (root) { + // ok, but triggers warning about stripping root + entry[field] = String(stripped); + this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute ${field}`, { + entry, + [field]: p, + }); + } + return true; + } + // no IO, just string checking for absolute indicators + [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[STRIPABSOLUTEPATH](entry, 'path') || + !this[STRIPABSOLUTEPATH](entry, 'linkpath')) { + return false; + } + entry.absolute = + path.isAbsolute(entry.path) ? + normalizeWindowsPath(path.resolve(entry.path)) + : 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, + 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) { + const parts = normalizeWindowsPath(path.relative(this.cwd, path.resolve(path.dirname(String(entry.absolute)), String(entry.linkpath)))).split('/'); + this[ENSURE_NO_SYMLINK](entry, this.cwd, parts, () => this[LINK](entry, String(entry.linkpath), 'symlink', done), er => { + this[ONERROR](er, entry); + done(); + }); + } + [HARDLINK](entry, done) { + const linkpath = normalizeWindowsPath(path.resolve(this.cwd, String(entry.linkpath))); + const parts = normalizeWindowsPath(String(entry.linkpath)).split('/'); + this[ENSURE_NO_SYMLINK](entry, this.cwd, parts, () => this[LINK](entry, linkpath, 'link', done), er => { + this[ONERROR](er, entry); + done(); + }); + } + [ENSURE_NO_SYMLINK](entry, cwd, parts, done, onError) { + const p = parts.shift(); + if (this.preservePaths || p === undefined) + return done(); + const t = path.resolve(cwd, p); + fs.lstat(t, (er, st) => { + if (er) + return done(); + if (st?.isSymbolicLink()) { + return onError(new SymlinkError(t, path.resolve(t, parts.join('/')))); + } + this[ENSURE_NO_SYMLINK](entry, t, parts, done, onError); + }); + } + [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)); + } + [CHECKFS2](entry, fullyDone) { + const done = (er) => { + 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) { + 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) { + 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); + /* c8 ignore start - This is only a problem if the file was successfully + * statted, BUT failed to open. Testing this is annoying, and we + * already have ample testint for other uses of oner() methods. + */ + } + catch (er) { + return oner(er); + } + /* c8 ignore stop */ + 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 { + 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 { + 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 { } + } + if (this[DOCHOWN](entry)) { + try { + fs.chownSync(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry))); + } + catch { } + } + 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, + cwd: this.cwd, + mode: mode, + }); + } + catch (er) { + return er; + } + } + [ENSURE_NO_SYMLINK](_entry, cwd, parts, done, onError) { + if (this.preservePaths || parts.length === 0) + return done(); + let t = cwd; + for (const p of parts) { + t = path.resolve(t, p); + const [er, st] = callSync(() => fs.lstatSync(t)); + if (er) + return done(); + if (st.isSymbolicLink()) { + return onError(new SymlinkError(t, path.resolve(cwd, parts.join('/')))); + } + } + done(); + } + [LINK](entry, linkpath, link, done) { + const linkSync = `${link}Sync`; + try { + fs[linkSync](linkpath, String(entry.absolute)); + done(); + entry.resume(); + } + catch (er) { + return this[ONERROR](er, entry); + } + } +} +//# sourceMappingURL=unpack.js.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/update.js b/node_modules/tar/dist/esm/update.js new file mode 100644 index 0000000000000..21398e9766663 --- /dev/null +++ b/node_modules/tar/dist/esm/update.js @@ -0,0 +1,30 @@ +// 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.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/warn-method.js b/node_modules/tar/dist/esm/warn-method.js new file mode 100644 index 0000000000000..13e798afefc85 --- /dev/null +++ b/node_modules/tar/dist/esm/warn-method.js @@ -0,0 +1,27 @@ +export 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 \ No newline at end of file diff --git a/node_modules/tar/dist/esm/winchars.js b/node_modules/tar/dist/esm/winchars.js new file mode 100644 index 0000000000000..4046778e14e0b --- /dev/null +++ b/node_modules/tar/dist/esm/winchars.js @@ -0,0 +1,9 @@ +// When writing files on Windows, translate the characters to their +// 0xf000 higher-encoded versions. +const raw = ['|', '<', '>', '?', ':']; +const win = raw.map(char => String.fromCodePoint(0xf000 + Number(char.codePointAt(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.map \ No newline at end of file diff --git a/node_modules/tar/dist/esm/write-entry.js b/node_modules/tar/dist/esm/write-entry.js new file mode 100644 index 0000000000000..158260236b2c3 --- /dev/null +++ b/node_modules/tar/dist/esm/write-entry.js @@ -0,0 +1,656 @@ +import 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.replaceAll(/\\/g, '/')); + p = p.replaceAll(/\\/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 { } + } + } + } + [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); + if (chunk) + super.end(chunk, cb); + else + 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 \ No newline at end of file diff --git a/node_modules/tar/index.js b/node_modules/tar/index.js deleted file mode 100644 index c9ae06e7906c4..0000000000000 --- a/node_modules/tar/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict' - -// high-level commands -exports.c = exports.create = require('./lib/create.js') -exports.r = exports.replace = require('./lib/replace.js') -exports.t = exports.list = require('./lib/list.js') -exports.u = exports.update = require('./lib/update.js') -exports.x = exports.extract = require('./lib/extract.js') - -// classes -exports.Pack = require('./lib/pack.js') -exports.Unpack = require('./lib/unpack.js') -exports.Parse = require('./lib/parse.js') -exports.ReadEntry = require('./lib/read-entry.js') -exports.WriteEntry = require('./lib/write-entry.js') -exports.Header = require('./lib/header.js') -exports.Pax = require('./lib/pax.js') -exports.types = require('./lib/types.js') diff --git a/node_modules/tar/lib/create.js b/node_modules/tar/lib/create.js deleted file mode 100644 index 9c860d4e4a764..0000000000000 --- a/node_modules/tar/lib/create.js +++ /dev/null @@ -1,111 +0,0 @@ -'use strict' - -// tar -c -const hlo = require('./high-level-opt.js') - -const Pack = require('./pack.js') -const fsm = require('fs-minipass') -const t = require('./list.js') -const path = require('path') - -module.exports = (opt_, files, cb) => { - if (typeof files === 'function') { - cb = files - } - - if (Array.isArray(opt_)) { - files = opt_, opt_ = {} - } - - if (!files || !Array.isArray(files) || !files.length) { - throw new TypeError('no files or directories specified') - } - - files = Array.from(files) - - const opt = hlo(opt_) - - if (opt.sync && typeof cb === 'function') { - throw new TypeError('callback not supported for sync tar functions') - } - - if (!opt.file && typeof cb === 'function') { - throw new TypeError('callback only supported with file option') - } - - return opt.file && opt.sync ? createFileSync(opt, files) - : opt.file ? createFile(opt, files, cb) - : opt.sync ? createSync(opt, files) - : create(opt, files) -} - -const createFileSync = (opt, files) => { - const p = new Pack.Sync(opt) - const stream = new fsm.WriteStreamSync(opt.file, { - mode: opt.mode || 0o666, - }) - p.pipe(stream) - addFilesSync(p, files) -} - -const createFile = (opt, files, cb) => { - const p = new Pack(opt) - const stream = new fsm.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 cb ? promise.then(cb, cb) : promise -} - -const addFilesSync = (p, files) => { - files.forEach(file => { - if (file.charAt(0) === '@') { - t({ - file: path.resolve(p.cwd, file.slice(1)), - sync: true, - noResume: true, - onentry: entry => p.add(entry), - }) - } else { - p.add(file) - } - }) - p.end() -} - -const addFilesAsync = (p, files) => { - while (files.length) { - const file = files.shift() - if (file.charAt(0) === '@') { - return t({ - file: path.resolve(p.cwd, file.slice(1)), - noResume: true, - onentry: entry => p.add(entry), - }).then(_ => addFilesAsync(p, files)) - } else { - p.add(file) - } - } - p.end() -} - -const createSync = (opt, files) => { - const p = new Pack.Sync(opt) - addFilesSync(p, files) - return p -} - -const create = (opt, files) => { - const p = new Pack(opt) - addFilesAsync(p, files) - return p -} diff --git a/node_modules/tar/lib/extract.js b/node_modules/tar/lib/extract.js deleted file mode 100644 index 54767982583f2..0000000000000 --- a/node_modules/tar/lib/extract.js +++ /dev/null @@ -1,113 +0,0 @@ -'use strict' - -// tar -x -const hlo = require('./high-level-opt.js') -const Unpack = require('./unpack.js') -const fs = require('fs') -const fsm = require('fs-minipass') -const path = require('path') -const stripSlash = require('./strip-trailing-slashes.js') - -module.exports = (opt_, files, cb) => { - if (typeof opt_ === 'function') { - cb = opt_, files = null, opt_ = {} - } else if (Array.isArray(opt_)) { - files = opt_, opt_ = {} - } - - if (typeof files === 'function') { - cb = files, files = null - } - - if (!files) { - files = [] - } else { - files = Array.from(files) - } - - const opt = hlo(opt_) - - if (opt.sync && typeof cb === 'function') { - throw new TypeError('callback not supported for sync tar functions') - } - - if (!opt.file && typeof cb === 'function') { - throw new TypeError('callback only supported with file option') - } - - if (files.length) { - filesFilter(opt, files) - } - - return opt.file && opt.sync ? extractFileSync(opt) - : opt.file ? extractFile(opt, cb) - : opt.sync ? extractSync(opt) - : extract(opt) -} - -// 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 => [stripSlash(f), true])) - const filter = opt.filter - - const mapHas = (file, r) => { - const root = r || path.parse(file).root || '.' - const ret = file === root ? false - : map.has(file) ? map.get(file) - : mapHas(path.dirname(file), root) - - map.set(file, ret) - return ret - } - - opt.filter = filter - ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) - : file => mapHas(stripSlash(file)) -} - -const extractFileSync = opt => { - const u = new Unpack.Sync(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, cb) => { - 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 cb ? p.then(cb, cb) : p -} - -const extractSync = opt => new Unpack.Sync(opt) - -const extract = opt => new Unpack(opt) diff --git a/node_modules/tar/lib/get-write-flag.js b/node_modules/tar/lib/get-write-flag.js deleted file mode 100644 index e86959996623c..0000000000000 --- a/node_modules/tar/lib/get-write-flag.js +++ /dev/null @@ -1,20 +0,0 @@ -// 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. -// Only supported in Node v12.9.0 and above. -const platform = process.env.__FAKE_PLATFORM__ || process.platform -const isWindows = platform === 'win32' -const fs = global.__FAKE_TESTING_FS__ || require('fs') - -/* istanbul ignore next */ -const { O_CREAT, O_TRUNC, O_WRONLY, UV_FS_O_FILEMAP = 0 } = fs.constants - -const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP -const fMapLimit = 512 * 1024 -const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY -module.exports = !fMapEnabled ? () => 'w' - : size => size < fMapLimit ? fMapFlag : 'w' diff --git a/node_modules/tar/lib/header.js b/node_modules/tar/lib/header.js deleted file mode 100644 index 411d5e45e879a..0000000000000 --- a/node_modules/tar/lib/header.js +++ /dev/null @@ -1,304 +0,0 @@ -'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.) - -const types = require('./types.js') -const pathModule = require('path').posix -const large = require('./large-numbers.js') - -const SLURP = Symbol('slurp') -const TYPE = Symbol('type') - -class Header { - constructor (data, off, ex, gex) { - this.cksumValid = false - this.needPax = false - this.nullBlock = false - - this.block = null - this.path = null - this.mode = null - this.uid = null - this.gid = null - this.size = null - this.mtime = null - this.cksum = null - this[TYPE] = '0' - this.linkpath = null - this.uname = null - this.gname = null - this.devmaj = 0 - this.devmin = 0 - this.atime = null - this.ctime = null - - if (Buffer.isBuffer(data)) { - this.decode(data, off || 0, ex, gex) - } else if (data) { - this.set(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 - this[SLURP](ex) - this[SLURP](gex, true) - - // old tar versions marked dirs as a file with a trailing / - this[TYPE] = decString(buf, off + 156, 1) - if (this[TYPE] === '') { - this[TYPE] = '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.slice(off + 257, off + 265).toString() === 'ustar\u000000') { - this.uname = decString(buf, off + 265, 32) - this.gname = decString(buf, off + 297, 32) - this.devmaj = decNumber(buf, off + 329, 8) - this.devmin = decNumber(buf, off + 337, 8) - 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 === null && sum === 8 * 0x20) { - this.nullBlock = true - } - } - - [SLURP] (ex, global) { - for (const k in ex) { - // we slurp in everything except for the path attribute in - // a global extended header, because that's weird. - if (ex[k] !== null && ex[k] !== undefined && - !(global && k === 'path')) { - this[k] = ex[k] - } - } - } - - encode (buf, off) { - if (!buf) { - buf = this.block = Buffer.alloc(512) - off = 0 - } - - if (!off) { - off = 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 - } - - set (data) { - for (const i in data) { - if (data[i] !== null && data[i] !== undefined) { - this[i] = data[i] - } - } - } - - get type () { - return types.name.get(this[TYPE]) || this[TYPE] - } - - get typeKey () { - return this[TYPE] - } - - set type (type) { - if (types.code.has(type)) { - this[TYPE] = types.code.get(type) - } else { - this[TYPE] = type - } - } -} - -const splitPrefix = (p, prefixSize) => { - const pathSize = 100 - let pp = p - let prefix = '' - let ret - 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) - - // 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.slice(off, off + size).toString('utf8').replace(/\0.*/, '') - -const decDate = (buf, off, size) => - numToDate(decNumber(buf, off, size)) - -const numToDate = num => num === null ? null : new Date(num * 1000) - -const decNumber = (buf, off, size) => - buf[off] & 0x80 ? large.parse(buf.slice(off, off + size)) - : decSmallNumber(buf, off, size) - -const nanNull = value => isNaN(value) ? null : value - -const decSmallNumber = (buf, off, size) => - nanNull(parseInt( - buf.slice(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, number) => - number === null ? false : - number > MAXNUM[size] || number < 0 - ? (large.encode(number, buf.slice(off, off + size)), true) - : (encSmallNumber(buf, off, size, number), false) - -const encSmallNumber = (buf, off, size, number) => - buf.write(octalString(number, size), off, size, 'ascii') - -const octalString = (number, size) => - padOctal(Math.floor(number).toString(8), size) - -const padOctal = (string, size) => - (string.length === size - 1 ? string - : new Array(size - string.length - 1).join('0') + string + ' ') + '\0' - -const encDate = (buf, off, size, date) => - date === null ? 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, string) => - string === null ? false : - (buf.write(string + NULLS, off, size, 'utf8'), - string.length !== Buffer.byteLength(string) || string.length > size) - -module.exports = Header diff --git a/node_modules/tar/lib/high-level-opt.js b/node_modules/tar/lib/high-level-opt.js deleted file mode 100644 index 40e44180e1669..0000000000000 --- a/node_modules/tar/lib/high-level-opt.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict' - -// 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'], -]) - -module.exports = opt => opt ? Object.keys(opt).map(k => [ - argmap.has(k) ? argmap.get(k) : k, opt[k], -]).reduce((set, kv) => (set[kv[0]] = kv[1], set), Object.create(null)) : {} diff --git a/node_modules/tar/lib/large-numbers.js b/node_modules/tar/lib/large-numbers.js deleted file mode 100644 index b11e72d996fde..0000000000000 --- a/node_modules/tar/lib/large-numbers.js +++ /dev/null @@ -1,104 +0,0 @@ -'use strict' -// Tar can encode large and negative numbers using a leading byte of -// 0xff for negative, and 0x80 for positive. - -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) - } - } -} - -const parse = (buf) => { - const pre = buf[0] - const value = pre === 0x80 ? pos(buf.slice(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 = 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 = 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 - -module.exports = { - encode, - parse, -} diff --git a/node_modules/tar/lib/list.js b/node_modules/tar/lib/list.js deleted file mode 100644 index f2358c25410b5..0000000000000 --- a/node_modules/tar/lib/list.js +++ /dev/null @@ -1,139 +0,0 @@ -'use strict' - -// XXX: This shares a lot in common with extract.js -// maybe some DRY opportunity here? - -// tar -t -const hlo = require('./high-level-opt.js') -const Parser = require('./parse.js') -const fs = require('fs') -const fsm = require('fs-minipass') -const path = require('path') -const stripSlash = require('./strip-trailing-slashes.js') - -module.exports = (opt_, files, cb) => { - if (typeof opt_ === 'function') { - cb = opt_, files = null, opt_ = {} - } else if (Array.isArray(opt_)) { - files = opt_, opt_ = {} - } - - if (typeof files === 'function') { - cb = files, files = null - } - - if (!files) { - files = [] - } else { - files = Array.from(files) - } - - const opt = hlo(opt_) - - if (opt.sync && typeof cb === 'function') { - throw new TypeError('callback not supported for sync tar functions') - } - - if (!opt.file && typeof cb === 'function') { - throw new TypeError('callback only supported with file option') - } - - if (files.length) { - filesFilter(opt, files) - } - - if (!opt.noResume) { - onentryFunction(opt) - } - - return opt.file && opt.sync ? listFileSync(opt) - : opt.file ? listFile(opt, cb) - : list(opt) -} - -const onentryFunction = opt => { - const onentry = opt.onentry - opt.onentry = onentry ? e => { - onentry(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 => [stripSlash(f), true])) - const filter = opt.filter - - const mapHas = (file, r) => { - const root = r || path.parse(file).root || '.' - const ret = file === root ? false - : map.has(file) ? map.get(file) - : mapHas(path.dirname(file), root) - - map.set(file, ret) - return ret - } - - opt.filter = filter - ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) - : file => mapHas(stripSlash(file)) -} - -const listFileSync = opt => { - const p = list(opt) - const file = opt.file - let threw = true - 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.slice(0, bytesRead)) - } - p.end() - } - threw = false - } finally { - if (threw && fd) { - try { - fs.closeSync(fd) - } catch (er) {} - } - } -} - -const listFile = (opt, cb) => { - 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 cb ? p.then(cb, cb) : p -} - -const list = opt => new Parser(opt) diff --git a/node_modules/tar/lib/mkdir.js b/node_modules/tar/lib/mkdir.js deleted file mode 100644 index 8ee8de7852d12..0000000000000 --- a/node_modules/tar/lib/mkdir.js +++ /dev/null @@ -1,229 +0,0 @@ -'use strict' -// wrapper around mkdirp for tar's needs. - -// TODO: This should probably be a class, not functionally -// passing around state in a gazillion args. - -const mkdirp = require('mkdirp') -const fs = require('fs') -const path = require('path') -const chownr = require('chownr') -const normPath = require('./normalize-windows-path.js') - -class SymlinkError extends Error { - constructor (symlink, path) { - super('Cannot extract through symbolic link') - this.path = path - this.symlink = symlink - } - - get name () { - return 'SylinkError' - } -} - -class CwdError extends Error { - constructor (path, code) { - super(code + ': Cannot cd into \'' + path + '\'') - this.path = path - this.code = code - } - - get name () { - return 'CwdError' - } -} - -const cGet = (cache, key) => cache.get(normPath(key)) -const cSet = (cache, key, val) => cache.set(normPath(key), val) - -const checkCwd = (dir, cb) => { - fs.stat(dir, (er, st) => { - if (er || !st.isDirectory()) { - er = new CwdError(dir, er && er.code || 'ENOTDIR') - } - cb(er) - }) -} - -module.exports = (dir, opt, cb) => { - dir = normPath(dir) - - // if there's any overlap between mask and mode, - // then we'll need an explicit chmod - const umask = opt.umask - 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 = normPath(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), done) - } - - const sub = normPath(path.relative(cwd, dir)) - const parts = sub.split('/') - mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done) -} - -const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { - if (!parts.length) { - return cb(null, created) - } - const p = parts.shift() - const part = normPath(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 && normPath(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 = 'ENOTDIR' - try { - ok = fs.statSync(dir).isDirectory() - } catch (er) { - code = er.code - } finally { - if (!ok) { - throw new CwdError(dir, code) - } - } -} - -module.exports.sync = (dir, opt) => { - dir = normPath(dir) - // if there's any overlap between mask and mode, - // then we'll need an explicit chmod - const umask = opt.umask - 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 = normPath(opt.cwd) - - const done = (created) => { - cSet(cache, dir, true) - if (created && doChown) { - chownr.sync(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(mkdirp.sync(dir, mode)) - } - - const sub = normPath(path.relative(cwd, dir)) - const parts = sub.split('/') - let created = null - for (let p = parts.shift(), part = cwd; - p && (part += '/' + p); - p = parts.shift()) { - part = normPath(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) -} diff --git a/node_modules/tar/lib/mode-fix.js b/node_modules/tar/lib/mode-fix.js deleted file mode 100644 index 42f1d6e657b1a..0000000000000 --- a/node_modules/tar/lib/mode-fix.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict' -module.exports = (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 -} diff --git a/node_modules/tar/lib/normalize-unicode.js b/node_modules/tar/lib/normalize-unicode.js deleted file mode 100644 index 79e285ab30d57..0000000000000 --- a/node_modules/tar/lib/normalize-unicode.js +++ /dev/null @@ -1,12 +0,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 -module.exports = s => { - if (!hasOwnProperty.call(normalizeCache, s)) { - normalizeCache[s] = s.normalize('NFD') - } - return normalizeCache[s] -} diff --git a/node_modules/tar/lib/normalize-windows-path.js b/node_modules/tar/lib/normalize-windows-path.js deleted file mode 100644 index eb13ba01b7b04..0000000000000 --- a/node_modules/tar/lib/normalize-windows-path.js +++ /dev/null @@ -1,8 +0,0 @@ -// 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 -module.exports = platform !== 'win32' ? p => p - : p => p && p.replace(/\\/g, '/') diff --git a/node_modules/tar/lib/pack.js b/node_modules/tar/lib/pack.js deleted file mode 100644 index d533a068f579f..0000000000000 --- a/node_modules/tar/lib/pack.js +++ /dev/null @@ -1,432 +0,0 @@ -'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')) - -class PackJob { - constructor (path, absolute) { - this.path = path || './' - this.absolute = absolute - this.entry = null - this.stat = null - this.readdir = null - this.pending = false - this.ignore = false - this.piped = false - } -} - -const { Minipass } = require('minipass') -const zlib = require('minizlib') -const ReadEntry = require('./read-entry.js') -const WriteEntry = require('./write-entry.js') -const WriteEntrySync = WriteEntry.Sync -const WriteEntryTar = WriteEntry.Tar -const Yallist = require('yallist') -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 fs = require('fs') -const path = require('path') -const warner = require('./warn-mixin.js') -const normPath = require('./normalize-windows-path.js') - -const Pack = warner(class Pack extends Minipass { - constructor (opt) { - super(opt) - opt = opt || Object.create(null) - 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 = normPath(opt.prefix || '') - this.linkCache = opt.linkCache || new Map() - this.statCache = opt.statCache || new Map() - this.readdirCache = opt.readdirCache || new Map() - - this[WRITEENTRYCLASS] = WriteEntry - if (typeof opt.onwarn === 'function') { - this.on('warn', opt.onwarn) - } - - this.portable = !!opt.portable - this.zip = null - - 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) - } - this.zip.on('data', chunk => super.write(chunk)) - this.zip.on('end', _ => super.end()) - this.zip.on('drain', _ => this[ONDRAIN]()) - this.on('resume', _ => this.zip.resume()) - } else { - this.on('drain', this[ONDRAIN]) - } - - this.noDirRecurse = !!opt.noDirRecurse - this.follow = !!opt.follow - this.noMtime = !!opt.noMtime - this.mtime = opt.mtime || null - - this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true - - this[QUEUE] = new Yallist() - this[JOBS] = 0 - this.jobs = +opt.jobs || 4 - this[PROCESSING] = false - this[ENDED] = false - } - - [WRITE] (chunk) { - return super.write(chunk) - } - - add (path) { - this.write(path) - return this - } - - end (path) { - if (path) { - this.write(path) - } - this[ENDED] = true - this[PROCESS]() - 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 = normPath(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, false) - 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 = normPath(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 !== null && 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) { - if (this.statCache.has(job.absolute)) { - this[ONSTAT](job, this.statCache.get(job.absolute)) - } else { - this[STAT](job) - } - } - if (!job.stat) { - return - } - - // filtered out! - if (job.ignore) { - return - } - - if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { - if (this.readdirCache.has(job.absolute)) { - this[ONREADDIR](job, this.readdirCache.get(job.absolute)) - } 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, - } - } - - [ENTRY] (job) { - this[JOBS] += 1 - try { - return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)) - .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 - - 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() - } -}) - -class PackSync extends Pack { - 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, stat) { - 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) - }) - } - - if (zip) { - source.on('data', chunk => { - zip.write(chunk) - }) - } else { - source.on('data', chunk => { - super[WRITE](chunk) - }) - } - } -} - -Pack.Sync = PackSync - -module.exports = Pack diff --git a/node_modules/tar/lib/parse.js b/node_modules/tar/lib/parse.js deleted file mode 100644 index 94e53042fad56..0000000000000 --- a/node_modules/tar/lib/parse.js +++ /dev/null @@ -1,552 +0,0 @@ -'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 - -const warner = require('./warn-mixin.js') -const Header = require('./header.js') -const EE = require('events') -const Yallist = require('yallist') -const maxMetaEntrySize = 1024 * 1024 -const Entry = require('./read-entry.js') -const Pax = require('./pax.js') -const zlib = require('minizlib') -const { nextTick } = require('process') - -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 - -module.exports = warner(class Parser extends EE { - constructor (opt) { - opt = opt || {} - super(opt) - - this.file = opt.file || '' - - // set to boolean false when an entry starts. 1024 bytes of \0 - // is technically a valid tarball, albeit a boring one. - this[SAW_VALID_ENTRY] = null - - // 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.writable = true - this.readable = false - - this[QUEUE] = new Yallist() - this[BUFFER] = null - this[READENTRY] = null - this[WRITEENTRY] = null - this[STATE] = 'begin' - this[META] = '' - this[EX] = null - this[GEX] = null - this[ENDED] = false - this[UNZIP] = null - this[ABORTED] = false - this[SAW_NULL_BLOCK] = false - this[SAW_EOF] = false - - this.on('end', () => this[CLOSESTREAM]()) - - if (typeof opt.onwarn === 'function') { - this.on('warn', opt.onwarn) - } - if (typeof opt.onentry === 'function') { - this.on('entry', opt.onentry) - } - } - - [CONSUMEHEADER] (chunk, position) { - if (this[SAW_VALID_ENTRY] === null) { - 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) && header.linkpath) { - this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', { header }) - } else { - const entry = this[WRITEENTRY] = new Entry(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] = null - 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] () { - nextTick(() => this.emit('close')) - } - - [PROCESSENTRY] (entry) { - let go = true - - if (!entry) { - this[READENTRY] = null - go = false - } else if (Array.isArray(entry)) { - this.emit.apply(this, entry) - } 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] - const br = entry.blockRemain - const c = (br >= chunk.length && position === 0) ? chunk - : chunk.slice(position, position + br) - - entry.write(c) - - if (!entry.blockRemain) { - this[STATE] = 'header' - this[WRITEENTRY] = null - 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]) { - 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': - this[EX] = this[EX] || Object.create(null) - this[EX].path = this[META].replace(/\0.*/, '') - break - - case 'NextFileHasLongLinkpath': - this[EX] = this[EX] || Object.create(null) - this[EX].linkpath = this[META].replace(/\0.*/, '') - break - - /* istanbul ignore next */ - default: throw new Error('unknown meta: ' + entry.type) - } - } - - 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) { - if (this[ABORTED]) { - return - } - - // first write, might be gzipped - const needSniff = this[UNZIP] === null || - this.brotli === undefined && this[UNZIP] === false - if (needSniff && chunk) { - if (this[BUFFER]) { - chunk = Buffer.concat([this[BUFFER], chunk]) - this[BUFFER] = null - } - if (chunk.length < gzipHeader.length) { - this[BUFFER] = chunk - return true - } - - // look for gzip header - for (let i = 0; this[UNZIP] === null && 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 - return true - } - } else { - // if it's tar, it's pretty reliably not brotli, chances of - // that happening are astronomical. - try { - new Header(chunk.slice(0, 512)) - this.brotli = false - } catch (_) { - this.brotli = true - } - } - } - - if (this[UNZIP] === null || (this[UNZIP] === false && this.brotli)) { - const ended = this[ENDED] - this[ENDED] = false - this[UNZIP] = this[UNZIP] === null - ? new zlib.Unzip() - : new zlib.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 - 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')) - } - - 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]) { - this[BUFFERCONCAT](chunk) - } else if (!chunk && !this[BUFFER]) { - this[MAYBEEND]() - } else { - this[CONSUMING] = true - if (this[BUFFER]) { - this[BUFFERCONCAT](chunk) - const c = this[BUFFER] - this[BUFFER] = null - 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] = null - 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 - - /* istanbul ignore next */ - default: - throw new Error('invalid state: ' + this[STATE]) - } - } - - if (position < length) { - if (this[BUFFER]) { - this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]]) - } else { - this[BUFFER] = chunk.slice(position) - } - } - } - - end (chunk) { - if (!this[ABORTED]) { - if (this[UNZIP]) { - this[UNZIP].end(chunk) - } else { - this[ENDED] = true - if (this.brotli === undefined) chunk = chunk || Buffer.alloc(0) - this.write(chunk) - } - } - } -}) diff --git a/node_modules/tar/lib/path-reservations.js b/node_modules/tar/lib/path-reservations.js deleted file mode 100644 index 8d349d584513f..0000000000000 --- a/node_modules/tar/lib/path-reservations.js +++ /dev/null @@ -1,156 +0,0 @@ -// 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. - -const assert = require('assert') -const normalize = require('./normalize-unicode.js') -const stripSlashes = require('./strip-trailing-slashes.js') -const { join } = require('path') - -const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform -const isWindows = platform === 'win32' - -module.exports = () => { - // path => [function or Set] - // A Set object means a directory reservation - // A fn is a direct reservation on that path - const queues = new Map() - - // fn => {paths:[path,...], dirs:[path, ...]} - const reservations = new Map() - - // 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) => { - if (set.length) { - path = join(set[set.length - 1], path) - } - set.push(path || '/') - return set - }, []) - return dirs - } - - // functions currently running - const running = new Set() - - // return the queues for each path the function cares about - // fn => {paths, dirs} - const getQueues = fn => { - const res = reservations.get(fn) - /* istanbul ignore if - unpossible */ - if (!res) { - throw new Error('function does not have any path reservations') - } - return { - paths: res.paths.map(path => queues.get(path)), - dirs: [...res.dirs].map(path => 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 - const check = fn => { - const { paths, dirs } = getQueues(fn) - return paths.every(q => q[0] === fn) && - dirs.every(q => q[0] instanceof Set && q[0].has(fn)) - } - - // run the function if it's first in line and not already running - const run = fn => { - if (running.has(fn) || !check(fn)) { - return false - } - running.add(fn) - fn(() => clear(fn)) - return true - } - - const clear = fn => { - if (!running.has(fn)) { - return false - } - - const { paths, dirs } = reservations.get(fn) - const next = new Set() - - paths.forEach(path => { - const q = queues.get(path) - assert.equal(q[0], fn) - if (q.length === 1) { - queues.delete(path) - } else { - q.shift() - if (typeof q[0] === 'function') { - next.add(q[0]) - } else { - q[0].forEach(fn => next.add(fn)) - } - } - }) - - dirs.forEach(dir => { - const q = queues.get(dir) - assert(q[0] instanceof Set) - if (q[0].size === 1 && q.length === 1) { - queues.delete(dir) - } else if (q[0].size === 1) { - q.shift() - - // must be a function or else the Set would've been reused - next.add(q[0]) - } else { - q[0].delete(fn) - } - }) - running.delete(fn) - - next.forEach(fn => run(fn)) - return true - } - - const reserve = (paths, fn) => { - // collide on matches across case and unicode normalization - // On windows, thanks to the magic of 8.3 shortnames, it is fundamentally - // impossible to determine whether two paths refer to the same thing on - // disk, without asking the kernel for a shortname. - // So, we just pretend that every path matches every other path here, - // effectively removing all parallelization on windows. - paths = isWindows ? ['win32 parallelization disabled'] : paths.map(p => { - // don't need normPath, because we skip this entirely for windows - return stripSlashes(join(normalize(p))).toLowerCase() - }) - - const dirs = new Set( - paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)) - ) - reservations.set(fn, { dirs, paths }) - paths.forEach(path => { - const q = queues.get(path) - if (!q) { - queues.set(path, [fn]) - } else { - q.push(fn) - } - }) - dirs.forEach(dir => { - const q = queues.get(dir) - if (!q) { - queues.set(dir, [new Set([fn])]) - } else if (q[q.length - 1] instanceof Set) { - q[q.length - 1].add(fn) - } else { - q.push(new Set([fn])) - } - }) - - return run(fn) - } - - return { check, reserve } -} diff --git a/node_modules/tar/lib/pax.js b/node_modules/tar/lib/pax.js deleted file mode 100644 index 4a7ca85386e83..0000000000000 --- a/node_modules/tar/lib/pax.js +++ /dev/null @@ -1,150 +0,0 @@ -'use strict' -const Header = require('./header.js') -const path = require('path') - -class Pax { - constructor (obj, global) { - this.atime = obj.atime || null - this.charset = obj.charset || null - this.comment = obj.comment || null - this.ctime = obj.ctime || null - this.gid = obj.gid || null - this.gname = obj.gname || null - this.linkpath = obj.linkpath || null - this.mtime = obj.mtime || null - this.path = obj.path || null - this.size = obj.size || null - this.uid = obj.uid || null - this.uname = obj.uname || null - this.dev = obj.dev || null - this.ino = obj.ino || null - this.nlink = obj.nlink || null - this.global = global || false - } - - encode () { - const body = this.encodeBody() - if (body === '') { - return null - } - - 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 - path: ('PaxHeader/' + path.basename(this.path)).slice(0, 99), - mode: this.mode || 0o644, - uid: this.uid || null, - gid: this.gid || null, - size: bodyLen, - mtime: this.mtime || null, - type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader', - linkpath: '', - uname: this.uname || '', - gname: this.gname || '', - devmaj: 0, - devmin: 0, - atime: this.atime || null, - ctime: this.ctime || null, - }).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] === null || this[field] === undefined) { - return '' - } - const v = this[field] instanceof Date ? this[field].getTime() / 1000 - : this[field] - 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 - } -} - -Pax.parse = (string, ex, g) => new Pax(merge(parseKV(string), ex), g) - -const merge = (a, b) => - b ? Object.keys(a).reduce((s, k) => (s[k] = a[k], s), b) : a - -const parseKV = string => - string - .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 k = kv.shift().replace(/^SCHILY\.(dev|ino|nlink)/, '$1') - if (!k) { - return set - } - - const v = kv.join('=') - set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) - ? new Date(v * 1000) - : /^[0-9]+$/.test(v) ? +v - : v - return set -} - -module.exports = Pax diff --git a/node_modules/tar/lib/read-entry.js b/node_modules/tar/lib/read-entry.js deleted file mode 100644 index 6186266e89c0a..0000000000000 --- a/node_modules/tar/lib/read-entry.js +++ /dev/null @@ -1,107 +0,0 @@ -'use strict' -const { Minipass } = require('minipass') -const normPath = require('./normalize-windows-path.js') - -const SLURP = Symbol('slurp') -module.exports = class ReadEntry extends Minipass { - 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 - this.startBlockSize = 512 * Math.ceil(header.size / 512) - this.blockRemain = this.startBlockSize - this.remain = header.size - this.type = header.type - this.meta = false - this.ignore = false - 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 - } - - this.path = normPath(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 = header.size - this.mtime = header.mtime - this.atime = header.atime - this.ctime = header.ctime - this.linkpath = normPath(header.linkpath) - 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.slice(0, r)) - } - - [SLURP] (ex, global) { - for (const k in ex) { - // we slurp in everything except for the path attribute in - // a global extended header, because that's weird. - if (ex[k] !== null && ex[k] !== undefined && - !(global && k === 'path')) { - this[k] = k === 'path' || k === 'linkpath' ? normPath(ex[k]) : ex[k] - } - } - } -} diff --git a/node_modules/tar/lib/replace.js b/node_modules/tar/lib/replace.js deleted file mode 100644 index 8db6800bdf464..0000000000000 --- a/node_modules/tar/lib/replace.js +++ /dev/null @@ -1,246 +0,0 @@ -'use strict' - -// tar -r -const hlo = require('./high-level-opt.js') -const Pack = require('./pack.js') -const fs = require('fs') -const fsm = require('fs-minipass') -const t = require('./list.js') -const path = require('path') - -// 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 Header = require('./header.js') - -module.exports = (opt_, files, cb) => { - const opt = hlo(opt_) - - if (!opt.file) { - 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 (!files || !Array.isArray(files) || !files.length) { - throw new TypeError('no files or directories specified') - } - - files = Array.from(files) - - return opt.sync ? replaceSync(opt, files) - : replace(opt, files, cb) -} - -const replaceSync = (opt, files) => { - const p = new Pack.Sync(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 / 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) { - opt.mtimeCache.set(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 fsm.WriteStreamSync(opt.file, { - fd: fd, - start: position, - }) - p.pipe(stream) - addFilesSync(p, files) -} - -const replace = (opt, files, cb) => { - 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) { - 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) - } - - const entryBlockSize = 512 * Math.ceil(h.size / 512) - if (position + entryBlockSize + 512 > size) { - return cb(null, position) - } - - position += entryBlockSize + 512 - if (position >= size) { - return cb(null, position) - } - - if (opt.mtimeCache) { - opt.mtimeCache.set(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) { - 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 fsm.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 cb ? promise.then(cb, cb) : promise -} - -const addFilesSync = (p, files) => { - files.forEach(file => { - if (file.charAt(0) === '@') { - t({ - file: path.resolve(p.cwd, file.slice(1)), - sync: true, - noResume: true, - onentry: entry => p.add(entry), - }) - } else { - p.add(file) - } - }) - p.end() -} - -const addFilesAsync = (p, files) => { - while (files.length) { - const file = files.shift() - if (file.charAt(0) === '@') { - return t({ - file: path.resolve(p.cwd, file.slice(1)), - noResume: true, - onentry: entry => p.add(entry), - }).then(_ => addFilesAsync(p, files)) - } else { - p.add(file) - } - } - p.end() -} diff --git a/node_modules/tar/lib/strip-absolute-path.js b/node_modules/tar/lib/strip-absolute-path.js deleted file mode 100644 index 185e2dead3929..0000000000000 --- a/node_modules/tar/lib/strip-absolute-path.js +++ /dev/null @@ -1,24 +0,0 @@ -// unix absolute paths are also absolute on win32, so we use this for both -const { isAbsolute, parse } = require('path').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'] -module.exports = 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] -} diff --git a/node_modules/tar/lib/strip-trailing-slashes.js b/node_modules/tar/lib/strip-trailing-slashes.js deleted file mode 100644 index 3e3ecec5a402b..0000000000000 --- a/node_modules/tar/lib/strip-trailing-slashes.js +++ /dev/null @@ -1,13 +0,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. -module.exports = 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) -} diff --git a/node_modules/tar/lib/types.js b/node_modules/tar/lib/types.js deleted file mode 100644 index 7bfc254658f4e..0000000000000 --- a/node_modules/tar/lib/types.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict' -// 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]])) diff --git a/node_modules/tar/lib/unpack.js b/node_modules/tar/lib/unpack.js deleted file mode 100644 index 03172e2c95d97..0000000000000 --- a/node_modules/tar/lib/unpack.js +++ /dev/null @@ -1,923 +0,0 @@ -'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.) - -const assert = require('assert') -const Parser = require('./parse.js') -const fs = require('fs') -const fsm = require('fs-minipass') -const path = require('path') -const mkdir = require('./mkdir.js') -const wc = require('./winchars.js') -const pathReservations = require('./path-reservations.js') -const stripAbsolutePath = require('./strip-absolute-path.js') -const normPath = require('./normalize-windows-path.js') -const stripSlash = require('./strip-trailing-slashes.js') -const normalize = require('./normalize-unicode.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 crypto = require('crypto') -const getFlag = require('./get-write-flag.js') -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 -/* istanbul ignore next */ -const unlinkFile = (path, cb) => { - if (!isWindows) { - return fs.unlink(path, cb) - } - - const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') - fs.rename(path, name, er => { - if (er) { - return cb(er) - } - fs.unlink(name, cb) - }) -} - -/* istanbul ignore next */ -const unlinkFileSync = path => { - if (!isWindows) { - return fs.unlinkSync(path) - } - - const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') - fs.renameSync(path, name) - fs.unlinkSync(name) -} - -// this.gid, entry.gid, this.processUid -const uint32 = (a, b, c) => - a === a >>> 0 ? a - : 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 => stripSlash(normPath(normalize(path))) - .toLowerCase() - -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 Parser { - constructor (opt) { - if (!opt) { - opt = {} - } - - opt.ondone = _ => { - this[ENDED] = true - this[MAYBECLOSE]() - } - - super(opt) - - this[CHECKED_CWD] = false - - this.reservations = pathReservations() - - this.transform = typeof opt.transform === 'function' ? opt.transform : null - - this.writable = true - this.readable = false - - this[PENDING] = 0 - this[ENDED] = false - - this.dirCache = opt.dirCache || new Map() - - 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 = null - this.gid = null - 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() : null - this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? - process.getgid() : null - - // 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 = normPath(entry.path) - const parts = p.split('/') - - if (this.strip) { - if (parts.length < this.strip) { - return false - } - if (entry.type === 'Link') { - const linkparts = normPath(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('..') || 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 = stripped - this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute path`, { - entry, - path: p, - }) - } - } - - if (path.isAbsolute(entry.path)) { - entry.absolute = normPath(path.resolve(entry.path)) - } else { - entry.absolute = normPath(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. - /* istanbul ignore if - defense in depth */ - if (!this.preservePaths && - entry.absolute.indexOf(this.cwd + '/') !== 0 && - entry.absolute !== this.cwd) { - this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', { - entry, - path: normPath(entry.path), - resolvedPath: entry.absolute, - cwd: this.cwd, - }) - return false - } - - // 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(entry.absolute) - entry.absolute = aRoot + wc.encode(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(normPath(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, - noChmod: this.noChmod, - }, 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 = entry.mode & 0o7777 || this.fmode - const stream = new fsm.WriteStream(entry.absolute, { - flags: getFlag(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) { - /* istanbul ignore else - we should always have a fd by now */ - if (stream.fd) { - fs.close(stream.fd, () => {}) - } - - this[ONERROR](er, entry) - fullyDone() - return - } - - if (--actions === 0) { - 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 = entry.absolute - const fd = stream.fd - - if (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 (this[DOCHOWN](entry)) { - actions++ - const uid = this[UID](entry) - const gid = this[GID](entry) - 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 = entry.mode & 0o7777 || this.dmode - this[MKDIR](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(entry.absolute, entry.atime || new Date(), entry.mtime, done) - } - - if (this[DOCHOWN](entry)) { - actions++ - fs.chown(entry.absolute, this[UID](entry), 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, entry.linkpath, 'symlink', done) - } - - [HARDLINK] (entry, done) { - const linkpath = normPath(path.resolve(this.cwd, 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, 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 = normPath(path.dirname(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(entry.absolute, (lstatEr, st) => { - if (st && (this.keep || this.newer && st.mtime > entry.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.noChmod && - entry.mode && - (st.mode & 0o7777) !== entry.mode - const afterChmod = er => this[MAKEFS](er, entry, done) - if (!needChmod) { - return afterChmod() - } - return fs.chmod(entry.absolute, 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(entry.absolute, er => - this[MAKEFS](er, 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(entry.absolute, er => - this[MAKEFS](er, 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, 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] - } -} -class UnpackSync extends Unpack { - [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 = normPath(path.dirname(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(entry.absolute)) - if (st && (this.keep || this.newer && st.mtime > entry.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.noChmod && - entry.mode && - (st.mode & 0o7777) !== entry.mode - const [er] = needChmod ? callSync(() => { - fs.chmodSync(entry.absolute, entry.mode) - }) : [] - return this[MAKEFS](er, entry) - } - // not a dir entry, have to remove it - const [er] = callSync(() => fs.rmdirSync(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(entry.absolute)) - this[MAKEFS](er, entry) - } - - [FILE] (entry, done) { - const mode = 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(entry.absolute, getFlag(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(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, uid, gid) - } catch (fchowner) { - try { - fs.chownSync(entry.absolute, uid, gid) - } catch (chowner) { - er = er || fchowner - } - } - } - - oner(er) - }) - } - - [DIRECTORY] (entry, done) { - const mode = entry.mode & 0o7777 || this.dmode - const er = this[MKDIR](entry.absolute, mode) - if (er) { - this[ONERROR](er, entry) - done() - return - } - if (entry.mtime && !this.noMtime) { - try { - fs.utimesSync(entry.absolute, entry.atime || new Date(), entry.mtime) - } catch (er) {} - } - if (this[DOCHOWN](entry)) { - try { - fs.chownSync(entry.absolute, this[UID](entry), this[GID](entry)) - } catch (er) {} - } - done() - entry.resume() - } - - [MKDIR] (dir, mode) { - try { - return mkdir.sync(normPath(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) { - try { - fs[link + 'Sync'](linkpath, entry.absolute) - done() - entry.resume() - } catch (er) { - return this[ONERROR](er, entry) - } - } -} - -Unpack.Sync = UnpackSync -module.exports = Unpack diff --git a/node_modules/tar/lib/update.js b/node_modules/tar/lib/update.js deleted file mode 100644 index 4d328543b315e..0000000000000 --- a/node_modules/tar/lib/update.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict' - -// tar -u - -const hlo = require('./high-level-opt.js') -const r = require('./replace.js') -// just call tar.r with the filter and mtimeCache - -module.exports = (opt_, files, cb) => { - const opt = hlo(opt_) - - if (!opt.file) { - 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 (!files || !Array.isArray(files) || !files.length) { - throw new TypeError('no files or directories specified') - } - - files = Array.from(files) - - mtimeFilter(opt) - return r(opt, files, cb) -} - -const mtimeFilter = opt => { - const filter = opt.filter - - if (!opt.mtimeCache) { - opt.mtimeCache = new Map() - } - - opt.filter = filter ? (path, stat) => - filter(path, stat) && !(opt.mtimeCache.get(path) > stat.mtime) - : (path, stat) => !(opt.mtimeCache.get(path) > stat.mtime) -} diff --git a/node_modules/tar/lib/warn-mixin.js b/node_modules/tar/lib/warn-mixin.js deleted file mode 100644 index a940639636133..0000000000000 --- a/node_modules/tar/lib/warn-mixin.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict' -module.exports = Base => class extends Base { - warn (code, message, data = {}) { - if (this.file) { - data.file = this.file - } - if (this.cwd) { - data.cwd = this.cwd - } - data.code = message instanceof Error && message.code || code - data.tarCode = code - if (!this.strict && data.recoverable !== false) { - if (message instanceof Error) { - data = Object.assign(message, data) - message = message.message - } - this.emit('warn', data.tarCode, message, data) - } else if (message instanceof Error) { - this.emit('error', Object.assign(message, data)) - } else { - this.emit('error', Object.assign(new Error(`${code}: ${message}`), data)) - } - } -} diff --git a/node_modules/tar/lib/winchars.js b/node_modules/tar/lib/winchars.js deleted file mode 100644 index ebcab4aed3e52..0000000000000 --- a/node_modules/tar/lib/winchars.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict' - -// 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]])) - -module.exports = { - encode: s => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s), - decode: s => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s), -} diff --git a/node_modules/tar/lib/write-entry.js b/node_modules/tar/lib/write-entry.js deleted file mode 100644 index 7d2f3eb1acc8c..0000000000000 --- a/node_modules/tar/lib/write-entry.js +++ /dev/null @@ -1,546 +0,0 @@ -'use strict' -const { Minipass } = require('minipass') -const Pax = require('./pax.js') -const Header = require('./header.js') -const fs = require('fs') -const path = require('path') -const normPath = require('./normalize-windows-path.js') -const stripSlash = require('./strip-trailing-slashes.js') - -const prefixPath = (path, prefix) => { - if (!prefix) { - return normPath(path) - } - path = normPath(path).replace(/^\.(\/|$)/, '') - return stripSlash(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') -const HAD_ERROR = Symbol('hadError') -const warner = require('./warn-mixin.js') -const winchars = require('./winchars.js') -const stripAbsolutePath = require('./strip-absolute-path.js') - -const modeFix = require('./mode-fix.js') - -const WriteEntry = warner(class WriteEntry extends Minipass { - constructor (p, opt) { - opt = opt || {} - super(opt) - if (typeof p !== 'string') { - throw new TypeError('path is required') - } - this.path = normPath(p) - // suppress atime, ctime, uid, gid, uname, gname - this.portable = !!opt.portable - // until node has builtin pwnam functions, this'll have to do - this.myuid = process.getuid && process.getuid() || 0 - this.myuser = process.env.USER || '' - this.maxReadSize = opt.maxReadSize || maxReadSize - this.linkCache = opt.linkCache || new Map() - this.statCache = opt.statCache || new Map() - this.preservePaths = !!opt.preservePaths - this.cwd = normPath(opt.cwd || process.cwd()) - this.strict = !!opt.strict - this.noPax = !!opt.noPax - this.noMtime = !!opt.noMtime - this.mtime = opt.mtime || null - this.prefix = opt.prefix ? normPath(opt.prefix) : null - - this.fd = null - this.blockLen = null - this.blockRemain = null - this.buf = null - this.offset = null - this.length = null - this.pos = null - this.remain = null - - if (typeof opt.onwarn === 'function') { - this.on('warn', opt.onwarn) - } - - let pathWarn = false - if (!this.preservePaths) { - const [root, stripped] = stripAbsolutePath(this.path) - if (root) { - 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 = normPath(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, - }) - } - - if (this.statCache.has(this.absolute)) { - this[ONLSTAT](this.statCache.get(this.absolute)) - } else { - this[LSTAT]() - } - } - - emit (ev, ...data) { - if (ev === 'error') { - this[HAD_ERROR] = 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] () { - if (this.type === 'Directory' && this.portable) { - this.noMtime = true - } - - this.header = new Header({ - path: this[PREFIX](this.path), - // only apply the prefix to hard links. - linkpath: this.type === 'Link' ? 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 ? null : this.stat.uid, - gid: this.portable ? null : this.stat.gid, - size: this.stat.size, - mtime: this.noMtime ? null : this.mtime || this.stat.mtime, - type: this.type, - uname: this.portable ? null : - this.stat.uid === this.myuid ? this.myuser : '', - atime: this.portable ? null : this.stat.atime, - ctime: this.portable ? null : this.stat.ctime, - }) - - if (this.header.encode() && !this.noPax) { - super.write(new Pax({ - atime: this.portable ? null : this.header.atime, - ctime: this.portable ? null : this.header.ctime, - gid: this.portable ? null : this.header.gid, - mtime: this.noMtime ? null : this.mtime || this.header.mtime, - path: this[PREFIX](this.path), - linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) - : this.linkpath, - size: this.header.size, - uid: this.portable ? null : this.header.uid, - uname: this.portable ? null : this.header.uname, - dev: this.portable ? null : this.stat.dev, - ino: this.portable ? null : this.stat.ino, - nlink: this.portable ? null : this.stat.nlink, - }).encode()) - } - super.write(this.header.block) - } - - [DIRECTORY] () { - 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 = normPath(linkpath) - this[HEADER]() - this.end() - } - - [HARDLINK] (linkpath) { - this.type = 'Link' - this.linkpath = normPath(path.relative(this.cwd, linkpath)) - this.stat.size = 0 - this[HEADER]() - this.end() - } - - [FILE] () { - if (this.stat.nlink > 1) { - const linkKey = this.stat.dev + ':' + this.stat.ino - if (this.linkCache.has(linkKey)) { - 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[HAD_ERROR]) { - return this[CLOSE]() - } - - 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 - 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) - }) - } - - [CLOSE] (cb) { - fs.close(this.fd, cb) - } - - [ONREAD] (bytesRead) { - if (bytesRead <= 0 && this.remain > 0) { - const er = new Error('encountered unexpected EOF') - er.path = this.absolute - er.syscall = 'read' - er.code = 'EOF' - return this[CLOSE](() => this.emit('error', er)) - } - - if (bytesRead > this.remain) { - const er = new Error('did not encounter expected EOF') - er.path = this.absolute - er.syscall = 'read' - er.code = 'EOF' - return this[CLOSE](() => this.emit('error', er)) - } - - // 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 writeBuf = this.offset === 0 && bytesRead === this.buf.length ? - this.buf : this.buf.slice(this.offset, this.offset + bytesRead) - - const flushed = this.write(writeBuf) - if (!flushed) { - this[AWAITDRAIN](() => this[ONDRAIN]()) - } else { - this[ONDRAIN]() - } - } - - [AWAITDRAIN] (cb) { - this.once('drain', cb) - } - - write (writeBuf) { - if (this.blockRemain < writeBuf.length) { - const er = new Error('writing more data than expected') - er.path = this.absolute - return this.emit('error', er) - } - this.remain -= writeBuf.length - this.blockRemain -= writeBuf.length - this.pos += writeBuf.length - this.offset += writeBuf.length - return super.write(writeBuf) - } - - [ONDRAIN] () { - if (!this.remain) { - if (this.blockRemain) { - super.write(Buffer.alloc(this.blockRemain)) - } - return this[CLOSE](er => er ? this.emit('error', er) : this.end()) - } - - 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]() - } -}) - -class WriteEntrySync extends WriteEntry { - [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 - 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() - } - - [CLOSE] (cb) { - fs.closeSync(this.fd) - cb() - } -} - -const WriteEntryTar = warner(class WriteEntryTar extends Minipass { - constructor (readEntry, opt) { - opt = opt || {} - super(opt) - this.preservePaths = !!opt.preservePaths - this.portable = !!opt.portable - this.strict = !!opt.strict - this.noPax = !!opt.noPax - this.noMtime = !!opt.noMtime - - this.readEntry = readEntry - this.type = readEntry.type - if (this.type === 'Directory' && this.portable) { - this.noMtime = true - } - - this.prefix = opt.prefix || null - - this.path = normPath(readEntry.path) - this.mode = this[MODE](readEntry.mode) - this.uid = this.portable ? null : readEntry.uid - this.gid = this.portable ? null : readEntry.gid - this.uname = this.portable ? null : readEntry.uname - this.gname = this.portable ? null : readEntry.gname - this.size = readEntry.size - this.mtime = this.noMtime ? null : opt.mtime || readEntry.mtime - this.atime = this.portable ? null : readEntry.atime - this.ctime = this.portable ? null : readEntry.ctime - this.linkpath = normPath(readEntry.linkpath) - - if (typeof opt.onwarn === 'function') { - this.on('warn', opt.onwarn) - } - - let pathWarn = false - if (!this.preservePaths) { - const [root, stripped] = stripAbsolutePath(this.path) - if (root) { - this.path = stripped - pathWarn = root - } - } - - this.remain = readEntry.size - this.blockRemain = readEntry.startBlockSize - - this.header = new Header({ - path: this[PREFIX](this.path), - linkpath: this.type === 'Link' ? 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 ? null : this.uid, - gid: this.portable ? null : this.gid, - size: this.size, - mtime: this.noMtime ? null : this.mtime, - type: this.type, - uname: this.portable ? null : this.uname, - atime: this.portable ? null : this.atime, - ctime: this.portable ? null : 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 ? null : this.atime, - ctime: this.portable ? null : this.ctime, - gid: this.portable ? null : this.gid, - mtime: this.noMtime ? null : this.mtime, - path: this[PREFIX](this.path), - linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) - : this.linkpath, - size: this.size, - uid: this.portable ? null : this.uid, - uname: this.portable ? null : this.uname, - dev: this.portable ? null : this.readEntry.dev, - ino: this.portable ? null : this.readEntry.ino, - nlink: this.portable ? null : this.readEntry.nlink, - }).encode()) - } - - super.write(this.header.block) - readEntry.pipe(this) - } - - [PREFIX] (path) { - return prefixPath(path, this.prefix) - } - - [MODE] (mode) { - return modeFix(mode, this.type === 'Directory', this.portable) - } - - write (data) { - const writeLen = data.length - if (writeLen > this.blockRemain) { - throw new Error('writing more to entry than is appropriate') - } - this.blockRemain -= writeLen - return super.write(data) - } - - end () { - if (this.blockRemain) { - super.write(Buffer.alloc(this.blockRemain)) - } - return super.end() - } -}) - -WriteEntry.Sync = WriteEntrySync -WriteEntry.Tar = WriteEntryTar - -const getType = stat => - stat.isFile() ? 'File' - : stat.isDirectory() ? 'Directory' - : stat.isSymbolicLink() ? 'SymbolicLink' - : 'Unsupported' - -module.exports = WriteEntry diff --git a/node_modules/tar/node_modules/fs-minipass/LICENSE b/node_modules/tar/node_modules/fs-minipass/LICENSE deleted file mode 100644 index 19129e315fe59..0000000000000 --- a/node_modules/tar/node_modules/fs-minipass/LICENSE +++ /dev/null @@ -1,15 +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. diff --git a/node_modules/tar/node_modules/fs-minipass/index.js b/node_modules/tar/node_modules/fs-minipass/index.js deleted file mode 100644 index 9b0779c80c55e..0000000000000 --- a/node_modules/tar/node_modules/fs-minipass/index.js +++ /dev/null @@ -1,422 +0,0 @@ -'use strict' -const MiniPass = require('minipass') -const EE = require('events').EventEmitter -const fs = require('fs') - -let writev = fs.writev -/* istanbul ignore next */ -if (!writev) { - // This entire block can be removed if support for earlier than Node.js - // 12.9.0 is not needed. - const binding = process.binding('fs') - const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback - - writev = (fd, iovec, pos, cb) => { - const done = (er, bw) => cb(er, bw, iovec) - const req = new FSReqWrap() - req.oncomplete = done - binding.writeBuffers(fd, iovec, pos, req) - } -} - -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, buf) => - this[_onread](er, br, buf)) - } - } - - [_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) - 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 (_) {} - } - } -} - -exports.ReadStream = ReadStream -exports.ReadStreamSync = ReadStreamSync - -exports.WriteStream = WriteStream -exports.WriteStreamSync = WriteStreamSync diff --git a/node_modules/tar/node_modules/fs-minipass/node_modules/minipass/LICENSE b/node_modules/tar/node_modules/fs-minipass/node_modules/minipass/LICENSE deleted file mode 100644 index bf1dece2e1f12..0000000000000 --- a/node_modules/tar/node_modules/fs-minipass/node_modules/minipass/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/tar/node_modules/fs-minipass/node_modules/minipass/index.js b/node_modules/tar/node_modules/fs-minipass/node_modules/minipass/index.js deleted file mode 100644 index e8797aab6cc27..0000000000000 --- a/node_modules/tar/node_modules/fs-minipass/node_modules/minipass/index.js +++ /dev/null @@ -1,649 +0,0 @@ -'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 - )) - } -} diff --git a/node_modules/tar/node_modules/fs-minipass/node_modules/minipass/package.json b/node_modules/tar/node_modules/fs-minipass/node_modules/minipass/package.json deleted file mode 100644 index 548d03fa6d5d4..0000000000000 --- a/node_modules/tar/node_modules/fs-minipass/node_modules/minipass/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/tar/node_modules/fs-minipass/package.json b/node_modules/tar/node_modules/fs-minipass/package.json deleted file mode 100644 index 2f2436cb5c3b1..0000000000000 --- a/node_modules/tar/node_modules/fs-minipass/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "fs-minipass", - "version": "2.1.0", - "main": "index.js", - "scripts": { - "test": "tap", - "preversion": "npm test", - "postversion": "npm publish", - "postpublish": "git push origin --follow-tags" - }, - "keywords": [], - "author": "Isaac Z. Schlueter (http://blog.izs.me/)", - "license": "ISC", - "repository": { - "type": "git", - "url": "git+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": "^3.0.0" - }, - "devDependencies": { - "mutate-fs": "^2.0.1", - "tap": "^14.6.4" - }, - "files": [ - "index.js" - ], - "tap": { - "check-coverage": true - }, - "engines": { - "node": ">= 8" - } -} diff --git a/node_modules/tar/node_modules/minipass/LICENSE b/node_modules/tar/node_modules/minipass/LICENSE deleted file mode 100644 index 97f8e32ed82e4..0000000000000 --- a/node_modules/tar/node_modules/minipass/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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. diff --git a/node_modules/tar/node_modules/minipass/index.js b/node_modules/tar/node_modules/minipass/index.js deleted file mode 100644 index ed07c17acd97b..0000000000000 --- a/node_modules/tar/node_modules/minipass/index.js +++ /dev/null @@ -1,702 +0,0 @@ -'use strict' -const proc = - typeof process === 'object' && process - ? process - : { - stdout: null, - stderr: null, - } -const EE = require('events') -const Stream = require('stream') -const stringdecoder = require('string_decoder') -const SD = stringdecoder.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 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 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) - } -} - -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 - if (options && options.debugExposeBuffer === true) { - Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] }) - } - if (options && options.debugExposePipes === true) { - Object.defineProperty(this, 'pipes', { get: () => this[PIPES] }) - } - this[SIGNAL] = options && options.signal - this[ABORTED] = false - if (this[SIGNAL]) { - this[SIGNAL].addEventListener('abort', () => this[ABORT]()) - if (this[SIGNAL].aborted) { - this[ABORT]() - } - } - } - - 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 - } - - // drop everything and get out of the flow completely - [ABORT]() { - this[ABORTED] = true - this.emit('abort', this[SIGNAL].reason) - this.destroy(this[SIGNAL].reason) - } - - get aborted() { - return this[ABORTED] - } - 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 : 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[OBJECTMODE]) this[BUFFERLENGTH] -= 1 - else this[BUFFERLENGTH] -= this[BUFFER][0].length - return this[BUFFER].shift() - } - - [FLUSH](noDrain) { - 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(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 !this[OBJECTMODE] && !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 - 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, 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]() { - let stopped = false - const stop = () => { - this.pause() - stopped = true - return Promise.resolve({ 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 = null - let reject = null - const onerr = er => { - this.removeListener('data', ondata) - this.removeListener('end', onend) - this.removeListener(DESTROYED, ondestroy) - stop() - reject(er) - } - const ondata = value => { - this.removeListener('error', onerr) - this.removeListener('end', onend) - this.removeListener(DESTROYED, ondestroy) - this.pause() - resolve({ value: value, done: !!this[EOF] }) - } - const onend = () => { - this.removeListener('error', onerr) - this.removeListener('data', ondata) - this.removeListener(DESTROYED, ondestroy) - stop() - 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, - throw: stop, - return: stop, - [ASYNCITERATOR]() { - return this - }, - } - } - - // for (let chunk of stream) - [ITERATOR]() { - let stopped = false - const stop = () => { - this.pause() - this.removeListener(ERROR, stop) - this.removeListener(DESTROYED, stop) - this.removeListener('end', stop) - stopped = true - return { done: true } - } - - const next = () => { - if (stopped) return stop() - const value = this.read() - return value === null ? stop() : { value } - } - this.once('end', stop) - this.once(ERROR, stop) - this.once(DESTROYED, stop) - - return { - next, - throw: stop, - return: stop, - [ITERATOR]() { - return this - }, - } - } - - 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) - // if no error to emit, still reject pending promises - else this.emit(DESTROYED) - - return this - } - - static isStream(s) { - return ( - !!s && - (s instanceof Minipass || - s instanceof Stream || - (s instanceof EE && - // readable - (typeof s.pipe === 'function' || - // writable - (typeof s.write === 'function' && typeof s.end === 'function')))) - ) - } -} - -exports.Minipass = Minipass diff --git a/node_modules/tar/node_modules/minipass/index.mjs b/node_modules/tar/node_modules/minipass/index.mjs deleted file mode 100644 index 6ef6cd8cf0703..0000000000000 --- a/node_modules/tar/node_modules/minipass/index.mjs +++ /dev/null @@ -1,702 +0,0 @@ -'use strict' -const proc = - typeof process === 'object' && process - ? process - : { - stdout: null, - stderr: null, - } -import EE from 'events' -import Stream from 'stream' -import stringdecoder from 'string_decoder' -const SD = stringdecoder.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 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 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) - } -} - -export 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 - if (options && options.debugExposeBuffer === true) { - Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] }) - } - if (options && options.debugExposePipes === true) { - Object.defineProperty(this, 'pipes', { get: () => this[PIPES] }) - } - this[SIGNAL] = options && options.signal - this[ABORTED] = false - if (this[SIGNAL]) { - this[SIGNAL].addEventListener('abort', () => this[ABORT]()) - if (this[SIGNAL].aborted) { - this[ABORT]() - } - } - } - - 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 - } - - // drop everything and get out of the flow completely - [ABORT]() { - this[ABORTED] = true - this.emit('abort', this[SIGNAL].reason) - this.destroy(this[SIGNAL].reason) - } - - get aborted() { - return this[ABORTED] - } - 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 : 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[OBJECTMODE]) this[BUFFERLENGTH] -= 1 - else this[BUFFERLENGTH] -= this[BUFFER][0].length - return this[BUFFER].shift() - } - - [FLUSH](noDrain) { - 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(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 !this[OBJECTMODE] && !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 - 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, 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]() { - let stopped = false - const stop = () => { - this.pause() - stopped = true - return Promise.resolve({ 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 = null - let reject = null - const onerr = er => { - this.removeListener('data', ondata) - this.removeListener('end', onend) - this.removeListener(DESTROYED, ondestroy) - stop() - reject(er) - } - const ondata = value => { - this.removeListener('error', onerr) - this.removeListener('end', onend) - this.removeListener(DESTROYED, ondestroy) - this.pause() - resolve({ value: value, done: !!this[EOF] }) - } - const onend = () => { - this.removeListener('error', onerr) - this.removeListener('data', ondata) - this.removeListener(DESTROYED, ondestroy) - stop() - 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, - throw: stop, - return: stop, - [ASYNCITERATOR]() { - return this - }, - } - } - - // for (let chunk of stream) - [ITERATOR]() { - let stopped = false - const stop = () => { - this.pause() - this.removeListener(ERROR, stop) - this.removeListener(DESTROYED, stop) - this.removeListener('end', stop) - stopped = true - return { done: true } - } - - const next = () => { - if (stopped) return stop() - const value = this.read() - return value === null ? stop() : { value } - } - this.once('end', stop) - this.once(ERROR, stop) - this.once(DESTROYED, stop) - - return { - next, - throw: stop, - return: stop, - [ITERATOR]() { - return this - }, - } - } - - 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) - // if no error to emit, still reject pending promises - else this.emit(DESTROYED) - - return this - } - - static isStream(s) { - return ( - !!s && - (s instanceof Minipass || - s instanceof Stream || - (s instanceof EE && - // readable - (typeof s.pipe === 'function' || - // writable - (typeof s.write === 'function' && typeof s.end === 'function')))) - ) - } -} - - diff --git a/node_modules/tar/node_modules/minipass/package.json b/node_modules/tar/node_modules/minipass/package.json deleted file mode 100644 index 0e20e988047f2..0000000000000 --- a/node_modules/tar/node_modules/minipass/package.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "name": "minipass", - "version": "5.0.0", - "description": "minimal implementation of a PassThrough stream", - "main": "./index.js", - "module": "./index.mjs", - "types": "./index.d.ts", - "exports": { - ".": { - "import": { - "types": "./index.d.ts", - "default": "./index.mjs" - }, - "require": { - "types": "./index.d.ts", - "default": "./index.js" - } - }, - "./package.json": "./package.json" - }, - "devDependencies": { - "@types/node": "^17.0.41", - "end-of-stream": "^1.4.0", - "node-abort-controller": "^3.1.1", - "prettier": "^2.6.2", - "tap": "^16.2.0", - "through2": "^2.0.3", - "ts-node": "^10.8.1", - "typedoc": "^0.23.24", - "typescript": "^4.7.3" - }, - "scripts": { - "pretest": "npm run prepare", - "presnap": "npm run prepare", - "prepare": "node ./scripts/transpile-to-esm.js", - "snap": "tap", - "test": "tap", - "preversion": "npm test", - "postversion": "npm publish", - "postpublish": "git push origin --follow-tags", - "typedoc": "typedoc ./index.d.ts", - "format": "prettier --write . --loglevel warn" - }, - "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", - "index.mjs" - ], - "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" - } -} diff --git a/node_modules/tar/package.json b/node_modules/tar/package.json index f84a41cca5af5..556b3e7d9f2fb 100644 --- a/node_modules/tar/package.json +++ b/node_modules/tar/package.json @@ -1,8 +1,8 @@ { - "author": "GitHub Inc.", + "author": "Isaac Z. Schlueter", "name": "tar", "description": "tar for node", - "version": "6.2.1", + "version": "7.5.16", "repository": { "type": "git", "url": "https://github.com/isaacs/node-tar.git" @@ -10,61 +10,289 @@ "scripts": { "genparse": "node scripts/generate-parse-fixtures.js", "snap": "tap", - "test": "tap" + "test": "tap", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "prepare": "tshy && bash scripts/build.sh", + "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", + "lint": "oxlint --fix src test", + "postsnap": "npm run lint", + "postlint": "npm run format" }, "dependencies": { - "chownr": "^2.0.0", - "fs-minipass": "^2.0.0", - "minipass": "^5.0.0", - "minizlib": "^2.1.1", - "mkdirp": "^1.0.3", - "yallist": "^4.0.0" + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.11.0", - "chmodr": "^1.2.0", + "@types/node": "^25.9.1", + "chmodr": "^2.0.2", "end-of-stream": "^1.4.3", + "esbuild": "^0.28.0", "events-to-array": "^2.0.3", "mutate-fs": "^2.1.1", - "nock": "^13.2.9", - "rimraf": "^3.0.2", - "tap": "^16.0.1" + "nock": "^13.5.4", + "oxlint": "^1.67.0", + "oxlint-tsgolint": "^0.23.0", + "prettier": "^3.8.3", + "rimraf": "^6.1.2", + "tap": "^21.7.4", + "tshy": "^4.1.2", + "typedoc": "^0.28.19" }, - "license": "ISC", + "license": "BlueOak-1.0.0", "engines": { - "node": ">=10" + "node": ">=18" }, "files": [ - "bin/", - "lib/", - "index.js" + "dist" ], - "tap": { - "coverage-map": "map.js", - "timeout": 0, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": { + "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" + } + }, + "./raw": "./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" + }, + "selfLink": false }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.11.0", - "content": "scripts/template-oss", - "engines": ">=10", - "distPaths": [ - "index.js" - ], - "allowPaths": [ - "/index.js" - ], - "ciVersions": [ - "10.x", - "12.x", - "14.x", - "16.x", - "18.x" - ] - } + "exports": { + "./package.json": "./package.json", + ".": { + "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" + } + }, + "./raw": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + }, + "./c": { + "import": { + "types": "./dist/esm/create.d.ts", + "default": "./dist/esm/create.js" + }, + "require": { + "types": "./dist/commonjs/create.d.ts", + "default": "./dist/commonjs/create.js" + } + }, + "./create": { + "import": { + "types": "./dist/esm/create.d.ts", + "default": "./dist/esm/create.js" + }, + "require": { + "types": "./dist/commonjs/create.d.ts", + "default": "./dist/commonjs/create.js" + } + }, + "./replace": { + "import": { + "types": "./dist/esm/create.d.ts", + "default": "./dist/esm/create.js" + }, + "require": { + "types": "./dist/commonjs/create.d.ts", + "default": "./dist/commonjs/create.js" + } + }, + "./r": { + "import": { + "types": "./dist/esm/create.d.ts", + "default": "./dist/esm/create.js" + }, + "require": { + "types": "./dist/commonjs/create.d.ts", + "default": "./dist/commonjs/create.js" + } + }, + "./list": { + "import": { + "types": "./dist/esm/list.d.ts", + "default": "./dist/esm/list.js" + }, + "require": { + "types": "./dist/commonjs/list.d.ts", + "default": "./dist/commonjs/list.js" + } + }, + "./t": { + "import": { + "types": "./dist/esm/list.d.ts", + "default": "./dist/esm/list.js" + }, + "require": { + "types": "./dist/commonjs/list.d.ts", + "default": "./dist/commonjs/list.js" + } + }, + "./update": { + "import": { + "types": "./dist/esm/update.d.ts", + "default": "./dist/esm/update.js" + }, + "require": { + "types": "./dist/commonjs/update.d.ts", + "default": "./dist/commonjs/update.js" + } + }, + "./u": { + "import": { + "types": "./dist/esm/update.d.ts", + "default": "./dist/esm/update.js" + }, + "require": { + "types": "./dist/commonjs/update.d.ts", + "default": "./dist/commonjs/update.js" + } + }, + "./extract": { + "import": { + "types": "./dist/esm/extract.d.ts", + "default": "./dist/esm/extract.js" + }, + "require": { + "types": "./dist/commonjs/extract.d.ts", + "default": "./dist/commonjs/extract.js" + } + }, + "./x": { + "import": { + "types": "./dist/esm/extract.d.ts", + "default": "./dist/esm/extract.js" + }, + "require": { + "types": "./dist/commonjs/extract.d.ts", + "default": "./dist/commonjs/extract.js" + } + }, + "./pack": { + "import": { + "types": "./dist/esm/pack.d.ts", + "default": "./dist/esm/pack.js" + }, + "require": { + "types": "./dist/commonjs/pack.d.ts", + "default": "./dist/commonjs/pack.js" + } + }, + "./unpack": { + "import": { + "types": "./dist/esm/unpack.d.ts", + "default": "./dist/esm/unpack.js" + }, + "require": { + "types": "./dist/commonjs/unpack.d.ts", + "default": "./dist/commonjs/unpack.js" + } + }, + "./parse": { + "import": { + "types": "./dist/esm/parse.d.ts", + "default": "./dist/esm/parse.js" + }, + "require": { + "types": "./dist/commonjs/parse.d.ts", + "default": "./dist/commonjs/parse.js" + } + }, + "./read-entry": { + "import": { + "types": "./dist/esm/read-entry.d.ts", + "default": "./dist/esm/read-entry.js" + }, + "require": { + "types": "./dist/commonjs/read-entry.d.ts", + "default": "./dist/commonjs/read-entry.js" + } + }, + "./write-entry": { + "import": { + "types": "./dist/esm/write-entry.d.ts", + "default": "./dist/esm/write-entry.js" + }, + "require": { + "types": "./dist/commonjs/write-entry.d.ts", + "default": "./dist/commonjs/write-entry.js" + } + }, + "./header": { + "import": { + "types": "./dist/esm/header.d.ts", + "default": "./dist/esm/header.js" + }, + "require": { + "types": "./dist/commonjs/header.d.ts", + "default": "./dist/commonjs/header.js" + } + }, + "./pax": { + "import": { + "types": "./dist/esm/pax.d.ts", + "default": "./dist/esm/pax.js" + }, + "require": { + "types": "./dist/commonjs/pax.d.ts", + "default": "./dist/commonjs/pax.js" + } + }, + "./types": { + "import": { + "types": "./dist/esm/types.d.ts", + "default": "./dist/esm/types.js" + }, + "require": { + "types": "./dist/commonjs/types.d.ts", + "default": "./dist/commonjs/types.js" + } + } + }, + "type": "module", + "main": "./dist/commonjs/index.min.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.min.js" } diff --git a/node_modules/tiny-relative-date/lib/factory.js b/node_modules/tiny-relative-date/lib/factory.js index ac901614457c9..bde0b693690f9 100644 --- a/node_modules/tiny-relative-date/lib/factory.js +++ b/node_modules/tiny-relative-date/lib/factory.js @@ -32,7 +32,7 @@ function relativeDateFactory(translations) { delta = calculateDelta(now, date); } - var translate = function translate(translatePhrase, timeValue) { + var translate = function translate(translatePhrase, timeValue, rawValue) { var key = void 0; if (translatePhrase === 'justNow') { @@ -46,7 +46,7 @@ function relativeDateFactory(translations) { var translation = translations[key]; if (typeof translation === 'function') { - return translation(timeValue); + return translation(timeValue, rawValue); } return translation.replace('{{time}}', timeValue); @@ -54,46 +54,46 @@ function relativeDateFactory(translations) { switch (false) { case !(delta < 30): - return translate('justNow'); + return translate('justNow', delta, delta); case !(delta < minute): - return translate('seconds', delta); + return translate('seconds', delta, delta); case !(delta < 2 * minute): - return translate('aMinute'); + return translate('aMinute', 1, delta); case !(delta < hour): - return translate('minutes', Math.floor(delta / minute)); + return translate('minutes', Math.floor(delta / minute), delta); case Math.floor(delta / hour) !== 1: - return translate('anHour'); + return translate('anHour', Math.floor(delta / minute), delta); case !(delta < day): - return translate('hours', Math.floor(delta / hour)); + return translate('hours', Math.floor(delta / hour), delta); case !(delta < day * 2): - return translate('aDay'); + return translate('aDay', 1, delta); case !(delta < week): - return translate('days', Math.floor(delta / day)); + return translate('days', Math.floor(delta / day), delta); case Math.floor(delta / week) !== 1: - return translate('aWeek'); + return translate('aWeek', 1, delta); case !(delta < month): - return translate('weeks', Math.floor(delta / week)); + return translate('weeks', Math.floor(delta / week), delta); case Math.floor(delta / month) !== 1: - return translate('aMonth'); + return translate('aMonth', 1, delta); case !(delta < year): - return translate('months', Math.floor(delta / month)); + return translate('months', Math.floor(delta / month), delta); case Math.floor(delta / year) !== 1: - return translate('aYear'); + return translate('aYear', 1, delta); default: - return translate('overAYear'); + return translate('overAYear', Math.floor(delta / year), delta); } }; } diff --git a/node_modules/tiny-relative-date/package.json b/node_modules/tiny-relative-date/package.json index 26c88147f9e69..deb0cea29a4bd 100644 --- a/node_modules/tiny-relative-date/package.json +++ b/node_modules/tiny-relative-date/package.json @@ -1,14 +1,14 @@ { "name": "tiny-relative-date", - "version": "1.3.0", + "version": "2.0.2", "description": "Tiny function that provides relative, human-readable dates.", "main": "lib/index.js", "module": "src/index.js", "scripts": { - "build": "babel src -d lib", + "build": "babel src -d lib && cp src/*.d.ts lib/", "test": "npm run eslint && npm run jasmine", - "eslint": "eslint --fix src/**/*.js", - "jasmine": "jasmine", + "eslint": "eslint --fix src/**/*.js spec/*.js", + "jasmine": "TZ=UTC jasmine", "prepublish": "npm run build" }, "files": [ @@ -23,17 +23,17 @@ "url": "https://github.com/wildlyinaccurate/relative-date.git" }, "devDependencies": { - "babel-cli": "^6.24.1", + "babel-cli": "^6.26.0", "babel-plugin-add-module-exports": "^0.2.1", "babel-preset-es2015": "^6.24.1", - "babel-register": "^6.24.1", - "eslint": "^4.1.0", - "eslint-config-standard": "^10.2.1", - "eslint-plugin-import": "^2.6.0", - "eslint-plugin-node": "^5.0.0", - "eslint-plugin-promise": "^3.5.0", + "babel-register": "^6.26.0", + "eslint": "^4.19.1", + "eslint-config-standard": "^11.0.0", + "eslint-plugin-import": "^2.11.0", + "eslint-plugin-node": "^6.0.1", + "eslint-plugin-promise": "^3.7.0", "eslint-plugin-standard": "^3.0.1", - "jasmine": "^2.6.0", - "jasmine-spec-reporter": "^4.1.1" + "jasmine": "^3.1.0", + "jasmine-spec-reporter": "^4.2.1" } } diff --git a/node_modules/tiny-relative-date/src/factory.js b/node_modules/tiny-relative-date/src/factory.js index 689359bcf9bc9..65d310c9444a0 100644 --- a/node_modules/tiny-relative-date/src/factory.js +++ b/node_modules/tiny-relative-date/src/factory.js @@ -1,89 +1,112 @@ const calculateDelta = (now, date) => Math.round(Math.abs(now - date) / 1000) +const minute = 60 +const hour = minute * 60 +const day = hour * 24 +const week = day * 7 +const month = day * 30 +const year = day * 365 + export default function relativeDateFactory (translations) { - return function relativeDate (date, now = new Date()) { - if (!(date instanceof Date)) { - date = new Date(date) + const translate = (date, now, translatePhrase, timeValue, rawValue) => { + let key + + if (translatePhrase === 'justNow') { + key = translatePhrase + } else if (now >= date) { + key = `${translatePhrase}Ago` + } else { + key = `${translatePhrase}FromNow` } - let delta = null + const translation = translations[key] - const minute = 60 - const hour = minute * 60 - const day = hour * 24 - const week = day * 7 - const month = day * 30 - const year = day * 365 - - delta = calculateDelta(now, date) - - if (delta > day && delta < week) { - date = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0) - delta = calculateDelta(now, date) + if (typeof translation === 'function') { + return translation(timeValue, rawValue) } - const translate = (translatePhrase, timeValue) => { - let key - - if (translatePhrase === 'justNow') { - key = translatePhrase - } else if (now >= date) { - key = `${translatePhrase}Ago` - } else { - key = `${translatePhrase}FromNow` - } + return translation.replace('{{time}}', timeValue) + } - const translation = translations[key] + return function relativeDate (date, now = new Date()) { + if (!(date instanceof Date)) { + date = new Date(date) + } - if (typeof translation === 'function') { - return translation(timeValue) - } + let delta = calculateDelta(now, date) - return translation.replace('{{time}}', timeValue) + if (delta > day && delta < week) { + date = new Date( + date.getFullYear(), + date.getMonth(), + date.getDate(), + 0, + 0, + 0 + ) + delta = calculateDelta(now, date) } switch (false) { case !(delta < 30): - return translate('justNow') + return translate(date, now, 'justNow', delta, delta) case !(delta < minute): - return translate('seconds', delta) + return translate(date, now, 'seconds', delta, delta) case !(delta < 2 * minute): - return translate('aMinute') + return translate(date, now, 'aMinute', 1, delta) case !(delta < hour): - return translate('minutes', Math.floor(delta / minute)) + return translate( + date, + now, + 'minutes', + Math.floor(delta / minute), + delta + ) case Math.floor(delta / hour) !== 1: - return translate('anHour') + return translate( + date, + now, + 'anHour', + Math.floor(delta / minute), + delta + ) case !(delta < day): - return translate('hours', Math.floor(delta / hour)) + return translate(date, now, 'hours', Math.floor(delta / hour), delta) case !(delta < day * 2): - return translate('aDay') + return translate(date, now, 'aDay', 1, delta) case !(delta < week): - return translate('days', Math.floor(delta / day)) + return translate(date, now, 'days', Math.floor(delta / day), delta) case Math.floor(delta / week) !== 1: - return translate('aWeek') + return translate(date, now, 'aWeek', 1, delta) case !(delta < month): - return translate('weeks', Math.floor(delta / week)) + return translate(date, now, 'weeks', Math.floor(delta / week), delta) case Math.floor(delta / month) !== 1: - return translate('aMonth') + return translate(date, now, 'aMonth', 1, delta) case !(delta < year): - return translate('months', Math.floor(delta / month)) + return translate(date, now, 'months', Math.floor(delta / month), delta) case Math.floor(delta / year) !== 1: - return translate('aYear') + return translate(date, now, 'aYear', 1, delta) default: - return translate('overAYear') + return translate( + date, + now, + 'overAYear', + Math.floor(delta / year), + delta + ) } } } diff --git a/node_modules/tiny-relative-date/translations/fa.js b/node_modules/tiny-relative-date/translations/fa.js new file mode 100644 index 0000000000000..2a92ba19bab95 --- /dev/null +++ b/node_modules/tiny-relative-date/translations/fa.js @@ -0,0 +1,31 @@ +module.exports = { + justNow: "اکنون", + secondsAgo: "{{time}} ثانیه قبل", + aMinuteAgo: "یک دقیقه قبل", + minutesAgo: "{{time}} دقیقه قبل", + anHourAgo: "یک ساعت قبل", + hoursAgo: "{{time}} ساعت قبل", + aDayAgo: "دیروز", + daysAgo: "{{time}} روز قبل", + aWeekAgo: "یک هفته قبل", + weeksAgo: "{{time}} هفته قبل", + aMonthAgo: "یک ماه قبل", + monthsAgo: "{{time}} ماه قبل", + aYearAgo: "یک سال قبل", + yearsAgo: "{{time}} سال قبل", + overAYearAgo: "بیش از یک سال قبل", + secondsFromNow: "{{time}} ثانیه بعد", + aMinuteFromNow: "یک دقیقه بعد", + minutesFromNow: "{{time}} دقیقه بعد", + anHourFromNow: "an hour from now", + hoursFromNow: "{{time}} ساعت بعد", + aDayFromNow: "فردا", + daysFromNow: "{{time}} روز بعد", + aWeekFromNow: "یک هفته بعد", + weeksFromNow: "{{time}} هفته بعد", + aMonthFromNow: "یک ماه بعد", + monthsFromNow: "{{time}} ماه بعد", + aYearFromNow: "یک سال بعد", + yearsFromNow: "{{time}} سال بعد", + overAYearFromNow: "بیش از یک سال بعد" +} diff --git a/node_modules/tiny-relative-date/translations/ne.js b/node_modules/tiny-relative-date/translations/ne.js new file mode 100644 index 0000000000000..331128ced0e9a --- /dev/null +++ b/node_modules/tiny-relative-date/translations/ne.js @@ -0,0 +1,31 @@ +module.exports = { + justNow: 'भर्खर', + secondsAgo: '{{time}} सेकेण्ड अघि', + aMinuteAgo: '१ मिनेट अघि', + minutesAgo: '{{time}} मिनेट अघि', + anHourAgo: '१ घण्टा अघि', + hoursAgo: '{{time}} घण्टा अघि', + aDayAgo: 'हिजो', + daysAgo: '{{time}} दिन अघि', + aWeekAgo: '१ हप्ता अघि', + weeksAgo: '{{time}} हप्ता अघि', + aMonthAgo: '१ महिना अघि', + monthsAgo: '{{time}} महिना अघि', + aYearAgo: '१ वर्ष अघि', + yearsAgo: '{{time}} वर्ष अघि', + overAYearAgo: '१ वर्षभन्दा धेरै', + secondsFromNow: 'अहिलेदेखि {{time}} सेकेण्ड', + aMinuteFromNow: 'अहिलेदेखि १ मिनेट', + minutesFromNow: 'अहिलेदेखि {{time}} मिनेट', + anHourFromNow: 'अहिलेदेखि १ घण्टा', + hoursFromNow: 'अहिलेदेखि {{time}} घण्टा', + aDayFromNow: 'भोलि', + daysFromNow: 'अहिलेदेखि {{time}} दिन', + aWeekFromNow: 'अहिलेदेखि १ हप्ता', + weeksFromNow: 'अहिलेदेखि {{time}} हप्ता', + aMonthFromNow: 'अहिलेदेखि १ महिना', + monthsFromNow: 'अहिलेदेखि {{time}} महिना', + aYearFromNow: 'अहिलेदेखि १ वर्ष', + yearsFromNow: 'अहिलेदेखि {{time}} वर्ष', + overAYearFromNow: 'अहिलेदेखि १ वर्ष भन्दा धेरै' +} diff --git a/node_modules/tinyglobby/LICENSE b/node_modules/tinyglobby/LICENSE new file mode 100644 index 0000000000000..8657364bb085e --- /dev/null +++ b/node_modules/tinyglobby/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Madeline Gurriarán + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/tinyglobby/dist/index.cjs b/node_modules/tinyglobby/dist/index.cjs new file mode 100644 index 0000000000000..5badacb548b2d --- /dev/null +++ b/node_modules/tinyglobby/dist/index.cjs @@ -0,0 +1,334 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +//#region \0rolldown/runtime.js +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); +//#endregion +let fs = require("fs"); +let path = require("path"); +let url = require("url"); +let fdir = require("fdir"); +let picomatch = require("picomatch"); +picomatch = __toESM(picomatch); +//#region src/utils.ts +const isReadonlyArray = Array.isArray; +const BACKSLASHES = /\\/g; +const isWin = process.platform === "win32"; +const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/; +function getPartialMatcher(patterns, options = {}) { + const patternsCount = patterns.length; + const patternsParts = Array(patternsCount); + const matchers = Array(patternsCount); + let i, j; + for (i = 0; i < patternsCount; i++) { + const parts = splitPattern(patterns[i]); + patternsParts[i] = parts; + const partsCount = parts.length; + const partMatchers = Array(partsCount); + for (j = 0; j < partsCount; j++) partMatchers[j] = (0, picomatch.default)(parts[j], options); + matchers[i] = partMatchers; + } + return (input) => { + const inputParts = input.split("/"); + if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true; + for (i = 0; i < patternsCount; i++) { + const patternParts = patternsParts[i]; + const matcher = matchers[i]; + const inputPatternCount = inputParts.length; + const minParts = Math.min(inputPatternCount, patternParts.length); + j = 0; + while (j < minParts) { + const part = patternParts[j]; + if (part.includes("/")) return true; + if (!matcher[j](inputParts[j])) break; + if (!options.noglobstar && part === "**") return true; + j++; + } + if (j === inputPatternCount) return true; + } + return false; + }; +} +/* node:coverage ignore next 2 */ +const WIN32_ROOT_DIR = /^[A-Z]:\/$/i; +const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/"; +function buildFormat(cwd, root, absolute) { + if (cwd === root || root.startsWith(`${cwd}/`)) { + if (absolute) { + const start = cwd.length + +!isRoot(cwd); + return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || "."; + } + const prefix = root.slice(cwd.length + 1); + if (prefix) return (p, isDir) => { + if (p === ".") return prefix; + const result = `${prefix}/${p}`; + return isDir ? result.slice(0, -1) : result; + }; + return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p; + } + if (absolute) return (p) => path.posix.relative(cwd, p) || "."; + return (p) => path.posix.relative(cwd, `${root}/${p}`) || "."; +} +function buildRelative(cwd, root) { + if (root.startsWith(`${cwd}/`)) { + const prefix = root.slice(cwd.length + 1); + return (p) => `${prefix}/${p}`; + } + return (p) => { + const result = path.posix.relative(cwd, `${root}/${p}`); + return p[p.length - 1] === "/" && result !== "" ? `${result}/` : result || "."; + }; +} +const splitPatternOptions = { parts: true }; +function splitPattern(path$1) { + var _result$parts; + const result = picomatch.default.scan(path$1, splitPatternOptions); + return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path$1]; +} +const ESCAPED_WIN32_BACKSLASHES = /\\(?![()[\]{}!+@])/g; +function convertPosixPathToPattern(path$2) { + return escapePosixPath(path$2); +} +function convertWin32PathToPattern(path$3) { + return escapeWin32Path(path$3).replace(ESCAPED_WIN32_BACKSLASHES, "/"); +} +/** +* Converts a path to a pattern depending on the platform. +* Identical to {@link escapePath} on POSIX systems. +* @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern} +*/ +/* node:coverage ignore next 3 */ +const convertPathToPattern = isWin ? convertWin32PathToPattern : convertPosixPathToPattern; +const POSIX_UNESCAPED_GLOB_SYMBOLS = /(? path$4.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&"); +const escapeWin32Path = (path$5) => path$5.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&"); +/** +* Escapes a path's special characters depending on the platform. +* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath} +*/ +/* node:coverage ignore next */ +const escapePath = isWin ? escapeWin32Path : escapePosixPath; +/** +* Checks if a pattern has dynamic parts. +* +* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy: +* +* - Doesn't necessarily return `false` on patterns that include `\`. +* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not. +* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`. +* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`. +* +* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern} +*/ +function isDynamicPattern(pattern, options) { + if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true; + const scan = picomatch.default.scan(pattern); + return scan.isGlob || scan.negated; +} +function log(...tasks) { + console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks); +} +function ensureStringArray(value) { + return typeof value === "string" ? [value] : value !== null && value !== void 0 ? value : []; +} +//#endregion +//#region src/patterns.ts +const PARENT_DIRECTORY = /^(\/?\.\.)+/; +const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g; +function normalizePattern(pattern, opts, props, isIgnore) { + var _PARENT_DIRECTORY$exe; + const cwd = opts.cwd; + let result = pattern; + if (pattern[pattern.length - 1] === "/") result = pattern.slice(0, -1); + if (result[result.length - 1] !== "*" && opts.expandDirectories) result += "/**"; + const escapedCwd = escapePath(cwd); + result = (0, path.isAbsolute)(result.replace(ESCAPING_BACKSLASHES, "")) ? path.posix.relative(escapedCwd, result) : path.posix.normalize(result); + const parentDir = (_PARENT_DIRECTORY$exe = PARENT_DIRECTORY.exec(result)) === null || _PARENT_DIRECTORY$exe === void 0 ? void 0 : _PARENT_DIRECTORY$exe[0]; + const parts = splitPattern(result); + if (parentDir) { + const n = (parentDir.length + 1) / 3; + let i = 0; + const cwdParts = escapedCwd.split("/"); + while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) { + result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || "."; + i++; + } + const potentialRoot = path.posix.join(cwd, parentDir.slice(i * 3)); + if (potentialRoot[0] !== "." && props.root.length > potentialRoot.length) { + props.root = potentialRoot; + props.depthOffset = -n + i; + } + } + if (!isIgnore && props.depthOffset >= 0) { + var _props$commonPath; + (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts); + const newCommonPath = []; + const length = Math.min(props.commonPath.length, parts.length); + for (let i = 0; i < length; i++) { + const part = parts[i]; + if (part === "**" && !parts[i + 1]) { + newCommonPath.pop(); + break; + } + if (i === parts.length - 1 || part !== props.commonPath[i] || isDynamicPattern(part)) break; + newCommonPath.push(part); + } + props.depthOffset = newCommonPath.length; + props.commonPath = newCommonPath; + props.root = newCommonPath.length > 0 ? path.posix.join(cwd, ...newCommonPath) : cwd; + } + return result; +} +function processPatterns(options, patterns, props) { + const matchPatterns = []; + const ignorePatterns = []; + for (const pattern of options.ignore) { + if (!pattern) continue; + if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, options, props, true)); + } + for (const pattern of patterns) { + if (!pattern) continue; + if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, options, props, false)); + else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), options, props, true)); + } + return { + match: matchPatterns, + ignore: ignorePatterns + }; +} +//#endregion +//#region src/crawler.ts +function buildCrawler(options, patterns) { + const cwd = options.cwd; + const props = { + root: cwd, + depthOffset: 0 + }; + const processed = processPatterns(options, patterns, props); + if (options.debug) log("internal processing patterns:", processed); + const { absolute, caseSensitiveMatch, debug, dot, followSymbolicLinks, onlyDirectories } = options; + const root = props.root.replace(BACKSLASHES, ""); + const matchOptions = { + dot, + nobrace: options.braceExpansion === false, + nocase: !caseSensitiveMatch, + noextglob: options.extglob === false, + noglobstar: options.globstar === false, + posix: true + }; + const matcher = (0, picomatch.default)(processed.match, matchOptions); + const ignore = (0, picomatch.default)(processed.ignore, matchOptions); + const partialMatcher = getPartialMatcher(processed.match, matchOptions); + const format = buildFormat(cwd, root, absolute); + const excludeFormatter = absolute ? format : buildFormat(cwd, root, true); + const excludePredicate = (_, p) => { + const relativePath = excludeFormatter(p, true); + return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath); + }; + let maxDepth; + if (options.deep !== void 0) maxDepth = Math.round(options.deep - props.depthOffset); + const crawler = new fdir.fdir({ + filters: [debug ? (p, isDirectory) => { + const path = format(p, isDirectory); + const matches = matcher(path) && !ignore(path); + if (matches) log(`matched ${path}`); + return matches; + } : (p, isDirectory) => { + const path = format(p, isDirectory); + return matcher(path) && !ignore(path); + }], + exclude: debug ? (_, p) => { + const skipped = excludePredicate(_, p); + log(`${skipped ? "skipped" : "crawling"} ${p}`); + return skipped; + } : excludePredicate, + fs: options.fs, + pathSeparator: "/", + relativePaths: !absolute, + resolvePaths: absolute, + includeBasePath: absolute, + resolveSymlinks: followSymbolicLinks, + excludeSymlinks: !followSymbolicLinks, + excludeFiles: onlyDirectories, + includeDirs: onlyDirectories || !options.onlyFiles, + maxDepth, + signal: options.signal + }).crawl(root); + if (options.debug) log("internal properties:", { + ...props, + root + }); + return [crawler, cwd !== root && !absolute && buildRelative(cwd, root)]; +} +//#endregion +//#region src/index.ts +function formatPaths(paths, mapper) { + if (mapper) for (let i = paths.length - 1; i >= 0; i--) paths[i] = mapper(paths[i]); + return paths; +} +const defaultOptions = { + caseSensitiveMatch: true, + cwd: process.cwd(), + debug: !!process.env.TINYGLOBBY_DEBUG, + expandDirectories: true, + followSymbolicLinks: true, + onlyFiles: true +}; +function getOptions(options) { + const opts = { + ...defaultOptions, + ...options + }; + opts.cwd = (opts.cwd instanceof URL ? (0, url.fileURLToPath)(opts.cwd) : (0, path.resolve)(opts.cwd)).replace(BACKSLASHES, "/"); + opts.ignore = ensureStringArray(opts.ignore); + opts.fs && (opts.fs = { + readdir: opts.fs.readdir || fs.readdir, + readdirSync: opts.fs.readdirSync || fs.readdirSync, + realpath: opts.fs.realpath || fs.realpath, + realpathSync: opts.fs.realpathSync || fs.realpathSync, + stat: opts.fs.stat || fs.stat, + statSync: opts.fs.statSync || fs.statSync + }); + if (opts.debug) log("globbing with options:", opts); + return opts; +} +function getCrawler(globInput, inputOptions = {}) { + var _ref; + if (globInput && (inputOptions === null || inputOptions === void 0 ? void 0 : inputOptions.patterns)) throw new Error("Cannot pass patterns as both an argument and an option"); + const isModern = isReadonlyArray(globInput) || typeof globInput === "string"; + const patterns = ensureStringArray((_ref = isModern ? globInput : globInput.patterns) !== null && _ref !== void 0 ? _ref : "**/*"); + const options = getOptions(isModern ? inputOptions : globInput); + return patterns.length > 0 ? buildCrawler(options, patterns) : []; +} +async function glob(globInput, options) { + const [crawler, relative] = getCrawler(globInput, options); + return crawler ? formatPaths(await crawler.withPromise(), relative) : []; +} +function globSync(globInput, options) { + const [crawler, relative] = getCrawler(globInput, options); + return crawler ? formatPaths(crawler.sync(), relative) : []; +} +//#endregion +exports.convertPathToPattern = convertPathToPattern; +exports.escapePath = escapePath; +exports.glob = glob; +exports.globSync = globSync; +exports.isDynamicPattern = isDynamicPattern; diff --git a/node_modules/tinyglobby/dist/index.d.cts b/node_modules/tinyglobby/dist/index.d.cts new file mode 100644 index 0000000000000..3e8e16aa2e93e --- /dev/null +++ b/node_modules/tinyglobby/dist/index.d.cts @@ -0,0 +1,148 @@ +import { FSLike } from "fdir"; + +//#region src/types.d.ts +type FileSystemAdapter = Partial; +interface GlobOptions { + /** + * Whether to return absolute paths. Disable to have relative paths. + * @default false + */ + absolute?: boolean; + /** + * Enables support for brace expansion syntax, like `{a,b}` or `{1..9}`. + * @default true + */ + braceExpansion?: boolean; + /** + * Whether to match in case-sensitive mode. + * @default true + */ + caseSensitiveMatch?: boolean; + /** + * The working directory in which to search. Results will be returned relative to this directory, unless + * {@link absolute} is set. + * + * It is important to avoid globbing outside this directory when possible, even with absolute paths enabled, + * as doing so can harm performance due to having to recalculate relative paths. + * @default process.cwd() + */ + cwd?: string | URL; + /** + * Logs useful debug information. Meant for development purposes. Logs can change at any time. + * @default false + */ + debug?: boolean; + /** + * Maximum directory depth to crawl. + * @default Infinity + */ + deep?: number; + /** + * Whether to return entries that start with a dot, like `.gitignore` or `.prettierrc`. + * @default false + */ + dot?: boolean; + /** + * Whether to automatically expand directory patterns. + * + * Important to disable if migrating from [`fast-glob`](https://github.com/mrmlnc/fast-glob). + * @default true + */ + expandDirectories?: boolean; + /** + * Enables support for extglobs, like `+(pattern)`. + * @default true + */ + extglob?: boolean; + /** + * Whether to traverse and include symbolic links. Can slightly affect performance. + * @default true + */ + followSymbolicLinks?: boolean; + /** + * An object that overrides `node:fs` functions. + * @default import('node:fs') + */ + fs?: FileSystemAdapter; + /** + * Enables support for matching nested directories with globstars (`**`). + * If `false`, `**` behaves exactly like `*`. + * @default true + */ + globstar?: boolean; + /** + * Glob patterns to exclude from the results. + * @default [] + */ + ignore?: string | readonly string[]; + /** + * Enable to only return directories. + * If `true`, disables {@link onlyFiles}. + * @default false + */ + onlyDirectories?: boolean; + /** + * Enable to only return files. + * @default true + */ + onlyFiles?: boolean; + /** + * @deprecated Provide patterns as the first argument instead. + */ + patterns?: string | readonly string[]; + /** + * An `AbortSignal` to abort crawling the file system. + * @default undefined + */ + signal?: AbortSignal; +} +//#endregion +//#region src/utils.d.ts +/** +* Converts a path to a pattern depending on the platform. +* Identical to {@link escapePath} on POSIX systems. +* @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern} +*/ +declare const convertPathToPattern: (path: string) => string; +/** +* Escapes a path's special characters depending on the platform. +* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath} +*/ +declare const escapePath: (path: string) => string; +/** +* Checks if a pattern has dynamic parts. +* +* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy: +* +* - Doesn't necessarily return `false` on patterns that include `\`. +* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not. +* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`. +* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`. +* +* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern} +*/ +declare function isDynamicPattern(pattern: string, options?: { + caseSensitiveMatch: boolean; +}): boolean; +//#endregion +//#region src/index.d.ts +/** +* Asynchronously match files following a glob pattern. +* @see {@link https://superchupu.dev/tinyglobby/documentation#glob} +*/ +declare function glob(patterns: string | readonly string[], options?: Omit): Promise; +/** +* @deprecated Provide patterns as the first argument instead. +*/ +declare function glob(options: GlobOptions): Promise; +/** +* Synchronously match files following a glob pattern. +* @see {@link https://superchupu.dev/tinyglobby/documentation#globSync} +*/ +declare function globSync(patterns: string | readonly string[], options?: Omit): string[]; +/** +* @deprecated Provide patterns as the first argument instead. +*/ +declare function globSync(options: GlobOptions): string[]; +//#endregion +export { type GlobOptions, convertPathToPattern, escapePath, glob, globSync, isDynamicPattern }; \ No newline at end of file diff --git a/node_modules/tinyglobby/dist/index.d.mts b/node_modules/tinyglobby/dist/index.d.mts new file mode 100644 index 0000000000000..3e8e16aa2e93e --- /dev/null +++ b/node_modules/tinyglobby/dist/index.d.mts @@ -0,0 +1,148 @@ +import { FSLike } from "fdir"; + +//#region src/types.d.ts +type FileSystemAdapter = Partial; +interface GlobOptions { + /** + * Whether to return absolute paths. Disable to have relative paths. + * @default false + */ + absolute?: boolean; + /** + * Enables support for brace expansion syntax, like `{a,b}` or `{1..9}`. + * @default true + */ + braceExpansion?: boolean; + /** + * Whether to match in case-sensitive mode. + * @default true + */ + caseSensitiveMatch?: boolean; + /** + * The working directory in which to search. Results will be returned relative to this directory, unless + * {@link absolute} is set. + * + * It is important to avoid globbing outside this directory when possible, even with absolute paths enabled, + * as doing so can harm performance due to having to recalculate relative paths. + * @default process.cwd() + */ + cwd?: string | URL; + /** + * Logs useful debug information. Meant for development purposes. Logs can change at any time. + * @default false + */ + debug?: boolean; + /** + * Maximum directory depth to crawl. + * @default Infinity + */ + deep?: number; + /** + * Whether to return entries that start with a dot, like `.gitignore` or `.prettierrc`. + * @default false + */ + dot?: boolean; + /** + * Whether to automatically expand directory patterns. + * + * Important to disable if migrating from [`fast-glob`](https://github.com/mrmlnc/fast-glob). + * @default true + */ + expandDirectories?: boolean; + /** + * Enables support for extglobs, like `+(pattern)`. + * @default true + */ + extglob?: boolean; + /** + * Whether to traverse and include symbolic links. Can slightly affect performance. + * @default true + */ + followSymbolicLinks?: boolean; + /** + * An object that overrides `node:fs` functions. + * @default import('node:fs') + */ + fs?: FileSystemAdapter; + /** + * Enables support for matching nested directories with globstars (`**`). + * If `false`, `**` behaves exactly like `*`. + * @default true + */ + globstar?: boolean; + /** + * Glob patterns to exclude from the results. + * @default [] + */ + ignore?: string | readonly string[]; + /** + * Enable to only return directories. + * If `true`, disables {@link onlyFiles}. + * @default false + */ + onlyDirectories?: boolean; + /** + * Enable to only return files. + * @default true + */ + onlyFiles?: boolean; + /** + * @deprecated Provide patterns as the first argument instead. + */ + patterns?: string | readonly string[]; + /** + * An `AbortSignal` to abort crawling the file system. + * @default undefined + */ + signal?: AbortSignal; +} +//#endregion +//#region src/utils.d.ts +/** +* Converts a path to a pattern depending on the platform. +* Identical to {@link escapePath} on POSIX systems. +* @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern} +*/ +declare const convertPathToPattern: (path: string) => string; +/** +* Escapes a path's special characters depending on the platform. +* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath} +*/ +declare const escapePath: (path: string) => string; +/** +* Checks if a pattern has dynamic parts. +* +* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy: +* +* - Doesn't necessarily return `false` on patterns that include `\`. +* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not. +* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`. +* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`. +* +* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern} +*/ +declare function isDynamicPattern(pattern: string, options?: { + caseSensitiveMatch: boolean; +}): boolean; +//#endregion +//#region src/index.d.ts +/** +* Asynchronously match files following a glob pattern. +* @see {@link https://superchupu.dev/tinyglobby/documentation#glob} +*/ +declare function glob(patterns: string | readonly string[], options?: Omit): Promise; +/** +* @deprecated Provide patterns as the first argument instead. +*/ +declare function glob(options: GlobOptions): Promise; +/** +* Synchronously match files following a glob pattern. +* @see {@link https://superchupu.dev/tinyglobby/documentation#globSync} +*/ +declare function globSync(patterns: string | readonly string[], options?: Omit): string[]; +/** +* @deprecated Provide patterns as the first argument instead. +*/ +declare function globSync(options: GlobOptions): string[]; +//#endregion +export { type GlobOptions, convertPathToPattern, escapePath, glob, globSync, isDynamicPattern }; \ No newline at end of file diff --git a/node_modules/tinyglobby/dist/index.mjs b/node_modules/tinyglobby/dist/index.mjs new file mode 100644 index 0000000000000..ac043aae12677 --- /dev/null +++ b/node_modules/tinyglobby/dist/index.mjs @@ -0,0 +1,306 @@ +import { readdir, readdirSync, realpath, realpathSync, stat, statSync } from "fs"; +import { isAbsolute, posix, resolve } from "path"; +import { fileURLToPath } from "url"; +import { fdir } from "fdir"; +import picomatch from "picomatch"; +//#region src/utils.ts +const isReadonlyArray = Array.isArray; +const BACKSLASHES = /\\/g; +const isWin = process.platform === "win32"; +const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/; +function getPartialMatcher(patterns, options = {}) { + const patternsCount = patterns.length; + const patternsParts = Array(patternsCount); + const matchers = Array(patternsCount); + let i, j; + for (i = 0; i < patternsCount; i++) { + const parts = splitPattern(patterns[i]); + patternsParts[i] = parts; + const partsCount = parts.length; + const partMatchers = Array(partsCount); + for (j = 0; j < partsCount; j++) partMatchers[j] = picomatch(parts[j], options); + matchers[i] = partMatchers; + } + return (input) => { + const inputParts = input.split("/"); + if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true; + for (i = 0; i < patternsCount; i++) { + const patternParts = patternsParts[i]; + const matcher = matchers[i]; + const inputPatternCount = inputParts.length; + const minParts = Math.min(inputPatternCount, patternParts.length); + j = 0; + while (j < minParts) { + const part = patternParts[j]; + if (part.includes("/")) return true; + if (!matcher[j](inputParts[j])) break; + if (!options.noglobstar && part === "**") return true; + j++; + } + if (j === inputPatternCount) return true; + } + return false; + }; +} +/* node:coverage ignore next 2 */ +const WIN32_ROOT_DIR = /^[A-Z]:\/$/i; +const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/"; +function buildFormat(cwd, root, absolute) { + if (cwd === root || root.startsWith(`${cwd}/`)) { + if (absolute) { + const start = cwd.length + +!isRoot(cwd); + return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || "."; + } + const prefix = root.slice(cwd.length + 1); + if (prefix) return (p, isDir) => { + if (p === ".") return prefix; + const result = `${prefix}/${p}`; + return isDir ? result.slice(0, -1) : result; + }; + return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p; + } + if (absolute) return (p) => posix.relative(cwd, p) || "."; + return (p) => posix.relative(cwd, `${root}/${p}`) || "."; +} +function buildRelative(cwd, root) { + if (root.startsWith(`${cwd}/`)) { + const prefix = root.slice(cwd.length + 1); + return (p) => `${prefix}/${p}`; + } + return (p) => { + const result = posix.relative(cwd, `${root}/${p}`); + return p[p.length - 1] === "/" && result !== "" ? `${result}/` : result || "."; + }; +} +const splitPatternOptions = { parts: true }; +function splitPattern(path) { + var _result$parts; + const result = picomatch.scan(path, splitPatternOptions); + return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path]; +} +const ESCAPED_WIN32_BACKSLASHES = /\\(?![()[\]{}!+@])/g; +function convertPosixPathToPattern(path) { + return escapePosixPath(path); +} +function convertWin32PathToPattern(path) { + return escapeWin32Path(path).replace(ESCAPED_WIN32_BACKSLASHES, "/"); +} +/** +* Converts a path to a pattern depending on the platform. +* Identical to {@link escapePath} on POSIX systems. +* @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern} +*/ +/* node:coverage ignore next 3 */ +const convertPathToPattern = isWin ? convertWin32PathToPattern : convertPosixPathToPattern; +const POSIX_UNESCAPED_GLOB_SYMBOLS = /(? path.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&"); +const escapeWin32Path = (path) => path.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&"); +/** +* Escapes a path's special characters depending on the platform. +* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath} +*/ +/* node:coverage ignore next */ +const escapePath = isWin ? escapeWin32Path : escapePosixPath; +/** +* Checks if a pattern has dynamic parts. +* +* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy: +* +* - Doesn't necessarily return `false` on patterns that include `\`. +* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not. +* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`. +* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`. +* +* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern} +*/ +function isDynamicPattern(pattern, options) { + if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true; + const scan = picomatch.scan(pattern); + return scan.isGlob || scan.negated; +} +function log(...tasks) { + console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks); +} +function ensureStringArray(value) { + return typeof value === "string" ? [value] : value !== null && value !== void 0 ? value : []; +} +//#endregion +//#region src/patterns.ts +const PARENT_DIRECTORY = /^(\/?\.\.)+/; +const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g; +function normalizePattern(pattern, opts, props, isIgnore) { + var _PARENT_DIRECTORY$exe; + const cwd = opts.cwd; + let result = pattern; + if (pattern[pattern.length - 1] === "/") result = pattern.slice(0, -1); + if (result[result.length - 1] !== "*" && opts.expandDirectories) result += "/**"; + const escapedCwd = escapePath(cwd); + result = isAbsolute(result.replace(ESCAPING_BACKSLASHES, "")) ? posix.relative(escapedCwd, result) : posix.normalize(result); + const parentDir = (_PARENT_DIRECTORY$exe = PARENT_DIRECTORY.exec(result)) === null || _PARENT_DIRECTORY$exe === void 0 ? void 0 : _PARENT_DIRECTORY$exe[0]; + const parts = splitPattern(result); + if (parentDir) { + const n = (parentDir.length + 1) / 3; + let i = 0; + const cwdParts = escapedCwd.split("/"); + while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) { + result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || "."; + i++; + } + const potentialRoot = posix.join(cwd, parentDir.slice(i * 3)); + if (potentialRoot[0] !== "." && props.root.length > potentialRoot.length) { + props.root = potentialRoot; + props.depthOffset = -n + i; + } + } + if (!isIgnore && props.depthOffset >= 0) { + var _props$commonPath; + (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts); + const newCommonPath = []; + const length = Math.min(props.commonPath.length, parts.length); + for (let i = 0; i < length; i++) { + const part = parts[i]; + if (part === "**" && !parts[i + 1]) { + newCommonPath.pop(); + break; + } + if (i === parts.length - 1 || part !== props.commonPath[i] || isDynamicPattern(part)) break; + newCommonPath.push(part); + } + props.depthOffset = newCommonPath.length; + props.commonPath = newCommonPath; + props.root = newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd; + } + return result; +} +function processPatterns(options, patterns, props) { + const matchPatterns = []; + const ignorePatterns = []; + for (const pattern of options.ignore) { + if (!pattern) continue; + if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, options, props, true)); + } + for (const pattern of patterns) { + if (!pattern) continue; + if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, options, props, false)); + else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), options, props, true)); + } + return { + match: matchPatterns, + ignore: ignorePatterns + }; +} +//#endregion +//#region src/crawler.ts +function buildCrawler(options, patterns) { + const cwd = options.cwd; + const props = { + root: cwd, + depthOffset: 0 + }; + const processed = processPatterns(options, patterns, props); + if (options.debug) log("internal processing patterns:", processed); + const { absolute, caseSensitiveMatch, debug, dot, followSymbolicLinks, onlyDirectories } = options; + const root = props.root.replace(BACKSLASHES, ""); + const matchOptions = { + dot, + nobrace: options.braceExpansion === false, + nocase: !caseSensitiveMatch, + noextglob: options.extglob === false, + noglobstar: options.globstar === false, + posix: true + }; + const matcher = picomatch(processed.match, matchOptions); + const ignore = picomatch(processed.ignore, matchOptions); + const partialMatcher = getPartialMatcher(processed.match, matchOptions); + const format = buildFormat(cwd, root, absolute); + const excludeFormatter = absolute ? format : buildFormat(cwd, root, true); + const excludePredicate = (_, p) => { + const relativePath = excludeFormatter(p, true); + return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath); + }; + let maxDepth; + if (options.deep !== void 0) maxDepth = Math.round(options.deep - props.depthOffset); + const crawler = new fdir({ + filters: [debug ? (p, isDirectory) => { + const path = format(p, isDirectory); + const matches = matcher(path) && !ignore(path); + if (matches) log(`matched ${path}`); + return matches; + } : (p, isDirectory) => { + const path = format(p, isDirectory); + return matcher(path) && !ignore(path); + }], + exclude: debug ? (_, p) => { + const skipped = excludePredicate(_, p); + log(`${skipped ? "skipped" : "crawling"} ${p}`); + return skipped; + } : excludePredicate, + fs: options.fs, + pathSeparator: "/", + relativePaths: !absolute, + resolvePaths: absolute, + includeBasePath: absolute, + resolveSymlinks: followSymbolicLinks, + excludeSymlinks: !followSymbolicLinks, + excludeFiles: onlyDirectories, + includeDirs: onlyDirectories || !options.onlyFiles, + maxDepth, + signal: options.signal + }).crawl(root); + if (options.debug) log("internal properties:", { + ...props, + root + }); + return [crawler, cwd !== root && !absolute && buildRelative(cwd, root)]; +} +//#endregion +//#region src/index.ts +function formatPaths(paths, mapper) { + if (mapper) for (let i = paths.length - 1; i >= 0; i--) paths[i] = mapper(paths[i]); + return paths; +} +const defaultOptions = { + caseSensitiveMatch: true, + cwd: process.cwd(), + debug: !!process.env.TINYGLOBBY_DEBUG, + expandDirectories: true, + followSymbolicLinks: true, + onlyFiles: true +}; +function getOptions(options) { + const opts = { + ...defaultOptions, + ...options + }; + opts.cwd = (opts.cwd instanceof URL ? fileURLToPath(opts.cwd) : resolve(opts.cwd)).replace(BACKSLASHES, "/"); + opts.ignore = ensureStringArray(opts.ignore); + opts.fs && (opts.fs = { + readdir: opts.fs.readdir || readdir, + readdirSync: opts.fs.readdirSync || readdirSync, + realpath: opts.fs.realpath || realpath, + realpathSync: opts.fs.realpathSync || realpathSync, + stat: opts.fs.stat || stat, + statSync: opts.fs.statSync || statSync + }); + if (opts.debug) log("globbing with options:", opts); + return opts; +} +function getCrawler(globInput, inputOptions = {}) { + var _ref; + if (globInput && (inputOptions === null || inputOptions === void 0 ? void 0 : inputOptions.patterns)) throw new Error("Cannot pass patterns as both an argument and an option"); + const isModern = isReadonlyArray(globInput) || typeof globInput === "string"; + const patterns = ensureStringArray((_ref = isModern ? globInput : globInput.patterns) !== null && _ref !== void 0 ? _ref : "**/*"); + const options = getOptions(isModern ? inputOptions : globInput); + return patterns.length > 0 ? buildCrawler(options, patterns) : []; +} +async function glob(globInput, options) { + const [crawler, relative] = getCrawler(globInput, options); + return crawler ? formatPaths(await crawler.withPromise(), relative) : []; +} +function globSync(globInput, options) { + const [crawler, relative] = getCrawler(globInput, options); + return crawler ? formatPaths(crawler.sync(), relative) : []; +} +//#endregion +export { convertPathToPattern, escapePath, glob, globSync, isDynamicPattern }; diff --git a/node_modules/tinyglobby/node_modules/fdir/LICENSE b/node_modules/tinyglobby/node_modules/fdir/LICENSE new file mode 100644 index 0000000000000..bb7fdee44cae6 --- /dev/null +++ b/node_modules/tinyglobby/node_modules/fdir/LICENSE @@ -0,0 +1,7 @@ +Copyright 2023 Abdullah Atta + +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. diff --git a/node_modules/tinyglobby/node_modules/fdir/dist/index.cjs b/node_modules/tinyglobby/node_modules/fdir/dist/index.cjs new file mode 100644 index 0000000000000..4868ffba35d99 --- /dev/null +++ b/node_modules/tinyglobby/node_modules/fdir/dist/index.cjs @@ -0,0 +1,588 @@ +//#region rolldown:runtime +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); + +//#endregion +const path = __toESM(require("path")); +const fs = __toESM(require("fs")); + +//#region src/utils.ts +function cleanPath(path$1) { + let normalized = (0, path.normalize)(path$1); + if (normalized.length > 1 && normalized[normalized.length - 1] === path.sep) normalized = normalized.substring(0, normalized.length - 1); + return normalized; +} +const SLASHES_REGEX = /[\\/]/g; +function convertSlashes(path$1, separator) { + return path$1.replace(SLASHES_REGEX, separator); +} +const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i; +function isRootDirectory(path$1) { + return path$1 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path$1); +} +function normalizePath(path$1, options) { + const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options; + const pathNeedsCleaning = process.platform === "win32" && path$1.includes("/") || path$1.startsWith("."); + if (resolvePaths) path$1 = (0, path.resolve)(path$1); + if (normalizePath$1 || pathNeedsCleaning) path$1 = cleanPath(path$1); + if (path$1 === ".") return ""; + const needsSeperator = path$1[path$1.length - 1] !== pathSeparator; + return convertSlashes(needsSeperator ? path$1 + pathSeparator : path$1, pathSeparator); +} + +//#endregion +//#region src/api/functions/join-path.ts +function joinPathWithBasePath(filename, directoryPath) { + return directoryPath + filename; +} +function joinPathWithRelativePath(root, options) { + return function(filename, directoryPath) { + const sameRoot = directoryPath.startsWith(root); + if (sameRoot) return directoryPath.slice(root.length) + filename; + else return convertSlashes((0, path.relative)(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename; + }; +} +function joinPath(filename) { + return filename; +} +function joinDirectoryPath(filename, directoryPath, separator) { + return directoryPath + filename + separator; +} +function build$7(root, options) { + const { relativePaths, includeBasePath } = options; + return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath; +} + +//#endregion +//#region src/api/functions/push-directory.ts +function pushDirectoryWithRelativePath(root) { + return function(directoryPath, paths) { + paths.push(directoryPath.substring(root.length) || "."); + }; +} +function pushDirectoryFilterWithRelativePath(root) { + return function(directoryPath, paths, filters) { + const relativePath = directoryPath.substring(root.length) || "."; + if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath); + }; +} +const pushDirectory = (directoryPath, paths) => { + paths.push(directoryPath || "."); +}; +const pushDirectoryFilter = (directoryPath, paths, filters) => { + const path$1 = directoryPath || "."; + if (filters.every((filter) => filter(path$1, true))) paths.push(path$1); +}; +const empty$2 = () => {}; +function build$6(root, options) { + const { includeDirs, filters, relativePaths } = options; + if (!includeDirs) return empty$2; + if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root); + return filters && filters.length ? pushDirectoryFilter : pushDirectory; +} + +//#endregion +//#region src/api/functions/push-file.ts +const pushFileFilterAndCount = (filename, _paths, counts, filters) => { + if (filters.every((filter) => filter(filename, false))) counts.files++; +}; +const pushFileFilter = (filename, paths, _counts, filters) => { + if (filters.every((filter) => filter(filename, false))) paths.push(filename); +}; +const pushFileCount = (_filename, _paths, counts, _filters) => { + counts.files++; +}; +const pushFile = (filename, paths) => { + paths.push(filename); +}; +const empty$1 = () => {}; +function build$5(options) { + const { excludeFiles, filters, onlyCounts } = options; + if (excludeFiles) return empty$1; + if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter; + else if (onlyCounts) return pushFileCount; + else return pushFile; +} + +//#endregion +//#region src/api/functions/get-array.ts +const getArray = (paths) => { + return paths; +}; +const getArrayGroup = () => { + return [""].slice(0, 0); +}; +function build$4(options) { + return options.group ? getArrayGroup : getArray; +} + +//#endregion +//#region src/api/functions/group-files.ts +const groupFiles = (groups, directory, files) => { + groups.push({ + directory, + files, + dir: directory + }); +}; +const empty = () => {}; +function build$3(options) { + return options.group ? groupFiles : empty; +} + +//#endregion +//#region src/api/functions/resolve-symlink.ts +const resolveSymlinksAsync = function(path$1, state, callback$1) { + const { queue, fs: fs$1, options: { suppressErrors } } = state; + queue.enqueue(); + fs$1.realpath(path$1, (error, resolvedPath) => { + if (error) return queue.dequeue(suppressErrors ? null : error, state); + fs$1.stat(resolvedPath, (error$1, stat) => { + if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state); + if (stat.isDirectory() && isRecursive(path$1, resolvedPath, state)) return queue.dequeue(null, state); + callback$1(stat, resolvedPath); + queue.dequeue(null, state); + }); + }); +}; +const resolveSymlinks = function(path$1, state, callback$1) { + const { queue, fs: fs$1, options: { suppressErrors } } = state; + queue.enqueue(); + try { + const resolvedPath = fs$1.realpathSync(path$1); + const stat = fs$1.statSync(resolvedPath); + if (stat.isDirectory() && isRecursive(path$1, resolvedPath, state)) return; + callback$1(stat, resolvedPath); + } catch (e) { + if (!suppressErrors) throw e; + } +}; +function build$2(options, isSynchronous) { + if (!options.resolveSymlinks || options.excludeSymlinks) return null; + return isSynchronous ? resolveSymlinks : resolveSymlinksAsync; +} +function isRecursive(path$1, resolved, state) { + if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state); + let parent = (0, path.dirname)(path$1); + let depth = 1; + while (parent !== state.root && depth < 2) { + const resolvedPath = state.symlinks.get(parent); + const isSameRoot = !!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath)); + if (isSameRoot) depth++; + else parent = (0, path.dirname)(parent); + } + state.symlinks.set(path$1, resolved); + return depth > 1; +} +function isRecursiveUsingRealPaths(resolved, state) { + return state.visited.includes(resolved + state.options.pathSeparator); +} + +//#endregion +//#region src/api/functions/invoke-callback.ts +const onlyCountsSync = (state) => { + return state.counts; +}; +const groupsSync = (state) => { + return state.groups; +}; +const defaultSync = (state) => { + return state.paths; +}; +const limitFilesSync = (state) => { + return state.paths.slice(0, state.options.maxFiles); +}; +const onlyCountsAsync = (state, error, callback$1) => { + report(error, callback$1, state.counts, state.options.suppressErrors); + return null; +}; +const defaultAsync = (state, error, callback$1) => { + report(error, callback$1, state.paths, state.options.suppressErrors); + return null; +}; +const limitFilesAsync = (state, error, callback$1) => { + report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors); + return null; +}; +const groupsAsync = (state, error, callback$1) => { + report(error, callback$1, state.groups, state.options.suppressErrors); + return null; +}; +function report(error, callback$1, output, suppressErrors) { + if (error && !suppressErrors) callback$1(error, output); + else callback$1(null, output); +} +function build$1(options, isSynchronous) { + const { onlyCounts, group, maxFiles } = options; + if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync; + else if (group) return isSynchronous ? groupsSync : groupsAsync; + else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync; + else return isSynchronous ? defaultSync : defaultAsync; +} + +//#endregion +//#region src/api/functions/walk-directory.ts +const readdirOpts = { withFileTypes: true }; +const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => { + state.queue.enqueue(); + if (currentDepth < 0) return state.queue.dequeue(null, state); + const { fs: fs$1 } = state; + state.visited.push(crawlPath); + state.counts.directories++; + fs$1.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => { + callback$1(entries, directoryPath, currentDepth); + state.queue.dequeue(state.options.suppressErrors ? null : error, state); + }); +}; +const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => { + const { fs: fs$1 } = state; + if (currentDepth < 0) return; + state.visited.push(crawlPath); + state.counts.directories++; + let entries = []; + try { + entries = fs$1.readdirSync(crawlPath || ".", readdirOpts); + } catch (e) { + if (!state.options.suppressErrors) throw e; + } + callback$1(entries, directoryPath, currentDepth); +}; +function build(isSynchronous) { + return isSynchronous ? walkSync : walkAsync; +} + +//#endregion +//#region src/api/queue.ts +/** +* This is a custom stateless queue to track concurrent async fs calls. +* It increments a counter whenever a call is queued and decrements it +* as soon as it completes. When the counter hits 0, it calls onQueueEmpty. +*/ +var Queue = class { + count = 0; + constructor(onQueueEmpty) { + this.onQueueEmpty = onQueueEmpty; + } + enqueue() { + this.count++; + return this.count; + } + dequeue(error, output) { + if (this.onQueueEmpty && (--this.count <= 0 || error)) { + this.onQueueEmpty(error, output); + if (error) { + output.controller.abort(); + this.onQueueEmpty = void 0; + } + } + } +}; + +//#endregion +//#region src/api/counter.ts +var Counter = class { + _files = 0; + _directories = 0; + set files(num) { + this._files = num; + } + get files() { + return this._files; + } + set directories(num) { + this._directories = num; + } + get directories() { + return this._directories; + } + /** + * @deprecated use `directories` instead + */ + /* c8 ignore next 3 */ + get dirs() { + return this._directories; + } +}; + +//#endregion +//#region src/api/aborter.ts +/** +* AbortController is not supported on Node 14 so we use this until we can drop +* support for Node 14. +*/ +var Aborter = class { + aborted = false; + abort() { + this.aborted = true; + } +}; + +//#endregion +//#region src/api/walker.ts +var Walker = class { + root; + isSynchronous; + state; + joinPath; + pushDirectory; + pushFile; + getArray; + groupFiles; + resolveSymlink; + walkDirectory; + callbackInvoker; + constructor(root, options, callback$1) { + this.isSynchronous = !callback$1; + this.callbackInvoker = build$1(options, this.isSynchronous); + this.root = normalizePath(root, options); + this.state = { + root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1), + paths: [""].slice(0, 0), + groups: [], + counts: new Counter(), + options, + queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)), + symlinks: /* @__PURE__ */ new Map(), + visited: [""].slice(0, 0), + controller: new Aborter(), + fs: options.fs || fs + }; + this.joinPath = build$7(this.root, options); + this.pushDirectory = build$6(this.root, options); + this.pushFile = build$5(options); + this.getArray = build$4(options); + this.groupFiles = build$3(options); + this.resolveSymlink = build$2(options, this.isSynchronous); + this.walkDirectory = build(this.isSynchronous); + } + start() { + this.pushDirectory(this.root, this.state.paths, this.state.options.filters); + this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk); + return this.isSynchronous ? this.callbackInvoker(this.state, null) : null; + } + walk = (entries, directoryPath, depth) => { + const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state; + if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return; + const files = this.getArray(this.state.paths); + for (let i = 0; i < entries.length; ++i) { + const entry = entries[i]; + if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) { + const filename = this.joinPath(entry.name, directoryPath); + this.pushFile(filename, files, this.state.counts, filters); + } else if (entry.isDirectory()) { + let path$1 = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator); + if (exclude && exclude(entry.name, path$1)) continue; + this.pushDirectory(path$1, paths, filters); + this.walkDirectory(this.state, path$1, path$1, depth - 1, this.walk); + } else if (this.resolveSymlink && entry.isSymbolicLink()) { + let path$1 = joinPathWithBasePath(entry.name, directoryPath); + this.resolveSymlink(path$1, this.state, (stat, resolvedPath) => { + if (stat.isDirectory()) { + resolvedPath = normalizePath(resolvedPath, this.state.options); + if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path$1 + pathSeparator)) return; + this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path$1 + pathSeparator, depth - 1, this.walk); + } else { + resolvedPath = useRealPaths ? resolvedPath : path$1; + const filename = (0, path.basename)(resolvedPath); + const directoryPath$1 = normalizePath((0, path.dirname)(resolvedPath), this.state.options); + resolvedPath = this.joinPath(filename, directoryPath$1); + this.pushFile(resolvedPath, files, this.state.counts, filters); + } + }); + } + } + this.groupFiles(this.state.groups, directoryPath, files); + }; +}; + +//#endregion +//#region src/api/async.ts +function promise(root, options) { + return new Promise((resolve$1, reject) => { + callback(root, options, (err, output) => { + if (err) return reject(err); + resolve$1(output); + }); + }); +} +function callback(root, options, callback$1) { + let walker = new Walker(root, options, callback$1); + walker.start(); +} + +//#endregion +//#region src/api/sync.ts +function sync(root, options) { + const walker = new Walker(root, options); + return walker.start(); +} + +//#endregion +//#region src/builder/api-builder.ts +var APIBuilder = class { + constructor(root, options) { + this.root = root; + this.options = options; + } + withPromise() { + return promise(this.root, this.options); + } + withCallback(cb) { + callback(this.root, this.options, cb); + } + sync() { + return sync(this.root, this.options); + } +}; + +//#endregion +//#region src/builder/index.ts +let pm = null; +/* c8 ignore next 6 */ +try { + require.resolve("picomatch"); + pm = require("picomatch"); +} catch {} +var Builder = class { + globCache = {}; + options = { + maxDepth: Infinity, + suppressErrors: true, + pathSeparator: path.sep, + filters: [] + }; + globFunction; + constructor(options) { + this.options = { + ...this.options, + ...options + }; + this.globFunction = this.options.globFunction; + } + group() { + this.options.group = true; + return this; + } + withPathSeparator(separator) { + this.options.pathSeparator = separator; + return this; + } + withBasePath() { + this.options.includeBasePath = true; + return this; + } + withRelativePaths() { + this.options.relativePaths = true; + return this; + } + withDirs() { + this.options.includeDirs = true; + return this; + } + withMaxDepth(depth) { + this.options.maxDepth = depth; + return this; + } + withMaxFiles(limit) { + this.options.maxFiles = limit; + return this; + } + withFullPaths() { + this.options.resolvePaths = true; + this.options.includeBasePath = true; + return this; + } + withErrors() { + this.options.suppressErrors = false; + return this; + } + withSymlinks({ resolvePaths = true } = {}) { + this.options.resolveSymlinks = true; + this.options.useRealPaths = resolvePaths; + return this.withFullPaths(); + } + withAbortSignal(signal) { + this.options.signal = signal; + return this; + } + normalize() { + this.options.normalizePath = true; + return this; + } + filter(predicate) { + this.options.filters.push(predicate); + return this; + } + onlyDirs() { + this.options.excludeFiles = true; + this.options.includeDirs = true; + return this; + } + exclude(predicate) { + this.options.exclude = predicate; + return this; + } + onlyCounts() { + this.options.onlyCounts = true; + return this; + } + crawl(root) { + return new APIBuilder(root || ".", this.options); + } + withGlobFunction(fn) { + this.globFunction = fn; + return this; + } + /** + * @deprecated Pass options using the constructor instead: + * ```ts + * new fdir(options).crawl("/path/to/root"); + * ``` + * This method will be removed in v7.0 + */ + /* c8 ignore next 4 */ + crawlWithOptions(root, options) { + this.options = { + ...this.options, + ...options + }; + return new APIBuilder(root || ".", this.options); + } + glob(...patterns) { + if (this.globFunction) return this.globWithOptions(patterns); + return this.globWithOptions(patterns, ...[{ dot: true }]); + } + globWithOptions(patterns, ...options) { + const globFn = this.globFunction || pm; + /* c8 ignore next 5 */ + if (!globFn) throw new Error("Please specify a glob function to use glob matching."); + var isMatch = this.globCache[patterns.join("\0")]; + if (!isMatch) { + isMatch = globFn(patterns, ...options); + this.globCache[patterns.join("\0")] = isMatch; + } + this.options.filters.push((path$1) => isMatch(path$1)); + return this; + } +}; + +//#endregion +exports.fdir = Builder; \ No newline at end of file diff --git a/node_modules/tinyglobby/node_modules/fdir/dist/index.d.cts b/node_modules/tinyglobby/node_modules/fdir/dist/index.d.cts new file mode 100644 index 0000000000000..f448ef5d9b563 --- /dev/null +++ b/node_modules/tinyglobby/node_modules/fdir/dist/index.d.cts @@ -0,0 +1,155 @@ +/// +import * as nativeFs from "fs"; +import picomatch from "picomatch"; + +//#region src/api/aborter.d.ts +/** + * AbortController is not supported on Node 14 so we use this until we can drop + * support for Node 14. + */ +declare class Aborter { + aborted: boolean; + abort(): void; +} +//#endregion +//#region src/api/queue.d.ts +type OnQueueEmptyCallback = (error: Error | null, output: WalkerState) => void; +/** + * This is a custom stateless queue to track concurrent async fs calls. + * It increments a counter whenever a call is queued and decrements it + * as soon as it completes. When the counter hits 0, it calls onQueueEmpty. + */ +declare class Queue { + private onQueueEmpty?; + count: number; + constructor(onQueueEmpty?: OnQueueEmptyCallback | undefined); + enqueue(): number; + dequeue(error: Error | null, output: WalkerState): void; +} +//#endregion +//#region src/types.d.ts +type Counts = { + files: number; + directories: number; + /** + * @deprecated use `directories` instead. Will be removed in v7.0. + */ + dirs: number; +}; +type Group = { + directory: string; + files: string[]; + /** + * @deprecated use `directory` instead. Will be removed in v7.0. + */ + dir: string; +}; +type GroupOutput = Group[]; +type OnlyCountsOutput = Counts; +type PathsOutput = string[]; +type Output = OnlyCountsOutput | PathsOutput | GroupOutput; +type FSLike = { + readdir: typeof nativeFs.readdir; + readdirSync: typeof nativeFs.readdirSync; + realpath: typeof nativeFs.realpath; + realpathSync: typeof nativeFs.realpathSync; + stat: typeof nativeFs.stat; + statSync: typeof nativeFs.statSync; +}; +type WalkerState = { + root: string; + paths: string[]; + groups: Group[]; + counts: Counts; + options: Options; + queue: Queue; + controller: Aborter; + fs: FSLike; + symlinks: Map; + visited: string[]; +}; +type ResultCallback = (error: Error | null, output: TOutput) => void; +type FilterPredicate = (path: string, isDirectory: boolean) => boolean; +type ExcludePredicate = (dirName: string, dirPath: string) => boolean; +type PathSeparator = "/" | "\\"; +type Options = { + includeBasePath?: boolean; + includeDirs?: boolean; + normalizePath?: boolean; + maxDepth: number; + maxFiles?: number; + resolvePaths?: boolean; + suppressErrors: boolean; + group?: boolean; + onlyCounts?: boolean; + filters: FilterPredicate[]; + resolveSymlinks?: boolean; + useRealPaths?: boolean; + excludeFiles?: boolean; + excludeSymlinks?: boolean; + exclude?: ExcludePredicate; + relativePaths?: boolean; + pathSeparator: PathSeparator; + signal?: AbortSignal; + globFunction?: TGlobFunction; + fs?: FSLike; +}; +type GlobMatcher = (test: string) => boolean; +type GlobFunction = (glob: string | string[], ...params: unknown[]) => GlobMatcher; +type GlobParams = T extends ((globs: string | string[], ...params: infer TParams extends unknown[]) => GlobMatcher) ? TParams : []; +//#endregion +//#region src/builder/api-builder.d.ts +declare class APIBuilder { + private readonly root; + private readonly options; + constructor(root: string, options: Options); + withPromise(): Promise; + withCallback(cb: ResultCallback): void; + sync(): TReturnType; +} +//#endregion +//#region src/builder/index.d.ts +declare class Builder { + private readonly globCache; + private options; + private globFunction?; + constructor(options?: Partial>); + group(): Builder; + withPathSeparator(separator: "/" | "\\"): this; + withBasePath(): this; + withRelativePaths(): this; + withDirs(): this; + withMaxDepth(depth: number): this; + withMaxFiles(limit: number): this; + withFullPaths(): this; + withErrors(): this; + withSymlinks({ + resolvePaths + }?: { + resolvePaths?: boolean | undefined; + }): this; + withAbortSignal(signal: AbortSignal): this; + normalize(): this; + filter(predicate: FilterPredicate): this; + onlyDirs(): this; + exclude(predicate: ExcludePredicate): this; + onlyCounts(): Builder; + crawl(root?: string): APIBuilder; + withGlobFunction(fn: TFunc): Builder; + /** + * @deprecated Pass options using the constructor instead: + * ```ts + * new fdir(options).crawl("/path/to/root"); + * ``` + * This method will be removed in v7.0 + */ + crawlWithOptions(root: string, options: Partial>): APIBuilder; + glob(...patterns: string[]): Builder; + globWithOptions(patterns: string[]): Builder; + globWithOptions(patterns: string[], ...options: GlobParams): Builder; +} +//#endregion +//#region src/index.d.ts +type Fdir = typeof Builder; +//#endregion +export { Counts, ExcludePredicate, FSLike, Fdir, FilterPredicate, GlobFunction, GlobMatcher, GlobParams, Group, GroupOutput, OnlyCountsOutput, Options, Output, PathSeparator, PathsOutput, ResultCallback, WalkerState, Builder as fdir }; \ No newline at end of file diff --git a/node_modules/tinyglobby/node_modules/fdir/dist/index.d.mts b/node_modules/tinyglobby/node_modules/fdir/dist/index.d.mts new file mode 100644 index 0000000000000..f448ef5d9b563 --- /dev/null +++ b/node_modules/tinyglobby/node_modules/fdir/dist/index.d.mts @@ -0,0 +1,155 @@ +/// +import * as nativeFs from "fs"; +import picomatch from "picomatch"; + +//#region src/api/aborter.d.ts +/** + * AbortController is not supported on Node 14 so we use this until we can drop + * support for Node 14. + */ +declare class Aborter { + aborted: boolean; + abort(): void; +} +//#endregion +//#region src/api/queue.d.ts +type OnQueueEmptyCallback = (error: Error | null, output: WalkerState) => void; +/** + * This is a custom stateless queue to track concurrent async fs calls. + * It increments a counter whenever a call is queued and decrements it + * as soon as it completes. When the counter hits 0, it calls onQueueEmpty. + */ +declare class Queue { + private onQueueEmpty?; + count: number; + constructor(onQueueEmpty?: OnQueueEmptyCallback | undefined); + enqueue(): number; + dequeue(error: Error | null, output: WalkerState): void; +} +//#endregion +//#region src/types.d.ts +type Counts = { + files: number; + directories: number; + /** + * @deprecated use `directories` instead. Will be removed in v7.0. + */ + dirs: number; +}; +type Group = { + directory: string; + files: string[]; + /** + * @deprecated use `directory` instead. Will be removed in v7.0. + */ + dir: string; +}; +type GroupOutput = Group[]; +type OnlyCountsOutput = Counts; +type PathsOutput = string[]; +type Output = OnlyCountsOutput | PathsOutput | GroupOutput; +type FSLike = { + readdir: typeof nativeFs.readdir; + readdirSync: typeof nativeFs.readdirSync; + realpath: typeof nativeFs.realpath; + realpathSync: typeof nativeFs.realpathSync; + stat: typeof nativeFs.stat; + statSync: typeof nativeFs.statSync; +}; +type WalkerState = { + root: string; + paths: string[]; + groups: Group[]; + counts: Counts; + options: Options; + queue: Queue; + controller: Aborter; + fs: FSLike; + symlinks: Map; + visited: string[]; +}; +type ResultCallback = (error: Error | null, output: TOutput) => void; +type FilterPredicate = (path: string, isDirectory: boolean) => boolean; +type ExcludePredicate = (dirName: string, dirPath: string) => boolean; +type PathSeparator = "/" | "\\"; +type Options = { + includeBasePath?: boolean; + includeDirs?: boolean; + normalizePath?: boolean; + maxDepth: number; + maxFiles?: number; + resolvePaths?: boolean; + suppressErrors: boolean; + group?: boolean; + onlyCounts?: boolean; + filters: FilterPredicate[]; + resolveSymlinks?: boolean; + useRealPaths?: boolean; + excludeFiles?: boolean; + excludeSymlinks?: boolean; + exclude?: ExcludePredicate; + relativePaths?: boolean; + pathSeparator: PathSeparator; + signal?: AbortSignal; + globFunction?: TGlobFunction; + fs?: FSLike; +}; +type GlobMatcher = (test: string) => boolean; +type GlobFunction = (glob: string | string[], ...params: unknown[]) => GlobMatcher; +type GlobParams = T extends ((globs: string | string[], ...params: infer TParams extends unknown[]) => GlobMatcher) ? TParams : []; +//#endregion +//#region src/builder/api-builder.d.ts +declare class APIBuilder { + private readonly root; + private readonly options; + constructor(root: string, options: Options); + withPromise(): Promise; + withCallback(cb: ResultCallback): void; + sync(): TReturnType; +} +//#endregion +//#region src/builder/index.d.ts +declare class Builder { + private readonly globCache; + private options; + private globFunction?; + constructor(options?: Partial>); + group(): Builder; + withPathSeparator(separator: "/" | "\\"): this; + withBasePath(): this; + withRelativePaths(): this; + withDirs(): this; + withMaxDepth(depth: number): this; + withMaxFiles(limit: number): this; + withFullPaths(): this; + withErrors(): this; + withSymlinks({ + resolvePaths + }?: { + resolvePaths?: boolean | undefined; + }): this; + withAbortSignal(signal: AbortSignal): this; + normalize(): this; + filter(predicate: FilterPredicate): this; + onlyDirs(): this; + exclude(predicate: ExcludePredicate): this; + onlyCounts(): Builder; + crawl(root?: string): APIBuilder; + withGlobFunction(fn: TFunc): Builder; + /** + * @deprecated Pass options using the constructor instead: + * ```ts + * new fdir(options).crawl("/path/to/root"); + * ``` + * This method will be removed in v7.0 + */ + crawlWithOptions(root: string, options: Partial>): APIBuilder; + glob(...patterns: string[]): Builder; + globWithOptions(patterns: string[]): Builder; + globWithOptions(patterns: string[], ...options: GlobParams): Builder; +} +//#endregion +//#region src/index.d.ts +type Fdir = typeof Builder; +//#endregion +export { Counts, ExcludePredicate, FSLike, Fdir, FilterPredicate, GlobFunction, GlobMatcher, GlobParams, Group, GroupOutput, OnlyCountsOutput, Options, Output, PathSeparator, PathsOutput, ResultCallback, WalkerState, Builder as fdir }; \ No newline at end of file diff --git a/node_modules/tinyglobby/node_modules/fdir/dist/index.mjs b/node_modules/tinyglobby/node_modules/fdir/dist/index.mjs new file mode 100644 index 0000000000000..5c37e092b507d --- /dev/null +++ b/node_modules/tinyglobby/node_modules/fdir/dist/index.mjs @@ -0,0 +1,570 @@ +import { createRequire } from "module"; +import { basename, dirname, normalize, relative, resolve, sep } from "path"; +import * as nativeFs from "fs"; + +//#region rolldown:runtime +var __require = /* @__PURE__ */ createRequire(import.meta.url); + +//#endregion +//#region src/utils.ts +function cleanPath(path) { + let normalized = normalize(path); + if (normalized.length > 1 && normalized[normalized.length - 1] === sep) normalized = normalized.substring(0, normalized.length - 1); + return normalized; +} +const SLASHES_REGEX = /[\\/]/g; +function convertSlashes(path, separator) { + return path.replace(SLASHES_REGEX, separator); +} +const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i; +function isRootDirectory(path) { + return path === "/" || WINDOWS_ROOT_DIR_REGEX.test(path); +} +function normalizePath(path, options) { + const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options; + const pathNeedsCleaning = process.platform === "win32" && path.includes("/") || path.startsWith("."); + if (resolvePaths) path = resolve(path); + if (normalizePath$1 || pathNeedsCleaning) path = cleanPath(path); + if (path === ".") return ""; + const needsSeperator = path[path.length - 1] !== pathSeparator; + return convertSlashes(needsSeperator ? path + pathSeparator : path, pathSeparator); +} + +//#endregion +//#region src/api/functions/join-path.ts +function joinPathWithBasePath(filename, directoryPath) { + return directoryPath + filename; +} +function joinPathWithRelativePath(root, options) { + return function(filename, directoryPath) { + const sameRoot = directoryPath.startsWith(root); + if (sameRoot) return directoryPath.slice(root.length) + filename; + else return convertSlashes(relative(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename; + }; +} +function joinPath(filename) { + return filename; +} +function joinDirectoryPath(filename, directoryPath, separator) { + return directoryPath + filename + separator; +} +function build$7(root, options) { + const { relativePaths, includeBasePath } = options; + return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath; +} + +//#endregion +//#region src/api/functions/push-directory.ts +function pushDirectoryWithRelativePath(root) { + return function(directoryPath, paths) { + paths.push(directoryPath.substring(root.length) || "."); + }; +} +function pushDirectoryFilterWithRelativePath(root) { + return function(directoryPath, paths, filters) { + const relativePath = directoryPath.substring(root.length) || "."; + if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath); + }; +} +const pushDirectory = (directoryPath, paths) => { + paths.push(directoryPath || "."); +}; +const pushDirectoryFilter = (directoryPath, paths, filters) => { + const path = directoryPath || "."; + if (filters.every((filter) => filter(path, true))) paths.push(path); +}; +const empty$2 = () => {}; +function build$6(root, options) { + const { includeDirs, filters, relativePaths } = options; + if (!includeDirs) return empty$2; + if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root); + return filters && filters.length ? pushDirectoryFilter : pushDirectory; +} + +//#endregion +//#region src/api/functions/push-file.ts +const pushFileFilterAndCount = (filename, _paths, counts, filters) => { + if (filters.every((filter) => filter(filename, false))) counts.files++; +}; +const pushFileFilter = (filename, paths, _counts, filters) => { + if (filters.every((filter) => filter(filename, false))) paths.push(filename); +}; +const pushFileCount = (_filename, _paths, counts, _filters) => { + counts.files++; +}; +const pushFile = (filename, paths) => { + paths.push(filename); +}; +const empty$1 = () => {}; +function build$5(options) { + const { excludeFiles, filters, onlyCounts } = options; + if (excludeFiles) return empty$1; + if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter; + else if (onlyCounts) return pushFileCount; + else return pushFile; +} + +//#endregion +//#region src/api/functions/get-array.ts +const getArray = (paths) => { + return paths; +}; +const getArrayGroup = () => { + return [""].slice(0, 0); +}; +function build$4(options) { + return options.group ? getArrayGroup : getArray; +} + +//#endregion +//#region src/api/functions/group-files.ts +const groupFiles = (groups, directory, files) => { + groups.push({ + directory, + files, + dir: directory + }); +}; +const empty = () => {}; +function build$3(options) { + return options.group ? groupFiles : empty; +} + +//#endregion +//#region src/api/functions/resolve-symlink.ts +const resolveSymlinksAsync = function(path, state, callback$1) { + const { queue, fs, options: { suppressErrors } } = state; + queue.enqueue(); + fs.realpath(path, (error, resolvedPath) => { + if (error) return queue.dequeue(suppressErrors ? null : error, state); + fs.stat(resolvedPath, (error$1, stat) => { + if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state); + if (stat.isDirectory() && isRecursive(path, resolvedPath, state)) return queue.dequeue(null, state); + callback$1(stat, resolvedPath); + queue.dequeue(null, state); + }); + }); +}; +const resolveSymlinks = function(path, state, callback$1) { + const { queue, fs, options: { suppressErrors } } = state; + queue.enqueue(); + try { + const resolvedPath = fs.realpathSync(path); + const stat = fs.statSync(resolvedPath); + if (stat.isDirectory() && isRecursive(path, resolvedPath, state)) return; + callback$1(stat, resolvedPath); + } catch (e) { + if (!suppressErrors) throw e; + } +}; +function build$2(options, isSynchronous) { + if (!options.resolveSymlinks || options.excludeSymlinks) return null; + return isSynchronous ? resolveSymlinks : resolveSymlinksAsync; +} +function isRecursive(path, resolved, state) { + if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state); + let parent = dirname(path); + let depth = 1; + while (parent !== state.root && depth < 2) { + const resolvedPath = state.symlinks.get(parent); + const isSameRoot = !!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath)); + if (isSameRoot) depth++; + else parent = dirname(parent); + } + state.symlinks.set(path, resolved); + return depth > 1; +} +function isRecursiveUsingRealPaths(resolved, state) { + return state.visited.includes(resolved + state.options.pathSeparator); +} + +//#endregion +//#region src/api/functions/invoke-callback.ts +const onlyCountsSync = (state) => { + return state.counts; +}; +const groupsSync = (state) => { + return state.groups; +}; +const defaultSync = (state) => { + return state.paths; +}; +const limitFilesSync = (state) => { + return state.paths.slice(0, state.options.maxFiles); +}; +const onlyCountsAsync = (state, error, callback$1) => { + report(error, callback$1, state.counts, state.options.suppressErrors); + return null; +}; +const defaultAsync = (state, error, callback$1) => { + report(error, callback$1, state.paths, state.options.suppressErrors); + return null; +}; +const limitFilesAsync = (state, error, callback$1) => { + report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors); + return null; +}; +const groupsAsync = (state, error, callback$1) => { + report(error, callback$1, state.groups, state.options.suppressErrors); + return null; +}; +function report(error, callback$1, output, suppressErrors) { + if (error && !suppressErrors) callback$1(error, output); + else callback$1(null, output); +} +function build$1(options, isSynchronous) { + const { onlyCounts, group, maxFiles } = options; + if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync; + else if (group) return isSynchronous ? groupsSync : groupsAsync; + else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync; + else return isSynchronous ? defaultSync : defaultAsync; +} + +//#endregion +//#region src/api/functions/walk-directory.ts +const readdirOpts = { withFileTypes: true }; +const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => { + state.queue.enqueue(); + if (currentDepth < 0) return state.queue.dequeue(null, state); + const { fs } = state; + state.visited.push(crawlPath); + state.counts.directories++; + fs.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => { + callback$1(entries, directoryPath, currentDepth); + state.queue.dequeue(state.options.suppressErrors ? null : error, state); + }); +}; +const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => { + const { fs } = state; + if (currentDepth < 0) return; + state.visited.push(crawlPath); + state.counts.directories++; + let entries = []; + try { + entries = fs.readdirSync(crawlPath || ".", readdirOpts); + } catch (e) { + if (!state.options.suppressErrors) throw e; + } + callback$1(entries, directoryPath, currentDepth); +}; +function build(isSynchronous) { + return isSynchronous ? walkSync : walkAsync; +} + +//#endregion +//#region src/api/queue.ts +/** +* This is a custom stateless queue to track concurrent async fs calls. +* It increments a counter whenever a call is queued and decrements it +* as soon as it completes. When the counter hits 0, it calls onQueueEmpty. +*/ +var Queue = class { + count = 0; + constructor(onQueueEmpty) { + this.onQueueEmpty = onQueueEmpty; + } + enqueue() { + this.count++; + return this.count; + } + dequeue(error, output) { + if (this.onQueueEmpty && (--this.count <= 0 || error)) { + this.onQueueEmpty(error, output); + if (error) { + output.controller.abort(); + this.onQueueEmpty = void 0; + } + } + } +}; + +//#endregion +//#region src/api/counter.ts +var Counter = class { + _files = 0; + _directories = 0; + set files(num) { + this._files = num; + } + get files() { + return this._files; + } + set directories(num) { + this._directories = num; + } + get directories() { + return this._directories; + } + /** + * @deprecated use `directories` instead + */ + /* c8 ignore next 3 */ + get dirs() { + return this._directories; + } +}; + +//#endregion +//#region src/api/aborter.ts +/** +* AbortController is not supported on Node 14 so we use this until we can drop +* support for Node 14. +*/ +var Aborter = class { + aborted = false; + abort() { + this.aborted = true; + } +}; + +//#endregion +//#region src/api/walker.ts +var Walker = class { + root; + isSynchronous; + state; + joinPath; + pushDirectory; + pushFile; + getArray; + groupFiles; + resolveSymlink; + walkDirectory; + callbackInvoker; + constructor(root, options, callback$1) { + this.isSynchronous = !callback$1; + this.callbackInvoker = build$1(options, this.isSynchronous); + this.root = normalizePath(root, options); + this.state = { + root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1), + paths: [""].slice(0, 0), + groups: [], + counts: new Counter(), + options, + queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)), + symlinks: /* @__PURE__ */ new Map(), + visited: [""].slice(0, 0), + controller: new Aborter(), + fs: options.fs || nativeFs + }; + this.joinPath = build$7(this.root, options); + this.pushDirectory = build$6(this.root, options); + this.pushFile = build$5(options); + this.getArray = build$4(options); + this.groupFiles = build$3(options); + this.resolveSymlink = build$2(options, this.isSynchronous); + this.walkDirectory = build(this.isSynchronous); + } + start() { + this.pushDirectory(this.root, this.state.paths, this.state.options.filters); + this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk); + return this.isSynchronous ? this.callbackInvoker(this.state, null) : null; + } + walk = (entries, directoryPath, depth) => { + const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state; + if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return; + const files = this.getArray(this.state.paths); + for (let i = 0; i < entries.length; ++i) { + const entry = entries[i]; + if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) { + const filename = this.joinPath(entry.name, directoryPath); + this.pushFile(filename, files, this.state.counts, filters); + } else if (entry.isDirectory()) { + let path = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator); + if (exclude && exclude(entry.name, path)) continue; + this.pushDirectory(path, paths, filters); + this.walkDirectory(this.state, path, path, depth - 1, this.walk); + } else if (this.resolveSymlink && entry.isSymbolicLink()) { + let path = joinPathWithBasePath(entry.name, directoryPath); + this.resolveSymlink(path, this.state, (stat, resolvedPath) => { + if (stat.isDirectory()) { + resolvedPath = normalizePath(resolvedPath, this.state.options); + if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path + pathSeparator)) return; + this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path + pathSeparator, depth - 1, this.walk); + } else { + resolvedPath = useRealPaths ? resolvedPath : path; + const filename = basename(resolvedPath); + const directoryPath$1 = normalizePath(dirname(resolvedPath), this.state.options); + resolvedPath = this.joinPath(filename, directoryPath$1); + this.pushFile(resolvedPath, files, this.state.counts, filters); + } + }); + } + } + this.groupFiles(this.state.groups, directoryPath, files); + }; +}; + +//#endregion +//#region src/api/async.ts +function promise(root, options) { + return new Promise((resolve$1, reject) => { + callback(root, options, (err, output) => { + if (err) return reject(err); + resolve$1(output); + }); + }); +} +function callback(root, options, callback$1) { + let walker = new Walker(root, options, callback$1); + walker.start(); +} + +//#endregion +//#region src/api/sync.ts +function sync(root, options) { + const walker = new Walker(root, options); + return walker.start(); +} + +//#endregion +//#region src/builder/api-builder.ts +var APIBuilder = class { + constructor(root, options) { + this.root = root; + this.options = options; + } + withPromise() { + return promise(this.root, this.options); + } + withCallback(cb) { + callback(this.root, this.options, cb); + } + sync() { + return sync(this.root, this.options); + } +}; + +//#endregion +//#region src/builder/index.ts +let pm = null; +/* c8 ignore next 6 */ +try { + __require.resolve("picomatch"); + pm = __require("picomatch"); +} catch {} +var Builder = class { + globCache = {}; + options = { + maxDepth: Infinity, + suppressErrors: true, + pathSeparator: sep, + filters: [] + }; + globFunction; + constructor(options) { + this.options = { + ...this.options, + ...options + }; + this.globFunction = this.options.globFunction; + } + group() { + this.options.group = true; + return this; + } + withPathSeparator(separator) { + this.options.pathSeparator = separator; + return this; + } + withBasePath() { + this.options.includeBasePath = true; + return this; + } + withRelativePaths() { + this.options.relativePaths = true; + return this; + } + withDirs() { + this.options.includeDirs = true; + return this; + } + withMaxDepth(depth) { + this.options.maxDepth = depth; + return this; + } + withMaxFiles(limit) { + this.options.maxFiles = limit; + return this; + } + withFullPaths() { + this.options.resolvePaths = true; + this.options.includeBasePath = true; + return this; + } + withErrors() { + this.options.suppressErrors = false; + return this; + } + withSymlinks({ resolvePaths = true } = {}) { + this.options.resolveSymlinks = true; + this.options.useRealPaths = resolvePaths; + return this.withFullPaths(); + } + withAbortSignal(signal) { + this.options.signal = signal; + return this; + } + normalize() { + this.options.normalizePath = true; + return this; + } + filter(predicate) { + this.options.filters.push(predicate); + return this; + } + onlyDirs() { + this.options.excludeFiles = true; + this.options.includeDirs = true; + return this; + } + exclude(predicate) { + this.options.exclude = predicate; + return this; + } + onlyCounts() { + this.options.onlyCounts = true; + return this; + } + crawl(root) { + return new APIBuilder(root || ".", this.options); + } + withGlobFunction(fn) { + this.globFunction = fn; + return this; + } + /** + * @deprecated Pass options using the constructor instead: + * ```ts + * new fdir(options).crawl("/path/to/root"); + * ``` + * This method will be removed in v7.0 + */ + /* c8 ignore next 4 */ + crawlWithOptions(root, options) { + this.options = { + ...this.options, + ...options + }; + return new APIBuilder(root || ".", this.options); + } + glob(...patterns) { + if (this.globFunction) return this.globWithOptions(patterns); + return this.globWithOptions(patterns, ...[{ dot: true }]); + } + globWithOptions(patterns, ...options) { + const globFn = this.globFunction || pm; + /* c8 ignore next 5 */ + if (!globFn) throw new Error("Please specify a glob function to use glob matching."); + var isMatch = this.globCache[patterns.join("\0")]; + if (!isMatch) { + isMatch = globFn(patterns, ...options); + this.globCache[patterns.join("\0")] = isMatch; + } + this.options.filters.push((path) => isMatch(path)); + return this; + } +}; + +//#endregion +export { Builder as fdir }; \ No newline at end of file diff --git a/node_modules/tinyglobby/node_modules/fdir/package.json b/node_modules/tinyglobby/node_modules/fdir/package.json new file mode 100644 index 0000000000000..e229dff815080 --- /dev/null +++ b/node_modules/tinyglobby/node_modules/fdir/package.json @@ -0,0 +1,103 @@ +{ + "name": "fdir", + "version": "6.5.0", + "description": "The fastest directory crawler & globbing alternative to glob, fast-glob, & tiny-glob. Crawls 1m files in < 1s", + "main": "./dist/index.cjs", + "types": "./dist/index.d.cts", + "type": "module", + "scripts": { + "prepublishOnly": "npm run test && npm run build", + "build": "tsdown", + "format": "prettier --write src __tests__ benchmarks", + "test": "vitest run __tests__/", + "test:coverage": "vitest run --coverage __tests__/", + "test:watch": "vitest __tests__/", + "bench": "ts-node benchmarks/benchmark.js", + "bench:glob": "ts-node benchmarks/glob-benchmark.ts", + "bench:fdir": "ts-node benchmarks/fdir-benchmark.ts", + "release": "./scripts/release.sh" + }, + "engines": { + "node": ">=12.0.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/thecodrr/fdir.git" + }, + "keywords": [ + "util", + "os", + "sys", + "fs", + "walk", + "crawler", + "directory", + "files", + "io", + "tiny-glob", + "glob", + "fast-glob", + "speed", + "javascript", + "nodejs" + ], + "author": "thecodrr ", + "license": "MIT", + "bugs": { + "url": "https://github.com/thecodrr/fdir/issues" + }, + "homepage": "https://github.com/thecodrr/fdir#readme", + "devDependencies": { + "@types/glob": "^8.1.0", + "@types/mock-fs": "^4.13.4", + "@types/node": "^20.9.4", + "@types/picomatch": "^4.0.0", + "@types/tap": "^15.0.11", + "@vitest/coverage-v8": "^0.34.6", + "all-files-in-tree": "^1.1.2", + "benny": "^3.7.1", + "csv-to-markdown-table": "^1.3.1", + "expect": "^29.7.0", + "fast-glob": "^3.3.2", + "fdir1": "npm:fdir@1.2.0", + "fdir2": "npm:fdir@2.1.0", + "fdir3": "npm:fdir@3.4.2", + "fdir4": "npm:fdir@4.1.0", + "fdir5": "npm:fdir@5.0.0", + "fs-readdir-recursive": "^1.1.0", + "get-all-files": "^4.1.0", + "glob": "^10.3.10", + "klaw-sync": "^6.0.0", + "mock-fs": "^5.2.0", + "picomatch": "^4.0.2", + "prettier": "^3.5.3", + "recur-readdir": "0.0.1", + "recursive-files": "^1.0.2", + "recursive-fs": "^2.1.0", + "recursive-readdir": "^2.2.3", + "rrdir": "^12.1.0", + "systeminformation": "^5.21.17", + "tiny-glob": "^0.2.9", + "ts-node": "^10.9.1", + "tsdown": "^0.12.5", + "typescript": "^5.3.2", + "vitest": "^0.34.6", + "walk-sync": "^3.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + }, + "module": "./dist/index.mjs", + "exports": { + ".": { + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" + }, + "./package.json": "./package.json" + } +} diff --git a/node_modules/tinyglobby/node_modules/picomatch/LICENSE b/node_modules/tinyglobby/node_modules/picomatch/LICENSE new file mode 100644 index 0000000000000..3608dca25e30b --- /dev/null +++ b/node_modules/tinyglobby/node_modules/picomatch/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017-present, Jon Schlinkert. + +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. diff --git a/node_modules/tinyglobby/node_modules/picomatch/index.js b/node_modules/tinyglobby/node_modules/picomatch/index.js new file mode 100644 index 0000000000000..a753b1d9e843c --- /dev/null +++ b/node_modules/tinyglobby/node_modules/picomatch/index.js @@ -0,0 +1,17 @@ +'use strict'; + +const pico = require('./lib/picomatch'); +const utils = require('./lib/utils'); + +function picomatch(glob, options, returnState = false) { + // default to os.platform() + if (options && (options.windows === null || options.windows === undefined)) { + // don't mutate the original options object + options = { ...options, windows: utils.isWindows() }; + } + + return pico(glob, options, returnState); +} + +Object.assign(picomatch, pico); +module.exports = picomatch; diff --git a/node_modules/tinyglobby/node_modules/picomatch/lib/constants.js b/node_modules/tinyglobby/node_modules/picomatch/lib/constants.js new file mode 100644 index 0000000000000..f0aeda7d48171 --- /dev/null +++ b/node_modules/tinyglobby/node_modules/picomatch/lib/constants.js @@ -0,0 +1,184 @@ +'use strict'; + +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; + +const DEFAULT_MAX_EXTGLOB_RECURSION = 0; + +/** + * Posix glob regex + */ + +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; +const SEP = '/'; + +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR, + SEP +}; + +/** + * Windows glob regex + */ + +const WINDOWS_CHARS = { + ...POSIX_CHARS, + + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)`, + SEP: '\\' +}; + +/** + * POSIX Bracket Regex + */ + +const POSIX_REGEX_SOURCE = { + __proto__: null, + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; + +module.exports = { + DEFAULT_MAX_EXTGLOB_RECURSION, + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, + + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + __proto__: null, + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, + + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ + + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ + + CHAR_ASTERISK: 42, /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ + + /** + * Create EXTGLOB_CHARS + */ + + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, + + /** + * Create GLOB_CHARS + */ + + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; diff --git a/node_modules/tinyglobby/node_modules/picomatch/lib/parse.js b/node_modules/tinyglobby/node_modules/picomatch/lib/parse.js new file mode 100644 index 0000000000000..57d994a87896b --- /dev/null +++ b/node_modules/tinyglobby/node_modules/picomatch/lib/parse.js @@ -0,0 +1,1386 @@ +'use strict'; + +const constants = require('./constants'); +const utils = require('./utils'); + +/** + * Constants + */ + +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants; + +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.join('-')}]`; + + try { + /* eslint-disable-next-line no-new */ + new RegExp(value); + } catch (ex) { + return args.map(v => utils.escapeRegex(v)).join('..'); + } + + return value; +}; + +/** + * Create the message for a syntax error + */ + +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; + +const splitTopLevel = input => { + const parts = []; + let bracket = 0; + let paren = 0; + let quote = 0; + let value = ''; + let escaped = false; + + for (const ch of input) { + if (escaped === true) { + value += ch; + escaped = false; + continue; + } + + if (ch === '\\') { + value += ch; + escaped = true; + continue; + } + + if (ch === '"') { + quote = quote === 1 ? 0 : 1; + value += ch; + continue; + } + + if (quote === 0) { + if (ch === '[') { + bracket++; + } else if (ch === ']' && bracket > 0) { + bracket--; + } else if (bracket === 0) { + if (ch === '(') { + paren++; + } else if (ch === ')' && paren > 0) { + paren--; + } else if (ch === '|' && paren === 0) { + parts.push(value); + value = ''; + continue; + } + } + } + + value += ch; + } + + parts.push(value); + return parts; +}; + +const isPlainBranch = branch => { + let escaped = false; + + for (const ch of branch) { + if (escaped === true) { + escaped = false; + continue; + } + + if (ch === '\\') { + escaped = true; + continue; + } + + if (/[?*+@!()[\]{}]/.test(ch)) { + return false; + } + } + + return true; +}; + +const normalizeSimpleBranch = branch => { + let value = branch.trim(); + let changed = true; + + while (changed === true) { + changed = false; + + if (/^@\([^\\()[\]{}|]+\)$/.test(value)) { + value = value.slice(2, -1); + changed = true; + } + } + + if (!isPlainBranch(value)) { + return; + } + + return value.replace(/\\(.)/g, '$1'); +}; + +const hasRepeatedCharPrefixOverlap = branches => { + const values = branches.map(normalizeSimpleBranch).filter(Boolean); + + for (let i = 0; i < values.length; i++) { + for (let j = i + 1; j < values.length; j++) { + const a = values[i]; + const b = values[j]; + const char = a[0]; + + if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) { + continue; + } + + if (a === b || a.startsWith(b) || b.startsWith(a)) { + return true; + } + } + } + + return false; +}; + +const parseRepeatedExtglob = (pattern, requireEnd = true) => { + if ((pattern[0] !== '+' && pattern[0] !== '*') || pattern[1] !== '(') { + return; + } + + let bracket = 0; + let paren = 0; + let quote = 0; + let escaped = false; + + for (let i = 1; i < pattern.length; i++) { + const ch = pattern[i]; + + if (escaped === true) { + escaped = false; + continue; + } + + if (ch === '\\') { + escaped = true; + continue; + } + + if (ch === '"') { + quote = quote === 1 ? 0 : 1; + continue; + } + + if (quote === 1) { + continue; + } + + if (ch === '[') { + bracket++; + continue; + } + + if (ch === ']' && bracket > 0) { + bracket--; + continue; + } + + if (bracket > 0) { + continue; + } + + if (ch === '(') { + paren++; + continue; + } + + if (ch === ')') { + paren--; + + if (paren === 0) { + if (requireEnd === true && i !== pattern.length - 1) { + return; + } + + return { + type: pattern[0], + body: pattern.slice(2, i), + end: i + }; + } + } + } +}; + +const getStarExtglobSequenceOutput = pattern => { + let index = 0; + const chars = []; + + while (index < pattern.length) { + const match = parseRepeatedExtglob(pattern.slice(index), false); + + if (!match || match.type !== '*') { + return; + } + + const branches = splitTopLevel(match.body).map(branch => branch.trim()); + if (branches.length !== 1) { + return; + } + + const branch = normalizeSimpleBranch(branches[0]); + if (!branch || branch.length !== 1) { + return; + } + + chars.push(branch); + index += match.end + 1; + } + + if (chars.length < 1) { + return; + } + + const source = chars.length === 1 + ? utils.escapeRegex(chars[0]) + : `[${chars.map(ch => utils.escapeRegex(ch)).join('')}]`; + + return `${source}*`; +}; + +const repeatedExtglobRecursion = pattern => { + let depth = 0; + let value = pattern.trim(); + let match = parseRepeatedExtglob(value); + + while (match) { + depth++; + value = match.body.trim(); + match = parseRepeatedExtglob(value); + } + + return depth; +}; + +const analyzeRepeatedExtglob = (body, options) => { + if (options.maxExtglobRecursion === false) { + return { risky: false }; + } + + const max = + typeof options.maxExtglobRecursion === 'number' + ? options.maxExtglobRecursion + : constants.DEFAULT_MAX_EXTGLOB_RECURSION; + + const branches = splitTopLevel(body).map(branch => branch.trim()); + + if (branches.length > 1) { + if ( + branches.some(branch => branch === '') || + branches.some(branch => /^[*?]+$/.test(branch)) || + hasRepeatedCharPrefixOverlap(branches) + ) { + return { risky: true }; + } + } + + for (const branch of branches) { + const safeOutput = getStarExtglobSequenceOutput(branch); + if (safeOutput) { + return { risky: true, safeOutput }; + } + + if (repeatedExtglobRecursion(branch) > max) { + return { risky: true }; + } + } + + return { risky: false }; +}; + +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + +const parse = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + input = REPLACEMENTS[input] || input; + + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; + + const capture = opts.capture ? '' : '?:'; + + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants.globChars(opts.windows); + const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); + + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } + + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + + input = utils.removePrefix(input, state); + len = input.length; + + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ''; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; + } + + if (count % 2 === 0) { + return false; + } + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren') { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.output = (prev.output || prev.value) + tok.value; + prev.value += tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + token.startIndex = state.index; + token.tokensIndex = tokens.length; + const output = (opts.capture ? '(' : '') + token.open; + + increment('parens'); + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; + + const extglobClose = token => { + const literal = input.slice(token.startIndex, state.index + 1); + const body = input.slice(token.startIndex + 2, state.index); + const analysis = analyzeRepeatedExtglob(body, opts); + + if ((token.type === 'plus' || token.type === 'star') && analysis.risky) { + const safeOutput = analysis.safeOutput + ? (token.output ? '' : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) + : undefined; + const open = tokens[token.tokensIndex]; + + open.type = 'text'; + open.value = literal; + open.output = safeOutput || utils.escapeRegex(literal); + + for (let i = token.tokensIndex + 1; i < tokens.length; i++) { + tokens[i].value = ''; + tokens[i].output = ''; + delete tokens[i].suffix; + } + + state.output = token.output + open.output; + state.backtrack = true; + + push({ type: 'paren', extglob: true, value, output: '' }); + decrement('parens'); + return; + } + + let output = token.close + (opts.capture ? ')' : ''); + let rest; + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. + // In this case, we need to parse the string and use it in the output of the original pattern. + // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. + // + // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. + const expression = parse(rest, { ...options, fastpaths: false }).output; + + output = token.close = `)${expression})${extglobStar})`; + } + + if (token.prev.type === 'bos') { + state.negatedExtglob = true; + } + } + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + return star; + } + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); + }); + } + } + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils.wrapOutput(output, state, options); + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + + /** + * Escaped characters + */ + + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } + } + + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } + + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; + } + + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + + /** + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; + } + + /** + * Parentheses + */ + + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } + + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + + /** + * Square brackets + */ + + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } + + value = `\\${value}`; + } else { + increment('brackets'); + } + + push({ type: 'bracket', value }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } + + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + decrement('brackets'); + + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + + prev.value += value; + append({ value }); + + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + + /** + * Braces + */ + + if (value === '{' && opts.nobrace !== true) { + increment('braces'); + + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + + braces.push(open); + push(open); + continue; + } + + if (value === '}') { + const brace = braces[braces.length - 1]; + + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } + + let output = ')'; + + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } + + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; + } + + /** + * Pipes + */ + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } + + /** + * Commas + */ + + if (value === ',') { + let output = value; + + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } + + push({ type: 'comma', value, output }); + continue; + } + + /** + * Slashes + */ + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } + + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; + } + + /** + * Dots + */ + + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; + } + + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; + } + + /** + * Question marks + */ + + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } + + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; + + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } + + push({ type: 'text', value, output }); + continue; + } + + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } + + push({ type: 'qmark', value, output: QMARK }); + continue; + } + + /** + * Exclamation + */ + + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } + + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + + /** + * Plus + */ + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } + + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } + + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; + } + + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } + + /** + * Plain text + */ + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Plain text + */ + + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } + + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Stars + */ + + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } + + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } + + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } + + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; + + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + + state.output += prior.output + prev.output; + state.globstar = true; + + consume(value + advance()); + + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); + + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; + + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + + const token = { type: 'star', value, output: star }; + + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + + } else { + state.output += nodot; + prev.output += nodot; + } + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } + + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; + } + } + } + + return state; +}; + +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + +parse.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants.globChars(opts.windows); + + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + + const source = create(match[1]); + if (!source) return; + + return source + DOT_LITERAL + match[2]; + } + } + }; + + const output = utils.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +module.exports = parse; diff --git a/node_modules/tinyglobby/node_modules/picomatch/lib/picomatch.js b/node_modules/tinyglobby/node_modules/picomatch/lib/picomatch.js new file mode 100644 index 0000000000000..fbb8b1ca9f1e1 --- /dev/null +++ b/node_modules/tinyglobby/node_modules/picomatch/lib/picomatch.js @@ -0,0 +1,349 @@ +'use strict'; + +const scan = require('./scan'); +const parse = require('./parse'); +const utils = require('./utils'); +const constants = require('./constants'); +const isObject = val => val && typeof val === 'object' && !Array.isArray(val); + +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + +const picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } + + const isState = isObject(glob) && glob.tokens && glob.input; + + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); + } + + const opts = options || {}; + const posix = opts.windows; + const regex = isState + ? picomatch.compileRe(glob, options) + : picomatch.makeRe(glob, options, false, true); + + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; + + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } + + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; +}; + +/** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + +picomatch.test = (input, regex, options, { glob, posix } = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + if (input === '') { + return { isMatch: false, output: '' }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + + return { isMatch: Boolean(match), match, output }; +}; + +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + +picomatch.matchBase = (input, glob, options) => { + const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex.test(utils.basename(input)); +}; + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + +picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); + return parse(pattern, { ...options, fastpaths: false }); +}; + +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +picomatch.scan = (input, options) => scan(input, options); + +/** + * Compile a regular expression from the `state` object returned by the + * [parse()](#parse) method. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {Object} `state` + * @param {Object} `options` + * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. + * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. + * @return {RegExp} + * @api public + */ + +picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } + + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; + } + + const regex = picomatch.toRegex(source, options); + if (returnState === true) { + regex.state = state; + } + + return regex; +}; + +/** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.makeRe(state[, options]); + * + * const result = picomatch.makeRe('*.js'); + * console.log(result); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. + * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } + + let parsed = { negated: false, fastpaths: true }; + + if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + parsed.output = parse.fastpaths(input, options); + } + + if (!parsed.output) { + parsed = parse(input, options); + } + + return picomatch.compileRe(parsed, options, returnOutput, returnState); +}; + +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; + +/** + * Picomatch constants. + * @return {Object} + */ + +picomatch.constants = constants; + +/** + * Expose "picomatch" + */ + +module.exports = picomatch; diff --git a/node_modules/tinyglobby/node_modules/picomatch/lib/scan.js b/node_modules/tinyglobby/node_modules/picomatch/lib/scan.js new file mode 100644 index 0000000000000..e59cd7a1357b1 --- /dev/null +++ b/node_modules/tinyglobby/node_modules/picomatch/lib/scan.js @@ -0,0 +1,391 @@ +'use strict'; + +const utils = require('./utils'); +const { + CHAR_ASTERISK, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET /* ] */ +} = require('./constants'); + +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; + +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; + +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not + * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + +const scan = (input, options) => { + const opts = options || {}; + + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; + + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + + while (index < length) { + code = advance(); + let next; + + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; + } + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; + + if (finished === true) continue; + if (prev === CHAR_DOT && index === (start + 1)) { + start += 2; + continue; + } + + lastIndex = index + 1; + continue; + } + + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; + + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) { + negatedExtglob = true; + } + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; + break; + } + } + continue; + } + break; + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + + let base = str; + let prefix = ''; + let glob = ''; + + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + + if (opts.unescape === true) { + if (glob) glob = utils.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils.removeBackslashes(base); + } + } + + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; + + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } + + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== '') { + parts.push(value); + } + prevIndex = i; + } + + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + + state.slashes = slashes; + state.parts = parts; + } + + return state; +}; + +module.exports = scan; diff --git a/node_modules/tinyglobby/node_modules/picomatch/lib/utils.js b/node_modules/tinyglobby/node_modules/picomatch/lib/utils.js new file mode 100644 index 0000000000000..9c97cae222ca8 --- /dev/null +++ b/node_modules/tinyglobby/node_modules/picomatch/lib/utils.js @@ -0,0 +1,72 @@ +/*global navigator*/ +'use strict'; + +const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL +} = require('./constants'); + +exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); +exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); +exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); +exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); +exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + +exports.isWindows = () => { + if (typeof navigator !== 'undefined' && navigator.platform) { + const platform = navigator.platform.toLowerCase(); + return platform === 'win32' || platform === 'windows'; + } + + if (typeof process !== 'undefined' && process.platform) { + return process.platform === 'win32'; + } + + return false; +}; + +exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); +}; + +exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; +}; + +exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; +}; + +exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; +}; + +exports.basename = (path, { windows } = {}) => { + const segs = path.split(windows ? /[\\/]/ : '/'); + const last = segs[segs.length - 1]; + + if (last === '') { + return segs[segs.length - 2]; + } + + return last; +}; diff --git a/node_modules/tinyglobby/node_modules/picomatch/package.json b/node_modules/tinyglobby/node_modules/picomatch/package.json new file mode 100644 index 0000000000000..9151f1d83587d --- /dev/null +++ b/node_modules/tinyglobby/node_modules/picomatch/package.json @@ -0,0 +1,82 @@ +{ + "name": "picomatch", + "description": "Blazing fast and accurate glob matcher written in JavaScript, with no dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.", + "version": "4.0.4", + "homepage": "https://github.com/micromatch/picomatch", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "funding": "https://github.com/sponsors/jonschlinkert", + "repository": "micromatch/picomatch", + "bugs": { + "url": "https://github.com/micromatch/picomatch/issues" + }, + "license": "MIT", + "files": [ + "index.js", + "posix.js", + "lib" + ], + "sideEffects": false, + "main": "index.js", + "engines": { + "node": ">=12" + }, + "scripts": { + "lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .", + "mocha": "mocha --reporter dot", + "test": "npm run lint && npm run mocha", + "test:ci": "npm run test:cover", + "test:cover": "nyc npm run mocha" + }, + "devDependencies": { + "eslint": "^8.57.0", + "fill-range": "^7.0.1", + "gulp-format-md": "^2.0.0", + "mocha": "^10.4.0", + "nyc": "^15.1.0" + }, + "keywords": [ + "glob", + "match", + "picomatch" + ], + "nyc": { + "reporter": [ + "html", + "lcov", + "text-summary" + ] + }, + "verb": { + "toc": { + "render": true, + "method": "preWrite", + "maxdepth": 3 + }, + "layout": "empty", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "related": { + "list": [ + "braces", + "micromatch" + ] + }, + "reflinks": [ + "braces", + "expand-brackets", + "extglob", + "fill-range", + "micromatch", + "minimatch", + "nanomatch", + "picomatch" + ] + } +} diff --git a/node_modules/tinyglobby/node_modules/picomatch/posix.js b/node_modules/tinyglobby/node_modules/picomatch/posix.js new file mode 100644 index 0000000000000..d2f2bc59d0ac7 --- /dev/null +++ b/node_modules/tinyglobby/node_modules/picomatch/posix.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/picomatch'); diff --git a/node_modules/tinyglobby/package.json b/node_modules/tinyglobby/package.json new file mode 100644 index 0000000000000..06dadac3a6130 --- /dev/null +++ b/node_modules/tinyglobby/package.json @@ -0,0 +1,73 @@ +{ + "name": "tinyglobby", + "version": "0.2.16", + "description": "A fast and minimal alternative to globby and fast-glob", + "type": "module", + "main": "./dist/index.cjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.cts", + "exports": { + ".": { + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" + }, + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "dist" + ], + "author": "Superchupu", + "license": "MIT", + "keywords": [ + "glob", + "patterns", + "fast", + "implementation" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/SuperchupuDev/tinyglobby.git" + }, + "bugs": { + "url": "https://github.com/SuperchupuDev/tinyglobby/issues" + }, + "homepage": "https://superchupu.dev/tinyglobby", + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + }, + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "devDependencies": { + "@biomejs/biome": "^2.4.10", + "@types/node": "^25.5.2", + "@types/picomatch": "^4.0.3", + "fast-glob": "^3.3.3", + "fs-fixture": "^2.13.0", + "glob": "^13.0.6", + "tinybench": "^6.0.0", + "tsdown": "^0.21.7", + "typescript": "^6.0.2" + }, + "engines": { + "node": ">=12.0.0" + }, + "publishConfig": { + "provenance": true + }, + "scripts": { + "bench": "node benchmark/bench.ts", + "bench:setup": "node benchmark/setup.ts", + "build": "tsdown", + "check": "biome check", + "check:fix": "biome check --write --unsafe", + "format": "biome format --write", + "lint": "biome lint", + "test": "node --test \"test/**/*.ts\"", + "test:coverage": "node --test --experimental-test-coverage \"test/**/*.ts\"", + "test:only": "node --test --test-only \"test/**/*.ts\"", + "typecheck": "tsc --noEmit" + } +} \ No newline at end of file diff --git a/node_modules/tuf-js/dist/config.js b/node_modules/tuf-js/dist/config.js index 6845679942fec..a15e161cc61ac 100644 --- a/node_modules/tuf-js/dist/config.js +++ b/node_modules/tuf-js/dist/config.js @@ -2,7 +2,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultConfig = void 0; exports.defaultConfig = { - maxRootRotations: 32, + maxRootRotations: 256, maxDelegations: 32, rootMaxLength: 512000, //bytes timestampMaxLength: 16384, // bytes @@ -12,4 +12,5 @@ exports.defaultConfig = { fetchTimeout: 100000, // milliseconds fetchRetries: undefined, fetchRetry: 2, + userAgent: '', }; diff --git a/node_modules/tuf-js/dist/error.js b/node_modules/tuf-js/dist/error.js index f4b10fa202895..3a3c26a068a95 100644 --- a/node_modules/tuf-js/dist/error.js +++ b/node_modules/tuf-js/dist/error.js @@ -40,6 +40,7 @@ class DownloadLengthMismatchError extends DownloadError { exports.DownloadLengthMismatchError = DownloadLengthMismatchError; // Returned by FetcherInterface implementations for HTTP errors. class DownloadHTTPError extends DownloadError { + statusCode; constructor(message, statusCode) { super(message); this.statusCode = statusCode; diff --git a/node_modules/tuf-js/dist/fetcher.js b/node_modules/tuf-js/dist/fetcher.js index f966ce1bb0cdc..dc6373d828896 100644 --- a/node_modules/tuf-js/dist/fetcher.js +++ b/node_modules/tuf-js/dist/fetcher.js @@ -6,11 +6,12 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.DefaultFetcher = exports.BaseFetcher = void 0; const debug_1 = __importDefault(require("debug")); const fs_1 = __importDefault(require("fs")); -const make_fetch_happen_1 = __importDefault(require("make-fetch-happen")); const util_1 = __importDefault(require("util")); const error_1 = require("./error"); const tmpfile_1 = require("./utils/tmpfile"); +const promise_retry_1 = require("@gar/promise-retry"); const log = (0, debug_1.default)('tuf:fetch'); +const USER_AGENT_HEADER = 'User-Agent'; class BaseFetcher { // Download file from given URL. The file is downloaded to a temporary // location and then passed to the given handler. The handler is responsible @@ -23,18 +24,24 @@ class BaseFetcher { const fileStream = fs_1.default.createWriteStream(tmpFile); // Read the stream a chunk at a time so that we can check // the length of the file as we go + const streamReader = reader.getReader(); try { - for await (const chunk of reader) { - const bufferChunk = Buffer.from(chunk); - numberOfBytesReceived += bufferChunk.length; + while (true) { + const { done, value: chunk } = await streamReader.read(); + if (done) { + break; + } + numberOfBytesReceived += chunk.length; if (numberOfBytesReceived > maxLength) { throw new error_1.DownloadLengthMismatchError('Max length reached'); } - await writeBufferToStream(fileStream, bufferChunk); + await writeBufferToStream(fileStream, Buffer.from(chunk)); } } finally { + streamReader.releaseLock(); // Make sure we always close the stream + // eslint-disable-next-line @typescript-eslint/unbound-method await util_1.default.promisify(fileStream.close).bind(fileStream)(); } return handler(tmpFile); @@ -54,21 +61,61 @@ class BaseFetcher { } exports.BaseFetcher = BaseFetcher; class DefaultFetcher extends BaseFetcher { + userAgent; + timeout; + retry; constructor(options = {}) { super(); + this.userAgent = options.userAgent; this.timeout = options.timeout; - this.retry = options.retry; + // Map retry to OperationOptions + if (options.retry === true) { + this.retry = { forever: true }; + } + else if (options.retry === false || options.retry === undefined) { + this.retry = undefined; + } + else if (typeof options.retry === 'number') { + if (options.retry < 0) { + throw new Error('Retry count must be non-negative number'); + } + this.retry = { retries: options.retry }; + } + else { + this.retry = options.retry; + } } async fetch(url) { - log('GET %s', url); - const response = await (0, make_fetch_happen_1.default)(url, { - timeout: this.timeout, - retry: this.retry, - }); - if (!response.ok || !response?.body) { - throw new error_1.DownloadHTTPError('Failed to download', response.status); - } - return response.body; + const shouldRetry = this.retry !== undefined; + return (0, promise_retry_1.promiseRetry)(async (retry, number) => { + log('GET %s (attempt %d)', url, number); + let response; + try { + response = await fetch(url, { + headers: { + [USER_AGENT_HEADER]: this.userAgent || '', + }, + signal: this.timeout + ? AbortSignal.timeout(this.timeout) + : undefined, + }); + } + catch (error) { + const err = error instanceof Error ? error : new Error(String(error)); + if (shouldRetry) { + return retry(err); + } + throw err; + } + if (!response.ok || !response.body) { + const err = new error_1.DownloadHTTPError('Failed to download', response.status); + if (shouldRetry && response.status >= 500 && response.status < 600) { + return retry(err); + } + throw err; + } + return response.body; + }, this.retry); } } exports.DefaultFetcher = DefaultFetcher; diff --git a/node_modules/tuf-js/dist/store.js b/node_modules/tuf-js/dist/store.js index 8567336108709..1b1669029a8db 100644 --- a/node_modules/tuf-js/dist/store.js +++ b/node_modules/tuf-js/dist/store.js @@ -4,8 +4,9 @@ exports.TrustedMetadataStore = void 0; const models_1 = require("@tufjs/models"); const error_1 = require("./error"); class TrustedMetadataStore { + trustedSet = {}; + referenceTime; constructor(rootData) { - this.trustedSet = {}; // Client workflow 5.1: record fixed update start time this.referenceTime = new Date(); // Client workflow 5.2: load trusted root metadata @@ -30,7 +31,9 @@ class TrustedMetadataStore { return this.trustedSet[name]; } updateRoot(bytesBuffer) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const data = JSON.parse(bytesBuffer.toString('utf8')); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument const newRoot = models_1.Metadata.fromJSON(models_1.MetadataKind.Root, data); if (newRoot.signed.type != models_1.MetadataKind.Root) { throw new error_1.RepositoryError(`Expected 'root', got ${newRoot.signed.type}`); @@ -54,7 +57,9 @@ class TrustedMetadataStore { if (this.root.signed.isExpired(this.referenceTime)) { throw new error_1.ExpiredMetadataError('Final root.json is expired'); } + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const data = JSON.parse(bytesBuffer.toString('utf8')); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument const newTimestamp = models_1.Metadata.fromJSON(models_1.MetadataKind.Timestamp, data); if (newTimestamp.signed.type != models_1.MetadataKind.Timestamp) { throw new error_1.RepositoryError(`Expected 'timestamp', got ${newTimestamp.signed.type}`); @@ -102,7 +107,9 @@ class TrustedMetadataStore { if (!trusted) { snapshotMeta.verify(bytesBuffer); } + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const data = JSON.parse(bytesBuffer.toString('utf8')); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument const newSnapshot = models_1.Metadata.fromJSON(models_1.MetadataKind.Snapshot, data); if (newSnapshot.signed.type != models_1.MetadataKind.Snapshot) { throw new error_1.RepositoryError(`Expected 'snapshot', got ${newSnapshot.signed.type}`); @@ -147,7 +154,9 @@ class TrustedMetadataStore { } // Client workflow 5.6.2: check against snapshot role's targets hash meta.verify(bytesBuffer); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const data = JSON.parse(bytesBuffer.toString('utf8')); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument const newDelegate = models_1.Metadata.fromJSON(models_1.MetadataKind.Targets, data); if (newDelegate.signed.type != models_1.MetadataKind.Targets) { throw new error_1.RepositoryError(`Expected 'targets', got ${newDelegate.signed.type}`); @@ -168,7 +177,9 @@ class TrustedMetadataStore { // Verifies and loads data as trusted root metadata. // Note that an expired initial root is still considered valid. loadTrustedRoot(bytesBuffer) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const data = JSON.parse(bytesBuffer.toString('utf8')); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument const root = models_1.Metadata.fromJSON(models_1.MetadataKind.Root, data); if (root.signed.type != models_1.MetadataKind.Root) { throw new error_1.RepositoryError(`Expected 'root', got ${root.signed.type}`); diff --git a/node_modules/tuf-js/dist/updater.js b/node_modules/tuf-js/dist/updater.js index 5317f7e14659a..94a7658155740 100644 --- a/node_modules/tuf-js/dist/updater.js +++ b/node_modules/tuf-js/dist/updater.js @@ -15,13 +15,23 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( }) : 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 __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -31,6 +41,7 @@ const models_1 = require("@tufjs/models"); const debug_1 = __importDefault(require("debug")); const fs = __importStar(require("fs")); const path = __importStar(require("path")); +const package_json_1 = require("../package.json"); const config_1 = require("./config"); const error_1 = require("./error"); const fetcher_1 = require("./fetcher"); @@ -38,6 +49,14 @@ const store_1 = require("./store"); const url = __importStar(require("./utils/url")); const log = (0, debug_1.default)('tuf:cache'); class Updater { + dir; + metadataBaseUrl; + targetDir; + targetBaseUrl; + forceCache; + trustedSet; + config; + fetcher; constructor(options) { const { metadataDir, metadataBaseUrl, targetDir, targetBaseUrl, fetcher, config, } = options; this.dir = metadataDir; @@ -48,9 +67,13 @@ class Updater { const data = this.loadLocalMetadata(models_1.MetadataKind.Root); this.trustedSet = new store_1.TrustedMetadataStore(data); this.config = { ...config_1.defaultConfig, ...config }; + const userAgent = config?.userAgent + ? `${config.userAgent} tuf-js/${package_json_1.version}` + : `tuf-js/${package_json_1.version}`; this.fetcher = fetcher || new fetcher_1.DefaultFetcher({ + userAgent, timeout: this.config.fetchTimeout, retry: this.config.fetchRetries ?? this.config.fetchRetry, }); @@ -144,7 +167,7 @@ class Updater { const rootVersion = this.trustedSet.root.signed.version; const lowerBound = rootVersion + 1; const upperBound = lowerBound + this.config.maxRootRotations; - for (let version = lowerBound; version <= upperBound; version++) { + for (let version = lowerBound; version < upperBound; version++) { const rootUrl = url.join(this.metadataBaseUrl, `${version}.root.json`); try { // Client workflow 5.3.3: download new root metadata file @@ -155,7 +178,13 @@ class Updater { this.persistMetadata(models_1.MetadataKind.Root, bytesData); } catch (error) { - break; + if (error instanceof error_1.DownloadHTTPError) { + // 404/403 means current root is newest available + if ([403, 404].includes(error.statusCode)) { + break; + } + } + throw error; } } } @@ -205,7 +234,7 @@ class Updater { } catch (error) { if (!this.trustedSet.timestamp) { - throw new ReferenceError('No timestamp metadata'); + throw new ReferenceError('No timestamp metadata', { cause: error }); } const snapshotMeta = this.trustedSet.timestamp.signed.snapshotMeta; const maxLength = snapshotMeta.length || this.config.snapshotMaxLength; @@ -239,7 +268,7 @@ class Updater { catch (error) { // Local 'role' does not exist or is invalid: update from remote if (!this.trustedSet.snapshot) { - throw new ReferenceError('No snapshot metadata'); + throw new ReferenceError('No snapshot metadata', { cause: error }); } const metaInfo = this.trustedSet.snapshot.signed.meta[`${role}.json`]; // TODO: use length for fetching @@ -247,7 +276,8 @@ class Updater { const version = this.trustedSet.root.signed.consistentSnapshot ? metaInfo.version : undefined; - const metadataUrl = url.join(this.metadataBaseUrl, version ? `${version}.${role}.json` : `${role}.json`); + const encodedRole = encodeURIComponent(role); + const metadataUrl = url.join(this.metadataBaseUrl, version ? `${version}.${encodedRole}.json` : `${encodedRole}.json`); try { // Client workflow 5.6.1: download targets metadata file const bytesData = await this.fetcher.downloadBytes(metadataUrl, maxLength); @@ -280,7 +310,6 @@ class Updater { while (visitedRoleNames.size <= this.config.maxDelegations && delegationsToVisit.length > 0) { // Pop the role name from the top of the stack. - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { roleName, parentRoleName } = delegationsToVisit.pop(); // Skip any visited current role to prevent cycles. // Client workflow 5.6.7.1: skip already-visited roles @@ -330,13 +359,14 @@ class Updater { return path.join(this.targetDir, filePath); } persistMetadata(metaDataName, bytesData) { + const encodedName = encodeURIComponent(metaDataName); try { - const filePath = path.join(this.dir, `${metaDataName}.json`); + const filePath = path.join(this.dir, `${encodedName}.json`); log('WRITE %s', filePath); fs.writeFileSync(filePath, bytesData.toString('utf8')); } catch (error) { - throw new error_1.PersistError(`Failed to persist metadata ${metaDataName} error: ${error}`); + throw new error_1.PersistError(`Failed to persist metadata ${encodedName} error: ${error}`); } } } diff --git a/node_modules/tuf-js/dist/utils/url.js b/node_modules/tuf-js/dist/utils/url.js index ce67fe2c23053..359d1f3ef385b 100644 --- a/node_modules/tuf-js/dist/utils/url.js +++ b/node_modules/tuf-js/dist/utils/url.js @@ -1,11 +1,10 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.join = void 0; +exports.join = join; const url_1 = require("url"); function join(base, path) { return new url_1.URL(ensureTrailingSlash(base) + removeLeadingSlash(path)).toString(); } -exports.join = join; function ensureTrailingSlash(path) { return path.endsWith('/') ? path : path + '/'; } diff --git a/node_modules/@tufjs/models/LICENSE b/node_modules/tuf-js/node_modules/@tufjs/models/LICENSE similarity index 100% rename from node_modules/@tufjs/models/LICENSE rename to node_modules/tuf-js/node_modules/@tufjs/models/LICENSE diff --git a/node_modules/tuf-js/node_modules/@tufjs/models/dist/base.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/base.js new file mode 100644 index 0000000000000..14f0024f8091a --- /dev/null +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/base.js @@ -0,0 +1,96 @@ +"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 { + specVersion; + expires; + version; + unrecognizedFields; + 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)); +} diff --git a/node_modules/@tufjs/models/dist/delegations.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/delegations.js similarity index 98% rename from node_modules/@tufjs/models/dist/delegations.js rename to node_modules/tuf-js/node_modules/@tufjs/models/dist/delegations.js index 7165f1e244393..9ad8bf05f1c6b 100644 --- a/node_modules/@tufjs/models/dist/delegations.js +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/delegations.js @@ -16,6 +16,10 @@ const utils_1 = require("./utils"); * describing targets with designated pathnames and/or further delegations. */ class Delegations { + keys; + roles; + unrecognizedFields; + succinctRoles; constructor(options) { this.keys = options.keys; this.unrecognizedFields = options.unrecognizedFields || {}; diff --git a/node_modules/@tufjs/models/dist/error.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/error.js similarity index 100% rename from node_modules/@tufjs/models/dist/error.js rename to node_modules/tuf-js/node_modules/@tufjs/models/dist/error.js diff --git a/node_modules/tuf-js/node_modules/@tufjs/models/dist/file.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/file.js new file mode 100644 index 0000000000000..c8cdcb1c40271 --- /dev/null +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/file.js @@ -0,0 +1,191 @@ +"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 { + version; + length; + hashes; + unrecognizedFields; + 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 { + length; + path; + hashes; + unrecognizedFields; + 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'); + } +} diff --git a/node_modules/@tufjs/models/dist/index.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/index.js similarity index 100% rename from node_modules/@tufjs/models/dist/index.js rename to node_modules/tuf-js/node_modules/@tufjs/models/dist/index.js diff --git a/node_modules/tuf-js/node_modules/@tufjs/models/dist/key.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/key.js new file mode 100644 index 0000000000000..10bf2f4b66fc0 --- /dev/null +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/key.js @@ -0,0 +1,90 @@ +"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 { + keyID; + keyType; + scheme; + keyVal; + unrecognizedFields; + 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; diff --git a/node_modules/@tufjs/models/dist/metadata.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/metadata.js similarity index 89% rename from node_modules/@tufjs/models/dist/metadata.js rename to node_modules/tuf-js/node_modules/@tufjs/models/dist/metadata.js index 9668b6f14fa70..1ae4b6829c0c7 100644 --- a/node_modules/@tufjs/models/dist/metadata.js +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/metadata.js @@ -39,6 +39,9 @@ const utils_1 = require("./utils"); * reasonable default values for new metadata. */ class Metadata { + signed; + signatures; + unrecognizedFields; constructor(signed, signatures, unrecognizedFields) { this.signed = signed; this.signatures = signatures || {}; @@ -103,7 +106,9 @@ class Metadata { if (!(other instanceof Metadata)) { return false; } - return (this.signed.equals(other.signed) && + return ( + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + this.signed.equals(other.signed) && util_1.default.isDeepStrictEqual(this.signatures, other.signatures) && util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); } @@ -125,6 +130,9 @@ class Metadata { 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: @@ -142,17 +150,16 @@ class Metadata { default: throw new TypeError('invalid metadata type'); } - const sigMap = signaturesFromJSON(signatures); + 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; -function signaturesFromJSON(data) { - if (!utils_1.guard.isObjectArray(data)) { - throw new TypeError('signatures is not an array'); - } - return data.reduce((acc, sigData) => { - const signature = signature_1.Signature.fromJSON(sigData); - return { ...acc, [signature.keyID]: signature }; - }, {}); -} diff --git a/node_modules/@tufjs/models/dist/role.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/role.js similarity index 98% rename from node_modules/@tufjs/models/dist/role.js rename to node_modules/tuf-js/node_modules/@tufjs/models/dist/role.js index f7ddbc6fe3f38..6c049e17c8dab 100644 --- a/node_modules/@tufjs/models/dist/role.js +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/role.js @@ -22,6 +22,9 @@ exports.TOP_LEVEL_ROLE_NAMES = [ * metadata, and which keys are accepted. */ class Role { + keyIDs; + threshold; + unrecognizedFields; constructor(options) { const { keyIDs, threshold, unrecognizedFields } = options; if (hasDuplicates(keyIDs)) { @@ -80,6 +83,10 @@ function hasDuplicates(array) { * set, at least one of them must be set. */ class DelegatedRole extends Role { + name; + terminating; + paths; + pathHashPrefixes; constructor(opts) { super(opts); const { name, terminating, paths, pathHashPrefixes } = opts; @@ -187,6 +194,10 @@ function isTargetInPathPattern(target, pattern) { * For details: https://github.com/theupdateframework/taps/blob/master/tap15.md */ class SuccinctRoles extends Role { + bitLength; + namePrefix; + numberOfBins; + suffixLen; constructor(opts) { super(opts); const { bitLength, namePrefix } = opts; diff --git a/node_modules/@tufjs/models/dist/root.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/root.js similarity index 98% rename from node_modules/@tufjs/models/dist/root.js rename to node_modules/tuf-js/node_modules/@tufjs/models/dist/root.js index 36d0ef0f186d1..76d4e4039980e 100644 --- a/node_modules/@tufjs/models/dist/root.js +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/root.js @@ -17,9 +17,12 @@ const utils_1 = require("./utils"); * This role specifies trusted keys for all other top-level roles, which may further delegate trust. */ class Root extends base_1.Signed { + type = base_1.MetadataKind.Root; + keys; + roles; + consistentSnapshot; constructor(options) { super(options); - this.type = base_1.MetadataKind.Root; this.keys = options.keys || {}; this.consistentSnapshot = options.consistentSnapshot ?? true; if (!options.roles) { diff --git a/node_modules/@tufjs/models/dist/signature.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/signature.js similarity index 98% rename from node_modules/@tufjs/models/dist/signature.js rename to node_modules/tuf-js/node_modules/@tufjs/models/dist/signature.js index 33eb204eb0835..43c0bfe58c483 100644 --- a/node_modules/@tufjs/models/dist/signature.js +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/signature.js @@ -10,6 +10,8 @@ exports.Signature = void 0; * Provide a `fromJSON` method to create a Signature from a JSON object. */ class Signature { + keyID; + sig; constructor(options) { const { keyID, sig } = options; this.keyID = keyID; diff --git a/node_modules/@tufjs/models/dist/snapshot.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/snapshot.js similarity index 97% rename from node_modules/@tufjs/models/dist/snapshot.js rename to node_modules/tuf-js/node_modules/@tufjs/models/dist/snapshot.js index e90ea8e729e4e..bc9983c12e669 100644 --- a/node_modules/@tufjs/models/dist/snapshot.js +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/snapshot.js @@ -16,9 +16,10 @@ const utils_1 = require("./utils"); * and hence the latest versions of all targets (including any dependencies between them) on the repository. */ class Snapshot extends base_1.Signed { + type = base_1.MetadataKind.Snapshot; + meta; constructor(opts) { super(opts); - this.type = base_1.MetadataKind.Snapshot; this.meta = opts.meta || { 'targets.json': new file_1.MetaFile({ version: 1 }) }; } equals(other) { diff --git a/node_modules/@tufjs/models/dist/targets.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/targets.js similarity index 97% rename from node_modules/@tufjs/models/dist/targets.js rename to node_modules/tuf-js/node_modules/@tufjs/models/dist/targets.js index 54bd8f8c554af..e509722f94758 100644 --- a/node_modules/@tufjs/models/dist/targets.js +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/targets.js @@ -14,9 +14,11 @@ const utils_1 = require("./utils"); // Targets contains verifying information about target files and also delegates // responsible to other Targets roles. class Targets extends base_1.Signed { + type = base_1.MetadataKind.Targets; + targets; + delegations; constructor(options) { super(options); - this.type = base_1.MetadataKind.Targets; this.targets = options.targets || {}; this.delegations = options.delegations; } diff --git a/node_modules/tuf-js/node_modules/@tufjs/models/dist/timestamp.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/timestamp.js new file mode 100644 index 0000000000000..d454b308f27e1 --- /dev/null +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/timestamp.js @@ -0,0 +1,59 @@ +"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 { + type = base_1.MetadataKind.Timestamp; + snapshotMeta; + constructor(options) { + super(options); + 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; +} diff --git a/node_modules/@tufjs/models/dist/utils/guard.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/guard.js similarity index 88% rename from node_modules/@tufjs/models/dist/utils/guard.js rename to node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/guard.js index efe558852303c..911e8475986bb 100644 --- a/node_modules/@tufjs/models/dist/utils/guard.js +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/guard.js @@ -1,33 +1,32 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.isObjectRecord = exports.isStringRecord = exports.isObjectArray = exports.isStringArray = exports.isObject = exports.isDefined = void 0; +exports.isDefined = isDefined; +exports.isObject = isObject; +exports.isStringArray = isStringArray; +exports.isObjectArray = isObjectArray; +exports.isStringRecord = isStringRecord; +exports.isObjectRecord = isObjectRecord; function isDefined(val) { return val !== undefined; } -exports.isDefined = isDefined; function isObject(value) { return typeof value === 'object' && value !== null; } -exports.isObject = isObject; function isStringArray(value) { return Array.isArray(value) && value.every((v) => typeof v === 'string'); } -exports.isStringArray = isStringArray; function isObjectArray(value) { return Array.isArray(value) && value.every(isObject); } -exports.isObjectArray = isObjectArray; 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')); } -exports.isStringRecord = isStringRecord; 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)); } -exports.isObjectRecord = isObjectRecord; diff --git a/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/index.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/index.js new file mode 100644 index 0000000000000..395cccc36cf92 --- /dev/null +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/index.js @@ -0,0 +1,38 @@ +"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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __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")); diff --git a/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/key.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/key.js new file mode 100644 index 0000000000000..3c3ec07f1425a --- /dev/null +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/key.js @@ -0,0 +1,142 @@ +"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); diff --git a/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/oid.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/oid.js new file mode 100644 index 0000000000000..00b29c3030d1e --- /dev/null +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/oid.js @@ -0,0 +1,26 @@ +"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; +} diff --git a/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/types.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/types.js new file mode 100644 index 0000000000000..c8ad2e549bdc6 --- /dev/null +++ b/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@tufjs/models/dist/utils/verify.js b/node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/verify.js similarity index 100% rename from node_modules/@tufjs/models/dist/utils/verify.js rename to node_modules/tuf-js/node_modules/@tufjs/models/dist/utils/verify.js diff --git a/node_modules/tuf-js/node_modules/@tufjs/models/package.json b/node_modules/tuf-js/node_modules/@tufjs/models/package.json new file mode 100644 index 0000000000000..de54f517e7ebe --- /dev/null +++ b/node_modules/tuf-js/node_modules/@tufjs/models/package.json @@ -0,0 +1,37 @@ +{ + "name": "@tufjs/models", + "version": "5.0.0", + "description": "TUF metadata models", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "build": "tsc --build tsconfig.build.json", + "clean": "rm -rf dist && rm tsconfig.build.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": "^10.2.1" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } +} diff --git a/node_modules/tuf-js/package.json b/node_modules/tuf-js/package.json index 9280719230d9a..d311a6a9f007c 100644 --- a/node_modules/tuf-js/package.json +++ b/node_modules/tuf-js/package.json @@ -1,12 +1,12 @@ { "name": "tuf-js", - "version": "2.2.1", + "version": "6.0.0", "description": "JavaScript implementation of The Update Framework (TUF)", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { - "build": "tsc --build", - "clean": "rm -rf dist", + "build": "tsc --build tsconfig.build.json", + "clean": "rm -rf dist && rm tsconfig.build.tsbuildinfo", "test": "jest" }, "repository": { @@ -28,16 +28,16 @@ }, "homepage": "https://github.com/theupdateframework/tuf-js/tree/main/packages/client#readme", "devDependencies": { - "@tufjs/repo-mock": "2.0.1", - "@types/debug": "^4.1.12", - "@types/make-fetch-happen": "^10.0.4" + "@tufjs/repo-mock": "5.0.0", + "@types/debug": "^4.1.13", + "@types/retry": "^0.12.5" }, "dependencies": { - "@tufjs/models": "2.0.1", - "debug": "^4.3.4", - "make-fetch-happen": "^13.0.1" + "@gar/promise-retry": "^1.0.3", + "@tufjs/models": "5.0.0", + "debug": "^4.4.3" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } } diff --git a/node_modules/undici/LICENSE b/node_modules/undici/LICENSE new file mode 100644 index 0000000000000..e7323bb52ec35 --- /dev/null +++ b/node_modules/undici/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Matteo Collina and Undici 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. diff --git a/node_modules/undici/docs/docs/api/Agent.md b/node_modules/undici/docs/docs/api/Agent.md new file mode 100644 index 0000000000000..dd5d99bc1e128 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Agent.md @@ -0,0 +1,80 @@ +# Agent + +Extends: `undici.Dispatcher` + +Agent allow dispatching requests against multiple different origins. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new undici.Agent([options])` + +Arguments: + +* **options** `AgentOptions` (optional) + +Returns: `Agent` + +### Parameter: `AgentOptions` + +Extends: [`PoolOptions`](Pool.md#parameter-pooloptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` +* **maxRedirections** `Integer` - Default: `0`. The number of HTTP redirection to follow unless otherwise specified in `DispatchOptions`. +* **interceptors** `{ Agent: DispatchInterceptor[] }` - Default: `[RedirectInterceptor]` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). Note that the behavior of interceptors is Experimental and might change at any given time. + +## Instance Properties + +### `Agent.closed` + +Implements [Client.closed](Client.md#clientclosed) + +### `Agent.destroyed` + +Implements [Client.destroyed](Client.md#clientdestroyed) + +## Instance Methods + +### `Agent.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `Agent.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Agent.dispatch(options, handler: AgentDispatchOptions)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +#### Parameter: `AgentDispatchOptions` + +Extends: [`DispatchOptions`](Dispatcher.md#parameter-dispatchoptions) + +* **origin** `string | URL` +* **maxRedirections** `Integer`. + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Agent.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `Agent.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Agent.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Agent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `Agent.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Agent.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). diff --git a/node_modules/undici/docs/docs/api/BalancedPool.md b/node_modules/undici/docs/docs/api/BalancedPool.md new file mode 100644 index 0000000000000..183ef523185a9 --- /dev/null +++ b/node_modules/undici/docs/docs/api/BalancedPool.md @@ -0,0 +1,99 @@ +# Class: BalancedPool + +Extends: `undici.Dispatcher` + +A pool of [Pool](Pool.md) instances connected to multiple upstreams. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new BalancedPool(upstreams [, options])` + +Arguments: + +* **upstreams** `URL | string | string[]` - It should only include the **protocol, hostname, and port**. +* **options** `BalancedPoolOptions` (optional) + +### Parameter: `BalancedPoolOptions` + +Extends: [`PoolOptions`](Pool.md#parameter-pooloptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` + +The `PoolOptions` are passed to each of the `Pool` instances being created. +## Instance Properties + +### `BalancedPool.upstreams` + +Returns an array of upstreams that were previously added. + +### `BalancedPool.closed` + +Implements [Client.closed](Client.md#clientclosed) + +### `BalancedPool.destroyed` + +Implements [Client.destroyed](Client.md#clientdestroyed) + +### `Pool.stats` + +Returns [`PoolStats`](PoolStats.md) instance for this pool. + +## Instance Methods + +### `BalancedPool.addUpstream(upstream)` + +Add an upstream. + +Arguments: + +* **upstream** `string` - It should only include the **protocol, hostname, and port**. + +### `BalancedPool.removeUpstream(upstream)` + +Removes an upstream that was previously added. + +### `BalancedPool.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `BalancedPool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `BalancedPool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `BalancedPool.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `BalancedPool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `BalancedPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `BalancedPool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `BalancedPool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain). diff --git a/node_modules/undici/docs/docs/api/CacheStorage.md b/node_modules/undici/docs/docs/api/CacheStorage.md new file mode 100644 index 0000000000000..08ee99fab148c --- /dev/null +++ b/node_modules/undici/docs/docs/api/CacheStorage.md @@ -0,0 +1,30 @@ +# CacheStorage + +Undici exposes a W3C spec-compliant implementation of [CacheStorage](https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage) and [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache). + +## Opening a Cache + +Undici exports a top-level CacheStorage instance. You can open a new Cache, or duplicate a Cache with an existing name, by using `CacheStorage.prototype.open`. If you open a Cache with the same name as an already-existing Cache, its list of cached Responses will be shared between both instances. + +```mjs +import { caches } from 'undici' + +const cache_1 = await caches.open('v1') +const cache_2 = await caches.open('v1') + +// Although .open() creates a new instance, +assert(cache_1 !== cache_2) +// The same Response is matched in both. +assert.deepStrictEqual(await cache_1.match('/req'), await cache_2.match('/req')) +``` + +## Deleting a Cache + +If a Cache is deleted, the cached Responses/Requests can still be used. + +```mjs +const response = await cache_1.match('/req') +await caches.delete('v1') + +await response.text() // the Response's body +``` diff --git a/node_modules/undici/docs/docs/api/Client.md b/node_modules/undici/docs/docs/api/Client.md new file mode 100644 index 0000000000000..fdee5ea702671 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Client.md @@ -0,0 +1,276 @@ +# Class: Client + +Extends: `undici.Dispatcher` + +A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new Client(url[, options])` + +Arguments: + +* **url** `URL | string` - Should only include the **protocol, hostname, and port**. +* **options** `ClientOptions` (optional) + +Returns: `Client` + +### Parameter: `ClientOptions` + +> ⚠️ Warning: The `H2` support is experimental. + +* **bodyTimeout** `number | null` (optional) - Default: `300e3` - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. Please note the `timeout` will be reset if you keep writing data to the scoket everytime. +* **headersTimeout** `number | null` (optional) - Default: `300e3` - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +* **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Defaults to 10 minutes. +* **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds. +* **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `2e3` - A number of milliseconds subtracted from server *keep-alive* hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 2 seconds. +* **maxHeaderSize** `number | null` (optional) - Default: `--max-http-header-size` or `16384` - The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB. +* **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable. +* **webSocket** `WebSocketOptions` (optional) - WebSocket-specific configuration options. + * **maxPayloadSize** `number` (optional) - Default: `134217728` (128 MB) - Maximum allowed payload size in bytes for WebSocket messages. Applied to uncompressed messages, compressed frame payloads, and decompressed (permessage-deflate) messages. Set to 0 to disable the limit. +* **pipelining** `number | null` (optional) - Default: `1` - The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Carefully consider your workload and environment before enabling concurrent requests as pipelining may reduce performance if used incorrectly. Pipelining is sensitive to network stack settings as well as head of line blocking caused by e.g. long running requests. Set to `0` to disable keep-alive connections. +* **connect** `ConnectOptions | Function | null` (optional) - Default: `null`. +* **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body. + +* **interceptors** `{ Client: DispatchInterceptor[] }` - Default: `[RedirectInterceptor]` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). Note that the behavior of interceptors is Experimental and might change at any given time. **Note: this is deprecated in favor of [Dispatcher#compose](./Dispatcher.md#dispatcher). Support will be droped in next major.** +* **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version. +* **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. +* **allowH2**: `boolean` - Default: `false`. Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. +* **maxConcurrentStreams**: `number` - Default: `100`. Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. + +#### Parameter: `ConnectOptions` + +Every Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +Furthermore, the following options can be passed: + +* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: 100. +* **timeout** `number | null` (optional) - In milliseconds, Default `10e3`. +* **servername** `string | null` (optional) +* **keepAlive** `boolean | null` (optional) - Default: `true` - TCP keep-alive enabled +* **keepAliveInitialDelay** `number | null` (optional) - Default: `60000` - TCP keep-alive interval for the socket in milliseconds + +### Example - Basic Client instantiation + +This will instantiate the undici Client, but it will not connect to the origin until something is queued. Consider using `client.connect` to prematurely connect to the origin, or just call `client.request`. + +```js +'use strict' +import { Client } from 'undici' + +const client = new Client('http://localhost:3000') +``` + +### Example - Custom connector + +This will allow you to perform some additional check on the socket that will be used for the next request. + +```js +'use strict' +import { Client, buildConnector } from 'undici' + +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (/* assertion */) { + socket.destroy() + cb(new Error('kaboom')) + } else { + cb(null, socket) + } + }) + } +}) +``` + +## Instance Methods + +### `Client.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `Client.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). + +### `Client.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `Client.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Client.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Client.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `Client.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Client.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Properties + +### `Client.closed` + +* `boolean` + +`true` after `client.close()` has been called. + +### `Client.destroyed` + +* `boolean` + +`true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. + +### `Client.pipelining` + +* `number` + +Property to get and set the pipelining factor. + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect). + +Parameters: + +* **origin** `URL` +* **targets** `Array` + +Emitted when a socket has been created and connected. The client will connect once `client.size > 0`. + +#### Example - Client connect event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('connect', (origin) => { + console.log(`Connected to ${origin}`) // should print before the request body statement +}) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.setEncoding('utf-8') + body.on('data', console.log) + client.close() + server.close() +} catch (error) { + console.error(error) + client.close() + server.close() +} +``` + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect). + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when socket has disconnected. The error argument of the event is the error which caused the socket to disconnect. The client will reconnect if or once `client.size > 0`. + +#### Example - Client disconnect event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.destroy() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('disconnect', (origin) => { + console.log(`Disconnected from ${origin}`) +}) + +try { + await client.request({ + path: '/', + method: 'GET' + }) +} catch (error) { + console.error(error.message) + client.close() + server.close() +} +``` + +### Event: `'drain'` + +Emitted when pipeline is no longer busy. + +See [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain). + +#### Example - Client drain event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('drain', () => { + console.log('drain event') + client.close() + server.close() +}) + +const requests = [ + client.request({ path: '/', method: 'GET' }), + client.request({ path: '/', method: 'GET' }), + client.request({ path: '/', method: 'GET' }) +] + +await Promise.all(requests) + +console.log('requests completed') +``` + +### Event: `'error'` + +Invoked for users errors such as throwing in the `onError` handler. diff --git a/node_modules/undici/docs/docs/api/Connector.md b/node_modules/undici/docs/docs/api/Connector.md new file mode 100644 index 0000000000000..56821bd643027 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Connector.md @@ -0,0 +1,115 @@ +# Connector + +Undici creates the underlying socket via the connector builder. +Normally, this happens automatically and you don't need to care about this, +but if you need to perform some additional check over the currently used socket, +this is the right place. + +If you want to create a custom connector, you must import the `buildConnector` utility. + +#### Parameter: `buildConnector.BuildOptions` + +Every Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +Furthermore, the following options can be passed: + +* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: `100`. +* **timeout** `number | null` (optional) - In milliseconds. Default `10e3`. +* **servername** `string | null` (optional) + +Once you call `buildConnector`, it will return a connector function, which takes the following parameters. + +#### Parameter: `connector.Options` + +* **hostname** `string` (required) +* **host** `string` (optional) +* **protocol** `string` (required) +* **port** `string` (required) +* **servername** `string` (optional) +* **localAddress** `string | null` (optional) Local address the socket should connect from. +* **httpSocket** `Socket` (optional) Establish secure connection on a given socket rather than creating a new socket. It can only be sent on TLS update. + +### Basic example + +```js +'use strict' + +import { Client, buildConnector } from 'undici' + +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (/* assertion */) { + socket.destroy() + cb(new Error('kaboom')) + } else { + cb(null, socket) + } + }) + } +}) +``` + +### Example: validate the CA fingerprint + +```js +'use strict' + +import { Client, buildConnector } from 'undici' + +const caFingerprint = 'FO:OB:AR' +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (getIssuerCertificate(socket).fingerprint256 !== caFingerprint) { + socket.destroy() + cb(new Error('Fingerprint does not match or malformed certificate')) + } else { + cb(null, socket) + } + }) + } +}) + +client.request({ + path: '/', + method: 'GET' +}, (err, data) => { + if (err) throw err + + const bufs = [] + data.body.on('data', (buf) => { + bufs.push(buf) + }) + data.body.on('end', () => { + console.log(Buffer.concat(bufs).toString('utf8')) + client.close() + }) +}) + +function getIssuerCertificate (socket) { + let certificate = socket.getPeerCertificate(true) + while (certificate && Object.keys(certificate).length > 0) { + // invalid certificate + if (certificate.issuerCertificate == null) { + return null + } + + // We have reached the root certificate. + // In case of self-signed certificates, `issuerCertificate` may be a circular reference. + if (certificate.fingerprint256 === certificate.issuerCertificate.fingerprint256) { + break + } + + // continue the loop + certificate = certificate.issuerCertificate + } + return certificate +} +``` diff --git a/node_modules/undici/docs/docs/api/ContentType.md b/node_modules/undici/docs/docs/api/ContentType.md new file mode 100644 index 0000000000000..2bcc9f71ca325 --- /dev/null +++ b/node_modules/undici/docs/docs/api/ContentType.md @@ -0,0 +1,57 @@ +# MIME Type Parsing + +## `MIMEType` interface + +* **type** `string` +* **subtype** `string` +* **parameters** `Map` +* **essence** `string` + +## `parseMIMEType(input)` + +Implements [parse a MIME type](https://mimesniff.spec.whatwg.org/#parse-a-mime-type). + +Parses a MIME type, returning its type, subtype, and any associated parameters. If the parser can't parse an input it returns the string literal `'failure'`. + +```js +import { parseMIMEType } from 'undici' + +parseMIMEType('text/html; charset=gbk') +// { +// type: 'text', +// subtype: 'html', +// parameters: Map(1) { 'charset' => 'gbk' }, +// essence: 'text/html' +// } +``` + +Arguments: + +* **input** `string` + +Returns: `MIMEType|'failure'` + +## `serializeAMimeType(input)` + +Implements [serialize a MIME type](https://mimesniff.spec.whatwg.org/#serialize-a-mime-type). + +Serializes a MIMEType object. + +```js +import { serializeAMimeType } from 'undici' + +serializeAMimeType({ + type: 'text', + subtype: 'html', + parameters: new Map([['charset', 'gbk']]), + essence: 'text/html' +}) +// text/html;charset=gbk + +``` + +Arguments: + +* **mimeType** `MIMEType` + +Returns: `string` diff --git a/node_modules/undici/docs/docs/api/Cookies.md b/node_modules/undici/docs/docs/api/Cookies.md new file mode 100644 index 0000000000000..0cad37914d625 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Cookies.md @@ -0,0 +1,101 @@ +# Cookie Handling + +## `Cookie` interface + +* **name** `string` +* **value** `string` +* **expires** `Date|number` (optional) +* **maxAge** `number` (optional) +* **domain** `string` (optional) +* **path** `string` (optional) +* **secure** `boolean` (optional) +* **httpOnly** `boolean` (optional) +* **sameSite** `'String'|'Lax'|'None'` (optional) +* **unparsed** `string[]` (optional) Left over attributes that weren't parsed. + +## `deleteCookie(headers, name[, attributes])` + +Sets the expiry time of the cookie to the unix epoch, causing browsers to delete it when received. + +```js +import { deleteCookie, Headers } from 'undici' + +const headers = new Headers() +deleteCookie(headers, 'name') + +console.log(headers.get('set-cookie')) // name=; Expires=Thu, 01 Jan 1970 00:00:00 GMT +``` + +Arguments: + +* **headers** `Headers` +* **name** `string` +* **attributes** `{ path?: string, domain?: string }` (optional) + +Returns: `void` + +## `getCookies(headers)` + +Parses the `Cookie` header and returns a list of attributes and values. + +```js +import { getCookies, Headers } from 'undici' + +const headers = new Headers({ + cookie: 'get=cookies; and=attributes' +}) + +console.log(getCookies(headers)) // { get: 'cookies', and: 'attributes' } +``` + +Arguments: + +* **headers** `Headers` + +Returns: `Record` + +## `getSetCookies(headers)` + +Parses all `Set-Cookie` headers. + +```js +import { getSetCookies, Headers } from 'undici' + +const headers = new Headers({ 'set-cookie': 'undici=getSetCookies; Secure' }) + +console.log(getSetCookies(headers)) +// [ +// { +// name: 'undici', +// value: 'getSetCookies', +// secure: true +// } +// ] + +``` + +Arguments: + +* **headers** `Headers` + +Returns: `Cookie[]` + +## `setCookie(headers, cookie)` + +Appends a cookie to the `Set-Cookie` header. + +```js +import { setCookie, Headers } from 'undici' + +const headers = new Headers() +setCookie(headers, { name: 'undici', value: 'setCookie' }) + +console.log(headers.get('Set-Cookie')) // undici=setCookie +``` + +Arguments: + +* **headers** `Headers` +* **cookie** `Cookie` + +Returns: `void` diff --git a/node_modules/undici/docs/docs/api/Debug.md b/node_modules/undici/docs/docs/api/Debug.md new file mode 100644 index 0000000000000..7efc99e3e31f5 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Debug.md @@ -0,0 +1,62 @@ +# Debug + +Undici (and subsenquently `fetch` and `websocket`) exposes a debug statement that can be enabled by setting `NODE_DEBUG` within the environment. + +The flags availabile are: + +## `undici` + +This flag enables debug statements for the core undici library. + +```sh +NODE_DEBUG=undici node script.js + +UNDICI 16241: connecting to nodejs.org using https:h1 +UNDICI 16241: connecting to nodejs.org using https:h1 +UNDICI 16241: connected to nodejs.org using https:h1 +UNDICI 16241: sending request to GET https://nodejs.org// +UNDICI 16241: received response to GET https://nodejs.org// - HTTP 307 +UNDICI 16241: connecting to nodejs.org using https:h1 +UNDICI 16241: trailers received from GET https://nodejs.org// +UNDICI 16241: connected to nodejs.org using https:h1 +UNDICI 16241: sending request to GET https://nodejs.org//en +UNDICI 16241: received response to GET https://nodejs.org//en - HTTP 200 +UNDICI 16241: trailers received from GET https://nodejs.org//en +``` + +## `fetch` + +This flag enables debug statements for the `fetch` API. + +> **Note**: statements are pretty similar to the ones in the `undici` flag, but scoped to `fetch` + +```sh +NODE_DEBUG=fetch node script.js + +FETCH 16241: connecting to nodejs.org using https:h1 +FETCH 16241: connecting to nodejs.org using https:h1 +FETCH 16241: connected to nodejs.org using https:h1 +FETCH 16241: sending request to GET https://nodejs.org// +FETCH 16241: received response to GET https://nodejs.org// - HTTP 307 +FETCH 16241: connecting to nodejs.org using https:h1 +FETCH 16241: trailers received from GET https://nodejs.org// +FETCH 16241: connected to nodejs.org using https:h1 +FETCH 16241: sending request to GET https://nodejs.org//en +FETCH 16241: received response to GET https://nodejs.org//en - HTTP 200 +FETCH 16241: trailers received from GET https://nodejs.org//en +``` + +## `websocket` + +This flag enables debug statements for the `Websocket` API. + +> **Note**: statements can overlap with `UNDICI` ones if `undici` or `fetch` flag has been enabled as well. + +```sh +NODE_DEBUG=websocket node script.js + +WEBSOCKET 18309: connecting to echo.websocket.org using https:h1 +WEBSOCKET 18309: connected to echo.websocket.org using https:h1 +WEBSOCKET 18309: sending request to GET https://echo.websocket.org// +WEBSOCKET 18309: connection opened +``` diff --git a/node_modules/undici/docs/docs/api/DiagnosticsChannel.md b/node_modules/undici/docs/docs/api/DiagnosticsChannel.md new file mode 100644 index 0000000000000..099c072f6c6ca --- /dev/null +++ b/node_modules/undici/docs/docs/api/DiagnosticsChannel.md @@ -0,0 +1,204 @@ +# Diagnostics Channel Support + +Stability: Experimental. + +Undici supports the [`diagnostics_channel`](https://nodejs.org/api/diagnostics_channel.html) (currently available only on Node.js v16+). +It is the preferred way to instrument Undici and retrieve internal information. + +The channels available are the following. + +## `undici:request:create` + +This message is published when a new outgoing request is created. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:create').subscribe(({ request }) => { + console.log('origin', request.origin) + console.log('completed', request.completed) + console.log('method', request.method) + console.log('path', request.path) + console.log('headers') // array of strings, e.g: ['foo', 'bar'] + request.addHeader('hello', 'world') + console.log('headers', request.headers) // e.g. ['foo', 'bar', 'hello', 'world'] +}) +``` + +Note: a request is only loosely completed to a given socket. + + +## `undici:request:bodySent` + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:bodySent').subscribe(({ request }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:request:headers` + +This message is published after the response headers have been received, i.e. the response has been completed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:headers').subscribe(({ request, response }) => { + // request is the same object undici:request:create + console.log('statusCode', response.statusCode) + console.log(response.statusText) + // response.headers are buffers. + console.log(response.headers.map((x) => x.toString())) +}) +``` + +## `undici:request:trailers` + +This message is published after the response body and trailers have been received, i.e. the response has been completed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:trailers').subscribe(({ request, trailers }) => { + // request is the same object undici:request:create + console.log('completed', request.completed) + // trailers are buffers. + console.log(trailers.map((x) => x.toString())) +}) +``` + +## `undici:request:error` + +This message is published if the request is going to error, but it has not errored yet. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:error').subscribe(({ request, error }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:client:sendHeaders` + +This message is published right before the first byte of the request is written to the socket. + +*Note*: It will publish the exact headers that will be sent to the server in raw format. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(({ request, headers, socket }) => { + // request is the same object undici:request:create + console.log(`Full headers list ${headers.split('\r\n')}`); +}) +``` + +## `undici:client:beforeConnect` + +This message is published before creating a new connection for **any** request. +You can not assume that this event is related to any specific request. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(({ connectParams, connector }) => { + // const { host, hostname, protocol, port, servername, version } = connectParams + // connector is a function that creates the socket +}) +``` + +## `undici:client:connected` + +This message is published after a connection is established. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:connected').subscribe(({ socket, connectParams, connector }) => { + // const { host, hostname, protocol, port, servername, version } = connectParams + // connector is a function that creates the socket +}) +``` + +## `undici:client:connectError` + +This message is published if it did not succeed to create new connection + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:connectError').subscribe(({ error, socket, connectParams, connector }) => { + // const { host, hostname, protocol, port, servername, version } = connectParams + // connector is a function that creates the socket + console.log(`Connect failed with ${error.message}`) +}) +``` + +## `undici:websocket:open` + +This message is published after the client has successfully connected to a server. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:open').subscribe(({ address, protocol, extensions }) => { + console.log(address) // address, family, and port + console.log(protocol) // negotiated subprotocols + console.log(extensions) // negotiated extensions +}) +``` + +## `undici:websocket:close` + +This message is published after the connection has closed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:close').subscribe(({ websocket, code, reason }) => { + console.log(websocket) // the WebSocket object + console.log(code) // the closing status code + console.log(reason) // the closing reason +}) +``` + +## `undici:websocket:socket_error` + +This message is published if the socket experiences an error. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:socket_error').subscribe((error) => { + console.log(error) +}) +``` + +## `undici:websocket:ping` + +This message is published after the client receives a ping frame, if the connection is not closing. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:ping').subscribe(({ payload }) => { + // a Buffer or undefined, containing the optional application data of the frame + console.log(payload) +}) +``` + +## `undici:websocket:pong` + +This message is published after the client receives a pong frame. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:pong').subscribe(({ payload }) => { + // a Buffer or undefined, containing the optional application data of the frame + console.log(payload) +}) +``` diff --git a/node_modules/undici/docs/docs/api/DispatchInterceptor.md b/node_modules/undici/docs/docs/api/DispatchInterceptor.md new file mode 100644 index 0000000000000..7dfc260e32a9c --- /dev/null +++ b/node_modules/undici/docs/docs/api/DispatchInterceptor.md @@ -0,0 +1,60 @@ +# Interface: DispatchInterceptor + +Extends: `Function` + +A function that can be applied to the `Dispatcher.Dispatch` function before it is invoked with a dispatch request. + +This allows one to write logic to intercept both the outgoing request, and the incoming response. + +### Parameter: `Dispatcher.Dispatch` + +The base dispatch function you are decorating. + +### ReturnType: `Dispatcher.Dispatch` + +A dispatch function that has been altered to provide additional logic + +### Basic Example + +Here is an example of an interceptor being used to provide a JWT bearer token + +```js +'use strict' + +const insertHeaderInterceptor = dispatch => { + return function InterceptedDispatch(opts, handler){ + opts.headers.push('Authorization', 'Bearer [Some token]') + return dispatch(opts, handler) + } +} + +const client = new Client('https://localhost:3000', { + interceptors: { Client: [insertHeaderInterceptor] } +}) + +``` + +### Basic Example 2 + +Here is a contrived example of an interceptor stripping the headers from a response. + +```js +'use strict' + +const clearHeadersInterceptor = dispatch => { + const { DecoratorHandler } = require('undici') + class ResultInterceptor extends DecoratorHandler { + onHeaders (statusCode, headers, resume) { + return super.onHeaders(statusCode, [], resume) + } + } + return function InterceptedDispatch(opts, handler){ + return dispatch(opts, new ResultInterceptor(handler)) + } +} + +const client = new Client('https://localhost:3000', { + interceptors: { Client: [clearHeadersInterceptor] } +}) + +``` diff --git a/node_modules/undici/docs/docs/api/Dispatcher.md b/node_modules/undici/docs/docs/api/Dispatcher.md new file mode 100644 index 0000000000000..ce14bfe1cd27f --- /dev/null +++ b/node_modules/undici/docs/docs/api/Dispatcher.md @@ -0,0 +1,1347 @@ +# Dispatcher + +Extends: `events.EventEmitter` + +Dispatcher is the core API used to dispatch requests. + +Requests are not guaranteed to be dispatched in order of invocation. + +## Instance Methods + +### `Dispatcher.close([callback]): Promise` + +Closes the dispatcher and gracefully waits for enqueued requests to complete before resolving. + +Arguments: + +* **callback** `(error: Error | null, data: null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +```js +dispatcher.close() // -> Promise +dispatcher.close(() => {}) // -> void +``` + +#### Example - Request resolves before Client closes + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('undici') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.setEncoding('utf8') + body.on('data', console.log) +} catch (error) {} + +await client.close() + +console.log('Client closed') +server.close() +``` + +### `Dispatcher.connect(options[, callback])` + +Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT). + +Arguments: + +* **options** `ConnectOptions` +* **callback** `(err: Error | null, data: ConnectData | null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `ConnectOptions` + +* **path** `string` +* **headers** `UndiciHeaders` (optional) - Default: `null` +* **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null` +* **opaque** `unknown` (optional) - This argument parameter is passed through to `ConnectData` + +#### Parameter: `ConnectData` + +* **statusCode** `number` +* **headers** `Record` +* **socket** `stream.Duplex` +* **opaque** `unknown` + +#### Example - Connect request with echo + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + throw Error('should never get here') +}).listen() + +server.on('connect', (req, socket, head) => { + socket.write('HTTP/1.1 200 Connection established\r\n\r\n') + + let data = head.toString() + socket.on('data', (buf) => { + data += buf.toString() + }) + + socket.on('end', () => { + socket.end(data) + }) +}) + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { socket } = await client.connect({ + path: '/' + }) + const wanted = 'Body' + let data = '' + socket.on('data', d => { data += d }) + socket.on('end', () => { + console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`) + client.close() + server.close() + }) + socket.write(wanted) + socket.end() +} catch (error) { } +``` + +### `Dispatcher.destroy([error, callback]): Promise` + +Destroy the dispatcher abruptly with the given error. All the pending and running requests will be asynchronously aborted and error. Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. + +Both arguments are optional; the method can be called in four different ways: + +Arguments: + +* **error** `Error | null` (optional) +* **callback** `(error: Error | null, data: null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +```js +dispatcher.destroy() // -> Promise +dispatcher.destroy(new Error()) // -> Promise +dispatcher.destroy(() => {}) // -> void +dispatcher.destroy(new Error(), () => {}) // -> void +``` + +#### Example - Request is aborted when Client is destroyed + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const request = client.request({ + path: '/', + method: 'GET' + }) + client.destroy() + .then(() => { + console.log('Client destroyed') + server.close() + }) + await request +} catch (error) { + console.error(error) +} +``` + +### `Dispatcher.dispatch(options, handler)` + +This is the low level API which all the preceding APIs are implemented on top of. +This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. +It is primarily intended for library developers who implement higher level APIs on top of this. + +Arguments: + +* **options** `DispatchOptions` +* **handler** `DispatchHandler` + +Returns: `Boolean` - `false` if dispatcher is busy and further dispatch calls won't make any progress until the `'drain'` event has been emitted. + +#### Parameter: `DispatchOptions` + +* **origin** `string | URL` +* **path** `string` +* **method** `string` +* **reset** `boolean` (optional) - Default: `false` - If `false`, the request will attempt to create a long-living connection by sending the `connection: keep-alive` header,otherwise will attempt to close it immediately after response by sending `connection: close` within the request and closing the socket afterwards. +* **body** `string | Buffer | Uint8Array | stream.Readable | Iterable | AsyncIterable | null` (optional) - Default: `null` +* **headers** `UndiciHeaders | string[]` (optional) - Default: `null`. +* **query** `Record | null` (optional) - Default: `null` - Query string params to be embedded in the request URL. Note that both keys and values of query are encoded using `encodeURIComponent`. If for some reason you need to send them unencoded, embed query params into path directly instead. +* **idempotent** `boolean` (optional) - Default: `true` if `method` is `'HEAD'` or `'GET'` - Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline has completed. +* **blocking** `boolean` (optional) - Default: `false` - Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. +* **upgrade** `string | null` (optional) - Default: `null` - Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. +* **bodyTimeout** `number | null` (optional) - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. +* **headersTimeout** `number | null` (optional) - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +* **throwOnError** `boolean` (optional) - Default: `false` - Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. +* **expectContinue** `boolean` (optional) - Default: `false` - For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server + +#### Parameter: `DispatchHandler` + +* **onConnect** `(abort: () => void, context: object) => void` - Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. +* **onError** `(error: Error) => void` - Invoked when an error has occurred. May not throw. +* **onUpgrade** `(statusCode: number, headers: Buffer[], socket: Duplex) => void` (optional) - Invoked when request is upgraded. Required if `DispatchOptions.upgrade` is defined or `DispatchOptions.method === 'CONNECT'`. +* **onResponseStarted** `() => void` (optional) - Invoked when response is received, before headers have been read. +* **onHeaders** `(statusCode: number, headers: Buffer[], resume: () => void, statusText: string) => boolean` - Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. Not required for `upgrade` requests. +* **onData** `(chunk: Buffer) => boolean` - Invoked when response payload data is received. Not required for `upgrade` requests. +* **onComplete** `(trailers: Buffer[]) => void` - Invoked when response payload and trailers have been received and the request has completed. Not required for `upgrade` requests. +* **onBodySent** `(chunk: string | Buffer | Uint8Array) => void` - Invoked when a body chunk is sent to the server. Not required. For a stream or iterable body this will be invoked for every chunk. For other body types, it will be invoked once after the body is sent. + +#### Example 1 - Dispatch GET request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const data = [] + +client.dispatch({ + path: '/', + method: 'GET', + headers: { + 'x-foo': 'bar' + } +}, { + onConnect: () => { + console.log('Connected!') + }, + onError: (error) => { + console.error(error) + }, + onHeaders: (statusCode, headers) => { + console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`) + }, + onData: (chunk) => { + console.log('onData: chunk received') + data.push(chunk) + }, + onComplete: (trailers) => { + console.log(`onComplete | trailers: ${trailers}`) + const res = Buffer.concat(data).toString('utf8') + console.log(`Data: ${res}`) + client.close() + server.close() + } +}) +``` + +#### Example 2 - Dispatch Upgrade Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end() +}).listen() + +await once(server, 'listening') + +server.on('upgrade', (request, socket, head) => { + console.log('Node.js Server - upgrade event') + socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n') + socket.write('Upgrade: WebSocket\r\n') + socket.write('Connection: Upgrade\r\n') + socket.write('\r\n') + socket.end() +}) + +const client = new Client(`http://localhost:${server.address().port}`) + +client.dispatch({ + path: '/', + method: 'GET', + upgrade: 'websocket' +}, { + onConnect: () => { + console.log('Undici Client - onConnect') + }, + onError: (error) => { + console.log('onError') // shouldn't print + }, + onUpgrade: (statusCode, headers, socket) => { + console.log('Undici Client - onUpgrade') + console.log(`onUpgrade Headers: ${headers}`) + socket.on('data', buffer => { + console.log(buffer.toString('utf8')) + }) + socket.on('end', () => { + client.close() + server.close() + }) + socket.end() + } +}) +``` + +#### Example 3 - Dispatch POST request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + request.on('data', (data) => { + console.log(`Request Data: ${data.toString('utf8')}`) + const body = JSON.parse(data) + body.message = 'World' + response.end(JSON.stringify(body)) + }) +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const data = [] + +client.dispatch({ + path: '/', + method: 'POST', + headers: { + 'content-type': 'application/json' + }, + body: JSON.stringify({ message: 'Hello' }) +}, { + onConnect: () => { + console.log('Connected!') + }, + onError: (error) => { + console.error(error) + }, + onHeaders: (statusCode, headers) => { + console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`) + }, + onData: (chunk) => { + console.log('onData: chunk received') + data.push(chunk) + }, + onComplete: (trailers) => { + console.log(`onComplete | trailers: ${trailers}`) + const res = Buffer.concat(data).toString('utf8') + console.log(`Response Data: ${res}`) + client.close() + server.close() + } +}) +``` + +### `Dispatcher.pipeline(options, handler)` + +For easy use with [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback). The `handler` argument should return a `Readable` from which the result will be read. Usually it should just return the `body` argument unless some kind of transformation needs to be performed based on e.g. `headers` or `statusCode`. The `handler` should validate the response and save any required state. If there is an error, it should be thrown. The function returns a `Duplex` which writes to the request and reads from the response. + +Arguments: + +* **options** `PipelineOptions` +* **handler** `(data: PipelineHandlerData) => stream.Readable` + +Returns: `stream.Duplex` + +#### Parameter: PipelineOptions + +Extends: [`RequestOptions`](#parameter-requestoptions) + +* **objectMode** `boolean` (optional) - Default: `false` - Set to `true` if the `handler` will return an object stream. + +#### Parameter: PipelineHandlerData + +* **statusCode** `number` +* **headers** `Record` +* **opaque** `unknown` +* **body** `stream.Readable` +* **context** `object` +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +#### Example 1 - Pipeline Echo + +```js +import { Readable, Writable, PassThrough, pipeline } from 'stream' +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + request.pipe(response) +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +let res = '' + +pipeline( + new Readable({ + read () { + this.push(Buffer.from('undici')) + this.push(null) + } + }), + client.pipeline({ + path: '/', + method: 'GET' + }, ({ statusCode, headers, body }) => { + console.log(`response received ${statusCode}`) + console.log('headers', headers) + return pipeline(body, new PassThrough(), () => {}) + }), + new Writable({ + write (chunk, _, callback) { + res += chunk.toString() + callback() + }, + final (callback) { + console.log(`Response pipelined to writable: ${res}`) + callback() + } + }), + error => { + if (error) { + console.error(error) + } + + client.close() + server.close() + } +) +``` + +### `Dispatcher.request(options[, callback])` + +Performs a HTTP request. + +Non-idempotent requests will not be pipelined in order +to avoid indirect failures. + +Idempotent requests will be automatically retried if +they fail due to indirect failure from the request +at the head of the pipeline. This does not apply to +idempotent requests with a stream request body. + +All response bodies must always be fully consumed or destroyed. + +Arguments: + +* **options** `RequestOptions` +* **callback** `(error: Error | null, data: ResponseData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed. + +#### Parameter: `RequestOptions` + +Extends: [`DispatchOptions`](#parameter-dispatchoptions) + +* **opaque** `unknown` (optional) - Default: `null` - Used for passing through context to `ResponseData`. +* **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null`. +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +The `RequestOptions.method` property should not be value `'CONNECT'`. + +#### Parameter: `ResponseData` + +* **statusCode** `number` +* **headers** `Record` - Note that all header keys are lower-cased, e. g. `content-type`. +* **body** `stream.Readable` which also implements [the body mixin from the Fetch Standard](https://fetch.spec.whatwg.org/#body-mixin). +* **trailers** `Record` - This object starts out + as empty and will be mutated to contain trailers after `body` has emitted `'end'`. +* **opaque** `unknown` +* **context** `object` + +`body` contains the following additional [body mixin](https://fetch.spec.whatwg.org/#body-mixin) methods and properties: + +* [`.arrayBuffer()`](https://fetch.spec.whatwg.org/#dom-body-arraybuffer) +* [`.blob()`](https://fetch.spec.whatwg.org/#dom-body-blob) +* [`.bytes()`](https://fetch.spec.whatwg.org/#dom-body-bytes) +* [`.json()`](https://fetch.spec.whatwg.org/#dom-body-json) +* [`.text()`](https://fetch.spec.whatwg.org/#dom-body-text) +* `body` +* `bodyUsed` + +`body` can not be consumed twice. For example, calling `text()` after `json()` throws `TypeError`. + +`body` contains the following additional extensions: + +- `dump({ limit: Integer })`, dump the response by reading up to `limit` bytes without killing the socket (optional) - Default: 262144. + +Note that body will still be a `Readable` even if it is empty, but attempting to deserialize it with `json()` will result in an exception. Recommended way to ensure there is a body to deserialize is to check if status code is not 204, and `content-type` header starts with `application/json`. + +#### Example 1 - Basic GET Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body, headers, statusCode, trailers } = await client.request({ + path: '/', + method: 'GET' + }) + console.log(`response received ${statusCode}`) + console.log('headers', headers) + body.setEncoding('utf8') + body.on('data', console.log) + body.on('end', () => { + console.log('trailers', trailers) + }) + + client.close() + server.close() +} catch (error) { + console.error(error) +} +``` + +#### Example 2 - Aborting a request + +> Node.js v15+ is required to run this example + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) +const abortController = new AbortController() + +try { + client.request({ + path: '/', + method: 'GET', + signal: abortController.signal + }) +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} + +abortController.abort() +``` + +Alternatively, any `EventEmitter` that emits an `'abort'` event may be used as an abort controller: + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import EventEmitter, { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) +const ee = new EventEmitter() + +try { + client.request({ + path: '/', + method: 'GET', + signal: ee + }) +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} + +ee.emit('abort') +``` + +Destroying the request or response body will have the same effect. + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.destroy() +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} +``` + +### `Dispatcher.stream(options, factory[, callback])` + +A faster version of `Dispatcher.request`. This method expects the second argument `factory` to return a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream which the response will be written to. This improves performance by avoiding creating an intermediate [`stream.Readable`](https://nodejs.org/api/stream.html#stream_readable_streams) stream when the user expects to directly pipe the response body to a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream. + +As demonstrated in [Example 1 - Basic GET stream request](#example-1---basic-get-stream-request), it is recommended to use the `option.opaque` property to avoid creating a closure for the `factory` method. This pattern works well with Node.js Web Frameworks such as [Fastify](https://fastify.io). See [Example 2 - Stream to Fastify Response](#example-2---stream-to-fastify-response) for more details. + +Arguments: + +* **options** `RequestOptions` +* **factory** `(data: StreamFactoryData) => stream.Writable` +* **callback** `(error: Error | null, data: StreamData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `StreamFactoryData` + +* **statusCode** `number` +* **headers** `Record` +* **opaque** `unknown` +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +#### Parameter: `StreamData` + +* **opaque** `unknown` +* **trailers** `Record` +* **context** `object` + +#### Example 1 - Basic GET stream request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' +import { Writable } from 'stream' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const bufs = [] + +try { + await client.stream({ + path: '/', + method: 'GET', + opaque: { bufs } + }, ({ statusCode, headers, opaque: { bufs } }) => { + console.log(`response received ${statusCode}`) + console.log('headers', headers) + return new Writable({ + write (chunk, encoding, callback) { + bufs.push(chunk) + callback() + } + }) + }) + + console.log(Buffer.concat(bufs).toString('utf-8')) + + client.close() + server.close() +} catch (error) { + console.error(error) +} +``` + +#### Example 2 - Stream to Fastify Response + +In this example, a (fake) request is made to the fastify server using `fastify.inject()`. This request then executes the fastify route handler which makes a subsequent request to the raw Node.js http server using `undici.dispatcher.stream()`. The fastify response is passed to the `opaque` option so that undici can tap into the underlying writable stream using `response.raw`. This methodology demonstrates how one could use undici and fastify together to create fast-as-possible requests from one backend server to another. + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' +import fastify from 'fastify' + +const nodeServer = createServer((request, response) => { + response.end('Hello, World! From Node.js HTTP Server') +}).listen() + +await once(nodeServer, 'listening') + +console.log('Node Server listening') + +const nodeServerUndiciClient = new Client(`http://localhost:${nodeServer.address().port}`) + +const fastifyServer = fastify() + +fastifyServer.route({ + url: '/', + method: 'GET', + handler: (request, response) => { + nodeServerUndiciClient.stream({ + path: '/', + method: 'GET', + opaque: response + }, ({ opaque }) => opaque.raw) + } +}) + +await fastifyServer.listen() + +console.log('Fastify Server listening') + +const fastifyServerUndiciClient = new Client(`http://localhost:${fastifyServer.server.address().port}`) + +try { + const { statusCode, body } = await fastifyServerUndiciClient.request({ + path: '/', + method: 'GET' + }) + + console.log(`response received ${statusCode}`) + body.setEncoding('utf8') + body.on('data', console.log) + + nodeServerUndiciClient.close() + fastifyServerUndiciClient.close() + fastifyServer.close() + nodeServer.close() +} catch (error) { } +``` + +### `Dispatcher.upgrade(options[, callback])` + +Upgrade to a different protocol. Visit [MDN - HTTP - Protocol upgrade mechanism](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) for more details. + +Arguments: + +* **options** `UpgradeOptions` + +* **callback** `(error: Error | null, data: UpgradeData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `UpgradeOptions` + +* **path** `string` +* **method** `string` (optional) - Default: `'GET'` +* **headers** `UndiciHeaders` (optional) - Default: `null` +* **protocol** `string` (optional) - Default: `'Websocket'` - A string of comma separated protocols, in descending preference order. +* **signal** `AbortSignal | EventEmitter | null` (optional) - Default: `null` + +#### Parameter: `UpgradeData` + +* **headers** `http.IncomingHeaders` +* **socket** `stream.Duplex` +* **opaque** `unknown` + +#### Example 1 - Basic Upgrade Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.statusCode = 101 + response.setHeader('connection', 'upgrade') + response.setHeader('upgrade', request.headers.upgrade) + response.end() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { headers, socket } = await client.upgrade({ + path: '/', + }) + socket.on('end', () => { + console.log(`upgrade: ${headers.upgrade}`) // upgrade: Websocket + client.close() + server.close() + }) + socket.end() +} catch (error) { + console.error(error) + client.close() + server.close() +} +``` + +### `Dispatcher.compose(interceptors[, interceptor])` + +Compose a new dispatcher from the current dispatcher and the given interceptors. + +> _Notes_: +> - The order of the interceptors matters. The first interceptor will be the first to be called. +> - It is important to note that the `interceptor` function should return a function that follows the `Dispatcher.dispatch` signature. +> - Any fork of the chain of `interceptors` can lead to unexpected results. + +Arguments: + +* **interceptors** `Interceptor[interceptor[]]`: It is an array of `Interceptor` functions passed as only argument, or several interceptors passed as separate arguments. + +Returns: `Dispatcher`. + +#### Parameter: `Interceptor` + +A function that takes a `dispatch` method and returns a `dispatch`-like function. + +#### Example 1 - Basic Compose + +```js +const { Client, RedirectHandler } = require('undici') + +const redirectInterceptor = dispatch => { + return (opts, handler) => { + const { maxRedirections } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler( + dispatch, + maxRedirections, + opts, + handler + ) + opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } +} + +const client = new Client('http://localhost:3000') + .compose(redirectInterceptor) + +await client.request({ path: '/', method: 'GET' }) +``` + +#### Example 2 - Chained Compose + +```js +const { Client, RedirectHandler, RetryHandler } = require('undici') + +const redirectInterceptor = dispatch => { + return (opts, handler) => { + const { maxRedirections } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler( + dispatch, + maxRedirections, + opts, + handler + ) + opts = { ...opts, maxRedirections: 0 } + return dispatch(opts, redirectHandler) + } +} + +const retryInterceptor = dispatch => { + return function retryInterceptor (opts, handler) { + return dispatch( + opts, + new RetryHandler(opts, { + handler, + dispatch + }) + ) + } +} + +const client = new Client('http://localhost:3000') + .compose(redirectInterceptor) + .compose(retryInterceptor) + +await client.request({ path: '/', method: 'GET' }) +``` + +#### Pre-built interceptors + +##### `redirect` + +The `redirect` interceptor allows you to customize the way your dispatcher handles redirects. + +It accepts the same arguments as the [`RedirectHandler` constructor](./RedirectHandler.md). + +**Example - Basic Redirect Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { redirect } = interceptors; + +const client = new Client("http://example.com").compose( + redirect({ maxRedirections: 3, throwOnMaxRedirects: true }) +); +client.request({ path: "/" }) +``` + +##### `retry` + +The `retry` interceptor allows you to customize the way your dispatcher handles retries. + +It accepts the same arguments as the [`RetryHandler` constructor](./RetryHandler.md). + +**Example - Basic Redirect Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { retry } = interceptors; + +const client = new Client("http://example.com").compose( + retry({ + maxRetries: 3, + minTimeout: 1000, + maxTimeout: 10000, + timeoutFactor: 2, + retryAfter: true, + }) +); +``` + +##### `dump` + +The `dump` interceptor enables you to dump the response body from a request upon a given limit. + +**Options** +- `maxSize` - The maximum size (in bytes) of the response body to dump. If the size of the request's body exceeds this value then the connection will be closed. Default: `1048576`. + +> The `Dispatcher#options` also gets extended with the options `dumpMaxSize`, `abortOnDumped`, and `waitForTrailers` which can be used to configure the interceptor at a request-per-request basis. + +**Example - Basic Dump Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { dump } = interceptors; + +const client = new Client("http://example.com").compose( + dump({ + maxSize: 1024, + }) +); + +// or +client.dispatch( + { + path: "/", + method: "GET", + dumpMaxSize: 1024, + }, + handler +); +``` + +##### `dns` + +The `dns` interceptor enables you to cache DNS lookups for a given duration, per origin. + +>It is well suited for scenarios where you want to cache DNS lookups to avoid the overhead of resolving the same domain multiple times + +**Options** +- `maxTTL` - The maximum time-to-live (in milliseconds) of the DNS cache. It should be a positive integer. Default: `10000`. + - Set `0` to disable TTL. +- `maxItems` - The maximum number of items to cache. It should be a positive integer. Default: `Infinity`. +- `dualStack` - Whether to resolve both IPv4 and IPv6 addresses. Default: `true`. + - It will also attempt a happy-eyeballs-like approach to connect to the available addresses in case of a connection failure. +- `affinity` - Whether to use IPv4 or IPv6 addresses. Default: `4`. + - It can be either `'4` or `6`. + - It will only take effect if `dualStack` is `false`. +- `lookup: (hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, addresses: DNSInterceptorRecord[]) => void) => void` - Custom lookup function. Default: `dns.lookup`. + - For more info see [dns.lookup](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback). +- `pick: (origin: URL, records: DNSInterceptorRecords, affinity: 4 | 6) => DNSInterceptorRecord` - Custom pick function. Default: `RoundRobin`. + - The function should return a single record from the records array. + - By default a simplified version of Round Robin is used. + - The `records` property can be mutated to store the state of the balancing algorithm. + +> The `Dispatcher#options` also gets extended with the options `dns.affinity`, `dns.dualStack`, `dns.lookup` and `dns.pick` which can be used to configure the interceptor at a request-per-request basis. + + +**DNSInterceptorRecord** +It represents a DNS record. +- `family` - (`number`) The IP family of the address. It can be either `4` or `6`. +- `address` - (`string`) The IP address. + +**DNSInterceptorOriginRecords** +It represents a map of DNS IP addresses records for a single origin. +- `4.ips` - (`DNSInterceptorRecord[] | null`) The IPv4 addresses. +- `6.ips` - (`DNSInterceptorRecord[] | null`) The IPv6 addresses. + +**Example - Basic DNS Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { dns } = interceptors; + +const client = new Agent().compose([ + dns({ ...opts }) +]) + +const response = await client.request({ + origin: `http://localhost:3030`, + ...requestOpts +}) +``` + +##### `Response Error Interceptor` + +**Introduction** + +The Response Error Interceptor is designed to handle HTTP response errors efficiently. It intercepts responses and throws detailed errors for responses with status codes indicating failure (4xx, 5xx). This interceptor enhances error handling by providing structured error information, including response headers, data, and status codes. + +**ResponseError Class** + +The `ResponseError` class extends the `UndiciError` class and encapsulates detailed error information. It captures the response status code, headers, and data, providing a structured way to handle errors. + +**Definition** + +```js +class ResponseError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message); + this.name = 'ResponseError'; + this.message = message || 'Response error'; + this.code = 'UND_ERR_RESPONSE'; + this.statusCode = code; + this.data = data; + this.headers = headers; + } +} +``` + +**Interceptor Handler** + +The interceptor's handler class extends `DecoratorHandler` and overrides methods to capture response details and handle errors based on the response status code. + +**Methods** + +- **onConnect**: Initializes response properties. +- **onHeaders**: Captures headers and status code. Decodes body if content type is `application/json` or `text/plain`. +- **onData**: Appends chunks to the body if status code indicates an error. +- **onComplete**: Finalizes error handling, constructs a `ResponseError`, and invokes the `onError` method. +- **onError**: Propagates errors to the handler. + +**Definition** + +```js +class Handler extends DecoratorHandler { + // Private properties + #handler; + #statusCode; + #contentType; + #decoder; + #headers; + #body; + + constructor (opts, { handler }) { + super(handler); + this.#handler = handler; + } + + onConnect (abort) { + this.#statusCode = 0; + this.#contentType = null; + this.#decoder = null; + this.#headers = null; + this.#body = ''; + return this.#handler.onConnect(abort); + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage, headers = parseHeaders(rawHeaders)) { + this.#statusCode = statusCode; + this.#headers = headers; + this.#contentType = headers['content-type']; + + if (this.#statusCode < 400) { + return this.#handler.onHeaders(statusCode, rawHeaders, resume, statusMessage, headers); + } + + if (this.#contentType === 'application/json' || this.#contentType === 'text/plain') { + this.#decoder = new TextDecoder('utf-8'); + } + } + + onData (chunk) { + if (this.#statusCode < 400) { + return this.#handler.onData(chunk); + } + this.#body += this.#decoder?.decode(chunk, { stream: true }) ?? ''; + } + + onComplete (rawTrailers) { + if (this.#statusCode >= 400) { + this.#body += this.#decoder?.decode(undefined, { stream: false }) ?? ''; + if (this.#contentType === 'application/json') { + try { + this.#body = JSON.parse(this.#body); + } catch { + // Do nothing... + } + } + + let err; + const stackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + try { + err = new ResponseError('Response Error', this.#statusCode, this.#headers, this.#body); + } finally { + Error.stackTraceLimit = stackTraceLimit; + } + + this.#handler.onError(err); + } else { + this.#handler.onComplete(rawTrailers); + } + } + + onError (err) { + this.#handler.onError(err); + } +} + +module.exports = (dispatch) => (opts, handler) => opts.throwOnError + ? dispatch(opts, new Handler(opts, { handler })) + : dispatch(opts, handler); +``` + +**Tests** + +Unit tests ensure the interceptor functions correctly, handling both error and non-error responses appropriately. + +**Example Tests** + +- **No Error if `throwOnError` is False**: + +```js +test('should not error if request is not meant to throw error', async (t) => { + const opts = { throwOnError: false }; + const handler = { onError: () => {}, onData: () => {}, onComplete: () => {} }; + const interceptor = createResponseErrorInterceptor((opts, handler) => handler.onComplete()); + assert.doesNotThrow(() => interceptor(opts, handler)); +}); +``` + +- **Error if Status Code is in Specified Error Codes**: + +```js +test('should error if request status code is in the specified error codes', async (t) => { + const opts = { throwOnError: true, statusCodes: [500] }; + const response = { statusCode: 500 }; + let capturedError; + const handler = { + onError: (err) => { capturedError = err; }, + onData: () => {}, + onComplete: () => {} + }; + + const interceptor = createResponseErrorInterceptor((opts, handler) => { + if (opts.throwOnError && opts.statusCodes.includes(response.statusCode)) { + handler.onError(new Error('Response Error')); + } else { + handler.onComplete(); + } + }); + + interceptor({ ...opts, response }, handler); + + await new Promise(resolve => setImmediate(resolve)); + + assert(capturedError, 'Expected error to be captured but it was not.'); + assert.strictEqual(capturedError.message, 'Response Error'); + assert.strictEqual(response.statusCode, 500); +}); +``` + +- **No Error if Status Code is Not in Specified Error Codes**: + +```js +test('should not error if request status code is not in the specified error codes', async (t) => { + const opts = { throwOnError: true, statusCodes: [500] }; + const response = { statusCode: 404 }; + const handler = { + onError: () => {}, + onData: () => {}, + onComplete: () => {} + }; + + const interceptor = createResponseErrorInterceptor((opts, handler) => { + if (opts.throwOnError && opts.statusCodes.includes(response.statusCode)) { + handler.onError(new Error('Response Error')); + } else { + handler.onComplete(); + } + }); + + assert.doesNotThrow(() => interceptor({ ...opts, response }, handler)); +}); +``` + +**Conclusion** + +The Response Error Interceptor provides a robust mechanism for handling HTTP response errors by capturing detailed error information and propagating it through a structured `ResponseError` class. This enhancement improves error handling and debugging capabilities in applications using the interceptor. + +## Instance Events + +### Event: `'connect'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` + +### Event: `'disconnect'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when the dispatcher has been disconnected from the origin. + +> **Note**: For HTTP/2, this event is also emitted when the dispatcher has received the [GOAWAY Frame](https://webconcepts.info/concepts/http2-frame-type/0x7) with an Error with the message `HTTP/2: "GOAWAY" frame received` and the code `UND_ERR_INFO`. +> Due to nature of the protocol of using binary frames, it is possible that requests gets hanging as a frame can be received between the `HEADER` and `DATA` frames. +> It is recommended to handle this event and close the dispatcher to create a new HTTP/2 session. + +### Event: `'connectionError'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when dispatcher fails to connect to +origin. + +### Event: `'drain'` + +Parameters: + +* **origin** `URL` + +Emitted when dispatcher is no longer busy. + +## Parameter: `UndiciHeaders` + +* `Record | string[] | Iterable<[string, string | string[] | undefined]> | null` + +Header arguments such as `options.headers` in [`Client.dispatch`](Client.md#clientdispatchoptions-handlers) can be specified in three forms: +* As an object specified by the `Record` (`IncomingHttpHeaders`) type. +* As an array of strings. An array representation of a header list must have an even length, or an `InvalidArgumentError` will be thrown. +* As an iterable that can encompass `Headers`, `Map`, or a custom iterator returning key-value pairs. +Keys are lowercase and values are not modified. + +Response headers will derive a `host` from the `url` of the [Client](Client.md#class-client) instance if no `host` header was previously specified. + +### Example 1 - Object + +```js +{ + 'content-length': '123', + 'content-type': 'text/plain', + connection: 'keep-alive', + host: 'mysite.com', + accept: '*/*' +} +``` + +### Example 2 - Array + +```js +[ + 'content-length', '123', + 'content-type', 'text/plain', + 'connection', 'keep-alive', + 'host', 'mysite.com', + 'accept', '*/*' +] +``` + +### Example 3 - Iterable + +```js +new Headers({ + 'content-length': '123', + 'content-type': 'text/plain', + connection: 'keep-alive', + host: 'mysite.com', + accept: '*/*' +}) +``` +or +```js +new Map([ + ['content-length', '123'], + ['content-type', 'text/plain'], + ['connection', 'keep-alive'], + ['host', 'mysite.com'], + ['accept', '*/*'] +]) +``` +or +```js +{ + *[Symbol.iterator] () { + yield ['content-length', '123'] + yield ['content-type', 'text/plain'] + yield ['connection', 'keep-alive'] + yield ['host', 'mysite.com'] + yield ['accept', '*/*'] + } +} +``` diff --git a/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md b/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md new file mode 100644 index 0000000000000..a4932de8be790 --- /dev/null +++ b/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md @@ -0,0 +1,162 @@ +# Class: EnvHttpProxyAgent + +Stability: Experimental. + +Extends: `undici.Dispatcher` + +EnvHttpProxyAgent automatically reads the proxy configuration from the environment variables `http_proxy`, `https_proxy`, and `no_proxy` and sets up the proxy agents accordingly. When `http_proxy` and `https_proxy` are set, `http_proxy` is used for HTTP requests and `https_proxy` is used for HTTPS requests. If only `http_proxy` is set, `http_proxy` is used for both HTTP and HTTPS requests. If only `https_proxy` is set, it is only used for HTTPS requests. + +`no_proxy` is a comma or space-separated list of hostnames that should not be proxied. The list may contain leading wildcard characters (`*`). If `no_proxy` is set, the EnvHttpProxyAgent will bypass the proxy for requests to hosts that match the list. If `no_proxy` is set to `"*"`, the EnvHttpProxyAgent will bypass the proxy for all requests. + +Uppercase environment variables are also supported: `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY`. However, if both the lowercase and uppercase environment variables are set, the uppercase environment variables will be ignored. + +## `new EnvHttpProxyAgent([options])` + +Arguments: + +* **options** `EnvHttpProxyAgentOptions` (optional) - extends the `Agent` options. + +Returns: `EnvHttpProxyAgent` + +### Parameter: `EnvHttpProxyAgentOptions` + +Extends: [`AgentOptions`](Agent.md#parameter-agentoptions) + +* **httpProxy** `string` (optional) - When set, it will override the `HTTP_PROXY` environment variable. +* **httpsProxy** `string` (optional) - When set, it will override the `HTTPS_PROXY` environment variable. +* **noProxy** `string` (optional) - When set, it will override the `NO_PROXY` environment variable. + +Examples: + +```js +import { EnvHttpProxyAgent } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() +// or +const envHttpProxyAgent = new EnvHttpProxyAgent({ httpProxy: 'my.proxy.server:8080', httpsProxy: 'my.proxy.server:8443', noProxy: 'localhost' }) +``` + +#### Example - EnvHttpProxyAgent instantiation + +This will instantiate the EnvHttpProxyAgent. It will not do anything until registered as the agent to use with requests. + +```js +import { EnvHttpProxyAgent } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() +``` + +#### Example - Basic Proxy Fetch with global agent dispatcher + +```js +import { setGlobalDispatcher, fetch, EnvHttpProxyAgent } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() +setGlobalDispatcher(envHttpProxyAgent) + +const { status, json } = await fetch('http://localhost:3000/foo') + +console.log('response received', status) // response received 200 + +const data = await json() // data { foo: "bar" } +``` + +#### Example - Basic Proxy Request with global agent dispatcher + +```js +import { setGlobalDispatcher, request, EnvHttpProxyAgent } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() +setGlobalDispatcher(envHttpProxyAgent) + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with local agent dispatcher + +```js +import { EnvHttpProxyAgent, request } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: envHttpProxyAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Fetch with local agent dispatcher + +```js +import { EnvHttpProxyAgent, fetch } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() + +const { + status, + json +} = await fetch('http://localhost:3000/foo', { dispatcher: envHttpProxyAgent }) + +console.log('response received', status) // response received 200 + +const data = await json() // data { foo: "bar" } +``` + +## Instance Methods + +### `EnvHttpProxyAgent.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `EnvHttpProxyAgent.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `EnvHttpProxyAgent.dispatch(options, handler: AgentDispatchOptions)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +#### Parameter: `AgentDispatchOptions` + +Extends: [`DispatchOptions`](Dispatcher.md#parameter-dispatchoptions) + +* **origin** `string | URL` +* **maxRedirections** `Integer`. + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `EnvHttpProxyAgent.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `EnvHttpProxyAgent.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `EnvHttpProxyAgent.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `EnvHttpProxyAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `EnvHttpProxyAgent.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `EnvHttpProxyAgent.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). diff --git a/node_modules/undici/docs/docs/api/Errors.md b/node_modules/undici/docs/docs/api/Errors.md new file mode 100644 index 0000000000000..a6af44de762c2 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Errors.md @@ -0,0 +1,49 @@ +# Errors + +Undici exposes a variety of error objects that you can use to enhance your error handling. +You can find all the error objects inside the `errors` key. + +```js +import { errors } from 'undici' +``` + +| Error | Error Codes | Description | +| ------------------------------------ | ------------------------------------- | ------------------------------------------------------------------------- | +| `UndiciError` | `UND_ERR` | all errors below are extended from `UndiciError`. | +| `ConnectTimeoutError` | `UND_ERR_CONNECT_TIMEOUT` | socket is destroyed due to connect timeout. | +| `HeadersTimeoutError` | `UND_ERR_HEADERS_TIMEOUT` | socket is destroyed due to headers timeout. | +| `HeadersOverflowError` | `UND_ERR_HEADERS_OVERFLOW` | socket is destroyed due to headers' max size being exceeded. | +| `BodyTimeoutError` | `UND_ERR_BODY_TIMEOUT` | socket is destroyed due to body timeout. | +| `ResponseStatusCodeError` | `UND_ERR_RESPONSE_STATUS_CODE` | an error is thrown when `throwOnError` is `true` for status codes >= 400. | +| `InvalidArgumentError` | `UND_ERR_INVALID_ARG` | passed an invalid argument. | +| `InvalidReturnValueError` | `UND_ERR_INVALID_RETURN_VALUE` | returned an invalid value. | +| `RequestAbortedError` | `UND_ERR_ABORTED` | the request has been aborted by the user | +| `ClientDestroyedError` | `UND_ERR_DESTROYED` | trying to use a destroyed client. | +| `ClientClosedError` | `UND_ERR_CLOSED` | trying to use a closed client. | +| `SocketError` | `UND_ERR_SOCKET` | there is an error with the socket. | +| `NotSupportedError` | `UND_ERR_NOT_SUPPORTED` | encountered unsupported functionality. | +| `RequestContentLengthMismatchError` | `UND_ERR_REQ_CONTENT_LENGTH_MISMATCH` | request body does not match content-length header | +| `ResponseContentLengthMismatchError` | `UND_ERR_RES_CONTENT_LENGTH_MISMATCH` | response body does not match content-length header | +| `InformationalError` | `UND_ERR_INFO` | expected error with reason | +| `ResponseExceededMaxSizeError` | `UND_ERR_RES_EXCEEDED_MAX_SIZE` | response body exceed the max size allowed | +| `SecureProxyConnectionError` | `UND_ERR_PRX_TLS` | tls connection to a proxy failed | +| `MessageSizeExceededError` | `UND_ERR_WS_MESSAGE_SIZE_EXCEEDED` | WebSocket decompressed message exceeded the maximum allowed size | + +### `SocketError` + +The `SocketError` has a `.socket` property which holds socket metadata: + +```ts +interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number +} +``` + +Be aware that in some cases the `.socket` property can be `null`. diff --git a/node_modules/undici/docs/docs/api/EventSource.md b/node_modules/undici/docs/docs/api/EventSource.md new file mode 100644 index 0000000000000..8244aa77ed942 --- /dev/null +++ b/node_modules/undici/docs/docs/api/EventSource.md @@ -0,0 +1,45 @@ +# EventSource + +> ⚠️ Warning: the EventSource API is experimental. + +Undici exposes a WHATWG spec-compliant implementation of [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) +for [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events). + +## Instantiating EventSource + +Undici exports a EventSource class. You can instantiate the EventSource as +follows: + +```mjs +import { EventSource } from 'undici' + +const eventSource = new EventSource('http://localhost:3000') +eventSource.onmessage = (event) => { + console.log(event.data) +} +``` + +## Using a custom Dispatcher + +undici allows you to set your own Dispatcher in the EventSource constructor. + +An example which allows you to modify the request headers is: + +```mjs +import { EventSource, Agent } from 'undici' + +class CustomHeaderAgent extends Agent { + dispatch (opts) { + opts.headers['x-custom-header'] = 'hello world' + return super.dispatch(...arguments) + } +} + +const eventSource = new EventSource('http://localhost:3000', { + dispatcher: new CustomHeaderAgent() +}) + +``` + +More information about the EventSource API can be found on +[MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventSource). diff --git a/node_modules/undici/docs/docs/api/Fetch.md b/node_modules/undici/docs/docs/api/Fetch.md new file mode 100644 index 0000000000000..00c349847dcd3 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Fetch.md @@ -0,0 +1,52 @@ +# Fetch + +Undici exposes a fetch() method starts the process of fetching a resource from the network. + +Documentation and examples can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/fetch). + +## FormData + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/FormData). + +If any parameters are passed to the FormData constructor other than `undefined`, an error will be thrown. Other parameters are ignored. + +## Response + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Response) + +## Request + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Request) + +## Header + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Headers) + +# Body Mixins + +`Response` and `Request` body inherit body mixin methods. These methods include: + +- [`.arrayBuffer()`](https://fetch.spec.whatwg.org/#dom-body-arraybuffer) +- [`.blob()`](https://fetch.spec.whatwg.org/#dom-body-blob) +- [`.bytes()`](https://fetch.spec.whatwg.org/#dom-body-bytes) +- [`.formData()`](https://fetch.spec.whatwg.org/#dom-body-formdata) +- [`.json()`](https://fetch.spec.whatwg.org/#dom-body-json) +- [`.text()`](https://fetch.spec.whatwg.org/#dom-body-text) + +There is an ongoing discussion regarding `.formData()` and its usefulness and performance in server environments. It is recommended to use a dedicated library for parsing `multipart/form-data` bodies, such as [Busboy](https://www.npmjs.com/package/busboy) or [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy). + +These libraries can be interfaced with fetch with the following example code: + +```mjs +import { Busboy } from '@fastify/busboy' +import { Readable } from 'node:stream' + +const response = await fetch('...') +const busboy = new Busboy({ + headers: { + 'content-type': response.headers.get('content-type') + } +}) + +Readable.fromWeb(response.body).pipe(busboy) +``` diff --git a/node_modules/undici/docs/docs/api/MockAgent.md b/node_modules/undici/docs/docs/api/MockAgent.md new file mode 100644 index 0000000000000..85ae69046e73f --- /dev/null +++ b/node_modules/undici/docs/docs/api/MockAgent.md @@ -0,0 +1,540 @@ +# Class: MockAgent + +Extends: `undici.Dispatcher` + +A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. + +## `new MockAgent([options])` + +Arguments: + +* **options** `MockAgentOptions` (optional) - It extends the `Agent` options. + +Returns: `MockAgent` + +### Parameter: `MockAgentOptions` + +Extends: [`AgentOptions`](Agent.md#parameter-agentoptions) + +* **agent** `Agent` (optional) - Default: `new Agent([options])` - a custom agent encapsulated by the MockAgent. + +### Example - Basic MockAgent instantiation + +This will instantiate the MockAgent. It will not do anything until registered as the agent to use with requests and mock interceptions are added. + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() +``` + +### Example - Basic MockAgent instantiation with custom agent + +```js +import { Agent, MockAgent } from 'undici' + +const agent = new Agent() + +const mockAgent = new MockAgent({ agent }) +``` + +## Instance Methods + +### `MockAgent.get(origin)` + +This method creates and retrieves MockPool or MockClient instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. + +For subsequent `MockAgent.get` calls on the same origin, the same mock instance will be returned. + +Arguments: + +* **origin** `string | RegExp | (value) => boolean` - a matcher for the pool origin to be retrieved from the MockAgent. + +| Matcher type | Condition to pass | +|:------------:| -------------------------- | +| `string` | Exact match against string | +| `RegExp` | Regex must pass | +| `Function` | Function must return true | + +Returns: `MockClient | MockPool`. + +| `MockAgentOptions` | Mock instance returned | +| -------------------- | ---------------------- | +| `connections === 1` | `MockClient` | +| `connections` > `1` | `MockPool` | + +#### Example - Basic Mocked Request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock agent dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock pool dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockPool }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock client dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +mockClient.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockClient }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked requests with multiple intercepts + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') +mockPool.intercept({ path: '/hello'}).reply(200, 'hello') + +const result1 = await request('http://localhost:3000/foo') + +console.log('response received', result1.statusCode) // response received 200 + +for await (const data of result1.body) { + console.log('data', data.toString('utf8')) // data foo +} + +const result2 = await request('http://localhost:3000/hello') + +console.log('response received', result2.statusCode) // response received 200 + +for await (const data of result2.body) { + console.log('data', data.toString('utf8')) // data hello +} +``` +#### Example - Mock different requests within the same file +```js +const { MockAgent, setGlobalDispatcher } = require('undici'); +const agent = new MockAgent(); +agent.disableNetConnect(); +setGlobalDispatcher(agent); +describe('Test', () => { + it('200', async () => { + const mockAgent = agent.get('http://test.com'); + // your test + }); + it('200', async () => { + const mockAgent = agent.get('http://testing.com'); + // your test + }); +}); +``` + +#### Example - Mocked request with query body, headers and trailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo?hello=there&see=ya', + method: 'POST', + body: 'form1=data1&form2=data2' +}).reply(200, { foo: 'bar' }, { + headers: { 'content-type': 'application/json' }, + trailers: { 'Content-MD5': 'test' } +}) + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo?hello=there&see=ya', { + method: 'POST', + body: 'form1=data1&form2=data2' +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // '{"foo":"bar"}' +} + +console.log('trailers', trailers) // { 'content-md5': 'test' } +``` + +#### Example - Mocked request with origin regex + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get(new RegExp('http://localhost:3000')) +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request with origin function + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get((origin) => origin === 'http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockAgent.close()` + +Closes the mock agent and waits for registered mock pools and clients to also close before resolving. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +await mockAgent.close() +``` + +### `MockAgent.dispatch(options, handlers)` + +Implements [`Agent.dispatch(options, handlers)`](Agent.md#parameter-agentdispatchoptions). + +### `MockAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockAgent request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await mockAgent.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockAgent.deactivate()` + +This method disables mocking in MockAgent. + +Returns: `void` + +#### Example - Deactivate Mocking + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.deactivate() +``` + +### `MockAgent.activate()` + +This method enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. + +Returns: `void` + +#### Example - Activate Mocking + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.deactivate() +// No mocking will occur + +// Later +mockAgent.activate() +``` + +### `MockAgent.enableNetConnect([host])` + +When requests are not matched in a MockAgent intercept, a real HTTP request is attempted. We can control this further through the use of `enableNetConnect`. This is achieved by defining host matchers so only matching requests will be attempted. + +When using a string, it should only include the **hostname and optionally, the port**. In addition, calling this method multiple times with a string will allow all HTTP requests that match these values. + +Arguments: + +* **host** `string | RegExp | (value) => boolean` - (optional) + +Returns: `void` + +#### Example - Allow all non-matching urls to be dispatched in a real HTTP request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect() + +await request('http://example.com') +// A real request is made +``` + +#### Example - Allow requests matching a host string to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect('example-1.com') +mockAgent.enableNetConnect('example-2.com:8080') + +await request('http://example-1.com') +// A real request is made + +await request('http://example-2.com:8080') +// A real request is made + +await request('http://example-3.com') +// Will throw +``` + +#### Example - Allow requests matching a host regex to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect(new RegExp('example.com')) + +await request('http://example.com') +// A real request is made +``` + +#### Example - Allow requests matching a host function to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect((value) => value === 'example.com') + +await request('http://example.com') +// A real request is made +``` + +### `MockAgent.disableNetConnect()` + +This method causes all requests to throw when requests are not matched in a MockAgent intercept. + +Returns: `void` + +#### Example - Disable all non-matching requests by throwing an error for each + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +mockAgent.disableNetConnect() + +await request('http://example.com') +// Will throw +``` + +### `MockAgent.pendingInterceptors()` + +This method returns any pending interceptors registered on a mock agent. A pending interceptor meets one of the following criteria: + +- Is registered with neither `.times()` nor `.persist()`, and has not been invoked; +- Is persistent (i.e., registered with `.persist()`) and has not been invoked; +- Is registered with `.times()` and has not been invoked `` of times. + +Returns: `PendingInterceptor[]` (where `PendingInterceptor` is a `MockDispatch` with an additional `origin: string`) + +#### Example - List all pending inteceptors + +```js +const agent = new MockAgent() +agent.disableNetConnect() + +agent + .get('https://example.com') + .intercept({ method: 'GET', path: '/' }) + .reply(200) + +const pendingInterceptors = agent.pendingInterceptors() +// Returns [ +// { +// timesInvoked: 0, +// times: 1, +// persist: false, +// consumed: false, +// pending: true, +// path: '/', +// method: 'GET', +// body: undefined, +// headers: undefined, +// data: { +// error: null, +// statusCode: 200, +// data: '', +// headers: {}, +// trailers: {} +// }, +// origin: 'https://example.com' +// } +// ] +``` + +### `MockAgent.assertNoPendingInterceptors([options])` + +This method throws if the mock agent has any pending interceptors. A pending interceptor meets one of the following criteria: + +- Is registered with neither `.times()` nor `.persist()`, and has not been invoked; +- Is persistent (i.e., registered with `.persist()`) and has not been invoked; +- Is registered with `.times()` and has not been invoked `` of times. + +#### Example - Check that there are no pending interceptors + +```js +const agent = new MockAgent() +agent.disableNetConnect() + +agent + .get('https://example.com') + .intercept({ method: 'GET', path: '/' }) + .reply(200) + +agent.assertNoPendingInterceptors() +// Throws an UndiciError with the following message: +// +// 1 interceptor is pending: +// +// ┌─────────┬────────┬───────────────────────┬──────┬─────────────┬────────────┬─────────────┬───────────┐ +// │ (index) │ Method │ Origin │ Path │ Status code │ Persistent │ Invocations │ Remaining │ +// ├─────────┼────────┼───────────────────────┼──────┼─────────────┼────────────┼─────────────┼───────────┤ +// │ 0 │ 'GET' │ 'https://example.com' │ '/' │ 200 │ '❌' │ 0 │ 1 │ +// └─────────┴────────┴───────────────────────┴──────┴─────────────┴────────────┴─────────────┴───────────┘ +``` diff --git a/node_modules/undici/docs/docs/api/MockClient.md b/node_modules/undici/docs/docs/api/MockClient.md new file mode 100644 index 0000000000000..ac546913d237d --- /dev/null +++ b/node_modules/undici/docs/docs/api/MockClient.md @@ -0,0 +1,77 @@ +# Class: MockClient + +Extends: `undici.Client` + +A mock client class that implements the same api as [MockPool](MockPool.md). + +## `new MockClient(origin, [options])` + +Arguments: + +* **origin** `string` - It should only include the **protocol, hostname, and port**. +* **options** `MockClientOptions` - It extends the `Client` options. + +Returns: `MockClient` + +### Parameter: `MockClientOptions` + +Extends: `ClientOptions` + +* **agent** `Agent` - the agent to associate this MockClient with. + +### Example - Basic MockClient instantiation + +We can use MockAgent to instantiate a MockClient ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered. + +```js +import { MockAgent } from 'undici' + +// Connections must be set to 1 to return a MockClient instance +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +``` + +## Instance Methods + +### `MockClient.intercept(options)` + +Implements: [`MockPool.intercept(options)`](MockPool.md#mockpoolinterceptoptions) + +### `MockClient.close()` + +Implements: [`MockPool.close()`](MockPool.md#mockpoolclose) + +### `MockClient.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `MockClient.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockClient request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +mockClient.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await mockClient.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` diff --git a/node_modules/undici/docs/docs/api/MockErrors.md b/node_modules/undici/docs/docs/api/MockErrors.md new file mode 100644 index 0000000000000..c1aa3dbee8ec5 --- /dev/null +++ b/node_modules/undici/docs/docs/api/MockErrors.md @@ -0,0 +1,12 @@ +# MockErrors + +Undici exposes a variety of mock error objects that you can use to enhance your mock error handling. +You can find all the mock error objects inside the `mockErrors` key. + +```js +import { mockErrors } from 'undici' +``` + +| Mock Error | Mock Error Codes | Description | +| --------------------- | ------------------------------- | ---------------------------------------------------------- | +| `MockNotMatchedError` | `UND_MOCK_ERR_MOCK_NOT_MATCHED` | The request does not match any registered mock dispatches. | diff --git a/node_modules/undici/docs/docs/api/MockPool.md b/node_modules/undici/docs/docs/api/MockPool.md new file mode 100644 index 0000000000000..96a986f57bb38 --- /dev/null +++ b/node_modules/undici/docs/docs/api/MockPool.md @@ -0,0 +1,547 @@ +# Class: MockPool + +Extends: `undici.Pool` + +A mock Pool class that implements the Pool API and is used by MockAgent to intercept real requests and return mocked responses. + +## `new MockPool(origin, [options])` + +Arguments: + +* **origin** `string` - It should only include the **protocol, hostname, and port**. +* **options** `MockPoolOptions` - It extends the `Pool` options. + +Returns: `MockPool` + +### Parameter: `MockPoolOptions` + +Extends: `PoolOptions` + +* **agent** `Agent` - the agent to associate this MockPool with. + +### Example - Basic MockPool instantiation + +We can use MockAgent to instantiate a MockPool ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered. + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +``` + +## Instance Methods + +### `MockPool.intercept(options)` + +This method defines the interception rules for matching against requests for a MockPool or MockPool. We can intercept multiple times on a single instance, but each intercept is only used once. For example if you expect to make 2 requests inside a test, you need to call `intercept()` twice. Assuming you use `disableNetConnect()` you will get `MockNotMatchedError` on the second request when you only call `intercept()` once. + +When defining interception rules, all the rules must pass for a request to be intercepted. If a request is not intercepted, a real request will be attempted. + +| Matcher type | Condition to pass | +|:------------:| -------------------------- | +| `string` | Exact match against string | +| `RegExp` | Regex must pass | +| `Function` | Function must return true | + +Arguments: + +* **options** `MockPoolInterceptOptions` - Interception options. + +Returns: `MockInterceptor` corresponding to the input options. + +### Parameter: `MockPoolInterceptOptions` + +* **path** `string | RegExp | (path: string) => boolean` - a matcher for the HTTP request path. When a `RegExp` or callback is used, it will match against the request path including all query parameters in alphabetical order. When a `string` is provided, the query parameters can be conveniently specified through the `MockPoolInterceptOptions.query` setting. +* **method** `string | RegExp | (method: string) => boolean` - (optional) - a matcher for the HTTP request method. Defaults to `GET`. +* **body** `string | RegExp | (body: string) => boolean` - (optional) - a matcher for the HTTP request body. +* **headers** `Record boolean`> - (optional) - a matcher for the HTTP request headers. To be intercepted, a request must match all defined headers. Extra headers not defined here may (or may not) be included in the request and do not affect the interception in any way. +* **query** `Record | null` - (optional) - a matcher for the HTTP request query string params. Only applies when a `string` was provided for `MockPoolInterceptOptions.path`. + +### Return: `MockInterceptor` + +We can define the behaviour of an intercepted request with the following options. + +* **reply** `(statusCode: number, replyData: string | Buffer | object | MockInterceptor.MockResponseDataHandler, responseOptions?: MockResponseOptions) => MockScope` - define a reply for a matching request. You can define the replyData as a callback to read incoming request data. Default for `responseOptions` is `{}`. +* **reply** `(callback: MockInterceptor.MockReplyOptionsCallback) => MockScope` - define a reply for a matching request, allowing dynamic mocking of all reply options rather than just the data. +* **replyWithError** `(error: Error) => MockScope` - define an error for a matching request to throw. +* **defaultReplyHeaders** `(headers: Record) => MockInterceptor` - define default headers to be included in subsequent replies. These are in addition to headers on a specific reply. +* **defaultReplyTrailers** `(trailers: Record) => MockInterceptor` - define default trailers to be included in subsequent replies. These are in addition to trailers on a specific reply. +* **replyContentLength** `() => MockInterceptor` - define automatically calculated `content-length` headers to be included in subsequent replies. + +The reply data of an intercepted request may either be a string, buffer, or JavaScript object. Objects are converted to JSON while strings and buffers are sent as-is. + +By default, `reply` and `replyWithError` define the behaviour for the first matching request only. Subsequent requests will not be affected (this can be changed using the returned `MockScope`). + +### Parameter: `MockResponseOptions` + +* **headers** `Record` - headers to be included on the mocked reply. +* **trailers** `Record` - trailers to be included on the mocked reply. + +### Return: `MockScope` + +A `MockScope` is associated with a single `MockInterceptor`. With this, we can configure the default behaviour of a intercepted reply. + +* **delay** `(waitInMs: number) => MockScope` - delay the associated reply by a set amount in ms. +* **persist** `() => MockScope` - any matching request will always reply with the defined response indefinitely. +* **times** `(repeatTimes: number) => MockScope` - any matching request will reply with the defined response a fixed amount of times. This is overridden by **persist**. + +#### Example - Basic Mocked Request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +// MockPool +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request using reply data callbacks + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/echo', + method: 'GET', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(200, ({ headers }) => ({ message: headers.get('message') })) + +const { statusCode, body, headers } = await request('http://localhost:3000', { + headers: { + message: 'hello world!' + } +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // { "message":"hello world!" } +} +``` + +#### Example - Mocked request using reply options callback + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/echo', + method: 'GET', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(({ headers }) => ({ statusCode: 200, data: { message: headers.get('message') }}))) + +const { statusCode, body, headers } = await request('http://localhost:3000', { + headers: { + message: 'hello world!' + } +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // { "message":"hello world!" } +} +``` + +#### Example - Basic Mocked requests with multiple intercepts + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo') + +mockPool.intercept({ + path: '/hello', + method: 'GET', +}).reply(200, 'hello') + +const result1 = await request('http://localhost:3000/foo') + +console.log('response received', result1.statusCode) // response received 200 + +for await (const data of result1.body) { + console.log('data', data.toString('utf8')) // data foo +} + +const result2 = await request('http://localhost:3000/hello') + +console.log('response received', result2.statusCode) // response received 200 + +for await (const data of result2.body) { + console.log('data', data.toString('utf8')) // data hello +} +``` + +#### Example - Mocked request with query body, request headers and response headers and trailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo?hello=there&see=ya', + method: 'POST', + body: 'form1=data1&form2=data2', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(200, { foo: 'bar' }, { + headers: { 'content-type': 'application/json' }, + trailers: { 'Content-MD5': 'test' } +}) + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo?hello=there&see=ya', { + method: 'POST', + body: 'form1=data1&form2=data2', + headers: { + foo: 'bar', + 'User-Agent': 'undici', + Host: 'example.com' + } + }) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // '{"foo":"bar"}' +} + +console.log('trailers', trailers) // { 'content-md5': 'test' } +``` + +#### Example - Mocked request using different matchers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: /^GET$/, + body: (value) => value === 'form=data', + headers: { + 'User-Agent': 'undici', + Host: /^example.com$/ + } +}).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { + method: 'GET', + body: 'form=data', + headers: { + foo: 'bar', + 'User-Agent': 'undici', + Host: 'example.com' + } +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request with reply with a defined error + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyWithError(new Error('kaboom')) + +try { + await request('http://localhost:3000/foo', { + method: 'GET' + }) +} catch (error) { + console.error(error) // Error: kaboom +} +``` + +#### Example - Mocked request with defaultReplyHeaders + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).defaultReplyHeaders({ foo: 'bar' }) + .reply(200, 'foo') + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { foo: 'bar' } +``` + +#### Example - Mocked request with defaultReplyTrailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).defaultReplyTrailers({ foo: 'bar' }) + .reply(200, 'foo') + +const { trailers } = await request('http://localhost:3000/foo') + +console.log('trailers', trailers) // trailers { foo: 'bar' } +``` + +#### Example - Mocked request with automatic content-length calculation + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyContentLength().reply(200, 'foo') + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { 'content-length': '3' } +``` + +#### Example - Mocked request with automatic content-length calculation on an object + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyContentLength().reply(200, { foo: 'bar' }) + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { 'content-length': '13' } +``` + +#### Example - Mocked request with persist enabled + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo').persist() + +const result1 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result2 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +// Etc +``` + +#### Example - Mocked request with times enabled + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo').times(2) + +const result1 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result2 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result3 = await request('http://localhost:3000/foo') +// Will not match and make attempt a real request +``` + +#### Example - Mocked request with path callback + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' +import querystring from 'querystring' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +const matchPath = requestPath => { + const [pathname, search] = requestPath.split('?') + const requestQuery = querystring.parse(search) + + if (!pathname.startsWith('/foo')) { + return false + } + + if (!Object.keys(requestQuery).includes('foo') || requestQuery.foo !== 'bar') { + return false + } + + return true +} + +mockPool.intercept({ + path: matchPath, + method: 'GET' +}).reply(200, 'foo') + +const result = await request('http://localhost:3000/foo?foo=bar') +// Will match and return mocked data +``` + +### `MockPool.close()` + +Closes the mock pool and de-registers from associated MockAgent. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() +const mockPool = mockAgent.get('http://localhost:3000') + +await mockPool.close() +``` + +### `MockPool.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `MockPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockPool request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ + path: '/foo', + method: 'GET', +}).reply(200, 'foo') + +const { + statusCode, + body +} = await mockPool.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` diff --git a/node_modules/undici/docs/docs/api/Pool.md b/node_modules/undici/docs/docs/api/Pool.md new file mode 100644 index 0000000000000..8fcabac31541d --- /dev/null +++ b/node_modules/undici/docs/docs/api/Pool.md @@ -0,0 +1,84 @@ +# Class: Pool + +Extends: `undici.Dispatcher` + +A pool of [Client](Client.md) instances connected to the same upstream target. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new Pool(url[, options])` + +Arguments: + +* **url** `URL | string` - It should only include the **protocol, hostname, and port**. +* **options** `PoolOptions` (optional) + +### Parameter: `PoolOptions` + +Extends: [`ClientOptions`](Client.md#parameter-clientoptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Client(origin, opts)` +* **connections** `number | null` (optional) - Default: `null` - The number of `Client` instances to create. When set to `null`, the `Pool` instance will create an unlimited amount of `Client` instances. +* **interceptors** `{ Pool: DispatchInterceptor[] } }` - Default: `{ Pool: [] }` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). + +## Instance Properties + +### `Pool.closed` + +Implements [Client.closed](Client.md#clientclosed) + +### `Pool.destroyed` + +Implements [Client.destroyed](Client.md#clientdestroyed) + +### `Pool.stats` + +Returns [`PoolStats`](PoolStats.md) instance for this pool. + +## Instance Methods + +### `Pool.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `Pool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Pool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `Pool.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Pool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Pool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `Pool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Pool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain). diff --git a/node_modules/undici/docs/docs/api/PoolStats.md b/node_modules/undici/docs/docs/api/PoolStats.md new file mode 100644 index 0000000000000..16b6dc25364a2 --- /dev/null +++ b/node_modules/undici/docs/docs/api/PoolStats.md @@ -0,0 +1,35 @@ +# Class: PoolStats + +Aggregate stats for a [Pool](Pool.md) or [BalancedPool](BalancedPool.md). + +## `new PoolStats(pool)` + +Arguments: + +* **pool** `Pool` - Pool or BalancedPool from which to return stats. + +## Instance Properties + +### `PoolStats.connected` + +Number of open socket connections in this pool. + +### `PoolStats.free` + +Number of open socket connections in this pool that do not have an active request. + +### `PoolStats.pending` + +Number of pending requests across all clients in this pool. + +### `PoolStats.queued` + +Number of queued requests across all clients in this pool. + +### `PoolStats.running` + +Number of currently active requests across all clients in this pool. + +### `PoolStats.size` + +Number of active, pending, or queued requests across all clients in this pool. diff --git a/node_modules/undici/docs/docs/api/ProxyAgent.md b/node_modules/undici/docs/docs/api/ProxyAgent.md new file mode 100644 index 0000000000000..a1a0d4651c82b --- /dev/null +++ b/node_modules/undici/docs/docs/api/ProxyAgent.md @@ -0,0 +1,131 @@ +# Class: ProxyAgent + +Extends: `undici.Dispatcher` + +A Proxy Agent class that implements the Agent API. It allows the connection through proxy in a simple way. + +## `new ProxyAgent([options])` + +Arguments: + +* **options** `ProxyAgentOptions` (required) - It extends the `Agent` options. + +Returns: `ProxyAgent` + +### Parameter: `ProxyAgentOptions` + +Extends: [`AgentOptions`](Agent.md#parameter-agentoptions) + +* **uri** `string | URL` (required) - The URI of the proxy server. This can be provided as a string, as an instance of the URL class, or as an object with a `uri` property of type string. +If the `uri` is provided as a string or `uri` is an object with an `uri` property of type string, then it will be parsed into a `URL` object according to the [WHATWG URL Specification](https://url.spec.whatwg.org). +For detailed information on the parsing process and potential validation errors, please refer to the ["Writing" section](https://url.spec.whatwg.org/#writing) of the WHATWG URL Specification. +* **token** `string` (optional) - It can be passed by a string of token for authentication. +* **auth** `string` (**deprecated**) - Use token. +* **clientFactory** `(origin: URL, opts: Object) => Dispatcher` (optional) - Default: `(origin, opts) => new Pool(origin, opts)` +* **requestTls** `BuildOptions` (optional) - Options object passed when creating the underlying socket via the connector builder for the request. It extends from [`Client#ConnectOptions`](/docs/docs/api/Client.md#parameter-connectoptions). +* **proxyTls** `BuildOptions` (optional) - Options object passed when creating the underlying socket via the connector builder for the proxy server. It extends from [`Client#ConnectOptions`](/docs/docs/api/Client.md#parameter-connectoptions). +* **proxyTunnel** `boolean` (optional) - For connections involving secure protocols, Undici will always establish a tunnel via the HTTP2 CONNECT extension. If proxyTunnel is set to true, this will occur for unsecured proxy/endpoint connections as well. Currently, there is no way to facilitate HTTP1 IP tunneling as described in https://www.rfc-editor.org/rfc/rfc9484.html#name-http-11-request. If proxyTunnel is set to false (the default), ProxyAgent connections where both the Proxy and Endpoint are unsecured will issue all requests to the Proxy, and prefix the endpoint request path with the endpoint origin address. + +Examples: + +```js +import { ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +// or +const proxyAgent = new ProxyAgent(new URL('my.proxy.server')) +// or +const proxyAgent = new ProxyAgent({ uri: 'my.proxy.server' }) +``` + +#### Example - Basic ProxyAgent instantiation + +This will instantiate the ProxyAgent. It will not do anything until registered as the agent to use with requests. + +```js +import { ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +``` + +#### Example - Basic Proxy Request with global agent dispatcher + +```js +import { setGlobalDispatcher, request, ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +setGlobalDispatcher(proxyAgent) + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with local agent dispatcher + +```js +import { ProxyAgent, request } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: proxyAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with authentication + +```js +import { setGlobalDispatcher, request, ProxyAgent } from 'undici'; + +const proxyAgent = new ProxyAgent({ + uri: 'my.proxy.server', + // token: 'Bearer xxxx' + token: `Basic ${Buffer.from('username:password').toString('base64')}` +}); +setGlobalDispatcher(proxyAgent); + +const { statusCode, body } = await request('http://localhost:3000/foo'); + +console.log('response received', statusCode); // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')); // data foo +} +``` + +### `ProxyAgent.close()` + +Closes the proxy agent and waits for registered pools and clients to also close before resolving. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { ProxyAgent, setGlobalDispatcher } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +setGlobalDispatcher(proxyAgent) + +await proxyAgent.close() +``` + +### `ProxyAgent.dispatch(options, handlers)` + +Implements [`Agent.dispatch(options, handlers)`](Agent.md#parameter-agentdispatchoptions). + +### `ProxyAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). diff --git a/node_modules/undici/docs/docs/api/RedirectHandler.md b/node_modules/undici/docs/docs/api/RedirectHandler.md new file mode 100644 index 0000000000000..90a937e7c13b9 --- /dev/null +++ b/node_modules/undici/docs/docs/api/RedirectHandler.md @@ -0,0 +1,96 @@ +# Class: RedirectHandler + +A class that handles redirection logic for HTTP requests. + +## `new RedirectHandler(dispatch, maxRedirections, opts, handler, redirectionLimitReached)` + +Arguments: + +- **dispatch** `function` - The dispatch function to be called after every retry. +- **maxRedirections** `number` - Maximum number of redirections allowed. +- **opts** `object` - Options for handling redirection. +- **handler** `object` - An object containing handlers for different stages of the request lifecycle. +- **redirectionLimitReached** `boolean` (default: `false`) - A flag that the implementer can provide to enable or disable the feature. If set to `false`, it indicates that the caller doesn't want to use the feature and prefers the old behavior. + +Returns: `RedirectHandler` + +### Parameters + +- **dispatch** `(options: Dispatch.DispatchOptions, handlers: Dispatch.DispatchHandlers) => Promise` (required) - Dispatch function to be called after every redirection. +- **maxRedirections** `number` (required) - Maximum number of redirections allowed. +- **opts** `object` (required) - Options for handling redirection. +- **handler** `object` (required) - Handlers for different stages of the request lifecycle. +- **redirectionLimitReached** `boolean` (default: `false`) - A flag that the implementer can provide to enable or disable the feature. If set to `false`, it indicates that the caller doesn't want to use the feature and prefers the old behavior. + +### Properties + +- **location** `string` - The current redirection location. +- **abort** `function` - The abort function. +- **opts** `object` - The options for handling redirection. +- **maxRedirections** `number` - Maximum number of redirections allowed. +- **handler** `object` - Handlers for different stages of the request lifecycle. +- **history** `Array` - An array representing the history of URLs during redirection. +- **redirectionLimitReached** `boolean` - Indicates whether the redirection limit has been reached. + +### Methods + +#### `onConnect(abort)` + +Called when the connection is established. + +Parameters: + +- **abort** `function` - The abort function. + +#### `onUpgrade(statusCode, headers, socket)` + +Called when an upgrade is requested. + +Parameters: + +- **statusCode** `number` - The HTTP status code. +- **headers** `object` - The headers received in the response. +- **socket** `object` - The socket object. + +#### `onError(error)` + +Called when an error occurs. + +Parameters: + +- **error** `Error` - The error that occurred. + +#### `onHeaders(statusCode, headers, resume, statusText)` + +Called when headers are received. + +Parameters: + +- **statusCode** `number` - The HTTP status code. +- **headers** `object` - The headers received in the response. +- **resume** `function` - The resume function. +- **statusText** `string` - The status text. + +#### `onData(chunk)` + +Called when data is received. + +Parameters: + +- **chunk** `Buffer` - The data chunk received. + +#### `onComplete(trailers)` + +Called when the request is complete. + +Parameters: + +- **trailers** `object` - The trailers received. + +#### `onBodySent(chunk)` + +Called when the request body is sent. + +Parameters: + +- **chunk** `Buffer` - The chunk of the request body sent. diff --git a/node_modules/undici/docs/docs/api/RetryAgent.md b/node_modules/undici/docs/docs/api/RetryAgent.md new file mode 100644 index 0000000000000..53ce52313156d --- /dev/null +++ b/node_modules/undici/docs/docs/api/RetryAgent.md @@ -0,0 +1,45 @@ +# Class: RetryAgent + +Extends: `undici.Dispatcher` + +A `undici.Dispatcher` that allows to automatically retry a request. +Wraps a `undici.RetryHandler`. + +## `new RetryAgent(dispatcher, [options])` + +Arguments: + +* **dispatcher** `undici.Dispatcher` (required) - the dispatcher to wrap +* **options** `RetryHandlerOptions` (optional) - the options + +Returns: `ProxyAgent` + +### Parameter: `RetryHandlerOptions` + +- **retry** `(err: Error, context: RetryContext, callback: (err?: Error | null) => void) => void` (optional) - Function to be called after every retry. It should pass error if no more retries should be performed. +- **maxRetries** `number` (optional) - Maximum number of retries. Default: `5` +- **maxTimeout** `number` (optional) - Maximum number of milliseconds to wait before retrying. Default: `30000` (30 seconds) +- **minTimeout** `number` (optional) - Minimum number of milliseconds to wait before retrying. Default: `500` (half a second) +- **timeoutFactor** `number` (optional) - Factor to multiply the timeout by for each retry attempt. Default: `2` +- **retryAfter** `boolean` (optional) - It enables automatic retry after the `Retry-After` header is received. Default: `true` +- +- **methods** `string[]` (optional) - Array of HTTP methods to retry. Default: `['GET', 'PUT', 'HEAD', 'OPTIONS', 'DELETE']` +- **statusCodes** `number[]` (optional) - Array of HTTP status codes to retry. Default: `[429, 500, 502, 503, 504]` +- **errorCodes** `string[]` (optional) - Array of Error codes to retry. Default: `['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN','ENETUNREACH', 'EHOSTDOWN', 'UND_ERR_SOCKET']` + +**`RetryContext`** + +- `state`: `RetryState` - Current retry state. It can be mutated. +- `opts`: `Dispatch.DispatchOptions & RetryOptions` - Options passed to the retry handler. + +Example: + +```js +import { Agent, RetryAgent } from 'undici' + +const agent = new RetryAgent(new Agent()) + +const res = await agent.request('http://example.com') +console.log(res.statuCode) +console.log(await res.body.text()) +``` diff --git a/node_modules/undici/docs/docs/api/RetryHandler.md b/node_modules/undici/docs/docs/api/RetryHandler.md new file mode 100644 index 0000000000000..0dd9f29533f86 --- /dev/null +++ b/node_modules/undici/docs/docs/api/RetryHandler.md @@ -0,0 +1,117 @@ +# Class: RetryHandler + +Extends: `undici.DispatcherHandlers` + +A handler class that implements the retry logic for a request. + +## `new RetryHandler(dispatchOptions, retryHandlers, [retryOptions])` + +Arguments: + +- **options** `Dispatch.DispatchOptions & RetryOptions` (required) - It is an intersection of `Dispatcher.DispatchOptions` and `RetryOptions`. +- **retryHandlers** `RetryHandlers` (required) - Object containing the `dispatch` to be used on every retry, and `handler` for handling the `dispatch` lifecycle. + +Returns: `retryHandler` + +### Parameter: `Dispatch.DispatchOptions & RetryOptions` + +Extends: [`Dispatch.DispatchOptions`](Dispatcher.md#parameter-dispatchoptions). + +#### `RetryOptions` + +- **retry** `(err: Error, context: RetryContext, callback: (err?: Error | null) => void) => number | null` (optional) - Function to be called after every retry. It should pass error if no more retries should be performed. +- **maxRetries** `number` (optional) - Maximum number of retries. Default: `5` +- **maxTimeout** `number` (optional) - Maximum number of milliseconds to wait before retrying. Default: `30000` (30 seconds) +- **minTimeout** `number` (optional) - Minimum number of milliseconds to wait before retrying. Default: `500` (half a second) +- **timeoutFactor** `number` (optional) - Factor to multiply the timeout by for each retry attempt. Default: `2` +- **retryAfter** `boolean` (optional) - It enables automatic retry after the `Retry-After` header is received. Default: `true` +- +- **methods** `string[]` (optional) - Array of HTTP methods to retry. Default: `['GET', 'PUT', 'HEAD', 'OPTIONS', 'DELETE']` +- **statusCodes** `number[]` (optional) - Array of HTTP status codes to retry. Default: `[429, 500, 502, 503, 504]` +- **errorCodes** `string[]` (optional) - Array of Error codes to retry. Default: `['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN','ENETUNREACH', 'EHOSTDOWN', 'UND_ERR_SOCKET']` + +**`RetryContext`** + +- `state`: `RetryState` - Current retry state. It can be mutated. +- `opts`: `Dispatch.DispatchOptions & RetryOptions` - Options passed to the retry handler. + +**`RetryState`** + +It represents the retry state for a given request. + +- `counter`: `number` - Current retry attempt. + +### Parameter `RetryHandlers` + +- **dispatch** `(options: Dispatch.DispatchOptions, handlers: Dispatch.DispatchHandlers) => Promise` (required) - Dispatch function to be called after every retry. +- **handler** Extends [`Dispatch.DispatchHandlers`](Dispatcher.md#dispatcherdispatchoptions-handler) (required) - Handler function to be called after the request is successful or the retries are exhausted. + +>__Note__: The `RetryHandler` does not retry over stateful bodies (e.g. streams, AsyncIterable) as those, once consumed, are left in an state that cannot be reutilized. For these situations the `RetryHandler` will identify +>the body as stateful and will not retry the request rejecting with the error `UND_ERR_REQ_RETRY`. + +Examples: + +```js +const client = new Client(`http://localhost:${server.address().port}`); +const chunks = []; +const handler = new RetryHandler( + { + ...dispatchOptions, + retryOptions: { + // custom retry function + retry: function (err, state, callback) { + counter++; + + if (err.code && err.code === "UND_ERR_DESTROYED") { + callback(err); + return; + } + + if (err.statusCode === 206) { + callback(err); + return; + } + + setTimeout(() => callback(null), 1000); + }, + }, + }, + { + dispatch: (...args) => { + return client.dispatch(...args); + }, + handler: { + onConnect() {}, + onBodySent() {}, + onHeaders(status, _rawHeaders, resume, _statusMessage) { + // do something with headers + }, + onData(chunk) { + chunks.push(chunk); + return true; + }, + onComplete() {}, + onError() { + // handle error properly + }, + }, + } +); +``` + +#### Example - Basic RetryHandler with defaults + +```js +const client = new Client(`http://localhost:${server.address().port}`); +const handler = new RetryHandler(dispatchOptions, { + dispatch: client.dispatch.bind(client), + handler: { + onConnect() {}, + onBodySent() {}, + onHeaders(status, _rawHeaders, resume, _statusMessage) {}, + onData(chunk) {}, + onComplete() {}, + onError(err) {}, + }, +}); +``` diff --git a/node_modules/undici/docs/docs/api/Util.md b/node_modules/undici/docs/docs/api/Util.md new file mode 100644 index 0000000000000..53b96e3ed3f50 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Util.md @@ -0,0 +1,25 @@ +# Util + +Utility API for third-party implementations of the dispatcher API. + +## `parseHeaders(headers, [obj])` + +Receives a header object and returns the parsed value. + +Arguments: + +- **headers** `(Buffer | string | (Buffer | string)[])[]` (required) - Header object. + +- **obj** `Record` (optional) - Object to specify a proxy object. The parsed value is assigned to this object. But, if **headers** is an object, it is not used. + +Returns: `Record` If **obj** is specified, it is equivalent to **obj**. + +## `headerNameToString(value)` + +Retrieves a header name and returns its lowercase value. + +Arguments: + +- **value** `string | Buffer` (required) - Header name. + +Returns: `string` diff --git a/node_modules/undici/docs/docs/api/WebSocket.md b/node_modules/undici/docs/docs/api/WebSocket.md new file mode 100644 index 0000000000000..8b6f7b9cfdaea --- /dev/null +++ b/node_modules/undici/docs/docs/api/WebSocket.md @@ -0,0 +1,51 @@ +# Class: WebSocket + +> ⚠️ Warning: the WebSocket API is experimental. + +Extends: [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) + +The WebSocket object provides a way to manage a WebSocket connection to a server, allowing bidirectional communication. The API follows the [WebSocket spec](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) and [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455). + +## `new WebSocket(url[, protocol])` + +Arguments: + +* **url** `URL | string` - The url's protocol *must* be `ws` or `wss`. +* **protocol** `string | string[] | WebSocketInit` (optional) - Subprotocol(s) to request the server use, or a [`Dispatcher`](./Dispatcher.md). + +### WebSocketInit + +When passing an object as the second argument, the following options are available: + +* **protocols** `string | string[]` (optional) - Subprotocol(s) to request the server use. +* **dispatcher** `Dispatcher` (optional) - A custom [`Dispatcher`](/docs/docs/api/Dispatcher.md) to use for the connection. +* **headers** `HeadersInit` (optional) - Custom headers to include in the WebSocket handshake request. + +### Example: + +This example will not work in browsers or other platforms that don't allow passing an object. + +```mjs +import { WebSocket, ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') + +const ws = new WebSocket('wss://echo.websocket.events', { + dispatcher: proxyAgent, + protocols: ['echo', 'chat'] +}) +``` + +If you do not need a custom Dispatcher, it's recommended to use the following pattern: + +```mjs +import { WebSocket } from 'undici' + +const ws = new WebSocket('wss://echo.websocket.events', ['echo', 'chat']) +``` + +## Read More + +- [MDN - WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +- [The WebSocket Specification](https://www.rfc-editor.org/rfc/rfc6455) +- [The WHATWG WebSocket Specification](https://websockets.spec.whatwg.org/) diff --git a/node_modules/undici/docs/docs/api/api-lifecycle.md b/node_modules/undici/docs/docs/api/api-lifecycle.md new file mode 100644 index 0000000000000..2e7db25d132a1 --- /dev/null +++ b/node_modules/undici/docs/docs/api/api-lifecycle.md @@ -0,0 +1,91 @@ +# Client Lifecycle + +An Undici [Client](Client.md) can be best described as a state machine. The following list is a summary of the various state transitions the `Client` will go through in its lifecycle. This document also contains detailed breakdowns of each state. + +> This diagram is not a perfect representation of the undici Client. Since the Client class is not actually implemented as a state-machine, actual execution may deviate slightly from what is described below. Consider this as a general resource for understanding the inner workings of the Undici client rather than some kind of formal specification. + +## State Transition Overview + +* A `Client` begins in the **idle** state with no socket connection and no requests in queue. + * The *connect* event transitions the `Client` to the **pending** state where requests can be queued prior to processing. + * The *close* and *destroy* events transition the `Client` to the **destroyed** state. Since there are no requests in the queue, the *close* event immediately transitions to the **destroyed** state. +* The **pending** state indicates the underlying socket connection has been successfully established and requests are queueing. + * The *process* event transitions the `Client` to the **processing** state where requests are processed. + * If requests are queued, the *close* event transitions to the **processing** state; otherwise, it transitions to the **destroyed** state. + * The *destroy* event transitions to the **destroyed** state. +* The **processing** state initializes to the **processing.running** state. + * If the current request requires draining, the *needDrain* event transitions the `Client` into the **processing.busy** state which will return to the **processing.running** state with the *drainComplete* event. + * After all queued requests are completed, the *keepalive* event transitions the `Client` back to the **pending** state. If no requests are queued during the timeout, the **close** event transitions the `Client` to the **destroyed** state. + * If the *close* event is fired while the `Client` still has queued requests, the `Client` transitions to the **process.closing** state where it will complete all existing requests before firing the *done* event. + * The *done* event gracefully transitions the `Client` to the **destroyed** state. + * At any point in time, the *destroy* event will transition the `Client` from the **processing** state to the **destroyed** state, destroying any queued requests. +* The **destroyed** state is a final state and the `Client` is no longer functional. + +A state diagram representing an Undici Client instance: + +```mermaid +stateDiagram-v2 + [*] --> idle + idle --> pending : connect + idle --> destroyed : destroy/close + + pending --> idle : timeout + pending --> destroyed : destroy + + state close_fork <> + pending --> close_fork : close + close_fork --> processing + close_fork --> destroyed + + pending --> processing : process + + processing --> pending : keepalive + processing --> destroyed : done + processing --> destroyed : destroy + + destroyed --> [*] + + state processing { + [*] --> running + running --> closing : close + running --> busy : needDrain + busy --> running : drainComplete + running --> [*] : keepalive + closing --> [*] : done + } +``` +## State details + +### idle + +The **idle** state is the initial state of a `Client` instance. While an `origin` is required for instantiating a `Client` instance, the underlying socket connection will not be established until a request is queued using [`Client.dispatch()`](Client.md#clientdispatchoptions-handlers). By calling `Client.dispatch()` directly or using one of the multiple implementations ([`Client.connect()`](Client.md#clientconnectoptions-callback), [`Client.pipeline()`](Client.md#clientpipelineoptions-handler), [`Client.request()`](Client.md#clientrequestoptions-callback), [`Client.stream()`](Client.md#clientstreamoptions-factory-callback), and [`Client.upgrade()`](Client.md#clientupgradeoptions-callback)), the `Client` instance will transition from **idle** to [**pending**](#pending) and then most likely directly to [**processing**](#processing). + +Calling [`Client.close()`](Client.md#clientclosecallback) or [`Client.destroy()`](Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](#destroyed) state since the `Client` instance will have no queued requests in this state. + +### pending + +The **pending** state signifies a non-processing `Client`. Upon entering this state, the `Client` establishes a socket connection and emits the [`'connect'`](Client.md#event-connect) event signalling a connection was successfully established with the `origin` provided during `Client` instantiation. The internal queue is initially empty, and requests can start queueing. + +Calling [`Client.close()`](Client.md#clientclosecallback) with queued requests, transitions the `Client` to the [**processing**](#processing) state. Without queued requests, it transitions to the [**destroyed**](#destroyed) state. + +Calling [`Client.destroy()`](Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](#destroyed) state regardless of existing requests. + +### processing + +The **processing** state is a state machine within itself. It initializes to the [**processing.running**](#running) state. The [`Client.dispatch()`](Client.md#clientdispatchoptions-handlers), [`Client.close()`](Client.md#clientclosecallback), and [`Client.destroy()`](Client.md#clientdestroyerror-callback) can be called at any time while the `Client` is in this state. `Client.dispatch()` will add more requests to the queue while existing requests continue to be processed. `Client.close()` will transition to the [**processing.closing**](#closing) state. And `Client.destroy()` will transition to [**destroyed**](#destroyed). + +#### running + +In the **processing.running** sub-state, queued requests are being processed in a FIFO order. If a request body requires draining, the *needDrain* event transitions to the [**processing.busy**](#busy) sub-state. The *close* event transitions the Client to the [**process.closing**](#closing) sub-state. If all queued requests are processed and neither [`Client.close()`](Client.md#clientclosecallback) nor [`Client.destroy()`](Client.md#clientdestroyerror-callback) are called, then the [**processing**](#processing) machine will trigger a *keepalive* event transitioning the `Client` back to the [**pending**](#pending) state. During this time, the `Client` is waiting for the socket connection to timeout, and once it does, it triggers the *timeout* event and transitions to the [**idle**](#idle) state. + +#### busy + +This sub-state is only entered when a request body is an instance of [Stream](https://nodejs.org/api/stream.html) and requires draining. The `Client` cannot process additional requests while in this state and must wait until the currently processing request body is completely drained before transitioning back to [**processing.running**](#running). + +#### closing + +This sub-state is only entered when a `Client` instance has queued requests and the [`Client.close()`](Client.md#clientclosecallback) method is called. In this state, the `Client` instance continues to process requests as usual, with the one exception that no additional requests can be queued. Once all of the queued requests are processed, the `Client` will trigger the *done* event gracefully entering the [**destroyed**](#destroyed) state without an error. + +### destroyed + +The **destroyed** state is a final state for the `Client` instance. Once in this state, a `Client` is nonfunctional. Calling any other `Client` methods will result in an `ClientDestroyedError`. diff --git a/node_modules/undici/docs/docs/best-practices/client-certificate.md b/node_modules/undici/docs/docs/best-practices/client-certificate.md new file mode 100644 index 0000000000000..9ead733af9e87 --- /dev/null +++ b/node_modules/undici/docs/docs/best-practices/client-certificate.md @@ -0,0 +1,64 @@ +# Client certificate + +Client certificate authentication can be configured with the `Client`, the required options are passed along through the `connect` option. + +The client certificates must be signed by a trusted CA. The Node.js default is to trust the well-known CAs curated by Mozilla. + +Setting the server option `requestCert: true` tells the server to request the client certificate. + +The server option `rejectUnauthorized: false` allows us to handle any invalid certificate errors in client code. The `authorized` property on the socket of the incoming request will show if the client certificate was valid. The `authorizationError` property will give the reason if the certificate was not valid. + +### Client Certificate Authentication + +```js +const { readFileSync } = require('node:fs') +const { join } = require('node:path') +const { createServer } = require('node:https') +const { Client } = require('undici') + +const serverOptions = { + ca: [ + readFileSync(join(__dirname, 'client-ca-crt.pem'), 'utf8') + ], + key: readFileSync(join(__dirname, 'server-key.pem'), 'utf8'), + cert: readFileSync(join(__dirname, 'server-crt.pem'), 'utf8'), + requestCert: true, + rejectUnauthorized: false +} + +const server = createServer(serverOptions, (req, res) => { + // true if client cert is valid + if(req.client.authorized === true) { + console.log('valid') + } else { + console.error(req.client.authorizationError) + } + res.end() +}) + +server.listen(0, function () { + const tls = { + ca: [ + readFileSync(join(__dirname, 'server-ca-crt.pem'), 'utf8') + ], + key: readFileSync(join(__dirname, 'client-key.pem'), 'utf8'), + cert: readFileSync(join(__dirname, 'client-crt.pem'), 'utf8'), + rejectUnauthorized: false, + servername: 'agent1' + } + const client = new Client(`https://localhost:${server.address().port}`, { + connect: tls + }) + + client.request({ + path: '/', + method: 'GET' + }, (err, { body }) => { + body.on('data', (buf) => {}) + body.on('end', () => { + client.close() + server.close() + }) + }) +}) +``` diff --git a/node_modules/undici/docs/docs/best-practices/mocking-request.md b/node_modules/undici/docs/docs/best-practices/mocking-request.md new file mode 100644 index 0000000000000..695439274449a --- /dev/null +++ b/node_modules/undici/docs/docs/best-practices/mocking-request.md @@ -0,0 +1,136 @@ +# Mocking Request + +Undici has its own mocking [utility](../api/MockAgent.md). It allow us to intercept undici HTTP requests and return mocked values instead. It can be useful for testing purposes. + +Example: + +```js +// bank.mjs +import { request } from 'undici' + +export async function bankTransfer(recipient, amount) { + const { body } = await request('http://localhost:3000/bank-transfer', + { + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient, + amount + }) + } + ) + return await body.json() +} +``` + +And this is what the test file looks like: + +```js +// index.test.mjs +import { strict as assert } from 'assert' +import { MockAgent, setGlobalDispatcher, } from 'undici' +import { bankTransfer } from './bank.mjs' + +const mockAgent = new MockAgent(); + +setGlobalDispatcher(mockAgent); + +// Provide the base url to the request +const mockPool = mockAgent.get('http://localhost:3000'); + +// intercept the request +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient: '1234567890', + amount: '100' + }) +}).reply(200, { + message: 'transaction processed' +}) + +const success = await bankTransfer('1234567890', '100') + +assert.deepEqual(success, { message: 'transaction processed' }) + +// if you dont want to check whether the body or the headers contain the same value +// just remove it from interceptor +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', +}).reply(400, { + message: 'bank account not found' +}) + +const badRequest = await bankTransfer('1234567890', '100') + +assert.deepEqual(badRequest, { message: 'bank account not found' }) +``` + +Explore other MockAgent functionality [here](../api/MockAgent.md) + +## Debug Mock Value + +When the interceptor and the request options are not the same, undici will automatically make a real HTTP request. To prevent real requests from being made, use `mockAgent.disableNetConnect()`: + +```js +const mockAgent = new MockAgent(); + +setGlobalDispatcher(mockAgent); +mockAgent.disableNetConnect() + +// Provide the base url to the request +const mockPool = mockAgent.get('http://localhost:3000'); + +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', +}).reply(200, { + message: 'transaction processed' +}) + +const badRequest = await bankTransfer('1234567890', '100') +// Will throw an error +// MockNotMatchedError: Mock dispatch not matched for path '/bank-transfer': +// subsequent request to origin http://localhost:3000 was not allowed (net.connect disabled) +``` + +## Reply with data based on request + +If the mocked response needs to be dynamically derived from the request parameters, you can provide a function instead of an object to `reply`: + +```js +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient: '1234567890', + amount: '100' + }) +}).reply(200, (opts) => { + // do something with opts + + return { message: 'transaction processed' } +}) +``` + +in this case opts will be + +``` +{ + method: 'POST', + headers: { 'X-TOKEN-SECRET': 'SuperSecretToken' }, + body: '{"recipient":"1234567890","amount":"100"}', + origin: 'http://localhost:3000', + path: '/bank-transfer' +} +``` diff --git a/node_modules/undici/docs/docs/best-practices/proxy.md b/node_modules/undici/docs/docs/best-practices/proxy.md new file mode 100644 index 0000000000000..5764ff38b3c67 --- /dev/null +++ b/node_modules/undici/docs/docs/best-practices/proxy.md @@ -0,0 +1,127 @@ +# Connecting through a proxy + +Connecting through a proxy is possible by: + +- Using [ProxyAgent](../api/ProxyAgent.md). +- Configuring `Client` or `Pool` constructor. + +The proxy url should be passed to the `Client` or `Pool` constructor, while the upstream server url +should be added to every request call in the `path`. +For instance, if you need to send a request to the `/hello` route of your upstream server, +the `path` should be `path: 'http://upstream.server:port/hello?foo=bar'`. + +If you proxy requires basic authentication, you can send it via the `proxy-authorization` header. + +### Connect without authentication + +```js +import { Client } from 'undici' +import { createServer } from 'http' +import { createProxy } from 'proxy' + +const server = await buildServer() +const proxyServer = await buildProxy() + +const serverUrl = `http://localhost:${server.address().port}` +const proxyUrl = `http://localhost:${proxyServer.address().port}` + +server.on('request', (req, res) => { + console.log(req.url) // '/hello?foo=bar' + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ hello: 'world' })) +}) + +const client = new Client(proxyUrl) + +const response = await client.request({ + method: 'GET', + path: serverUrl + '/hello?foo=bar' +}) + +response.body.setEncoding('utf8') +let data = '' +for await (const chunk of response.body) { + data += chunk +} +console.log(response.statusCode) // 200 +console.log(JSON.parse(data)) // { hello: 'world' } + +server.close() +proxyServer.close() +client.close() + +function buildServer () { + return new Promise((resolve, reject) => { + const server = createServer() + server.listen(0, () => resolve(server)) + }) +} + +function buildProxy () { + return new Promise((resolve, reject) => { + const server = createProxy(createServer()) + server.listen(0, () => resolve(server)) + }) +} +``` + +### Connect with authentication + +```js +import { Client } from 'undici' +import { createServer } from 'http' +import { createProxy } from 'proxy' + +const server = await buildServer() +const proxyServer = await buildProxy() + +const serverUrl = `http://localhost:${server.address().port}` +const proxyUrl = `http://localhost:${proxyServer.address().port}` + +proxyServer.authenticate = function (req) { + return req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}` +} + +server.on('request', (req, res) => { + console.log(req.url) // '/hello?foo=bar' + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ hello: 'world' })) +}) + +const client = new Client(proxyUrl) + +const response = await client.request({ + method: 'GET', + path: serverUrl + '/hello?foo=bar', + headers: { + 'proxy-authorization': `Basic ${Buffer.from('user:pass').toString('base64')}` + } +}) + +response.body.setEncoding('utf8') +let data = '' +for await (const chunk of response.body) { + data += chunk +} +console.log(response.statusCode) // 200 +console.log(JSON.parse(data)) // { hello: 'world' } + +server.close() +proxyServer.close() +client.close() + +function buildServer () { + return new Promise((resolve, reject) => { + const server = createServer() + server.listen(0, () => resolve(server)) + }) +} + +function buildProxy () { + return new Promise((resolve, reject) => { + const server = createProxy(createServer()) + server.listen(0, () => resolve(server)) + }) +} +``` + diff --git a/node_modules/undici/docs/docs/best-practices/writing-tests.md b/node_modules/undici/docs/docs/best-practices/writing-tests.md new file mode 100644 index 0000000000000..57549de63572a --- /dev/null +++ b/node_modules/undici/docs/docs/best-practices/writing-tests.md @@ -0,0 +1,20 @@ +# Writing tests + +Undici is tuned for a production use case and its default will keep +a socket open for a few seconds after an HTTP request is completed to +remove the overhead of opening up a new socket. These settings that makes +Undici shine in production are not a good fit for using Undici in automated +tests, as it will result in longer execution times. + +The following are good defaults that will keep the socket open for only 10ms: + +```js +import { request, setGlobalDispatcher, Agent } from 'undici' + +const agent = new Agent({ + keepAliveTimeout: 10, // milliseconds + keepAliveMaxTimeout: 10 // milliseconds +}) + +setGlobalDispatcher(agent) +``` diff --git a/node_modules/undici/index-fetch.js b/node_modules/undici/index-fetch.js new file mode 100644 index 0000000000000..711d7e8a1e4de --- /dev/null +++ b/node_modules/undici/index-fetch.js @@ -0,0 +1,35 @@ +'use strict' + +const { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global') +const EnvHttpProxyAgent = require('./lib/dispatcher/env-http-proxy-agent') +const fetchImpl = require('./lib/web/fetch').fetch + +module.exports.fetch = function fetch (resource, init = undefined) { + return fetchImpl(resource, init).catch((err) => { + if (err && typeof err === 'object') { + Error.captureStackTrace(err) + } + throw err + }) +} +module.exports.FormData = require('./lib/web/fetch/formdata').FormData +module.exports.Headers = require('./lib/web/fetch/headers').Headers +module.exports.Response = require('./lib/web/fetch/response').Response +module.exports.Request = require('./lib/web/fetch/request').Request + +const { CloseEvent, ErrorEvent, MessageEvent, createFastMessageEvent } = require('./lib/web/websocket/events') +module.exports.WebSocket = require('./lib/web/websocket/websocket').WebSocket +module.exports.CloseEvent = CloseEvent +module.exports.ErrorEvent = ErrorEvent +module.exports.MessageEvent = MessageEvent +module.exports.createFastMessageEvent = createFastMessageEvent + +module.exports.EventSource = require('./lib/web/eventsource/eventsource').EventSource + +const api = require('./lib/api') +const Dispatcher = require('./lib/dispatcher/dispatcher') +Object.assign(Dispatcher.prototype, api) +// Expose the fetch implementation to be enabled in Node.js core via a flag +module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent +module.exports.getGlobalDispatcher = getGlobalDispatcher +module.exports.setGlobalDispatcher = setGlobalDispatcher diff --git a/node_modules/undici/index.js b/node_modules/undici/index.js new file mode 100644 index 0000000000000..0c37ed4853b6b --- /dev/null +++ b/node_modules/undici/index.js @@ -0,0 +1,169 @@ +'use strict' + +const Client = require('./lib/dispatcher/client') +const Dispatcher = require('./lib/dispatcher/dispatcher') +const Pool = require('./lib/dispatcher/pool') +const BalancedPool = require('./lib/dispatcher/balanced-pool') +const Agent = require('./lib/dispatcher/agent') +const ProxyAgent = require('./lib/dispatcher/proxy-agent') +const EnvHttpProxyAgent = require('./lib/dispatcher/env-http-proxy-agent') +const RetryAgent = require('./lib/dispatcher/retry-agent') +const errors = require('./lib/core/errors') +const util = require('./lib/core/util') +const { InvalidArgumentError } = errors +const api = require('./lib/api') +const buildConnector = require('./lib/core/connect') +const MockClient = require('./lib/mock/mock-client') +const MockAgent = require('./lib/mock/mock-agent') +const MockPool = require('./lib/mock/mock-pool') +const mockErrors = require('./lib/mock/mock-errors') +const RetryHandler = require('./lib/handler/retry-handler') +const { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global') +const DecoratorHandler = require('./lib/handler/decorator-handler') +const RedirectHandler = require('./lib/handler/redirect-handler') +const createRedirectInterceptor = require('./lib/interceptor/redirect-interceptor') + +Object.assign(Dispatcher.prototype, api) + +module.exports.Dispatcher = Dispatcher +module.exports.Client = Client +module.exports.Pool = Pool +module.exports.BalancedPool = BalancedPool +module.exports.Agent = Agent +module.exports.ProxyAgent = ProxyAgent +module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent +module.exports.RetryAgent = RetryAgent +module.exports.RetryHandler = RetryHandler + +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.createRedirectInterceptor = createRedirectInterceptor +module.exports.interceptors = { + redirect: require('./lib/interceptor/redirect'), + retry: require('./lib/interceptor/retry'), + dump: require('./lib/interceptor/dump'), + dns: require('./lib/interceptor/dns') +} + +module.exports.buildConnector = buildConnector +module.exports.errors = errors +module.exports.util = { + parseHeaders: util.parseHeaders, + headerNameToString: util.headerNameToString +} + +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null + } + + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') + } + + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } + + let path = opts.path + if (!opts.path.startsWith('/')) { + path = `/${path}` + } + + url = new URL(util.parseOrigin(url).origin + path) + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {} + } + + url = util.parseURL(url) + } + + const { agent, dispatcher = getGlobalDispatcher() } = opts + + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') + } + + return fn.call(dispatcher, { + ...opts, + origin: url.origin, + path: url.search ? `${url.pathname}${url.search}` : url.pathname, + method: opts.method || (opts.body ? 'PUT' : 'GET') + }, handler) + } +} + +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher + +const fetchImpl = require('./lib/web/fetch').fetch +module.exports.fetch = async function fetch (init, options = undefined) { + try { + return await fetchImpl(init, options) + } catch (err) { + if (err && typeof err === 'object') { + Error.captureStackTrace(err) + } + + throw err + } +} +module.exports.Headers = require('./lib/web/fetch/headers').Headers +module.exports.Response = require('./lib/web/fetch/response').Response +module.exports.Request = require('./lib/web/fetch/request').Request +module.exports.FormData = require('./lib/web/fetch/formdata').FormData +module.exports.File = globalThis.File ?? require('node:buffer').File +module.exports.FileReader = require('./lib/web/fileapi/filereader').FileReader + +const { setGlobalOrigin, getGlobalOrigin } = require('./lib/web/fetch/global') + +module.exports.setGlobalOrigin = setGlobalOrigin +module.exports.getGlobalOrigin = getGlobalOrigin + +const { CacheStorage } = require('./lib/web/cache/cachestorage') +const { kConstruct } = require('./lib/web/cache/symbols') + +// Cache & CacheStorage are tightly coupled with fetch. Even if it may run +// in an older version of Node, it doesn't have any use without fetch. +module.exports.caches = new CacheStorage(kConstruct) + +const { deleteCookie, getCookies, getSetCookies, setCookie } = require('./lib/web/cookies') + +module.exports.deleteCookie = deleteCookie +module.exports.getCookies = getCookies +module.exports.getSetCookies = getSetCookies +module.exports.setCookie = setCookie + +const { parseMIMEType, serializeAMimeType } = require('./lib/web/fetch/data-url') + +module.exports.parseMIMEType = parseMIMEType +module.exports.serializeAMimeType = serializeAMimeType + +const { CloseEvent, ErrorEvent, MessageEvent } = require('./lib/web/websocket/events') +module.exports.WebSocket = require('./lib/web/websocket/websocket').WebSocket +module.exports.CloseEvent = CloseEvent +module.exports.ErrorEvent = ErrorEvent +module.exports.MessageEvent = MessageEvent + +module.exports.request = makeDispatcher(api.request) +module.exports.stream = makeDispatcher(api.stream) +module.exports.pipeline = makeDispatcher(api.pipeline) +module.exports.connect = makeDispatcher(api.connect) +module.exports.upgrade = makeDispatcher(api.upgrade) + +module.exports.MockClient = MockClient +module.exports.MockPool = MockPool +module.exports.MockAgent = MockAgent +module.exports.mockErrors = mockErrors + +const { EventSource } = require('./lib/web/eventsource/eventsource') + +module.exports.EventSource = EventSource diff --git a/node_modules/undici/lib/api/abort-signal.js b/node_modules/undici/lib/api/abort-signal.js new file mode 100644 index 0000000000000..2afe747d3a107 --- /dev/null +++ b/node_modules/undici/lib/api/abort-signal.js @@ -0,0 +1,57 @@ +const { addAbortListener } = require('../core/util') +const { RequestAbortedError } = require('../core/errors') + +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') + +function abort (self) { + if (self.abort) { + self.abort(self[kSignal]?.reason) + } else { + self.reason = self[kSignal]?.reason ?? new RequestAbortedError() + } + removeSignal(self) +} + +function addSignal (self, signal) { + self.reason = null + + self[kSignal] = null + self[kListener] = null + + if (!signal) { + return + } + + if (signal.aborted) { + abort(self) + return + } + + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } + + addAbortListener(self[kSignal], self[kListener]) +} + +function removeSignal (self) { + if (!self[kSignal]) { + return + } + + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) + } + + self[kSignal] = null + self[kListener] = null +} + +module.exports = { + addSignal, + removeSignal +} diff --git a/node_modules/undici/lib/api/api-connect.js b/node_modules/undici/lib/api/api-connect.js new file mode 100644 index 0000000000000..f9dbbf64fe807 --- /dev/null +++ b/node_modules/undici/lib/api/api-connect.js @@ -0,0 +1,108 @@ +'use strict' + +const assert = require('node:assert') +const { AsyncResource } = require('node:async_hooks') +const { InvalidArgumentError, SocketError } = require('../core/errors') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') + +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_CONNECT') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason) + return + } + + assert(this.callback) + + this.abort = abort + this.context = context + } + + onHeaders () { + throw new SocketError('bad connect', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this + + removeSignal(this) + + this.callback = null + + let headers = rawHeaders + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + } + + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const connectHandler = new ConnectHandler(opts, callback) + this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = connect diff --git a/node_modules/undici/lib/api/api-pipeline.js b/node_modules/undici/lib/api/api-pipeline.js new file mode 100644 index 0000000000000..e64b329496580 --- /dev/null +++ b/node_modules/undici/lib/api/api-pipeline.js @@ -0,0 +1,251 @@ +'use strict' + +const { + Readable, + Duplex, + PassThrough +} = require('node:stream') +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = require('../core/errors') +const util = require('../core/util') +const { AsyncResource } = require('node:async_hooks') +const { addSignal, removeSignal } = require('./abort-signal') +const assert = require('node:assert') + +const kResume = Symbol('resume') + +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) + + this[kResume] = null + } + + _read () { + const { [kResume]: resume } = this + + if (resume) { + this[kResume] = null + resume() + } + } + + _destroy (err, callback) { + this._read() + + callback(err) + } +} + +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } + + _read () { + this[kResume]() + } + + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + callback(err) + } +} + +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } + + const { signal, method, opaque, onInfo, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_PIPELINE') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null + + this.req = new PipelineRequest().on('error', util.nop) + + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this + + if (body?.resume) { + body.resume() + } + }, + write: (chunk, encoding, callback) => { + const { req } = this + + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() + } else { + req[kResume] = callback + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this + + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (abort && err) { + abort() + } + + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) + + removeSignal(this) + + callback(err) + } + }).on('prefinish', () => { + const { req } = this + + // Node < 15 does not call _final in same tick. + req.push(null) + }) + + this.res = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + const { ret, res } = this + + if (this.reason) { + abort(this.reason) + return + } + + assert(!res, 'pipeline cannot be retried') + assert(!ret.destroyed) + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this + + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } + + this.res = new PipelineResponse(resume) + + let body + try { + this.handler = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + body = this.runInAsyncScope(handler, null, { + statusCode, + headers, + opaque, + body: this.res, + context + }) + } catch (err) { + this.res.on('error', util.nop) + throw err + } + + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } + + body + .on('data', (chunk) => { + const { ret, body } = this + + if (!ret.push(chunk) && body.pause) { + body.pause() + } + }) + .on('error', (err) => { + const { ret } = this + + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this + + ret.push(null) + }) + .on('close', () => { + const { ret } = this + + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) + + this.body = body + } + + onData (chunk) { + const { res } = this + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this + res.push(null) + } + + onError (err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) + } +} + +function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler) + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) + } +} + +module.exports = pipeline diff --git a/node_modules/undici/lib/api/api-request.js b/node_modules/undici/lib/api/api-request.js new file mode 100644 index 0000000000000..be17d62877403 --- /dev/null +++ b/node_modules/undici/lib/api/api-request.js @@ -0,0 +1,214 @@ +'use strict' + +const assert = require('node:assert') +const { Readable } = require('./readable') +const { InvalidArgumentError, RequestAbortedError } = require('../core/errors') +const util = require('../core/util') +const { getResolveErrorBodyCallback } = require('./util') +const { AsyncResource } = require('node:async_hooks') + +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.method = method + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.res = null + this.abort = null + this.body = body + this.trailers = {} + this.context = null + this.onInfo = onInfo || null + this.throwOnError = throwOnError + this.highWaterMark = highWaterMark + this.signal = signal + this.reason = null + this.removeAbortListener = null + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + if (this.signal) { + if (this.signal.aborted) { + this.reason = this.signal.reason ?? new RequestAbortedError() + } else { + this.removeAbortListener = util.addAbortListener(this.signal, () => { + this.reason = this.signal.reason ?? new RequestAbortedError() + if (this.res) { + util.destroy(this.res.on('error', util.nop), this.reason) + } else if (this.abort) { + this.abort(this.reason) + } + + if (this.removeAbortListener) { + this.res?.off('close', this.removeAbortListener) + this.removeAbortListener() + this.removeAbortListener = null + } + }) + } + } + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason) + return + } + + assert(this.callback) + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + const contentLength = parsedHeaders['content-length'] + const res = new Readable({ + resume, + abort, + contentType, + contentLength: this.method !== 'HEAD' && contentLength + ? Number(contentLength) + : null, + highWaterMark + }) + + if (this.removeAbortListener) { + res.on('close', this.removeAbortListener) + } + + this.callback = null + this.res = res + if (callback !== null) { + if (this.throwOnError && statusCode >= 400) { + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ) + } else { + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + trailers: this.trailers, + opaque, + body: res, + context + }) + } + } + } + + onData (chunk) { + return this.res.push(chunk) + } + + onComplete (trailers) { + util.parseHeaders(trailers, this.trailers) + this.res.push(null) + } + + onError (err) { + const { res, callback, body, opaque } = this + + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res, err) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + + if (this.removeAbortListener) { + res?.off('close', this.removeAbortListener) + this.removeAbortListener() + this.removeAbortListener = null + } + } +} + +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + this.dispatch(opts, new RequestHandler(opts, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = request +module.exports.RequestHandler = RequestHandler diff --git a/node_modules/undici/lib/api/api-stream.js b/node_modules/undici/lib/api/api-stream.js new file mode 100644 index 0000000000000..fba2266dd7d99 --- /dev/null +++ b/node_modules/undici/lib/api/api-stream.js @@ -0,0 +1,220 @@ +'use strict' + +const assert = require('node:assert') +const { finished, PassThrough } = require('node:stream') +const { InvalidArgumentError, InvalidReturnValueError } = require('../core/errors') +const util = require('../core/util') +const { getResolveErrorBodyCallback } = require('./util') +const { AsyncResource } = require('node:async_hooks') +const { addSignal, removeSignal } = require('./abort-signal') + +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_STREAM') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.factory = factory + this.callback = callback + this.res = null + this.abort = null + this.context = null + this.trailers = null + this.body = body + this.onInfo = onInfo || null + this.throwOnError = throwOnError || false + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason) + return + } + + assert(this.callback) + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback, responseHeaders } = this + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + this.factory = null + + let res + + if (this.throwOnError && statusCode >= 400) { + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + res = new PassThrough() + + this.callback = null + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ) + } else { + if (factory === null) { + return + } + + res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }) + + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } + + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this + + this.res = null + if (err || !res.readable) { + util.destroy(res, err) + } + + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + + if (err) { + abort() + } + }) + } + + res.on('drain', resume) + + this.res = res + + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState?.needDrain + + return needDrain !== true + } + + onData (chunk) { + const { res } = this + + return res ? res.write(chunk) : true + } + + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + if (!res) { + return + } + + this.trailers = util.parseHeaders(trailers) + + res.end() + } + + onError (err) { + const { res, callback, opaque, body } = this + + removeSignal(this) + + this.factory = null + + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + this.dispatch(opts, new StreamHandler(opts, factory, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = stream diff --git a/node_modules/undici/lib/api/api-upgrade.js b/node_modules/undici/lib/api/api-upgrade.js new file mode 100644 index 0000000000000..7effcf21049d7 --- /dev/null +++ b/node_modules/undici/lib/api/api-upgrade.js @@ -0,0 +1,108 @@ +'use strict' + +const { InvalidArgumentError, SocketError } = require('../core/errors') +const { AsyncResource } = require('node:async_hooks') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') +const assert = require('node:assert') + +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_UPGRADE') + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason) + return + } + + assert(this.callback) + + this.abort = abort + this.context = null + } + + onHeaders () { + throw new SocketError('bad upgrade', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + assert(statusCode === 101) + + const { callback, opaque, context } = this + + removeSignal(this) + + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const upgradeHandler = new UpgradeHandler(opts, callback) + this.dispatch({ + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + }, upgradeHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = upgrade diff --git a/node_modules/undici/lib/api/index.js b/node_modules/undici/lib/api/index.js new file mode 100644 index 0000000000000..8983a5e746f5d --- /dev/null +++ b/node_modules/undici/lib/api/index.js @@ -0,0 +1,7 @@ +'use strict' + +module.exports.request = require('./api-request') +module.exports.stream = require('./api-stream') +module.exports.pipeline = require('./api-pipeline') +module.exports.upgrade = require('./api-upgrade') +module.exports.connect = require('./api-connect') diff --git a/node_modules/undici/lib/api/readable.js b/node_modules/undici/lib/api/readable.js new file mode 100644 index 0000000000000..47fbf3e0ef1b5 --- /dev/null +++ b/node_modules/undici/lib/api/readable.js @@ -0,0 +1,385 @@ +// Ported from https://github.com/nodejs/undici/pull/907 + +'use strict' + +const assert = require('node:assert') +const { Readable } = require('node:stream') +const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require('../core/errors') +const util = require('../core/util') +const { ReadableStreamFrom } = require('../core/util') + +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('kAbort') +const kContentType = Symbol('kContentType') +const kContentLength = Symbol('kContentLength') + +const noop = () => {} + +class BodyReadable extends Readable { + constructor ({ + resume, + abort, + contentType = '', + contentLength, + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) + + this._readableState.dataEmitted = false + + this[kAbort] = abort + this[kConsume] = null + this[kBody] = null + this[kContentType] = contentType + this[kContentLength] = contentLength + + // Is stream being consumed through Readable API? + // This is an optimization so that we avoid checking + // for 'data' and 'readable' listeners in the hot path + // inside push(). + this[kReading] = false + } + + destroy (err) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (err) { + this[kAbort]() + } + + return super.destroy(err) + } + + _destroy (err, callback) { + // Workaround for Node "bug". If the stream is destroyed in same + // tick as it is created, then a user who is waiting for a + // promise (i.e micro tick) for installing a 'error' listener will + // never get a chance and will always encounter an unhandled exception. + if (!this[kReading]) { + setImmediate(() => { + callback(err) + }) + } else { + callback(err) + } + } + + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true + } + return super.on(ev, ...args) + } + + addListener (ev, ...args) { + return this.on(ev, ...args) + } + + off (ev, ...args) { + const ret = super.off(ev, ...args) + if (ev === 'data' || ev === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ) + } + return ret + } + + removeListener (ev, ...args) { + return this.off(ev, ...args) + } + + push (chunk) { + if (this[kConsume] && chunk !== null) { + consumePush(this[kConsume], chunk) + return this[kReading] ? super.push(chunk) : true + } + return super.push(chunk) + } + + // https://fetch.spec.whatwg.org/#dom-body-text + async text () { + return consume(this, 'text') + } + + // https://fetch.spec.whatwg.org/#dom-body-json + async json () { + return consume(this, 'json') + } + + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') + } + + // https://fetch.spec.whatwg.org/#dom-body-bytes + async bytes () { + return consume(this, 'bytes') + } + + // https://fetch.spec.whatwg.org/#dom-body-arraybuffer + async arrayBuffer () { + return consume(this, 'arrayBuffer') + } + + // https://fetch.spec.whatwg.org/#dom-body-formdata + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } + + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util.isDisturbed(this) + } + + // https://fetch.spec.whatwg.org/#dom-body-body + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStreamFrom(this) + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader() // Ensure stream is locked. + assert(this[kBody].locked) + } + } + return this[kBody] + } + + async dump (opts) { + let limit = Number.isFinite(opts?.limit) ? opts.limit : 128 * 1024 + const signal = opts?.signal + + if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) { + throw new InvalidArgumentError('signal must be an AbortSignal') + } + + signal?.throwIfAborted() + + if (this._readableState.closeEmitted) { + return null + } + + return await new Promise((resolve, reject) => { + if (this[kContentLength] > limit) { + this.destroy(new AbortError()) + } + + const onAbort = () => { + this.destroy(signal.reason ?? new AbortError()) + } + signal?.addEventListener('abort', onAbort) + + this + .on('close', function () { + signal?.removeEventListener('abort', onAbort) + if (signal?.aborted) { + reject(signal.reason ?? new AbortError()) + } else { + resolve(null) + } + }) + .on('error', noop) + .on('data', function (chunk) { + limit -= chunk.length + if (limit <= 0) { + this.destroy() + } + }) + .resume() + }) + } +} + +// https://streams.spec.whatwg.org/#readablestream-locked +function isLocked (self) { + // Consume is an implicit lock. + return (self[kBody] && self[kBody].locked === true) || self[kConsume] +} + +// https://fetch.spec.whatwg.org/#body-unusable +function isUnusable (self) { + return util.isDisturbed(self) || isLocked(self) +} + +async function consume (stream, type) { + assert(!stream[kConsume]) + + return new Promise((resolve, reject) => { + if (isUnusable(stream)) { + const rState = stream._readableState + if (rState.destroyed && rState.closeEmitted === false) { + stream + .on('error', err => { + reject(err) + }) + .on('close', () => { + reject(new TypeError('unusable')) + }) + } else { + reject(rState.errored ?? new TypeError('unusable')) + } + } else { + queueMicrotask(() => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + } + + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) + } + }) + + consumeStart(stream[kConsume]) + }) + } + }) +} + +function consumeStart (consume) { + if (consume.body === null) { + return + } + + const { _readableState: state } = consume.stream + + if (state.bufferIndex) { + const start = state.bufferIndex + const end = state.buffer.length + for (let n = start; n < end; n++) { + consumePush(consume, state.buffer[n]) + } + } else { + for (const chunk of state.buffer) { + consumePush(consume, chunk) + } + } + + if (state.endEmitted) { + consumeEnd(this[kConsume]) + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume]) + }) + } + + consume.stream.resume() + + while (consume.stream.read() != null) { + // Loop + } +} + +/** + * @param {Buffer[]} chunks + * @param {number} length + */ +function chunksDecode (chunks, length) { + if (chunks.length === 0 || length === 0) { + return '' + } + const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length) + const bufferLength = buffer.length + + // Skip BOM. + const start = + bufferLength > 2 && + buffer[0] === 0xef && + buffer[1] === 0xbb && + buffer[2] === 0xbf + ? 3 + : 0 + return buffer.utf8Slice(start, bufferLength) +} + +/** + * @param {Buffer[]} chunks + * @param {number} length + * @returns {Uint8Array} + */ +function chunksConcat (chunks, length) { + if (chunks.length === 0 || length === 0) { + return new Uint8Array(0) + } + if (chunks.length === 1) { + // fast-path + return new Uint8Array(chunks[0]) + } + const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer) + + let offset = 0 + for (let i = 0; i < chunks.length; ++i) { + const chunk = chunks[i] + buffer.set(chunk, offset) + offset += chunk.length + } + + return buffer +} + +function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume + + try { + if (type === 'text') { + resolve(chunksDecode(body, length)) + } else if (type === 'json') { + resolve(JSON.parse(chunksDecode(body, length))) + } else if (type === 'arrayBuffer') { + resolve(chunksConcat(body, length).buffer) + } else if (type === 'blob') { + resolve(new Blob(body, { type: stream[kContentType] })) + } else if (type === 'bytes') { + resolve(chunksConcat(body, length)) + } + + consumeFinish(consume) + } catch (err) { + stream.destroy(err) + } +} + +function consumePush (consume, chunk) { + consume.length += chunk.length + consume.body.push(chunk) +} + +function consumeFinish (consume, err) { + if (consume.body === null) { + return + } + + if (err) { + consume.reject(err) + } else { + consume.resolve() + } + + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null +} + +module.exports = { Readable: BodyReadable, chunksDecode } diff --git a/node_modules/undici/lib/api/util.js b/node_modules/undici/lib/api/util.js new file mode 100644 index 0000000000000..2f983bf424c70 --- /dev/null +++ b/node_modules/undici/lib/api/util.js @@ -0,0 +1,93 @@ +const assert = require('node:assert') +const { + ResponseStatusCodeError +} = require('../core/errors') + +const { chunksDecode } = require('./readable') +const CHUNK_LIMIT = 128 * 1024 + +async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { + assert(body) + + let chunks = [] + let length = 0 + + try { + for await (const chunk of body) { + chunks.push(chunk) + length += chunk.length + if (length > CHUNK_LIMIT) { + chunks = [] + length = 0 + break + } + } + } catch { + chunks = [] + length = 0 + // Do nothing.... + } + + const message = `Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}` + + if (statusCode === 204 || !contentType || !length) { + queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers))) + return + } + + const stackTraceLimit = Error.stackTraceLimit + Error.stackTraceLimit = 0 + let payload + + try { + if (isContentTypeApplicationJson(contentType)) { + payload = JSON.parse(chunksDecode(chunks, length)) + } else if (isContentTypeText(contentType)) { + payload = chunksDecode(chunks, length) + } + } catch { + // process in a callback to avoid throwing in the microtask queue + } finally { + Error.stackTraceLimit = stackTraceLimit + } + queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers, payload))) +} + +const isContentTypeApplicationJson = (contentType) => { + return ( + contentType.length > 15 && + contentType[11] === '/' && + contentType[0] === 'a' && + contentType[1] === 'p' && + contentType[2] === 'p' && + contentType[3] === 'l' && + contentType[4] === 'i' && + contentType[5] === 'c' && + contentType[6] === 'a' && + contentType[7] === 't' && + contentType[8] === 'i' && + contentType[9] === 'o' && + contentType[10] === 'n' && + contentType[12] === 'j' && + contentType[13] === 's' && + contentType[14] === 'o' && + contentType[15] === 'n' + ) +} + +const isContentTypeText = (contentType) => { + return ( + contentType.length > 4 && + contentType[4] === '/' && + contentType[0] === 't' && + contentType[1] === 'e' && + contentType[2] === 'x' && + contentType[3] === 't' + ) +} + +module.exports = { + getResolveErrorBodyCallback, + isContentTypeApplicationJson, + isContentTypeText +} diff --git a/node_modules/undici/lib/core/connect.js b/node_modules/undici/lib/core/connect.js new file mode 100644 index 0000000000000..8cd8abccc545f --- /dev/null +++ b/node_modules/undici/lib/core/connect.js @@ -0,0 +1,240 @@ +'use strict' + +const net = require('node:net') +const assert = require('node:assert') +const util = require('./util') +const { InvalidArgumentError, ConnectTimeoutError } = require('./errors') +const timers = require('../util/timers') + +function noop () {} + +let tls // include tls conditionally since it is not always available + +// TODO: session re-use does not wait for the first +// connection to resolve the session and might therefore +// resolve the same servername multiple times even when +// re-use is enabled. + +let SessionCache +// FIXME: remove workaround when the Node bug is fixed +// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 +if (global.FinalizationRegistry && !(process.env.NODE_V8_COVERAGE || process.env.UNDICI_NO_FG)) { + SessionCache = class WeakSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + this._sessionRegistry = new global.FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { + return + } + + const ref = this._sessionCache.get(key) + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key) + } + }) + } + + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey) + return ref ? ref.deref() : null + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + this._sessionCache.set(sessionKey, new WeakRef(session)) + this._sessionRegistry.register(session, sessionKey) + } + } +} else { + SessionCache = class SimpleSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + } + + get (sessionKey) { + return this._sessionCache.get(sessionKey) + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + if (this._sessionCache.size >= this._maxCachedSessions) { + // remove the oldest session + const { value: oldestKey } = this._sessionCache.keys().next() + this._sessionCache.delete(oldestKey) + } + + this._sessionCache.set(sessionKey, session) + } + } +} + +function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) { + if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { + throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') + } + + const options = { path: socketPath, ...opts } + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) + timeout = timeout == null ? 10e3 : timeout + allowH2 = allowH2 != null ? allowH2 : false + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket + if (protocol === 'https:') { + if (!tls) { + tls = require('node:tls') + } + servername = servername || options.servername || util.getServerName(host) || null + + const sessionKey = servername || hostname + assert(sessionKey) + + const session = customSession || sessionCache.get(sessionKey) || null + + port = port || 443 + + socket = tls.connect({ + highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... + ...options, + servername, + session, + localAddress, + // TODO(HTTP/2): Add support for h2c + ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], + socket: httpSocket, // upgrade socket connection + port, + host: hostname + }) + + socket + .on('session', function (session) { + // TODO (fix): Can a session become invalid once established? Don't think so? + sessionCache.set(sessionKey, session) + }) + } else { + assert(!httpSocket, 'httpSocket can only be sent on TLS update') + + port = port || 80 + + socket = net.connect({ + highWaterMark: 64 * 1024, // Same as nodejs fs streams. + ...options, + localAddress, + port, + host: hostname + }) + } + + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (options.keepAlive == null || options.keepAlive) { + const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay + socket.setKeepAlive(true, keepAliveInitialDelay) + } + + const clearConnectTimeout = setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port }) + + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + queueMicrotask(clearConnectTimeout) + + if (callback) { + const cb = callback + callback = null + cb(null, this) + } + }) + .on('error', function (err) { + queueMicrotask(clearConnectTimeout) + + if (callback) { + const cb = callback + callback = null + cb(err) + } + }) + + return socket + } +} + +/** + * @param {WeakRef} socketWeakRef + * @param {object} opts + * @param {number} opts.timeout + * @param {string} opts.hostname + * @param {number} opts.port + * @returns {() => void} + */ +const setupConnectTimeout = process.platform === 'win32' + ? (socketWeakRef, opts) => { + if (!opts.timeout) { + return noop + } + + let s1 = null + let s2 = null + const fastTimer = timers.setFastTimeout(() => { + // setImmediate is added to make sure that we prioritize socket error events over timeouts + s1 = setImmediate(() => { + // Windows needs an extra setImmediate probably due to implementation differences in the socket logic + s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts)) + }) + }, opts.timeout) + return () => { + timers.clearFastTimeout(fastTimer) + clearImmediate(s1) + clearImmediate(s2) + } + } + : (socketWeakRef, opts) => { + if (!opts.timeout) { + return noop + } + + let s1 = null + const fastTimer = timers.setFastTimeout(() => { + // setImmediate is added to make sure that we prioritize socket error events over timeouts + s1 = setImmediate(() => { + onConnectTimeout(socketWeakRef.deref(), opts) + }) + }, opts.timeout) + return () => { + timers.clearFastTimeout(fastTimer) + clearImmediate(s1) + } + } + +/** + * @param {net.Socket} socket + * @param {object} opts + * @param {number} opts.timeout + * @param {string} opts.hostname + * @param {number} opts.port + */ +function onConnectTimeout (socket, opts) { + // The socket could be already garbage collected + if (socket == null) { + return + } + + let message = 'Connect Timeout Error' + if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) { + message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},` + } else { + message += ` (attempted address: ${opts.hostname}:${opts.port},` + } + + message += ` timeout: ${opts.timeout}ms)` + + util.destroy(socket, new ConnectTimeoutError(message)) +} + +module.exports = buildConnector diff --git a/node_modules/undici/lib/core/constants.js b/node_modules/undici/lib/core/constants.js new file mode 100644 index 0000000000000..6ec770dd53344 --- /dev/null +++ b/node_modules/undici/lib/core/constants.js @@ -0,0 +1,118 @@ +'use strict' + +/** @type {Record} */ +const headerNameLowerCasedRecord = {} + +// https://developer.mozilla.org/docs/Web/HTTP/Headers +const wellknownHeaderNames = [ + 'Accept', + 'Accept-Encoding', + 'Accept-Language', + 'Accept-Ranges', + 'Access-Control-Allow-Credentials', + 'Access-Control-Allow-Headers', + 'Access-Control-Allow-Methods', + 'Access-Control-Allow-Origin', + 'Access-Control-Expose-Headers', + 'Access-Control-Max-Age', + 'Access-Control-Request-Headers', + 'Access-Control-Request-Method', + 'Age', + 'Allow', + 'Alt-Svc', + 'Alt-Used', + 'Authorization', + 'Cache-Control', + 'Clear-Site-Data', + 'Connection', + 'Content-Disposition', + 'Content-Encoding', + 'Content-Language', + 'Content-Length', + 'Content-Location', + 'Content-Range', + 'Content-Security-Policy', + 'Content-Security-Policy-Report-Only', + 'Content-Type', + 'Cookie', + 'Cross-Origin-Embedder-Policy', + 'Cross-Origin-Opener-Policy', + 'Cross-Origin-Resource-Policy', + 'Date', + 'Device-Memory', + 'Downlink', + 'ECT', + 'ETag', + 'Expect', + 'Expect-CT', + 'Expires', + 'Forwarded', + 'From', + 'Host', + 'If-Match', + 'If-Modified-Since', + 'If-None-Match', + 'If-Range', + 'If-Unmodified-Since', + 'Keep-Alive', + 'Last-Modified', + 'Link', + 'Location', + 'Max-Forwards', + 'Origin', + 'Permissions-Policy', + 'Pragma', + 'Proxy-Authenticate', + 'Proxy-Authorization', + 'RTT', + 'Range', + 'Referer', + 'Referrer-Policy', + 'Refresh', + 'Retry-After', + 'Sec-WebSocket-Accept', + 'Sec-WebSocket-Extensions', + 'Sec-WebSocket-Key', + 'Sec-WebSocket-Protocol', + 'Sec-WebSocket-Version', + 'Server', + 'Server-Timing', + 'Service-Worker-Allowed', + 'Service-Worker-Navigation-Preload', + 'Set-Cookie', + 'SourceMap', + 'Strict-Transport-Security', + 'Supports-Loading-Mode', + 'TE', + 'Timing-Allow-Origin', + 'Trailer', + 'Transfer-Encoding', + 'Upgrade', + 'Upgrade-Insecure-Requests', + 'User-Agent', + 'Vary', + 'Via', + 'WWW-Authenticate', + 'X-Content-Type-Options', + 'X-DNS-Prefetch-Control', + 'X-Frame-Options', + 'X-Permitted-Cross-Domain-Policies', + 'X-Powered-By', + 'X-Requested-With', + 'X-XSS-Protection' +] + +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = wellknownHeaderNames[i] + const lowerCasedKey = key.toLowerCase() + headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = + lowerCasedKey +} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(headerNameLowerCasedRecord, null) + +module.exports = { + wellknownHeaderNames, + headerNameLowerCasedRecord +} diff --git a/node_modules/undici/lib/core/diagnostics.js b/node_modules/undici/lib/core/diagnostics.js new file mode 100644 index 0000000000000..e1af3db611270 --- /dev/null +++ b/node_modules/undici/lib/core/diagnostics.js @@ -0,0 +1,202 @@ +'use strict' +const diagnosticsChannel = require('node:diagnostics_channel') +const util = require('node:util') + +const undiciDebugLog = util.debuglog('undici') +const fetchDebuglog = util.debuglog('fetch') +const websocketDebuglog = util.debuglog('websocket') +let isClientSet = false +const channels = { + // Client + beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'), + connected: diagnosticsChannel.channel('undici:client:connected'), + connectError: diagnosticsChannel.channel('undici:client:connectError'), + sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'), + // Request + create: diagnosticsChannel.channel('undici:request:create'), + bodySent: diagnosticsChannel.channel('undici:request:bodySent'), + headers: diagnosticsChannel.channel('undici:request:headers'), + trailers: diagnosticsChannel.channel('undici:request:trailers'), + error: diagnosticsChannel.channel('undici:request:error'), + // WebSocket + open: diagnosticsChannel.channel('undici:websocket:open'), + close: diagnosticsChannel.channel('undici:websocket:close'), + socketError: diagnosticsChannel.channel('undici:websocket:socket_error'), + ping: diagnosticsChannel.channel('undici:websocket:ping'), + pong: diagnosticsChannel.channel('undici:websocket:pong') +} + +if (undiciDebugLog.enabled || fetchDebuglog.enabled) { + const debuglog = fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog + + // Track all Client events + diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => { + const { + connectParams: { version, protocol, port, host } + } = evt + debuglog( + 'connecting to %s using %s%s', + `${host}${port ? `:${port}` : ''}`, + protocol, + version + ) + }) + + diagnosticsChannel.channel('undici:client:connected').subscribe(evt => { + const { + connectParams: { version, protocol, port, host } + } = evt + debuglog( + 'connected to %s using %s%s', + `${host}${port ? `:${port}` : ''}`, + protocol, + version + ) + }) + + diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => { + const { + connectParams: { version, protocol, port, host }, + error + } = evt + debuglog( + 'connection to %s using %s%s errored - %s', + `${host}${port ? `:${port}` : ''}`, + protocol, + version, + error.message + ) + }) + + diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => { + const { + request: { method, path, origin } + } = evt + debuglog('sending request to %s %s/%s', method, origin, path) + }) + + // Track Request events + diagnosticsChannel.channel('undici:request:headers').subscribe(evt => { + const { + request: { method, path, origin }, + response: { statusCode } + } = evt + debuglog( + 'received response to %s %s/%s - HTTP %d', + method, + origin, + path, + statusCode + ) + }) + + diagnosticsChannel.channel('undici:request:trailers').subscribe(evt => { + const { + request: { method, path, origin } + } = evt + debuglog('trailers received from %s %s/%s', method, origin, path) + }) + + diagnosticsChannel.channel('undici:request:error').subscribe(evt => { + const { + request: { method, path, origin }, + error + } = evt + debuglog( + 'request to %s %s/%s errored - %s', + method, + origin, + path, + error.message + ) + }) + + isClientSet = true +} + +if (websocketDebuglog.enabled) { + if (!isClientSet) { + const debuglog = undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog + diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => { + const { + connectParams: { version, protocol, port, host } + } = evt + debuglog( + 'connecting to %s%s using %s%s', + host, + port ? `:${port}` : '', + protocol, + version + ) + }) + + diagnosticsChannel.channel('undici:client:connected').subscribe(evt => { + const { + connectParams: { version, protocol, port, host } + } = evt + debuglog( + 'connected to %s%s using %s%s', + host, + port ? `:${port}` : '', + protocol, + version + ) + }) + + diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => { + const { + connectParams: { version, protocol, port, host }, + error + } = evt + debuglog( + 'connection to %s%s using %s%s errored - %s', + host, + port ? `:${port}` : '', + protocol, + version, + error.message + ) + }) + + diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => { + const { + request: { method, path, origin } + } = evt + debuglog('sending request to %s %s/%s', method, origin, path) + }) + } + + // Track all WebSocket events + diagnosticsChannel.channel('undici:websocket:open').subscribe(evt => { + const { + address: { address, port } + } = evt + websocketDebuglog('connection opened %s%s', address, port ? `:${port}` : '') + }) + + diagnosticsChannel.channel('undici:websocket:close').subscribe(evt => { + const { websocket, code, reason } = evt + websocketDebuglog( + 'closed connection to %s - %s %s', + websocket.url, + code, + reason + ) + }) + + diagnosticsChannel.channel('undici:websocket:socket_error').subscribe(err => { + websocketDebuglog('connection errored - %s', err.message) + }) + + diagnosticsChannel.channel('undici:websocket:ping').subscribe(evt => { + websocketDebuglog('ping received') + }) + + diagnosticsChannel.channel('undici:websocket:pong').subscribe(evt => { + websocketDebuglog('pong received') + }) +} + +module.exports = { + channels +} diff --git a/node_modules/undici/lib/core/errors.js b/node_modules/undici/lib/core/errors.js new file mode 100644 index 0000000000000..202880132dbb3 --- /dev/null +++ b/node_modules/undici/lib/core/errors.js @@ -0,0 +1,425 @@ +'use strict' + +const kUndiciError = Symbol.for('undici.error.UND_ERR') +class UndiciError extends Error { + constructor (message) { + super(message) + this.name = 'UndiciError' + this.code = 'UND_ERR' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kUndiciError] === true + } + + [kUndiciError] = true +} + +const kConnectTimeoutError = Symbol.for('undici.error.UND_ERR_CONNECT_TIMEOUT') +class ConnectTimeoutError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ConnectTimeoutError' + this.message = message || 'Connect Timeout Error' + this.code = 'UND_ERR_CONNECT_TIMEOUT' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kConnectTimeoutError] === true + } + + [kConnectTimeoutError] = true +} + +const kHeadersTimeoutError = Symbol.for('undici.error.UND_ERR_HEADERS_TIMEOUT') +class HeadersTimeoutError extends UndiciError { + constructor (message) { + super(message) + this.name = 'HeadersTimeoutError' + this.message = message || 'Headers Timeout Error' + this.code = 'UND_ERR_HEADERS_TIMEOUT' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kHeadersTimeoutError] === true + } + + [kHeadersTimeoutError] = true +} + +const kHeadersOverflowError = Symbol.for('undici.error.UND_ERR_HEADERS_OVERFLOW') +class HeadersOverflowError extends UndiciError { + constructor (message) { + super(message) + this.name = 'HeadersOverflowError' + this.message = message || 'Headers Overflow Error' + this.code = 'UND_ERR_HEADERS_OVERFLOW' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kHeadersOverflowError] === true + } + + [kHeadersOverflowError] = true +} + +const kBodyTimeoutError = Symbol.for('undici.error.UND_ERR_BODY_TIMEOUT') +class BodyTimeoutError extends UndiciError { + constructor (message) { + super(message) + this.name = 'BodyTimeoutError' + this.message = message || 'Body Timeout Error' + this.code = 'UND_ERR_BODY_TIMEOUT' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kBodyTimeoutError] === true + } + + [kBodyTimeoutError] = true +} + +const kResponseStatusCodeError = Symbol.for('undici.error.UND_ERR_RESPONSE_STATUS_CODE') +class ResponseStatusCodeError extends UndiciError { + constructor (message, statusCode, headers, body) { + super(message) + this.name = 'ResponseStatusCodeError' + this.message = message || 'Response Status Code Error' + this.code = 'UND_ERR_RESPONSE_STATUS_CODE' + this.body = body + this.status = statusCode + this.statusCode = statusCode + this.headers = headers + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseStatusCodeError] === true + } + + [kResponseStatusCodeError] = true +} + +const kInvalidArgumentError = Symbol.for('undici.error.UND_ERR_INVALID_ARG') +class InvalidArgumentError extends UndiciError { + constructor (message) { + super(message) + this.name = 'InvalidArgumentError' + this.message = message || 'Invalid Argument Error' + this.code = 'UND_ERR_INVALID_ARG' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kInvalidArgumentError] === true + } + + [kInvalidArgumentError] = true +} + +const kInvalidReturnValueError = Symbol.for('undici.error.UND_ERR_INVALID_RETURN_VALUE') +class InvalidReturnValueError extends UndiciError { + constructor (message) { + super(message) + this.name = 'InvalidReturnValueError' + this.message = message || 'Invalid Return Value Error' + this.code = 'UND_ERR_INVALID_RETURN_VALUE' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kInvalidReturnValueError] === true + } + + [kInvalidReturnValueError] = true +} + +const kAbortError = Symbol.for('undici.error.UND_ERR_ABORT') +class AbortError extends UndiciError { + constructor (message) { + super(message) + this.name = 'AbortError' + this.message = message || 'The operation was aborted' + this.code = 'UND_ERR_ABORT' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kAbortError] === true + } + + [kAbortError] = true +} + +const kRequestAbortedError = Symbol.for('undici.error.UND_ERR_ABORTED') +class RequestAbortedError extends AbortError { + constructor (message) { + super(message) + this.name = 'AbortError' + this.message = message || 'Request aborted' + this.code = 'UND_ERR_ABORTED' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kRequestAbortedError] === true + } + + [kRequestAbortedError] = true +} + +const kInformationalError = Symbol.for('undici.error.UND_ERR_INFO') +class InformationalError extends UndiciError { + constructor (message) { + super(message) + this.name = 'InformationalError' + this.message = message || 'Request information' + this.code = 'UND_ERR_INFO' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kInformationalError] === true + } + + [kInformationalError] = true +} + +const kRequestContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH') +class RequestContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + this.name = 'RequestContentLengthMismatchError' + this.message = message || 'Request body length does not match content-length header' + this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kRequestContentLengthMismatchError] === true + } + + [kRequestContentLengthMismatchError] = true +} + +const kResponseContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH') +class ResponseContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ResponseContentLengthMismatchError' + this.message = message || 'Response body length does not match content-length header' + this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseContentLengthMismatchError] === true + } + + [kResponseContentLengthMismatchError] = true +} + +const kClientDestroyedError = Symbol.for('undici.error.UND_ERR_DESTROYED') +class ClientDestroyedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ClientDestroyedError' + this.message = message || 'The client is destroyed' + this.code = 'UND_ERR_DESTROYED' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kClientDestroyedError] === true + } + + [kClientDestroyedError] = true +} + +const kClientClosedError = Symbol.for('undici.error.UND_ERR_CLOSED') +class ClientClosedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ClientClosedError' + this.message = message || 'The client is closed' + this.code = 'UND_ERR_CLOSED' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kClientClosedError] === true + } + + [kClientClosedError] = true +} + +const kSocketError = Symbol.for('undici.error.UND_ERR_SOCKET') +class SocketError extends UndiciError { + constructor (message, socket) { + super(message) + this.name = 'SocketError' + this.message = message || 'Socket error' + this.code = 'UND_ERR_SOCKET' + this.socket = socket + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kSocketError] === true + } + + [kSocketError] = true +} + +const kNotSupportedError = Symbol.for('undici.error.UND_ERR_NOT_SUPPORTED') +class NotSupportedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'NotSupportedError' + this.message = message || 'Not supported error' + this.code = 'UND_ERR_NOT_SUPPORTED' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kNotSupportedError] === true + } + + [kNotSupportedError] = true +} + +const kBalancedPoolMissingUpstreamError = Symbol.for('undici.error.UND_ERR_BPL_MISSING_UPSTREAM') +class BalancedPoolMissingUpstreamError extends UndiciError { + constructor (message) { + super(message) + this.name = 'MissingUpstreamError' + this.message = message || 'No upstream has been added to the BalancedPool' + this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kBalancedPoolMissingUpstreamError] === true + } + + [kBalancedPoolMissingUpstreamError] = true +} + +const kHTTPParserError = Symbol.for('undici.error.UND_ERR_HTTP_PARSER') +class HTTPParserError extends Error { + constructor (message, code, data) { + super(message) + this.name = 'HTTPParserError' + this.code = code ? `HPE_${code}` : undefined + this.data = data ? data.toString() : undefined + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kHTTPParserError] === true + } + + [kHTTPParserError] = true +} + +const kResponseExceededMaxSizeError = Symbol.for('undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE') +class ResponseExceededMaxSizeError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ResponseExceededMaxSizeError' + this.message = message || 'Response content exceeded max size' + this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseExceededMaxSizeError] === true + } + + [kResponseExceededMaxSizeError] = true +} + +const kRequestRetryError = Symbol.for('undici.error.UND_ERR_REQ_RETRY') +class RequestRetryError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message) + this.name = 'RequestRetryError' + this.message = message || 'Request retry error' + this.code = 'UND_ERR_REQ_RETRY' + this.statusCode = code + this.data = data + this.headers = headers + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kRequestRetryError] === true + } + + [kRequestRetryError] = true +} + +const kResponseError = Symbol.for('undici.error.UND_ERR_RESPONSE') +class ResponseError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message) + this.name = 'ResponseError' + this.message = message || 'Response error' + this.code = 'UND_ERR_RESPONSE' + this.statusCode = code + this.data = data + this.headers = headers + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseError] === true + } + + [kResponseError] = true +} + +const kSecureProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_TLS') +class SecureProxyConnectionError extends UndiciError { + constructor (cause, message, options) { + super(message, { cause, ...(options ?? {}) }) + this.name = 'SecureProxyConnectionError' + this.message = message || 'Secure Proxy Connection failed' + this.code = 'UND_ERR_PRX_TLS' + this.cause = cause + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kSecureProxyConnectionError] === true + } + + [kSecureProxyConnectionError] = true +} + +const kMessageSizeExceededError = Symbol.for('undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED') +class MessageSizeExceededError extends UndiciError { + constructor (message) { + super(message) + this.name = 'MessageSizeExceededError' + this.message = message || 'Max decompressed message size exceeded' + this.code = 'UND_ERR_WS_MESSAGE_SIZE_EXCEEDED' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kMessageSizeExceededError] === true + } + + get [kMessageSizeExceededError] () { + return true + } +} + +module.exports = { + AbortError, + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + ResponseStatusCodeError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError, + RequestRetryError, + ResponseError, + SecureProxyConnectionError, + MessageSizeExceededError +} diff --git a/node_modules/undici/lib/core/request.js b/node_modules/undici/lib/core/request.js new file mode 100644 index 0000000000000..4da60667ec290 --- /dev/null +++ b/node_modules/undici/lib/core/request.js @@ -0,0 +1,405 @@ +'use strict' + +const { + InvalidArgumentError, + NotSupportedError +} = require('./errors') +const assert = require('node:assert') +const { + isValidHTTPToken, + isValidHeaderValue, + isStream, + destroy, + isBuffer, + isFormDataLike, + isIterable, + isBlobLike, + buildURL, + validateHandler, + getServerName, + normalizedMethodRecords +} = require('./util') +const { channels } = require('./diagnostics.js') +const { headerNameLowerCasedRecord } = require('./constants') + +// Verifies that a given path is valid does not contain control chars \x00 to \x20 +const invalidPathRegex = /[^\u0021-\u00ff]/ + +const kHandler = Symbol('handler') + +class Request { + constructor (origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + throwOnError, + expectContinue, + servername + }, handler) { + if (typeof path !== 'string') { + throw new InvalidArgumentError('path must be a string') + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { + throw new InvalidArgumentError('path must be an absolute URL or start with a slash') + } else if (invalidPathRegex.test(path)) { + throw new InvalidArgumentError('invalid request path') + } + + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) { + throw new InvalidArgumentError('invalid request method') + } + + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') + } + + if (upgrade && !isValidHeaderValue(upgrade)) { + throw new InvalidArgumentError('invalid upgrade header') + } + + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } + + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } + + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') + } + + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') + } + + this.headersTimeout = headersTimeout + + this.bodyTimeout = bodyTimeout + + this.throwOnError = throwOnError === true + + this.method = method + + this.abort = null + + if (body == null) { + this.body = null + } else if (isStream(body)) { + this.body = body + + const rState = this.body._readableState + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy () { + destroy(this) + } + this.body.on('end', this.endHandler) + } + + this.errorHandler = err => { + if (this.abort) { + this.abort(err) + } else { + this.error = err + } + } + this.body.on('error', this.errorHandler) + } else if (isBuffer(body)) { + this.body = body.byteLength ? body : null + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null + } else if (typeof body === 'string') { + this.body = body.length ? Buffer.from(body) : null + } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) { + this.body = body + } else { + throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + } + + this.completed = false + + this.aborted = false + + this.upgrade = upgrade || null + + this.path = query ? buildURL(path, query) : path + + this.origin = origin + + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent + + this.blocking = blocking == null ? false : blocking + + this.reset = reset == null ? null : reset + + this.host = null + + this.contentLength = null + + this.contentType = null + + this.headers = [] + + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]) + } + } else if (headers && typeof headers === 'object') { + if (headers[Symbol.iterator]) { + for (const header of headers) { + if (!Array.isArray(header) || header.length !== 2) { + throw new InvalidArgumentError('headers must be in key-value pair format') + } + processHeader(this, header[0], header[1]) + } + } else { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; ++i) { + processHeader(this, keys[i], headers[keys[i]]) + } + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } + + validateHandler(handler, method, upgrade) + + this.servername = servername || getServerName(this.host) + + this[kHandler] = handler + + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) + } + } + + onBodySent (chunk) { + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk) + } catch (err) { + this.abort(err) + } + } + } + + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) + } + + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent() + } catch (err) { + this.abort(err) + } + } + } + + onConnect (abort) { + assert(!this.aborted) + assert(!this.completed) + + if (this.error) { + abort(this.error) + } else { + this.abort = abort + return this[kHandler].onConnect(abort) + } + } + + onResponseStarted () { + return this[kHandler].onResponseStarted?.() + } + + onHeaders (statusCode, headers, resume, statusText) { + assert(!this.aborted) + assert(!this.completed) + + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } + + try { + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } catch (err) { + this.abort(err) + } + } + + onData (chunk) { + assert(!this.aborted) + assert(!this.completed) + + try { + return this[kHandler].onData(chunk) + } catch (err) { + this.abort(err) + return false + } + } + + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted) + assert(!this.completed) + + return this[kHandler].onUpgrade(statusCode, headers, socket) + } + + onComplete (trailers) { + this.onFinally() + + assert(!this.aborted) + + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } + + try { + return this[kHandler].onComplete(trailers) + } catch (err) { + // TODO (fix): This might be a bad idea? + this.onError(err) + } + } + + onError (error) { + this.onFinally() + + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } + + if (this.aborted) { + return + } + this.aborted = true + + return this[kHandler].onError(error) + } + + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler) + this.errorHandler = null + } + + if (this.endHandler) { + this.body.off('end', this.endHandler) + this.endHandler = null + } + } + + addHeader (key, value) { + processHeader(this, key, value) + return this + } +} + +function processHeader (request, key, val) { + if (val && (typeof val === 'object' && !Array.isArray(val))) { + throw new InvalidArgumentError(`invalid ${key} header`) + } else if (val === undefined) { + return + } + + let headerName = headerNameLowerCasedRecord[key] + + if (headerName === undefined) { + headerName = key.toLowerCase() + if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) { + throw new InvalidArgumentError('invalid header key') + } + } + + if (Array.isArray(val)) { + const arr = [] + for (let i = 0; i < val.length; i++) { + if (typeof val[i] === 'string') { + if (!isValidHeaderValue(val[i])) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + arr.push(val[i]) + } else if (val[i] === null) { + arr.push('') + } else if (typeof val[i] === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) + } else { + arr.push(`${val[i]}`) + } + } + val = arr + } else if (typeof val === 'string') { + if (!isValidHeaderValue(val)) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + } else if (val === null) { + val = '' + } else { + val = `${val}` + } + + if (headerName === 'host') { + if (request.host !== null) { + throw new InvalidArgumentError('duplicate host header') + } + if (typeof val !== 'string') { + throw new InvalidArgumentError('invalid host header') + } + // Consumed by Client + request.host = val + } else if (headerName === 'content-length') { + if (request.contentLength !== null) { + throw new InvalidArgumentError('duplicate content-length header') + } + request.contentLength = parseInt(val, 10) + if (!Number.isFinite(request.contentLength)) { + throw new InvalidArgumentError('invalid content-length header') + } + } else if (request.contentType === null && headerName === 'content-type') { + request.contentType = val + request.headers.push(key, val) + } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') { + throw new InvalidArgumentError(`invalid ${headerName} header`) + } else if (headerName === 'connection') { + const value = typeof val === 'string' ? val.toLowerCase() : null + if (value !== 'close' && value !== 'keep-alive') { + throw new InvalidArgumentError('invalid connection header') + } + + if (value === 'close') { + request.reset = true + } + } else if (headerName === 'expect') { + throw new NotSupportedError('expect header not supported') + } else { + request.headers.push(key, val) + } +} + +module.exports = Request diff --git a/node_modules/undici/lib/core/symbols.js b/node_modules/undici/lib/core/symbols.js new file mode 100644 index 0000000000000..c8ba5dd8ec596 --- /dev/null +++ b/node_modules/undici/lib/core/symbols.js @@ -0,0 +1,67 @@ +module.exports = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kBody: Symbol('abstracted request body'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kResume: Symbol('resume'), + kOnError: Symbol('on error'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelining'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kInterceptors: Symbol('dispatch interceptors'), + kMaxResponseSize: Symbol('max response size'), + kHTTP2Session: Symbol('http2Session'), + kHTTP2SessionState: Symbol('http2Session state'), + kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), + kConstruct: Symbol('constructable'), + kListeners: Symbol('listeners'), + kHTTPContext: Symbol('http context'), + kMaxConcurrentStreams: Symbol('max concurrent streams'), + kNoProxyAgent: Symbol('no proxy agent'), + kHttpProxyAgent: Symbol('http proxy agent'), + kHttpsProxyAgent: Symbol('https proxy agent') +} diff --git a/node_modules/undici/lib/core/tree.js b/node_modules/undici/lib/core/tree.js new file mode 100644 index 0000000000000..17dfca4cc4e38 --- /dev/null +++ b/node_modules/undici/lib/core/tree.js @@ -0,0 +1,152 @@ +'use strict' + +const { + wellknownHeaderNames, + headerNameLowerCasedRecord +} = require('./constants') + +class TstNode { + /** @type {any} */ + value = null + /** @type {null | TstNode} */ + left = null + /** @type {null | TstNode} */ + middle = null + /** @type {null | TstNode} */ + right = null + /** @type {number} */ + code + /** + * @param {string} key + * @param {any} value + * @param {number} index + */ + constructor (key, value, index) { + if (index === undefined || index >= key.length) { + throw new TypeError('Unreachable') + } + const code = this.code = key.charCodeAt(index) + // check code is ascii string + if (code > 0x7F) { + throw new TypeError('key must be ascii string') + } + if (key.length !== ++index) { + this.middle = new TstNode(key, value, index) + } else { + this.value = value + } + } + + /** + * @param {string} key + * @param {any} value + */ + add (key, value) { + const length = key.length + if (length === 0) { + throw new TypeError('Unreachable') + } + let index = 0 + let node = this + while (true) { + const code = key.charCodeAt(index) + // check code is ascii string + if (code > 0x7F) { + throw new TypeError('key must be ascii string') + } + if (node.code === code) { + if (length === ++index) { + node.value = value + break + } else if (node.middle !== null) { + node = node.middle + } else { + node.middle = new TstNode(key, value, index) + break + } + } else if (node.code < code) { + if (node.left !== null) { + node = node.left + } else { + node.left = new TstNode(key, value, index) + break + } + } else if (node.right !== null) { + node = node.right + } else { + node.right = new TstNode(key, value, index) + break + } + } + } + + /** + * @param {Uint8Array} key + * @return {TstNode | null} + */ + search (key) { + const keylength = key.length + let index = 0 + let node = this + while (node !== null && index < keylength) { + let code = key[index] + // A-Z + // First check if it is bigger than 0x5a. + // Lowercase letters have higher char codes than uppercase ones. + // Also we assume that headers will mostly contain lowercase characters. + if (code <= 0x5a && code >= 0x41) { + // Lowercase for uppercase. + code |= 32 + } + while (node !== null) { + if (code === node.code) { + if (keylength === ++index) { + // Returns Node since it is the last key. + return node + } + node = node.middle + break + } + node = node.code < code ? node.left : node.right + } + } + return null + } +} + +class TernarySearchTree { + /** @type {TstNode | null} */ + node = null + + /** + * @param {string} key + * @param {any} value + * */ + insert (key, value) { + if (this.node === null) { + this.node = new TstNode(key, value, 0) + } else { + this.node.add(key, value) + } + } + + /** + * @param {Uint8Array} key + * @return {any} + */ + lookup (key) { + return this.node?.search(key)?.value ?? null + } +} + +const tree = new TernarySearchTree() + +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]] + tree.insert(key, key) +} + +module.exports = { + TernarySearchTree, + tree +} diff --git a/node_modules/undici/lib/core/util.js b/node_modules/undici/lib/core/util.js new file mode 100644 index 0000000000000..9ee7ec23c5224 --- /dev/null +++ b/node_modules/undici/lib/core/util.js @@ -0,0 +1,719 @@ +'use strict' + +const assert = require('node:assert') +const { kDestroyed, kBodyUsed, kListeners, kBody } = require('./symbols') +const { IncomingMessage } = require('node:http') +const stream = require('node:stream') +const net = require('node:net') +const { Blob } = require('node:buffer') +const nodeUtil = require('node:util') +const { stringify } = require('node:querystring') +const { EventEmitter: EE } = require('node:events') +const { InvalidArgumentError } = require('./errors') +const { headerNameLowerCasedRecord } = require('./constants') +const { tree } = require('./tree') + +const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) + +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false + } + + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] + } +} + +function wrapRequestBody (body) { + if (isStream(body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (bodyLength(body) === 0) { + body + .on('data', function () { + assert(false) + }) + } + + if (typeof body.readableDidRead !== 'boolean') { + body[kBodyUsed] = false + EE.prototype.on.call(body, 'data', function () { + this[kBodyUsed] = true + }) + } + + return body + } else if (body && typeof body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + return new BodyAsyncIterable(body) + } else if ( + body && + typeof body !== 'string' && + !ArrayBuffer.isView(body) && + isIterable(body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + return new BodyAsyncIterable(body) + } else { + return body + } +} + +function nop () {} + +function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' +} + +// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) +function isBlobLike (object) { + if (object === null) { + return false + } else if (object instanceof Blob) { + return true + } else if (typeof object !== 'object') { + return false + } else { + const sTag = object[Symbol.toStringTag] + + return (sTag === 'Blob' || sTag === 'File') && ( + ('stream' in object && typeof object.stream === 'function') || + ('arrayBuffer' in object && typeof object.arrayBuffer === 'function') + ) + } +} + +function buildURL (url, queryParams) { + if (url.includes('?') || url.includes('#')) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') + } + + const stringified = stringify(queryParams) + + if (stringified) { + url += '?' + stringified + } + + return url +} + +function isValidPort (port) { + const value = parseInt(port, 10) + return ( + value === Number(port) && + value >= 0 && + value <= 65535 + ) +} + +function isHttpOrHttpsPrefixed (value) { + return ( + value != null && + value[0] === 'h' && + value[1] === 't' && + value[2] === 't' && + value[3] === 'p' && + ( + value[4] === ':' || + ( + value[4] === 's' && + value[5] === ':' + ) + ) + ) +} + +function parseURL (url) { + if (typeof url === 'string') { + url = new URL(url) + + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url + } + + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') + } + + if (!(url instanceof URL)) { + if (url.port != null && url.port !== '' && isValidPort(url.port) === false) { + throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') + } + + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') + } + + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') + } + + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') + } + + if (url.origin != null && typeof url.origin !== 'string') { + throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') + } + + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + const port = url.port != null + ? url.port + : (url.protocol === 'https:' ? 443 : 80) + let origin = url.origin != null + ? url.origin + : `${url.protocol || ''}//${url.hostname || ''}:${port}` + let path = url.path != null + ? url.path + : `${url.pathname || ''}${url.search || ''}` + + if (origin[origin.length - 1] === '/') { + origin = origin.slice(0, origin.length - 1) + } + + if (path && path[0] !== '/') { + path = `/${path}` + } + // new URL(path, origin) is unsafe when `path` contains an absolute URL + // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: + // If first parameter is a relative URL, second param is required, and will be used as the base URL. + // If first parameter is an absolute URL, a given second param will be ignored. + return new URL(`${origin}${path}`) + } + + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url +} + +function parseOrigin (url) { + url = parseURL(url) + + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') + } + + return url +} + +function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']') + + assert(idx !== -1) + return host.substring(1, idx) + } + + const idx = host.indexOf(':') + if (idx === -1) return host + + return host.substring(0, idx) +} + +// IP addresses are not valid server names per RFC6066 +// > Currently, the only server names supported are DNS hostnames +function getServerName (host) { + if (!host) { + return null + } + + assert(typeof host === 'string') + + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' + } + + return servername +} + +function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) +} + +function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') +} + +function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) +} + +function bodyLength (body) { + if (body == null) { + return 0 + } else if (isStream(body)) { + const state = body._readableState + return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) + ? state.length + : null + } else if (isBlobLike(body)) { + return body.size != null ? body.size : null + } else if (isBuffer(body)) { + return body.byteLength + } + + return null +} + +function isDestroyed (body) { + return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body))) +} + +function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return + } + + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null + } + + stream.destroy(err) + } else if (err) { + queueMicrotask(() => { + stream.emit('error', err) + }) + } + + if (stream.destroyed !== true) { + stream[kDestroyed] = true + } +} + +const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ +function parseKeepAliveTimeout (val) { + const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) + return m ? parseInt(m[1], 10) * 1000 : null +} + +/** + * Retrieves a header name and returns its lowercase value. + * @param {string | Buffer} value Header name + * @returns {string} + */ +function headerNameToString (value) { + return typeof value === 'string' + ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() + : tree.lookup(value) ?? value.toString('latin1').toLowerCase() +} + +/** + * Receive the buffer as a string and return its lowercase value. + * @param {Buffer} value Header name + * @returns {string} + */ +function bufferToLowerCasedHeaderName (value) { + return tree.lookup(value) ?? value.toString('latin1').toLowerCase() +} + +/** + * @param {Record | (Buffer | string | (Buffer | string)[])[]} headers + * @param {Record} [obj] + * @returns {Record} + */ +function parseHeaders (headers, obj) { + if (obj === undefined) obj = {} + for (let i = 0; i < headers.length; i += 2) { + const key = headerNameToString(headers[i]) + let val = obj[key] + + if (val) { + if (typeof val === 'string') { + val = [val] + obj[key] = val + } + val.push(headers[i + 1].toString('utf8')) + } else { + const headersValue = headers[i + 1] + if (typeof headersValue === 'string') { + obj[key] = headersValue + } else { + obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('utf8')) : headersValue.toString('utf8') + } + } + } + + // See https://github.com/nodejs/node/pull/46528 + if ('content-length' in obj && 'content-disposition' in obj) { + obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') + } + + return obj +} + +function parseRawHeaders (headers) { + const len = headers.length + const ret = new Array(len) + + let hasContentLength = false + let contentDispositionIdx = -1 + let key + let val + let kLen = 0 + + for (let n = 0; n < headers.length; n += 2) { + key = headers[n] + val = headers[n + 1] + + typeof key !== 'string' && (key = key.toString()) + typeof val !== 'string' && (val = val.toString('utf8')) + + kLen = key.length + if (kLen === 14 && key[7] === '-' && (key === 'content-length' || key.toLowerCase() === 'content-length')) { + hasContentLength = true + } else if (kLen === 19 && key[7] === '-' && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { + contentDispositionIdx = n + 1 + } + ret[n] = key + ret[n + 1] = val + } + + // See https://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') + } + + return ret +} + +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +} + +function validateHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') + } + + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') + } + + if (upgrade || method === 'CONNECT') { + if (typeof handler.onUpgrade !== 'function') { + throw new InvalidArgumentError('invalid onUpgrade method') + } + } else { + if (typeof handler.onHeaders !== 'function') { + throw new InvalidArgumentError('invalid onHeaders method') + } + + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') + } + + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError('invalid onComplete method') + } + } +} + +// A body is disturbed if it has been read from and it cannot +// be re-used without losing state or data. +function isDisturbed (body) { + // TODO (fix): Why is body[kBodyUsed] needed? + return !!(body && (stream.isDisturbed(body) || body[kBodyUsed])) +} + +function isErrored (body) { + return !!(body && stream.isErrored(body)) +} + +function isReadable (body) { + return !!(body && stream.isReadable(body)) +} + +function getSocketInfo (socket) { + return { + localAddress: socket.localAddress, + localPort: socket.localPort, + remoteAddress: socket.remoteAddress, + remotePort: socket.remotePort, + remoteFamily: socket.remoteFamily, + timeout: socket.timeout, + bytesWritten: socket.bytesWritten, + bytesRead: socket.bytesRead + } +} + +/** @type {globalThis['ReadableStream']} */ +function ReadableStreamFrom (iterable) { + // We cannot use ReadableStream.from here because it does not return a byte stream. + + let iterator + return new ReadableStream( + { + async start () { + iterator = iterable[Symbol.asyncIterator]() + }, + async pull (controller) { + const { done, value } = await iterator.next() + if (done) { + queueMicrotask(() => { + controller.close() + controller.byobRequest?.respond(0) + }) + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) + if (buf.byteLength) { + controller.enqueue(new Uint8Array(buf)) + } + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + }, + type: 'bytes' + } + ) +} + +// The chunk should be a FormData instance and contains +// all the required methods. +function isFormDataLike (object) { + return ( + object && + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + object[Symbol.toStringTag] === 'FormData' + ) +} + +function addAbortListener (signal, listener) { + if ('addEventListener' in signal) { + signal.addEventListener('abort', listener, { once: true }) + return () => signal.removeEventListener('abort', listener) + } + signal.addListener('abort', listener) + return () => signal.removeListener('abort', listener) +} + +const hasToWellFormed = typeof String.prototype.toWellFormed === 'function' +const hasIsWellFormed = typeof String.prototype.isWellFormed === 'function' + +/** + * @param {string} val + */ +function toUSVString (val) { + return hasToWellFormed ? `${val}`.toWellFormed() : nodeUtil.toUSVString(val) +} + +/** + * @param {string} val + */ +// TODO: move this to webidl +function isUSVString (val) { + return hasIsWellFormed ? `${val}`.isWellFormed() : toUSVString(val) === `${val}` +} + +/** + * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 + * @param {number} c + */ +function isTokenCharCode (c) { + switch (c) { + case 0x22: + case 0x28: + case 0x29: + case 0x2c: + case 0x2f: + case 0x3a: + case 0x3b: + case 0x3c: + case 0x3d: + case 0x3e: + case 0x3f: + case 0x40: + case 0x5b: + case 0x5c: + case 0x5d: + case 0x7b: + case 0x7d: + // DQUOTE and "(),/:;<=>?@[\]{}" + return false + default: + // VCHAR %x21-7E + return c >= 0x21 && c <= 0x7e + } +} + +/** + * @param {string} characters + */ +function isValidHTTPToken (characters) { + if (characters.length === 0) { + return false + } + for (let i = 0; i < characters.length; ++i) { + if (!isTokenCharCode(characters.charCodeAt(i))) { + return false + } + } + return true +} + +// headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js + +/** + * Matches if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ +const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ + +/** + * @param {string} characters + */ +function isValidHeaderValue (characters) { + return !headerCharRegex.test(characters) +} + +// Parsed accordingly to RFC 9110 +// https://www.rfc-editor.org/rfc/rfc9110#field.content-range +function parseRangeHeader (range) { + if (range == null || range === '') return { start: 0, end: null, size: null } + + const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null + return m + ? { + start: parseInt(m[1]), + end: m[2] ? parseInt(m[2]) : null, + size: m[3] ? parseInt(m[3]) : null + } + : null +} + +function addListener (obj, name, listener) { + const listeners = (obj[kListeners] ??= []) + listeners.push([name, listener]) + obj.on(name, listener) + return obj +} + +function removeAllListeners (obj) { + for (const [name, listener] of obj[kListeners] ?? []) { + obj.removeListener(name, listener) + } + obj[kListeners] = null +} + +function errorRequest (client, request, err) { + try { + request.onError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) + } +} + +const kEnumerableProperty = Object.create(null) +kEnumerableProperty.enumerable = true + +const normalizedMethodRecordsBase = { + delete: 'DELETE', + DELETE: 'DELETE', + get: 'GET', + GET: 'GET', + head: 'HEAD', + HEAD: 'HEAD', + options: 'OPTIONS', + OPTIONS: 'OPTIONS', + post: 'POST', + POST: 'POST', + put: 'PUT', + PUT: 'PUT' +} + +const normalizedMethodRecords = { + ...normalizedMethodRecordsBase, + patch: 'patch', + PATCH: 'PATCH' +} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(normalizedMethodRecordsBase, null) +Object.setPrototypeOf(normalizedMethodRecords, null) + +module.exports = { + kEnumerableProperty, + nop, + isDisturbed, + isErrored, + isReadable, + toUSVString, + isUSVString, + isBlobLike, + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + headerNameToString, + bufferToLowerCasedHeaderName, + addListener, + removeAllListeners, + errorRequest, + parseRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone, + ReadableStreamFrom, + isBuffer, + validateHandler, + getSocketInfo, + isFormDataLike, + buildURL, + addAbortListener, + isValidHTTPToken, + isValidHeaderValue, + isTokenCharCode, + parseRangeHeader, + normalizedMethodRecordsBase, + normalizedMethodRecords, + isValidPort, + isHttpOrHttpsPrefixed, + nodeMajor, + nodeMinor, + safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'], + wrapRequestBody +} diff --git a/node_modules/undici/lib/dispatcher/agent.js b/node_modules/undici/lib/dispatcher/agent.js new file mode 100644 index 0000000000000..90b46fe3aeb4b --- /dev/null +++ b/node_modules/undici/lib/dispatcher/agent.js @@ -0,0 +1,129 @@ +'use strict' + +const { InvalidArgumentError } = require('../core/errors') +const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require('../core/symbols') +const DispatcherBase = require('./dispatcher-base') +const Pool = require('./pool') +const Client = require('./client') +const util = require('../core/util') +const createRedirectInterceptor = require('../interceptor/redirect-interceptor') + +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kMaxRedirections = Symbol('maxRedirections') +const kOnDrain = Symbol('onDrain') +const kFactory = Symbol('factory') +const kOptions = Symbol('options') + +function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) +} + +class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + super(options) + + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } + + this[kInterceptors] = options.interceptors?.Agent && Array.isArray(options.interceptors.Agent) + ? options.interceptors.Agent + : [createRedirectInterceptor({ maxRedirections })] + + this[kOptions] = { ...util.deepClone(options), connect } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kMaxRedirections] = maxRedirections + this[kFactory] = factory + this[kClients] = new Map() + + this[kOnDrain] = (origin, targets) => { + this.emit('drain', origin, [this, ...targets]) + } + + this[kOnConnect] = (origin, targets) => { + this.emit('connect', origin, [this, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + this.emit('disconnect', origin, [this, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + this.emit('connectionError', origin, [this, ...targets], err) + } + } + + get [kRunning] () { + let ret = 0 + for (const client of this[kClients].values()) { + ret += client[kRunning] + } + return ret + } + + [kDispatch] (opts, handler) { + let key + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + key = String(opts.origin) + } else { + throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') + } + + let dispatcher = this[kClients].get(key) + + if (!dispatcher) { + dispatcher = this[kFactory](opts.origin, this[kOptions]) + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + // This introduces a tiny memory leak, as dispatchers are never removed from the map. + // TODO(mcollina): remove te timer when the client/pool do not have any more + // active connections. + this[kClients].set(key, dispatcher) + } + + return dispatcher.dispatch(opts, handler) + } + + async [kClose] () { + const closePromises = [] + for (const client of this[kClients].values()) { + closePromises.push(client.close()) + } + this[kClients].clear() + + await Promise.all(closePromises) + } + + async [kDestroy] (err) { + const destroyPromises = [] + for (const client of this[kClients].values()) { + destroyPromises.push(client.destroy(err)) + } + this[kClients].clear() + + await Promise.all(destroyPromises) + } +} + +module.exports = Agent diff --git a/node_modules/undici/lib/dispatcher/balanced-pool.js b/node_modules/undici/lib/dispatcher/balanced-pool.js new file mode 100644 index 0000000000000..1e2de289cb73f --- /dev/null +++ b/node_modules/undici/lib/dispatcher/balanced-pool.js @@ -0,0 +1,209 @@ +'use strict' + +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = require('../core/errors') +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = require('./pool-base') +const Pool = require('./pool') +const { kUrl, kInterceptors } = require('../core/symbols') +const { parseOrigin } = require('../core/util') +const kFactory = Symbol('factory') + +const kOptions = Symbol('options') +const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') +const kCurrentWeight = Symbol('kCurrentWeight') +const kIndex = Symbol('kIndex') +const kWeight = Symbol('kWeight') +const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') +const kErrorPenalty = Symbol('kErrorPenalty') + +/** + * Calculate the greatest common divisor of two numbers by + * using the Euclidean algorithm. + * + * @param {number} a + * @param {number} b + * @returns {number} + */ +function getGreatestCommonDivisor (a, b) { + if (a === 0) return b + + while (b !== 0) { + const t = b + b = a % b + a = t + } + return a +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + super() + + this[kOptions] = opts + this[kIndex] = -1 + this[kCurrentWeight] = 0 + + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 + + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + this[kInterceptors] = opts.interceptors?.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) + ? opts.interceptors.BalancedPool + : [] + this[kFactory] = factory + + for (const upstream of upstreams) { + this.addUpstream(upstream) + } + this._updateBalancedPoolStats() + } + + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + if (this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this + } + const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) + + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) + + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) + + pool.on('disconnect', (...args) => { + const err = args[2] + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + } + }) + + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] + } + + this._updateBalancedPoolStats() + + return this + } + + _updateBalancedPoolStats () { + let result = 0 + for (let i = 0; i < this[kClients].length; i++) { + result = getGreatestCommonDivisor(this[kClients][i][kWeight], result) + } + + this[kGreatestCommonDivisor] = result + } + + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) + + if (pool) { + this[kRemoveClient](pool) + } + + return this + } + + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } + + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients].length === 0) { + throw new BalancedPoolMissingUpstreamError() + } + + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + + if (!dispatcher) { + return + } + + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) + + if (allClientsBusy) { + return + } + + let counter = 0 + + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) + + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] + + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex] + } + + // decrease the current weight every `this[kClients].length`. + if (this[kIndex] === 0) { + // Set the current weight to the next lower weight. + this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] + + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } + } + + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] + } +} + +module.exports = BalancedPool diff --git a/node_modules/undici/lib/dispatcher/client-h1.js b/node_modules/undici/lib/dispatcher/client-h1.js new file mode 100644 index 0000000000000..ef3d38ea4f2ed --- /dev/null +++ b/node_modules/undici/lib/dispatcher/client-h1.js @@ -0,0 +1,1416 @@ +'use strict' + +/* global WebAssembly */ + +const assert = require('node:assert') +const util = require('../core/util.js') +const { channels } = require('../core/diagnostics.js') +const timers = require('../util/timers.js') +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError +} = require('../core/errors.js') +const { + kUrl, + kReset, + kClient, + kParser, + kBlocking, + kRunning, + kPending, + kSize, + kWriting, + kQueue, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kMaxRequests, + kCounter, + kMaxResponseSize, + kOnError, + kResume, + kHTTPContext +} = require('../core/symbols.js') + +const constants = require('../llhttp/constants.js') +const EMPTY_BUF = Buffer.alloc(0) +const FastBuffer = Buffer[Symbol.species] +const addListener = util.addListener +const removeAllListeners = util.removeAllListeners + +let extractBody + +async function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? require('../llhttp/llhttp-wasm.js') : undefined + + let mod + try { + mod = await WebAssembly.compile(require('../llhttp/llhttp_simd-wasm.js')) + } catch (e) { + /* istanbul ignore next */ + + // We could check if the error was caused by the simd option not + // being enabled, but the occurring of this other error + // * https://github.com/emscripten-core/emscripten/issues/11495 + // got me to remove that check to avoid breaking Node 12. + mod = await WebAssembly.compile(llhttpWasmData || require('../llhttp/llhttp-wasm.js')) + } + + return await WebAssembly.instantiate(mod, { + env: { + /* eslint-disable camelcase */ + + wasm_on_url: (p, at, len) => { + /* istanbul ignore next */ + return 0 + }, + wasm_on_status: (p, at, len) => { + assert(currentParser.ptr === p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_begin: (p) => { + assert(currentParser.ptr === p) + return currentParser.onMessageBegin() || 0 + }, + wasm_on_header_field: (p, at, len) => { + assert(currentParser.ptr === p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_header_value: (p, at, len) => { + assert(currentParser.ptr === p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { + assert(currentParser.ptr === p) + return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 + }, + wasm_on_body: (p, at, len) => { + assert(currentParser.ptr === p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_complete: (p) => { + assert(currentParser.ptr === p) + return currentParser.onMessageComplete() || 0 + } + + /* eslint-enable camelcase */ + } + }) +} + +let llhttpInstance = null +let llhttpPromise = lazyllhttp() +llhttpPromise.catch() + +let currentParser = null +let currentBufferRef = null +let currentBufferSize = 0 +let currentBufferPtr = null + +const USE_NATIVE_TIMER = 0 +const USE_FAST_TIMER = 1 + +// Use fast timers for headers and body to take eventual event loop +// latency into account. +const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER +const TIMEOUT_BODY = 4 | USE_FAST_TIMER + +// Use native timers to ignore event loop latency for keep-alive +// handling. +const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER + +class Parser { + constructor (client, socket, { exports }) { + assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) + + this.llhttp = exports + this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) + this.client = client + this.socket = socket + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + this.statusCode = null + this.statusText = '' + this.upgrade = false + this.headers = [] + this.headersSize = 0 + this.headersMaxSize = client[kMaxHeadersSize] + this.shouldKeepAlive = false + this.paused = false + this.resume = this.resume.bind(this) + + this.bytesRead = 0 + + this.keepAlive = '' + this.contentLength = '' + this.connection = '' + this.maxResponseSize = client[kMaxResponseSize] + } + + setTimeout (delay, type) { + // If the existing timer and the new timer are of different timer type + // (fast or native) or have different delay, we need to clear the existing + // timer and set a new one. + if ( + delay !== this.timeoutValue || + (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER) + ) { + // If a timeout is already set, clear it with clearTimeout of the fast + // timer implementation, as it can clear fast and native timers. + if (this.timeout) { + timers.clearTimeout(this.timeout) + this.timeout = null + } + + if (delay) { + if (type & USE_FAST_TIMER) { + this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this)) + } else { + this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this)) + this.timeout.unref() + } + } + + this.timeoutValue = delay + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + this.timeoutType = type + } + + resume () { + if (this.socket.destroyed || !this.paused) { + return + } + + assert(this.ptr != null) + assert(currentParser == null) + + this.llhttp.llhttp_resume(this.ptr) + + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + this.paused = false + this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. + this.readMore() + } + + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read() + if (chunk === null) { + break + } + this.execute(chunk) + } + } + + execute (data) { + assert(this.ptr != null) + assert(currentParser == null) + assert(!this.paused) + + const { socket, llhttp } = this + + if (data.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr) + } + currentBufferSize = Math.ceil(data.length / 4096) * 4096 + currentBufferPtr = llhttp.malloc(currentBufferSize) + } + + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) + + // Call `execute` on the wasm parser. + // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, + // and finally the length of bytes to parse. + // The return value is an error code or `constants.ERROR.OK`. + try { + let ret + + try { + currentBufferRef = data + currentParser = this + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) + /* eslint-disable-next-line no-useless-catch */ + } catch (err) { + /* istanbul ignore next: difficult to make a test case for */ + throw err + } finally { + currentParser = null + currentBufferRef = null + } + + const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr + + if (ret !== constants.ERROR.OK) { + const body = data.subarray(offset) + + if (ret === constants.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(body) + } else if (ret === constants.ERROR.PAUSED) { + this.paused = true + socket.unshift(body) + } else { + throw this.createError(ret, body) + } + } + } catch (err) { + util.destroy(socket, err) + } + } + + finish () { + assert(currentParser === null) + assert(this.ptr != null) + assert(!this.paused) + + const { llhttp } = this + + let ret + + try { + currentParser = this + ret = llhttp.llhttp_finish(this.ptr) + } finally { + currentParser = null + } + + if (ret === constants.ERROR.OK) { + return null + } + + if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) { + this.paused = true + return null + } + + return this.createError(ret, EMPTY_BUF) + } + + createError (ret, data) { + const { llhttp, contentLength, bytesRead } = this + + if (contentLength && bytesRead !== parseInt(contentLength, 10)) { + return new ResponseContentLengthMismatchError() + } + + const ptr = llhttp.llhttp_get_error_reason(this.ptr) + let message = '' + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) + message = + 'Response does not match the HTTP/1.1 protocol (' + + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + + ')' + } + + return new HTTPParserError(message, constants.ERROR[ret], data) + } + + destroy () { + assert(this.ptr != null) + assert(currentParser == null) + + this.llhttp.llhttp_free(this.ptr) + this.ptr = null + + this.timeout && timers.clearTimeout(this.timeout) + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + + this.paused = false + } + + onStatus (buf) { + this.statusText = buf.toString() + } + + onMessageBegin () { + const { socket, client } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + if (!request) { + return -1 + } + request.onResponseStarted() + } + + onHeaderField (buf) { + const len = this.headers.length + + if ((len & 1) === 0) { + this.headers.push(buf) + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + this.trackHeader(buf.length) + } + + onHeaderValue (buf) { + let len = this.headers.length + + if ((len & 1) === 1) { + this.headers.push(buf) + len += 1 + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + const key = this.headers[len - 2] + if (key.length === 10) { + const headerName = util.bufferToLowerCasedHeaderName(key) + if (headerName === 'keep-alive') { + this.keepAlive += buf.toString() + } else if (headerName === 'connection') { + this.connection += buf.toString() + } + } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') { + this.contentLength += buf.toString() + } + + this.trackHeader(buf.length) + } + + trackHeader (len) { + this.headersSize += len + if (this.headersSize >= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()) + } + } + + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this + + assert(upgrade) + assert(client[kSocket] === socket) + assert(!socket.destroyed) + assert(!this.paused) + assert((headers.length & 1) === 0) + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + assert(request.upgrade || request.method === 'CONNECT') + + this.statusCode = null + this.statusText = '' + this.shouldKeepAlive = null + + this.headers = [] + this.headersSize = 0 + + socket.unshift(head) + + socket[kParser].destroy() + socket[kParser] = null + + socket[kClient] = null + socket[kError] = null + + removeAllListeners(socket) + + client[kSocket] = null + client[kHTTPContext] = null // TODO (fix): This is hacky... + client[kQueue][client[kRunningIdx]++] = null + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) + + try { + request.onUpgrade(statusCode, headers, socket) + } catch (err) { + util.destroy(socket, err) + } + + client[kResume]() + } + + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -1 + } + + assert(!this.upgrade) + assert(this.statusCode < 200) + + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) + return -1 + } + + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) + return -1 + } + + assert(this.timeoutType === TIMEOUT_HEADERS) + + this.statusCode = statusCode + this.shouldKeepAlive = ( + shouldKeepAlive || + // Override llhttp value which does not allow keepAlive for HEAD. + (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') + ) + + if (this.statusCode >= 200) { + const bodyTimeout = request.bodyTimeout != null + ? request.bodyTimeout + : client[kBodyTimeout] + this.setTimeout(bodyTimeout, TIMEOUT_BODY) + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + if (upgrade) { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + assert((this.headers.length & 1) === 0) + this.headers = [] + this.headersSize = 0 + + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null + + if (keepAliveTimeout != null) { + const timeout = Math.min( + keepAliveTimeout - client[kKeepAliveTimeoutThreshold], + client[kKeepAliveMaxTimeout] + ) + if (timeout <= 0) { + socket[kReset] = true + } else { + client[kKeepAliveTimeoutValue] = timeout + } + } else { + client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] + } + } else { + // Stop more requests from being dispatched. + socket[kReset] = true + } + + const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false + + if (request.aborted) { + return -1 + } + + if (request.method === 'HEAD') { + return 1 + } + + if (statusCode < 200) { + return 1 + } + + if (socket[kBlocking]) { + socket[kBlocking] = false + client[kResume]() + } + + return pause ? constants.ERROR.PAUSED : 0 + } + + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this + + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + assert(statusCode >= 200) + + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()) + return -1 + } + + this.bytesRead += buf.length + + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED + } + } + + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this + + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } + + if (upgrade) { + return + } + + assert(statusCode >= 100) + assert((this.headers.length & 1) === 0) + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + this.statusCode = null + this.statusText = '' + this.bytesRead = 0 + this.contentLength = '' + this.keepAlive = '' + this.connection = '' + + this.headers = [] + this.headersSize = 0 + + if (statusCode < 200) { + return + } + + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()) + return -1 + } + + request.onComplete(headers) + + client[kQueue][client[kRunningIdx]++] = null + + if (socket[kWriting]) { + assert(client[kRunning] === 0) + // Response completed before request. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (!shouldKeepAlive) { + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (socket[kReset] && client[kRunning] === 0) { + // Destroy socket once all requests have completed. + // The request at the tail of the pipeline is the one + // that requested reset and no further requests should + // have been queued since then. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (client[kPipelining] == null || client[kPipelining] === 1) { + // We must wait a full event loop cycle to reuse this socket to make sure + // that non-spec compliant servers are not closing the connection even if they + // said they won't. + setImmediate(() => client[kResume]()) + } else { + client[kResume]() + } + } +} + +function onParserTimeout (parser) { + const { socket, timeoutType, client, paused } = parser.deref() + + /* istanbul ignore else */ + if (timeoutType === TIMEOUT_HEADERS) { + if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { + assert(!paused, 'cannot be paused while waiting for headers') + util.destroy(socket, new HeadersTimeoutError()) + } + } else if (timeoutType === TIMEOUT_BODY) { + if (!paused) { + util.destroy(socket, new BodyTimeoutError()) + } + } else if (timeoutType === TIMEOUT_KEEP_ALIVE) { + assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) + util.destroy(socket, new InformationalError('socket idle timeout')) + } +} + +async function connectH1 (client, socket) { + client[kSocket] = socket + + if (!llhttpInstance) { + llhttpInstance = await llhttpPromise + llhttpPromise = null + } + + socket[kNoRef] = false + socket[kWriting] = false + socket[kReset] = false + socket[kBlocking] = false + socket[kParser] = new Parser(client, socket, llhttpInstance) + + addListener(socket, 'error', function (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + const parser = this[kParser] + + // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded + // to the user. + if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { + const parserErr = parser.finish() + if (parserErr) { + this[kError] = parserErr + this[kClient][kOnError](parserErr) + } + return + } + + this[kError] = err + + this[kClient][kOnError](err) + }) + addListener(socket, 'readable', function () { + const parser = this[kParser] + + if (parser) { + parser.readMore() + } + }) + addListener(socket, 'end', function () { + const parser = this[kParser] + + if (parser.statusCode && !parser.shouldKeepAlive) { + const parserErr = parser.finish() + if (parserErr) { + util.destroy(this, parserErr) + } + return + } + + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) + }) + addListener(socket, 'close', function () { + const client = this[kClient] + const parser = this[kParser] + + if (parser) { + if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { + this[kError] = parser.finish() || this[kError] + } + + this[kParser].destroy() + this[kParser] = null + } + + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) + + client[kSocket] = null + client[kHTTPContext] = null // TODO (fix): This is hacky... + + if (client.destroyed) { + assert(client[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + util.errorRequest(client, request, err) + } + } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + + util.errorRequest(client, request, err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + + client[kResume]() + }) + + let closed = false + socket.on('close', () => { + closed = true + }) + + return { + version: 'h1', + defaultPipelining: 1, + write (...args) { + return writeH1(client, ...args) + }, + resume () { + resumeH1(client) + }, + destroy (err, callback) { + if (closed) { + queueMicrotask(callback) + } else { + socket.destroy(err).on('close', callback) + } + }, + get destroyed () { + return socket.destroyed + }, + busy (request) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return true + } + + if (request) { + if (client[kRunning] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return true + } + + if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { + // Don't dispatch an upgrade until all preceding requests have completed. + // A misbehaving server might upgrade the connection before all pipelined + // request has completed. + return true + } + + if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && + (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) { + // Request with stream or iterator body can error while other requests + // are inflight and indirectly error those as well. + // Ensure this doesn't happen by waiting for inflight + // to complete before dispatching. + + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return true + } + } + + return false + } + } +} + +function resumeH1 (client) { + const socket = client[kSocket] + + if (socket && !socket.destroyed) { + if (client[kSize] === 0) { + if (!socket[kNoRef] && socket.unref) { + socket.unref() + socket[kNoRef] = true + } + } else if (socket[kNoRef] && socket.ref) { + socket.ref() + socket[kNoRef] = false + } + + if (client[kSize] === 0) { + if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { + socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE) + } + } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { + if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { + const request = client[kQueue][client[kRunningIdx]] + const headersTimeout = request.headersTimeout != null + ? request.headersTimeout + : client[kHeadersTimeout] + socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) + } + } + } +} + +// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 +function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' +} + +function writeH1 (client, request) { + const { method, path, host, upgrade, blocking, reset } = request + + let { body, headers, contentLength } = request + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' || + method === 'QUERY' || + method === 'PROPFIND' || + method === 'PROPPATCH' + ) + + if (util.isFormDataLike(body)) { + if (!extractBody) { + extractBody = require('../web/fetch/body.js').extractBody + } + + const [bodyStream, contentType] = extractBody(body) + if (request.contentType == null) { + headers.push('content-type', contentType) + } + body = bodyStream.stream + contentLength = bodyStream.length + } else if (util.isBlobLike(body) && request.contentType == null && body.type) { + headers.push('content-type', body.type) + } + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + const bodyLength = util.bodyLength(body) + + contentLength = bodyLength ?? contentLength + + if (contentLength === null) { + contentLength = request.contentLength + } + + if (contentLength === 0 && !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + util.errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + const socket = client[kSocket] + + const abort = (err) => { + if (request.aborted || request.completed) { + return + } + + util.errorRequest(client, request, err || new RequestAbortedError()) + + util.destroy(body) + util.destroy(socket, new InformationalError('aborted')) + } + + try { + request.onConnect(abort) + } catch (err) { + util.errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + if (method === 'HEAD') { + // https://github.com/mcollina/undici/issues/258 + // Close after a HEAD request to interop with misbehaving servers + // that may send a body in the response. + + socket[kReset] = true + } + + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. + + socket[kReset] = true + } + + if (reset != null) { + socket[kReset] = reset + } + + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true + } + + if (blocking) { + socket[kBlocking] = true + } + + let header = `${method} ${path} HTTP/1.1\r\n` + + if (typeof host === 'string') { + header += `host: ${host}\r\n` + } else { + header += client[kHostHeader] + } + + if (upgrade) { + header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` + } else if (client[kPipelining] && !socket[kReset]) { + header += 'connection: keep-alive\r\n' + } else { + header += 'connection: close\r\n' + } + + if (Array.isArray(headers)) { + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0] + const val = headers[n + 1] + + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + header += `${key}: ${val[i]}\r\n` + } + } else { + header += `${key}: ${val}\r\n` + } + } + } + + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }) + } + + /* istanbul ignore else: assertion */ + if (!body || bodyLength === 0) { + writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload) + } else if (util.isBuffer(body)) { + writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload) + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload) + } else { + writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload) + } + } else if (util.isStream(body)) { + writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload) + } else if (util.isIterable(body)) { + writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload) + } else { + assert(false) + } + + return true +} + +function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') + + let finished = false + + const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }) + + const onData = function (chunk) { + if (finished) { + return + } + + try { + if (!writer.write(chunk) && this.pause) { + this.pause() + } + } catch (err) { + util.destroy(this, err) + } + } + const onDrain = function () { + if (finished) { + return + } + + if (body.resume) { + body.resume() + } + } + const onClose = function () { + // 'close' might be emitted *before* 'error' for + // broken streams. Wait a tick to avoid this case. + queueMicrotask(() => { + // It's only safe to remove 'error' listener after + // 'close'. + body.removeListener('error', onFinished) + }) + + if (!finished) { + const err = new RequestAbortedError() + queueMicrotask(() => onFinished(err)) + } + } + const onFinished = function (err) { + if (finished) { + return + } + + finished = true + + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) + + socket + .off('drain', onDrain) + .off('error', onFinished) + + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('close', onClose) + + if (!err) { + try { + writer.end() + } catch (er) { + err = er + } + } + + writer.destroy(err) + + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err) + } else { + util.destroy(body) + } + } + + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onClose) + + if (body.resume) { + body.resume() + } + + socket + .on('drain', onDrain) + .on('error', onFinished) + + if (body.errorEmitted ?? body.errored) { + setImmediate(() => onFinished(body.errored)) + } else if (body.endEmitted ?? body.readableEnded) { + setImmediate(() => onFinished(null)) + } + + if (body.closeEmitted ?? body.closed) { + setImmediate(onClose) + } +} + +function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) { + try { + if (!body) { + if (contentLength === 0) { + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + assert(contentLength === null, 'no body must not have content length') + socket.write(`${header}\r\n`, 'latin1') + } + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(body) + socket.uncork() + request.onBodySent(body) + + if (!expectsPayload && request.reset !== false) { + socket[kReset] = true + } + } + request.onRequestSent() + + client[kResume]() + } catch (err) { + abort(err) + } +} + +async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) { + assert(contentLength === body.size, 'blob body must have content length') + + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()) + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(buffer) + socket.uncork() + + request.onBodySent(buffer) + request.onRequestSent() + + if (!expectsPayload && request.reset !== false) { + socket[kReset] = true + } + + client[kResume]() + } catch (err) { + abort(err) + } +} + +async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') + + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) + + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) + + socket + .on('close', onDrain) + .on('drain', onDrain) + + const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }) + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + if (!writer.write(chunk)) { + await waitForDrain() + } + } + + writer.end() + } catch (err) { + writer.destroy(err) + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain) + } +} + +class AsyncWriter { + constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) { + this.socket = socket + this.request = request + this.contentLength = contentLength + this.client = client + this.bytesWritten = 0 + this.expectsPayload = expectsPayload + this.header = header + this.abort = abort + + socket[kWriting] = true + } + + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return false + } + + const len = Buffer.byteLength(chunk) + if (!len) { + return true + } + + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + socket.cork() + + if (bytesWritten === 0) { + if (!expectsPayload && request.reset !== false) { + socket[kReset] = true + } + + if (contentLength === null) { + socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') + } else { + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + } + } + + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') + } + + this.bytesWritten += len + + const ret = socket.write(chunk) + + socket.uncork() + + request.onBodySent(chunk) + + if (!ret) { + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + } + + return ret + } + + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this + request.onRequestSent() + + socket[kWriting] = false + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return + } + + if (bytesWritten === 0) { + if (expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. + + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + socket.write(`${header}\r\n`, 'latin1') + } + } else if (contentLength === null) { + socket.write('\r\n0\r\n\r\n', 'latin1') + } + + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + process.emitWarning(new RequestContentLengthMismatchError()) + } + } + + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + + client[kResume]() + } + + destroy (err) { + const { socket, client, abort } = this + + socket[kWriting] = false + + if (err) { + assert(client[kRunning] <= 1, 'pipeline should only contain this request') + abort(err) + } + } +} + +module.exports = connectH1 diff --git a/node_modules/undici/lib/dispatcher/client-h2.js b/node_modules/undici/lib/dispatcher/client-h2.js new file mode 100644 index 0000000000000..4a52effb1f3b1 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/client-h2.js @@ -0,0 +1,744 @@ +'use strict' + +const assert = require('node:assert') +const { pipeline } = require('node:stream') +const util = require('../core/util.js') +const { + RequestContentLengthMismatchError, + RequestAbortedError, + SocketError, + InformationalError +} = require('../core/errors.js') +const { + kUrl, + kReset, + kClient, + kRunning, + kPending, + kQueue, + kPendingIdx, + kRunningIdx, + kError, + kSocket, + kStrictContentLength, + kOnError, + kMaxConcurrentStreams, + kHTTP2Session, + kResume, + kSize, + kHTTPContext +} = require('../core/symbols.js') + +const kOpenStreams = Symbol('open streams') + +let extractBody + +// Experimental +let h2ExperimentalWarned = false + +/** @type {import('http2')} */ +let http2 +try { + http2 = require('node:http2') +} catch { + // @ts-ignore + http2 = { constants: {} } +} + +const { + constants: { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_CONTENT_LENGTH, + HTTP2_HEADER_EXPECT, + HTTP2_HEADER_STATUS + } +} = http2 + +function parseH2Headers (headers) { + const result = [] + + for (const [name, value] of Object.entries(headers)) { + // h2 may concat the header value by array + // e.g. Set-Cookie + if (Array.isArray(value)) { + for (const subvalue of value) { + // we need to provide each header value of header name + // because the headers handler expect name-value pair + result.push(Buffer.from(name), Buffer.from(subvalue)) + } + } else { + result.push(Buffer.from(name), Buffer.from(value)) + } + } + + return result +} + +async function connectH2 (client, socket) { + client[kSocket] = socket + + if (!h2ExperimentalWarned) { + h2ExperimentalWarned = true + process.emitWarning('H2 support is experimental, expect them to change at any time.', { + code: 'UNDICI-H2' + }) + } + + const session = http2.connect(client[kUrl], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kMaxConcurrentStreams] + }) + + session[kOpenStreams] = 0 + session[kClient] = client + session[kSocket] = socket + + util.addListener(session, 'error', onHttp2SessionError) + util.addListener(session, 'frameError', onHttp2FrameError) + util.addListener(session, 'end', onHttp2SessionEnd) + util.addListener(session, 'goaway', onHTTP2GoAway) + util.addListener(session, 'close', function () { + const { [kClient]: client } = this + const { [kSocket]: socket } = client + + const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket)) + + client[kHTTP2Session] = null + + if (client.destroyed) { + assert(client[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + util.errorRequest(client, request, err) + } + } + }) + + session.unref() + + client[kHTTP2Session] = session + socket[kHTTP2Session] = session + + util.addListener(socket, 'error', function (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + this[kError] = err + + this[kClient][kOnError](err) + }) + + util.addListener(socket, 'end', function () { + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) + }) + + util.addListener(socket, 'close', function () { + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) + + client[kSocket] = null + + if (this[kHTTP2Session] != null) { + this[kHTTP2Session].destroy(err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + + client[kResume]() + }) + + let closed = false + socket.on('close', () => { + closed = true + }) + + return { + version: 'h2', + defaultPipelining: Infinity, + write (...args) { + return writeH2(client, ...args) + }, + resume () { + resumeH2(client) + }, + destroy (err, callback) { + if (closed) { + queueMicrotask(callback) + } else { + // Destroying the socket will trigger the session close + socket.destroy(err).on('close', callback) + } + }, + get destroyed () { + return socket.destroyed + }, + busy () { + return false + } + } +} + +function resumeH2 (client) { + const socket = client[kSocket] + + if (socket?.destroyed === false) { + if (client[kSize] === 0 && client[kMaxConcurrentStreams] === 0) { + socket.unref() + client[kHTTP2Session].unref() + } else { + socket.ref() + client[kHTTP2Session].ref() + } + } +} + +function onHttp2SessionError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + this[kSocket][kError] = err + this[kClient][kOnError](err) +} + +function onHttp2FrameError (type, code, id) { + if (id === 0) { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + this[kSocket][kError] = err + this[kClient][kOnError](err) + } +} + +function onHttp2SessionEnd () { + const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket])) + this.destroy(err) + util.destroy(this[kSocket], err) +} + +/** + * This is the root cause of #3011 + * We need to handle GOAWAY frames properly, and trigger the session close + * along with the socket right away + */ +function onHTTP2GoAway (code) { + // We cannot recover, so best to close the session and the socket + const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${code}`, util.getSocketInfo(this)) + const client = this[kClient] + + client[kSocket] = null + client[kHTTPContext] = null + + if (this[kHTTP2Session] != null) { + this[kHTTP2Session].destroy(err) + this[kHTTP2Session] = null + } + + util.destroy(this[kSocket], err) + + // Fail head of pipeline. + if (client[kRunningIdx] < client[kQueue].length) { + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + util.errorRequest(client, request, err) + client[kPendingIdx] = client[kRunningIdx] + } + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + + client[kResume]() +} + +// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 +function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' +} + +function writeH2 (client, request) { + const session = client[kHTTP2Session] + const { method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request + let { body } = request + + if (upgrade) { + util.errorRequest(client, request, new Error('Upgrade not supported for H2')) + return false + } + + const headers = {} + for (let n = 0; n < reqHeaders.length; n += 2) { + const key = reqHeaders[n + 0] + const val = reqHeaders[n + 1] + + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + if (headers[key]) { + headers[key] += `,${val[i]}` + } else { + headers[key] = val[i] + } + } + } else { + headers[key] = val + } + } + + /** @type {import('node:http2').ClientHttp2Stream} */ + let stream + + const { hostname, port } = client[kUrl] + + headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}` + headers[HTTP2_HEADER_METHOD] = method + + const abort = (err) => { + if (request.aborted || request.completed) { + return + } + + err = err || new RequestAbortedError() + + util.errorRequest(client, request, err) + + if (stream != null) { + util.destroy(stream, err) + } + + // We do not destroy the socket as we can continue using the session + // the stream get's destroyed and the session remains to create new streams + util.destroy(body, err) + client[kQueue][client[kRunningIdx]++] = null + client[kResume]() + } + + try { + // We are already connected, streams are pending. + // We can call on connect, and wait for abort + request.onConnect(abort) + } catch (err) { + util.errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + if (method === 'CONNECT') { + session.ref() + // We are already connected, streams are pending, first request + // will create a new stream. We trigger a request to create the stream and wait until + // `ready` event is triggered + // We disabled endStream to allow the user to write to the stream + stream = session.request(headers, { endStream: false, signal }) + + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream) + ++session[kOpenStreams] + client[kQueue][client[kRunningIdx]++] = null + } else { + stream.once('ready', () => { + request.onUpgrade(null, null, stream) + ++session[kOpenStreams] + client[kQueue][client[kRunningIdx]++] = null + }) + } + + stream.once('close', () => { + session[kOpenStreams] -= 1 + if (session[kOpenStreams] === 0) session.unref() + }) + + return true + } + + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omitted when sending CONNECT + + headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_SCHEME] = 'https' + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + let contentLength = util.bodyLength(body) + + if (util.isFormDataLike(body)) { + extractBody ??= require('../web/fetch/body.js').extractBody + + const [bodyStream, contentType] = extractBody(body) + headers['content-type'] = contentType + + body = bodyStream.stream + contentLength = bodyStream.length + } + + if (contentLength == null) { + contentLength = request.contentLength + } + + if (contentLength === 0 || !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + util.errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + if (contentLength != null) { + assert(body, 'no body must not have content length') + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` + } + + session.ref() + + const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null + if (expectContinue) { + headers[HTTP2_HEADER_EXPECT] = '100-continue' + stream = session.request(headers, { endStream: shouldEndStream, signal }) + + stream.once('continue', writeBodyH2) + } else { + stream = session.request(headers, { + endStream: shouldEndStream, + signal + }) + writeBodyH2() + } + + // Increment counter as we have new streams open + ++session[kOpenStreams] + + stream.once('response', headers => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers + request.onResponseStarted() + + // Due to the stream nature, it is possible we face a race condition + // where the stream has been assigned, but the request has been aborted + // the request remains in-flight and headers hasn't been received yet + // for those scenarios, best effort is to destroy the stream immediately + // as there's no value to keep it open. + if (request.aborted) { + const err = new RequestAbortedError() + util.errorRequest(client, request, err) + util.destroy(stream, err) + return + } + + if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) { + stream.pause() + } + + stream.on('data', (chunk) => { + if (request.onData(chunk) === false) { + stream.pause() + } + }) + }) + + stream.once('end', () => { + // When state is null, it means we haven't consumed body and the stream still do not have + // a state. + // Present specially when using pipeline or stream + if (stream.state?.state == null || stream.state.state < 6) { + request.onComplete([]) + } + + if (session[kOpenStreams] === 0) { + // Stream is closed or half-closed-remote (6), decrement counter and cleanup + // It does not have sense to continue working with the stream as we do not + // have yet RST_STREAM support on client-side + + session.unref() + } + + abort(new InformationalError('HTTP/2: stream half-closed (remote)')) + client[kQueue][client[kRunningIdx]++] = null + client[kPendingIdx] = client[kRunningIdx] + client[kResume]() + }) + + stream.once('close', () => { + session[kOpenStreams] -= 1 + if (session[kOpenStreams] === 0) { + session.unref() + } + }) + + stream.once('error', function (err) { + abort(err) + }) + + stream.once('frameError', (type, code) => { + abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)) + }) + + // stream.on('aborted', () => { + // // TODO(HTTP/2): Support aborted + // }) + + // stream.on('timeout', () => { + // // TODO(HTTP/2): Support timeout + // }) + + // stream.on('push', headers => { + // // TODO(HTTP/2): Support push + // }) + + // stream.on('trailers', headers => { + // // TODO(HTTP/2): Support trailers + // }) + + return true + + function writeBodyH2 () { + /* istanbul ignore else: assertion */ + if (!body || contentLength === 0) { + writeBuffer( + abort, + stream, + null, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } else if (util.isBuffer(body)) { + writeBuffer( + abort, + stream, + body, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable( + abort, + stream, + body.stream(), + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } else { + writeBlob( + abort, + stream, + body, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } + } else if (util.isStream(body)) { + writeStream( + abort, + client[kSocket], + expectsPayload, + stream, + body, + client, + request, + contentLength + ) + } else if (util.isIterable(body)) { + writeIterable( + abort, + stream, + body, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } else { + assert(false) + } + } +} + +function writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { + try { + if (body != null && util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + h2stream.cork() + h2stream.write(body) + h2stream.uncork() + h2stream.end() + + request.onBodySent(body) + } + + if (!expectsPayload) { + socket[kReset] = true + } + + request.onRequestSent() + client[kResume]() + } catch (error) { + abort(error) + } +} + +function writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') + + // For HTTP/2, is enough to pipe the stream + const pipe = pipeline( + body, + h2stream, + (err) => { + if (err) { + util.destroy(pipe, err) + abort(err) + } else { + util.removeAllListeners(pipe) + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + client[kResume]() + } + } + ) + + util.addListener(pipe, 'data', onPipeData) + + function onPipeData (chunk) { + request.onBodySent(chunk) + } +} + +async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { + assert(contentLength === body.size, 'blob body must have content length') + + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()) + + h2stream.cork() + h2stream.write(buffer) + h2stream.uncork() + h2stream.end() + + request.onBodySent(buffer) + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + client[kResume]() + } catch (err) { + abort(err) + } +} + +async function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') + + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) + + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) + + h2stream + .on('close', onDrain) + .on('drain', onDrain) + + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + const res = h2stream.write(chunk) + request.onBodySent(chunk) + if (!res) { + await waitForDrain() + } + } + + h2stream.end() + + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + client[kResume]() + } catch (err) { + abort(err) + } finally { + h2stream + .off('close', onDrain) + .off('drain', onDrain) + } +} + +module.exports = connectH2 diff --git a/node_modules/undici/lib/dispatcher/client.js b/node_modules/undici/lib/dispatcher/client.js new file mode 100644 index 0000000000000..18472fffd773f --- /dev/null +++ b/node_modules/undici/lib/dispatcher/client.js @@ -0,0 +1,623 @@ +// @ts-check + +'use strict' + +const assert = require('node:assert') +const net = require('node:net') +const http = require('node:http') +const util = require('../core/util.js') +const { channels } = require('../core/diagnostics.js') +const Request = require('../core/request.js') +const DispatcherBase = require('./dispatcher-base') +const { + InvalidArgumentError, + InformationalError, + ClientDestroyedError +} = require('../core/errors.js') +const buildConnector = require('../core/connect.js') +const { + kUrl, + kServerName, + kClient, + kBusy, + kConnect, + kResuming, + kRunning, + kPending, + kSize, + kQueue, + kConnected, + kConnecting, + kNeedDrain, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kConnector, + kMaxRedirections, + kMaxRequests, + kCounter, + kClose, + kDestroy, + kDispatch, + kInterceptors, + kLocalAddress, + kMaxResponseSize, + kOnError, + kHTTPContext, + kMaxConcurrentStreams, + kResume +} = require('../core/symbols.js') +const connectH1 = require('./client-h1.js') +const connectH2 = require('./client-h2.js') +let deprecatedInterceptorWarned = false + +const kClosedResolve = Symbol('kClosedResolve') + +const noop = () => {} + +function getPipelining (client) { + return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1 +} + +/** + * @type {import('../../types/client.js').default} + */ +class Client extends DispatcherBase { + /** + * + * @param {string|URL} url + * @param {import('../../types/client.js').Client.Options} options + */ + constructor (url, { + interceptors, + maxHeaderSize, + headersTimeout, + socketTimeout, + requestTimeout, + connectTimeout, + bodyTimeout, + idleTimeout, + keepAlive, + keepAliveTimeout, + maxKeepAliveTimeout, + keepAliveMaxTimeout, + keepAliveTimeoutThreshold, + socketPath, + pipelining, + tls, + strictContentLength, + maxCachedSessions, + maxRedirections, + connect, + maxRequestsPerClient, + localAddress, + maxResponseSize, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + // h2 + maxConcurrentStreams, + allowH2, + webSocket + } = {}) { + super({ webSocket }) + + if (keepAlive !== undefined) { + throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') + } + + if (socketTimeout !== undefined) { + throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + } + + if (requestTimeout !== undefined) { + throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + } + + if (idleTimeout !== undefined) { + throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') + } + + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') + } + + if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { + throw new InvalidArgumentError('invalid maxHeaderSize') + } + + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') + } + + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') + } + + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } + + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } + + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') + } + + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') + } + + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') + } + + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') + } + + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') + } + + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } + + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError('allowH2 must be a valid boolean value') + } + + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + if (interceptors?.Client && Array.isArray(interceptors.Client)) { + this[kInterceptors] = interceptors.Client + if (!deprecatedInterceptorWarned) { + deprecatedInterceptorWarned = true + process.emitWarning('Client.Options#interceptor is deprecated. Use Dispatcher#compose instead.', { + code: 'UNDICI-CLIENT-INTERCEPTOR-DEPRECATED' + }) + } + } else { + this[kInterceptors] = [createRedirectInterceptor({ maxRedirections })] + } + + this[kUrl] = util.parseOrigin(url) + this[kConnector] = connect + this[kPipelining] = pipelining != null ? pipelining : 1 + this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize + this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout + this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout + this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold + this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] + this[kServerName] = null + this[kLocalAddress] = localAddress != null ? localAddress : null + this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` + this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 + this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 + this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength + this[kMaxRedirections] = maxRedirections + this[kMaxRequests] = maxRequestsPerClient + this[kClosedResolve] = null + this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 + this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server + this[kHTTPContext] = null + + // kQueue is built up of 3 sections separated by + // the kRunningIdx and kPendingIdx indices. + // | complete | running | pending | + // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length + // kRunningIdx points to the first running element. + // kPendingIdx points to the first pending element. + // This implements a fast queue with an amortized + // time of O(1). + + this[kQueue] = [] + this[kRunningIdx] = 0 + this[kPendingIdx] = 0 + + this[kResume] = (sync) => resume(this, sync) + this[kOnError] = (err) => onError(this, err) + } + + get pipelining () { + return this[kPipelining] + } + + set pipelining (value) { + this[kPipelining] = value + this[kResume](true) + } + + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] + } + + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] + } + + get [kSize] () { + return this[kQueue].length - this[kRunningIdx] + } + + get [kConnected] () { + return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed + } + + get [kBusy] () { + return Boolean( + this[kHTTPContext]?.busy(null) || + (this[kSize] >= (getPipelining(this) || 1)) || + this[kPending] > 0 + ) + } + + /* istanbul ignore: only used for test */ + [kConnect] (cb) { + connect(this) + this.once('connect', cb) + } + + [kDispatch] (opts, handler) { + const origin = opts.origin || this[kUrl].origin + const request = new Request(origin, opts, handler) + + this[kQueue].push(request) + if (this[kResuming]) { + // Do nothing. + } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { + // Wait a tick in case stream/iterator is ended in the same tick. + this[kResuming] = 1 + queueMicrotask(() => resume(this)) + } else { + this[kResume](true) + } + + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2 + } + + return this[kNeedDrain] < 2 + } + + async [kClose] () { + // TODO: for H2 we need to gracefully flush the remaining enqueued + // request and close each stream. + return new Promise((resolve) => { + if (this[kSize]) { + this[kClosedResolve] = resolve + } else { + resolve(null) + } + }) + } + + async [kDestroy] (err) { + return new Promise((resolve) => { + const requests = this[kQueue].splice(this[kPendingIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + util.errorRequest(this, request, err) + } + + const callback = () => { + if (this[kClosedResolve]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve]() + this[kClosedResolve] = null + } + resolve(null) + } + + if (this[kHTTPContext]) { + this[kHTTPContext].destroy(err, callback) + this[kHTTPContext] = null + } else { + queueMicrotask(callback) + } + + this[kResume]() + }) + } +} + +const createRedirectInterceptor = require('../interceptor/redirect-interceptor.js') + +function onError (client, err) { + if ( + client[kRunning] === 0 && + err.code !== 'UND_ERR_INFO' && + err.code !== 'UND_ERR_SOCKET' + ) { + // Error is not caused by running request and not a recoverable + // socket error. + + assert(client[kPendingIdx] === client[kRunningIdx]) + + const requests = client[kQueue].splice(client[kRunningIdx]) + + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + util.errorRequest(client, request, err) + } + assert(client[kSize] === 0) + } +} + +/** + * @param {Client} client + * @returns + */ +async function connect (client) { + assert(!client[kConnecting]) + assert(!client[kHTTPContext]) + + let { host, hostname, protocol, port } = client[kUrl] + + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']') + + assert(idx !== -1) + const ip = hostname.substring(1, idx) + + assert(net.isIP(ip)) + hostname = ip + } + + client[kConnecting] = true + + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }) + } + + try { + const socket = await new Promise((resolve, reject) => { + client[kConnector]({ + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, (err, socket) => { + if (err) { + reject(err) + } else { + resolve(socket) + } + }) + }) + + if (client.destroyed) { + util.destroy(socket.on('error', noop), new ClientDestroyedError()) + return + } + + assert(socket) + + try { + client[kHTTPContext] = socket.alpnProtocol === 'h2' + ? await connectH2(client, socket) + : await connectH1(client, socket) + } catch (err) { + socket.destroy().on('error', noop) + throw err + } + + client[kConnecting] = false + + socket[kCounter] = 0 + socket[kMaxRequests] = client[kMaxRequests] + socket[kClient] = client + socket[kError] = null + + if (channels.connected.hasSubscribers) { + channels.connected.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + socket + }) + } + client.emit('connect', client[kUrl], [client]) + } catch (err) { + if (client.destroyed) { + return + } + + client[kConnecting] = false + + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }) + } + + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + assert(client[kRunning] === 0) + while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { + const request = client[kQueue][client[kPendingIdx]++] + util.errorRequest(client, request, err) + } + } else { + onError(client, err) + } + + client.emit('connectionError', client[kUrl], [client], err) + } + + client[kResume]() +} + +function emitDrain (client) { + client[kNeedDrain] = 0 + client.emit('drain', client[kUrl], [client]) +} + +function resume (client, sync) { + if (client[kResuming] === 2) { + return + } + + client[kResuming] = 2 + + _resume(client, sync) + client[kResuming] = 0 + + if (client[kRunningIdx] > 256) { + client[kQueue].splice(0, client[kRunningIdx]) + client[kPendingIdx] -= client[kRunningIdx] + client[kRunningIdx] = 0 + } +} + +function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0) + return + } + + if (client[kClosedResolve] && !client[kSize]) { + client[kClosedResolve]() + client[kClosedResolve] = null + return + } + + if (client[kHTTPContext]) { + client[kHTTPContext].resume() + } + + if (client[kBusy]) { + client[kNeedDrain] = 2 + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1 + queueMicrotask(() => emitDrain(client)) + } else { + emitDrain(client) + } + continue + } + + if (client[kPending] === 0) { + return + } + + if (client[kRunning] >= (getPipelining(client) || 1)) { + return + } + + const request = client[kQueue][client[kPendingIdx]] + + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return + } + + client[kServerName] = request.servername + client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => { + client[kHTTPContext] = null + resume(client) + }) + } + + if (client[kConnecting]) { + return + } + + if (!client[kHTTPContext]) { + connect(client) + return + } + + if (client[kHTTPContext].destroyed) { + return + } + + if (client[kHTTPContext].busy(request)) { + return + } + + if (!request.aborted && client[kHTTPContext].write(request)) { + client[kPendingIdx]++ + } else { + client[kQueue].splice(client[kPendingIdx], 1) + } + } +} + +module.exports = Client diff --git a/node_modules/undici/lib/dispatcher/dispatcher-base.js b/node_modules/undici/lib/dispatcher/dispatcher-base.js new file mode 100644 index 0000000000000..c999b2c2fb674 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/dispatcher-base.js @@ -0,0 +1,198 @@ +'use strict' + +const Dispatcher = require('./dispatcher') +const { + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError +} = require('../core/errors') +const { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = require('../core/symbols') + +const kOnDestroyed = Symbol('onDestroyed') +const kOnClosed = Symbol('onClosed') +const kInterceptedDispatch = Symbol('Intercepted Dispatch') +const kWebSocketOptions = Symbol('webSocketOptions') + +class DispatcherBase extends Dispatcher { + constructor (opts) { + super() + + this[kDestroyed] = false + this[kOnDestroyed] = null + this[kClosed] = false + this[kOnClosed] = [] + this[kWebSocketOptions] = opts?.webSocket ?? {} + } + + get webSocketOptions () { + return { + maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 + } + } + + get destroyed () { + return this[kDestroyed] + } + + get closed () { + return this[kClosed] + } + + get interceptors () { + return this[kInterceptors] + } + + set interceptors (newInterceptors) { + if (newInterceptors) { + for (let i = newInterceptors.length - 1; i >= 0; i--) { + const interceptor = this[kInterceptors][i] + if (typeof interceptor !== 'function') { + throw new InvalidArgumentError('interceptor must be an function') + } + } + } + + this[kInterceptors] = newInterceptors + } + + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError(), null)) + return + } + + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + this[kClosed] = true + this[kOnClosed].push(callback) + + const onClosed = () => { + const callbacks = this[kOnClosed] + this[kOnClosed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kClose]() + .then(() => this.destroy()) + .then(() => { + queueMicrotask(onClosed) + }) + } + + destroy (err, callback) { + if (typeof err === 'function') { + callback = err + err = null + } + + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.destroy(err, (err, data) => { + return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + if (!err) { + err = new ClientDestroyedError() + } + + this[kDestroyed] = true + this[kOnDestroyed] = this[kOnDestroyed] || [] + this[kOnDestroyed].push(callback) + + const onDestroyed = () => { + const callbacks = this[kOnDestroyed] + this[kOnDestroyed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kDestroy](err).then(() => { + queueMicrotask(onDestroyed) + }) + } + + [kInterceptedDispatch] (opts, handler) { + if (!this[kInterceptors] || this[kInterceptors].length === 0) { + this[kInterceptedDispatch] = this[kDispatch] + return this[kDispatch](opts, handler) + } + + let dispatch = this[kDispatch].bind(this) + for (let i = this[kInterceptors].length - 1; i >= 0; i--) { + dispatch = this[kInterceptors][i](dispatch) + } + this[kInterceptedDispatch] = dispatch + return dispatch(opts, handler) + } + + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } + + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError() + } + + if (this[kClosed]) { + throw new ClientClosedError() + } + + return this[kInterceptedDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + handler.onError(err) + + return false + } + } +} + +module.exports = DispatcherBase diff --git a/node_modules/undici/lib/dispatcher/dispatcher.js b/node_modules/undici/lib/dispatcher/dispatcher.js new file mode 100644 index 0000000000000..b1e0098ec4b66 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/dispatcher.js @@ -0,0 +1,65 @@ +'use strict' +const EventEmitter = require('node:events') + +class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') + } + + close () { + throw new Error('not implemented') + } + + destroy () { + throw new Error('not implemented') + } + + compose (...args) { + // So we handle [interceptor1, interceptor2] or interceptor1, interceptor2, ... + const interceptors = Array.isArray(args[0]) ? args[0] : args + let dispatch = this.dispatch.bind(this) + + for (const interceptor of interceptors) { + if (interceptor == null) { + continue + } + + if (typeof interceptor !== 'function') { + throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`) + } + + dispatch = interceptor(dispatch) + + if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) { + throw new TypeError('invalid interceptor') + } + } + + return new ComposedDispatcher(this, dispatch) + } +} + +class ComposedDispatcher extends Dispatcher { + #dispatcher = null + #dispatch = null + + constructor (dispatcher, dispatch) { + super() + this.#dispatcher = dispatcher + this.#dispatch = dispatch + } + + dispatch (...args) { + this.#dispatch(...args) + } + + close (...args) { + return this.#dispatcher.close(...args) + } + + destroy (...args) { + return this.#dispatcher.destroy(...args) + } +} + +module.exports = Dispatcher diff --git a/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js b/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js new file mode 100644 index 0000000000000..897011adbcd63 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js @@ -0,0 +1,160 @@ +'use strict' + +const DispatcherBase = require('./dispatcher-base') +const { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require('../core/symbols') +const ProxyAgent = require('./proxy-agent') +const Agent = require('./agent') + +const DEFAULT_PORTS = { + 'http:': 80, + 'https:': 443 +} + +let experimentalWarned = false + +class EnvHttpProxyAgent extends DispatcherBase { + #noProxyValue = null + #noProxyEntries = null + #opts = null + + constructor (opts = {}) { + super() + this.#opts = opts + + if (!experimentalWarned) { + experimentalWarned = true + process.emitWarning('EnvHttpProxyAgent is experimental, expect them to change at any time.', { + code: 'UNDICI-EHPA' + }) + } + + const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts + + this[kNoProxyAgent] = new Agent(agentOpts) + + const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY + if (HTTP_PROXY) { + this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY }) + } else { + this[kHttpProxyAgent] = this[kNoProxyAgent] + } + + const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY + if (HTTPS_PROXY) { + this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY }) + } else { + this[kHttpsProxyAgent] = this[kHttpProxyAgent] + } + + this.#parseNoProxy() + } + + [kDispatch] (opts, handler) { + const url = new URL(opts.origin) + const agent = this.#getProxyAgentForUrl(url) + return agent.dispatch(opts, handler) + } + + async [kClose] () { + await this[kNoProxyAgent].close() + if (!this[kHttpProxyAgent][kClosed]) { + await this[kHttpProxyAgent].close() + } + if (!this[kHttpsProxyAgent][kClosed]) { + await this[kHttpsProxyAgent].close() + } + } + + async [kDestroy] (err) { + await this[kNoProxyAgent].destroy(err) + if (!this[kHttpProxyAgent][kDestroyed]) { + await this[kHttpProxyAgent].destroy(err) + } + if (!this[kHttpsProxyAgent][kDestroyed]) { + await this[kHttpsProxyAgent].destroy(err) + } + } + + #getProxyAgentForUrl (url) { + let { protocol, host: hostname, port } = url + + // Stripping ports in this way instead of using parsedUrl.hostname to make + // sure that the brackets around IPv6 addresses are kept. + hostname = hostname.replace(/:\d*$/, '').toLowerCase() + port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0 + if (!this.#shouldProxy(hostname, port)) { + return this[kNoProxyAgent] + } + if (protocol === 'https:') { + return this[kHttpsProxyAgent] + } + return this[kHttpProxyAgent] + } + + #shouldProxy (hostname, port) { + if (this.#noProxyChanged) { + this.#parseNoProxy() + } + + if (this.#noProxyEntries.length === 0) { + return true // Always proxy if NO_PROXY is not set or empty. + } + if (this.#noProxyValue === '*') { + return false // Never proxy if wildcard is set. + } + + for (let i = 0; i < this.#noProxyEntries.length; i++) { + const entry = this.#noProxyEntries[i] + if (entry.port && entry.port !== port) { + continue // Skip if ports don't match. + } + if (!/^[.*]/.test(entry.hostname)) { + // No wildcards, so don't proxy only if there is not an exact match. + if (hostname === entry.hostname) { + return false + } + } else { + // Don't proxy if the hostname ends with the no_proxy host. + if (hostname.endsWith(entry.hostname.replace(/^\*/, ''))) { + return false + } + } + } + + return true + } + + #parseNoProxy () { + const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv + const noProxySplit = noProxyValue.split(/[,\s]/) + const noProxyEntries = [] + + for (let i = 0; i < noProxySplit.length; i++) { + const entry = noProxySplit[i] + if (!entry) { + continue + } + const parsed = entry.match(/^(.+):(\d+)$/) + noProxyEntries.push({ + hostname: (parsed ? parsed[1] : entry).toLowerCase(), + port: parsed ? Number.parseInt(parsed[2], 10) : 0 + }) + } + + this.#noProxyValue = noProxyValue + this.#noProxyEntries = noProxyEntries + } + + get #noProxyChanged () { + if (this.#opts.noProxy !== undefined) { + return false + } + return this.#noProxyValue !== this.#noProxyEnv + } + + get #noProxyEnv () { + return process.env.no_proxy ?? process.env.NO_PROXY ?? '' + } +} + +module.exports = EnvHttpProxyAgent diff --git a/node_modules/undici/lib/dispatcher/fixed-queue.js b/node_modules/undici/lib/dispatcher/fixed-queue.js new file mode 100644 index 0000000000000..35726819e925a --- /dev/null +++ b/node_modules/undici/lib/dispatcher/fixed-queue.js @@ -0,0 +1,117 @@ +/* eslint-disable */ + +'use strict' + +// Extracted from node/lib/internal/fixed_queue.js + +// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. +const kSize = 2048; +const kMask = kSize - 1; + +// The FixedQueue is implemented as a singly-linked list of fixed-size +// circular buffers. It looks something like this: +// +// head tail +// | | +// v v +// +-----------+ <-----\ +-----------+ <------\ +-----------+ +// | [null] | \----- | next | \------- | next | +// +-----------+ +-----------+ +-----------+ +// | item | <-- bottom | item | <-- bottom | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | bottom --> | item | +// | item | | item | | item | +// | ... | | ... | | ... | +// | item | | item | | item | +// | item | | item | | item | +// | [empty] | <-- top | item | | item | +// | [empty] | | item | | item | +// | [empty] | | [empty] | <-- top top --> | [empty] | +// +-----------+ +-----------+ +-----------+ +// +// Or, if there is only one circular buffer, it looks something +// like either of these: +// +// head tail head tail +// | | | | +// v v v v +// +-----------+ +-----------+ +// | [null] | | [null] | +// +-----------+ +-----------+ +// | [empty] | | item | +// | [empty] | | item | +// | item | <-- bottom top --> | [empty] | +// | item | | [empty] | +// | [empty] | <-- top bottom --> | item | +// | [empty] | | item | +// +-----------+ +-----------+ +// +// Adding a value means moving `top` forward by one, removing means +// moving `bottom` forward by one. After reaching the end, the queue +// wraps around. +// +// When `top === bottom` the current queue is empty and when +// `top + 1 === bottom` it's full. This wastes a single space of storage +// but allows much quicker checks. + +class FixedCircularBuffer { + constructor() { + this.bottom = 0; + this.top = 0; + this.list = new Array(kSize); + this.next = null; + } + + isEmpty() { + return this.top === this.bottom; + } + + isFull() { + return ((this.top + 1) & kMask) === this.bottom; + } + + push(data) { + this.list[this.top] = data; + this.top = (this.top + 1) & kMask; + } + + shift() { + const nextItem = this.list[this.bottom]; + if (nextItem === undefined) + return null; + this.list[this.bottom] = undefined; + this.bottom = (this.bottom + 1) & kMask; + return nextItem; + } +} + +module.exports = class FixedQueue { + constructor() { + this.head = this.tail = new FixedCircularBuffer(); + } + + isEmpty() { + return this.head.isEmpty(); + } + + push(data) { + if (this.head.isFull()) { + // Head is full: Creates a new queue, sets the old queue's `.next` to it, + // and sets it as the new main queue. + this.head = this.head.next = new FixedCircularBuffer(); + } + this.head.push(data); + } + + shift() { + const tail = this.tail; + const next = tail.shift(); + if (tail.isEmpty() && tail.next !== null) { + // If there is another queue, it forms the new tail. + this.tail = tail.next; + } + return next; + } +}; diff --git a/node_modules/undici/lib/dispatcher/pool-base.js b/node_modules/undici/lib/dispatcher/pool-base.js new file mode 100644 index 0000000000000..6f9ec5e120b72 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/pool-base.js @@ -0,0 +1,194 @@ +'use strict' + +const DispatcherBase = require('./dispatcher-base') +const FixedQueue = require('./fixed-queue') +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('../core/symbols') +const PoolStats = require('./pool-stats') + +const kClients = Symbol('clients') +const kNeedDrain = Symbol('needDrain') +const kQueue = Symbol('queue') +const kClosedResolve = Symbol('closed resolve') +const kOnDrain = Symbol('onDrain') +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kGetDispatcher = Symbol('get dispatcher') +const kAddClient = Symbol('add client') +const kRemoveClient = Symbol('remove client') +const kStats = Symbol('stats') + +class PoolBase extends DispatcherBase { + constructor (opts) { + super(opts) + + this[kQueue] = new FixedQueue() + this[kClients] = [] + this[kQueued] = 0 + + const pool = this + + this[kOnDrain] = function onDrain (origin, targets) { + const queue = pool[kQueue] + + let needDrain = false + + while (!needDrain) { + const item = queue.shift() + if (!item) { + break + } + pool[kQueued]-- + needDrain = !this.dispatch(item.opts, item.handler) + } + + this[kNeedDrain] = needDrain + + if (!this[kNeedDrain] && pool[kNeedDrain]) { + pool[kNeedDrain] = false + pool.emit('drain', origin, [pool, ...targets]) + } + + if (pool[kClosedResolve] && queue.isEmpty()) { + Promise + .all(pool[kClients].map(c => c.close())) + .then(pool[kClosedResolve]) + } + } + + this[kOnConnect] = (origin, targets) => { + pool.emit('connect', origin, [pool, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + pool.emit('disconnect', origin, [pool, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + pool.emit('connectionError', origin, [pool, ...targets], err) + } + + this[kStats] = new PoolStats(this) + } + + get [kBusy] () { + return this[kNeedDrain] + } + + get [kConnected] () { + return this[kClients].filter(client => client[kConnected]).length + } + + get [kFree] () { + return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length + } + + get [kPending] () { + let ret = this[kQueued] + for (const { [kPending]: pending } of this[kClients]) { + ret += pending + } + return ret + } + + get [kRunning] () { + let ret = 0 + for (const { [kRunning]: running } of this[kClients]) { + ret += running + } + return ret + } + + get [kSize] () { + let ret = this[kQueued] + for (const { [kSize]: size } of this[kClients]) { + ret += size + } + return ret + } + + get stats () { + return this[kStats] + } + + async [kClose] () { + if (this[kQueue].isEmpty()) { + await Promise.all(this[kClients].map(c => c.close())) + } else { + await new Promise((resolve) => { + this[kClosedResolve] = resolve + }) + } + } + + async [kDestroy] (err) { + while (true) { + const item = this[kQueue].shift() + if (!item) { + break + } + item.handler.onError(err) + } + + await Promise.all(this[kClients].map(c => c.destroy(err))) + } + + [kDispatch] (opts, handler) { + const dispatcher = this[kGetDispatcher]() + + if (!dispatcher) { + this[kNeedDrain] = true + this[kQueue].push({ opts, handler }) + this[kQueued]++ + } else if (!dispatcher.dispatch(opts, handler)) { + dispatcher[kNeedDrain] = true + this[kNeedDrain] = !this[kGetDispatcher]() + } + + return !this[kNeedDrain] + } + + [kAddClient] (client) { + client + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].push(client) + + if (this[kNeedDrain]) { + queueMicrotask(() => { + if (this[kNeedDrain]) { + this[kOnDrain](client[kUrl], [this, client]) + } + }) + } + + return this + } + + [kRemoveClient] (client) { + client.close(() => { + const idx = this[kClients].indexOf(client) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + }) + + this[kNeedDrain] = this[kClients].some(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + } +} + +module.exports = { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} diff --git a/node_modules/undici/lib/dispatcher/pool-stats.js b/node_modules/undici/lib/dispatcher/pool-stats.js new file mode 100644 index 0000000000000..8c7e8c9572e1f --- /dev/null +++ b/node_modules/undici/lib/dispatcher/pool-stats.js @@ -0,0 +1,34 @@ +const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = require('../core/symbols') +const kPool = Symbol('pool') + +class PoolStats { + constructor (pool) { + this[kPool] = pool + } + + get connected () { + return this[kPool][kConnected] + } + + get free () { + return this[kPool][kFree] + } + + get pending () { + return this[kPool][kPending] + } + + get queued () { + return this[kPool][kQueued] + } + + get running () { + return this[kPool][kRunning] + } + + get size () { + return this[kPool][kSize] + } +} + +module.exports = PoolStats diff --git a/node_modules/undici/lib/dispatcher/pool.js b/node_modules/undici/lib/dispatcher/pool.js new file mode 100644 index 0000000000000..9eaf3fd03a983 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/pool.js @@ -0,0 +1,107 @@ +'use strict' + +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kGetDispatcher +} = require('./pool-base') +const Client = require('./client') +const { + InvalidArgumentError +} = require('../core/errors') +const util = require('../core/util') +const { kUrl, kInterceptors } = require('../core/symbols') +const buildConnector = require('../core/connect') + +const kOptions = Symbol('options') +const kConnections = Symbol('connections') +const kFactory = Symbol('factory') + +function defaultFactory (origin, opts) { + return new Client(origin, opts) +} + +class Pool extends PoolBase { + constructor (origin, { + connections, + factory = defaultFactory, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + allowH2, + ...options + } = {}) { + if (connections != null && (!Number.isFinite(connections) || connections < 0)) { + throw new InvalidArgumentError('invalid connections') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + super(options) + + this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) + ? options.interceptors.Pool + : [] + this[kConnections] = connections || null + this[kUrl] = util.parseOrigin(origin) + this[kOptions] = { ...util.deepClone(options), connect, allowH2 } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kFactory] = factory + + this.on('connectionError', (origin, targets, error) => { + // If a connection error occurs, we remove the client from the pool, + // and emit a connectionError event. They will not be re-used. + // Fixes https://github.com/nodejs/undici/issues/3895 + for (const target of targets) { + // Do not use kRemoveClient here, as it will close the client, + // but the client cannot be closed in this state. + const idx = this[kClients].indexOf(target) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + } + }) + } + + [kGetDispatcher] () { + for (const client of this[kClients]) { + if (!client[kNeedDrain]) { + return client + } + } + + if (!this[kConnections] || this[kClients].length < this[kConnections]) { + const dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + return dispatcher + } + } +} + +module.exports = Pool diff --git a/node_modules/undici/lib/dispatcher/proxy-agent.js b/node_modules/undici/lib/dispatcher/proxy-agent.js new file mode 100644 index 0000000000000..fed1803890923 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/proxy-agent.js @@ -0,0 +1,274 @@ +'use strict' + +const { kProxy, kClose, kDestroy, kDispatch, kInterceptors } = require('../core/symbols') +const { URL } = require('node:url') +const Agent = require('./agent') +const Pool = require('./pool') +const DispatcherBase = require('./dispatcher-base') +const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require('../core/errors') +const buildConnector = require('../core/connect') +const Client = require('./client') + +const kAgent = Symbol('proxy agent') +const kClient = Symbol('proxy client') +const kProxyHeaders = Symbol('proxy headers') +const kRequestTls = Symbol('request tls settings') +const kProxyTls = Symbol('proxy tls settings') +const kConnectEndpoint = Symbol('connect endpoint function') +const kTunnelProxy = Symbol('tunnel proxy') + +function defaultProtocolPort (protocol) { + return protocol === 'https:' ? 443 : 80 +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +const noop = () => {} + +function defaultAgentFactory (origin, opts) { + if (opts.connections === 1) { + return new Client(origin, opts) + } + return new Pool(origin, opts) +} + +class Http1ProxyWrapper extends DispatcherBase { + #client + + constructor (proxyUrl, { headers = {}, connect, factory }) { + super() + if (!proxyUrl) { + throw new InvalidArgumentError('Proxy URL is mandatory') + } + + this[kProxyHeaders] = headers + if (factory) { + this.#client = factory(proxyUrl, { connect }) + } else { + this.#client = new Client(proxyUrl, { connect }) + } + } + + [kDispatch] (opts, handler) { + const onHeaders = handler.onHeaders + handler.onHeaders = function (statusCode, data, resume) { + if (statusCode === 407) { + if (typeof handler.onError === 'function') { + handler.onError(new InvalidArgumentError('Proxy Authentication Required (407)')) + } + return + } + if (onHeaders) onHeaders.call(this, statusCode, data, resume) + } + + // Rewrite request as an HTTP1 Proxy request, without tunneling. + const { + origin, + path = '/', + headers = {} + } = opts + + opts.path = origin + path + + if (!('host' in headers) && !('Host' in headers)) { + const { host } = new URL(origin) + headers.host = host + } + opts.headers = { ...this[kProxyHeaders], ...headers } + + return this.#client[kDispatch](opts, handler) + } + + async [kClose] () { + return this.#client.close() + } + + async [kDestroy] (err) { + return this.#client.destroy(err) + } +} + +class ProxyAgent extends DispatcherBase { + constructor (opts) { + super() + + if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) { + throw new InvalidArgumentError('Proxy uri is mandatory') + } + + const { clientFactory = defaultFactory } = opts + if (typeof clientFactory !== 'function') { + throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') + } + + const { proxyTunnel = true } = opts + + const url = this.#getUrl(opts) + const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url + + this[kProxy] = { uri: href, protocol } + this[kInterceptors] = opts.interceptors?.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) + ? opts.interceptors.ProxyAgent + : [] + this[kRequestTls] = opts.requestTls + this[kProxyTls] = opts.proxyTls + this[kProxyHeaders] = opts.headers || {} + this[kTunnelProxy] = proxyTunnel + + if (opts.auth && opts.token) { + throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') + } else if (opts.auth) { + /* @deprecated in favour of opts.token */ + this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` + } else if (opts.token) { + this[kProxyHeaders]['proxy-authorization'] = opts.token + } else if (username && password) { + this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` + } + + const connect = buildConnector({ ...opts.proxyTls }) + this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) + + const agentFactory = opts.factory || defaultAgentFactory + const factory = (origin, options) => { + const { protocol } = new URL(origin) + if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') { + return new Http1ProxyWrapper(this[kProxy].uri, { + headers: this[kProxyHeaders], + connect, + factory: agentFactory + }) + } + return agentFactory(origin, options) + } + this[kClient] = clientFactory(url, { connect }) + this[kAgent] = new Agent({ + ...opts, + factory, + connect: async (opts, callback) => { + let requestedPath = opts.host + if (!opts.port) { + requestedPath += `:${defaultProtocolPort(opts.protocol)}` + } + try { + const { socket, statusCode } = await this[kClient].connect({ + origin, + port, + path: requestedPath, + signal: opts.signal, + headers: { + ...this[kProxyHeaders], + host: opts.host + }, + servername: this[kProxyTls]?.servername || proxyHostname + }) + if (statusCode !== 200) { + socket.on('error', noop).destroy() + callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) + } + if (opts.protocol !== 'https:') { + callback(null, socket) + return + } + let servername + if (this[kRequestTls]) { + servername = this[kRequestTls].servername + } else { + servername = opts.servername + } + this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) + } catch (err) { + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + // Throw a custom error to avoid loop in client.js#connect + callback(new SecureProxyConnectionError(err)) + } else { + callback(err) + } + } + } + }) + } + + dispatch (opts, handler) { + const headers = buildHeaders(opts.headers) + throwIfProxyAuthIsSent(headers) + + if (headers && !('host' in headers) && !('Host' in headers)) { + const { host } = new URL(opts.origin) + headers.host = host + } + + return this[kAgent].dispatch( + { + ...opts, + headers + }, + handler + ) + } + + /** + * @param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts + * @returns {URL} + */ + #getUrl (opts) { + if (typeof opts === 'string') { + return new URL(opts) + } else if (opts instanceof URL) { + return opts + } else { + return new URL(opts.uri) + } + } + + async [kClose] () { + await this[kAgent].close() + await this[kClient].close() + } + + async [kDestroy] () { + await this[kAgent].destroy() + await this[kClient].destroy() + } +} + +/** + * @param {string[] | Record} headers + * @returns {Record} + */ +function buildHeaders (headers) { + // When using undici.fetch, the headers list is stored + // as an array. + if (Array.isArray(headers)) { + /** @type {Record} */ + const headersPair = {} + + for (let i = 0; i < headers.length; i += 2) { + headersPair[headers[i]] = headers[i + 1] + } + + return headersPair + } + + return headers +} + +/** + * @param {Record} headers + * + * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers + * Nevertheless, it was changed and to avoid a security vulnerability by end users + * this check was created. + * It should be removed in the next major version for performance reasons + */ +function throwIfProxyAuthIsSent (headers) { + const existProxyAuth = headers && Object.keys(headers) + .find((key) => key.toLowerCase() === 'proxy-authorization') + if (existProxyAuth) { + throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') + } +} + +module.exports = ProxyAgent diff --git a/node_modules/undici/lib/dispatcher/retry-agent.js b/node_modules/undici/lib/dispatcher/retry-agent.js new file mode 100644 index 0000000000000..0c2120d6f26a2 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/retry-agent.js @@ -0,0 +1,35 @@ +'use strict' + +const Dispatcher = require('./dispatcher') +const RetryHandler = require('../handler/retry-handler') + +class RetryAgent extends Dispatcher { + #agent = null + #options = null + constructor (agent, options = {}) { + super(options) + this.#agent = agent + this.#options = options + } + + dispatch (opts, handler) { + const retry = new RetryHandler({ + ...opts, + retryOptions: this.#options + }, { + dispatch: this.#agent.dispatch.bind(this.#agent), + handler + }) + return this.#agent.dispatch(opts, retry) + } + + close () { + return this.#agent.close() + } + + destroy () { + return this.#agent.destroy() + } +} + +module.exports = RetryAgent diff --git a/node_modules/undici/lib/global.js b/node_modules/undici/lib/global.js new file mode 100644 index 0000000000000..0c7528fa65316 --- /dev/null +++ b/node_modules/undici/lib/global.js @@ -0,0 +1,32 @@ +'use strict' + +// We include a version number for the Dispatcher API. In case of breaking changes, +// this version number must be increased to avoid conflicts. +const globalDispatcher = Symbol.for('undici.globalDispatcher.1') +const { InvalidArgumentError } = require('./core/errors') +const Agent = require('./dispatcher/agent') + +if (getGlobalDispatcher() === undefined) { + setGlobalDispatcher(new Agent()) +} + +function setGlobalDispatcher (agent) { + if (!agent || typeof agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument agent must implement Agent') + } + Object.defineProperty(globalThis, globalDispatcher, { + value: agent, + writable: true, + enumerable: false, + configurable: false + }) +} + +function getGlobalDispatcher () { + return globalThis[globalDispatcher] +} + +module.exports = { + setGlobalDispatcher, + getGlobalDispatcher +} diff --git a/node_modules/undici/lib/handler/decorator-handler.js b/node_modules/undici/lib/handler/decorator-handler.js new file mode 100644 index 0000000000000..26f220c64cd1f --- /dev/null +++ b/node_modules/undici/lib/handler/decorator-handler.js @@ -0,0 +1,44 @@ +'use strict' + +module.exports = class DecoratorHandler { + #handler + + constructor (handler) { + if (typeof handler !== 'object' || handler === null) { + throw new TypeError('handler must be an object') + } + this.#handler = handler + } + + onConnect (...args) { + return this.#handler.onConnect?.(...args) + } + + onError (...args) { + return this.#handler.onError?.(...args) + } + + onUpgrade (...args) { + return this.#handler.onUpgrade?.(...args) + } + + onResponseStarted (...args) { + return this.#handler.onResponseStarted?.(...args) + } + + onHeaders (...args) { + return this.#handler.onHeaders?.(...args) + } + + onData (...args) { + return this.#handler.onData?.(...args) + } + + onComplete (...args) { + return this.#handler.onComplete?.(...args) + } + + onBodySent (...args) { + return this.#handler.onBodySent?.(...args) + } +} diff --git a/node_modules/undici/lib/handler/redirect-handler.js b/node_modules/undici/lib/handler/redirect-handler.js new file mode 100644 index 0000000000000..16a7b2150a9de --- /dev/null +++ b/node_modules/undici/lib/handler/redirect-handler.js @@ -0,0 +1,232 @@ +'use strict' + +const util = require('../core/util') +const { kBodyUsed } = require('../core/symbols') +const assert = require('node:assert') +const { InvalidArgumentError } = require('../core/errors') +const EE = require('node:events') + +const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] + +const kBody = Symbol('body') + +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false + } + + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] + } +} + +class RedirectHandler { + constructor (dispatch, maxRedirections, opts, handler) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + util.validateHandler(handler, opts.method, opts.upgrade) + + this.dispatch = dispatch + this.location = null + this.abort = null + this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy + this.maxRedirections = maxRedirections + this.handler = handler + this.history = [] + this.redirectionLimitReached = false + + if (util.isStream(this.opts.body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (util.bodyLength(this.opts.body) === 0) { + this.opts.body + .on('data', function () { + assert(false) + }) + } + + if (typeof this.opts.body.readableDidRead !== 'boolean') { + this.opts.body[kBodyUsed] = false + EE.prototype.on.call(this.opts.body, 'data', function () { + this[kBodyUsed] = true + }) + } + } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + this.opts.body = new BodyAsyncIterable(this.opts.body) + } else if ( + this.opts.body && + typeof this.opts.body !== 'string' && + !ArrayBuffer.isView(this.opts.body) && + util.isIterable(this.opts.body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + this.opts.body = new BodyAsyncIterable(this.opts.body) + } + } + + onConnect (abort) { + this.abort = abort + this.handler.onConnect(abort, { history: this.history }) + } + + onUpgrade (statusCode, headers, socket) { + this.handler.onUpgrade(statusCode, headers, socket) + } + + onError (error) { + this.handler.onError(error) + } + + onHeaders (statusCode, headers, resume, statusText) { + this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) + ? null + : parseLocation(statusCode, headers) + + if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) { + if (this.request) { + this.request.abort(new Error('max redirects')) + } + + this.redirectionLimitReached = true + this.abort(new Error('max redirects')) + return + } + + if (this.opts.origin) { + this.history.push(new URL(this.opts.path, this.opts.origin)) + } + + if (!this.location) { + return this.handler.onHeaders(statusCode, headers, resume, statusText) + } + + const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) + const path = search ? `${pathname}${search}` : pathname + + // Remove headers referring to the original URL. + // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. + // https://tools.ietf.org/html/rfc7231#section-6.4 + this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) + this.opts.path = path + this.opts.origin = origin + this.opts.maxRedirections = 0 + this.opts.query = null + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + // In case of HTTP 303, always replace method to be either HEAD or GET + if (statusCode === 303 && this.opts.method !== 'HEAD') { + this.opts.method = 'GET' + this.opts.body = null + } + } + + onData (chunk) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response bodies. + + Redirection is used to serve the requested resource from another URL, so it is assumes that + no body is generated (and thus can be ignored). Even though generating a body is not prohibited. + + For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually + (which means it's optional and not mandated) contain just an hyperlink to the value of + the Location response header, so the body can be ignored safely. + + For status 300, which is "Multiple Choices", the spec mentions both generating a Location + response header AND a response body with the other possible location to follow. + Since the spec explicitly chooses not to specify a format for such body and leave it to + servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. + */ + } else { + return this.handler.onData(chunk) + } + } + + onComplete (trailers) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections + and neither are useful if present. + + See comment on onData method above for more detailed information. + */ + + this.location = null + this.abort = null + + this.dispatch(this.opts, this) + } else { + this.handler.onComplete(trailers) + } + } + + onBodySent (chunk) { + if (this.handler.onBodySent) { + this.handler.onBodySent(chunk) + } + } +} + +function parseLocation (statusCode, headers) { + if (redirectableStatusCodes.indexOf(statusCode) === -1) { + return null + } + + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].length === 8 && util.headerNameToString(headers[i]) === 'location') { + return headers[i + 1] + } + } +} + +// https://tools.ietf.org/html/rfc7231#section-6.4.4 +function shouldRemoveHeader (header, removeContent, unknownOrigin) { + if (header.length === 4) { + return util.headerNameToString(header) === 'host' + } + if (removeContent && util.headerNameToString(header).startsWith('content-')) { + return true + } + if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { + const name = util.headerNameToString(header) + return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' + } + return false +} + +// https://tools.ietf.org/html/rfc7231#section-6.4 +function cleanRequestHeaders (headers, removeContent, unknownOrigin) { + const ret = [] + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { + ret.push(headers[i], headers[i + 1]) + } + } + } else if (headers && typeof headers === 'object') { + for (const key of Object.keys(headers)) { + if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { + ret.push(key, headers[key]) + } + } + } else { + assert(headers == null, 'headers must be an object or an array') + } + return ret +} + +module.exports = RedirectHandler diff --git a/node_modules/undici/lib/handler/retry-handler.js b/node_modules/undici/lib/handler/retry-handler.js new file mode 100644 index 0000000000000..5d1ccf0053876 --- /dev/null +++ b/node_modules/undici/lib/handler/retry-handler.js @@ -0,0 +1,374 @@ +'use strict' +const assert = require('node:assert') + +const { kRetryHandlerDefaultRetry } = require('../core/symbols') +const { RequestRetryError } = require('../core/errors') +const { + isDisturbed, + parseHeaders, + parseRangeHeader, + wrapRequestBody +} = require('../core/util') + +function calculateRetryAfterHeader (retryAfter) { + const current = Date.now() + return new Date(retryAfter).getTime() - current +} + +class RetryHandler { + constructor (opts, handlers) { + const { retryOptions, ...dispatchOpts } = opts + const { + // Retry scoped + retry: retryFn, + maxRetries, + maxTimeout, + minTimeout, + timeoutFactor, + // Response scoped + methods, + errorCodes, + retryAfter, + statusCodes + } = retryOptions ?? {} + + this.dispatch = handlers.dispatch + this.handler = handlers.handler + this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) } + this.abort = null + this.aborted = false + this.retryOpts = { + retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], + retryAfter: retryAfter ?? true, + maxTimeout: maxTimeout ?? 30 * 1000, // 30s, + minTimeout: minTimeout ?? 500, // .5s + timeoutFactor: timeoutFactor ?? 2, + maxRetries: maxRetries ?? 5, + // What errors we should retry + methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + // Indicates which errors to retry + statusCodes: statusCodes ?? [500, 502, 503, 504, 429], + // List of errors to retry + errorCodes: errorCodes ?? [ + 'ECONNRESET', + 'ECONNREFUSED', + 'ENOTFOUND', + 'ENETDOWN', + 'ENETUNREACH', + 'EHOSTDOWN', + 'EHOSTUNREACH', + 'EPIPE', + 'UND_ERR_SOCKET' + ] + } + + this.retryCount = 0 + this.retryCountCheckpoint = 0 + this.start = 0 + this.end = null + this.etag = null + this.resume = null + + // Handle possible onConnect duplication + this.handler.onConnect(reason => { + this.aborted = true + if (this.abort) { + this.abort(reason) + } else { + this.reason = reason + } + }) + } + + onRequestSent () { + if (this.handler.onRequestSent) { + this.handler.onRequestSent() + } + } + + onUpgrade (statusCode, headers, socket) { + if (this.handler.onUpgrade) { + this.handler.onUpgrade(statusCode, headers, socket) + } + } + + onConnect (abort) { + if (this.aborted) { + abort(this.reason) + } else { + this.abort = abort + } + } + + onBodySent (chunk) { + if (this.handler.onBodySent) return this.handler.onBodySent(chunk) + } + + static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { + const { statusCode, code, headers } = err + const { method, retryOptions } = opts + const { + maxRetries, + minTimeout, + maxTimeout, + timeoutFactor, + statusCodes, + errorCodes, + methods + } = retryOptions + const { counter } = state + + // Any code that is not a Undici's originated and allowed to retry + if (code && code !== 'UND_ERR_REQ_RETRY' && !errorCodes.includes(code)) { + cb(err) + return + } + + // If a set of method are provided and the current method is not in the list + if (Array.isArray(methods) && !methods.includes(method)) { + cb(err) + return + } + + // If a set of status code are provided and the current status code is not in the list + if ( + statusCode != null && + Array.isArray(statusCodes) && + !statusCodes.includes(statusCode) + ) { + cb(err) + return + } + + // If we reached the max number of retries + if (counter > maxRetries) { + cb(err) + return + } + + let retryAfterHeader = headers?.['retry-after'] + if (retryAfterHeader) { + retryAfterHeader = Number(retryAfterHeader) + retryAfterHeader = Number.isNaN(retryAfterHeader) + ? calculateRetryAfterHeader(retryAfterHeader) + : retryAfterHeader * 1e3 // Retry-After is in seconds + } + + const retryTimeout = + retryAfterHeader > 0 + ? Math.min(retryAfterHeader, maxTimeout) + : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout) + + setTimeout(() => cb(null), retryTimeout) + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const headers = parseHeaders(rawHeaders) + + this.retryCount += 1 + + if (statusCode >= 300) { + if (this.retryOpts.statusCodes.includes(statusCode) === false) { + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } else { + this.abort( + new RequestRetryError('Request failed', statusCode, { + headers, + data: { + count: this.retryCount + } + }) + ) + return false + } + } + + // Checkpoint for resume from where we left it + if (this.resume != null) { + this.resume = null + + // Only Partial Content 206 supposed to provide Content-Range, + // any other status code that partially consumed the payload + // should not be retry because it would result in downstream + // wrongly concatanete multiple responses. + if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) { + this.abort( + new RequestRetryError('server does not support the range header and the payload was partially consumed', statusCode, { + headers, + data: { count: this.retryCount } + }) + ) + return false + } + + const contentRange = parseRangeHeader(headers['content-range']) + // If no content range + if (!contentRange) { + this.abort( + new RequestRetryError('Content-Range mismatch', statusCode, { + headers, + data: { count: this.retryCount } + }) + ) + return false + } + + // Let's start with a weak etag check + if (this.etag != null && this.etag !== headers.etag) { + this.abort( + new RequestRetryError('ETag mismatch', statusCode, { + headers, + data: { count: this.retryCount } + }) + ) + return false + } + + const { start, size, end = size - 1 } = contentRange + + assert(this.start === start, 'content-range mismatch') + assert(this.end == null || this.end === end, 'content-range mismatch') + + this.resume = resume + return true + } + + if (this.end == null) { + if (statusCode === 206) { + // First time we receive 206 + const range = parseRangeHeader(headers['content-range']) + + if (range == null) { + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } + + const { start, size, end = size - 1 } = range + assert( + start != null && Number.isFinite(start), + 'content-range mismatch' + ) + assert(end != null && Number.isFinite(end), 'invalid content-length') + + this.start = start + this.end = end + } + + // We make our best to checkpoint the body for further range headers + if (this.end == null) { + const contentLength = headers['content-length'] + this.end = contentLength != null ? Number(contentLength) - 1 : null + } + + assert(Number.isFinite(this.start)) + assert( + this.end == null || Number.isFinite(this.end), + 'invalid content-length' + ) + + this.resume = resume + this.etag = headers.etag != null ? headers.etag : null + + // Weak etags are not useful for comparison nor cache + // for instance not safe to assume if the response is byte-per-byte + // equal + if (this.etag != null && this.etag.startsWith('W/')) { + this.etag = null + } + + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } + + const err = new RequestRetryError('Request failed', statusCode, { + headers, + data: { count: this.retryCount } + }) + + this.abort(err) + + return false + } + + onData (chunk) { + this.start += chunk.length + + return this.handler.onData(chunk) + } + + onComplete (rawTrailers) { + this.retryCount = 0 + return this.handler.onComplete(rawTrailers) + } + + onError (err) { + if (this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) + } + + // We reconcile in case of a mix between network errors + // and server error response + if (this.retryCount - this.retryCountCheckpoint > 0) { + // We count the difference between the last checkpoint and the current retry count + this.retryCount = + this.retryCountCheckpoint + + (this.retryCount - this.retryCountCheckpoint) + } else { + this.retryCount += 1 + } + + this.retryOpts.retry( + err, + { + state: { counter: this.retryCount }, + opts: { retryOptions: this.retryOpts, ...this.opts } + }, + onRetry.bind(this) + ) + + function onRetry (err) { + if (err != null || this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) + } + + if (this.start !== 0) { + const headers = { range: `bytes=${this.start}-${this.end ?? ''}` } + + // Weak etag check - weak etags will make comparison algorithms never match + if (this.etag != null) { + headers['if-match'] = this.etag + } + + this.opts = { + ...this.opts, + headers: { + ...this.opts.headers, + ...headers + } + } + } + + try { + this.retryCountCheckpoint = this.retryCount + this.dispatch(this.opts, this) + } catch (err) { + this.handler.onError(err) + } + } + } +} + +module.exports = RetryHandler diff --git a/node_modules/undici/lib/interceptor/dns.js b/node_modules/undici/lib/interceptor/dns.js new file mode 100644 index 0000000000000..917732646e64a --- /dev/null +++ b/node_modules/undici/lib/interceptor/dns.js @@ -0,0 +1,375 @@ +'use strict' +const { isIP } = require('node:net') +const { lookup } = require('node:dns') +const DecoratorHandler = require('../handler/decorator-handler') +const { InvalidArgumentError, InformationalError } = require('../core/errors') +const maxInt = Math.pow(2, 31) - 1 + +class DNSInstance { + #maxTTL = 0 + #maxItems = 0 + #records = new Map() + dualStack = true + affinity = null + lookup = null + pick = null + + constructor (opts) { + this.#maxTTL = opts.maxTTL + this.#maxItems = opts.maxItems + this.dualStack = opts.dualStack + this.affinity = opts.affinity + this.lookup = opts.lookup ?? this.#defaultLookup + this.pick = opts.pick ?? this.#defaultPick + } + + get full () { + return this.#records.size === this.#maxItems + } + + runLookup (origin, opts, cb) { + const ips = this.#records.get(origin.hostname) + + // If full, we just return the origin + if (ips == null && this.full) { + cb(null, origin.origin) + return + } + + const newOpts = { + affinity: this.affinity, + dualStack: this.dualStack, + lookup: this.lookup, + pick: this.pick, + ...opts.dns, + maxTTL: this.#maxTTL, + maxItems: this.#maxItems + } + + // If no IPs we lookup + if (ips == null) { + this.lookup(origin, newOpts, (err, addresses) => { + if (err || addresses == null || addresses.length === 0) { + cb(err ?? new InformationalError('No DNS entries found')) + return + } + + this.setRecords(origin, addresses) + const records = this.#records.get(origin.hostname) + + const ip = this.pick( + origin, + records, + newOpts.affinity + ) + + let port + if (typeof ip.port === 'number') { + port = `:${ip.port}` + } else if (origin.port !== '') { + port = `:${origin.port}` + } else { + port = '' + } + + cb( + null, + `${origin.protocol}//${ + ip.family === 6 ? `[${ip.address}]` : ip.address + }${port}` + ) + }) + } else { + // If there's IPs we pick + const ip = this.pick( + origin, + ips, + newOpts.affinity + ) + + // If no IPs we lookup - deleting old records + if (ip == null) { + this.#records.delete(origin.hostname) + this.runLookup(origin, opts, cb) + return + } + + let port + if (typeof ip.port === 'number') { + port = `:${ip.port}` + } else if (origin.port !== '') { + port = `:${origin.port}` + } else { + port = '' + } + + cb( + null, + `${origin.protocol}//${ + ip.family === 6 ? `[${ip.address}]` : ip.address + }${port}` + ) + } + } + + #defaultLookup (origin, opts, cb) { + lookup( + origin.hostname, + { + all: true, + family: this.dualStack === false ? this.affinity : 0, + order: 'ipv4first' + }, + (err, addresses) => { + if (err) { + return cb(err) + } + + const results = new Map() + + for (const addr of addresses) { + // On linux we found duplicates, we attempt to remove them with + // the latest record + results.set(`${addr.address}:${addr.family}`, addr) + } + + cb(null, results.values()) + } + ) + } + + #defaultPick (origin, hostnameRecords, affinity) { + let ip = null + const { records, offset } = hostnameRecords + + let family + if (this.dualStack) { + if (affinity == null) { + // Balance between ip families + if (offset == null || offset === maxInt) { + hostnameRecords.offset = 0 + affinity = 4 + } else { + hostnameRecords.offset++ + affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4 + } + } + + if (records[affinity] != null && records[affinity].ips.length > 0) { + family = records[affinity] + } else { + family = records[affinity === 4 ? 6 : 4] + } + } else { + family = records[affinity] + } + + // If no IPs we return null + if (family == null || family.ips.length === 0) { + return ip + } + + if (family.offset == null || family.offset === maxInt) { + family.offset = 0 + } else { + family.offset++ + } + + const position = family.offset % family.ips.length + ip = family.ips[position] ?? null + + if (ip == null) { + return ip + } + + if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms + // We delete expired records + // It is possible that they have different TTL, so we manage them individually + family.ips.splice(position, 1) + return this.pick(origin, hostnameRecords, affinity) + } + + return ip + } + + setRecords (origin, addresses) { + const timestamp = Date.now() + const records = { records: { 4: null, 6: null } } + for (const record of addresses) { + record.timestamp = timestamp + if (typeof record.ttl === 'number') { + // The record TTL is expected to be in ms + record.ttl = Math.min(record.ttl, this.#maxTTL) + } else { + record.ttl = this.#maxTTL + } + + const familyRecords = records.records[record.family] ?? { ips: [] } + + familyRecords.ips.push(record) + records.records[record.family] = familyRecords + } + + this.#records.set(origin.hostname, records) + } + + getHandler (meta, opts) { + return new DNSDispatchHandler(this, meta, opts) + } +} + +class DNSDispatchHandler extends DecoratorHandler { + #state = null + #opts = null + #dispatch = null + #handler = null + #origin = null + + constructor (state, { origin, handler, dispatch }, opts) { + super(handler) + this.#origin = origin + this.#handler = handler + this.#opts = { ...opts } + this.#state = state + this.#dispatch = dispatch + } + + onError (err) { + switch (err.code) { + case 'ETIMEDOUT': + case 'ECONNREFUSED': { + if (this.#state.dualStack) { + // We delete the record and retry + this.#state.runLookup(this.#origin, this.#opts, (err, newOrigin) => { + if (err) { + return this.#handler.onError(err) + } + + const dispatchOpts = { + ...this.#opts, + origin: newOrigin + } + + this.#dispatch(dispatchOpts, this) + }) + + // if dual-stack disabled, we error out + return + } + + this.#handler.onError(err) + return + } + case 'ENOTFOUND': + this.#state.deleteRecord(this.#origin) + // eslint-disable-next-line no-fallthrough + default: + this.#handler.onError(err) + break + } + } +} + +module.exports = interceptorOpts => { + if ( + interceptorOpts?.maxTTL != null && + (typeof interceptorOpts?.maxTTL !== 'number' || interceptorOpts?.maxTTL < 0) + ) { + throw new InvalidArgumentError('Invalid maxTTL. Must be a positive number') + } + + if ( + interceptorOpts?.maxItems != null && + (typeof interceptorOpts?.maxItems !== 'number' || + interceptorOpts?.maxItems < 1) + ) { + throw new InvalidArgumentError( + 'Invalid maxItems. Must be a positive number and greater than zero' + ) + } + + if ( + interceptorOpts?.affinity != null && + interceptorOpts?.affinity !== 4 && + interceptorOpts?.affinity !== 6 + ) { + throw new InvalidArgumentError('Invalid affinity. Must be either 4 or 6') + } + + if ( + interceptorOpts?.dualStack != null && + typeof interceptorOpts?.dualStack !== 'boolean' + ) { + throw new InvalidArgumentError('Invalid dualStack. Must be a boolean') + } + + if ( + interceptorOpts?.lookup != null && + typeof interceptorOpts?.lookup !== 'function' + ) { + throw new InvalidArgumentError('Invalid lookup. Must be a function') + } + + if ( + interceptorOpts?.pick != null && + typeof interceptorOpts?.pick !== 'function' + ) { + throw new InvalidArgumentError('Invalid pick. Must be a function') + } + + const dualStack = interceptorOpts?.dualStack ?? true + let affinity + if (dualStack) { + affinity = interceptorOpts?.affinity ?? null + } else { + affinity = interceptorOpts?.affinity ?? 4 + } + + const opts = { + maxTTL: interceptorOpts?.maxTTL ?? 10e3, // Expressed in ms + lookup: interceptorOpts?.lookup ?? null, + pick: interceptorOpts?.pick ?? null, + dualStack, + affinity, + maxItems: interceptorOpts?.maxItems ?? Infinity + } + + const instance = new DNSInstance(opts) + + return dispatch => { + return function dnsInterceptor (origDispatchOpts, handler) { + const origin = + origDispatchOpts.origin.constructor === URL + ? origDispatchOpts.origin + : new URL(origDispatchOpts.origin) + + if (isIP(origin.hostname) !== 0) { + return dispatch(origDispatchOpts, handler) + } + + instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => { + if (err) { + return handler.onError(err) + } + + let dispatchOpts = null + dispatchOpts = { + ...origDispatchOpts, + servername: origin.hostname, // For SNI on TLS + origin: newOrigin, + headers: { + host: origin.hostname, + ...origDispatchOpts.headers + } + } + + dispatch( + dispatchOpts, + instance.getHandler({ origin, dispatch, handler }, origDispatchOpts) + ) + }) + + return true + } + } +} diff --git a/node_modules/undici/lib/interceptor/dump.js b/node_modules/undici/lib/interceptor/dump.js new file mode 100644 index 0000000000000..fc9cacb198d1e --- /dev/null +++ b/node_modules/undici/lib/interceptor/dump.js @@ -0,0 +1,123 @@ +'use strict' + +const util = require('../core/util') +const { InvalidArgumentError, RequestAbortedError } = require('../core/errors') +const DecoratorHandler = require('../handler/decorator-handler') + +class DumpHandler extends DecoratorHandler { + #maxSize = 1024 * 1024 + #abort = null + #dumped = false + #aborted = false + #size = 0 + #reason = null + #handler = null + + constructor ({ maxSize }, handler) { + super(handler) + + if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) { + throw new InvalidArgumentError('maxSize must be a number greater than 0') + } + + this.#maxSize = maxSize ?? this.#maxSize + this.#handler = handler + } + + onConnect (abort) { + this.#abort = abort + + this.#handler.onConnect(this.#customAbort.bind(this)) + } + + #customAbort (reason) { + this.#aborted = true + this.#reason = reason + } + + // TODO: will require adjustment after new hooks are out + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const headers = util.parseHeaders(rawHeaders) + const contentLength = headers['content-length'] + + if (contentLength != null && contentLength > this.#maxSize) { + throw new RequestAbortedError( + `Response size (${contentLength}) larger than maxSize (${ + this.#maxSize + })` + ) + } + + if (this.#aborted) { + return true + } + + return this.#handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } + + onError (err) { + if (this.#dumped) { + return + } + + err = this.#reason ?? err + + this.#handler.onError(err) + } + + onData (chunk) { + this.#size = this.#size + chunk.length + + if (this.#size >= this.#maxSize) { + this.#dumped = true + + if (this.#aborted) { + this.#handler.onError(this.#reason) + } else { + this.#handler.onComplete([]) + } + } + + return true + } + + onComplete (trailers) { + if (this.#dumped) { + return + } + + if (this.#aborted) { + this.#handler.onError(this.reason) + return + } + + this.#handler.onComplete(trailers) + } +} + +function createDumpInterceptor ( + { maxSize: defaultMaxSize } = { + maxSize: 1024 * 1024 + } +) { + return dispatch => { + return function Intercept (opts, handler) { + const { dumpMaxSize = defaultMaxSize } = + opts + + const dumpHandler = new DumpHandler( + { maxSize: dumpMaxSize }, + handler + ) + + return dispatch(opts, dumpHandler) + } + } +} + +module.exports = createDumpInterceptor diff --git a/node_modules/undici/lib/interceptor/redirect-interceptor.js b/node_modules/undici/lib/interceptor/redirect-interceptor.js new file mode 100644 index 0000000000000..896ee8db93966 --- /dev/null +++ b/node_modules/undici/lib/interceptor/redirect-interceptor.js @@ -0,0 +1,21 @@ +'use strict' + +const RedirectHandler = require('../handler/redirect-handler') + +function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { + return (dispatch) => { + return function Intercept (opts, handler) { + const { maxRedirections = defaultMaxRedirections } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) + opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } + } +} + +module.exports = createRedirectInterceptor diff --git a/node_modules/undici/lib/interceptor/redirect.js b/node_modules/undici/lib/interceptor/redirect.js new file mode 100644 index 0000000000000..d2e789d8efb85 --- /dev/null +++ b/node_modules/undici/lib/interceptor/redirect.js @@ -0,0 +1,24 @@ +'use strict' +const RedirectHandler = require('../handler/redirect-handler') + +module.exports = opts => { + const globalMaxRedirections = opts?.maxRedirections + return dispatch => { + return function redirectInterceptor (opts, handler) { + const { maxRedirections = globalMaxRedirections, ...baseOpts } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler( + dispatch, + maxRedirections, + opts, + handler + ) + + return dispatch(baseOpts, redirectHandler) + } + } +} diff --git a/node_modules/undici/lib/interceptor/response-error.js b/node_modules/undici/lib/interceptor/response-error.js new file mode 100644 index 0000000000000..3ded9c87fb736 --- /dev/null +++ b/node_modules/undici/lib/interceptor/response-error.js @@ -0,0 +1,86 @@ +'use strict' + +const { parseHeaders } = require('../core/util') +const DecoratorHandler = require('../handler/decorator-handler') +const { ResponseError } = require('../core/errors') + +class Handler extends DecoratorHandler { + #handler + #statusCode + #contentType + #decoder + #headers + #body + + constructor (opts, { handler }) { + super(handler) + this.#handler = handler + } + + onConnect (abort) { + this.#statusCode = 0 + this.#contentType = null + this.#decoder = null + this.#headers = null + this.#body = '' + + return this.#handler.onConnect(abort) + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage, headers = parseHeaders(rawHeaders)) { + this.#statusCode = statusCode + this.#headers = headers + this.#contentType = headers['content-type'] + + if (this.#statusCode < 400) { + return this.#handler.onHeaders(statusCode, rawHeaders, resume, statusMessage, headers) + } + + if (this.#contentType === 'application/json' || this.#contentType === 'text/plain') { + this.#decoder = new TextDecoder('utf-8') + } + } + + onData (chunk) { + if (this.#statusCode < 400) { + return this.#handler.onData(chunk) + } + + this.#body += this.#decoder?.decode(chunk, { stream: true }) ?? '' + } + + onComplete (rawTrailers) { + if (this.#statusCode >= 400) { + this.#body += this.#decoder?.decode(undefined, { stream: false }) ?? '' + + if (this.#contentType === 'application/json') { + try { + this.#body = JSON.parse(this.#body) + } catch { + // Do nothing... + } + } + + let err + const stackTraceLimit = Error.stackTraceLimit + Error.stackTraceLimit = 0 + try { + err = new ResponseError('Response Error', this.#statusCode, this.#headers, this.#body) + } finally { + Error.stackTraceLimit = stackTraceLimit + } + + this.#handler.onError(err) + } else { + this.#handler.onComplete(rawTrailers) + } + } + + onError (err) { + this.#handler.onError(err) + } +} + +module.exports = (dispatch) => (opts, handler) => opts.throwOnError + ? dispatch(opts, new Handler(opts, { handler })) + : dispatch(opts, handler) diff --git a/node_modules/undici/lib/interceptor/retry.js b/node_modules/undici/lib/interceptor/retry.js new file mode 100644 index 0000000000000..1c16fd845a9a9 --- /dev/null +++ b/node_modules/undici/lib/interceptor/retry.js @@ -0,0 +1,19 @@ +'use strict' +const RetryHandler = require('../handler/retry-handler') + +module.exports = globalOpts => { + return dispatch => { + return function retryInterceptor (opts, handler) { + return dispatch( + opts, + new RetryHandler( + { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } }, + { + handler, + dispatch + } + ) + ) + } + } +} diff --git a/node_modules/undici/lib/llhttp/constants.js b/node_modules/undici/lib/llhttp/constants.js new file mode 100644 index 0000000000000..fb0b5a24c523e --- /dev/null +++ b/node_modules/undici/lib/llhttp/constants.js @@ -0,0 +1,278 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; +const utils_1 = require("./utils"); +// C headers +var ERROR; +(function (ERROR) { + ERROR[ERROR["OK"] = 0] = "OK"; + ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; + ERROR[ERROR["STRICT"] = 2] = "STRICT"; + ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; + ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; + ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; + ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; + ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; + ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; + ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; + ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; + ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; + ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; + ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; + ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; + ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; + ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; + ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; + ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; + ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; + ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; + ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; + ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; + ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; + ERROR[ERROR["USER"] = 24] = "USER"; +})(ERROR = exports.ERROR || (exports.ERROR = {})); +var TYPE; +(function (TYPE) { + TYPE[TYPE["BOTH"] = 0] = "BOTH"; + TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; + TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; +})(TYPE = exports.TYPE || (exports.TYPE = {})); +var FLAGS; +(function (FLAGS) { + FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; + FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; + FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; + FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; + FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; + FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; + FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; + FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; + // 1 << 8 is unused + FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; +})(FLAGS = exports.FLAGS || (exports.FLAGS = {})); +var LENIENT_FLAGS; +(function (LENIENT_FLAGS) { + LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; + LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; + LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; +})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); +var METHODS; +(function (METHODS) { + METHODS[METHODS["DELETE"] = 0] = "DELETE"; + METHODS[METHODS["GET"] = 1] = "GET"; + METHODS[METHODS["HEAD"] = 2] = "HEAD"; + METHODS[METHODS["POST"] = 3] = "POST"; + METHODS[METHODS["PUT"] = 4] = "PUT"; + /* pathological */ + METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; + METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; + METHODS[METHODS["TRACE"] = 7] = "TRACE"; + /* WebDAV */ + METHODS[METHODS["COPY"] = 8] = "COPY"; + METHODS[METHODS["LOCK"] = 9] = "LOCK"; + METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; + METHODS[METHODS["MOVE"] = 11] = "MOVE"; + METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; + METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; + METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; + METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; + METHODS[METHODS["BIND"] = 16] = "BIND"; + METHODS[METHODS["REBIND"] = 17] = "REBIND"; + METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; + METHODS[METHODS["ACL"] = 19] = "ACL"; + /* subversion */ + METHODS[METHODS["REPORT"] = 20] = "REPORT"; + METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; + METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; + METHODS[METHODS["MERGE"] = 23] = "MERGE"; + /* upnp */ + METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; + METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; + METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; + METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; + /* RFC-5789 */ + METHODS[METHODS["PATCH"] = 28] = "PATCH"; + METHODS[METHODS["PURGE"] = 29] = "PURGE"; + /* CalDAV */ + METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; + /* RFC-2068, section 19.6.1.2 */ + METHODS[METHODS["LINK"] = 31] = "LINK"; + METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; + /* icecast */ + METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; + /* RFC-7540, section 11.6 */ + METHODS[METHODS["PRI"] = 34] = "PRI"; + /* RFC-2326 RTSP */ + METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; + METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; + METHODS[METHODS["SETUP"] = 37] = "SETUP"; + METHODS[METHODS["PLAY"] = 38] = "PLAY"; + METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; + METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; + METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; + METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; + METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; + METHODS[METHODS["RECORD"] = 44] = "RECORD"; + /* RAOP */ + METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; +})(METHODS = exports.METHODS || (exports.METHODS = {})); +exports.METHODS_HTTP = [ + METHODS.DELETE, + METHODS.GET, + METHODS.HEAD, + METHODS.POST, + METHODS.PUT, + METHODS.CONNECT, + METHODS.OPTIONS, + METHODS.TRACE, + METHODS.COPY, + METHODS.LOCK, + METHODS.MKCOL, + METHODS.MOVE, + METHODS.PROPFIND, + METHODS.PROPPATCH, + METHODS.SEARCH, + METHODS.UNLOCK, + METHODS.BIND, + METHODS.REBIND, + METHODS.UNBIND, + METHODS.ACL, + METHODS.REPORT, + METHODS.MKACTIVITY, + METHODS.CHECKOUT, + METHODS.MERGE, + METHODS['M-SEARCH'], + METHODS.NOTIFY, + METHODS.SUBSCRIBE, + METHODS.UNSUBSCRIBE, + METHODS.PATCH, + METHODS.PURGE, + METHODS.MKCALENDAR, + METHODS.LINK, + METHODS.UNLINK, + METHODS.PRI, + // TODO(indutny): should we allow it with HTTP? + METHODS.SOURCE, +]; +exports.METHODS_ICE = [ + METHODS.SOURCE, +]; +exports.METHODS_RTSP = [ + METHODS.OPTIONS, + METHODS.DESCRIBE, + METHODS.ANNOUNCE, + METHODS.SETUP, + METHODS.PLAY, + METHODS.PAUSE, + METHODS.TEARDOWN, + METHODS.GET_PARAMETER, + METHODS.SET_PARAMETER, + METHODS.REDIRECT, + METHODS.RECORD, + METHODS.FLUSH, + // For AirPlay + METHODS.GET, + METHODS.POST, +]; +exports.METHOD_MAP = utils_1.enumToMap(METHODS); +exports.H_METHOD_MAP = {}; +Object.keys(exports.METHOD_MAP).forEach((key) => { + if (/^H/.test(key)) { + exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; + } +}); +var FINISH; +(function (FINISH) { + FINISH[FINISH["SAFE"] = 0] = "SAFE"; + FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; + FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; +})(FINISH = exports.FINISH || (exports.FINISH = {})); +exports.ALPHA = []; +for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { + // Upper case + exports.ALPHA.push(String.fromCharCode(i)); + // Lower case + exports.ALPHA.push(String.fromCharCode(i + 0x20)); +} +exports.NUM_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, +}; +exports.HEX_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, + a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, +}; +exports.NUM = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', +]; +exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); +exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; +exports.USERINFO_CHARS = exports.ALPHANUM + .concat(exports.MARK) + .concat(['%', ';', ':', '&', '=', '+', '$', ',']); +// TODO(indutny): use RFC +exports.STRICT_URL_CHAR = [ + '!', '"', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', + '@', '[', '\\', ']', '^', '_', + '`', + '{', '|', '}', '~', +].concat(exports.ALPHANUM); +exports.URL_CHAR = exports.STRICT_URL_CHAR + .concat(['\t', '\f']); +// All characters with 0x80 bit set to 1 +for (let i = 0x80; i <= 0xff; i++) { + exports.URL_CHAR.push(i); +} +exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); +/* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ +exports.STRICT_TOKEN = [ + '!', '#', '$', '%', '&', '\'', + '*', '+', '-', '.', + '^', '_', '`', + '|', '~', +].concat(exports.ALPHANUM); +exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); +/* + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + */ +exports.HEADER_CHARS = ['\t']; +for (let i = 32; i <= 255; i++) { + if (i !== 127) { + exports.HEADER_CHARS.push(i); + } +} +// ',' = \x44 +exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); +exports.MAJOR = exports.NUM_MAP; +exports.MINOR = exports.MAJOR; +var HEADER_STATE; +(function (HEADER_STATE) { + HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; + HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; + HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; + HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; + HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; + HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; + HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; +})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); +exports.SPECIAL_HEADERS = { + 'connection': HEADER_STATE.CONNECTION, + 'content-length': HEADER_STATE.CONTENT_LENGTH, + 'proxy-connection': HEADER_STATE.CONNECTION, + 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, + 'upgrade': HEADER_STATE.UPGRADE, +}; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/undici/lib/llhttp/llhttp-wasm.js b/node_modules/undici/lib/llhttp/llhttp-wasm.js new file mode 100644 index 0000000000000..8ac8481930c2d --- /dev/null +++ b/node_modules/undici/lib/llhttp/llhttp-wasm.js @@ -0,0 +1,5 @@ +'use strict' + +const { Buffer } = require('node:buffer') + +module.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0sBQYAAAIAAAAAAAACAQIAAgICAAADAAAAAAMDAwMBAQEBAQEBAQEAAAIAAAAEBQFwARISBQMBAAIGCAF/AUGA1AQLB9EFIgZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAIGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAJGGxsaHR0cF9zaG91bGRfa2VlcF9hbGl2ZQAvDGxsaHR0cF9hbGxvYwALBm1hbGxvYwAxC2xsaHR0cF9mcmVlAAwEZnJlZQAMD2xsaHR0cF9nZXRfdHlwZQANFWxsaHR0cF9nZXRfaHR0cF9tYWpvcgAOFWxsaHR0cF9nZXRfaHR0cF9taW5vcgAPEWxsaHR0cF9nZXRfbWV0aG9kABAWbGxodHRwX2dldF9zdGF0dXNfY29kZQAREmxsaHR0cF9nZXRfdXBncmFkZQASDGxsaHR0cF9yZXNldAATDmxsaHR0cF9leGVjdXRlABQUbGxodHRwX3NldHRpbmdzX2luaXQAFQ1sbGh0dHBfZmluaXNoABYMbGxodHRwX3BhdXNlABcNbGxodHRwX3Jlc3VtZQAYG2xsaHR0cF9yZXN1bWVfYWZ0ZXJfdXBncmFkZQAZEGxsaHR0cF9nZXRfZXJybm8AGhdsbGh0dHBfZ2V0X2Vycm9yX3JlYXNvbgAbF2xsaHR0cF9zZXRfZXJyb3JfcmVhc29uABwUbGxodHRwX2dldF9lcnJvcl9wb3MAHRFsbGh0dHBfZXJybm9fbmFtZQAeEmxsaHR0cF9tZXRob2RfbmFtZQAfEmxsaHR0cF9zdGF0dXNfbmFtZQAgGmxsaHR0cF9zZXRfbGVuaWVudF9oZWFkZXJzACEhbGxodHRwX3NldF9sZW5pZW50X2NodW5rZWRfbGVuZ3RoACIdbGxodHRwX3NldF9sZW5pZW50X2tlZXBfYWxpdmUAIyRsbGh0dHBfc2V0X2xlbmllbnRfdHJhbnNmZXJfZW5jb2RpbmcAJBhsbGh0dHBfbWVzc2FnZV9uZWVkc19lb2YALgkXAQBBAQsRAQIDBAUKBgcrLSwqKSglJyYK07MCLBYAQYjQACgCAARAAAtBiNAAQQE2AgALFAAgABAwIAAgAjYCOCAAIAE6ACgLFAAgACAALwEyIAAtAC4gABAvEAALHgEBf0HAABAyIgEQMCABQYAINgI4IAEgADoAKCABC48MAQd/AkAgAEUNACAAQQhrIgEgAEEEaygCACIAQXhxIgRqIQUCQCAAQQFxDQAgAEEDcUUNASABIAEoAgAiAGsiAUGc0AAoAgBJDQEgACAEaiEEAkACQEGg0AAoAgAgAUcEQCAAQf8BTQRAIABBA3YhAyABKAIIIgAgASgCDCICRgRAQYzQAEGM0AAoAgBBfiADd3E2AgAMBQsgAiAANgIIIAAgAjYCDAwECyABKAIYIQYgASABKAIMIgBHBEAgACABKAIIIgI2AgggAiAANgIMDAMLIAFBFGoiAygCACICRQRAIAEoAhAiAkUNAiABQRBqIQMLA0AgAyEHIAIiAEEUaiIDKAIAIgINACAAQRBqIQMgACgCECICDQALIAdBADYCAAwCCyAFKAIEIgBBA3FBA0cNAiAFIABBfnE2AgRBlNAAIAQ2AgAgBSAENgIAIAEgBEEBcjYCBAwDC0EAIQALIAZFDQACQCABKAIcIgJBAnRBvNIAaiIDKAIAIAFGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgAUYbaiAANgIAIABFDQELIAAgBjYCGCABKAIQIgIEQCAAIAI2AhAgAiAANgIYCyABQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAFTw0AIAUoAgQiAEEBcUUNAAJAAkACQAJAIABBAnFFBEBBpNAAKAIAIAVGBEBBpNAAIAE2AgBBmNAAQZjQACgCACAEaiIANgIAIAEgAEEBcjYCBCABQaDQACgCAEcNBkGU0ABBADYCAEGg0ABBADYCAAwGC0Gg0AAoAgAgBUYEQEGg0AAgATYCAEGU0ABBlNAAKAIAIARqIgA2AgAgASAAQQFyNgIEIAAgAWogADYCAAwGCyAAQXhxIARqIQQgAEH/AU0EQCAAQQN2IQMgBSgCCCIAIAUoAgwiAkYEQEGM0ABBjNAAKAIAQX4gA3dxNgIADAULIAIgADYCCCAAIAI2AgwMBAsgBSgCGCEGIAUgBSgCDCIARwRAQZzQACgCABogACAFKAIIIgI2AgggAiAANgIMDAMLIAVBFGoiAygCACICRQRAIAUoAhAiAkUNAiAFQRBqIQMLA0AgAyEHIAIiAEEUaiIDKAIAIgINACAAQRBqIQMgACgCECICDQALIAdBADYCAAwCCyAFIABBfnE2AgQgASAEaiAENgIAIAEgBEEBcjYCBAwDC0EAIQALIAZFDQACQCAFKAIcIgJBAnRBvNIAaiIDKAIAIAVGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiAANgIAIABFDQELIAAgBjYCGCAFKAIQIgIEQCAAIAI2AhAgAiAANgIYCyAFQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAEaiAENgIAIAEgBEEBcjYCBCABQaDQACgCAEcNAEGU0AAgBDYCAAwBCyAEQf8BTQRAIARBeHFBtNAAaiEAAn9BjNAAKAIAIgJBASAEQQN2dCIDcUUEQEGM0AAgAiADcjYCACAADAELIAAoAggLIgIgATYCDCAAIAE2AgggASAANgIMIAEgAjYCCAwBC0EfIQIgBEH///8HTQRAIARBJiAEQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAgsgASACNgIcIAFCADcCECACQQJ0QbzSAGohAAJAQZDQACgCACIDQQEgAnQiB3FFBEAgACABNgIAQZDQACADIAdyNgIAIAEgADYCGCABIAE2AgggASABNgIMDAELIARBGSACQQF2a0EAIAJBH0cbdCECIAAoAgAhAAJAA0AgACIDKAIEQXhxIARGDQEgAkEddiEAIAJBAXQhAiADIABBBHFqQRBqIgcoAgAiAA0ACyAHIAE2AgAgASADNgIYIAEgATYCDCABIAE2AggMAQsgAygCCCIAIAE2AgwgAyABNgIIIAFBADYCGCABIAM2AgwgASAANgIIC0Gs0ABBrNAAKAIAQQFrIgBBfyAAGzYCAAsLBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LQAEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABAwIAAgBDYCOCAAIAM6ACggACACOgAtIAAgATYCGAu74gECB38DfiABIAJqIQQCQCAAIgIoAgwiAA0AIAIoAgQEQCACIAE2AgQLIwBBEGsiCCQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAIoAhwiA0EBaw7dAdoBAdkBAgMEBQYHCAkKCwwNDtgBDxDXARES1gETFBUWFxgZGhvgAd8BHB0e1QEfICEiIyQl1AEmJygpKiss0wHSAS0u0QHQAS8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRtsBR0hJSs8BzgFLzQFMzAFNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AAYEBggGDAYQBhQGGAYcBiAGJAYoBiwGMAY0BjgGPAZABkQGSAZMBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBywHKAbgByQG5AcgBugG7AbwBvQG+Ab8BwAHBAcIBwwHEAcUBxgEA3AELQQAMxgELQQ4MxQELQQ0MxAELQQ8MwwELQRAMwgELQRMMwQELQRQMwAELQRUMvwELQRYMvgELQRgMvQELQRkMvAELQRoMuwELQRsMugELQRwMuQELQR0MuAELQQgMtwELQR4MtgELQSAMtQELQR8MtAELQQcMswELQSEMsgELQSIMsQELQSMMsAELQSQMrwELQRIMrgELQREMrQELQSUMrAELQSYMqwELQScMqgELQSgMqQELQcMBDKgBC0EqDKcBC0ErDKYBC0EsDKUBC0EtDKQBC0EuDKMBC0EvDKIBC0HEAQyhAQtBMAygAQtBNAyfAQtBDAyeAQtBMQydAQtBMgycAQtBMwybAQtBOQyaAQtBNQyZAQtBxQEMmAELQQsMlwELQToMlgELQTYMlQELQQoMlAELQTcMkwELQTgMkgELQTwMkQELQTsMkAELQT0MjwELQQkMjgELQSkMjQELQT4MjAELQT8MiwELQcAADIoBC0HBAAyJAQtBwgAMiAELQcMADIcBC0HEAAyGAQtBxQAMhQELQcYADIQBC0EXDIMBC0HHAAyCAQtByAAMgQELQckADIABC0HKAAx/C0HLAAx+C0HNAAx9C0HMAAx8C0HOAAx7C0HPAAx6C0HQAAx5C0HRAAx4C0HSAAx3C0HTAAx2C0HUAAx1C0HWAAx0C0HVAAxzC0EGDHILQdcADHELQQUMcAtB2AAMbwtBBAxuC0HZAAxtC0HaAAxsC0HbAAxrC0HcAAxqC0EDDGkLQd0ADGgLQd4ADGcLQd8ADGYLQeEADGULQeAADGQLQeIADGMLQeMADGILQQIMYQtB5AAMYAtB5QAMXwtB5gAMXgtB5wAMXQtB6AAMXAtB6QAMWwtB6gAMWgtB6wAMWQtB7AAMWAtB7QAMVwtB7gAMVgtB7wAMVQtB8AAMVAtB8QAMUwtB8gAMUgtB8wAMUQtB9AAMUAtB9QAMTwtB9gAMTgtB9wAMTQtB+AAMTAtB+QAMSwtB+gAMSgtB+wAMSQtB/AAMSAtB/QAMRwtB/gAMRgtB/wAMRQtBgAEMRAtBgQEMQwtBggEMQgtBgwEMQQtBhAEMQAtBhQEMPwtBhgEMPgtBhwEMPQtBiAEMPAtBiQEMOwtBigEMOgtBiwEMOQtBjAEMOAtBjQEMNwtBjgEMNgtBjwEMNQtBkAEMNAtBkQEMMwtBkgEMMgtBkwEMMQtBlAEMMAtBlQEMLwtBlgEMLgtBlwEMLQtBmAEMLAtBmQEMKwtBmgEMKgtBmwEMKQtBnAEMKAtBnQEMJwtBngEMJgtBnwEMJQtBoAEMJAtBoQEMIwtBogEMIgtBowEMIQtBpAEMIAtBpQEMHwtBpgEMHgtBpwEMHQtBqAEMHAtBqQEMGwtBqgEMGgtBqwEMGQtBrAEMGAtBrQEMFwtBrgEMFgtBAQwVC0GvAQwUC0GwAQwTC0GxAQwSC0GzAQwRC0GyAQwQC0G0AQwPC0G1AQwOC0G2AQwNC0G3AQwMC0G4AQwLC0G5AQwKC0G6AQwJC0G7AQwIC0HGAQwHC0G8AQwGC0G9AQwFC0G+AQwEC0G/AQwDC0HAAQwCC0HCAQwBC0HBAQshAwNAAkACQAJAAkACQAJAAkACQAJAIAICfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAgJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADDsYBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHyAhIyUmKCorLC8wMTIzNDU2Nzk6Ozw9lANAQkRFRklLTk9QUVJTVFVWWFpbXF1eX2BhYmNkZWZnaGpsb3Bxc3V2eHl6e3x/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AbgBuQG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAccByAHJAcsBzAHNAc4BzwGKA4kDiAOHA4QDgwOAA/sC+gL5AvgC9wL0AvMC8gLLAsECsALZAQsgASAERw3wAkHdASEDDLMDCyABIARHDcgBQcMBIQMMsgMLIAEgBEcNe0H3ACEDDLEDCyABIARHDXBB7wAhAwywAwsgASAERw1pQeoAIQMMrwMLIAEgBEcNZUHoACEDDK4DCyABIARHDWJB5gAhAwytAwsgASAERw0aQRghAwysAwsgASAERw0VQRIhAwyrAwsgASAERw1CQcUAIQMMqgMLIAEgBEcNNEE/IQMMqQMLIAEgBEcNMkE8IQMMqAMLIAEgBEcNK0ExIQMMpwMLIAItAC5BAUYNnwMMwQILQQAhAAJAAkACQCACLQAqRQ0AIAItACtFDQAgAi8BMCIDQQJxRQ0BDAILIAIvATAiA0EBcUUNAQtBASEAIAItAChBAUYNACACLwEyIgVB5ABrQeQASQ0AIAVBzAFGDQAgBUGwAkYNACADQcAAcQ0AQQAhACADQYgEcUGABEYNACADQShxQQBHIQALIAJBADsBMCACQQA6AC8gAEUN3wIgAkIANwMgDOACC0EAIQACQCACKAI4IgNFDQAgAygCLCIDRQ0AIAIgAxEAACEACyAARQ3MASAAQRVHDd0CIAJBBDYCHCACIAE2AhQgAkGwGDYCECACQRU2AgxBACEDDKQDCyABIARGBEBBBiEDDKQDCyABQQFqIQFBACEAAkAgAigCOCIDRQ0AIAMoAlQiA0UNACACIAMRAAAhAAsgAA3ZAgwcCyACQgA3AyBBEiEDDIkDCyABIARHDRZBHSEDDKEDCyABIARHBEAgAUEBaiEBQRAhAwyIAwtBByEDDKADCyACIAIpAyAiCiAEIAFrrSILfSIMQgAgCiAMWhs3AyAgCiALWA3UAkEIIQMMnwMLIAEgBEcEQCACQQk2AgggAiABNgIEQRQhAwyGAwtBCSEDDJ4DCyACKQMgQgBSDccBIAIgAi8BMEGAAXI7ATAMQgsgASAERw0/QdAAIQMMnAMLIAEgBEYEQEELIQMMnAMLIAFBAWohAUEAIQACQCACKAI4IgNFDQAgAygCUCIDRQ0AIAIgAxEAACEACyAADc8CDMYBC0EAIQACQCACKAI4IgNFDQAgAygCSCIDRQ0AIAIgAxEAACEACyAARQ3GASAAQRVHDc0CIAJBCzYCHCACIAE2AhQgAkGCGTYCECACQRU2AgxBACEDDJoDC0EAIQACQCACKAI4IgNFDQAgAygCSCIDRQ0AIAIgAxEAACEACyAARQ0MIABBFUcNygIgAkEaNgIcIAIgATYCFCACQYIZNgIQIAJBFTYCDEEAIQMMmQMLQQAhAAJAIAIoAjgiA0UNACADKAJMIgNFDQAgAiADEQAAIQALIABFDcQBIABBFUcNxwIgAkELNgIcIAIgATYCFCACQZEXNgIQIAJBFTYCDEEAIQMMmAMLIAEgBEYEQEEPIQMMmAMLIAEtAAAiAEE7Rg0HIABBDUcNxAIgAUEBaiEBDMMBC0EAIQACQCACKAI4IgNFDQAgAygCTCIDRQ0AIAIgAxEAACEACyAARQ3DASAAQRVHDcICIAJBDzYCHCACIAE2AhQgAkGRFzYCECACQRU2AgxBACEDDJYDCwNAIAEtAABB8DVqLQAAIgBBAUcEQCAAQQJHDcECIAIoAgQhAEEAIQMgAkEANgIEIAIgACABQQFqIgEQLSIADcICDMUBCyAEIAFBAWoiAUcNAAtBEiEDDJUDC0EAIQACQCACKAI4IgNFDQAgAygCTCIDRQ0AIAIgAxEAACEACyAARQ3FASAAQRVHDb0CIAJBGzYCHCACIAE2AhQgAkGRFzYCECACQRU2AgxBACEDDJQDCyABIARGBEBBFiEDDJQDCyACQQo2AgggAiABNgIEQQAhAAJAIAIoAjgiA0UNACADKAJIIgNFDQAgAiADEQAAIQALIABFDcIBIABBFUcNuQIgAkEVNgIcIAIgATYCFCACQYIZNgIQIAJBFTYCDEEAIQMMkwMLIAEgBEcEQANAIAEtAABB8DdqLQAAIgBBAkcEQAJAIABBAWsOBMQCvQIAvgK9AgsgAUEBaiEBQQghAwz8AgsgBCABQQFqIgFHDQALQRUhAwyTAwtBFSEDDJIDCwNAIAEtAABB8DlqLQAAIgBBAkcEQCAAQQFrDgTFArcCwwK4ArcCCyAEIAFBAWoiAUcNAAtBGCEDDJEDCyABIARHBEAgAkELNgIIIAIgATYCBEEHIQMM+AILQRkhAwyQAwsgAUEBaiEBDAILIAEgBEYEQEEaIQMMjwMLAkAgAS0AAEENaw4UtQG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwEAvwELQQAhAyACQQA2AhwgAkGvCzYCECACQQI2AgwgAiABQQFqNgIUDI4DCyABIARGBEBBGyEDDI4DCyABLQAAIgBBO0cEQCAAQQ1HDbECIAFBAWohAQy6AQsgAUEBaiEBC0EiIQMM8wILIAEgBEYEQEEcIQMMjAMLQgAhCgJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAS0AAEEwaw43wQLAAgABAgMEBQYH0AHQAdAB0AHQAdAB0AEICQoLDA3QAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdABDg8QERIT0AELQgIhCgzAAgtCAyEKDL8CC0IEIQoMvgILQgUhCgy9AgtCBiEKDLwCC0IHIQoMuwILQgghCgy6AgtCCSEKDLkCC0IKIQoMuAILQgshCgy3AgtCDCEKDLYCC0INIQoMtQILQg4hCgy0AgtCDyEKDLMCC0IKIQoMsgILQgshCgyxAgtCDCEKDLACC0INIQoMrwILQg4hCgyuAgtCDyEKDK0CC0IAIQoCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBMGsON8ACvwIAAQIDBAUGB74CvgK+Ar4CvgK+Ar4CCAkKCwwNvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ag4PEBESE74CC0ICIQoMvwILQgMhCgy+AgtCBCEKDL0CC0IFIQoMvAILQgYhCgy7AgtCByEKDLoCC0IIIQoMuQILQgkhCgy4AgtCCiEKDLcCC0ILIQoMtgILQgwhCgy1AgtCDSEKDLQCC0IOIQoMswILQg8hCgyyAgtCCiEKDLECC0ILIQoMsAILQgwhCgyvAgtCDSEKDK4CC0IOIQoMrQILQg8hCgysAgsgAiACKQMgIgogBCABa60iC30iDEIAIAogDFobNwMgIAogC1gNpwJBHyEDDIkDCyABIARHBEAgAkEJNgIIIAIgATYCBEElIQMM8AILQSAhAwyIAwtBASEFIAIvATAiA0EIcUUEQCACKQMgQgBSIQULAkAgAi0ALgRAQQEhACACLQApQQVGDQEgA0HAAHFFIAVxRQ0BC0EAIQAgA0HAAHENAEECIQAgA0EIcQ0AIANBgARxBEACQCACLQAoQQFHDQAgAi0ALUEKcQ0AQQUhAAwCC0EEIQAMAQsgA0EgcUUEQAJAIAItAChBAUYNACACLwEyIgBB5ABrQeQASQ0AIABBzAFGDQAgAEGwAkYNAEEEIQAgA0EocUUNAiADQYgEcUGABEYNAgtBACEADAELQQBBAyACKQMgUBshAAsgAEEBaw4FvgIAsAEBpAKhAgtBESEDDO0CCyACQQE6AC8MhAMLIAEgBEcNnQJBJCEDDIQDCyABIARHDRxBxgAhAwyDAwtBACEAAkAgAigCOCIDRQ0AIAMoAkQiA0UNACACIAMRAAAhAAsgAEUNJyAAQRVHDZgCIAJB0AA2AhwgAiABNgIUIAJBkRg2AhAgAkEVNgIMQQAhAwyCAwsgASAERgRAQSghAwyCAwtBACEDIAJBADYCBCACQQw2AgggAiABIAEQKiIARQ2UAiACQSc2AhwgAiABNgIUIAIgADYCDAyBAwsgASAERgRAQSkhAwyBAwsgAS0AACIAQSBGDRMgAEEJRw2VAiABQQFqIQEMFAsgASAERwRAIAFBAWohAQwWC0EqIQMM/wILIAEgBEYEQEErIQMM/wILIAEtAAAiAEEJRyAAQSBHcQ2QAiACLQAsQQhHDd0CIAJBADoALAzdAgsgASAERgRAQSwhAwz+AgsgAS0AAEEKRw2OAiABQQFqIQEMsAELIAEgBEcNigJBLyEDDPwCCwNAIAEtAAAiAEEgRwRAIABBCmsOBIQCiAKIAoQChgILIAQgAUEBaiIBRw0AC0ExIQMM+wILQTIhAyABIARGDfoCIAIoAgAiACAEIAFraiEHIAEgAGtBA2ohBgJAA0AgAEHwO2otAAAgAS0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQEgAEEDRgRAQQYhAQziAgsgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAc2AgAM+wILIAJBADYCAAyGAgtBMyEDIAQgASIARg35AiAEIAFrIAIoAgAiAWohByAAIAFrQQhqIQYCQANAIAFB9DtqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBCEYEQEEFIQEM4QILIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADPoCCyACQQA2AgAgACEBDIUCC0E0IQMgBCABIgBGDfgCIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgJAA0AgAUHQwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBBUYEQEEHIQEM4AILIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADPkCCyACQQA2AgAgACEBDIQCCyABIARHBEADQCABLQAAQYA+ai0AACIAQQFHBEAgAEECRg0JDIECCyAEIAFBAWoiAUcNAAtBMCEDDPgCC0EwIQMM9wILIAEgBEcEQANAIAEtAAAiAEEgRwRAIABBCmsOBP8B/gH+Af8B/gELIAQgAUEBaiIBRw0AC0E4IQMM9wILQTghAwz2AgsDQCABLQAAIgBBIEcgAEEJR3EN9gEgBCABQQFqIgFHDQALQTwhAwz1AgsDQCABLQAAIgBBIEcEQAJAIABBCmsOBPkBBAT5AQALIABBLEYN9QEMAwsgBCABQQFqIgFHDQALQT8hAwz0AgtBwAAhAyABIARGDfMCIAIoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAEGAQGstAAAgAS0AAEEgckcNASAAQQZGDdsCIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPQCCyACQQA2AgALQTYhAwzZAgsgASAERgRAQcEAIQMM8gILIAJBDDYCCCACIAE2AgQgAi0ALEEBaw4E+wHuAewB6wHUAgsgAUEBaiEBDPoBCyABIARHBEADQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxIgBBCUYNACAAQSBGDQACQAJAAkACQCAAQeMAaw4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUExIQMM3AILIAFBAWohAUEyIQMM2wILIAFBAWohAUEzIQMM2gILDP4BCyAEIAFBAWoiAUcNAAtBNSEDDPACC0E1IQMM7wILIAEgBEcEQANAIAEtAABBgDxqLQAAQQFHDfcBIAQgAUEBaiIBRw0AC0E9IQMM7wILQT0hAwzuAgtBACEAAkAgAigCOCIDRQ0AIAMoAkAiA0UNACACIAMRAAAhAAsgAEUNASAAQRVHDeYBIAJBwgA2AhwgAiABNgIUIAJB4xg2AhAgAkEVNgIMQQAhAwztAgsgAUEBaiEBC0E8IQMM0gILIAEgBEYEQEHCACEDDOsCCwJAA0ACQCABLQAAQQlrDhgAAswCzALRAswCzALMAswCzALMAswCzALMAswCzALMAswCzALMAswCzALMAgDMAgsgBCABQQFqIgFHDQALQcIAIQMM6wILIAFBAWohASACLQAtQQFxRQ3+AQtBLCEDDNACCyABIARHDd4BQcQAIQMM6AILA0AgAS0AAEGQwABqLQAAQQFHDZwBIAQgAUEBaiIBRw0AC0HFACEDDOcCCyABLQAAIgBBIEYN/gEgAEE6Rw3AAiACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgAN3gEM3QELQccAIQMgBCABIgBGDeUCIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgNAIAFBkMIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNvwIgAUEFRg3CAiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBzYCAAzlAgtByAAhAyAEIAEiAEYN5AIgBCABayACKAIAIgFqIQcgACABa0EJaiEGA0AgAUGWwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw2+AkECIAFBCUYNwgIaIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADOQCCyABIARGBEBByQAhAwzkAgsCQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxQe4Aaw4HAL8CvwK/Ar8CvwIBvwILIAFBAWohAUE+IQMMywILIAFBAWohAUE/IQMMygILQcoAIQMgBCABIgBGDeICIAQgAWsgAigCACIBaiEGIAAgAWtBAWohBwNAIAFBoMIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNvAIgAUEBRg2+AiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBjYCAAziAgtBywAhAyAEIAEiAEYN4QIgBCABayACKAIAIgFqIQcgACABa0EOaiEGA0AgAUGiwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw27AiABQQ5GDb4CIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADOECC0HMACEDIAQgASIARg3gAiAEIAFrIAIoAgAiAWohByAAIAFrQQ9qIQYDQCABQcDCAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDboCQQMgAUEPRg2+AhogAUEBaiEBIAQgAEEBaiIARw0ACyACIAc2AgAM4AILQc0AIQMgBCABIgBGDd8CIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgNAIAFB0MIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNuQJBBCABQQVGDb0CGiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBzYCAAzfAgsgASAERgRAQc4AIQMM3wILAkACQAJAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXFB4wBrDhMAvAK8ArwCvAK8ArwCvAK8ArwCvAK8ArwCAbwCvAK8AgIDvAILIAFBAWohAUHBACEDDMgCCyABQQFqIQFBwgAhAwzHAgsgAUEBaiEBQcMAIQMMxgILIAFBAWohAUHEACEDDMUCCyABIARHBEAgAkENNgIIIAIgATYCBEHFACEDDMUCC0HPACEDDN0CCwJAAkAgAS0AAEEKaw4EAZABkAEAkAELIAFBAWohAQtBKCEDDMMCCyABIARGBEBB0QAhAwzcAgsgAS0AAEEgRw0AIAFBAWohASACLQAtQQFxRQ3QAQtBFyEDDMECCyABIARHDcsBQdIAIQMM2QILQdMAIQMgASAERg3YAiACKAIAIgAgBCABa2ohBiABIABrQQFqIQUDQCABLQAAIABB1sIAai0AAEcNxwEgAEEBRg3KASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBjYCAAzYAgsgASAERgRAQdUAIQMM2AILIAEtAABBCkcNwgEgAUEBaiEBDMoBCyABIARGBEBB1gAhAwzXAgsCQAJAIAEtAABBCmsOBADDAcMBAcMBCyABQQFqIQEMygELIAFBAWohAUHKACEDDL0CC0EAIQACQCACKAI4IgNFDQAgAygCPCIDRQ0AIAIgAxEAACEACyAADb8BQc0AIQMMvAILIAItAClBIkYNzwIMiQELIAQgASIFRgRAQdsAIQMM1AILQQAhAEEBIQFBASEGQQAhAwJAAn8CQAJAAkACQAJAAkACQCAFLQAAQTBrDgrFAcQBAAECAwQFBgjDAQtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshA0EAIQFBACEGDL0BC0EJIQNBASEAQQAhAUEAIQYMvAELIAEgBEYEQEHdACEDDNMCCyABLQAAQS5HDbgBIAFBAWohAQyIAQsgASAERw22AUHfACEDDNECCyABIARHBEAgAkEONgIIIAIgATYCBEHQACEDDLgCC0HgACEDDNACC0HhACEDIAEgBEYNzwIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGA0AgAS0AACAAQeLCAGotAABHDbEBIABBA0YNswEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMzwILQeIAIQMgASAERg3OAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYDQCABLQAAIABB5sIAai0AAEcNsAEgAEECRg2vASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAzOAgtB4wAhAyABIARGDc0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgNAIAEtAAAgAEHpwgBqLQAARw2vASAAQQNGDa0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADM0CCyABIARGBEBB5QAhAwzNAgsgAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANqgFB1gAhAwyzAgsgASAERwRAA0AgAS0AACIAQSBHBEACQAJAAkAgAEHIAGsOCwABswGzAbMBswGzAbMBswGzAQKzAQsgAUEBaiEBQdIAIQMMtwILIAFBAWohAUHTACEDDLYCCyABQQFqIQFB1AAhAwy1AgsgBCABQQFqIgFHDQALQeQAIQMMzAILQeQAIQMMywILA0AgAS0AAEHwwgBqLQAAIgBBAUcEQCAAQQJrDgOnAaYBpQGkAQsgBCABQQFqIgFHDQALQeYAIQMMygILIAFBAWogASAERw0CGkHnACEDDMkCCwNAIAEtAABB8MQAai0AACIAQQFHBEACQCAAQQJrDgSiAaEBoAEAnwELQdcAIQMMsQILIAQgAUEBaiIBRw0AC0HoACEDDMgCCyABIARGBEBB6QAhAwzIAgsCQCABLQAAIgBBCmsOGrcBmwGbAbQBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBpAGbAZsBAJkBCyABQQFqCyEBQQYhAwytAgsDQCABLQAAQfDGAGotAABBAUcNfSAEIAFBAWoiAUcNAAtB6gAhAwzFAgsgAUEBaiABIARHDQIaQesAIQMMxAILIAEgBEYEQEHsACEDDMQCCyABQQFqDAELIAEgBEYEQEHtACEDDMMCCyABQQFqCyEBQQQhAwyoAgsgASAERgRAQe4AIQMMwQILAkACQAJAIAEtAABB8MgAai0AAEEBaw4HkAGPAY4BAHwBAo0BCyABQQFqIQEMCwsgAUEBagyTAQtBACEDIAJBADYCHCACQZsSNgIQIAJBBzYCDCACIAFBAWo2AhQMwAILAkADQCABLQAAQfDIAGotAAAiAEEERwRAAkACQCAAQQFrDgeUAZMBkgGNAQAEAY0BC0HaACEDDKoCCyABQQFqIQFB3AAhAwypAgsgBCABQQFqIgFHDQALQe8AIQMMwAILIAFBAWoMkQELIAQgASIARgRAQfAAIQMMvwILIAAtAABBL0cNASAAQQFqIQEMBwsgBCABIgBGBEBB8QAhAwy+AgsgAC0AACIBQS9GBEAgAEEBaiEBQd0AIQMMpQILIAFBCmsiA0EWSw0AIAAhAUEBIAN0QYmAgAJxDfkBC0EAIQMgAkEANgIcIAIgADYCFCACQYwcNgIQIAJBBzYCDAy8AgsgASAERwRAIAFBAWohAUHeACEDDKMCC0HyACEDDLsCCyABIARGBEBB9AAhAwy7AgsCQCABLQAAQfDMAGotAABBAWsOA/cBcwCCAQtB4QAhAwyhAgsgASAERwRAA0AgAS0AAEHwygBqLQAAIgBBA0cEQAJAIABBAWsOAvkBAIUBC0HfACEDDKMCCyAEIAFBAWoiAUcNAAtB8wAhAwy6AgtB8wAhAwy5AgsgASAERwRAIAJBDzYCCCACIAE2AgRB4AAhAwygAgtB9QAhAwy4AgsgASAERgRAQfYAIQMMuAILIAJBDzYCCCACIAE2AgQLQQMhAwydAgsDQCABLQAAQSBHDY4CIAQgAUEBaiIBRw0AC0H3ACEDDLUCCyABIARGBEBB+AAhAwy1AgsgAS0AAEEgRw16IAFBAWohAQxbC0EAIQACQCACKAI4IgNFDQAgAygCOCIDRQ0AIAIgAxEAACEACyAADXgMgAILIAEgBEYEQEH6ACEDDLMCCyABLQAAQcwARw10IAFBAWohAUETDHYLQfsAIQMgASAERg2xAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYDQCABLQAAIABB8M4Aai0AAEcNcyAAQQVGDXUgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMsQILIAEgBEYEQEH8ACEDDLECCwJAAkAgAS0AAEHDAGsODAB0dHR0dHR0dHR0AXQLIAFBAWohAUHmACEDDJgCCyABQQFqIQFB5wAhAwyXAgtB/QAhAyABIARGDa8CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDXIgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADLACCyACQQA2AgAgBkEBaiEBQRAMcwtB/gAhAyABIARGDa4CIAIoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQfbOAGotAABHDXEgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK8CCyACQQA2AgAgBkEBaiEBQRYMcgtB/wAhAyABIARGDa0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQfzOAGotAABHDXAgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK4CCyACQQA2AgAgBkEBaiEBQQUMcQsgASAERgRAQYABIQMMrQILIAEtAABB2QBHDW4gAUEBaiEBQQgMcAsgASAERgRAQYEBIQMMrAILAkACQCABLQAAQc4Aaw4DAG8BbwsgAUEBaiEBQesAIQMMkwILIAFBAWohAUHsACEDDJICCyABIARGBEBBggEhAwyrAgsCQAJAIAEtAABByABrDggAbm5ubm5uAW4LIAFBAWohAUHqACEDDJICCyABQQFqIQFB7QAhAwyRAgtBgwEhAyABIARGDakCIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQYDPAGotAABHDWwgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKoCCyACQQA2AgAgBkEBaiEBQQAMbQtBhAEhAyABIARGDagCIAIoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQYPPAGotAABHDWsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKkCCyACQQA2AgAgBkEBaiEBQSMMbAsgASAERgRAQYUBIQMMqAILAkACQCABLQAAQcwAaw4IAGtra2trawFrCyABQQFqIQFB7wAhAwyPAgsgAUEBaiEBQfAAIQMMjgILIAEgBEYEQEGGASEDDKcCCyABLQAAQcUARw1oIAFBAWohAQxgC0GHASEDIAEgBEYNpQIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBiM8Aai0AAEcNaCAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpgILIAJBADYCACAGQQFqIQFBLQxpC0GIASEDIAEgBEYNpAIgAigCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABB0M8Aai0AAEcNZyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpQILIAJBADYCACAGQQFqIQFBKQxoCyABIARGBEBBiQEhAwykAgtBASABLQAAQd8ARw1nGiABQQFqIQEMXgtBigEhAyABIARGDaICIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgNAIAEtAAAgAEGMzwBqLQAARw1kIABBAUYN+gEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMogILQYsBIQMgASAERg2hAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGOzwBqLQAARw1kIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyiAgsgAkEANgIAIAZBAWohAUECDGULQYwBIQMgASAERg2gAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHwzwBqLQAARw1jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyhAgsgAkEANgIAIAZBAWohAUEfDGQLQY0BIQMgASAERg2fAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHyzwBqLQAARw1iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAygAgsgAkEANgIAIAZBAWohAUEJDGMLIAEgBEYEQEGOASEDDJ8CCwJAAkAgAS0AAEHJAGsOBwBiYmJiYgFiCyABQQFqIQFB+AAhAwyGAgsgAUEBaiEBQfkAIQMMhQILQY8BIQMgASAERg2dAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGRzwBqLQAARw1gIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyeAgsgAkEANgIAIAZBAWohAUEYDGELQZABIQMgASAERg2cAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGXzwBqLQAARw1fIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAydAgsgAkEANgIAIAZBAWohAUEXDGALQZEBIQMgASAERg2bAiACKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIAEtAAAgAEGazwBqLQAARw1eIABBBkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAycAgsgAkEANgIAIAZBAWohAUEVDF8LQZIBIQMgASAERg2aAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGhzwBqLQAARw1dIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAybAgsgAkEANgIAIAZBAWohAUEeDF4LIAEgBEYEQEGTASEDDJoCCyABLQAAQcwARw1bIAFBAWohAUEKDF0LIAEgBEYEQEGUASEDDJkCCwJAAkAgAS0AAEHBAGsODwBcXFxcXFxcXFxcXFxcAVwLIAFBAWohAUH+ACEDDIACCyABQQFqIQFB/wAhAwz/AQsgASAERgRAQZUBIQMMmAILAkACQCABLQAAQcEAaw4DAFsBWwsgAUEBaiEBQf0AIQMM/wELIAFBAWohAUGAASEDDP4BC0GWASEDIAEgBEYNlgIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBp88Aai0AAEcNWSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlwILIAJBADYCACAGQQFqIQFBCwxaCyABIARGBEBBlwEhAwyWAgsCQAJAAkACQCABLQAAQS1rDiMAW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1sBW1tbW1sCW1tbA1sLIAFBAWohAUH7ACEDDP8BCyABQQFqIQFB/AAhAwz+AQsgAUEBaiEBQYEBIQMM/QELIAFBAWohAUGCASEDDPwBC0GYASEDIAEgBEYNlAIgAigCACIAIAQgAWtqIQUgASAAa0EEaiEGAkADQCABLQAAIABBqc8Aai0AAEcNVyAAQQRGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlQILIAJBADYCACAGQQFqIQFBGQxYC0GZASEDIAEgBEYNkwIgAigCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBrs8Aai0AAEcNViAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlAILIAJBADYCACAGQQFqIQFBBgxXC0GaASEDIAEgBEYNkgIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBtM8Aai0AAEcNVSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMkwILIAJBADYCACAGQQFqIQFBHAxWC0GbASEDIAEgBEYNkQIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBts8Aai0AAEcNVCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMkgILIAJBADYCACAGQQFqIQFBJwxVCyABIARGBEBBnAEhAwyRAgsCQAJAIAEtAABB1ABrDgIAAVQLIAFBAWohAUGGASEDDPgBCyABQQFqIQFBhwEhAwz3AQtBnQEhAyABIARGDY8CIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbjPAGotAABHDVIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADJACCyACQQA2AgAgBkEBaiEBQSYMUwtBngEhAyABIARGDY4CIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbrPAGotAABHDVEgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI8CCyACQQA2AgAgBkEBaiEBQQMMUgtBnwEhAyABIARGDY0CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDVAgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI4CCyACQQA2AgAgBkEBaiEBQQwMUQtBoAEhAyABIARGDYwCIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQbzPAGotAABHDU8gAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI0CCyACQQA2AgAgBkEBaiEBQQ0MUAsgASAERgRAQaEBIQMMjAILAkACQCABLQAAQcYAaw4LAE9PT09PT09PTwFPCyABQQFqIQFBiwEhAwzzAQsgAUEBaiEBQYwBIQMM8gELIAEgBEYEQEGiASEDDIsCCyABLQAAQdAARw1MIAFBAWohAQxGCyABIARGBEBBowEhAwyKAgsCQAJAIAEtAABByQBrDgcBTU1NTU0ATQsgAUEBaiEBQY4BIQMM8QELIAFBAWohAUEiDE0LQaQBIQMgASAERg2IAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHAzwBqLQAARw1LIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyJAgsgAkEANgIAIAZBAWohAUEdDEwLIAEgBEYEQEGlASEDDIgCCwJAAkAgAS0AAEHSAGsOAwBLAUsLIAFBAWohAUGQASEDDO8BCyABQQFqIQFBBAxLCyABIARGBEBBpgEhAwyHAgsCQAJAAkACQAJAIAEtAABBwQBrDhUATU1NTU1NTU1NTQFNTQJNTQNNTQRNCyABQQFqIQFBiAEhAwzxAQsgAUEBaiEBQYkBIQMM8AELIAFBAWohAUGKASEDDO8BCyABQQFqIQFBjwEhAwzuAQsgAUEBaiEBQZEBIQMM7QELQacBIQMgASAERg2FAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHtzwBqLQAARw1IIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyGAgsgAkEANgIAIAZBAWohAUERDEkLQagBIQMgASAERg2EAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHCzwBqLQAARw1HIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyFAgsgAkEANgIAIAZBAWohAUEsDEgLQakBIQMgASAERg2DAiACKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHFzwBqLQAARw1GIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyEAgsgAkEANgIAIAZBAWohAUErDEcLQaoBIQMgASAERg2CAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHKzwBqLQAARw1FIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyDAgsgAkEANgIAIAZBAWohAUEUDEYLIAEgBEYEQEGrASEDDIICCwJAAkACQAJAIAEtAABBwgBrDg8AAQJHR0dHR0dHR0dHRwNHCyABQQFqIQFBkwEhAwzrAQsgAUEBaiEBQZQBIQMM6gELIAFBAWohAUGVASEDDOkBCyABQQFqIQFBlgEhAwzoAQsgASAERgRAQawBIQMMgQILIAEtAABBxQBHDUIgAUEBaiEBDD0LQa0BIQMgASAERg3/ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHNzwBqLQAARw1CIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyAAgsgAkEANgIAIAZBAWohAUEODEMLIAEgBEYEQEGuASEDDP8BCyABLQAAQdAARw1AIAFBAWohAUElDEILQa8BIQMgASAERg39ASACKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEHQzwBqLQAARw1AIABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz+AQsgAkEANgIAIAZBAWohAUEqDEELIAEgBEYEQEGwASEDDP0BCwJAAkAgAS0AAEHVAGsOCwBAQEBAQEBAQEABQAsgAUEBaiEBQZoBIQMM5AELIAFBAWohAUGbASEDDOMBCyABIARGBEBBsQEhAwz8AQsCQAJAIAEtAABBwQBrDhQAPz8/Pz8/Pz8/Pz8/Pz8/Pz8/AT8LIAFBAWohAUGZASEDDOMBCyABQQFqIQFBnAEhAwziAQtBsgEhAyABIARGDfoBIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQdnPAGotAABHDT0gAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPsBCyACQQA2AgAgBkEBaiEBQSEMPgtBswEhAyABIARGDfkBIAIoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAS0AACAAQd3PAGotAABHDTwgAEEGRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPoBCyACQQA2AgAgBkEBaiEBQRoMPQsgASAERgRAQbQBIQMM+QELAkACQAJAIAEtAABBxQBrDhEAPT09PT09PT09AT09PT09Aj0LIAFBAWohAUGdASEDDOEBCyABQQFqIQFBngEhAwzgAQsgAUEBaiEBQZ8BIQMM3wELQbUBIQMgASAERg33ASACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHkzwBqLQAARw06IABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz4AQsgAkEANgIAIAZBAWohAUEoDDsLQbYBIQMgASAERg32ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHqzwBqLQAARw05IABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz3AQsgAkEANgIAIAZBAWohAUEHDDoLIAEgBEYEQEG3ASEDDPYBCwJAAkAgAS0AAEHFAGsODgA5OTk5OTk5OTk5OTkBOQsgAUEBaiEBQaEBIQMM3QELIAFBAWohAUGiASEDDNwBC0G4ASEDIAEgBEYN9AEgAigCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB7c8Aai0AAEcNNyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM9QELIAJBADYCACAGQQFqIQFBEgw4C0G5ASEDIAEgBEYN8wEgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8M8Aai0AAEcNNiAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM9AELIAJBADYCACAGQQFqIQFBIAw3C0G6ASEDIAEgBEYN8gEgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8s8Aai0AAEcNNSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM8wELIAJBADYCACAGQQFqIQFBDww2CyABIARGBEBBuwEhAwzyAQsCQAJAIAEtAABByQBrDgcANTU1NTUBNQsgAUEBaiEBQaUBIQMM2QELIAFBAWohAUGmASEDDNgBC0G8ASEDIAEgBEYN8AEgAigCACIAIAQgAWtqIQUgASAAa0EHaiEGAkADQCABLQAAIABB9M8Aai0AAEcNMyAAQQdGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM8QELIAJBADYCACAGQQFqIQFBGww0CyABIARGBEBBvQEhAwzwAQsCQAJAAkAgAS0AAEHCAGsOEgA0NDQ0NDQ0NDQBNDQ0NDQ0AjQLIAFBAWohAUGkASEDDNgBCyABQQFqIQFBpwEhAwzXAQsgAUEBaiEBQagBIQMM1gELIAEgBEYEQEG+ASEDDO8BCyABLQAAQc4ARw0wIAFBAWohAQwsCyABIARGBEBBvwEhAwzuAQsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABLQAAQcEAaw4VAAECAz8EBQY/Pz8HCAkKCz8MDQ4PPwsgAUEBaiEBQegAIQMM4wELIAFBAWohAUHpACEDDOIBCyABQQFqIQFB7gAhAwzhAQsgAUEBaiEBQfIAIQMM4AELIAFBAWohAUHzACEDDN8BCyABQQFqIQFB9gAhAwzeAQsgAUEBaiEBQfcAIQMM3QELIAFBAWohAUH6ACEDDNwBCyABQQFqIQFBgwEhAwzbAQsgAUEBaiEBQYQBIQMM2gELIAFBAWohAUGFASEDDNkBCyABQQFqIQFBkgEhAwzYAQsgAUEBaiEBQZgBIQMM1wELIAFBAWohAUGgASEDDNYBCyABQQFqIQFBowEhAwzVAQsgAUEBaiEBQaoBIQMM1AELIAEgBEcEQCACQRA2AgggAiABNgIEQasBIQMM1AELQcABIQMM7AELQQAhAAJAIAIoAjgiA0UNACADKAI0IgNFDQAgAiADEQAAIQALIABFDV4gAEEVRw0HIAJB0QA2AhwgAiABNgIUIAJBsBc2AhAgAkEVNgIMQQAhAwzrAQsgAUEBaiABIARHDQgaQcIBIQMM6gELA0ACQCABLQAAQQprDgQIAAALAAsgBCABQQFqIgFHDQALQcMBIQMM6QELIAEgBEcEQCACQRE2AgggAiABNgIEQQEhAwzQAQtBxAEhAwzoAQsgASAERgRAQcUBIQMM6AELAkACQCABLQAAQQprDgQBKCgAKAsgAUEBagwJCyABQQFqDAULIAEgBEYEQEHGASEDDOcBCwJAAkAgAS0AAEEKaw4XAQsLAQsLCwsLCwsLCwsLCwsLCwsLCwALCyABQQFqIQELQbABIQMMzQELIAEgBEYEQEHIASEDDOYBCyABLQAAQSBHDQkgAkEAOwEyIAFBAWohAUGzASEDDMwBCwNAIAEhAAJAIAEgBEcEQCABLQAAQTBrQf8BcSIDQQpJDQEMJwtBxwEhAwzmAQsCQCACLwEyIgFBmTNLDQAgAiABQQpsIgU7ATIgBUH+/wNxIANB//8Dc0sNACAAQQFqIQEgAiADIAVqIgM7ATIgA0H//wNxQegHSQ0BCwtBACEDIAJBADYCHCACQcEJNgIQIAJBDTYCDCACIABBAWo2AhQM5AELIAJBADYCHCACIAE2AhQgAkHwDDYCECACQRs2AgxBACEDDOMBCyACKAIEIQAgAkEANgIEIAIgACABECYiAA0BIAFBAWoLIQFBrQEhAwzIAQsgAkHBATYCHCACIAA2AgwgAiABQQFqNgIUQQAhAwzgAQsgAigCBCEAIAJBADYCBCACIAAgARAmIgANASABQQFqCyEBQa4BIQMMxQELIAJBwgE2AhwgAiAANgIMIAIgAUEBajYCFEEAIQMM3QELIAJBADYCHCACIAE2AhQgAkGXCzYCECACQQ02AgxBACEDDNwBCyACQQA2AhwgAiABNgIUIAJB4xA2AhAgAkEJNgIMQQAhAwzbAQsgAkECOgAoDKwBC0EAIQMgAkEANgIcIAJBrws2AhAgAkECNgIMIAIgAUEBajYCFAzZAQtBAiEDDL8BC0ENIQMMvgELQSYhAwy9AQtBFSEDDLwBC0EWIQMMuwELQRghAwy6AQtBHCEDDLkBC0EdIQMMuAELQSAhAwy3AQtBISEDDLYBC0EjIQMMtQELQcYAIQMMtAELQS4hAwyzAQtBPSEDDLIBC0HLACEDDLEBC0HOACEDDLABC0HYACEDDK8BC0HZACEDDK4BC0HbACEDDK0BC0HxACEDDKwBC0H0ACEDDKsBC0GNASEDDKoBC0GXASEDDKkBC0GpASEDDKgBC0GvASEDDKcBC0GxASEDDKYBCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJB8Rs2AhAgAkEGNgIMDL0BCyACQQA2AgAgBkEBaiEBQSQLOgApIAIoAgQhACACQQA2AgQgAiAAIAEQJyIARQRAQeUAIQMMowELIAJB+QA2AhwgAiABNgIUIAIgADYCDEEAIQMMuwELIABBFUcEQCACQQA2AhwgAiABNgIUIAJBzA42AhAgAkEgNgIMQQAhAwy7AQsgAkH4ADYCHCACIAE2AhQgAkHKGDYCECACQRU2AgxBACEDDLoBCyACQQA2AhwgAiABNgIUIAJBjhs2AhAgAkEGNgIMQQAhAwy5AQsgAkEANgIcIAIgATYCFCACQf4RNgIQIAJBBzYCDEEAIQMMuAELIAJBADYCHCACIAE2AhQgAkGMHDYCECACQQc2AgxBACEDDLcBCyACQQA2AhwgAiABNgIUIAJBww82AhAgAkEHNgIMQQAhAwy2AQsgAkEANgIcIAIgATYCFCACQcMPNgIQIAJBBzYCDEEAIQMMtQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0RIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMtAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0gIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMswELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0iIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMsgELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0OIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMsQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0dIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMsAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0fIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMrwELIABBP0cNASABQQFqCyEBQQUhAwyUAQtBACEDIAJBADYCHCACIAE2AhQgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwyjAQtB1QAhAwyJAQsgAEEVRwRAIAJBADYCHCACIAE2AhQgAkG5DTYCECACQRo2AgxBACEDDKIBCyACQeQANgIcIAIgATYCFCACQeMXNgIQIAJBFTYCDEEAIQMMoQELIAJBADYCACAGQQFqIQEgAi0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACEDIAJBADYCHCACIAE2AhQgAkH3CTYCECACQQg2AgwMoAELIAJBADYCACAGQQFqIQEgAi0AKUEhRg0DIAJBADYCHCACIAE2AhQgAkGbCjYCECACQQg2AgxBACEDDJ8BCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJBkDM2AhAgAkEINgIMDJ0BCyACQQA2AgAgBkEBaiEBIAItAClBI0kNACACQQA2AhwgAiABNgIUIAJB0wk2AhAgAkEINgIMQQAhAwycAQtB0QAhAwyCAQsgAS0AAEEwayIAQf8BcUEKSQRAIAIgADoAKiABQQFqIQFBzwAhAwyCAQsgAigCBCEAIAJBADYCBCACIAAgARAoIgBFDYYBIAJB3gA2AhwgAiABNgIUIAIgADYCDEEAIQMMmgELIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ2GASACQdwANgIcIAIgATYCFCACIAA2AgxBACEDDJkBCyACKAIEIQAgAkEANgIEIAIgACAFECgiAEUEQCAFIQEMhwELIAJB2gA2AhwgAiAFNgIUIAIgADYCDAyYAQtBACEBQQEhAwsgAiADOgArIAVBAWohAwJAAkACQCACLQAtQRBxDQACQAJAAkAgAi0AKg4DAQACBAsgBkUNAwwCCyAADQEMAgsgAUUNAQsgAigCBCEAIAJBADYCBCACIAAgAxAoIgBFBEAgAyEBDAILIAJB2AA2AhwgAiADNgIUIAIgADYCDEEAIQMMmAELIAIoAgQhACACQQA2AgQgAiAAIAMQKCIARQRAIAMhAQyHAQsgAkHZADYCHCACIAM2AhQgAiAANgIMQQAhAwyXAQtBzAAhAwx9CyAAQRVHBEAgAkEANgIcIAIgATYCFCACQZQNNgIQIAJBITYCDEEAIQMMlgELIAJB1wA2AhwgAiABNgIUIAJByRc2AhAgAkEVNgIMQQAhAwyVAQtBACEDIAJBADYCHCACIAE2AhQgAkGAETYCECACQQk2AgwMlAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0AIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMkwELQckAIQMMeQsgAkEANgIcIAIgATYCFCACQcEoNgIQIAJBBzYCDCACQQA2AgBBACEDDJEBCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAlIgBFDQAgAkHSADYCHCACIAE2AhQgAiAANgIMDJABC0HIACEDDHYLIAJBADYCACAFIQELIAJBgBI7ASogAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANAQtBxwAhAwxzCyAAQRVGBEAgAkHRADYCHCACIAE2AhQgAkHjFzYCECACQRU2AgxBACEDDIwBC0EAIQMgAkEANgIcIAIgATYCFCACQbkNNgIQIAJBGjYCDAyLAQtBACEDIAJBADYCHCACIAE2AhQgAkGgGTYCECACQR42AgwMigELIAEtAABBOkYEQCACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgBFDQEgAkHDADYCHCACIAA2AgwgAiABQQFqNgIUDIoBC0EAIQMgAkEANgIcIAIgATYCFCACQbERNgIQIAJBCjYCDAyJAQsgAUEBaiEBQTshAwxvCyACQcMANgIcIAIgADYCDCACIAFBAWo2AhQMhwELQQAhAyACQQA2AhwgAiABNgIUIAJB8A42AhAgAkEcNgIMDIYBCyACIAIvATBBEHI7ATAMZgsCQCACLwEwIgBBCHFFDQAgAi0AKEEBRw0AIAItAC1BCHFFDQMLIAIgAEH3+wNxQYAEcjsBMAwECyABIARHBEACQANAIAEtAABBMGsiAEH/AXFBCk8EQEE1IQMMbgsgAikDICIKQpmz5syZs+bMGVYNASACIApCCn4iCjcDICAKIACtQv8BgyILQn+FVg0BIAIgCiALfDcDICAEIAFBAWoiAUcNAAtBOSEDDIUBCyACKAIEIQBBACEDIAJBADYCBCACIAAgAUEBaiIBECoiAA0MDHcLQTkhAwyDAQsgAi0AMEEgcQ0GQcUBIQMMaQtBACEDIAJBADYCBCACIAEgARAqIgBFDQQgAkE6NgIcIAIgADYCDCACIAFBAWo2AhQMgQELIAItAChBAUcNACACLQAtQQhxRQ0BC0E3IQMMZgsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIABEAgAkE7NgIcIAIgADYCDCACIAFBAWo2AhQMfwsgAUEBaiEBDG4LIAJBCDoALAwECyABQQFqIQEMbQtBACEDIAJBADYCHCACIAE2AhQgAkHkEjYCECACQQQ2AgwMewsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIARQ1sIAJBNzYCHCACIAE2AhQgAiAANgIMDHoLIAIgAi8BMEEgcjsBMAtBMCEDDF8LIAJBNjYCHCACIAE2AhQgAiAANgIMDHcLIABBLEcNASABQQFqIQBBASEBAkACQAJAAkACQCACLQAsQQVrDgQDAQIEAAsgACEBDAQLQQIhAQwBC0EEIQELIAJBAToALCACIAIvATAgAXI7ATAgACEBDAELIAIgAi8BMEEIcjsBMCAAIQELQTkhAwxcCyACQQA6ACwLQTQhAwxaCyABIARGBEBBLSEDDHMLAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0EtIQMMdAsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIARQ0CIAJBLDYCHCACIAE2AhQgAiAANgIMDHMLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABECoiAEUEQCABQQFqIQEMAgsgAkEsNgIcIAIgADYCDCACIAFBAWo2AhQMcgsgAS0AAEENRgRAIAIoAgQhAEEAIQMgAkEANgIEIAIgACABECoiAEUEQCABQQFqIQEMAgsgAkEsNgIcIAIgADYCDCACIAFBAWo2AhQMcgsgAi0ALUEBcQRAQcQBIQMMWQsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIADQEMZQtBLyEDDFcLIAJBLjYCHCACIAE2AhQgAiAANgIMDG8LQQAhAyACQQA2AhwgAiABNgIUIAJB8BQ2AhAgAkEDNgIMDG4LQQEhAwJAAkACQAJAIAItACxBBWsOBAMBAgAECyACIAIvATBBCHI7ATAMAwtBAiEDDAELQQQhAwsgAkEBOgAsIAIgAi8BMCADcjsBMAtBKiEDDFMLQQAhAyACQQA2AhwgAiABNgIUIAJB4Q82AhAgAkEKNgIMDGsLQQEhAwJAAkACQAJAAkACQCACLQAsQQJrDgcFBAQDAQIABAsgAiACLwEwQQhyOwEwDAMLQQIhAwwBC0EEIQMLIAJBAToALCACIAIvATAgA3I7ATALQSshAwxSC0EAIQMgAkEANgIcIAIgATYCFCACQasSNgIQIAJBCzYCDAxqC0EAIQMgAkEANgIcIAIgATYCFCACQf0NNgIQIAJBHTYCDAxpCyABIARHBEADQCABLQAAQSBHDUggBCABQQFqIgFHDQALQSUhAwxpC0ElIQMMaAsgAi0ALUEBcQRAQcMBIQMMTwsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKSIABEAgAkEmNgIcIAIgADYCDCACIAFBAWo2AhQMaAsgAUEBaiEBDFwLIAFBAWohASACLwEwIgBBgAFxBEBBACEAAkAgAigCOCIDRQ0AIAMoAlQiA0UNACACIAMRAAAhAAsgAEUNBiAAQRVHDR8gAkEFNgIcIAIgATYCFCACQfkXNgIQIAJBFTYCDEEAIQMMZwsCQCAAQaAEcUGgBEcNACACLQAtQQJxDQBBACEDIAJBADYCHCACIAE2AhQgAkGWEzYCECACQQQ2AgwMZwsgAgJ/IAIvATBBFHFBFEYEQEEBIAItAChBAUYNARogAi8BMkHlAEYMAQsgAi0AKUEFRgs6AC5BACEAAkAgAigCOCIDRQ0AIAMoAiQiA0UNACACIAMRAAAhAAsCQAJAAkACQAJAIAAOFgIBAAQEBAQEBAQEBAQEBAQEBAQEBAMECyACQQE6AC4LIAIgAi8BMEHAAHI7ATALQSchAwxPCyACQSM2AhwgAiABNgIUIAJBpRY2AhAgAkEVNgIMQQAhAwxnC0EAIQMgAkEANgIcIAIgATYCFCACQdULNgIQIAJBETYCDAxmC0EAIQACQCACKAI4IgNFDQAgAygCLCIDRQ0AIAIgAxEAACEACyAADQELQQ4hAwxLCyAAQRVGBEAgAkECNgIcIAIgATYCFCACQbAYNgIQIAJBFTYCDEEAIQMMZAtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMYwtBACEDIAJBADYCHCACIAE2AhQgAkGqHDYCECACQQ82AgwMYgsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEgCqdqIgEQKyIARQ0AIAJBBTYCHCACIAE2AhQgAiAANgIMDGELQQ8hAwxHC0EAIQMgAkEANgIcIAIgATYCFCACQc0TNgIQIAJBDDYCDAxfC0IBIQoLIAFBAWohAQJAIAIpAyAiC0L//////////w9YBEAgAiALQgSGIAqENwMgDAELQQAhAyACQQA2AhwgAiABNgIUIAJBrQk2AhAgAkEMNgIMDF4LQSQhAwxEC0EAIQMgAkEANgIcIAIgATYCFCACQc0TNgIQIAJBDDYCDAxcCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAsIgBFBEAgAUEBaiEBDFILIAJBFzYCHCACIAA2AgwgAiABQQFqNgIUDFsLIAIoAgQhAEEAIQMgAkEANgIEAkAgAiAAIAEQLCIARQRAIAFBAWohAQwBCyACQRY2AhwgAiAANgIMIAIgAUEBajYCFAxbC0EfIQMMQQtBACEDIAJBADYCHCACIAE2AhQgAkGaDzYCECACQSI2AgwMWQsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQLSIARQRAIAFBAWohAQxQCyACQRQ2AhwgAiAANgIMIAIgAUEBajYCFAxYCyACKAIEIQBBACEDIAJBADYCBAJAIAIgACABEC0iAEUEQCABQQFqIQEMAQsgAkETNgIcIAIgADYCDCACIAFBAWo2AhQMWAtBHiEDDD4LQQAhAyACQQA2AhwgAiABNgIUIAJBxgw2AhAgAkEjNgIMDFYLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABEC0iAEUEQCABQQFqIQEMTgsgAkERNgIcIAIgADYCDCACIAFBAWo2AhQMVQsgAkEQNgIcIAIgATYCFCACIAA2AgwMVAtBACEDIAJBADYCHCACIAE2AhQgAkHGDDYCECACQSM2AgwMUwtBACEDIAJBADYCHCACIAE2AhQgAkHAFTYCECACQQI2AgwMUgsgAigCBCEAQQAhAyACQQA2AgQCQCACIAAgARAtIgBFBEAgAUEBaiEBDAELIAJBDjYCHCACIAA2AgwgAiABQQFqNgIUDFILQRshAww4C0EAIQMgAkEANgIcIAIgATYCFCACQcYMNgIQIAJBIzYCDAxQCyACKAIEIQBBACEDIAJBADYCBAJAIAIgACABECwiAEUEQCABQQFqIQEMAQsgAkENNgIcIAIgADYCDCACIAFBAWo2AhQMUAtBGiEDDDYLQQAhAyACQQA2AhwgAiABNgIUIAJBmg82AhAgAkEiNgIMDE4LIAIoAgQhAEEAIQMgAkEANgIEAkAgAiAAIAEQLCIARQRAIAFBAWohAQwBCyACQQw2AhwgAiAANgIMIAIgAUEBajYCFAxOC0EZIQMMNAtBACEDIAJBADYCHCACIAE2AhQgAkGaDzYCECACQSI2AgwMTAsgAEEVRwRAQQAhAyACQQA2AhwgAiABNgIUIAJBgww2AhAgAkETNgIMDEwLIAJBCjYCHCACIAE2AhQgAkHkFjYCECACQRU2AgxBACEDDEsLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABIAqnaiIBECsiAARAIAJBBzYCHCACIAE2AhQgAiAANgIMDEsLQRMhAwwxCyAAQRVHBEBBACEDIAJBADYCHCACIAE2AhQgAkHaDTYCECACQRQ2AgwMSgsgAkEeNgIcIAIgATYCFCACQfkXNgIQIAJBFTYCDEEAIQMMSQtBACEAAkAgAigCOCIDRQ0AIAMoAiwiA0UNACACIAMRAAAhAAsgAEUNQSAAQRVGBEAgAkEDNgIcIAIgATYCFCACQbAYNgIQIAJBFTYCDEEAIQMMSQtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMSAtBACEDIAJBADYCHCACIAE2AhQgAkHaDTYCECACQRQ2AgwMRwtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMRgsgAkEAOgAvIAItAC1BBHFFDT8LIAJBADoALyACQQE6ADRBACEDDCsLQQAhAyACQQA2AhwgAkHkETYCECACQQc2AgwgAiABQQFqNgIUDEMLAkADQAJAIAEtAABBCmsOBAACAgACCyAEIAFBAWoiAUcNAAtB3QEhAwxDCwJAAkAgAi0ANEEBRw0AQQAhAAJAIAIoAjgiA0UNACADKAJYIgNFDQAgAiADEQAAIQALIABFDQAgAEEVRw0BIAJB3AE2AhwgAiABNgIUIAJB1RY2AhAgAkEVNgIMQQAhAwxEC0HBASEDDCoLIAJBADYCHCACIAE2AhQgAkHpCzYCECACQR82AgxBACEDDEILAkACQCACLQAoQQFrDgIEAQALQcABIQMMKQtBuQEhAwwoCyACQQI6AC9BACEAAkAgAigCOCIDRQ0AIAMoAgAiA0UNACACIAMRAAAhAAsgAEUEQEHCASEDDCgLIABBFUcEQCACQQA2AhwgAiABNgIUIAJBpAw2AhAgAkEQNgIMQQAhAwxBCyACQdsBNgIcIAIgATYCFCACQfoWNgIQIAJBFTYCDEEAIQMMQAsgASAERgRAQdoBIQMMQAsgAS0AAEHIAEYNASACQQE6ACgLQawBIQMMJQtBvwEhAwwkCyABIARHBEAgAkEQNgIIIAIgATYCBEG+ASEDDCQLQdkBIQMMPAsgASAERgRAQdgBIQMMPAsgAS0AAEHIAEcNBCABQQFqIQFBvQEhAwwiCyABIARGBEBB1wEhAww7CwJAAkAgAS0AAEHFAGsOEAAFBQUFBQUFBQUFBQUFBQEFCyABQQFqIQFBuwEhAwwiCyABQQFqIQFBvAEhAwwhC0HWASEDIAEgBEYNOSACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGD0ABqLQAARw0DIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAw6CyACKAIEIQAgAkIANwMAIAIgACAGQQFqIgEQJyIARQRAQcYBIQMMIQsgAkHVATYCHCACIAE2AhQgAiAANgIMQQAhAww5C0HUASEDIAEgBEYNOCACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGB0ABqLQAARw0CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAw5CyACQYEEOwEoIAIoAgQhACACQgA3AwAgAiAAIAZBAWoiARAnIgANAwwCCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJB2Bs2AhAgAkEINgIMDDYLQboBIQMMHAsgAkHTATYCHCACIAE2AhQgAiAANgIMQQAhAww0C0EAIQACQCACKAI4IgNFDQAgAygCOCIDRQ0AIAIgAxEAACEACyAARQ0AIABBFUYNASACQQA2AhwgAiABNgIUIAJBzA42AhAgAkEgNgIMQQAhAwwzC0HkACEDDBkLIAJB+AA2AhwgAiABNgIUIAJByhg2AhAgAkEVNgIMQQAhAwwxC0HSASEDIAQgASIARg0wIAQgAWsgAigCACIBaiEFIAAgAWtBBGohBgJAA0AgAC0AACABQfzPAGotAABHDQEgAUEERg0DIAFBAWohASAEIABBAWoiAEcNAAsgAiAFNgIADDELIAJBADYCHCACIAA2AhQgAkGQMzYCECACQQg2AgwgAkEANgIAQQAhAwwwCyABIARHBEAgAkEONgIIIAIgATYCBEG3ASEDDBcLQdEBIQMMLwsgAkEANgIAIAZBAWohAQtBuAEhAwwUCyABIARGBEBB0AEhAwwtCyABLQAAQTBrIgBB/wFxQQpJBEAgAiAAOgAqIAFBAWohAUG2ASEDDBQLIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ0UIAJBzwE2AhwgAiABNgIUIAIgADYCDEEAIQMMLAsgASAERgRAQc4BIQMMLAsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ0VIAJBzQE2AhwgAiABNgIUIAIgADYCDEEAIQMMLAtBtQEhAwwSCyAEIAEiBUYEQEHMASEDDCsLQQAhAEEBIQFBASEGQQAhAwJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAUtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyEDQQAhAUEAIQYMAgtBCSEDQQEhAEEAIQFBACEGDAELQQAhAUEBIQMLIAIgAzoAKyAFQQFqIQMCQAJAIAItAC1BEHENAAJAAkACQCACLQAqDgMBAAIECyAGRQ0DDAILIAANAQwCCyABRQ0BCyACKAIEIQAgAkEANgIEIAIgACADECgiAEUEQCADIQEMAwsgAkHJATYCHCACIAM2AhQgAiAANgIMQQAhAwwtCyACKAIEIQAgAkEANgIEIAIgACADECgiAEUEQCADIQEMGAsgAkHKATYCHCACIAM2AhQgAiAANgIMQQAhAwwsCyACKAIEIQAgAkEANgIEIAIgACAFECgiAEUEQCAFIQEMFgsgAkHLATYCHCACIAU2AhQgAiAANgIMDCsLQbQBIQMMEQtBACEAAkAgAigCOCIDRQ0AIAMoAjwiA0UNACACIAMRAAAhAAsCQCAABEAgAEEVRg0BIAJBADYCHCACIAE2AhQgAkGUDTYCECACQSE2AgxBACEDDCsLQbIBIQMMEQsgAkHIATYCHCACIAE2AhQgAkHJFzYCECACQRU2AgxBACEDDCkLIAJBADYCACAGQQFqIQFB9QAhAwwPCyACLQApQQVGBEBB4wAhAwwPC0HiACEDDA4LIAAhASACQQA2AgALIAJBADoALEEJIQMMDAsgAkEANgIAIAdBAWohAUHAACEDDAsLQQELOgAsIAJBADYCACAGQQFqIQELQSkhAwwIC0E4IQMMBwsCQCABIARHBEADQCABLQAAQYA+ai0AACIAQQFHBEAgAEECRw0DIAFBAWohAQwFCyAEIAFBAWoiAUcNAAtBPiEDDCELQT4hAwwgCwsgAkEAOgAsDAELQQshAwwEC0E6IQMMAwsgAUEBaiEBQS0hAwwCCyACIAE6ACwgAkEANgIAIAZBAWohAUEMIQMMAQsgAkEANgIAIAZBAWohAUEKIQMMAAsAC0EAIQMgAkEANgIcIAIgATYCFCACQc0QNgIQIAJBCTYCDAwXC0EAIQMgAkEANgIcIAIgATYCFCACQekKNgIQIAJBCTYCDAwWC0EAIQMgAkEANgIcIAIgATYCFCACQbcQNgIQIAJBCTYCDAwVC0EAIQMgAkEANgIcIAIgATYCFCACQZwRNgIQIAJBCTYCDAwUC0EAIQMgAkEANgIcIAIgATYCFCACQc0QNgIQIAJBCTYCDAwTC0EAIQMgAkEANgIcIAIgATYCFCACQekKNgIQIAJBCTYCDAwSC0EAIQMgAkEANgIcIAIgATYCFCACQbcQNgIQIAJBCTYCDAwRC0EAIQMgAkEANgIcIAIgATYCFCACQZwRNgIQIAJBCTYCDAwQC0EAIQMgAkEANgIcIAIgATYCFCACQZcVNgIQIAJBDzYCDAwPC0EAIQMgAkEANgIcIAIgATYCFCACQZcVNgIQIAJBDzYCDAwOC0EAIQMgAkEANgIcIAIgATYCFCACQcASNgIQIAJBCzYCDAwNC0EAIQMgAkEANgIcIAIgATYCFCACQZUJNgIQIAJBCzYCDAwMC0EAIQMgAkEANgIcIAIgATYCFCACQeEPNgIQIAJBCjYCDAwLC0EAIQMgAkEANgIcIAIgATYCFCACQfsPNgIQIAJBCjYCDAwKC0EAIQMgAkEANgIcIAIgATYCFCACQfEZNgIQIAJBAjYCDAwJC0EAIQMgAkEANgIcIAIgATYCFCACQcQUNgIQIAJBAjYCDAwIC0EAIQMgAkEANgIcIAIgATYCFCACQfIVNgIQIAJBAjYCDAwHCyACQQI2AhwgAiABNgIUIAJBnBo2AhAgAkEWNgIMQQAhAwwGC0EBIQMMBQtB1AAhAyABIARGDQQgCEEIaiEJIAIoAgAhBQJAAkAgASAERwRAIAVB2MIAaiEHIAQgBWogAWshACAFQX9zQQpqIgUgAWohBgNAIAEtAAAgBy0AAEcEQEECIQcMAwsgBUUEQEEAIQcgBiEBDAMLIAVBAWshBSAHQQFqIQcgBCABQQFqIgFHDQALIAAhBSAEIQELIAlBATYCACACIAU2AgAMAQsgAkEANgIAIAkgBzYCAAsgCSABNgIEIAgoAgwhACAIKAIIDgMBBAIACwALIAJBADYCHCACQbUaNgIQIAJBFzYCDCACIABBAWo2AhRBACEDDAILIAJBADYCHCACIAA2AhQgAkHKGjYCECACQQk2AgxBACEDDAELIAEgBEYEQEEiIQMMAQsgAkEJNgIIIAIgATYCBEEhIQMLIAhBEGokACADRQRAIAIoAgwhAAwBCyACIAM2AhxBACEAIAIoAgQiAUUNACACIAEgBCACKAIIEQEAIgFFDQAgAiAENgIUIAIgATYCDCABIQALIAALvgIBAn8gAEEAOgAAIABB3ABqIgFBAWtBADoAACAAQQA6AAIgAEEAOgABIAFBA2tBADoAACABQQJrQQA6AAAgAEEAOgADIAFBBGtBADoAAEEAIABrQQNxIgEgAGoiAEEANgIAQdwAIAFrQXxxIgIgAGoiAUEEa0EANgIAAkAgAkEJSQ0AIABBADYCCCAAQQA2AgQgAUEIa0EANgIAIAFBDGtBADYCACACQRlJDQAgAEEANgIYIABBADYCFCAAQQA2AhAgAEEANgIMIAFBEGtBADYCACABQRRrQQA2AgAgAUEYa0EANgIAIAFBHGtBADYCACACIABBBHFBGHIiAmsiAUEgSQ0AIAAgAmohAANAIABCADcDGCAAQgA3AxAgAEIANwMIIABCADcDACAAQSBqIQAgAUEgayIBQR9LDQALCwtWAQF/AkAgACgCDA0AAkACQAJAAkAgAC0ALw4DAQADAgsgACgCOCIBRQ0AIAEoAiwiAUUNACAAIAERAAAiAQ0DC0EADwsACyAAQcMWNgIQQQ4hAQsgAQsaACAAKAIMRQRAIABB0Rs2AhAgAEEVNgIMCwsUACAAKAIMQRVGBEAgAEEANgIMCwsUACAAKAIMQRZGBEAgAEEANgIMCwsHACAAKAIMCwcAIAAoAhALCQAgACABNgIQCwcAIAAoAhQLFwAgAEEkTwRAAAsgAEECdEGgM2ooAgALFwAgAEEuTwRAAAsgAEECdEGwNGooAgALvwkBAX9B6yghAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB5ABrDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0HhJw8LQaQhDwtByywPC0H+MQ8LQcAkDwtBqyQPC0GNKA8LQeImDwtBgDAPC0G5Lw8LQdckDwtB7x8PC0HhHw8LQfofDwtB8iAPC0GoLw8LQa4yDwtBiDAPC0HsJw8LQYIiDwtBjh0PC0HQLg8LQcojDwtBxTIPC0HfHA8LQdIcDwtBxCAPC0HXIA8LQaIfDwtB7S4PC0GrMA8LQdQlDwtBzC4PC0H6Lg8LQfwrDwtB0jAPC0HxHQ8LQbsgDwtB9ysPC0GQMQ8LQdcxDwtBoi0PC0HUJw8LQeArDwtBnywPC0HrMQ8LQdUfDwtByjEPC0HeJQ8LQdQeDwtB9BwPC0GnMg8LQbEdDwtBoB0PC0G5MQ8LQbwwDwtBkiEPC0GzJg8LQeksDwtBrB4PC0HUKw8LQfcmDwtBgCYPC0GwIQ8LQf4eDwtBjSMPC0GJLQ8LQfciDwtBoDEPC0GuHw8LQcYlDwtB6B4PC0GTIg8LQcIvDwtBwx0PC0GLLA8LQeEdDwtBjS8PC0HqIQ8LQbQtDwtB0i8PC0HfMg8LQdIyDwtB8DAPC0GpIg8LQfkjDwtBmR4PC0G1LA8LQZswDwtBkjIPC0G2Kw8LQcIiDwtB+DIPC0GeJQ8LQdAiDwtBuh4PC0GBHg8LAAtB1iEhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCz4BAn8CQCAAKAI4IgNFDQAgAygCBCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBxhE2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCCCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9go2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCDCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7Ro2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCECIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlRA2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCFCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBqhs2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCGCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7RM2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCKCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9gg2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCHCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBwhk2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCICIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlBQ2AhBBGCEECyAEC1kBAn8CQCAALQAoQQFGDQAgAC8BMiIBQeQAa0HkAEkNACABQcwBRg0AIAFBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhAiAAQYgEcUGABEYNACAAQShxRSECCyACC4wBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UNACAALwEwIgFBAnFFDQEMAgsgAC8BMCIBQQFxRQ0BC0EBIQIgAC0AKEEBRg0AIAAvATIiAEHkAGtB5ABJDQAgAEHMAUYNACAAQbACRg0AIAFBwABxDQBBACECIAFBiARxQYAERg0AIAFBKHFBAEchAgsgAgtXACAAQRhqQgA3AwAgAEIANwMAIABBOGpCADcDACAAQTBqQgA3AwAgAEEoakIANwMAIABBIGpCADcDACAAQRBqQgA3AwAgAEEIakIANwMAIABB3QE2AhwLBgAgABAyC5otAQt/IwBBEGsiCiQAQaTQACgCACIJRQRAQeTTACgCACIFRQRAQfDTAEJ/NwIAQejTAEKAgISAgIDAADcCAEHk0wAgCkEIakFwcUHYqtWqBXMiBTYCAEH40wBBADYCAEHI0wBBADYCAAtBzNMAQYDUBDYCAEGc0ABBgNQENgIAQbDQACAFNgIAQazQAEF/NgIAQdDTAEGArAM2AgADQCABQcjQAGogAUG80ABqIgI2AgAgAiABQbTQAGoiAzYCACABQcDQAGogAzYCACABQdDQAGogAUHE0ABqIgM2AgAgAyACNgIAIAFB2NAAaiABQczQAGoiAjYCACACIAM2AgAgAUHU0ABqIAI2AgAgAUEgaiIBQYACRw0AC0GM1ARBwasDNgIAQajQAEH00wAoAgA2AgBBmNAAQcCrAzYCAEGk0ABBiNQENgIAQcz/B0E4NgIAQYjUBCEJCwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB7AFNBEBBjNAAKAIAIgZBECAAQRNqQXBxIABBC0kbIgRBA3YiAHYiAUEDcQRAAkAgAUEBcSAAckEBcyICQQN0IgBBtNAAaiIBIABBvNAAaigCACIAKAIIIgNGBEBBjNAAIAZBfiACd3E2AgAMAQsgASADNgIIIAMgATYCDAsgAEEIaiEBIAAgAkEDdCICQQNyNgIEIAAgAmoiACAAKAIEQQFyNgIEDBELQZTQACgCACIIIARPDQEgAQRAAkBBAiAAdCICQQAgAmtyIAEgAHRxaCIAQQN0IgJBtNAAaiIBIAJBvNAAaigCACICKAIIIgNGBEBBjNAAIAZBfiAAd3EiBjYCAAwBCyABIAM2AgggAyABNgIMCyACIARBA3I2AgQgAEEDdCIAIARrIQUgACACaiAFNgIAIAIgBGoiBCAFQQFyNgIEIAgEQCAIQXhxQbTQAGohAEGg0AAoAgAhAwJ/QQEgCEEDdnQiASAGcUUEQEGM0AAgASAGcjYCACAADAELIAAoAggLIgEgAzYCDCAAIAM2AgggAyAANgIMIAMgATYCCAsgAkEIaiEBQaDQACAENgIAQZTQACAFNgIADBELQZDQACgCACILRQ0BIAtoQQJ0QbzSAGooAgAiACgCBEF4cSAEayEFIAAhAgNAAkAgAigCECIBRQRAIAJBFGooAgAiAUUNAQsgASgCBEF4cSAEayIDIAVJIQIgAyAFIAIbIQUgASAAIAIbIQAgASECDAELCyAAKAIYIQkgACgCDCIDIABHBEBBnNAAKAIAGiADIAAoAggiATYCCCABIAM2AgwMEAsgAEEUaiICKAIAIgFFBEAgACgCECIBRQ0DIABBEGohAgsDQCACIQcgASIDQRRqIgIoAgAiAQ0AIANBEGohAiADKAIQIgENAAsgB0EANgIADA8LQX8hBCAAQb9/Sw0AIABBE2oiAUFwcSEEQZDQACgCACIIRQ0AQQAgBGshBQJAAkACQAJ/QQAgBEGAAkkNABpBHyAEQf///wdLDQAaIARBJiABQQh2ZyIAa3ZBAXEgAEEBdGtBPmoLIgZBAnRBvNIAaigCACICRQRAQQAhAUEAIQMMAQtBACEBIARBGSAGQQF2a0EAIAZBH0cbdCEAQQAhAwNAAkAgAigCBEF4cSAEayIHIAVPDQAgAiEDIAciBQ0AQQAhBSACIQEMAwsgASACQRRqKAIAIgcgByACIABBHXZBBHFqQRBqKAIAIgJGGyABIAcbIQEgAEEBdCEAIAINAAsLIAEgA3JFBEBBACEDQQIgBnQiAEEAIABrciAIcSIARQ0DIABoQQJ0QbzSAGooAgAhAQsgAUUNAQsDQCABKAIEQXhxIARrIgIgBUkhACACIAUgABshBSABIAMgABshAyABKAIQIgAEfyAABSABQRRqKAIACyIBDQALCyADRQ0AIAVBlNAAKAIAIARrTw0AIAMoAhghByADIAMoAgwiAEcEQEGc0AAoAgAaIAAgAygCCCIBNgIIIAEgADYCDAwOCyADQRRqIgIoAgAiAUUEQCADKAIQIgFFDQMgA0EQaiECCwNAIAIhBiABIgBBFGoiAigCACIBDQAgAEEQaiECIAAoAhAiAQ0ACyAGQQA2AgAMDQtBlNAAKAIAIgMgBE8EQEGg0AAoAgAhAQJAIAMgBGsiAkEQTwRAIAEgBGoiACACQQFyNgIEIAEgA2ogAjYCACABIARBA3I2AgQMAQsgASADQQNyNgIEIAEgA2oiACAAKAIEQQFyNgIEQQAhAEEAIQILQZTQACACNgIAQaDQACAANgIAIAFBCGohAQwPC0GY0AAoAgAiAyAESwRAIAQgCWoiACADIARrIgFBAXI2AgRBpNAAIAA2AgBBmNAAIAE2AgAgCSAEQQNyNgIEIAlBCGohAQwPC0EAIQEgBAJ/QeTTACgCAARAQezTACgCAAwBC0Hw0wBCfzcCAEHo0wBCgICEgICAwAA3AgBB5NMAIApBDGpBcHFB2KrVqgVzNgIAQfjTAEEANgIAQcjTAEEANgIAQYCABAsiACAEQccAaiIFaiIGQQAgAGsiB3EiAk8EQEH80wBBMDYCAAwPCwJAQcTTACgCACIBRQ0AQbzTACgCACIIIAJqIQAgACABTSAAIAhLcQ0AQQAhAUH80wBBMDYCAAwPC0HI0wAtAABBBHENBAJAAkAgCQRAQczTACEBA0AgASgCACIAIAlNBEAgACABKAIEaiAJSw0DCyABKAIIIgENAAsLQQAQMyIAQX9GDQUgAiEGQejTACgCACIBQQFrIgMgAHEEQCACIABrIAAgA2pBACABa3FqIQYLIAQgBk8NBSAGQf7///8HSw0FQcTTACgCACIDBEBBvNMAKAIAIgcgBmohASABIAdNDQYgASADSw0GCyAGEDMiASAARw0BDAcLIAYgA2sgB3EiBkH+////B0sNBCAGEDMhACAAIAEoAgAgASgCBGpGDQMgACEBCwJAIAYgBEHIAGpPDQAgAUF/Rg0AQezTACgCACIAIAUgBmtqQQAgAGtxIgBB/v///wdLBEAgASEADAcLIAAQM0F/RwRAIAAgBmohBiABIQAMBwtBACAGaxAzGgwECyABIgBBf0cNBQwDC0EAIQMMDAtBACEADAoLIABBf0cNAgtByNMAQcjTACgCAEEEcjYCAAsgAkH+////B0sNASACEDMhAEEAEDMhASAAQX9GDQEgAUF/Rg0BIAAgAU8NASABIABrIgYgBEE4ak0NAQtBvNMAQbzTACgCACAGaiIBNgIAQcDTACgCACABSQRAQcDTACABNgIACwJAAkACQEGk0AAoAgAiAgRAQczTACEBA0AgACABKAIAIgMgASgCBCIFakYNAiABKAIIIgENAAsMAgtBnNAAKAIAIgFBAEcgACABT3FFBEBBnNAAIAA2AgALQQAhAUHQ0wAgBjYCAEHM0wAgADYCAEGs0ABBfzYCAEGw0ABB5NMAKAIANgIAQdjTAEEANgIAA0AgAUHI0ABqIAFBvNAAaiICNgIAIAIgAUG00ABqIgM2AgAgAUHA0ABqIAM2AgAgAUHQ0ABqIAFBxNAAaiIDNgIAIAMgAjYCACABQdjQAGogAUHM0ABqIgI2AgAgAiADNgIAIAFB1NAAaiACNgIAIAFBIGoiAUGAAkcNAAtBeCAAa0EPcSIBIABqIgIgBkE4ayIDIAFrIgFBAXI2AgRBqNAAQfTTACgCADYCAEGY0AAgATYCAEGk0AAgAjYCACAAIANqQTg2AgQMAgsgACACTQ0AIAIgA0kNACABKAIMQQhxDQBBeCACa0EPcSIAIAJqIgNBmNAAKAIAIAZqIgcgAGsiAEEBcjYCBCABIAUgBmo2AgRBqNAAQfTTACgCADYCAEGY0AAgADYCAEGk0AAgAzYCACACIAdqQTg2AgQMAQsgAEGc0AAoAgBJBEBBnNAAIAA2AgALIAAgBmohA0HM0wAhAQJAAkACQANAIAMgASgCAEcEQCABKAIIIgENAQwCCwsgAS0ADEEIcUUNAQtBzNMAIQEDQCABKAIAIgMgAk0EQCADIAEoAgRqIgUgAksNAwsgASgCCCEBDAALAAsgASAANgIAIAEgASgCBCAGajYCBCAAQXggAGtBD3FqIgkgBEEDcjYCBCADQXggA2tBD3FqIgYgBCAJaiIEayEBIAIgBkYEQEGk0AAgBDYCAEGY0ABBmNAAKAIAIAFqIgA2AgAgBCAAQQFyNgIEDAgLQaDQACgCACAGRgRAQaDQACAENgIAQZTQAEGU0AAoAgAgAWoiADYCACAEIABBAXI2AgQgACAEaiAANgIADAgLIAYoAgQiBUEDcUEBRw0GIAVBeHEhCCAFQf8BTQRAIAVBA3YhAyAGKAIIIgAgBigCDCICRgRAQYzQAEGM0AAoAgBBfiADd3E2AgAMBwsgAiAANgIIIAAgAjYCDAwGCyAGKAIYIQcgBiAGKAIMIgBHBEAgACAGKAIIIgI2AgggAiAANgIMDAULIAZBFGoiAigCACIFRQRAIAYoAhAiBUUNBCAGQRBqIQILA0AgAiEDIAUiAEEUaiICKAIAIgUNACAAQRBqIQIgACgCECIFDQALIANBADYCAAwEC0F4IABrQQ9xIgEgAGoiByAGQThrIgMgAWsiAUEBcjYCBCAAIANqQTg2AgQgAiAFQTcgBWtBD3FqQT9rIgMgAyACQRBqSRsiA0EjNgIEQajQAEH00wAoAgA2AgBBmNAAIAE2AgBBpNAAIAc2AgAgA0EQakHU0wApAgA3AgAgA0HM0wApAgA3AghB1NMAIANBCGo2AgBB0NMAIAY2AgBBzNMAIAA2AgBB2NMAQQA2AgAgA0EkaiEBA0AgAUEHNgIAIAUgAUEEaiIBSw0ACyACIANGDQAgAyADKAIEQX5xNgIEIAMgAyACayIFNgIAIAIgBUEBcjYCBCAFQf8BTQRAIAVBeHFBtNAAaiEAAn9BjNAAKAIAIgFBASAFQQN2dCIDcUUEQEGM0AAgASADcjYCACAADAELIAAoAggLIgEgAjYCDCAAIAI2AgggAiAANgIMIAIgATYCCAwBC0EfIQEgBUH///8HTQRAIAVBJiAFQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAQsgAiABNgIcIAJCADcCECABQQJ0QbzSAGohAEGQ0AAoAgAiA0EBIAF0IgZxRQRAIAAgAjYCAEGQ0AAgAyAGcjYCACACIAA2AhggAiACNgIIIAIgAjYCDAwBCyAFQRkgAUEBdmtBACABQR9HG3QhASAAKAIAIQMCQANAIAMiACgCBEF4cSAFRg0BIAFBHXYhAyABQQF0IQEgACADQQRxakEQaiIGKAIAIgMNAAsgBiACNgIAIAIgADYCGCACIAI2AgwgAiACNgIIDAELIAAoAggiASACNgIMIAAgAjYCCCACQQA2AhggAiAANgIMIAIgATYCCAtBmNAAKAIAIgEgBE0NAEGk0AAoAgAiACAEaiICIAEgBGsiAUEBcjYCBEGY0AAgATYCAEGk0AAgAjYCACAAIARBA3I2AgQgAEEIaiEBDAgLQQAhAUH80wBBMDYCAAwHC0EAIQALIAdFDQACQCAGKAIcIgJBAnRBvNIAaiIDKAIAIAZGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAdBEEEUIAcoAhAgBkYbaiAANgIAIABFDQELIAAgBzYCGCAGKAIQIgIEQCAAIAI2AhAgAiAANgIYCyAGQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAIaiEBIAYgCGoiBigCBCEFCyAGIAVBfnE2AgQgASAEaiABNgIAIAQgAUEBcjYCBCABQf8BTQRAIAFBeHFBtNAAaiEAAn9BjNAAKAIAIgJBASABQQN2dCIBcUUEQEGM0AAgASACcjYCACAADAELIAAoAggLIgEgBDYCDCAAIAQ2AgggBCAANgIMIAQgATYCCAwBC0EfIQUgAUH///8HTQRAIAFBJiABQQh2ZyIAa3ZBAXEgAEEBdGtBPmohBQsgBCAFNgIcIARCADcCECAFQQJ0QbzSAGohAEGQ0AAoAgAiAkEBIAV0IgNxRQRAIAAgBDYCAEGQ0AAgAiADcjYCACAEIAA2AhggBCAENgIIIAQgBDYCDAwBCyABQRkgBUEBdmtBACAFQR9HG3QhBSAAKAIAIQACQANAIAAiAigCBEF4cSABRg0BIAVBHXYhACAFQQF0IQUgAiAAQQRxakEQaiIDKAIAIgANAAsgAyAENgIAIAQgAjYCGCAEIAQ2AgwgBCAENgIIDAELIAIoAggiACAENgIMIAIgBDYCCCAEQQA2AhggBCACNgIMIAQgADYCCAsgCUEIaiEBDAILAkAgB0UNAAJAIAMoAhwiAUECdEG80gBqIgIoAgAgA0YEQCACIAA2AgAgAA0BQZDQACAIQX4gAXdxIgg2AgAMAgsgB0EQQRQgBygCECADRhtqIAA2AgAgAEUNAQsgACAHNgIYIAMoAhAiAQRAIAAgATYCECABIAA2AhgLIANBFGooAgAiAUUNACAAQRRqIAE2AgAgASAANgIYCwJAIAVBD00EQCADIAQgBWoiAEEDcjYCBCAAIANqIgAgACgCBEEBcjYCBAwBCyADIARqIgIgBUEBcjYCBCADIARBA3I2AgQgAiAFaiAFNgIAIAVB/wFNBEAgBUF4cUG00ABqIQACf0GM0AAoAgAiAUEBIAVBA3Z0IgVxRQRAQYzQACABIAVyNgIAIAAMAQsgACgCCAsiASACNgIMIAAgAjYCCCACIAA2AgwgAiABNgIIDAELQR8hASAFQf///wdNBEAgBUEmIAVBCHZnIgBrdkEBcSAAQQF0a0E+aiEBCyACIAE2AhwgAkIANwIQIAFBAnRBvNIAaiEAQQEgAXQiBCAIcUUEQCAAIAI2AgBBkNAAIAQgCHI2AgAgAiAANgIYIAIgAjYCCCACIAI2AgwMAQsgBUEZIAFBAXZrQQAgAUEfRxt0IQEgACgCACEEAkADQCAEIgAoAgRBeHEgBUYNASABQR12IQQgAUEBdCEBIAAgBEEEcWpBEGoiBigCACIEDQALIAYgAjYCACACIAA2AhggAiACNgIMIAIgAjYCCAwBCyAAKAIIIgEgAjYCDCAAIAI2AgggAkEANgIYIAIgADYCDCACIAE2AggLIANBCGohAQwBCwJAIAlFDQACQCAAKAIcIgFBAnRBvNIAaiICKAIAIABGBEAgAiADNgIAIAMNAUGQ0AAgC0F+IAF3cTYCAAwCCyAJQRBBFCAJKAIQIABGG2ogAzYCACADRQ0BCyADIAk2AhggACgCECIBBEAgAyABNgIQIAEgAzYCGAsgAEEUaigCACIBRQ0AIANBFGogATYCACABIAM2AhgLAkAgBUEPTQRAIAAgBCAFaiIBQQNyNgIEIAAgAWoiASABKAIEQQFyNgIEDAELIAAgBGoiByAFQQFyNgIEIAAgBEEDcjYCBCAFIAdqIAU2AgAgCARAIAhBeHFBtNAAaiEBQaDQACgCACEDAn9BASAIQQN2dCICIAZxRQRAQYzQACACIAZyNgIAIAEMAQsgASgCCAsiAiADNgIMIAEgAzYCCCADIAE2AgwgAyACNgIIC0Gg0AAgBzYCAEGU0AAgBTYCAAsgAEEIaiEBCyAKQRBqJAAgAQtDACAARQRAPwBBEHQPCwJAIABB//8DcQ0AIABBAEgNACAAQRB2QAAiAEF/RgRAQfzTAEEwNgIAQX8PCyAAQRB0DwsACwvcPyIAQYAICwkBAAAAAgAAAAMAQZQICwUEAAAABQBBpAgLCQYAAAAHAAAACABB3AgLii1JbnZhbGlkIGNoYXIgaW4gdXJsIHF1ZXJ5AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fYm9keQBDb250ZW50LUxlbmd0aCBvdmVyZmxvdwBDaHVuayBzaXplIG92ZXJmbG93AFJlc3BvbnNlIG92ZXJmbG93AEludmFsaWQgbWV0aG9kIGZvciBIVFRQL3gueCByZXF1ZXN0AEludmFsaWQgbWV0aG9kIGZvciBSVFNQL3gueCByZXF1ZXN0AEV4cGVjdGVkIFNPVVJDRSBtZXRob2QgZm9yIElDRS94LnggcmVxdWVzdABJbnZhbGlkIGNoYXIgaW4gdXJsIGZyYWdtZW50IHN0YXJ0AEV4cGVjdGVkIGRvdABTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3N0YXR1cwBJbnZhbGlkIHJlc3BvbnNlIHN0YXR1cwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zAFVzZXIgY2FsbGJhY2sgZXJyb3IAYG9uX3Jlc2V0YCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfaGVhZGVyYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9iZWdpbmAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3N0YXR1c19jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3ZlcnNpb25fY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl91cmxfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl92YWx1ZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXRob2RfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfZmllbGRfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fbmFtZWAgY2FsbGJhY2sgZXJyb3IAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzZXJ2ZXIASW52YWxpZCBoZWFkZXIgdmFsdWUgY2hhcgBJbnZhbGlkIGhlYWRlciBmaWVsZCBjaGFyAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fdmVyc2lvbgBJbnZhbGlkIG1pbm9yIHZlcnNpb24ASW52YWxpZCBtYWpvciB2ZXJzaW9uAEV4cGVjdGVkIHNwYWNlIGFmdGVyIHZlcnNpb24ARXhwZWN0ZWQgQ1JMRiBhZnRlciB2ZXJzaW9uAEludmFsaWQgSFRUUCB2ZXJzaW9uAEludmFsaWQgaGVhZGVyIHRva2VuAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fdXJsAEludmFsaWQgY2hhcmFjdGVycyBpbiB1cmwAVW5leHBlY3RlZCBzdGFydCBjaGFyIGluIHVybABEb3VibGUgQCBpbiB1cmwARW1wdHkgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyYWN0ZXIgaW4gQ29udGVudC1MZW5ndGgARHVwbGljYXRlIENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhciBpbiB1cmwgcGF0aABDb250ZW50LUxlbmd0aCBjYW4ndCBiZSBwcmVzZW50IHdpdGggVHJhbnNmZXItRW5jb2RpbmcASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgc2l6ZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2hlYWRlcl92YWx1ZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgTEYgYWZ0ZXIgaGVhZGVyIHZhbHVlAEludmFsaWQgYFRyYW5zZmVyLUVuY29kaW5nYCBoZWFkZXIgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZSB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlZCB2YWx1ZQBQYXVzZWQgYnkgb25faGVhZGVyc19jb21wbGV0ZQBJbnZhbGlkIEVPRiBzdGF0ZQBvbl9yZXNldCBwYXVzZQBvbl9jaHVua19oZWFkZXIgcGF1c2UAb25fbWVzc2FnZV9iZWdpbiBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fdmFsdWUgcGF1c2UAb25fc3RhdHVzX2NvbXBsZXRlIHBhdXNlAG9uX3ZlcnNpb25fY29tcGxldGUgcGF1c2UAb25fdXJsX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl92YWx1ZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXNzYWdlX2NvbXBsZXRlIHBhdXNlAG9uX21ldGhvZF9jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfZmllbGRfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUgcGF1c2UAVW5leHBlY3RlZCBzcGFjZSBhZnRlciBzdGFydCBsaW5lAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBuYW1lAFBhdXNlIG9uIENPTk5FQ1QvVXBncmFkZQBQYXVzZSBvbiBQUkkvVXBncmFkZQBFeHBlY3RlZCBIVFRQLzIgQ29ubmVjdGlvbiBQcmVmYWNlAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fbWV0aG9kAEV4cGVjdGVkIHNwYWNlIGFmdGVyIG1ldGhvZABTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2hlYWRlcl9maWVsZABQYXVzZWQASW52YWxpZCB3b3JkIGVuY291bnRlcmVkAEludmFsaWQgbWV0aG9kIGVuY291bnRlcmVkAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2NoZW1hAFJlcXVlc3QgaGFzIGludmFsaWQgYFRyYW5zZmVyLUVuY29kaW5nYABTV0lUQ0hfUFJPWFkAVVNFX1BST1hZAE1LQUNUSVZJVFkAVU5QUk9DRVNTQUJMRV9FTlRJVFkAQ09QWQBNT1ZFRF9QRVJNQU5FTlRMWQBUT09fRUFSTFkATk9USUZZAEZBSUxFRF9ERVBFTkRFTkNZAEJBRF9HQVRFV0FZAFBMQVkAUFVUAENIRUNLT1VUAEdBVEVXQVlfVElNRU9VVABSRVFVRVNUX1RJTUVPVVQATkVUV09SS19DT05ORUNUX1RJTUVPVVQAQ09OTkVDVElPTl9USU1FT1VUAExPR0lOX1RJTUVPVVQATkVUV09SS19SRUFEX1RJTUVPVVQAUE9TVABNSVNESVJFQ1RFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX0xPQURfQkFMQU5DRURfUkVRVUVTVABCQURfUkVRVUVTVABIVFRQX1JFUVVFU1RfU0VOVF9UT19IVFRQU19QT1JUAFJFUE9SVABJTV9BX1RFQVBPVABSRVNFVF9DT05URU5UAE5PX0NPTlRFTlQAUEFSVElBTF9DT05URU5UAEhQRV9JTlZBTElEX0NPTlNUQU5UAEhQRV9DQl9SRVNFVABHRVQASFBFX1NUUklDVABDT05GTElDVABURU1QT1JBUllfUkVESVJFQ1QAUEVSTUFORU5UX1JFRElSRUNUAENPTk5FQ1QATVVMVElfU1RBVFVTAEhQRV9JTlZBTElEX1NUQVRVUwBUT09fTUFOWV9SRVFVRVNUUwBFQVJMWV9ISU5UUwBVTkFWQUlMQUJMRV9GT1JfTEVHQUxfUkVBU09OUwBPUFRJT05TAFNXSVRDSElOR19QUk9UT0NPTFMAVkFSSUFOVF9BTFNPX05FR09USUFURVMATVVMVElQTEVfQ0hPSUNFUwBJTlRFUk5BTF9TRVJWRVJfRVJST1IAV0VCX1NFUlZFUl9VTktOT1dOX0VSUk9SAFJBSUxHVU5fRVJST1IASURFTlRJVFlfUFJPVklERVJfQVVUSEVOVElDQVRJT05fRVJST1IAU1NMX0NFUlRJRklDQVRFX0VSUk9SAElOVkFMSURfWF9GT1JXQVJERURfRk9SAFNFVF9QQVJBTUVURVIAR0VUX1BBUkFNRVRFUgBIUEVfVVNFUgBTRUVfT1RIRVIASFBFX0NCX0NIVU5LX0hFQURFUgBNS0NBTEVOREFSAFNFVFVQAFdFQl9TRVJWRVJfSVNfRE9XTgBURUFSRE9XTgBIUEVfQ0xPU0VEX0NPTk5FQ1RJT04ASEVVUklTVElDX0VYUElSQVRJT04ARElTQ09OTkVDVEVEX09QRVJBVElPTgBOT05fQVVUSE9SSVRBVElWRV9JTkZPUk1BVElPTgBIUEVfSU5WQUxJRF9WRVJTSU9OAEhQRV9DQl9NRVNTQUdFX0JFR0lOAFNJVEVfSVNfRlJPWkVOAEhQRV9JTlZBTElEX0hFQURFUl9UT0tFTgBJTlZBTElEX1RPS0VOAEZPUkJJRERFTgBFTkhBTkNFX1lPVVJfQ0FMTQBIUEVfSU5WQUxJRF9VUkwAQkxPQ0tFRF9CWV9QQVJFTlRBTF9DT05UUk9MAE1LQ09MAEFDTABIUEVfSU5URVJOQUwAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRV9VTk9GRklDSUFMAEhQRV9PSwBVTkxJTksAVU5MT0NLAFBSSQBSRVRSWV9XSVRIAEhQRV9JTlZBTElEX0NPTlRFTlRfTEVOR1RIAEhQRV9VTkVYUEVDVEVEX0NPTlRFTlRfTEVOR1RIAEZMVVNIAFBST1BQQVRDSABNLVNFQVJDSABVUklfVE9PX0xPTkcAUFJPQ0VTU0lORwBNSVNDRUxMQU5FT1VTX1BFUlNJU1RFTlRfV0FSTklORwBNSVNDRUxMQU5FT1VTX1dBUk5JTkcASFBFX0lOVkFMSURfVFJBTlNGRVJfRU5DT0RJTkcARXhwZWN0ZWQgQ1JMRgBIUEVfSU5WQUxJRF9DSFVOS19TSVpFAE1PVkUAQ09OVElOVUUASFBFX0NCX1NUQVRVU19DT01QTEVURQBIUEVfQ0JfSEVBREVSU19DT01QTEVURQBIUEVfQ0JfVkVSU0lPTl9DT01QTEVURQBIUEVfQ0JfVVJMX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19DT01QTEVURQBIUEVfQ0JfSEVBREVSX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9OQU1FX0NPTVBMRVRFAEhQRV9DQl9NRVNTQUdFX0NPTVBMRVRFAEhQRV9DQl9NRVRIT0RfQ09NUExFVEUASFBFX0NCX0hFQURFUl9GSUVMRF9DT01QTEVURQBERUxFVEUASFBFX0lOVkFMSURfRU9GX1NUQVRFAElOVkFMSURfU1NMX0NFUlRJRklDQVRFAFBBVVNFAE5PX1JFU1BPTlNFAFVOU1VQUE9SVEVEX01FRElBX1RZUEUAR09ORQBOT1RfQUNDRVBUQUJMRQBTRVJWSUNFX1VOQVZBSUxBQkxFAFJBTkdFX05PVF9TQVRJU0ZJQUJMRQBPUklHSU5fSVNfVU5SRUFDSEFCTEUAUkVTUE9OU0VfSVNfU1RBTEUAUFVSR0UATUVSR0UAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRQBSRVFVRVNUX0hFQURFUl9UT09fTEFSR0UAUEFZTE9BRF9UT09fTEFSR0UASU5TVUZGSUNJRU5UX1NUT1JBR0UASFBFX1BBVVNFRF9VUEdSQURFAEhQRV9QQVVTRURfSDJfVVBHUkFERQBTT1VSQ0UAQU5OT1VOQ0UAVFJBQ0UASFBFX1VORVhQRUNURURfU1BBQ0UAREVTQ1JJQkUAVU5TVUJTQ1JJQkUAUkVDT1JEAEhQRV9JTlZBTElEX01FVEhPRABOT1RfRk9VTkQAUFJPUEZJTkQAVU5CSU5EAFJFQklORABVTkFVVEhPUklaRUQATUVUSE9EX05PVF9BTExPV0VEAEhUVFBfVkVSU0lPTl9OT1RfU1VQUE9SVEVEAEFMUkVBRFlfUkVQT1JURUQAQUNDRVBURUQATk9UX0lNUExFTUVOVEVEAExPT1BfREVURUNURUQASFBFX0NSX0VYUEVDVEVEAEhQRV9MRl9FWFBFQ1RFRABDUkVBVEVEAElNX1VTRUQASFBFX1BBVVNFRABUSU1FT1VUX09DQ1VSRUQAUEFZTUVOVF9SRVFVSVJFRABQUkVDT05ESVRJT05fUkVRVUlSRUQAUFJPWFlfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATkVUV09SS19BVVRIRU5USUNBVElPTl9SRVFVSVJFRABMRU5HVEhfUkVRVUlSRUQAU1NMX0NFUlRJRklDQVRFX1JFUVVJUkVEAFVQR1JBREVfUkVRVUlSRUQAUEFHRV9FWFBJUkVEAFBSRUNPTkRJVElPTl9GQUlMRUQARVhQRUNUQVRJT05fRkFJTEVEAFJFVkFMSURBVElPTl9GQUlMRUQAU1NMX0hBTkRTSEFLRV9GQUlMRUQATE9DS0VEAFRSQU5TRk9STUFUSU9OX0FQUExJRUQATk9UX01PRElGSUVEAE5PVF9FWFRFTkRFRABCQU5EV0lEVEhfTElNSVRfRVhDRUVERUQAU0lURV9JU19PVkVSTE9BREVEAEhFQUQARXhwZWN0ZWQgSFRUUC8AAF4TAAAmEwAAMBAAAPAXAACdEwAAFRIAADkXAADwEgAAChAAAHUSAACtEgAAghMAAE8UAAB/EAAAoBUAACMUAACJEgAAixQAAE0VAADUEQAAzxQAABAYAADJFgAA3BYAAMERAADgFwAAuxQAAHQUAAB8FQAA5RQAAAgXAAAfEAAAZRUAAKMUAAAoFQAAAhUAAJkVAAAsEAAAixkAAE8PAADUDgAAahAAAM4QAAACFwAAiQ4AAG4TAAAcEwAAZhQAAFYXAADBEwAAzRMAAGwTAABoFwAAZhcAAF8XAAAiEwAAzg8AAGkOAADYDgAAYxYAAMsTAACqDgAAKBcAACYXAADFEwAAXRYAAOgRAABnEwAAZRMAAPIWAABzEwAAHRcAAPkWAADzEQAAzw4AAM4VAAAMEgAAsxEAAKURAABhEAAAMhcAALsTAEH5NQsBAQBBkDYL4AEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB/TcLAQEAQZE4C14CAwICAgICAAACAgACAgACAgICAgICAgICAAQAAAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAEH9OQsBAQBBkToLXgIAAgICAgIAAAICAAICAAICAgICAgICAgIAAwAEAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAQfA7Cw1sb3NlZWVwLWFsaXZlAEGJPAsBAQBBoDwL4AEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBBiT4LAQEAQaA+C+cBAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAEGwwAALXwEBAAEBAQEBAAABAQABAQABAQEBAQEBAQEBAAAAAAAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAEGQwgALIWVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgBBwMIACy1yYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNCg0KU00NCg0KVFRQL0NFL1RTUC8AQfnCAAsFAQIAAQMAQZDDAAvgAQQBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAEH5xAALBQECAAEDAEGQxQAL4AEEAQEFAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB+cYACwQBAAABAEGRxwAL3wEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAEH6yAALBAEAAAIAQZDJAAtfAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAQfrKAAsEAQAAAQBBkMsACwEBAEGqywALQQIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAEH6zAALBAEAAAEAQZDNAAsBAQBBms0ACwYCAAAAAAIAQbHNAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB8M4AC5YBTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRU9SRElSRUNUT1JUUkNIUEFSQU1FVEVSVVJDRUJTQ1JJQkVBUkRPV05BQ0VJTkROS0NLVUJTQ1JJQkVIVFRQL0FEVFAv', 'base64') diff --git a/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js b/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js new file mode 100644 index 0000000000000..3ee81325f5b78 --- /dev/null +++ b/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js @@ -0,0 +1,5 @@ +'use strict' + +const { Buffer } = require('node:buffer') + +module.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0sBQYAAAIAAAAAAAACAQIAAgICAAADAAAAAAMDAwMBAQEBAQEBAQEAAAIAAAAEBQFwARISBQMBAAIGCAF/AUGA1AQLB9EFIgZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAIGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAJGGxsaHR0cF9zaG91bGRfa2VlcF9hbGl2ZQAvDGxsaHR0cF9hbGxvYwALBm1hbGxvYwAxC2xsaHR0cF9mcmVlAAwEZnJlZQAMD2xsaHR0cF9nZXRfdHlwZQANFWxsaHR0cF9nZXRfaHR0cF9tYWpvcgAOFWxsaHR0cF9nZXRfaHR0cF9taW5vcgAPEWxsaHR0cF9nZXRfbWV0aG9kABAWbGxodHRwX2dldF9zdGF0dXNfY29kZQAREmxsaHR0cF9nZXRfdXBncmFkZQASDGxsaHR0cF9yZXNldAATDmxsaHR0cF9leGVjdXRlABQUbGxodHRwX3NldHRpbmdzX2luaXQAFQ1sbGh0dHBfZmluaXNoABYMbGxodHRwX3BhdXNlABcNbGxodHRwX3Jlc3VtZQAYG2xsaHR0cF9yZXN1bWVfYWZ0ZXJfdXBncmFkZQAZEGxsaHR0cF9nZXRfZXJybm8AGhdsbGh0dHBfZ2V0X2Vycm9yX3JlYXNvbgAbF2xsaHR0cF9zZXRfZXJyb3JfcmVhc29uABwUbGxodHRwX2dldF9lcnJvcl9wb3MAHRFsbGh0dHBfZXJybm9fbmFtZQAeEmxsaHR0cF9tZXRob2RfbmFtZQAfEmxsaHR0cF9zdGF0dXNfbmFtZQAgGmxsaHR0cF9zZXRfbGVuaWVudF9oZWFkZXJzACEhbGxodHRwX3NldF9sZW5pZW50X2NodW5rZWRfbGVuZ3RoACIdbGxodHRwX3NldF9sZW5pZW50X2tlZXBfYWxpdmUAIyRsbGh0dHBfc2V0X2xlbmllbnRfdHJhbnNmZXJfZW5jb2RpbmcAJBhsbGh0dHBfbWVzc2FnZV9uZWVkc19lb2YALgkXAQBBAQsRAQIDBAUKBgcrLSwqKSglJyYK77MCLBYAQYjQACgCAARAAAtBiNAAQQE2AgALFAAgABAwIAAgAjYCOCAAIAE6ACgLFAAgACAALwEyIAAtAC4gABAvEAALHgEBf0HAABAyIgEQMCABQYAINgI4IAEgADoAKCABC48MAQd/AkAgAEUNACAAQQhrIgEgAEEEaygCACIAQXhxIgRqIQUCQCAAQQFxDQAgAEEDcUUNASABIAEoAgAiAGsiAUGc0AAoAgBJDQEgACAEaiEEAkACQEGg0AAoAgAgAUcEQCAAQf8BTQRAIABBA3YhAyABKAIIIgAgASgCDCICRgRAQYzQAEGM0AAoAgBBfiADd3E2AgAMBQsgAiAANgIIIAAgAjYCDAwECyABKAIYIQYgASABKAIMIgBHBEAgACABKAIIIgI2AgggAiAANgIMDAMLIAFBFGoiAygCACICRQRAIAEoAhAiAkUNAiABQRBqIQMLA0AgAyEHIAIiAEEUaiIDKAIAIgINACAAQRBqIQMgACgCECICDQALIAdBADYCAAwCCyAFKAIEIgBBA3FBA0cNAiAFIABBfnE2AgRBlNAAIAQ2AgAgBSAENgIAIAEgBEEBcjYCBAwDC0EAIQALIAZFDQACQCABKAIcIgJBAnRBvNIAaiIDKAIAIAFGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgAUYbaiAANgIAIABFDQELIAAgBjYCGCABKAIQIgIEQCAAIAI2AhAgAiAANgIYCyABQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAFTw0AIAUoAgQiAEEBcUUNAAJAAkACQAJAIABBAnFFBEBBpNAAKAIAIAVGBEBBpNAAIAE2AgBBmNAAQZjQACgCACAEaiIANgIAIAEgAEEBcjYCBCABQaDQACgCAEcNBkGU0ABBADYCAEGg0ABBADYCAAwGC0Gg0AAoAgAgBUYEQEGg0AAgATYCAEGU0ABBlNAAKAIAIARqIgA2AgAgASAAQQFyNgIEIAAgAWogADYCAAwGCyAAQXhxIARqIQQgAEH/AU0EQCAAQQN2IQMgBSgCCCIAIAUoAgwiAkYEQEGM0ABBjNAAKAIAQX4gA3dxNgIADAULIAIgADYCCCAAIAI2AgwMBAsgBSgCGCEGIAUgBSgCDCIARwRAQZzQACgCABogACAFKAIIIgI2AgggAiAANgIMDAMLIAVBFGoiAygCACICRQRAIAUoAhAiAkUNAiAFQRBqIQMLA0AgAyEHIAIiAEEUaiIDKAIAIgINACAAQRBqIQMgACgCECICDQALIAdBADYCAAwCCyAFIABBfnE2AgQgASAEaiAENgIAIAEgBEEBcjYCBAwDC0EAIQALIAZFDQACQCAFKAIcIgJBAnRBvNIAaiIDKAIAIAVGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiAANgIAIABFDQELIAAgBjYCGCAFKAIQIgIEQCAAIAI2AhAgAiAANgIYCyAFQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAEaiAENgIAIAEgBEEBcjYCBCABQaDQACgCAEcNAEGU0AAgBDYCAAwBCyAEQf8BTQRAIARBeHFBtNAAaiEAAn9BjNAAKAIAIgJBASAEQQN2dCIDcUUEQEGM0AAgAiADcjYCACAADAELIAAoAggLIgIgATYCDCAAIAE2AgggASAANgIMIAEgAjYCCAwBC0EfIQIgBEH///8HTQRAIARBJiAEQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAgsgASACNgIcIAFCADcCECACQQJ0QbzSAGohAAJAQZDQACgCACIDQQEgAnQiB3FFBEAgACABNgIAQZDQACADIAdyNgIAIAEgADYCGCABIAE2AgggASABNgIMDAELIARBGSACQQF2a0EAIAJBH0cbdCECIAAoAgAhAAJAA0AgACIDKAIEQXhxIARGDQEgAkEddiEAIAJBAXQhAiADIABBBHFqQRBqIgcoAgAiAA0ACyAHIAE2AgAgASADNgIYIAEgATYCDCABIAE2AggMAQsgAygCCCIAIAE2AgwgAyABNgIIIAFBADYCGCABIAM2AgwgASAANgIIC0Gs0ABBrNAAKAIAQQFrIgBBfyAAGzYCAAsLBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LQAEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABAwIAAgBDYCOCAAIAM6ACggACACOgAtIAAgATYCGAu74gECB38DfiABIAJqIQQCQCAAIgIoAgwiAA0AIAIoAgQEQCACIAE2AgQLIwBBEGsiCCQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAIoAhwiA0EBaw7dAdoBAdkBAgMEBQYHCAkKCwwNDtgBDxDXARES1gETFBUWFxgZGhvgAd8BHB0e1QEfICEiIyQl1AEmJygpKiss0wHSAS0u0QHQAS8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRtsBR0hJSs8BzgFLzQFMzAFNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AAYEBggGDAYQBhQGGAYcBiAGJAYoBiwGMAY0BjgGPAZABkQGSAZMBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBywHKAbgByQG5AcgBugG7AbwBvQG+Ab8BwAHBAcIBwwHEAcUBxgEA3AELQQAMxgELQQ4MxQELQQ0MxAELQQ8MwwELQRAMwgELQRMMwQELQRQMwAELQRUMvwELQRYMvgELQRgMvQELQRkMvAELQRoMuwELQRsMugELQRwMuQELQR0MuAELQQgMtwELQR4MtgELQSAMtQELQR8MtAELQQcMswELQSEMsgELQSIMsQELQSMMsAELQSQMrwELQRIMrgELQREMrQELQSUMrAELQSYMqwELQScMqgELQSgMqQELQcMBDKgBC0EqDKcBC0ErDKYBC0EsDKUBC0EtDKQBC0EuDKMBC0EvDKIBC0HEAQyhAQtBMAygAQtBNAyfAQtBDAyeAQtBMQydAQtBMgycAQtBMwybAQtBOQyaAQtBNQyZAQtBxQEMmAELQQsMlwELQToMlgELQTYMlQELQQoMlAELQTcMkwELQTgMkgELQTwMkQELQTsMkAELQT0MjwELQQkMjgELQSkMjQELQT4MjAELQT8MiwELQcAADIoBC0HBAAyJAQtBwgAMiAELQcMADIcBC0HEAAyGAQtBxQAMhQELQcYADIQBC0EXDIMBC0HHAAyCAQtByAAMgQELQckADIABC0HKAAx/C0HLAAx+C0HNAAx9C0HMAAx8C0HOAAx7C0HPAAx6C0HQAAx5C0HRAAx4C0HSAAx3C0HTAAx2C0HUAAx1C0HWAAx0C0HVAAxzC0EGDHILQdcADHELQQUMcAtB2AAMbwtBBAxuC0HZAAxtC0HaAAxsC0HbAAxrC0HcAAxqC0EDDGkLQd0ADGgLQd4ADGcLQd8ADGYLQeEADGULQeAADGQLQeIADGMLQeMADGILQQIMYQtB5AAMYAtB5QAMXwtB5gAMXgtB5wAMXQtB6AAMXAtB6QAMWwtB6gAMWgtB6wAMWQtB7AAMWAtB7QAMVwtB7gAMVgtB7wAMVQtB8AAMVAtB8QAMUwtB8gAMUgtB8wAMUQtB9AAMUAtB9QAMTwtB9gAMTgtB9wAMTQtB+AAMTAtB+QAMSwtB+gAMSgtB+wAMSQtB/AAMSAtB/QAMRwtB/gAMRgtB/wAMRQtBgAEMRAtBgQEMQwtBggEMQgtBgwEMQQtBhAEMQAtBhQEMPwtBhgEMPgtBhwEMPQtBiAEMPAtBiQEMOwtBigEMOgtBiwEMOQtBjAEMOAtBjQEMNwtBjgEMNgtBjwEMNQtBkAEMNAtBkQEMMwtBkgEMMgtBkwEMMQtBlAEMMAtBlQEMLwtBlgEMLgtBlwEMLQtBmAEMLAtBmQEMKwtBmgEMKgtBmwEMKQtBnAEMKAtBnQEMJwtBngEMJgtBnwEMJQtBoAEMJAtBoQEMIwtBogEMIgtBowEMIQtBpAEMIAtBpQEMHwtBpgEMHgtBpwEMHQtBqAEMHAtBqQEMGwtBqgEMGgtBqwEMGQtBrAEMGAtBrQEMFwtBrgEMFgtBAQwVC0GvAQwUC0GwAQwTC0GxAQwSC0GzAQwRC0GyAQwQC0G0AQwPC0G1AQwOC0G2AQwNC0G3AQwMC0G4AQwLC0G5AQwKC0G6AQwJC0G7AQwIC0HGAQwHC0G8AQwGC0G9AQwFC0G+AQwEC0G/AQwDC0HAAQwCC0HCAQwBC0HBAQshAwNAAkACQAJAAkACQAJAAkACQAJAIAICfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAgJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADDsYBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHyAhIyUmKCorLC8wMTIzNDU2Nzk6Ozw9lANAQkRFRklLTk9QUVJTVFVWWFpbXF1eX2BhYmNkZWZnaGpsb3Bxc3V2eHl6e3x/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AbgBuQG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAccByAHJAcsBzAHNAc4BzwGKA4kDiAOHA4QDgwOAA/sC+gL5AvgC9wL0AvMC8gLLAsECsALZAQsgASAERw3wAkHdASEDDLMDCyABIARHDcgBQcMBIQMMsgMLIAEgBEcNe0H3ACEDDLEDCyABIARHDXBB7wAhAwywAwsgASAERw1pQeoAIQMMrwMLIAEgBEcNZUHoACEDDK4DCyABIARHDWJB5gAhAwytAwsgASAERw0aQRghAwysAwsgASAERw0VQRIhAwyrAwsgASAERw1CQcUAIQMMqgMLIAEgBEcNNEE/IQMMqQMLIAEgBEcNMkE8IQMMqAMLIAEgBEcNK0ExIQMMpwMLIAItAC5BAUYNnwMMwQILQQAhAAJAAkACQCACLQAqRQ0AIAItACtFDQAgAi8BMCIDQQJxRQ0BDAILIAIvATAiA0EBcUUNAQtBASEAIAItAChBAUYNACACLwEyIgVB5ABrQeQASQ0AIAVBzAFGDQAgBUGwAkYNACADQcAAcQ0AQQAhACADQYgEcUGABEYNACADQShxQQBHIQALIAJBADsBMCACQQA6AC8gAEUN3wIgAkIANwMgDOACC0EAIQACQCACKAI4IgNFDQAgAygCLCIDRQ0AIAIgAxEAACEACyAARQ3MASAAQRVHDd0CIAJBBDYCHCACIAE2AhQgAkGwGDYCECACQRU2AgxBACEDDKQDCyABIARGBEBBBiEDDKQDCyABQQFqIQFBACEAAkAgAigCOCIDRQ0AIAMoAlQiA0UNACACIAMRAAAhAAsgAA3ZAgwcCyACQgA3AyBBEiEDDIkDCyABIARHDRZBHSEDDKEDCyABIARHBEAgAUEBaiEBQRAhAwyIAwtBByEDDKADCyACIAIpAyAiCiAEIAFrrSILfSIMQgAgCiAMWhs3AyAgCiALWA3UAkEIIQMMnwMLIAEgBEcEQCACQQk2AgggAiABNgIEQRQhAwyGAwtBCSEDDJ4DCyACKQMgQgBSDccBIAIgAi8BMEGAAXI7ATAMQgsgASAERw0/QdAAIQMMnAMLIAEgBEYEQEELIQMMnAMLIAFBAWohAUEAIQACQCACKAI4IgNFDQAgAygCUCIDRQ0AIAIgAxEAACEACyAADc8CDMYBC0EAIQACQCACKAI4IgNFDQAgAygCSCIDRQ0AIAIgAxEAACEACyAARQ3GASAAQRVHDc0CIAJBCzYCHCACIAE2AhQgAkGCGTYCECACQRU2AgxBACEDDJoDC0EAIQACQCACKAI4IgNFDQAgAygCSCIDRQ0AIAIgAxEAACEACyAARQ0MIABBFUcNygIgAkEaNgIcIAIgATYCFCACQYIZNgIQIAJBFTYCDEEAIQMMmQMLQQAhAAJAIAIoAjgiA0UNACADKAJMIgNFDQAgAiADEQAAIQALIABFDcQBIABBFUcNxwIgAkELNgIcIAIgATYCFCACQZEXNgIQIAJBFTYCDEEAIQMMmAMLIAEgBEYEQEEPIQMMmAMLIAEtAAAiAEE7Rg0HIABBDUcNxAIgAUEBaiEBDMMBC0EAIQACQCACKAI4IgNFDQAgAygCTCIDRQ0AIAIgAxEAACEACyAARQ3DASAAQRVHDcICIAJBDzYCHCACIAE2AhQgAkGRFzYCECACQRU2AgxBACEDDJYDCwNAIAEtAABB8DVqLQAAIgBBAUcEQCAAQQJHDcECIAIoAgQhAEEAIQMgAkEANgIEIAIgACABQQFqIgEQLSIADcICDMUBCyAEIAFBAWoiAUcNAAtBEiEDDJUDC0EAIQACQCACKAI4IgNFDQAgAygCTCIDRQ0AIAIgAxEAACEACyAARQ3FASAAQRVHDb0CIAJBGzYCHCACIAE2AhQgAkGRFzYCECACQRU2AgxBACEDDJQDCyABIARGBEBBFiEDDJQDCyACQQo2AgggAiABNgIEQQAhAAJAIAIoAjgiA0UNACADKAJIIgNFDQAgAiADEQAAIQALIABFDcIBIABBFUcNuQIgAkEVNgIcIAIgATYCFCACQYIZNgIQIAJBFTYCDEEAIQMMkwMLIAEgBEcEQANAIAEtAABB8DdqLQAAIgBBAkcEQAJAIABBAWsOBMQCvQIAvgK9AgsgAUEBaiEBQQghAwz8AgsgBCABQQFqIgFHDQALQRUhAwyTAwtBFSEDDJIDCwNAIAEtAABB8DlqLQAAIgBBAkcEQCAAQQFrDgTFArcCwwK4ArcCCyAEIAFBAWoiAUcNAAtBGCEDDJEDCyABIARHBEAgAkELNgIIIAIgATYCBEEHIQMM+AILQRkhAwyQAwsgAUEBaiEBDAILIAEgBEYEQEEaIQMMjwMLAkAgAS0AAEENaw4UtQG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwEAvwELQQAhAyACQQA2AhwgAkGvCzYCECACQQI2AgwgAiABQQFqNgIUDI4DCyABIARGBEBBGyEDDI4DCyABLQAAIgBBO0cEQCAAQQ1HDbECIAFBAWohAQy6AQsgAUEBaiEBC0EiIQMM8wILIAEgBEYEQEEcIQMMjAMLQgAhCgJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAS0AAEEwaw43wQLAAgABAgMEBQYH0AHQAdAB0AHQAdAB0AEICQoLDA3QAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdABDg8QERIT0AELQgIhCgzAAgtCAyEKDL8CC0IEIQoMvgILQgUhCgy9AgtCBiEKDLwCC0IHIQoMuwILQgghCgy6AgtCCSEKDLkCC0IKIQoMuAILQgshCgy3AgtCDCEKDLYCC0INIQoMtQILQg4hCgy0AgtCDyEKDLMCC0IKIQoMsgILQgshCgyxAgtCDCEKDLACC0INIQoMrwILQg4hCgyuAgtCDyEKDK0CC0IAIQoCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBMGsON8ACvwIAAQIDBAUGB74CvgK+Ar4CvgK+Ar4CCAkKCwwNvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ag4PEBESE74CC0ICIQoMvwILQgMhCgy+AgtCBCEKDL0CC0IFIQoMvAILQgYhCgy7AgtCByEKDLoCC0IIIQoMuQILQgkhCgy4AgtCCiEKDLcCC0ILIQoMtgILQgwhCgy1AgtCDSEKDLQCC0IOIQoMswILQg8hCgyyAgtCCiEKDLECC0ILIQoMsAILQgwhCgyvAgtCDSEKDK4CC0IOIQoMrQILQg8hCgysAgsgAiACKQMgIgogBCABa60iC30iDEIAIAogDFobNwMgIAogC1gNpwJBHyEDDIkDCyABIARHBEAgAkEJNgIIIAIgATYCBEElIQMM8AILQSAhAwyIAwtBASEFIAIvATAiA0EIcUUEQCACKQMgQgBSIQULAkAgAi0ALgRAQQEhACACLQApQQVGDQEgA0HAAHFFIAVxRQ0BC0EAIQAgA0HAAHENAEECIQAgA0EIcQ0AIANBgARxBEACQCACLQAoQQFHDQAgAi0ALUEKcQ0AQQUhAAwCC0EEIQAMAQsgA0EgcUUEQAJAIAItAChBAUYNACACLwEyIgBB5ABrQeQASQ0AIABBzAFGDQAgAEGwAkYNAEEEIQAgA0EocUUNAiADQYgEcUGABEYNAgtBACEADAELQQBBAyACKQMgUBshAAsgAEEBaw4FvgIAsAEBpAKhAgtBESEDDO0CCyACQQE6AC8MhAMLIAEgBEcNnQJBJCEDDIQDCyABIARHDRxBxgAhAwyDAwtBACEAAkAgAigCOCIDRQ0AIAMoAkQiA0UNACACIAMRAAAhAAsgAEUNJyAAQRVHDZgCIAJB0AA2AhwgAiABNgIUIAJBkRg2AhAgAkEVNgIMQQAhAwyCAwsgASAERgRAQSghAwyCAwtBACEDIAJBADYCBCACQQw2AgggAiABIAEQKiIARQ2UAiACQSc2AhwgAiABNgIUIAIgADYCDAyBAwsgASAERgRAQSkhAwyBAwsgAS0AACIAQSBGDRMgAEEJRw2VAiABQQFqIQEMFAsgASAERwRAIAFBAWohAQwWC0EqIQMM/wILIAEgBEYEQEErIQMM/wILIAEtAAAiAEEJRyAAQSBHcQ2QAiACLQAsQQhHDd0CIAJBADoALAzdAgsgASAERgRAQSwhAwz+AgsgAS0AAEEKRw2OAiABQQFqIQEMsAELIAEgBEcNigJBLyEDDPwCCwNAIAEtAAAiAEEgRwRAIABBCmsOBIQCiAKIAoQChgILIAQgAUEBaiIBRw0AC0ExIQMM+wILQTIhAyABIARGDfoCIAIoAgAiACAEIAFraiEHIAEgAGtBA2ohBgJAA0AgAEHwO2otAAAgAS0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQEgAEEDRgRAQQYhAQziAgsgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAc2AgAM+wILIAJBADYCAAyGAgtBMyEDIAQgASIARg35AiAEIAFrIAIoAgAiAWohByAAIAFrQQhqIQYCQANAIAFB9DtqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBCEYEQEEFIQEM4QILIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADPoCCyACQQA2AgAgACEBDIUCC0E0IQMgBCABIgBGDfgCIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgJAA0AgAUHQwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBBUYEQEEHIQEM4AILIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADPkCCyACQQA2AgAgACEBDIQCCyABIARHBEADQCABLQAAQYA+ai0AACIAQQFHBEAgAEECRg0JDIECCyAEIAFBAWoiAUcNAAtBMCEDDPgCC0EwIQMM9wILIAEgBEcEQANAIAEtAAAiAEEgRwRAIABBCmsOBP8B/gH+Af8B/gELIAQgAUEBaiIBRw0AC0E4IQMM9wILQTghAwz2AgsDQCABLQAAIgBBIEcgAEEJR3EN9gEgBCABQQFqIgFHDQALQTwhAwz1AgsDQCABLQAAIgBBIEcEQAJAIABBCmsOBPkBBAT5AQALIABBLEYN9QEMAwsgBCABQQFqIgFHDQALQT8hAwz0AgtBwAAhAyABIARGDfMCIAIoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAEGAQGstAAAgAS0AAEEgckcNASAAQQZGDdsCIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPQCCyACQQA2AgALQTYhAwzZAgsgASAERgRAQcEAIQMM8gILIAJBDDYCCCACIAE2AgQgAi0ALEEBaw4E+wHuAewB6wHUAgsgAUEBaiEBDPoBCyABIARHBEADQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxIgBBCUYNACAAQSBGDQACQAJAAkACQCAAQeMAaw4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUExIQMM3AILIAFBAWohAUEyIQMM2wILIAFBAWohAUEzIQMM2gILDP4BCyAEIAFBAWoiAUcNAAtBNSEDDPACC0E1IQMM7wILIAEgBEcEQANAIAEtAABBgDxqLQAAQQFHDfcBIAQgAUEBaiIBRw0AC0E9IQMM7wILQT0hAwzuAgtBACEAAkAgAigCOCIDRQ0AIAMoAkAiA0UNACACIAMRAAAhAAsgAEUNASAAQRVHDeYBIAJBwgA2AhwgAiABNgIUIAJB4xg2AhAgAkEVNgIMQQAhAwztAgsgAUEBaiEBC0E8IQMM0gILIAEgBEYEQEHCACEDDOsCCwJAA0ACQCABLQAAQQlrDhgAAswCzALRAswCzALMAswCzALMAswCzALMAswCzALMAswCzALMAswCzALMAgDMAgsgBCABQQFqIgFHDQALQcIAIQMM6wILIAFBAWohASACLQAtQQFxRQ3+AQtBLCEDDNACCyABIARHDd4BQcQAIQMM6AILA0AgAS0AAEGQwABqLQAAQQFHDZwBIAQgAUEBaiIBRw0AC0HFACEDDOcCCyABLQAAIgBBIEYN/gEgAEE6Rw3AAiACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgAN3gEM3QELQccAIQMgBCABIgBGDeUCIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgNAIAFBkMIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNvwIgAUEFRg3CAiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBzYCAAzlAgtByAAhAyAEIAEiAEYN5AIgBCABayACKAIAIgFqIQcgACABa0EJaiEGA0AgAUGWwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw2+AkECIAFBCUYNwgIaIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADOQCCyABIARGBEBByQAhAwzkAgsCQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxQe4Aaw4HAL8CvwK/Ar8CvwIBvwILIAFBAWohAUE+IQMMywILIAFBAWohAUE/IQMMygILQcoAIQMgBCABIgBGDeICIAQgAWsgAigCACIBaiEGIAAgAWtBAWohBwNAIAFBoMIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNvAIgAUEBRg2+AiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBjYCAAziAgtBywAhAyAEIAEiAEYN4QIgBCABayACKAIAIgFqIQcgACABa0EOaiEGA0AgAUGiwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw27AiABQQ5GDb4CIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADOECC0HMACEDIAQgASIARg3gAiAEIAFrIAIoAgAiAWohByAAIAFrQQ9qIQYDQCABQcDCAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDboCQQMgAUEPRg2+AhogAUEBaiEBIAQgAEEBaiIARw0ACyACIAc2AgAM4AILQc0AIQMgBCABIgBGDd8CIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgNAIAFB0MIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNuQJBBCABQQVGDb0CGiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBzYCAAzfAgsgASAERgRAQc4AIQMM3wILAkACQAJAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXFB4wBrDhMAvAK8ArwCvAK8ArwCvAK8ArwCvAK8ArwCAbwCvAK8AgIDvAILIAFBAWohAUHBACEDDMgCCyABQQFqIQFBwgAhAwzHAgsgAUEBaiEBQcMAIQMMxgILIAFBAWohAUHEACEDDMUCCyABIARHBEAgAkENNgIIIAIgATYCBEHFACEDDMUCC0HPACEDDN0CCwJAAkAgAS0AAEEKaw4EAZABkAEAkAELIAFBAWohAQtBKCEDDMMCCyABIARGBEBB0QAhAwzcAgsgAS0AAEEgRw0AIAFBAWohASACLQAtQQFxRQ3QAQtBFyEDDMECCyABIARHDcsBQdIAIQMM2QILQdMAIQMgASAERg3YAiACKAIAIgAgBCABa2ohBiABIABrQQFqIQUDQCABLQAAIABB1sIAai0AAEcNxwEgAEEBRg3KASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBjYCAAzYAgsgASAERgRAQdUAIQMM2AILIAEtAABBCkcNwgEgAUEBaiEBDMoBCyABIARGBEBB1gAhAwzXAgsCQAJAIAEtAABBCmsOBADDAcMBAcMBCyABQQFqIQEMygELIAFBAWohAUHKACEDDL0CC0EAIQACQCACKAI4IgNFDQAgAygCPCIDRQ0AIAIgAxEAACEACyAADb8BQc0AIQMMvAILIAItAClBIkYNzwIMiQELIAQgASIFRgRAQdsAIQMM1AILQQAhAEEBIQFBASEGQQAhAwJAAn8CQAJAAkACQAJAAkACQCAFLQAAQTBrDgrFAcQBAAECAwQFBgjDAQtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshA0EAIQFBACEGDL0BC0EJIQNBASEAQQAhAUEAIQYMvAELIAEgBEYEQEHdACEDDNMCCyABLQAAQS5HDbgBIAFBAWohAQyIAQsgASAERw22AUHfACEDDNECCyABIARHBEAgAkEONgIIIAIgATYCBEHQACEDDLgCC0HgACEDDNACC0HhACEDIAEgBEYNzwIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGA0AgAS0AACAAQeLCAGotAABHDbEBIABBA0YNswEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMzwILQeIAIQMgASAERg3OAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYDQCABLQAAIABB5sIAai0AAEcNsAEgAEECRg2vASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAzOAgtB4wAhAyABIARGDc0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgNAIAEtAAAgAEHpwgBqLQAARw2vASAAQQNGDa0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADM0CCyABIARGBEBB5QAhAwzNAgsgAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANqgFB1gAhAwyzAgsgASAERwRAA0AgAS0AACIAQSBHBEACQAJAAkAgAEHIAGsOCwABswGzAbMBswGzAbMBswGzAQKzAQsgAUEBaiEBQdIAIQMMtwILIAFBAWohAUHTACEDDLYCCyABQQFqIQFB1AAhAwy1AgsgBCABQQFqIgFHDQALQeQAIQMMzAILQeQAIQMMywILA0AgAS0AAEHwwgBqLQAAIgBBAUcEQCAAQQJrDgOnAaYBpQGkAQsgBCABQQFqIgFHDQALQeYAIQMMygILIAFBAWogASAERw0CGkHnACEDDMkCCwNAIAEtAABB8MQAai0AACIAQQFHBEACQCAAQQJrDgSiAaEBoAEAnwELQdcAIQMMsQILIAQgAUEBaiIBRw0AC0HoACEDDMgCCyABIARGBEBB6QAhAwzIAgsCQCABLQAAIgBBCmsOGrcBmwGbAbQBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBpAGbAZsBAJkBCyABQQFqCyEBQQYhAwytAgsDQCABLQAAQfDGAGotAABBAUcNfSAEIAFBAWoiAUcNAAtB6gAhAwzFAgsgAUEBaiABIARHDQIaQesAIQMMxAILIAEgBEYEQEHsACEDDMQCCyABQQFqDAELIAEgBEYEQEHtACEDDMMCCyABQQFqCyEBQQQhAwyoAgsgASAERgRAQe4AIQMMwQILAkACQAJAIAEtAABB8MgAai0AAEEBaw4HkAGPAY4BAHwBAo0BCyABQQFqIQEMCwsgAUEBagyTAQtBACEDIAJBADYCHCACQZsSNgIQIAJBBzYCDCACIAFBAWo2AhQMwAILAkADQCABLQAAQfDIAGotAAAiAEEERwRAAkACQCAAQQFrDgeUAZMBkgGNAQAEAY0BC0HaACEDDKoCCyABQQFqIQFB3AAhAwypAgsgBCABQQFqIgFHDQALQe8AIQMMwAILIAFBAWoMkQELIAQgASIARgRAQfAAIQMMvwILIAAtAABBL0cNASAAQQFqIQEMBwsgBCABIgBGBEBB8QAhAwy+AgsgAC0AACIBQS9GBEAgAEEBaiEBQd0AIQMMpQILIAFBCmsiA0EWSw0AIAAhAUEBIAN0QYmAgAJxDfkBC0EAIQMgAkEANgIcIAIgADYCFCACQYwcNgIQIAJBBzYCDAy8AgsgASAERwRAIAFBAWohAUHeACEDDKMCC0HyACEDDLsCCyABIARGBEBB9AAhAwy7AgsCQCABLQAAQfDMAGotAABBAWsOA/cBcwCCAQtB4QAhAwyhAgsgASAERwRAA0AgAS0AAEHwygBqLQAAIgBBA0cEQAJAIABBAWsOAvkBAIUBC0HfACEDDKMCCyAEIAFBAWoiAUcNAAtB8wAhAwy6AgtB8wAhAwy5AgsgASAERwRAIAJBDzYCCCACIAE2AgRB4AAhAwygAgtB9QAhAwy4AgsgASAERgRAQfYAIQMMuAILIAJBDzYCCCACIAE2AgQLQQMhAwydAgsDQCABLQAAQSBHDY4CIAQgAUEBaiIBRw0AC0H3ACEDDLUCCyABIARGBEBB+AAhAwy1AgsgAS0AAEEgRw16IAFBAWohAQxbC0EAIQACQCACKAI4IgNFDQAgAygCOCIDRQ0AIAIgAxEAACEACyAADXgMgAILIAEgBEYEQEH6ACEDDLMCCyABLQAAQcwARw10IAFBAWohAUETDHYLQfsAIQMgASAERg2xAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYDQCABLQAAIABB8M4Aai0AAEcNcyAAQQVGDXUgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMsQILIAEgBEYEQEH8ACEDDLECCwJAAkAgAS0AAEHDAGsODAB0dHR0dHR0dHR0AXQLIAFBAWohAUHmACEDDJgCCyABQQFqIQFB5wAhAwyXAgtB/QAhAyABIARGDa8CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDXIgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADLACCyACQQA2AgAgBkEBaiEBQRAMcwtB/gAhAyABIARGDa4CIAIoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQfbOAGotAABHDXEgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK8CCyACQQA2AgAgBkEBaiEBQRYMcgtB/wAhAyABIARGDa0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQfzOAGotAABHDXAgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK4CCyACQQA2AgAgBkEBaiEBQQUMcQsgASAERgRAQYABIQMMrQILIAEtAABB2QBHDW4gAUEBaiEBQQgMcAsgASAERgRAQYEBIQMMrAILAkACQCABLQAAQc4Aaw4DAG8BbwsgAUEBaiEBQesAIQMMkwILIAFBAWohAUHsACEDDJICCyABIARGBEBBggEhAwyrAgsCQAJAIAEtAABByABrDggAbm5ubm5uAW4LIAFBAWohAUHqACEDDJICCyABQQFqIQFB7QAhAwyRAgtBgwEhAyABIARGDakCIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQYDPAGotAABHDWwgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKoCCyACQQA2AgAgBkEBaiEBQQAMbQtBhAEhAyABIARGDagCIAIoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQYPPAGotAABHDWsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKkCCyACQQA2AgAgBkEBaiEBQSMMbAsgASAERgRAQYUBIQMMqAILAkACQCABLQAAQcwAaw4IAGtra2trawFrCyABQQFqIQFB7wAhAwyPAgsgAUEBaiEBQfAAIQMMjgILIAEgBEYEQEGGASEDDKcCCyABLQAAQcUARw1oIAFBAWohAQxgC0GHASEDIAEgBEYNpQIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBiM8Aai0AAEcNaCAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpgILIAJBADYCACAGQQFqIQFBLQxpC0GIASEDIAEgBEYNpAIgAigCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABB0M8Aai0AAEcNZyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpQILIAJBADYCACAGQQFqIQFBKQxoCyABIARGBEBBiQEhAwykAgtBASABLQAAQd8ARw1nGiABQQFqIQEMXgtBigEhAyABIARGDaICIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgNAIAEtAAAgAEGMzwBqLQAARw1kIABBAUYN+gEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMogILQYsBIQMgASAERg2hAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGOzwBqLQAARw1kIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyiAgsgAkEANgIAIAZBAWohAUECDGULQYwBIQMgASAERg2gAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHwzwBqLQAARw1jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyhAgsgAkEANgIAIAZBAWohAUEfDGQLQY0BIQMgASAERg2fAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHyzwBqLQAARw1iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAygAgsgAkEANgIAIAZBAWohAUEJDGMLIAEgBEYEQEGOASEDDJ8CCwJAAkAgAS0AAEHJAGsOBwBiYmJiYgFiCyABQQFqIQFB+AAhAwyGAgsgAUEBaiEBQfkAIQMMhQILQY8BIQMgASAERg2dAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGRzwBqLQAARw1gIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyeAgsgAkEANgIAIAZBAWohAUEYDGELQZABIQMgASAERg2cAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGXzwBqLQAARw1fIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAydAgsgAkEANgIAIAZBAWohAUEXDGALQZEBIQMgASAERg2bAiACKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIAEtAAAgAEGazwBqLQAARw1eIABBBkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAycAgsgAkEANgIAIAZBAWohAUEVDF8LQZIBIQMgASAERg2aAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGhzwBqLQAARw1dIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAybAgsgAkEANgIAIAZBAWohAUEeDF4LIAEgBEYEQEGTASEDDJoCCyABLQAAQcwARw1bIAFBAWohAUEKDF0LIAEgBEYEQEGUASEDDJkCCwJAAkAgAS0AAEHBAGsODwBcXFxcXFxcXFxcXFxcAVwLIAFBAWohAUH+ACEDDIACCyABQQFqIQFB/wAhAwz/AQsgASAERgRAQZUBIQMMmAILAkACQCABLQAAQcEAaw4DAFsBWwsgAUEBaiEBQf0AIQMM/wELIAFBAWohAUGAASEDDP4BC0GWASEDIAEgBEYNlgIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBp88Aai0AAEcNWSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlwILIAJBADYCACAGQQFqIQFBCwxaCyABIARGBEBBlwEhAwyWAgsCQAJAAkACQCABLQAAQS1rDiMAW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1sBW1tbW1sCW1tbA1sLIAFBAWohAUH7ACEDDP8BCyABQQFqIQFB/AAhAwz+AQsgAUEBaiEBQYEBIQMM/QELIAFBAWohAUGCASEDDPwBC0GYASEDIAEgBEYNlAIgAigCACIAIAQgAWtqIQUgASAAa0EEaiEGAkADQCABLQAAIABBqc8Aai0AAEcNVyAAQQRGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlQILIAJBADYCACAGQQFqIQFBGQxYC0GZASEDIAEgBEYNkwIgAigCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBrs8Aai0AAEcNViAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlAILIAJBADYCACAGQQFqIQFBBgxXC0GaASEDIAEgBEYNkgIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBtM8Aai0AAEcNVSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMkwILIAJBADYCACAGQQFqIQFBHAxWC0GbASEDIAEgBEYNkQIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBts8Aai0AAEcNVCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMkgILIAJBADYCACAGQQFqIQFBJwxVCyABIARGBEBBnAEhAwyRAgsCQAJAIAEtAABB1ABrDgIAAVQLIAFBAWohAUGGASEDDPgBCyABQQFqIQFBhwEhAwz3AQtBnQEhAyABIARGDY8CIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbjPAGotAABHDVIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADJACCyACQQA2AgAgBkEBaiEBQSYMUwtBngEhAyABIARGDY4CIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbrPAGotAABHDVEgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI8CCyACQQA2AgAgBkEBaiEBQQMMUgtBnwEhAyABIARGDY0CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDVAgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI4CCyACQQA2AgAgBkEBaiEBQQwMUQtBoAEhAyABIARGDYwCIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQbzPAGotAABHDU8gAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI0CCyACQQA2AgAgBkEBaiEBQQ0MUAsgASAERgRAQaEBIQMMjAILAkACQCABLQAAQcYAaw4LAE9PT09PT09PTwFPCyABQQFqIQFBiwEhAwzzAQsgAUEBaiEBQYwBIQMM8gELIAEgBEYEQEGiASEDDIsCCyABLQAAQdAARw1MIAFBAWohAQxGCyABIARGBEBBowEhAwyKAgsCQAJAIAEtAABByQBrDgcBTU1NTU0ATQsgAUEBaiEBQY4BIQMM8QELIAFBAWohAUEiDE0LQaQBIQMgASAERg2IAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHAzwBqLQAARw1LIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyJAgsgAkEANgIAIAZBAWohAUEdDEwLIAEgBEYEQEGlASEDDIgCCwJAAkAgAS0AAEHSAGsOAwBLAUsLIAFBAWohAUGQASEDDO8BCyABQQFqIQFBBAxLCyABIARGBEBBpgEhAwyHAgsCQAJAAkACQAJAIAEtAABBwQBrDhUATU1NTU1NTU1NTQFNTQJNTQNNTQRNCyABQQFqIQFBiAEhAwzxAQsgAUEBaiEBQYkBIQMM8AELIAFBAWohAUGKASEDDO8BCyABQQFqIQFBjwEhAwzuAQsgAUEBaiEBQZEBIQMM7QELQacBIQMgASAERg2FAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHtzwBqLQAARw1IIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyGAgsgAkEANgIAIAZBAWohAUERDEkLQagBIQMgASAERg2EAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHCzwBqLQAARw1HIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyFAgsgAkEANgIAIAZBAWohAUEsDEgLQakBIQMgASAERg2DAiACKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHFzwBqLQAARw1GIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyEAgsgAkEANgIAIAZBAWohAUErDEcLQaoBIQMgASAERg2CAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHKzwBqLQAARw1FIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyDAgsgAkEANgIAIAZBAWohAUEUDEYLIAEgBEYEQEGrASEDDIICCwJAAkACQAJAIAEtAABBwgBrDg8AAQJHR0dHR0dHR0dHRwNHCyABQQFqIQFBkwEhAwzrAQsgAUEBaiEBQZQBIQMM6gELIAFBAWohAUGVASEDDOkBCyABQQFqIQFBlgEhAwzoAQsgASAERgRAQawBIQMMgQILIAEtAABBxQBHDUIgAUEBaiEBDD0LQa0BIQMgASAERg3/ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHNzwBqLQAARw1CIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyAAgsgAkEANgIAIAZBAWohAUEODEMLIAEgBEYEQEGuASEDDP8BCyABLQAAQdAARw1AIAFBAWohAUElDEILQa8BIQMgASAERg39ASACKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEHQzwBqLQAARw1AIABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz+AQsgAkEANgIAIAZBAWohAUEqDEELIAEgBEYEQEGwASEDDP0BCwJAAkAgAS0AAEHVAGsOCwBAQEBAQEBAQEABQAsgAUEBaiEBQZoBIQMM5AELIAFBAWohAUGbASEDDOMBCyABIARGBEBBsQEhAwz8AQsCQAJAIAEtAABBwQBrDhQAPz8/Pz8/Pz8/Pz8/Pz8/Pz8/AT8LIAFBAWohAUGZASEDDOMBCyABQQFqIQFBnAEhAwziAQtBsgEhAyABIARGDfoBIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQdnPAGotAABHDT0gAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPsBCyACQQA2AgAgBkEBaiEBQSEMPgtBswEhAyABIARGDfkBIAIoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAS0AACAAQd3PAGotAABHDTwgAEEGRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPoBCyACQQA2AgAgBkEBaiEBQRoMPQsgASAERgRAQbQBIQMM+QELAkACQAJAIAEtAABBxQBrDhEAPT09PT09PT09AT09PT09Aj0LIAFBAWohAUGdASEDDOEBCyABQQFqIQFBngEhAwzgAQsgAUEBaiEBQZ8BIQMM3wELQbUBIQMgASAERg33ASACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHkzwBqLQAARw06IABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz4AQsgAkEANgIAIAZBAWohAUEoDDsLQbYBIQMgASAERg32ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHqzwBqLQAARw05IABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz3AQsgAkEANgIAIAZBAWohAUEHDDoLIAEgBEYEQEG3ASEDDPYBCwJAAkAgAS0AAEHFAGsODgA5OTk5OTk5OTk5OTkBOQsgAUEBaiEBQaEBIQMM3QELIAFBAWohAUGiASEDDNwBC0G4ASEDIAEgBEYN9AEgAigCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB7c8Aai0AAEcNNyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM9QELIAJBADYCACAGQQFqIQFBEgw4C0G5ASEDIAEgBEYN8wEgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8M8Aai0AAEcNNiAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM9AELIAJBADYCACAGQQFqIQFBIAw3C0G6ASEDIAEgBEYN8gEgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8s8Aai0AAEcNNSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM8wELIAJBADYCACAGQQFqIQFBDww2CyABIARGBEBBuwEhAwzyAQsCQAJAIAEtAABByQBrDgcANTU1NTUBNQsgAUEBaiEBQaUBIQMM2QELIAFBAWohAUGmASEDDNgBC0G8ASEDIAEgBEYN8AEgAigCACIAIAQgAWtqIQUgASAAa0EHaiEGAkADQCABLQAAIABB9M8Aai0AAEcNMyAAQQdGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM8QELIAJBADYCACAGQQFqIQFBGww0CyABIARGBEBBvQEhAwzwAQsCQAJAAkAgAS0AAEHCAGsOEgA0NDQ0NDQ0NDQBNDQ0NDQ0AjQLIAFBAWohAUGkASEDDNgBCyABQQFqIQFBpwEhAwzXAQsgAUEBaiEBQagBIQMM1gELIAEgBEYEQEG+ASEDDO8BCyABLQAAQc4ARw0wIAFBAWohAQwsCyABIARGBEBBvwEhAwzuAQsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABLQAAQcEAaw4VAAECAz8EBQY/Pz8HCAkKCz8MDQ4PPwsgAUEBaiEBQegAIQMM4wELIAFBAWohAUHpACEDDOIBCyABQQFqIQFB7gAhAwzhAQsgAUEBaiEBQfIAIQMM4AELIAFBAWohAUHzACEDDN8BCyABQQFqIQFB9gAhAwzeAQsgAUEBaiEBQfcAIQMM3QELIAFBAWohAUH6ACEDDNwBCyABQQFqIQFBgwEhAwzbAQsgAUEBaiEBQYQBIQMM2gELIAFBAWohAUGFASEDDNkBCyABQQFqIQFBkgEhAwzYAQsgAUEBaiEBQZgBIQMM1wELIAFBAWohAUGgASEDDNYBCyABQQFqIQFBowEhAwzVAQsgAUEBaiEBQaoBIQMM1AELIAEgBEcEQCACQRA2AgggAiABNgIEQasBIQMM1AELQcABIQMM7AELQQAhAAJAIAIoAjgiA0UNACADKAI0IgNFDQAgAiADEQAAIQALIABFDV4gAEEVRw0HIAJB0QA2AhwgAiABNgIUIAJBsBc2AhAgAkEVNgIMQQAhAwzrAQsgAUEBaiABIARHDQgaQcIBIQMM6gELA0ACQCABLQAAQQprDgQIAAALAAsgBCABQQFqIgFHDQALQcMBIQMM6QELIAEgBEcEQCACQRE2AgggAiABNgIEQQEhAwzQAQtBxAEhAwzoAQsgASAERgRAQcUBIQMM6AELAkACQCABLQAAQQprDgQBKCgAKAsgAUEBagwJCyABQQFqDAULIAEgBEYEQEHGASEDDOcBCwJAAkAgAS0AAEEKaw4XAQsLAQsLCwsLCwsLCwsLCwsLCwsLCwALCyABQQFqIQELQbABIQMMzQELIAEgBEYEQEHIASEDDOYBCyABLQAAQSBHDQkgAkEAOwEyIAFBAWohAUGzASEDDMwBCwNAIAEhAAJAIAEgBEcEQCABLQAAQTBrQf8BcSIDQQpJDQEMJwtBxwEhAwzmAQsCQCACLwEyIgFBmTNLDQAgAiABQQpsIgU7ATIgBUH+/wNxIANB//8Dc0sNACAAQQFqIQEgAiADIAVqIgM7ATIgA0H//wNxQegHSQ0BCwtBACEDIAJBADYCHCACQcEJNgIQIAJBDTYCDCACIABBAWo2AhQM5AELIAJBADYCHCACIAE2AhQgAkHwDDYCECACQRs2AgxBACEDDOMBCyACKAIEIQAgAkEANgIEIAIgACABECYiAA0BIAFBAWoLIQFBrQEhAwzIAQsgAkHBATYCHCACIAA2AgwgAiABQQFqNgIUQQAhAwzgAQsgAigCBCEAIAJBADYCBCACIAAgARAmIgANASABQQFqCyEBQa4BIQMMxQELIAJBwgE2AhwgAiAANgIMIAIgAUEBajYCFEEAIQMM3QELIAJBADYCHCACIAE2AhQgAkGXCzYCECACQQ02AgxBACEDDNwBCyACQQA2AhwgAiABNgIUIAJB4xA2AhAgAkEJNgIMQQAhAwzbAQsgAkECOgAoDKwBC0EAIQMgAkEANgIcIAJBrws2AhAgAkECNgIMIAIgAUEBajYCFAzZAQtBAiEDDL8BC0ENIQMMvgELQSYhAwy9AQtBFSEDDLwBC0EWIQMMuwELQRghAwy6AQtBHCEDDLkBC0EdIQMMuAELQSAhAwy3AQtBISEDDLYBC0EjIQMMtQELQcYAIQMMtAELQS4hAwyzAQtBPSEDDLIBC0HLACEDDLEBC0HOACEDDLABC0HYACEDDK8BC0HZACEDDK4BC0HbACEDDK0BC0HxACEDDKwBC0H0ACEDDKsBC0GNASEDDKoBC0GXASEDDKkBC0GpASEDDKgBC0GvASEDDKcBC0GxASEDDKYBCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJB8Rs2AhAgAkEGNgIMDL0BCyACQQA2AgAgBkEBaiEBQSQLOgApIAIoAgQhACACQQA2AgQgAiAAIAEQJyIARQRAQeUAIQMMowELIAJB+QA2AhwgAiABNgIUIAIgADYCDEEAIQMMuwELIABBFUcEQCACQQA2AhwgAiABNgIUIAJBzA42AhAgAkEgNgIMQQAhAwy7AQsgAkH4ADYCHCACIAE2AhQgAkHKGDYCECACQRU2AgxBACEDDLoBCyACQQA2AhwgAiABNgIUIAJBjhs2AhAgAkEGNgIMQQAhAwy5AQsgAkEANgIcIAIgATYCFCACQf4RNgIQIAJBBzYCDEEAIQMMuAELIAJBADYCHCACIAE2AhQgAkGMHDYCECACQQc2AgxBACEDDLcBCyACQQA2AhwgAiABNgIUIAJBww82AhAgAkEHNgIMQQAhAwy2AQsgAkEANgIcIAIgATYCFCACQcMPNgIQIAJBBzYCDEEAIQMMtQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0RIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMtAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0gIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMswELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0iIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMsgELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0OIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMsQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0dIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMsAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0fIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMrwELIABBP0cNASABQQFqCyEBQQUhAwyUAQtBACEDIAJBADYCHCACIAE2AhQgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwyjAQtB1QAhAwyJAQsgAEEVRwRAIAJBADYCHCACIAE2AhQgAkG5DTYCECACQRo2AgxBACEDDKIBCyACQeQANgIcIAIgATYCFCACQeMXNgIQIAJBFTYCDEEAIQMMoQELIAJBADYCACAGQQFqIQEgAi0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACEDIAJBADYCHCACIAE2AhQgAkH3CTYCECACQQg2AgwMoAELIAJBADYCACAGQQFqIQEgAi0AKUEhRg0DIAJBADYCHCACIAE2AhQgAkGbCjYCECACQQg2AgxBACEDDJ8BCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJBkDM2AhAgAkEINgIMDJ0BCyACQQA2AgAgBkEBaiEBIAItAClBI0kNACACQQA2AhwgAiABNgIUIAJB0wk2AhAgAkEINgIMQQAhAwycAQtB0QAhAwyCAQsgAS0AAEEwayIAQf8BcUEKSQRAIAIgADoAKiABQQFqIQFBzwAhAwyCAQsgAigCBCEAIAJBADYCBCACIAAgARAoIgBFDYYBIAJB3gA2AhwgAiABNgIUIAIgADYCDEEAIQMMmgELIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ2GASACQdwANgIcIAIgATYCFCACIAA2AgxBACEDDJkBCyACKAIEIQAgAkEANgIEIAIgACAFECgiAEUEQCAFIQEMhwELIAJB2gA2AhwgAiAFNgIUIAIgADYCDAyYAQtBACEBQQEhAwsgAiADOgArIAVBAWohAwJAAkACQCACLQAtQRBxDQACQAJAAkAgAi0AKg4DAQACBAsgBkUNAwwCCyAADQEMAgsgAUUNAQsgAigCBCEAIAJBADYCBCACIAAgAxAoIgBFBEAgAyEBDAILIAJB2AA2AhwgAiADNgIUIAIgADYCDEEAIQMMmAELIAIoAgQhACACQQA2AgQgAiAAIAMQKCIARQRAIAMhAQyHAQsgAkHZADYCHCACIAM2AhQgAiAANgIMQQAhAwyXAQtBzAAhAwx9CyAAQRVHBEAgAkEANgIcIAIgATYCFCACQZQNNgIQIAJBITYCDEEAIQMMlgELIAJB1wA2AhwgAiABNgIUIAJByRc2AhAgAkEVNgIMQQAhAwyVAQtBACEDIAJBADYCHCACIAE2AhQgAkGAETYCECACQQk2AgwMlAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0AIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMkwELQckAIQMMeQsgAkEANgIcIAIgATYCFCACQcEoNgIQIAJBBzYCDCACQQA2AgBBACEDDJEBCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAlIgBFDQAgAkHSADYCHCACIAE2AhQgAiAANgIMDJABC0HIACEDDHYLIAJBADYCACAFIQELIAJBgBI7ASogAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANAQtBxwAhAwxzCyAAQRVGBEAgAkHRADYCHCACIAE2AhQgAkHjFzYCECACQRU2AgxBACEDDIwBC0EAIQMgAkEANgIcIAIgATYCFCACQbkNNgIQIAJBGjYCDAyLAQtBACEDIAJBADYCHCACIAE2AhQgAkGgGTYCECACQR42AgwMigELIAEtAABBOkYEQCACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgBFDQEgAkHDADYCHCACIAA2AgwgAiABQQFqNgIUDIoBC0EAIQMgAkEANgIcIAIgATYCFCACQbERNgIQIAJBCjYCDAyJAQsgAUEBaiEBQTshAwxvCyACQcMANgIcIAIgADYCDCACIAFBAWo2AhQMhwELQQAhAyACQQA2AhwgAiABNgIUIAJB8A42AhAgAkEcNgIMDIYBCyACIAIvATBBEHI7ATAMZgsCQCACLwEwIgBBCHFFDQAgAi0AKEEBRw0AIAItAC1BCHFFDQMLIAIgAEH3+wNxQYAEcjsBMAwECyABIARHBEACQANAIAEtAABBMGsiAEH/AXFBCk8EQEE1IQMMbgsgAikDICIKQpmz5syZs+bMGVYNASACIApCCn4iCjcDICAKIACtQv8BgyILQn+FVg0BIAIgCiALfDcDICAEIAFBAWoiAUcNAAtBOSEDDIUBCyACKAIEIQBBACEDIAJBADYCBCACIAAgAUEBaiIBECoiAA0MDHcLQTkhAwyDAQsgAi0AMEEgcQ0GQcUBIQMMaQtBACEDIAJBADYCBCACIAEgARAqIgBFDQQgAkE6NgIcIAIgADYCDCACIAFBAWo2AhQMgQELIAItAChBAUcNACACLQAtQQhxRQ0BC0E3IQMMZgsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIABEAgAkE7NgIcIAIgADYCDCACIAFBAWo2AhQMfwsgAUEBaiEBDG4LIAJBCDoALAwECyABQQFqIQEMbQtBACEDIAJBADYCHCACIAE2AhQgAkHkEjYCECACQQQ2AgwMewsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIARQ1sIAJBNzYCHCACIAE2AhQgAiAANgIMDHoLIAIgAi8BMEEgcjsBMAtBMCEDDF8LIAJBNjYCHCACIAE2AhQgAiAANgIMDHcLIABBLEcNASABQQFqIQBBASEBAkACQAJAAkACQCACLQAsQQVrDgQDAQIEAAsgACEBDAQLQQIhAQwBC0EEIQELIAJBAToALCACIAIvATAgAXI7ATAgACEBDAELIAIgAi8BMEEIcjsBMCAAIQELQTkhAwxcCyACQQA6ACwLQTQhAwxaCyABIARGBEBBLSEDDHMLAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0EtIQMMdAsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIARQ0CIAJBLDYCHCACIAE2AhQgAiAANgIMDHMLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABECoiAEUEQCABQQFqIQEMAgsgAkEsNgIcIAIgADYCDCACIAFBAWo2AhQMcgsgAS0AAEENRgRAIAIoAgQhAEEAIQMgAkEANgIEIAIgACABECoiAEUEQCABQQFqIQEMAgsgAkEsNgIcIAIgADYCDCACIAFBAWo2AhQMcgsgAi0ALUEBcQRAQcQBIQMMWQsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIADQEMZQtBLyEDDFcLIAJBLjYCHCACIAE2AhQgAiAANgIMDG8LQQAhAyACQQA2AhwgAiABNgIUIAJB8BQ2AhAgAkEDNgIMDG4LQQEhAwJAAkACQAJAIAItACxBBWsOBAMBAgAECyACIAIvATBBCHI7ATAMAwtBAiEDDAELQQQhAwsgAkEBOgAsIAIgAi8BMCADcjsBMAtBKiEDDFMLQQAhAyACQQA2AhwgAiABNgIUIAJB4Q82AhAgAkEKNgIMDGsLQQEhAwJAAkACQAJAAkACQCACLQAsQQJrDgcFBAQDAQIABAsgAiACLwEwQQhyOwEwDAMLQQIhAwwBC0EEIQMLIAJBAToALCACIAIvATAgA3I7ATALQSshAwxSC0EAIQMgAkEANgIcIAIgATYCFCACQasSNgIQIAJBCzYCDAxqC0EAIQMgAkEANgIcIAIgATYCFCACQf0NNgIQIAJBHTYCDAxpCyABIARHBEADQCABLQAAQSBHDUggBCABQQFqIgFHDQALQSUhAwxpC0ElIQMMaAsgAi0ALUEBcQRAQcMBIQMMTwsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKSIABEAgAkEmNgIcIAIgADYCDCACIAFBAWo2AhQMaAsgAUEBaiEBDFwLIAFBAWohASACLwEwIgBBgAFxBEBBACEAAkAgAigCOCIDRQ0AIAMoAlQiA0UNACACIAMRAAAhAAsgAEUNBiAAQRVHDR8gAkEFNgIcIAIgATYCFCACQfkXNgIQIAJBFTYCDEEAIQMMZwsCQCAAQaAEcUGgBEcNACACLQAtQQJxDQBBACEDIAJBADYCHCACIAE2AhQgAkGWEzYCECACQQQ2AgwMZwsgAgJ/IAIvATBBFHFBFEYEQEEBIAItAChBAUYNARogAi8BMkHlAEYMAQsgAi0AKUEFRgs6AC5BACEAAkAgAigCOCIDRQ0AIAMoAiQiA0UNACACIAMRAAAhAAsCQAJAAkACQAJAIAAOFgIBAAQEBAQEBAQEBAQEBAQEBAQEBAMECyACQQE6AC4LIAIgAi8BMEHAAHI7ATALQSchAwxPCyACQSM2AhwgAiABNgIUIAJBpRY2AhAgAkEVNgIMQQAhAwxnC0EAIQMgAkEANgIcIAIgATYCFCACQdULNgIQIAJBETYCDAxmC0EAIQACQCACKAI4IgNFDQAgAygCLCIDRQ0AIAIgAxEAACEACyAADQELQQ4hAwxLCyAAQRVGBEAgAkECNgIcIAIgATYCFCACQbAYNgIQIAJBFTYCDEEAIQMMZAtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMYwtBACEDIAJBADYCHCACIAE2AhQgAkGqHDYCECACQQ82AgwMYgsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEgCqdqIgEQKyIARQ0AIAJBBTYCHCACIAE2AhQgAiAANgIMDGELQQ8hAwxHC0EAIQMgAkEANgIcIAIgATYCFCACQc0TNgIQIAJBDDYCDAxfC0IBIQoLIAFBAWohAQJAIAIpAyAiC0L//////////w9YBEAgAiALQgSGIAqENwMgDAELQQAhAyACQQA2AhwgAiABNgIUIAJBrQk2AhAgAkEMNgIMDF4LQSQhAwxEC0EAIQMgAkEANgIcIAIgATYCFCACQc0TNgIQIAJBDDYCDAxcCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAsIgBFBEAgAUEBaiEBDFILIAJBFzYCHCACIAA2AgwgAiABQQFqNgIUDFsLIAIoAgQhAEEAIQMgAkEANgIEAkAgAiAAIAEQLCIARQRAIAFBAWohAQwBCyACQRY2AhwgAiAANgIMIAIgAUEBajYCFAxbC0EfIQMMQQtBACEDIAJBADYCHCACIAE2AhQgAkGaDzYCECACQSI2AgwMWQsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQLSIARQRAIAFBAWohAQxQCyACQRQ2AhwgAiAANgIMIAIgAUEBajYCFAxYCyACKAIEIQBBACEDIAJBADYCBAJAIAIgACABEC0iAEUEQCABQQFqIQEMAQsgAkETNgIcIAIgADYCDCACIAFBAWo2AhQMWAtBHiEDDD4LQQAhAyACQQA2AhwgAiABNgIUIAJBxgw2AhAgAkEjNgIMDFYLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABEC0iAEUEQCABQQFqIQEMTgsgAkERNgIcIAIgADYCDCACIAFBAWo2AhQMVQsgAkEQNgIcIAIgATYCFCACIAA2AgwMVAtBACEDIAJBADYCHCACIAE2AhQgAkHGDDYCECACQSM2AgwMUwtBACEDIAJBADYCHCACIAE2AhQgAkHAFTYCECACQQI2AgwMUgsgAigCBCEAQQAhAyACQQA2AgQCQCACIAAgARAtIgBFBEAgAUEBaiEBDAELIAJBDjYCHCACIAA2AgwgAiABQQFqNgIUDFILQRshAww4C0EAIQMgAkEANgIcIAIgATYCFCACQcYMNgIQIAJBIzYCDAxQCyACKAIEIQBBACEDIAJBADYCBAJAIAIgACABECwiAEUEQCABQQFqIQEMAQsgAkENNgIcIAIgADYCDCACIAFBAWo2AhQMUAtBGiEDDDYLQQAhAyACQQA2AhwgAiABNgIUIAJBmg82AhAgAkEiNgIMDE4LIAIoAgQhAEEAIQMgAkEANgIEAkAgAiAAIAEQLCIARQRAIAFBAWohAQwBCyACQQw2AhwgAiAANgIMIAIgAUEBajYCFAxOC0EZIQMMNAtBACEDIAJBADYCHCACIAE2AhQgAkGaDzYCECACQSI2AgwMTAsgAEEVRwRAQQAhAyACQQA2AhwgAiABNgIUIAJBgww2AhAgAkETNgIMDEwLIAJBCjYCHCACIAE2AhQgAkHkFjYCECACQRU2AgxBACEDDEsLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABIAqnaiIBECsiAARAIAJBBzYCHCACIAE2AhQgAiAANgIMDEsLQRMhAwwxCyAAQRVHBEBBACEDIAJBADYCHCACIAE2AhQgAkHaDTYCECACQRQ2AgwMSgsgAkEeNgIcIAIgATYCFCACQfkXNgIQIAJBFTYCDEEAIQMMSQtBACEAAkAgAigCOCIDRQ0AIAMoAiwiA0UNACACIAMRAAAhAAsgAEUNQSAAQRVGBEAgAkEDNgIcIAIgATYCFCACQbAYNgIQIAJBFTYCDEEAIQMMSQtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMSAtBACEDIAJBADYCHCACIAE2AhQgAkHaDTYCECACQRQ2AgwMRwtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMRgsgAkEAOgAvIAItAC1BBHFFDT8LIAJBADoALyACQQE6ADRBACEDDCsLQQAhAyACQQA2AhwgAkHkETYCECACQQc2AgwgAiABQQFqNgIUDEMLAkADQAJAIAEtAABBCmsOBAACAgACCyAEIAFBAWoiAUcNAAtB3QEhAwxDCwJAAkAgAi0ANEEBRw0AQQAhAAJAIAIoAjgiA0UNACADKAJYIgNFDQAgAiADEQAAIQALIABFDQAgAEEVRw0BIAJB3AE2AhwgAiABNgIUIAJB1RY2AhAgAkEVNgIMQQAhAwxEC0HBASEDDCoLIAJBADYCHCACIAE2AhQgAkHpCzYCECACQR82AgxBACEDDEILAkACQCACLQAoQQFrDgIEAQALQcABIQMMKQtBuQEhAwwoCyACQQI6AC9BACEAAkAgAigCOCIDRQ0AIAMoAgAiA0UNACACIAMRAAAhAAsgAEUEQEHCASEDDCgLIABBFUcEQCACQQA2AhwgAiABNgIUIAJBpAw2AhAgAkEQNgIMQQAhAwxBCyACQdsBNgIcIAIgATYCFCACQfoWNgIQIAJBFTYCDEEAIQMMQAsgASAERgRAQdoBIQMMQAsgAS0AAEHIAEYNASACQQE6ACgLQawBIQMMJQtBvwEhAwwkCyABIARHBEAgAkEQNgIIIAIgATYCBEG+ASEDDCQLQdkBIQMMPAsgASAERgRAQdgBIQMMPAsgAS0AAEHIAEcNBCABQQFqIQFBvQEhAwwiCyABIARGBEBB1wEhAww7CwJAAkAgAS0AAEHFAGsOEAAFBQUFBQUFBQUFBQUFBQEFCyABQQFqIQFBuwEhAwwiCyABQQFqIQFBvAEhAwwhC0HWASEDIAEgBEYNOSACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGD0ABqLQAARw0DIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAw6CyACKAIEIQAgAkIANwMAIAIgACAGQQFqIgEQJyIARQRAQcYBIQMMIQsgAkHVATYCHCACIAE2AhQgAiAANgIMQQAhAww5C0HUASEDIAEgBEYNOCACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGB0ABqLQAARw0CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAw5CyACQYEEOwEoIAIoAgQhACACQgA3AwAgAiAAIAZBAWoiARAnIgANAwwCCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJB2Bs2AhAgAkEINgIMDDYLQboBIQMMHAsgAkHTATYCHCACIAE2AhQgAiAANgIMQQAhAww0C0EAIQACQCACKAI4IgNFDQAgAygCOCIDRQ0AIAIgAxEAACEACyAARQ0AIABBFUYNASACQQA2AhwgAiABNgIUIAJBzA42AhAgAkEgNgIMQQAhAwwzC0HkACEDDBkLIAJB+AA2AhwgAiABNgIUIAJByhg2AhAgAkEVNgIMQQAhAwwxC0HSASEDIAQgASIARg0wIAQgAWsgAigCACIBaiEFIAAgAWtBBGohBgJAA0AgAC0AACABQfzPAGotAABHDQEgAUEERg0DIAFBAWohASAEIABBAWoiAEcNAAsgAiAFNgIADDELIAJBADYCHCACIAA2AhQgAkGQMzYCECACQQg2AgwgAkEANgIAQQAhAwwwCyABIARHBEAgAkEONgIIIAIgATYCBEG3ASEDDBcLQdEBIQMMLwsgAkEANgIAIAZBAWohAQtBuAEhAwwUCyABIARGBEBB0AEhAwwtCyABLQAAQTBrIgBB/wFxQQpJBEAgAiAAOgAqIAFBAWohAUG2ASEDDBQLIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ0UIAJBzwE2AhwgAiABNgIUIAIgADYCDEEAIQMMLAsgASAERgRAQc4BIQMMLAsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ0VIAJBzQE2AhwgAiABNgIUIAIgADYCDEEAIQMMLAtBtQEhAwwSCyAEIAEiBUYEQEHMASEDDCsLQQAhAEEBIQFBASEGQQAhAwJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAUtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyEDQQAhAUEAIQYMAgtBCSEDQQEhAEEAIQFBACEGDAELQQAhAUEBIQMLIAIgAzoAKyAFQQFqIQMCQAJAIAItAC1BEHENAAJAAkACQCACLQAqDgMBAAIECyAGRQ0DDAILIAANAQwCCyABRQ0BCyACKAIEIQAgAkEANgIEIAIgACADECgiAEUEQCADIQEMAwsgAkHJATYCHCACIAM2AhQgAiAANgIMQQAhAwwtCyACKAIEIQAgAkEANgIEIAIgACADECgiAEUEQCADIQEMGAsgAkHKATYCHCACIAM2AhQgAiAANgIMQQAhAwwsCyACKAIEIQAgAkEANgIEIAIgACAFECgiAEUEQCAFIQEMFgsgAkHLATYCHCACIAU2AhQgAiAANgIMDCsLQbQBIQMMEQtBACEAAkAgAigCOCIDRQ0AIAMoAjwiA0UNACACIAMRAAAhAAsCQCAABEAgAEEVRg0BIAJBADYCHCACIAE2AhQgAkGUDTYCECACQSE2AgxBACEDDCsLQbIBIQMMEQsgAkHIATYCHCACIAE2AhQgAkHJFzYCECACQRU2AgxBACEDDCkLIAJBADYCACAGQQFqIQFB9QAhAwwPCyACLQApQQVGBEBB4wAhAwwPC0HiACEDDA4LIAAhASACQQA2AgALIAJBADoALEEJIQMMDAsgAkEANgIAIAdBAWohAUHAACEDDAsLQQELOgAsIAJBADYCACAGQQFqIQELQSkhAwwIC0E4IQMMBwsCQCABIARHBEADQCABLQAAQYA+ai0AACIAQQFHBEAgAEECRw0DIAFBAWohAQwFCyAEIAFBAWoiAUcNAAtBPiEDDCELQT4hAwwgCwsgAkEAOgAsDAELQQshAwwEC0E6IQMMAwsgAUEBaiEBQS0hAwwCCyACIAE6ACwgAkEANgIAIAZBAWohAUEMIQMMAQsgAkEANgIAIAZBAWohAUEKIQMMAAsAC0EAIQMgAkEANgIcIAIgATYCFCACQc0QNgIQIAJBCTYCDAwXC0EAIQMgAkEANgIcIAIgATYCFCACQekKNgIQIAJBCTYCDAwWC0EAIQMgAkEANgIcIAIgATYCFCACQbcQNgIQIAJBCTYCDAwVC0EAIQMgAkEANgIcIAIgATYCFCACQZwRNgIQIAJBCTYCDAwUC0EAIQMgAkEANgIcIAIgATYCFCACQc0QNgIQIAJBCTYCDAwTC0EAIQMgAkEANgIcIAIgATYCFCACQekKNgIQIAJBCTYCDAwSC0EAIQMgAkEANgIcIAIgATYCFCACQbcQNgIQIAJBCTYCDAwRC0EAIQMgAkEANgIcIAIgATYCFCACQZwRNgIQIAJBCTYCDAwQC0EAIQMgAkEANgIcIAIgATYCFCACQZcVNgIQIAJBDzYCDAwPC0EAIQMgAkEANgIcIAIgATYCFCACQZcVNgIQIAJBDzYCDAwOC0EAIQMgAkEANgIcIAIgATYCFCACQcASNgIQIAJBCzYCDAwNC0EAIQMgAkEANgIcIAIgATYCFCACQZUJNgIQIAJBCzYCDAwMC0EAIQMgAkEANgIcIAIgATYCFCACQeEPNgIQIAJBCjYCDAwLC0EAIQMgAkEANgIcIAIgATYCFCACQfsPNgIQIAJBCjYCDAwKC0EAIQMgAkEANgIcIAIgATYCFCACQfEZNgIQIAJBAjYCDAwJC0EAIQMgAkEANgIcIAIgATYCFCACQcQUNgIQIAJBAjYCDAwIC0EAIQMgAkEANgIcIAIgATYCFCACQfIVNgIQIAJBAjYCDAwHCyACQQI2AhwgAiABNgIUIAJBnBo2AhAgAkEWNgIMQQAhAwwGC0EBIQMMBQtB1AAhAyABIARGDQQgCEEIaiEJIAIoAgAhBQJAAkAgASAERwRAIAVB2MIAaiEHIAQgBWogAWshACAFQX9zQQpqIgUgAWohBgNAIAEtAAAgBy0AAEcEQEECIQcMAwsgBUUEQEEAIQcgBiEBDAMLIAVBAWshBSAHQQFqIQcgBCABQQFqIgFHDQALIAAhBSAEIQELIAlBATYCACACIAU2AgAMAQsgAkEANgIAIAkgBzYCAAsgCSABNgIEIAgoAgwhACAIKAIIDgMBBAIACwALIAJBADYCHCACQbUaNgIQIAJBFzYCDCACIABBAWo2AhRBACEDDAILIAJBADYCHCACIAA2AhQgAkHKGjYCECACQQk2AgxBACEDDAELIAEgBEYEQEEiIQMMAQsgAkEJNgIIIAIgATYCBEEhIQMLIAhBEGokACADRQRAIAIoAgwhAAwBCyACIAM2AhxBACEAIAIoAgQiAUUNACACIAEgBCACKAIIEQEAIgFFDQAgAiAENgIUIAIgATYCDCABIQALIAALvgIBAn8gAEEAOgAAIABB3ABqIgFBAWtBADoAACAAQQA6AAIgAEEAOgABIAFBA2tBADoAACABQQJrQQA6AAAgAEEAOgADIAFBBGtBADoAAEEAIABrQQNxIgEgAGoiAEEANgIAQdwAIAFrQXxxIgIgAGoiAUEEa0EANgIAAkAgAkEJSQ0AIABBADYCCCAAQQA2AgQgAUEIa0EANgIAIAFBDGtBADYCACACQRlJDQAgAEEANgIYIABBADYCFCAAQQA2AhAgAEEANgIMIAFBEGtBADYCACABQRRrQQA2AgAgAUEYa0EANgIAIAFBHGtBADYCACACIABBBHFBGHIiAmsiAUEgSQ0AIAAgAmohAANAIABCADcDGCAAQgA3AxAgAEIANwMIIABCADcDACAAQSBqIQAgAUEgayIBQR9LDQALCwtWAQF/AkAgACgCDA0AAkACQAJAAkAgAC0ALw4DAQADAgsgACgCOCIBRQ0AIAEoAiwiAUUNACAAIAERAAAiAQ0DC0EADwsACyAAQcMWNgIQQQ4hAQsgAQsaACAAKAIMRQRAIABB0Rs2AhAgAEEVNgIMCwsUACAAKAIMQRVGBEAgAEEANgIMCwsUACAAKAIMQRZGBEAgAEEANgIMCwsHACAAKAIMCwcAIAAoAhALCQAgACABNgIQCwcAIAAoAhQLFwAgAEEkTwRAAAsgAEECdEGgM2ooAgALFwAgAEEuTwRAAAsgAEECdEGwNGooAgALvwkBAX9B6yghAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB5ABrDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0HhJw8LQaQhDwtByywPC0H+MQ8LQcAkDwtBqyQPC0GNKA8LQeImDwtBgDAPC0G5Lw8LQdckDwtB7x8PC0HhHw8LQfofDwtB8iAPC0GoLw8LQa4yDwtBiDAPC0HsJw8LQYIiDwtBjh0PC0HQLg8LQcojDwtBxTIPC0HfHA8LQdIcDwtBxCAPC0HXIA8LQaIfDwtB7S4PC0GrMA8LQdQlDwtBzC4PC0H6Lg8LQfwrDwtB0jAPC0HxHQ8LQbsgDwtB9ysPC0GQMQ8LQdcxDwtBoi0PC0HUJw8LQeArDwtBnywPC0HrMQ8LQdUfDwtByjEPC0HeJQ8LQdQeDwtB9BwPC0GnMg8LQbEdDwtBoB0PC0G5MQ8LQbwwDwtBkiEPC0GzJg8LQeksDwtBrB4PC0HUKw8LQfcmDwtBgCYPC0GwIQ8LQf4eDwtBjSMPC0GJLQ8LQfciDwtBoDEPC0GuHw8LQcYlDwtB6B4PC0GTIg8LQcIvDwtBwx0PC0GLLA8LQeEdDwtBjS8PC0HqIQ8LQbQtDwtB0i8PC0HfMg8LQdIyDwtB8DAPC0GpIg8LQfkjDwtBmR4PC0G1LA8LQZswDwtBkjIPC0G2Kw8LQcIiDwtB+DIPC0GeJQ8LQdAiDwtBuh4PC0GBHg8LAAtB1iEhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCz4BAn8CQCAAKAI4IgNFDQAgAygCBCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBxhE2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCCCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9go2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCDCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7Ro2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCECIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlRA2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCFCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBqhs2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCGCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7RM2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCKCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9gg2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCHCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBwhk2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCICIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlBQ2AhBBGCEECyAEC1kBAn8CQCAALQAoQQFGDQAgAC8BMiIBQeQAa0HkAEkNACABQcwBRg0AIAFBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhAiAAQYgEcUGABEYNACAAQShxRSECCyACC4wBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UNACAALwEwIgFBAnFFDQEMAgsgAC8BMCIBQQFxRQ0BC0EBIQIgAC0AKEEBRg0AIAAvATIiAEHkAGtB5ABJDQAgAEHMAUYNACAAQbACRg0AIAFBwABxDQBBACECIAFBiARxQYAERg0AIAFBKHFBAEchAgsgAgtzACAAQRBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAA/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQTBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQSBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQd0BNgIcCwYAIAAQMguaLQELfyMAQRBrIgokAEGk0AAoAgAiCUUEQEHk0wAoAgAiBUUEQEHw0wBCfzcCAEHo0wBCgICEgICAwAA3AgBB5NMAIApBCGpBcHFB2KrVqgVzIgU2AgBB+NMAQQA2AgBByNMAQQA2AgALQczTAEGA1AQ2AgBBnNAAQYDUBDYCAEGw0AAgBTYCAEGs0ABBfzYCAEHQ0wBBgKwDNgIAA0AgAUHI0ABqIAFBvNAAaiICNgIAIAIgAUG00ABqIgM2AgAgAUHA0ABqIAM2AgAgAUHQ0ABqIAFBxNAAaiIDNgIAIAMgAjYCACABQdjQAGogAUHM0ABqIgI2AgAgAiADNgIAIAFB1NAAaiACNgIAIAFBIGoiAUGAAkcNAAtBjNQEQcGrAzYCAEGo0ABB9NMAKAIANgIAQZjQAEHAqwM2AgBBpNAAQYjUBDYCAEHM/wdBODYCAEGI1AQhCQsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAQewBTQRAQYzQACgCACIGQRAgAEETakFwcSAAQQtJGyIEQQN2IgB2IgFBA3EEQAJAIAFBAXEgAHJBAXMiAkEDdCIAQbTQAGoiASAAQbzQAGooAgAiACgCCCIDRgRAQYzQACAGQX4gAndxNgIADAELIAEgAzYCCCADIAE2AgwLIABBCGohASAAIAJBA3QiAkEDcjYCBCAAIAJqIgAgACgCBEEBcjYCBAwRC0GU0AAoAgAiCCAETw0BIAEEQAJAQQIgAHQiAkEAIAJrciABIAB0cWgiAEEDdCICQbTQAGoiASACQbzQAGooAgAiAigCCCIDRgRAQYzQACAGQX4gAHdxIgY2AgAMAQsgASADNgIIIAMgATYCDAsgAiAEQQNyNgIEIABBA3QiACAEayEFIAAgAmogBTYCACACIARqIgQgBUEBcjYCBCAIBEAgCEF4cUG00ABqIQBBoNAAKAIAIQMCf0EBIAhBA3Z0IgEgBnFFBEBBjNAAIAEgBnI2AgAgAAwBCyAAKAIICyIBIAM2AgwgACADNgIIIAMgADYCDCADIAE2AggLIAJBCGohAUGg0AAgBDYCAEGU0AAgBTYCAAwRC0GQ0AAoAgAiC0UNASALaEECdEG80gBqKAIAIgAoAgRBeHEgBGshBSAAIQIDQAJAIAIoAhAiAUUEQCACQRRqKAIAIgFFDQELIAEoAgRBeHEgBGsiAyAFSSECIAMgBSACGyEFIAEgACACGyEAIAEhAgwBCwsgACgCGCEJIAAoAgwiAyAARwRAQZzQACgCABogAyAAKAIIIgE2AgggASADNgIMDBALIABBFGoiAigCACIBRQRAIAAoAhAiAUUNAyAAQRBqIQILA0AgAiEHIAEiA0EUaiICKAIAIgENACADQRBqIQIgAygCECIBDQALIAdBADYCAAwPC0F/IQQgAEG/f0sNACAAQRNqIgFBcHEhBEGQ0AAoAgAiCEUNAEEAIARrIQUCQAJAAkACf0EAIARBgAJJDQAaQR8gBEH///8HSw0AGiAEQSYgAUEIdmciAGt2QQFxIABBAXRrQT5qCyIGQQJ0QbzSAGooAgAiAkUEQEEAIQFBACEDDAELQQAhASAEQRkgBkEBdmtBACAGQR9HG3QhAEEAIQMDQAJAIAIoAgRBeHEgBGsiByAFTw0AIAIhAyAHIgUNAEEAIQUgAiEBDAMLIAEgAkEUaigCACIHIAcgAiAAQR12QQRxakEQaigCACICRhsgASAHGyEBIABBAXQhACACDQALCyABIANyRQRAQQAhA0ECIAZ0IgBBACAAa3IgCHEiAEUNAyAAaEECdEG80gBqKAIAIQELIAFFDQELA0AgASgCBEF4cSAEayICIAVJIQAgAiAFIAAbIQUgASADIAAbIQMgASgCECIABH8gAAUgAUEUaigCAAsiAQ0ACwsgA0UNACAFQZTQACgCACAEa08NACADKAIYIQcgAyADKAIMIgBHBEBBnNAAKAIAGiAAIAMoAggiATYCCCABIAA2AgwMDgsgA0EUaiICKAIAIgFFBEAgAygCECIBRQ0DIANBEGohAgsDQCACIQYgASIAQRRqIgIoAgAiAQ0AIABBEGohAiAAKAIQIgENAAsgBkEANgIADA0LQZTQACgCACIDIARPBEBBoNAAKAIAIQECQCADIARrIgJBEE8EQCABIARqIgAgAkEBcjYCBCABIANqIAI2AgAgASAEQQNyNgIEDAELIAEgA0EDcjYCBCABIANqIgAgACgCBEEBcjYCBEEAIQBBACECC0GU0AAgAjYCAEGg0AAgADYCACABQQhqIQEMDwtBmNAAKAIAIgMgBEsEQCAEIAlqIgAgAyAEayIBQQFyNgIEQaTQACAANgIAQZjQACABNgIAIAkgBEEDcjYCBCAJQQhqIQEMDwtBACEBIAQCf0Hk0wAoAgAEQEHs0wAoAgAMAQtB8NMAQn83AgBB6NMAQoCAhICAgMAANwIAQeTTACAKQQxqQXBxQdiq1aoFczYCAEH40wBBADYCAEHI0wBBADYCAEGAgAQLIgAgBEHHAGoiBWoiBkEAIABrIgdxIgJPBEBB/NMAQTA2AgAMDwsCQEHE0wAoAgAiAUUNAEG80wAoAgAiCCACaiEAIAAgAU0gACAIS3ENAEEAIQFB/NMAQTA2AgAMDwtByNMALQAAQQRxDQQCQAJAIAkEQEHM0wAhAQNAIAEoAgAiACAJTQRAIAAgASgCBGogCUsNAwsgASgCCCIBDQALC0EAEDMiAEF/Rg0FIAIhBkHo0wAoAgAiAUEBayIDIABxBEAgAiAAayAAIANqQQAgAWtxaiEGCyAEIAZPDQUgBkH+////B0sNBUHE0wAoAgAiAwRAQbzTACgCACIHIAZqIQEgASAHTQ0GIAEgA0sNBgsgBhAzIgEgAEcNAQwHCyAGIANrIAdxIgZB/v///wdLDQQgBhAzIQAgACABKAIAIAEoAgRqRg0DIAAhAQsCQCAGIARByABqTw0AIAFBf0YNAEHs0wAoAgAiACAFIAZrakEAIABrcSIAQf7///8HSwRAIAEhAAwHCyAAEDNBf0cEQCAAIAZqIQYgASEADAcLQQAgBmsQMxoMBAsgASIAQX9HDQUMAwtBACEDDAwLQQAhAAwKCyAAQX9HDQILQcjTAEHI0wAoAgBBBHI2AgALIAJB/v///wdLDQEgAhAzIQBBABAzIQEgAEF/Rg0BIAFBf0YNASAAIAFPDQEgASAAayIGIARBOGpNDQELQbzTAEG80wAoAgAgBmoiATYCAEHA0wAoAgAgAUkEQEHA0wAgATYCAAsCQAJAAkBBpNAAKAIAIgIEQEHM0wAhAQNAIAAgASgCACIDIAEoAgQiBWpGDQIgASgCCCIBDQALDAILQZzQACgCACIBQQBHIAAgAU9xRQRAQZzQACAANgIAC0EAIQFB0NMAIAY2AgBBzNMAIAA2AgBBrNAAQX82AgBBsNAAQeTTACgCADYCAEHY0wBBADYCAANAIAFByNAAaiABQbzQAGoiAjYCACACIAFBtNAAaiIDNgIAIAFBwNAAaiADNgIAIAFB0NAAaiABQcTQAGoiAzYCACADIAI2AgAgAUHY0ABqIAFBzNAAaiICNgIAIAIgAzYCACABQdTQAGogAjYCACABQSBqIgFBgAJHDQALQXggAGtBD3EiASAAaiICIAZBOGsiAyABayIBQQFyNgIEQajQAEH00wAoAgA2AgBBmNAAIAE2AgBBpNAAIAI2AgAgACADakE4NgIEDAILIAAgAk0NACACIANJDQAgASgCDEEIcQ0AQXggAmtBD3EiACACaiIDQZjQACgCACAGaiIHIABrIgBBAXI2AgQgASAFIAZqNgIEQajQAEH00wAoAgA2AgBBmNAAIAA2AgBBpNAAIAM2AgAgAiAHakE4NgIEDAELIABBnNAAKAIASQRAQZzQACAANgIACyAAIAZqIQNBzNMAIQECQAJAAkADQCADIAEoAgBHBEAgASgCCCIBDQEMAgsLIAEtAAxBCHFFDQELQczTACEBA0AgASgCACIDIAJNBEAgAyABKAIEaiIFIAJLDQMLIAEoAgghAQwACwALIAEgADYCACABIAEoAgQgBmo2AgQgAEF4IABrQQ9xaiIJIARBA3I2AgQgA0F4IANrQQ9xaiIGIAQgCWoiBGshASACIAZGBEBBpNAAIAQ2AgBBmNAAQZjQACgCACABaiIANgIAIAQgAEEBcjYCBAwIC0Gg0AAoAgAgBkYEQEGg0AAgBDYCAEGU0ABBlNAAKAIAIAFqIgA2AgAgBCAAQQFyNgIEIAAgBGogADYCAAwICyAGKAIEIgVBA3FBAUcNBiAFQXhxIQggBUH/AU0EQCAFQQN2IQMgBigCCCIAIAYoAgwiAkYEQEGM0ABBjNAAKAIAQX4gA3dxNgIADAcLIAIgADYCCCAAIAI2AgwMBgsgBigCGCEHIAYgBigCDCIARwRAIAAgBigCCCICNgIIIAIgADYCDAwFCyAGQRRqIgIoAgAiBUUEQCAGKAIQIgVFDQQgBkEQaiECCwNAIAIhAyAFIgBBFGoiAigCACIFDQAgAEEQaiECIAAoAhAiBQ0ACyADQQA2AgAMBAtBeCAAa0EPcSIBIABqIgcgBkE4ayIDIAFrIgFBAXI2AgQgACADakE4NgIEIAIgBUE3IAVrQQ9xakE/ayIDIAMgAkEQakkbIgNBIzYCBEGo0ABB9NMAKAIANgIAQZjQACABNgIAQaTQACAHNgIAIANBEGpB1NMAKQIANwIAIANBzNMAKQIANwIIQdTTACADQQhqNgIAQdDTACAGNgIAQczTACAANgIAQdjTAEEANgIAIANBJGohAQNAIAFBBzYCACAFIAFBBGoiAUsNAAsgAiADRg0AIAMgAygCBEF+cTYCBCADIAMgAmsiBTYCACACIAVBAXI2AgQgBUH/AU0EQCAFQXhxQbTQAGohAAJ/QYzQACgCACIBQQEgBUEDdnQiA3FFBEBBjNAAIAEgA3I2AgAgAAwBCyAAKAIICyIBIAI2AgwgACACNgIIIAIgADYCDCACIAE2AggMAQtBHyEBIAVB////B00EQCAFQSYgBUEIdmciAGt2QQFxIABBAXRrQT5qIQELIAIgATYCHCACQgA3AhAgAUECdEG80gBqIQBBkNAAKAIAIgNBASABdCIGcUUEQCAAIAI2AgBBkNAAIAMgBnI2AgAgAiAANgIYIAIgAjYCCCACIAI2AgwMAQsgBUEZIAFBAXZrQQAgAUEfRxt0IQEgACgCACEDAkADQCADIgAoAgRBeHEgBUYNASABQR12IQMgAUEBdCEBIAAgA0EEcWpBEGoiBigCACIDDQALIAYgAjYCACACIAA2AhggAiACNgIMIAIgAjYCCAwBCyAAKAIIIgEgAjYCDCAAIAI2AgggAkEANgIYIAIgADYCDCACIAE2AggLQZjQACgCACIBIARNDQBBpNAAKAIAIgAgBGoiAiABIARrIgFBAXI2AgRBmNAAIAE2AgBBpNAAIAI2AgAgACAEQQNyNgIEIABBCGohAQwIC0EAIQFB/NMAQTA2AgAMBwtBACEACyAHRQ0AAkAgBigCHCICQQJ0QbzSAGoiAygCACAGRgRAIAMgADYCACAADQFBkNAAQZDQACgCAEF+IAJ3cTYCAAwCCyAHQRBBFCAHKAIQIAZGG2ogADYCACAARQ0BCyAAIAc2AhggBigCECICBEAgACACNgIQIAIgADYCGAsgBkEUaigCACICRQ0AIABBFGogAjYCACACIAA2AhgLIAEgCGohASAGIAhqIgYoAgQhBQsgBiAFQX5xNgIEIAEgBGogATYCACAEIAFBAXI2AgQgAUH/AU0EQCABQXhxQbTQAGohAAJ/QYzQACgCACICQQEgAUEDdnQiAXFFBEBBjNAAIAEgAnI2AgAgAAwBCyAAKAIICyIBIAQ2AgwgACAENgIIIAQgADYCDCAEIAE2AggMAQtBHyEFIAFB////B00EQCABQSYgAUEIdmciAGt2QQFxIABBAXRrQT5qIQULIAQgBTYCHCAEQgA3AhAgBUECdEG80gBqIQBBkNAAKAIAIgJBASAFdCIDcUUEQCAAIAQ2AgBBkNAAIAIgA3I2AgAgBCAANgIYIAQgBDYCCCAEIAQ2AgwMAQsgAUEZIAVBAXZrQQAgBUEfRxt0IQUgACgCACEAAkADQCAAIgIoAgRBeHEgAUYNASAFQR12IQAgBUEBdCEFIAIgAEEEcWpBEGoiAygCACIADQALIAMgBDYCACAEIAI2AhggBCAENgIMIAQgBDYCCAwBCyACKAIIIgAgBDYCDCACIAQ2AgggBEEANgIYIAQgAjYCDCAEIAA2AggLIAlBCGohAQwCCwJAIAdFDQACQCADKAIcIgFBAnRBvNIAaiICKAIAIANGBEAgAiAANgIAIAANAUGQ0AAgCEF+IAF3cSIINgIADAILIAdBEEEUIAcoAhAgA0YbaiAANgIAIABFDQELIAAgBzYCGCADKAIQIgEEQCAAIAE2AhAgASAANgIYCyADQRRqKAIAIgFFDQAgAEEUaiABNgIAIAEgADYCGAsCQCAFQQ9NBEAgAyAEIAVqIgBBA3I2AgQgACADaiIAIAAoAgRBAXI2AgQMAQsgAyAEaiICIAVBAXI2AgQgAyAEQQNyNgIEIAIgBWogBTYCACAFQf8BTQRAIAVBeHFBtNAAaiEAAn9BjNAAKAIAIgFBASAFQQN2dCIFcUUEQEGM0AAgASAFcjYCACAADAELIAAoAggLIgEgAjYCDCAAIAI2AgggAiAANgIMIAIgATYCCAwBC0EfIQEgBUH///8HTQRAIAVBJiAFQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAQsgAiABNgIcIAJCADcCECABQQJ0QbzSAGohAEEBIAF0IgQgCHFFBEAgACACNgIAQZDQACAEIAhyNgIAIAIgADYCGCACIAI2AgggAiACNgIMDAELIAVBGSABQQF2a0EAIAFBH0cbdCEBIAAoAgAhBAJAA0AgBCIAKAIEQXhxIAVGDQEgAUEddiEEIAFBAXQhASAAIARBBHFqQRBqIgYoAgAiBA0ACyAGIAI2AgAgAiAANgIYIAIgAjYCDCACIAI2AggMAQsgACgCCCIBIAI2AgwgACACNgIIIAJBADYCGCACIAA2AgwgAiABNgIICyADQQhqIQEMAQsCQCAJRQ0AAkAgACgCHCIBQQJ0QbzSAGoiAigCACAARgRAIAIgAzYCACADDQFBkNAAIAtBfiABd3E2AgAMAgsgCUEQQRQgCSgCECAARhtqIAM2AgAgA0UNAQsgAyAJNgIYIAAoAhAiAQRAIAMgATYCECABIAM2AhgLIABBFGooAgAiAUUNACADQRRqIAE2AgAgASADNgIYCwJAIAVBD00EQCAAIAQgBWoiAUEDcjYCBCAAIAFqIgEgASgCBEEBcjYCBAwBCyAAIARqIgcgBUEBcjYCBCAAIARBA3I2AgQgBSAHaiAFNgIAIAgEQCAIQXhxQbTQAGohAUGg0AAoAgAhAwJ/QQEgCEEDdnQiAiAGcUUEQEGM0AAgAiAGcjYCACABDAELIAEoAggLIgIgAzYCDCABIAM2AgggAyABNgIMIAMgAjYCCAtBoNAAIAc2AgBBlNAAIAU2AgALIABBCGohAQsgCkEQaiQAIAELQwAgAEUEQD8AQRB0DwsCQCAAQf//A3ENACAAQQBIDQAgAEEQdkAAIgBBf0YEQEH80wBBMDYCAEF/DwsgAEEQdA8LAAsL3D8iAEGACAsJAQAAAAIAAAADAEGUCAsFBAAAAAUAQaQICwkGAAAABwAAAAgAQdwIC4otSW52YWxpZCBjaGFyIGluIHVybCBxdWVyeQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2JvZHkAQ29udGVudC1MZW5ndGggb3ZlcmZsb3cAQ2h1bmsgc2l6ZSBvdmVyZmxvdwBSZXNwb25zZSBvdmVyZmxvdwBJbnZhbGlkIG1ldGhvZCBmb3IgSFRUUC94LnggcmVxdWVzdABJbnZhbGlkIG1ldGhvZCBmb3IgUlRTUC94LnggcmVxdWVzdABFeHBlY3RlZCBTT1VSQ0UgbWV0aG9kIGZvciBJQ0UveC54IHJlcXVlc3QASW52YWxpZCBjaGFyIGluIHVybCBmcmFnbWVudCBzdGFydABFeHBlY3RlZCBkb3QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9zdGF0dXMASW52YWxpZCByZXNwb25zZSBzdGF0dXMASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucwBVc2VyIGNhbGxiYWNrIGVycm9yAGBvbl9yZXNldGAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2hlYWRlcmAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfYmVnaW5gIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fdmFsdWVgIGNhbGxiYWNrIGVycm9yAGBvbl9zdGF0dXNfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl92ZXJzaW9uX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdXJsX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAEVtcHR5IENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhcmFjdGVyIGluIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZWQgdmFsdWUAUGF1c2VkIGJ5IG9uX2hlYWRlcnNfY29tcGxldGUASW52YWxpZCBFT0Ygc3RhdGUAb25fcmVzZXQgcGF1c2UAb25fY2h1bmtfaGVhZGVyIHBhdXNlAG9uX21lc3NhZ2VfYmVnaW4gcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlIHBhdXNlAG9uX3N0YXR1c19jb21wbGV0ZSBwYXVzZQBvbl92ZXJzaW9uX2NvbXBsZXRlIHBhdXNlAG9uX3VybF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGUgcGF1c2UAb25fbWVzc2FnZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXRob2RfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lIHBhdXNlAFVuZXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgc3RhcnQgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AAU1dJVENIX1BST1hZAFVTRV9QUk9YWQBNS0FDVElWSVRZAFVOUFJPQ0VTU0FCTEVfRU5USVRZAENPUFkATU9WRURfUEVSTUFORU5UTFkAVE9PX0VBUkxZAE5PVElGWQBGQUlMRURfREVQRU5ERU5DWQBCQURfR0FURVdBWQBQTEFZAFBVVABDSEVDS09VVABHQVRFV0FZX1RJTUVPVVQAUkVRVUVTVF9USU1FT1VUAE5FVFdPUktfQ09OTkVDVF9USU1FT1VUAENPTk5FQ1RJT05fVElNRU9VVABMT0dJTl9USU1FT1VUAE5FVFdPUktfUkVBRF9USU1FT1VUAFBPU1QATUlTRElSRUNURURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9MT0FEX0JBTEFOQ0VEX1JFUVVFU1QAQkFEX1JFUVVFU1QASFRUUF9SRVFVRVNUX1NFTlRfVE9fSFRUUFNfUE9SVABSRVBPUlQASU1fQV9URUFQT1QAUkVTRVRfQ09OVEVOVABOT19DT05URU5UAFBBUlRJQUxfQ09OVEVOVABIUEVfSU5WQUxJRF9DT05TVEFOVABIUEVfQ0JfUkVTRVQAR0VUAEhQRV9TVFJJQ1QAQ09ORkxJQ1QAVEVNUE9SQVJZX1JFRElSRUNUAFBFUk1BTkVOVF9SRURJUkVDVABDT05ORUNUAE1VTFRJX1NUQVRVUwBIUEVfSU5WQUxJRF9TVEFUVVMAVE9PX01BTllfUkVRVUVTVFMARUFSTFlfSElOVFMAVU5BVkFJTEFCTEVfRk9SX0xFR0FMX1JFQVNPTlMAT1BUSU9OUwBTV0lUQ0hJTkdfUFJPVE9DT0xTAFZBUklBTlRfQUxTT19ORUdPVElBVEVTAE1VTFRJUExFX0NIT0lDRVMASU5URVJOQUxfU0VSVkVSX0VSUk9SAFdFQl9TRVJWRVJfVU5LTk9XTl9FUlJPUgBSQUlMR1VOX0VSUk9SAElERU5USVRZX1BST1ZJREVSX0FVVEhFTlRJQ0FUSU9OX0VSUk9SAFNTTF9DRVJUSUZJQ0FURV9FUlJPUgBJTlZBTElEX1hfRk9SV0FSREVEX0ZPUgBTRVRfUEFSQU1FVEVSAEdFVF9QQVJBTUVURVIASFBFX1VTRVIAU0VFX09USEVSAEhQRV9DQl9DSFVOS19IRUFERVIATUtDQUxFTkRBUgBTRVRVUABXRUJfU0VSVkVSX0lTX0RPV04AVEVBUkRPV04ASFBFX0NMT1NFRF9DT05ORUNUSU9OAEhFVVJJU1RJQ19FWFBJUkFUSU9OAERJU0NPTk5FQ1RFRF9PUEVSQVRJT04ATk9OX0FVVEhPUklUQVRJVkVfSU5GT1JNQVRJT04ASFBFX0lOVkFMSURfVkVSU0lPTgBIUEVfQ0JfTUVTU0FHRV9CRUdJTgBTSVRFX0lTX0ZST1pFTgBIUEVfSU5WQUxJRF9IRUFERVJfVE9LRU4ASU5WQUxJRF9UT0tFTgBGT1JCSURERU4ARU5IQU5DRV9ZT1VSX0NBTE0ASFBFX0lOVkFMSURfVVJMAEJMT0NLRURfQllfUEFSRU5UQUxfQ09OVFJPTABNS0NPTABBQ0wASFBFX0lOVEVSTkFMAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0VfVU5PRkZJQ0lBTABIUEVfT0sAVU5MSU5LAFVOTE9DSwBQUkkAUkVUUllfV0lUSABIUEVfSU5WQUxJRF9DT05URU5UX0xFTkdUSABIUEVfVU5FWFBFQ1RFRF9DT05URU5UX0xFTkdUSABGTFVTSABQUk9QUEFUQ0gATS1TRUFSQ0gAVVJJX1RPT19MT05HAFBST0NFU1NJTkcATUlTQ0VMTEFORU9VU19QRVJTSVNURU5UX1dBUk5JTkcATUlTQ0VMTEFORU9VU19XQVJOSU5HAEhQRV9JTlZBTElEX1RSQU5TRkVSX0VOQ09ESU5HAEV4cGVjdGVkIENSTEYASFBFX0lOVkFMSURfQ0hVTktfU0laRQBNT1ZFAENPTlRJTlVFAEhQRV9DQl9TVEFUVVNfQ09NUExFVEUASFBFX0NCX0hFQURFUlNfQ09NUExFVEUASFBFX0NCX1ZFUlNJT05fQ09NUExFVEUASFBFX0NCX1VSTF9DT01QTEVURQBIUEVfQ0JfQ0hVTktfQ09NUExFVEUASFBFX0NCX0hFQURFUl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fTkFNRV9DT01QTEVURQBIUEVfQ0JfTUVTU0FHRV9DT01QTEVURQBIUEVfQ0JfTUVUSE9EX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfRklFTERfQ09NUExFVEUAREVMRVRFAEhQRV9JTlZBTElEX0VPRl9TVEFURQBJTlZBTElEX1NTTF9DRVJUSUZJQ0FURQBQQVVTRQBOT19SRVNQT05TRQBVTlNVUFBPUlRFRF9NRURJQV9UWVBFAEdPTkUATk9UX0FDQ0VQVEFCTEUAU0VSVklDRV9VTkFWQUlMQUJMRQBSQU5HRV9OT1RfU0FUSVNGSUFCTEUAT1JJR0lOX0lTX1VOUkVBQ0hBQkxFAFJFU1BPTlNFX0lTX1NUQUxFAFBVUkdFAE1FUkdFAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0UAUkVRVUVTVF9IRUFERVJfVE9PX0xBUkdFAFBBWUxPQURfVE9PX0xBUkdFAElOU1VGRklDSUVOVF9TVE9SQUdFAEhQRV9QQVVTRURfVVBHUkFERQBIUEVfUEFVU0VEX0gyX1VQR1JBREUAU09VUkNFAEFOTk9VTkNFAFRSQUNFAEhQRV9VTkVYUEVDVEVEX1NQQUNFAERFU0NSSUJFAFVOU1VCU0NSSUJFAFJFQ09SRABIUEVfSU5WQUxJRF9NRVRIT0QATk9UX0ZPVU5EAFBST1BGSU5EAFVOQklORABSRUJJTkQAVU5BVVRIT1JJWkVEAE1FVEhPRF9OT1RfQUxMT1dFRABIVFRQX1ZFUlNJT05fTk9UX1NVUFBPUlRFRABBTFJFQURZX1JFUE9SVEVEAEFDQ0VQVEVEAE5PVF9JTVBMRU1FTlRFRABMT09QX0RFVEVDVEVEAEhQRV9DUl9FWFBFQ1RFRABIUEVfTEZfRVhQRUNURUQAQ1JFQVRFRABJTV9VU0VEAEhQRV9QQVVTRUQAVElNRU9VVF9PQ0NVUkVEAFBBWU1FTlRfUkVRVUlSRUQAUFJFQ09ORElUSU9OX1JFUVVJUkVEAFBST1hZX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAE5FVFdPUktfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATEVOR1RIX1JFUVVJUkVEAFNTTF9DRVJUSUZJQ0FURV9SRVFVSVJFRABVUEdSQURFX1JFUVVJUkVEAFBBR0VfRVhQSVJFRABQUkVDT05ESVRJT05fRkFJTEVEAEVYUEVDVEFUSU9OX0ZBSUxFRABSRVZBTElEQVRJT05fRkFJTEVEAFNTTF9IQU5EU0hBS0VfRkFJTEVEAExPQ0tFRABUUkFOU0ZPUk1BVElPTl9BUFBMSUVEAE5PVF9NT0RJRklFRABOT1RfRVhURU5ERUQAQkFORFdJRFRIX0xJTUlUX0VYQ0VFREVEAFNJVEVfSVNfT1ZFUkxPQURFRABIRUFEAEV4cGVjdGVkIEhUVFAvAABeEwAAJhMAADAQAADwFwAAnRMAABUSAAA5FwAA8BIAAAoQAAB1EgAArRIAAIITAABPFAAAfxAAAKAVAAAjFAAAiRIAAIsUAABNFQAA1BEAAM8UAAAQGAAAyRYAANwWAADBEQAA4BcAALsUAAB0FAAAfBUAAOUUAAAIFwAAHxAAAGUVAACjFAAAKBUAAAIVAACZFQAALBAAAIsZAABPDwAA1A4AAGoQAADOEAAAAhcAAIkOAABuEwAAHBMAAGYUAABWFwAAwRMAAM0TAABsEwAAaBcAAGYXAABfFwAAIhMAAM4PAABpDgAA2A4AAGMWAADLEwAAqg4AACgXAAAmFwAAxRMAAF0WAADoEQAAZxMAAGUTAADyFgAAcxMAAB0XAAD5FgAA8xEAAM8OAADOFQAADBIAALMRAAClEQAAYRAAADIXAAC7EwBB+TULAQEAQZA2C+ABAQECAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQf03CwEBAEGROAteAgMCAgICAgAAAgIAAgIAAgICAgICAgICAgAEAAAAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAAIAAgBB/TkLAQEAQZE6C14CAAICAgICAAACAgACAgACAgICAgICAgICAAMABAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAEHwOwsNbG9zZWVlcC1hbGl2ZQBBiTwLAQEAQaA8C+ABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQYk+CwEBAEGgPgvnAQEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZABBsMAAC18BAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQBBkMIACyFlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AQcDCAAstcmFuc2Zlci1lbmNvZGluZ3BncmFkZQ0KDQoNClNNDQoNClRUUC9DRS9UU1AvAEH5wgALBQECAAEDAEGQwwAL4AEEAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB+cQACwUBAgABAwBBkMUAC+ABBAEBBQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQfnGAAsEAQAAAQBBkccAC98BAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB+sgACwQBAAACAEGQyQALXwMEAAAEBAQEBAQEBAQEBAUEBAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAEH6ygALBAEAAAEAQZDLAAsBAQBBqssAC0ECAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB+swACwQBAAABAEGQzQALAQEAQZrNAAsGAgAAAAACAEGxzQALOgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQfDOAAuWAU5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==', 'base64') diff --git a/node_modules/undici/lib/llhttp/utils.js b/node_modules/undici/lib/llhttp/utils.js new file mode 100644 index 0000000000000..8a32e564e7002 --- /dev/null +++ b/node_modules/undici/lib/llhttp/utils.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.enumToMap = void 0; +function enumToMap(obj) { + const res = {}; + Object.keys(obj).forEach((key) => { + const value = obj[key]; + if (typeof value === 'number') { + res[key] = value; + } + }); + return res; +} +exports.enumToMap = enumToMap; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/undici/lib/mock/mock-agent.js b/node_modules/undici/lib/mock/mock-agent.js new file mode 100644 index 0000000000000..c02ee375e2551 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-agent.js @@ -0,0 +1,160 @@ +'use strict' + +const { kClients } = require('../core/symbols') +const Agent = require('../dispatcher/agent') +const { + kAgent, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory +} = require('./mock-symbols') +const MockClient = require('./mock-client') +const MockPool = require('./mock-pool') +const { matchValue, buildMockOptions } = require('./mock-utils') +const { InvalidArgumentError, UndiciError } = require('../core/errors') +const Dispatcher = require('../dispatcher/dispatcher') +const Pluralizer = require('./pluralizer') +const PendingInterceptorsFormatter = require('./pending-interceptors-formatter') + +class MockAgent extends Dispatcher { + constructor (opts) { + super(opts) + + this[kNetConnect] = true + this[kIsMockActive] = true + + // Instantiate Agent and encapsulate + if ((opts?.agent && typeof opts.agent.dispatch !== 'function')) { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + const agent = opts?.agent ? opts.agent : new Agent(opts) + this[kAgent] = agent + + this[kClients] = agent[kClients] + this[kOptions] = buildMockOptions(opts) + } + + get (origin) { + let dispatcher = this[kMockAgentGet](origin) + + if (!dispatcher) { + dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + } + return dispatcher + } + + dispatch (opts, handler) { + // Call MockAgent.get to perform additional setup before dispatching as normal + this.get(opts.origin) + return this[kAgent].dispatch(opts, handler) + } + + async close () { + await this[kAgent].close() + this[kClients].clear() + } + + deactivate () { + this[kIsMockActive] = false + } + + activate () { + this[kIsMockActive] = true + } + + enableNetConnect (matcher) { + if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { + if (Array.isArray(this[kNetConnect])) { + this[kNetConnect].push(matcher) + } else { + this[kNetConnect] = [matcher] + } + } else if (typeof matcher === 'undefined') { + this[kNetConnect] = true + } else { + throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') + } + } + + disableNetConnect () { + this[kNetConnect] = false + } + + // This is required to bypass issues caused by using global symbols - see: + // https://github.com/nodejs/undici/issues/1447 + get isMockActive () { + return this[kIsMockActive] + } + + [kMockAgentSet] (origin, dispatcher) { + this[kClients].set(origin, dispatcher) + } + + [kFactory] (origin) { + const mockOptions = Object.assign({ agent: this }, this[kOptions]) + return this[kOptions] && this[kOptions].connections === 1 + ? new MockClient(origin, mockOptions) + : new MockPool(origin, mockOptions) + } + + [kMockAgentGet] (origin) { + // First check if we can immediately find it + const client = this[kClients].get(origin) + if (client) { + return client + } + + // If the origin is not a string create a dummy parent pool and return to user + if (typeof origin !== 'string') { + const dispatcher = this[kFactory]('http://localhost:9999') + this[kMockAgentSet](origin, dispatcher) + return dispatcher + } + + // If we match, create a pool and assign the same dispatches + for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) { + if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { + const dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] + return dispatcher + } + } + } + + [kGetNetConnect] () { + return this[kNetConnect] + } + + pendingInterceptors () { + const mockAgentClients = this[kClients] + + return Array.from(mockAgentClients.entries()) + .flatMap(([origin, scope]) => scope[kDispatches].map(dispatch => ({ ...dispatch, origin }))) + .filter(({ pending }) => pending) + } + + assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { + const pending = this.pendingInterceptors() + + if (pending.length === 0) { + return + } + + const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) + + throw new UndiciError(` +${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: + +${pendingInterceptorsFormatter.format(pending)} +`.trim()) + } +} + +module.exports = MockAgent diff --git a/node_modules/undici/lib/mock/mock-client.js b/node_modules/undici/lib/mock/mock-client.js new file mode 100644 index 0000000000000..c375dbd455b26 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-client.js @@ -0,0 +1,59 @@ +'use strict' + +const { promisify } = require('node:util') +const Client = require('../dispatcher/client') +const { buildMockDispatch } = require('./mock-utils') +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = require('./mock-symbols') +const { MockInterceptor } = require('./mock-interceptor') +const Symbols = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') + +/** + * MockClient provides an API that extends the Client to influence the mockDispatches. + */ +class MockClient extends Client { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockClient diff --git a/node_modules/undici/lib/mock/mock-errors.js b/node_modules/undici/lib/mock/mock-errors.js new file mode 100644 index 0000000000000..3de5603c8a90e --- /dev/null +++ b/node_modules/undici/lib/mock/mock-errors.js @@ -0,0 +1,28 @@ +'use strict' + +const { UndiciError } = require('../core/errors') + +const kMockNotMatchedError = Symbol.for('undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED') + +/** + * The request does not match any registered mock dispatches. + */ +class MockNotMatchedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, MockNotMatchedError) + this.name = 'MockNotMatchedError' + this.message = message || 'The request does not match any registered mock dispatches' + this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kMockNotMatchedError] === true + } + + [kMockNotMatchedError] = true +} + +module.exports = { + MockNotMatchedError +} diff --git a/node_modules/undici/lib/mock/mock-interceptor.js b/node_modules/undici/lib/mock/mock-interceptor.js new file mode 100644 index 0000000000000..c6b16b35f9c37 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-interceptor.js @@ -0,0 +1,207 @@ +'use strict' + +const { getResponseData, buildKey, addMockDispatch } = require('./mock-utils') +const { + kDispatches, + kDispatchKey, + kDefaultHeaders, + kDefaultTrailers, + kContentLength, + kMockDispatch +} = require('./mock-symbols') +const { InvalidArgumentError } = require('../core/errors') +const { buildURL } = require('../core/util') + +/** + * Defines the scope API for an interceptor reply + */ +class MockScope { + constructor (mockDispatch) { + this[kMockDispatch] = mockDispatch + } + + /** + * Delay a reply by a set amount in ms. + */ + delay (waitInMs) { + if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { + throw new InvalidArgumentError('waitInMs must be a valid integer > 0') + } + + this[kMockDispatch].delay = waitInMs + return this + } + + /** + * For a defined reply, never mark as consumed. + */ + persist () { + this[kMockDispatch].persist = true + return this + } + + /** + * Allow one to define a reply for a set amount of matching requests. + */ + times (repeatTimes) { + if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { + throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') + } + + this[kMockDispatch].times = repeatTimes + return this + } +} + +/** + * Defines an interceptor for a Mock + */ +class MockInterceptor { + constructor (opts, mockDispatches) { + if (typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object') + } + if (typeof opts.path === 'undefined') { + throw new InvalidArgumentError('opts.path must be defined') + } + if (typeof opts.method === 'undefined') { + opts.method = 'GET' + } + // See https://github.com/nodejs/undici/issues/1245 + // As per RFC 3986, clients are not supposed to send URI + // fragments to servers when they retrieve a document, + if (typeof opts.path === 'string') { + if (opts.query) { + opts.path = buildURL(opts.path, opts.query) + } else { + // Matches https://github.com/nodejs/undici/blob/main/lib/web/fetch/index.js#L1811 + const parsedURL = new URL(opts.path, 'data://') + opts.path = parsedURL.pathname + parsedURL.search + } + } + if (typeof opts.method === 'string') { + opts.method = opts.method.toUpperCase() + } + + this[kDispatchKey] = buildKey(opts) + this[kDispatches] = mockDispatches + this[kDefaultHeaders] = {} + this[kDefaultTrailers] = {} + this[kContentLength] = false + } + + createMockScopeDispatchData ({ statusCode, data, responseOptions }) { + const responseData = getResponseData(data) + const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} + const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } + const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } + + return { statusCode, data, headers, trailers } + } + + validateReplyParameters (replyParameters) { + if (typeof replyParameters.statusCode === 'undefined') { + throw new InvalidArgumentError('statusCode must be defined') + } + if (typeof replyParameters.responseOptions !== 'object' || replyParameters.responseOptions === null) { + throw new InvalidArgumentError('responseOptions must be an object') + } + } + + /** + * Mock an undici request with a defined reply. + */ + reply (replyOptionsCallbackOrStatusCode) { + // Values of reply aren't available right now as they + // can only be available when the reply callback is invoked. + if (typeof replyOptionsCallbackOrStatusCode === 'function') { + // We'll first wrap the provided callback in another function, + // this function will properly resolve the data from the callback + // when invoked. + const wrappedDefaultsCallback = (opts) => { + // Our reply options callback contains the parameter for statusCode, data and options. + const resolvedData = replyOptionsCallbackOrStatusCode(opts) + + // Check if it is in the right format + if (typeof resolvedData !== 'object' || resolvedData === null) { + throw new InvalidArgumentError('reply options callback must return an object') + } + + const replyParameters = { data: '', responseOptions: {}, ...resolvedData } + this.validateReplyParameters(replyParameters) + // Since the values can be obtained immediately we return them + // from this higher order function that will be resolved later. + return { + ...this.createMockScopeDispatchData(replyParameters) + } + } + + // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) + return new MockScope(newMockDispatch) + } + + // We can have either one or three parameters, if we get here, + // we should have 1-3 parameters. So we spread the arguments of + // this function to obtain the parameters, since replyData will always + // just be the statusCode. + const replyParameters = { + statusCode: replyOptionsCallbackOrStatusCode, + data: arguments[1] === undefined ? '' : arguments[1], + responseOptions: arguments[2] === undefined ? {} : arguments[2] + } + this.validateReplyParameters(replyParameters) + + // Send in-already provided data like usual + const dispatchData = this.createMockScopeDispatchData(replyParameters) + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) + return new MockScope(newMockDispatch) + } + + /** + * Mock an undici request with a defined error. + */ + replyWithError (error) { + if (typeof error === 'undefined') { + throw new InvalidArgumentError('error must be defined') + } + + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) + return new MockScope(newMockDispatch) + } + + /** + * Set default reply headers on the interceptor for subsequent replies + */ + defaultReplyHeaders (headers) { + if (typeof headers === 'undefined') { + throw new InvalidArgumentError('headers must be defined') + } + + this[kDefaultHeaders] = headers + return this + } + + /** + * Set default reply trailers on the interceptor for subsequent replies + */ + defaultReplyTrailers (trailers) { + if (typeof trailers === 'undefined') { + throw new InvalidArgumentError('trailers must be defined') + } + + this[kDefaultTrailers] = trailers + return this + } + + /** + * Set reply content length header for replies on the interceptor + */ + replyContentLength () { + this[kContentLength] = true + return this + } +} + +module.exports.MockInterceptor = MockInterceptor +module.exports.MockScope = MockScope diff --git a/node_modules/undici/lib/mock/mock-pool.js b/node_modules/undici/lib/mock/mock-pool.js new file mode 100644 index 0000000000000..8b005d72ead3f --- /dev/null +++ b/node_modules/undici/lib/mock/mock-pool.js @@ -0,0 +1,59 @@ +'use strict' + +const { promisify } = require('node:util') +const Pool = require('../dispatcher/pool') +const { buildMockDispatch } = require('./mock-utils') +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = require('./mock-symbols') +const { MockInterceptor } = require('./mock-interceptor') +const Symbols = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') + +/** + * MockPool provides an API that extends the Pool to influence the mockDispatches. + */ +class MockPool extends Pool { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockPool diff --git a/node_modules/undici/lib/mock/mock-symbols.js b/node_modules/undici/lib/mock/mock-symbols.js new file mode 100644 index 0000000000000..8c4cbb60e16c4 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-symbols.js @@ -0,0 +1,23 @@ +'use strict' + +module.exports = { + kAgent: Symbol('agent'), + kOptions: Symbol('options'), + kFactory: Symbol('factory'), + kDispatches: Symbol('dispatches'), + kDispatchKey: Symbol('dispatch key'), + kDefaultHeaders: Symbol('default headers'), + kDefaultTrailers: Symbol('default trailers'), + kContentLength: Symbol('content length'), + kMockAgent: Symbol('mock agent'), + kMockAgentSet: Symbol('mock agent set'), + kMockAgentGet: Symbol('mock agent get'), + kMockDispatch: Symbol('mock dispatch'), + kClose: Symbol('close'), + kOriginalClose: Symbol('original agent close'), + kOrigin: Symbol('origin'), + kIsMockActive: Symbol('is mock active'), + kNetConnect: Symbol('net connect'), + kGetNetConnect: Symbol('get net connect'), + kConnected: Symbol('connected') +} diff --git a/node_modules/undici/lib/mock/mock-utils.js b/node_modules/undici/lib/mock/mock-utils.js new file mode 100644 index 0000000000000..8f18db31ee210 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-utils.js @@ -0,0 +1,367 @@ +'use strict' + +const { MockNotMatchedError } = require('./mock-errors') +const { + kDispatches, + kMockAgent, + kOriginalDispatch, + kOrigin, + kGetNetConnect +} = require('./mock-symbols') +const { buildURL } = require('../core/util') +const { STATUS_CODES } = require('node:http') +const { + types: { + isPromise + } +} = require('node:util') + +function matchValue (match, value) { + if (typeof match === 'string') { + return match === value + } + if (match instanceof RegExp) { + return match.test(value) + } + if (typeof match === 'function') { + return match(value) === true + } + return false +} + +function lowerCaseEntries (headers) { + return Object.fromEntries( + Object.entries(headers).map(([headerName, headerValue]) => { + return [headerName.toLocaleLowerCase(), headerValue] + }) + ) +} + +/** + * @param {import('../../index').Headers|string[]|Record} headers + * @param {string} key + */ +function getHeaderByName (headers, key) { + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { + return headers[i + 1] + } + } + + return undefined + } else if (typeof headers.get === 'function') { + return headers.get(key) + } else { + return lowerCaseEntries(headers)[key.toLocaleLowerCase()] + } +} + +/** @param {string[]} headers */ +function buildHeadersFromArray (headers) { // fetch HeadersList + const clone = headers.slice() + const entries = [] + for (let index = 0; index < clone.length; index += 2) { + entries.push([clone[index], clone[index + 1]]) + } + return Object.fromEntries(entries) +} + +function matchHeaders (mockDispatch, headers) { + if (typeof mockDispatch.headers === 'function') { + if (Array.isArray(headers)) { // fetch HeadersList + headers = buildHeadersFromArray(headers) + } + return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) + } + if (typeof mockDispatch.headers === 'undefined') { + return true + } + if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { + return false + } + + for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { + const headerValue = getHeaderByName(headers, matchHeaderName) + + if (!matchValue(matchHeaderValue, headerValue)) { + return false + } + } + return true +} + +function safeUrl (path) { + if (typeof path !== 'string') { + return path + } + + const pathSegments = path.split('?') + + if (pathSegments.length !== 2) { + return path + } + + const qp = new URLSearchParams(pathSegments.pop()) + qp.sort() + return [...pathSegments, qp.toString()].join('?') +} + +function matchKey (mockDispatch, { path, method, body, headers }) { + const pathMatch = matchValue(mockDispatch.path, path) + const methodMatch = matchValue(mockDispatch.method, method) + const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true + const headersMatch = matchHeaders(mockDispatch, headers) + return pathMatch && methodMatch && bodyMatch && headersMatch +} + +function getResponseData (data) { + if (Buffer.isBuffer(data)) { + return data + } else if (data instanceof Uint8Array) { + return data + } else if (data instanceof ArrayBuffer) { + return data + } else if (typeof data === 'object') { + return JSON.stringify(data) + } else { + return data.toString() + } +} + +function getMockDispatch (mockDispatches, key) { + const basePath = key.query ? buildURL(key.path, key.query) : key.path + const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath + + // Match path + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) + } + + // Match method + matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`) + } + + // Match body + matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`) + } + + // Match headers + matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) + if (matchedMockDispatches.length === 0) { + const headers = typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers + throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`) + } + + return matchedMockDispatches[0] +} + +function addMockDispatch (mockDispatches, key, data) { + const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } + const replyData = typeof data === 'function' ? { callback: data } : { ...data } + const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } + mockDispatches.push(newMockDispatch) + return newMockDispatch +} + +function deleteMockDispatch (mockDispatches, key) { + const index = mockDispatches.findIndex(dispatch => { + if (!dispatch.consumed) { + return false + } + return matchKey(dispatch, key) + }) + if (index !== -1) { + mockDispatches.splice(index, 1) + } +} + +function buildKey (opts) { + const { path, method, body, headers, query } = opts + return { + path, + method, + body, + headers, + query + } +} + +function generateKeyValues (data) { + const keys = Object.keys(data) + const result = [] + for (let i = 0; i < keys.length; ++i) { + const key = keys[i] + const value = data[key] + const name = Buffer.from(`${key}`) + if (Array.isArray(value)) { + for (let j = 0; j < value.length; ++j) { + result.push(name, Buffer.from(`${value[j]}`)) + } + } else { + result.push(name, Buffer.from(`${value}`)) + } + } + return result +} + +/** + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + * @param {number} statusCode + */ +function getStatusText (statusCode) { + return STATUS_CODES[statusCode] || 'unknown' +} + +async function getResponse (body) { + const buffers = [] + for await (const data of body) { + buffers.push(data) + } + return Buffer.concat(buffers).toString('utf8') +} + +/** + * Mock dispatch function used to simulate undici dispatches + */ +function mockDispatch (opts, handler) { + // Get mock dispatch from built key + const key = buildKey(opts) + const mockDispatch = getMockDispatch(this[kDispatches], key) + + mockDispatch.timesInvoked++ + + // Here's where we resolve a callback if a callback is present for the dispatch data. + if (mockDispatch.data.callback) { + mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } + } + + // Parse mockDispatch data + const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch + const { timesInvoked, times } = mockDispatch + + // If it's used up and not persistent, mark as consumed + mockDispatch.consumed = !persist && timesInvoked >= times + mockDispatch.pending = timesInvoked < times + + // If specified, trigger dispatch error + if (error !== null) { + deleteMockDispatch(this[kDispatches], key) + handler.onError(error) + return true + } + + // Handle the request with a delay if necessary + if (typeof delay === 'number' && delay > 0) { + setTimeout(() => { + handleReply(this[kDispatches]) + }, delay) + } else { + handleReply(this[kDispatches]) + } + + function handleReply (mockDispatches, _data = data) { + // fetch's HeadersList is a 1D string array + const optsHeaders = Array.isArray(opts.headers) + ? buildHeadersFromArray(opts.headers) + : opts.headers + const body = typeof _data === 'function' + ? _data({ ...opts, headers: optsHeaders }) + : _data + + // util.types.isPromise is likely needed for jest. + if (isPromise(body)) { + // If handleReply is asynchronous, throwing an error + // in the callback will reject the promise, rather than + // synchronously throw the error, which breaks some tests. + // Rather, we wait for the callback to resolve if it is a + // promise, and then re-run handleReply with the new body. + body.then((newData) => handleReply(mockDispatches, newData)) + return + } + + const responseData = getResponseData(body) + const responseHeaders = generateKeyValues(headers) + const responseTrailers = generateKeyValues(trailers) + + handler.onConnect?.(err => handler.onError(err), null) + handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode)) + handler.onData?.(Buffer.from(responseData)) + handler.onComplete?.(responseTrailers) + deleteMockDispatch(mockDispatches, key) + } + + function resume () {} + + return true +} + +function buildMockDispatch () { + const agent = this[kMockAgent] + const origin = this[kOrigin] + const originalDispatch = this[kOriginalDispatch] + + return function dispatch (opts, handler) { + if (agent.isMockActive) { + try { + mockDispatch.call(this, opts, handler) + } catch (error) { + if (error instanceof MockNotMatchedError) { + const netConnect = agent[kGetNetConnect]() + if (netConnect === false) { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) + } + if (checkNetConnect(netConnect, origin)) { + originalDispatch.call(this, opts, handler) + } else { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) + } + } else { + throw error + } + } + } else { + originalDispatch.call(this, opts, handler) + } + } +} + +function checkNetConnect (netConnect, origin) { + const url = new URL(origin) + if (netConnect === true) { + return true + } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { + return true + } + return false +} + +function buildMockOptions (opts) { + if (opts) { + const { agent, ...mockOptions } = opts + return mockOptions + } +} + +module.exports = { + getResponseData, + getMockDispatch, + addMockDispatch, + deleteMockDispatch, + buildKey, + generateKeyValues, + matchValue, + getResponse, + getStatusText, + mockDispatch, + buildMockDispatch, + checkNetConnect, + buildMockOptions, + getHeaderByName, + buildHeadersFromArray +} diff --git a/node_modules/undici/lib/mock/pending-interceptors-formatter.js b/node_modules/undici/lib/mock/pending-interceptors-formatter.js new file mode 100644 index 0000000000000..ccca951195aa6 --- /dev/null +++ b/node_modules/undici/lib/mock/pending-interceptors-formatter.js @@ -0,0 +1,43 @@ +'use strict' + +const { Transform } = require('node:stream') +const { Console } = require('node:console') + +const PERSISTENT = process.versions.icu ? '✅' : 'Y ' +const NOT_PERSISTENT = process.versions.icu ? '❌' : 'N ' + +/** + * Gets the output of `console.table(…)` as a string. + */ +module.exports = class PendingInterceptorsFormatter { + constructor ({ disableColors } = {}) { + this.transform = new Transform({ + transform (chunk, _enc, cb) { + cb(null, chunk) + } + }) + + this.logger = new Console({ + stdout: this.transform, + inspectOptions: { + colors: !disableColors && !process.env.CI + } + }) + } + + format (pendingInterceptors) { + const withPrettyHeaders = pendingInterceptors.map( + ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + Method: method, + Origin: origin, + Path: path, + 'Status code': statusCode, + Persistent: persist ? PERSISTENT : NOT_PERSISTENT, + Invocations: timesInvoked, + Remaining: persist ? Infinity : times - timesInvoked + })) + + this.logger.table(withPrettyHeaders) + return this.transform.read().toString() + } +} diff --git a/node_modules/undici/lib/mock/pluralizer.js b/node_modules/undici/lib/mock/pluralizer.js new file mode 100644 index 0000000000000..47f150bc27a80 --- /dev/null +++ b/node_modules/undici/lib/mock/pluralizer.js @@ -0,0 +1,29 @@ +'use strict' + +const singulars = { + pronoun: 'it', + is: 'is', + was: 'was', + this: 'this' +} + +const plurals = { + pronoun: 'they', + is: 'are', + was: 'were', + this: 'these' +} + +module.exports = class Pluralizer { + constructor (singular, plural) { + this.singular = singular + this.plural = plural + } + + pluralize (count) { + const one = count === 1 + const keys = one ? singulars : plurals + const noun = one ? this.singular : this.plural + return { ...keys, count, noun } + } +} diff --git a/node_modules/undici/lib/util/timers.js b/node_modules/undici/lib/util/timers.js new file mode 100644 index 0000000000000..c15bbc37aa158 --- /dev/null +++ b/node_modules/undici/lib/util/timers.js @@ -0,0 +1,423 @@ +'use strict' + +/** + * This module offers an optimized timer implementation designed for scenarios + * where high precision is not critical. + * + * The timer achieves faster performance by using a low-resolution approach, + * with an accuracy target of within 500ms. This makes it particularly useful + * for timers with delays of 1 second or more, where exact timing is less + * crucial. + * + * It's important to note that Node.js timers are inherently imprecise, as + * delays can occur due to the event loop being blocked by other operations. + * Consequently, timers may trigger later than their scheduled time. + */ + +/** + * The fastNow variable contains the internal fast timer clock value. + * + * @type {number} + */ +let fastNow = 0 + +/** + * RESOLUTION_MS represents the target resolution time in milliseconds. + * + * @type {number} + * @default 1000 + */ +const RESOLUTION_MS = 1e3 + +/** + * TICK_MS defines the desired interval in milliseconds between each tick. + * The target value is set to half the resolution time, minus 1 ms, to account + * for potential event loop overhead. + * + * @type {number} + * @default 499 + */ +const TICK_MS = (RESOLUTION_MS >> 1) - 1 + +/** + * fastNowTimeout is a Node.js timer used to manage and process + * the FastTimers stored in the `fastTimers` array. + * + * @type {NodeJS.Timeout} + */ +let fastNowTimeout + +/** + * The kFastTimer symbol is used to identify FastTimer instances. + * + * @type {Symbol} + */ +const kFastTimer = Symbol('kFastTimer') + +/** + * The fastTimers array contains all active FastTimers. + * + * @type {FastTimer[]} + */ +const fastTimers = [] + +/** + * These constants represent the various states of a FastTimer. + */ + +/** + * The `NOT_IN_LIST` constant indicates that the FastTimer is not included + * in the `fastTimers` array. Timers with this status will not be processed + * during the next tick by the `onTick` function. + * + * A FastTimer can be re-added to the `fastTimers` array by invoking the + * `refresh` method on the FastTimer instance. + * + * @type {-2} + */ +const NOT_IN_LIST = -2 + +/** + * The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled + * for removal from the `fastTimers` array. A FastTimer in this state will + * be removed in the next tick by the `onTick` function and will no longer + * be processed. + * + * This status is also set when the `clear` method is called on the FastTimer instance. + * + * @type {-1} + */ +const TO_BE_CLEARED = -1 + +/** + * The `PENDING` constant signifies that the FastTimer is awaiting processing + * in the next tick by the `onTick` function. Timers with this status will have + * their `_idleStart` value set and their status updated to `ACTIVE` in the next tick. + * + * @type {0} + */ +const PENDING = 0 + +/** + * The `ACTIVE` constant indicates that the FastTimer is active and waiting + * for its timer to expire. During the next tick, the `onTick` function will + * check if the timer has expired, and if so, it will execute the associated callback. + * + * @type {1} + */ +const ACTIVE = 1 + +/** + * The onTick function processes the fastTimers array. + * + * @returns {void} + */ +function onTick () { + /** + * Increment the fastNow value by the TICK_MS value, despite the actual time + * that has passed since the last tick. This approach ensures independence + * from the system clock and delays caused by a blocked event loop. + * + * @type {number} + */ + fastNow += TICK_MS + + /** + * The `idx` variable is used to iterate over the `fastTimers` array. + * Expired timers are removed by replacing them with the last element in the array. + * Consequently, `idx` is only incremented when the current element is not removed. + * + * @type {number} + */ + let idx = 0 + + /** + * The len variable will contain the length of the fastTimers array + * and will be decremented when a FastTimer should be removed from the + * fastTimers array. + * + * @type {number} + */ + let len = fastTimers.length + + while (idx < len) { + /** + * @type {FastTimer} + */ + const timer = fastTimers[idx] + + // If the timer is in the ACTIVE state and the timer has expired, it will + // be processed in the next tick. + if (timer._state === PENDING) { + // Set the _idleStart value to the fastNow value minus the TICK_MS value + // to account for the time the timer was in the PENDING state. + timer._idleStart = fastNow - TICK_MS + timer._state = ACTIVE + } else if ( + timer._state === ACTIVE && + fastNow >= timer._idleStart + timer._idleTimeout + ) { + timer._state = TO_BE_CLEARED + timer._idleStart = -1 + timer._onTimeout(timer._timerArg) + } + + if (timer._state === TO_BE_CLEARED) { + timer._state = NOT_IN_LIST + + // Move the last element to the current index and decrement len if it is + // not the only element in the array. + if (--len !== 0) { + fastTimers[idx] = fastTimers[len] + } + } else { + ++idx + } + } + + // Set the length of the fastTimers array to the new length and thus + // removing the excess FastTimers elements from the array. + fastTimers.length = len + + // If there are still active FastTimers in the array, refresh the Timer. + // If there are no active FastTimers, the timer will be refreshed again + // when a new FastTimer is instantiated. + if (fastTimers.length !== 0) { + refreshTimeout() + } +} + +function refreshTimeout () { + // If the fastNowTimeout is already set, refresh it. + if (fastNowTimeout) { + fastNowTimeout.refresh() + // fastNowTimeout is not instantiated yet, create a new Timer. + } else { + clearTimeout(fastNowTimeout) + fastNowTimeout = setTimeout(onTick, TICK_MS) + + // If the Timer has an unref method, call it to allow the process to exit if + // there are no other active handles. + if (fastNowTimeout.unref) { + fastNowTimeout.unref() + } + } +} + +/** + * The `FastTimer` class is a data structure designed to store and manage + * timer information. + */ +class FastTimer { + [kFastTimer] = true + + /** + * The state of the timer, which can be one of the following: + * - NOT_IN_LIST (-2) + * - TO_BE_CLEARED (-1) + * - PENDING (0) + * - ACTIVE (1) + * + * @type {-2|-1|0|1} + * @private + */ + _state = NOT_IN_LIST + + /** + * The number of milliseconds to wait before calling the callback. + * + * @type {number} + * @private + */ + _idleTimeout = -1 + + /** + * The time in milliseconds when the timer was started. This value is used to + * calculate when the timer should expire. + * + * @type {number} + * @default -1 + * @private + */ + _idleStart = -1 + + /** + * The function to be executed when the timer expires. + * @type {Function} + * @private + */ + _onTimeout + + /** + * The argument to be passed to the callback when the timer expires. + * + * @type {*} + * @private + */ + _timerArg + + /** + * @constructor + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should wait + * before the specified function or code is executed. + * @param {*} arg + */ + constructor (callback, delay, arg) { + this._onTimeout = callback + this._idleTimeout = delay + this._timerArg = arg + + this.refresh() + } + + /** + * Sets the timer's start time to the current time, and reschedules the timer + * to call its callback at the previously specified duration adjusted to the + * current time. + * Using this on a timer that has already called its callback will reactivate + * the timer. + * + * @returns {void} + */ + refresh () { + // In the special case that the timer is not in the list of active timers, + // add it back to the array to be processed in the next tick by the onTick + // function. + if (this._state === NOT_IN_LIST) { + fastTimers.push(this) + } + + // If the timer is the only active timer, refresh the fastNowTimeout for + // better resolution. + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout() + } + + // Setting the state to PENDING will cause the timer to be reset in the + // next tick by the onTick function. + this._state = PENDING + } + + /** + * The `clear` method cancels the timer, preventing it from executing. + * + * @returns {void} + * @private + */ + clear () { + // Set the state to TO_BE_CLEARED to mark the timer for removal in the next + // tick by the onTick function. + this._state = TO_BE_CLEARED + + // Reset the _idleStart value to -1 to indicate that the timer is no longer + // active. + this._idleStart = -1 + } +} + +/** + * This module exports a setTimeout and clearTimeout function that can be + * used as a drop-in replacement for the native functions. + */ +module.exports = { + /** + * The setTimeout() method sets a timer which executes a function once the + * timer expires. + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should + * wait before the specified function or code is executed. + * @param {*} [arg] An optional argument to be passed to the callback function + * when the timer expires. + * @returns {NodeJS.Timeout|FastTimer} + */ + setTimeout (callback, delay, arg) { + // If the delay is less than or equal to the RESOLUTION_MS value return a + // native Node.js Timer instance. + return delay <= RESOLUTION_MS + ? setTimeout(callback, delay, arg) + : new FastTimer(callback, delay, arg) + }, + /** + * The clearTimeout method cancels an instantiated Timer previously created + * by calling setTimeout. + * + * @param {NodeJS.Timeout|FastTimer} timeout + */ + clearTimeout (timeout) { + // If the timeout is a FastTimer, call its own clear method. + if (timeout[kFastTimer]) { + /** + * @type {FastTimer} + */ + timeout.clear() + // Otherwise it is an instance of a native NodeJS.Timeout, so call the + // Node.js native clearTimeout function. + } else { + clearTimeout(timeout) + } + }, + /** + * The setFastTimeout() method sets a fastTimer which executes a function once + * the timer expires. + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should + * wait before the specified function or code is executed. + * @param {*} [arg] An optional argument to be passed to the callback function + * when the timer expires. + * @returns {FastTimer} + */ + setFastTimeout (callback, delay, arg) { + return new FastTimer(callback, delay, arg) + }, + /** + * The clearTimeout method cancels an instantiated FastTimer previously + * created by calling setFastTimeout. + * + * @param {FastTimer} timeout + */ + clearFastTimeout (timeout) { + timeout.clear() + }, + /** + * The now method returns the value of the internal fast timer clock. + * + * @returns {number} + */ + now () { + return fastNow + }, + /** + * Trigger the onTick function to process the fastTimers array. + * Exported for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + * @param {number} [delay=0] The delay in milliseconds to add to the now value. + */ + tick (delay = 0) { + fastNow += delay - RESOLUTION_MS + 1 + onTick() + onTick() + }, + /** + * Reset FastTimers. + * Exported for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + */ + reset () { + fastNow = 0 + fastTimers.length = 0 + clearTimeout(fastNowTimeout) + fastNowTimeout = null + }, + /** + * Exporting for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + */ + kFastTimer +} diff --git a/node_modules/undici/lib/web/cache/cache.js b/node_modules/undici/lib/web/cache/cache.js new file mode 100644 index 0000000000000..1c1a591124277 --- /dev/null +++ b/node_modules/undici/lib/web/cache/cache.js @@ -0,0 +1,859 @@ +'use strict' + +const { kConstruct } = require('./symbols') +const { urlEquals, getFieldValues } = require('./util') +const { kEnumerableProperty, isDisturbed } = require('../../core/util') +const { webidl } = require('../fetch/webidl') +const { Response, cloneResponse, fromInnerResponse } = require('../fetch/response') +const { Request, fromInnerRequest } = require('../fetch/request') +const { kState } = require('../fetch/symbols') +const { fetching } = require('../fetch/index') +const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require('../fetch/util') +const assert = require('node:assert') + +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation + * @typedef {Object} CacheBatchOperation + * @property {'delete' | 'put'} type + * @property {any} request + * @property {any} response + * @property {import('../../types/cache').CacheQueryOptions} options + */ + +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ + +class Cache { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} + */ + #relevantRequestResponseList + + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor() + } + + webidl.util.markAsUncloneable(this) + this.#relevantRequestResponseList = arguments[1] + } + + async match (request, options = {}) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.match' + webidl.argumentLengthCheck(arguments, 1, prefix) + + request = webidl.converters.RequestInfo(request, prefix, 'request') + options = webidl.converters.CacheQueryOptions(options, prefix, 'options') + + const p = this.#internalMatchAll(request, options, 1) + + if (p.length === 0) { + return + } + + return p[0] + } + + async matchAll (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.matchAll' + if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request') + options = webidl.converters.CacheQueryOptions(options, prefix, 'options') + + return this.#internalMatchAll(request, options) + } + + async add (request) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.add' + webidl.argumentLengthCheck(arguments, 1, prefix) + + request = webidl.converters.RequestInfo(request, prefix, 'request') + + // 1. + const requests = [request] + + // 2. + const responseArrayPromise = this.addAll(requests) + + // 3. + return await responseArrayPromise + } + + async addAll (requests) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.addAll' + webidl.argumentLengthCheck(arguments, 1, prefix) + + // 1. + const responsePromises = [] + + // 2. + const requestList = [] + + // 3. + for (let request of requests) { + if (request === undefined) { + throw webidl.errors.conversionFailed({ + prefix, + argument: 'Argument 1', + types: ['undefined is not allowed'] + }) + } + + request = webidl.converters.RequestInfo(request) + + if (typeof request === 'string') { + continue + } + + // 3.1 + const r = request[kState] + + // 3.2 + if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { + throw webidl.errors.exception({ + header: prefix, + message: 'Expected http/s scheme when method is not GET.' + }) + } + } + + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = [] + + // 5. + for (const request of requests) { + // 5.1 + const r = new Request(request)[kState] + + // 5.2 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: prefix, + message: 'Expected http/s scheme.' + }) + } + + // 5.4 + r.initiator = 'fetch' + r.destination = 'subresource' + + // 5.5 + requestList.push(r) + + // 5.6 + const responsePromise = createDeferredPromise() + + // 5.7 + fetchControllers.push(fetching({ + request: r, + processResponse (response) { + // 1. + if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Received an invalid status code or the request failed.' + })) + } else if (response.headersList.contains('vary')) { // 2. + // 2.1 + const fieldValues = getFieldValues(response.headersList.get('vary')) + + // 2.2 + for (const fieldValue of fieldValues) { + // 2.2.1 + if (fieldValue === '*') { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'invalid vary field value' + })) + + for (const controller of fetchControllers) { + controller.abort() + } + + return + } + } + } + }, + processResponseEndOfBody (response) { + // 1. + if (response.aborted) { + responsePromise.reject(new DOMException('aborted', 'AbortError')) + return + } + + // 2. + responsePromise.resolve(response) + } + })) + + // 5.8 + responsePromises.push(responsePromise.promise) + } + + // 6. + const p = Promise.all(responsePromises) + + // 7. + const responses = await p + + // 7.1 + const operations = [] + + // 7.2 + let index = 0 + + // 7.3 + for (const response of responses) { + // 7.3.1 + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 7.3.2 + request: requestList[index], // 7.3.3 + response // 7.3.4 + } + + operations.push(operation) // 7.3.5 + + index++ // 7.3.6 + } + + // 7.5 + const cacheJobPromise = createDeferredPromise() + + // 7.6.1 + let errorData = null + + // 7.6.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 7.6.3 + queueMicrotask(() => { + // 7.6.3.1 + if (errorData === null) { + cacheJobPromise.resolve(undefined) + } else { + // 7.6.3.2 + cacheJobPromise.reject(errorData) + } + }) + + // 7.7 + return cacheJobPromise.promise + } + + async put (request, response) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.put' + webidl.argumentLengthCheck(arguments, 2, prefix) + + request = webidl.converters.RequestInfo(request, prefix, 'request') + response = webidl.converters.Response(response, prefix, 'response') + + // 1. + let innerRequest = null + + // 2. + if (request instanceof Request) { + innerRequest = request[kState] + } else { // 3. + innerRequest = new Request(request)[kState] + } + + // 4. + if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { + throw webidl.errors.exception({ + header: prefix, + message: 'Expected an http/s scheme when method is not GET' + }) + } + + // 5. + const innerResponse = response[kState] + + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: prefix, + message: 'Got 206 status' + }) + } + + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) + + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: prefix, + message: 'Got * vary field value' + }) + } + } + } + + // 8. + if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { + throw webidl.errors.exception({ + header: prefix, + message: 'Response body is locked or disturbed' + }) + } + + // 9. + const clonedResponse = cloneResponse(innerResponse) + + // 10. + const bodyReadPromise = createDeferredPromise() + + // 11. + if (innerResponse.body != null) { + // 11.1 + const stream = innerResponse.body.stream + + // 11.2 + const reader = stream.getReader() + + // 11.3 + readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) + } else { + bodyReadPromise.resolve(undefined) + } + + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = [] + + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. + } + + // 17. + operations.push(operation) + + // 19. + const bytes = await bodyReadPromise.promise + + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes + } + + // 19.1 + const cacheJobPromise = createDeferredPromise() + + // 19.2.1 + let errorData = null + + // 19.2.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve() + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise + } + + async delete (request, options = {}) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.delete' + webidl.argumentLengthCheck(arguments, 1, prefix) + + request = webidl.converters.RequestInfo(request, prefix, 'request') + options = webidl.converters.CacheQueryOptions(options, prefix, 'options') + + /** + * @type {Request} + */ + let r = null + + if (request instanceof Request) { + r = request[kState] + + if (r.method !== 'GET' && !options.ignoreMethod) { + return false + } + } else { + assert(typeof request === 'string') + + r = new Request(request)[kState] + } + + /** @type {CacheBatchOperation[]} */ + const operations = [] + + /** @type {CacheBatchOperation} */ + const operation = { + type: 'delete', + request: r, + options + } + + operations.push(operation) + + const cacheJobPromise = createDeferredPromise() + + let errorData = null + let requestResponses + + try { + requestResponses = this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length) + } else { + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys + * @param {any} request + * @param {import('../../types/cache').CacheQueryOptions} options + * @returns {Promise} + */ + async keys (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.keys' + + if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request') + options = webidl.converters.CacheQueryOptions(options, prefix, 'options') + + // 1. + let r = null + + // 2. + if (request !== undefined) { + // 2.1 + if (request instanceof Request) { + // 2.1.1 + r = request[kState] + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = new Request(request)[kState] + } + } + + // 4. + const promise = createDeferredPromise() + + // 5. + // 5.1 + const requests = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + // 5.2.1.1 + requests.push(requestResponse[0]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + // 5.3.2.1 + requests.push(requestResponse[0]) + } + } + + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = [] + + // 5.4.2 + for (const request of requests) { + const requestObject = fromInnerRequest( + request, + new AbortController().signal, + 'immutable' + ) + // 5.4.2.1 + requestList.push(requestObject) + } + + // 5.4.3 + promise.resolve(Object.freeze(requestList)) + }) + + return promise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} + */ + #batchCacheOperations (operations) { + // 1. + const cache = this.#relevantRequestResponseList + + // 2. + const backupCache = [...cache] + + // 3. + const addedItems = [] + + // 4.1 + const resultList = [] + + try { + // 4.2 + for (const operation of operations) { + // 4.2.1 + if (operation.type !== 'delete' && operation.type !== 'put') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'operation type does not match "delete" or "put"' + }) + } + + // 4.2.2 + if (operation.type === 'delete' && operation.response != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'delete operation should not have an associated response' + }) + } + + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } + + // 4.2.4 + let requestResponses + + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options) + + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } + + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) + + // 4.2.5.2.1 + cache.splice(idx, 1) + } + } else if (operation.type === 'put') { // 4.2.6 + // 4.2.6.1 + if (operation.response == null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'put operation should have an associated response' + }) + } + + // 4.2.6.2 + const r = operation.request + + // 4.2.6.3 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'expected http or https scheme' + }) + } + + // 4.2.6.4 + if (r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'not get method' + }) + } + + // 4.2.6.5 + if (operation.options != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'options must not be defined' + }) + } + + // 4.2.6.6 + requestResponses = this.#queryCache(operation.request) + + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) + + // 4.2.6.7.1 + cache.splice(idx, 1) + } + + // 4.2.6.8 + cache.push([operation.request, operation.response]) + + // 4.2.6.10 + addedItems.push([operation.request, operation.response]) + } + + // 4.2.7 + resultList.push([operation.request, operation.response]) + } + + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0 + + // 5.2 + this.#relevantRequestResponseList = backupCache + + // 5.3 + throw e + } + } + + /** + * @see https://w3c.github.io/ServiceWorker/#query-cache + * @param {any} requestQuery + * @param {import('../../types/cache').CacheQueryOptions} options + * @param {requestResponseList} targetStorage + * @returns {requestResponseList} + */ + #queryCache (requestQuery, options, targetStorage) { + /** @type {requestResponseList} */ + const resultList = [] + + const storage = targetStorage ?? this.#relevantRequestResponseList + + for (const requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse) + } + } + + return resultList + } + + /** + * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm + * @param {any} requestQuery + * @param {any} request + * @param {any | null} response + * @param {import('../../types/cache').CacheQueryOptions | undefined} options + * @returns {boolean} + */ + #requestMatchesCachedItem (requestQuery, request, response = null, options) { + // if (options?.ignoreMethod === false && request.method === 'GET') { + // return false + // } + + const queryURL = new URL(requestQuery.url) + + const cachedURL = new URL(request.url) + + if (options?.ignoreSearch) { + cachedURL.search = '' + + queryURL.search = '' + } + + if (!urlEquals(queryURL, cachedURL, true)) { + return false + } + + if ( + response == null || + options?.ignoreVary || + !response.headersList.contains('vary') + ) { + return true + } + + const fieldValues = getFieldValues(response.headersList.get('vary')) + + for (const fieldValue of fieldValues) { + if (fieldValue === '*') { + return false + } + + const requestValue = request.headersList.get(fieldValue) + const queryValue = requestQuery.headersList.get(fieldValue) + + // If one has the header and the other doesn't, or one has + // a different value than the other, return false + if (requestValue !== queryValue) { + return false + } + } + + return true + } + + #internalMatchAll (request, options, maxResponses = Infinity) { + // 1. + let r = null + + // 2. + if (request !== undefined) { + if (request instanceof Request) { + // 2.1.1 + r = request[kState] + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { + // 2.2.1 + r = new Request(request)[kState] + } + } + + // 5. + // 5.1 + const responses = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + responses.push(requestResponse[1]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]) + } + } + + // 5.4 + // We don't implement CORs so we don't need to loop over the responses, yay! + + // 5.5.1 + const responseList = [] + + // 5.5.2 + for (const response of responses) { + // 5.5.2.1 + const responseObject = fromInnerResponse(response, 'immutable') + + responseList.push(responseObject.clone()) + + if (responseList.length >= maxResponses) { + break + } + } + + // 6. + return Object.freeze(responseList) + } +} + +Object.defineProperties(Cache.prototype, { + [Symbol.toStringTag]: { + value: 'Cache', + configurable: true + }, + match: kEnumerableProperty, + matchAll: kEnumerableProperty, + add: kEnumerableProperty, + addAll: kEnumerableProperty, + put: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +const cacheQueryOptionConverters = [ + { + key: 'ignoreSearch', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'ignoreMethod', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'ignoreVary', + converter: webidl.converters.boolean, + defaultValue: () => false + } +] + +webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) + +webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: 'cacheName', + converter: webidl.converters.DOMString + } +]) + +webidl.converters.Response = webidl.interfaceConverter(Response) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.RequestInfo +) + +module.exports = { + Cache +} diff --git a/node_modules/undici/lib/web/cache/cachestorage.js b/node_modules/undici/lib/web/cache/cachestorage.js new file mode 100644 index 0000000000000..55dba352e99d8 --- /dev/null +++ b/node_modules/undici/lib/web/cache/cachestorage.js @@ -0,0 +1,152 @@ +'use strict' + +const { kConstruct } = require('./symbols') +const { Cache } = require('./cache') +const { webidl } = require('../fetch/webidl') +const { kEnumerableProperty } = require('../../core/util') + +class CacheStorage { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map} + */ + async has (cacheName) { + webidl.brandCheck(this, CacheStorage) + + const prefix = 'CacheStorage.has' + webidl.argumentLengthCheck(arguments, 1, prefix) + + cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') + + // 2.1.1 + // 2.2 + return this.#caches.has(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open + * @param {string} cacheName + * @returns {Promise} + */ + async open (cacheName) { + webidl.brandCheck(this, CacheStorage) + + const prefix = 'CacheStorage.open' + webidl.argumentLengthCheck(arguments, 1, prefix) + + cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') + + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') + + // 2.1.1 + const cache = this.#caches.get(cacheName) + + // 2.1.1.1 + return new Cache(kConstruct, cache) + } + + // 2.2 + const cache = [] + + // 2.3 + this.#caches.set(cacheName, cache) + + // 2.4 + return new Cache(kConstruct, cache) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete + * @param {string} cacheName + * @returns {Promise} + */ + async delete (cacheName) { + webidl.brandCheck(this, CacheStorage) + + const prefix = 'CacheStorage.delete' + webidl.argumentLengthCheck(arguments, 1, prefix) + + cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') + + return this.#caches.delete(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {Promise} + */ + async keys () { + webidl.brandCheck(this, CacheStorage) + + // 2.1 + const keys = this.#caches.keys() + + // 2.2 + return [...keys] + } +} + +Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: 'CacheStorage', + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +module.exports = { + CacheStorage +} diff --git a/node_modules/undici/lib/web/cache/symbols.js b/node_modules/undici/lib/web/cache/symbols.js new file mode 100644 index 0000000000000..9271fb6126702 --- /dev/null +++ b/node_modules/undici/lib/web/cache/symbols.js @@ -0,0 +1,5 @@ +'use strict' + +module.exports = { + kConstruct: require('../../core/symbols').kConstruct +} diff --git a/node_modules/undici/lib/web/cache/util.js b/node_modules/undici/lib/web/cache/util.js new file mode 100644 index 0000000000000..5ac9d846ddc09 --- /dev/null +++ b/node_modules/undici/lib/web/cache/util.js @@ -0,0 +1,45 @@ +'use strict' + +const assert = require('node:assert') +const { URLSerializer } = require('../fetch/data-url') +const { isValidHeaderName } = require('../fetch/util') + +/** + * @see https://url.spec.whatwg.org/#concept-url-equals + * @param {URL} A + * @param {URL} B + * @param {boolean | undefined} excludeFragment + * @returns {boolean} + */ +function urlEquals (A, B, excludeFragment = false) { + const serializedA = URLSerializer(A, excludeFragment) + + const serializedB = URLSerializer(B, excludeFragment) + + return serializedA === serializedB +} + +/** + * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 + * @param {string} header + */ +function getFieldValues (header) { + assert(header !== null) + + const values = [] + + for (let value of header.split(',')) { + value = value.trim() + + if (isValidHeaderName(value)) { + values.push(value) + } + } + + return values +} + +module.exports = { + urlEquals, + getFieldValues +} diff --git a/node_modules/undici/lib/web/cookies/constants.js b/node_modules/undici/lib/web/cookies/constants.js new file mode 100644 index 0000000000000..85f1fec0e93c8 --- /dev/null +++ b/node_modules/undici/lib/web/cookies/constants.js @@ -0,0 +1,12 @@ +'use strict' + +// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size +const maxAttributeValueSize = 1024 + +// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size +const maxNameValuePairSize = 4096 + +module.exports = { + maxAttributeValueSize, + maxNameValuePairSize +} diff --git a/node_modules/undici/lib/web/cookies/index.js b/node_modules/undici/lib/web/cookies/index.js new file mode 100644 index 0000000000000..323aa9ee6fbfb --- /dev/null +++ b/node_modules/undici/lib/web/cookies/index.js @@ -0,0 +1,184 @@ +'use strict' + +const { parseSetCookie } = require('./parse') +const { stringify } = require('./util') +const { webidl } = require('../fetch/webidl') +const { Headers } = require('../fetch/headers') + +/** + * @typedef {Object} Cookie + * @property {string} name + * @property {string} value + * @property {Date|number|undefined} expires + * @property {number|undefined} maxAge + * @property {string|undefined} domain + * @property {string|undefined} path + * @property {boolean|undefined} secure + * @property {boolean|undefined} httpOnly + * @property {'Strict'|'Lax'|'None'} sameSite + * @property {string[]} unparsed + */ + +/** + * @param {Headers} headers + * @returns {Record} + */ +function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, 'getCookies') + + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookie = headers.get('cookie') + const out = {} + + if (!cookie) { + return out + } + + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('=') + + out[name.trim()] = value.join('=') + } + + return out +} + +/** + * @param {Headers} headers + * @param {string} name + * @param {{ path?: string, domain?: string }|undefined} attributes + * @returns {void} + */ +function deleteCookie (headers, name, attributes) { + webidl.brandCheck(headers, Headers, { strict: false }) + + const prefix = 'deleteCookie' + webidl.argumentLengthCheck(arguments, 2, prefix) + + name = webidl.converters.DOMString(name, prefix, 'name') + attributes = webidl.converters.DeleteCookieAttributes(attributes) + + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }) +} + +/** + * @param {Headers} headers + * @returns {Cookie[]} + */ +function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, 'getSetCookies') + + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookies = headers.getSetCookie() + + if (!cookies) { + return [] + } + + return cookies.map((pair) => parseSetCookie(pair)) +} + +/** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ +function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, 'setCookie') + + webidl.brandCheck(headers, Headers, { strict: false }) + + cookie = webidl.converters.Cookie(cookie) + + const str = stringify(cookie) + + if (str) { + headers.append('Set-Cookie', str) + } +} + +webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: () => null + } +]) + +webidl.converters.Cookie = webidl.dictionaryConverter([ + { + converter: webidl.converters.DOMString, + key: 'name' + }, + { + converter: webidl.converters.DOMString, + key: 'value' + }, + { + converter: webidl.nullableConverter((value) => { + if (typeof value === 'number') { + return webidl.converters['unsigned long long'](value) + } + + return new Date(value) + }), + key: 'expires', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters['long long']), + key: 'maxAge', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'secure', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'httpOnly', + defaultValue: () => null + }, + { + converter: webidl.converters.USVString, + key: 'sameSite', + allowedValues: ['Strict', 'Lax', 'None'] + }, + { + converter: webidl.sequenceConverter(webidl.converters.DOMString), + key: 'unparsed', + defaultValue: () => new Array(0) + } +]) + +module.exports = { + getCookies, + deleteCookie, + getSetCookies, + setCookie +} diff --git a/node_modules/undici/lib/web/cookies/parse.js b/node_modules/undici/lib/web/cookies/parse.js new file mode 100644 index 0000000000000..3c48c26b93ffa --- /dev/null +++ b/node_modules/undici/lib/web/cookies/parse.js @@ -0,0 +1,317 @@ +'use strict' + +const { maxNameValuePairSize, maxAttributeValueSize } = require('./constants') +const { isCTLExcludingHtab } = require('./util') +const { collectASequenceOfCodePointsFast } = require('../fetch/data-url') +const assert = require('node:assert') + +/** + * @description Parses the field-value attributes of a set-cookie header string. + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} header + * @returns if the header is invalid, null will be returned + */ +function parseSetCookie (header) { + // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F + // character (CTL characters excluding HTAB): Abort these steps and + // ignore the set-cookie-string entirely. + if (isCTLExcludingHtab(header)) { + return null + } + + let nameValuePair = '' + let unparsedAttributes = '' + let name = '' + let value = '' + + // 2. If the set-cookie-string contains a %x3B (";") character: + if (header.includes(';')) { + // 1. The name-value-pair string consists of the characters up to, + // but not including, the first %x3B (";"), and the unparsed- + // attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question). + const position = { position: 0 } + + nameValuePair = collectASequenceOfCodePointsFast(';', header, position) + unparsedAttributes = header.slice(position.position) + } else { + // Otherwise: + + // 1. The name-value-pair string consists of all the characters + // contained in the set-cookie-string, and the unparsed- + // attributes is the empty string. + nameValuePair = header + } + + // 3. If the name-value-pair string lacks a %x3D ("=") character, then + // the name string is empty, and the value string is the value of + // name-value-pair. + if (!nameValuePair.includes('=')) { + value = nameValuePair + } else { + // Otherwise, the name string consists of the characters up to, but + // not including, the first %x3D ("=") character, and the (possibly + // empty) value string consists of the characters after the first + // %x3D ("=") character. + const position = { position: 0 } + name = collectASequenceOfCodePointsFast( + '=', + nameValuePair, + position + ) + value = nameValuePair.slice(position.position + 1) + } + + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim() + value = value.trim() + + // 5. If the sum of the lengths of the name string and the value string + // is more than 4096 octets, abort these steps and ignore the set- + // cookie-string entirely. + if (name.length + value.length > maxNameValuePairSize) { + return null + } + + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + return { + name, value, ...parseUnparsedAttributes(unparsedAttributes) + } +} + +/** + * Parses the remaining attributes of a set-cookie header + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} unparsedAttributes + * @param {[Object.]={}} cookieAttributeList + */ +function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { + // 1. If the unparsed-attributes string is empty, skip the rest of + // these steps. + if (unparsedAttributes.length === 0) { + return cookieAttributeList + } + + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';') + unparsedAttributes = unparsedAttributes.slice(1) + + let cookieAv = '' + + // 3. If the remaining unparsed-attributes contains a %x3B (";") + // character: + if (unparsedAttributes.includes(';')) { + // 1. Consume the characters of the unparsed-attributes up to, but + // not including, the first %x3B (";") character. + cookieAv = collectASequenceOfCodePointsFast( + ';', + unparsedAttributes, + { position: 0 } + ) + unparsedAttributes = unparsedAttributes.slice(cookieAv.length) + } else { + // Otherwise: + + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes + unparsedAttributes = '' + } + + // Let the cookie-av string be the characters consumed in this step. + + let attributeName = '' + let attributeValue = '' + + // 4. If the cookie-av string contains a %x3D ("=") character: + if (cookieAv.includes('=')) { + // 1. The (possibly empty) attribute-name string consists of the + // characters up to, but not including, the first %x3D ("=") + // character, and the (possibly empty) attribute-value string + // consists of the characters after the first %x3D ("=") + // character. + const position = { position: 0 } + + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ) + attributeValue = cookieAv.slice(position.position + 1) + } else { + // Otherwise: + + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv + } + + // 5. Remove any leading or trailing WSP characters from the attribute- + // name string and the attribute-value string. + attributeName = attributeName.trim() + attributeValue = attributeValue.trim() + + // 6. If the attribute-value is longer than 1024 octets, ignore the + // cookie-av string and return to Step 1 of this algorithm. + if (attributeValue.length > maxAttributeValueSize) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 7. Process the attribute-name and attribute-value according to the + // requirements in the following subsections. (Notice that + // attributes with unrecognized attribute-names are ignored.) + const attributeNameLowercase = attributeName.toLowerCase() + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 + // If the attribute-name case-insensitively matches the string + // "Expires", the user agent MUST process the cookie-av as follows. + if (attributeNameLowercase === 'expires') { + // 1. Let the expiry-time be the result of parsing the attribute-value + // as cookie-date (see Section 5.1.1). + const expiryTime = new Date(attributeValue) + + // 2. If the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. + + cookieAttributeList.expires = expiryTime + } else if (attributeNameLowercase === 'max-age') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 + // If the attribute-name case-insensitively matches the string "Max- + // Age", the user agent MUST process the cookie-av as follows. + + // 1. If the first character of the attribute-value is not a DIGIT or a + // "-" character, ignore the cookie-av. + const charCode = attributeValue.charCodeAt(0) + + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue) + + // 4. Let cookie-age-limit be the maximum age of the cookie (which + // SHOULD be 400 days or less, see Section 4.1.2.2). + + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + + // 6. If delta-seconds is less than or equal to zero (0), let expiry- + // time be the earliest representable date and time. Otherwise, let + // the expiry-time be the current date and time plus delta-seconds + // seconds. + // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds + + // 7. Append an attribute to the cookie-attribute-list with an + // attribute-name of Max-Age and an attribute-value of expiry-time. + cookieAttributeList.maxAge = deltaSeconds + } else if (attributeNameLowercase === 'domain') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 + // If the attribute-name case-insensitively matches the string "Domain", + // the user agent MUST process the cookie-av as follows. + + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue + + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1) + } + + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase() + + // 4. Append an attribute to the cookie-attribute-list with an + // attribute-name of Domain and an attribute-value of cookie-domain. + cookieAttributeList.domain = cookieDomain + } else if (attributeNameLowercase === 'path') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 + // If the attribute-name case-insensitively matches the string "Path", + // the user agent MUST process the cookie-av as follows. + + // 1. If the attribute-value is empty or if the first character of the + // attribute-value is not %x2F ("/"): + let cookiePath = '' + if (attributeValue.length === 0 || attributeValue[0] !== '/') { + // 1. Let cookie-path be the default-path. + cookiePath = '/' + } else { + // Otherwise: + + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue + } + + // 2. Append an attribute to the cookie-attribute-list with an + // attribute-name of Path and an attribute-value of cookie-path. + cookieAttributeList.path = cookiePath + } else if (attributeNameLowercase === 'secure') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 + // If the attribute-name case-insensitively matches the string "Secure", + // the user agent MUST append an attribute to the cookie-attribute-list + // with an attribute-name of Secure and an empty attribute-value. + + cookieAttributeList.secure = true + } else if (attributeNameLowercase === 'httponly') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 + // If the attribute-name case-insensitively matches the string + // "HttpOnly", the user agent MUST append an attribute to the cookie- + // attribute-list with an attribute-name of HttpOnly and an empty + // attribute-value. + + cookieAttributeList.httpOnly = true + } else if (attributeNameLowercase === 'samesite') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 + // If the attribute-name case-insensitively matches the string + // "SameSite", the user agent MUST process the cookie-av as follows: + + // 1. Let enforcement be "Default". + let enforcement = 'Default' + + const attributeValueLowercase = attributeValue.toLowerCase() + // 2. If cookie-av's attribute-value is a case-insensitive match for + // "None", set enforcement to "None". + if (attributeValueLowercase.includes('none')) { + enforcement = 'None' + } + + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict' + } + + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax' + } + + // 5. Append an attribute to the cookie-attribute-list with an + // attribute-name of "SameSite" and an attribute-value of + // enforcement. + cookieAttributeList.sameSite = enforcement + } else { + cookieAttributeList.unparsed ??= [] + + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) + } + + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) +} + +module.exports = { + parseSetCookie, + parseUnparsedAttributes +} diff --git a/node_modules/undici/lib/web/cookies/util.js b/node_modules/undici/lib/web/cookies/util.js new file mode 100644 index 0000000000000..254f5419e905b --- /dev/null +++ b/node_modules/undici/lib/web/cookies/util.js @@ -0,0 +1,282 @@ +'use strict' + +/** + * @param {string} value + * @returns {boolean} + */ +function isCTLExcludingHtab (value) { + for (let i = 0; i < value.length; ++i) { + const code = value.charCodeAt(i) + + if ( + (code >= 0x00 && code <= 0x08) || + (code >= 0x0A && code <= 0x1F) || + code === 0x7F + ) { + return true + } + } + return false +} + +/** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ +function validateCookieName (name) { + for (let i = 0; i < name.length; ++i) { + const code = name.charCodeAt(i) + + if ( + code < 0x21 || // exclude CTLs (0-31), SP and HT + code > 0x7E || // exclude non-ascii and DEL + code === 0x22 || // " + code === 0x28 || // ( + code === 0x29 || // ) + code === 0x3C || // < + code === 0x3E || // > + code === 0x40 || // @ + code === 0x2C || // , + code === 0x3B || // ; + code === 0x3A || // : + code === 0x5C || // \ + code === 0x2F || // / + code === 0x5B || // [ + code === 0x5D || // ] + code === 0x3F || // ? + code === 0x3D || // = + code === 0x7B || // { + code === 0x7D // } + ) { + throw new Error('Invalid cookie name') + } + } +} + +/** + cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + ; US-ASCII characters excluding CTLs, + ; whitespace DQUOTE, comma, semicolon, + ; and backslash + * @param {string} value + */ +function validateCookieValue (value) { + let len = value.length + let i = 0 + + // if the value is wrapped in DQUOTE + if (value[0] === '"') { + if (len === 1 || value[len - 1] !== '"') { + throw new Error('Invalid cookie value') + } + --len + ++i + } + + while (i < len) { + const code = value.charCodeAt(i++) + + if ( + code < 0x21 || // exclude CTLs (0-31) + code > 0x7E || // non-ascii and DEL (127) + code === 0x22 || // " + code === 0x2C || // , + code === 0x3B || // ; + code === 0x5C // \ + ) { + throw new Error('Invalid cookie value') + } + } +} + +/** + * path-value = + * @param {string} path + */ +function validateCookiePath (path) { + for (let i = 0; i < path.length; ++i) { + const code = path.charCodeAt(i) + + if ( + code < 0x20 || // exclude CTLs (0-31) + code === 0x7F || // DEL + code === 0x3B // ; + ) { + throw new Error('Invalid cookie path') + } + } +} + +/** + * I have no idea why these values aren't allowed to be honest, + * but Deno tests these. - Khafra + * @param {string} domain + */ +function validateCookieDomain (domain) { + if ( + domain.startsWith('-') || + domain.endsWith('.') || + domain.endsWith('-') + ) { + throw new Error('Invalid cookie domain') + } +} + +const IMFDays = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' +] + +const IMFMonths = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' +] + +const IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, '0')) + +/** + * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 + * @param {number|Date} date + IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + ; fixed length/zone/capitalization subset of the format + ; see Section 3.3 of [RFC5322] + + day-name = %x4D.6F.6E ; "Mon", case-sensitive + / %x54.75.65 ; "Tue", case-sensitive + / %x57.65.64 ; "Wed", case-sensitive + / %x54.68.75 ; "Thu", case-sensitive + / %x46.72.69 ; "Fri", case-sensitive + / %x53.61.74 ; "Sat", case-sensitive + / %x53.75.6E ; "Sun", case-sensitive + date1 = day SP month SP year + ; e.g., 02 Jun 1982 + + day = 2DIGIT + month = %x4A.61.6E ; "Jan", case-sensitive + / %x46.65.62 ; "Feb", case-sensitive + / %x4D.61.72 ; "Mar", case-sensitive + / %x41.70.72 ; "Apr", case-sensitive + / %x4D.61.79 ; "May", case-sensitive + / %x4A.75.6E ; "Jun", case-sensitive + / %x4A.75.6C ; "Jul", case-sensitive + / %x41.75.67 ; "Aug", case-sensitive + / %x53.65.70 ; "Sep", case-sensitive + / %x4F.63.74 ; "Oct", case-sensitive + / %x4E.6F.76 ; "Nov", case-sensitive + / %x44.65.63 ; "Dec", case-sensitive + year = 4DIGIT + + GMT = %x47.4D.54 ; "GMT", case-sensitive + + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) + + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ +function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date) + } + + return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT` +} + +/** + max-age-av = "Max-Age=" non-zero-digit *DIGIT + ; In practice, both expires-av and max-age-av + ; are limited to dates representable by the + ; user agent. + * @param {number} maxAge + */ +function validateCookieMaxAge (maxAge) { + if (maxAge < 0) { + throw new Error('Invalid cookie max-age') + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 + * @param {import('./index').Cookie} cookie + */ +function stringify (cookie) { + if (cookie.name.length === 0) { + return null + } + + validateCookieName(cookie.name) + validateCookieValue(cookie.value) + + const out = [`${cookie.name}=${cookie.value}`] + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 + if (cookie.name.startsWith('__Secure-')) { + cookie.secure = true + } + + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true + cookie.domain = null + cookie.path = '/' + } + + if (cookie.secure) { + out.push('Secure') + } + + if (cookie.httpOnly) { + out.push('HttpOnly') + } + + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge) + out.push(`Max-Age=${cookie.maxAge}`) + } + + if (cookie.domain) { + validateCookieDomain(cookie.domain) + out.push(`Domain=${cookie.domain}`) + } + + if (cookie.path) { + validateCookiePath(cookie.path) + out.push(`Path=${cookie.path}`) + } + + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`) + } + + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`) + } + + for (const part of cookie.unparsed) { + if (!part.includes('=')) { + throw new Error('Invalid unparsed') + } + + const [key, ...value] = part.split('=') + + out.push(`${key.trim()}=${value.join('=')}`) + } + + return out.join('; ') +} + +module.exports = { + isCTLExcludingHtab, + validateCookieName, + validateCookiePath, + validateCookieValue, + toIMFDate, + stringify +} diff --git a/node_modules/undici/lib/web/eventsource/eventsource-stream.js b/node_modules/undici/lib/web/eventsource/eventsource-stream.js new file mode 100644 index 0000000000000..754934568d056 --- /dev/null +++ b/node_modules/undici/lib/web/eventsource/eventsource-stream.js @@ -0,0 +1,398 @@ +'use strict' +const { Transform } = require('node:stream') +const { isASCIINumber, isValidLastEventId } = require('./util') + +/** + * @type {number[]} BOM + */ +const BOM = [0xEF, 0xBB, 0xBF] +/** + * @type {10} LF + */ +const LF = 0x0A +/** + * @type {13} CR + */ +const CR = 0x0D +/** + * @type {58} COLON + */ +const COLON = 0x3A +/** + * @type {32} SPACE + */ +const SPACE = 0x20 + +/** + * @typedef {object} EventSourceStreamEvent + * @type {object} + * @property {string} [event] The event type. + * @property {string} [data] The data of the message. + * @property {string} [id] A unique ID for the event. + * @property {string} [retry] The reconnection time, in milliseconds. + */ + +/** + * @typedef eventSourceSettings + * @type {object} + * @property {string} lastEventId The last event ID received from the server. + * @property {string} origin The origin of the event source. + * @property {number} reconnectionTime The reconnection time, in milliseconds. + */ + +class EventSourceStream extends Transform { + /** + * @type {eventSourceSettings} + */ + state = null + + /** + * Leading byte-order-mark check. + * @type {boolean} + */ + checkBOM = true + + /** + * @type {boolean} + */ + crlfCheck = false + + /** + * @type {boolean} + */ + eventEndCheck = false + + /** + * @type {Buffer} + */ + buffer = null + + pos = 0 + + event = { + data: undefined, + event: undefined, + id: undefined, + retry: undefined + } + + /** + * @param {object} options + * @param {eventSourceSettings} options.eventSourceSettings + * @param {Function} [options.push] + */ + constructor (options = {}) { + // Enable object mode as EventSourceStream emits objects of shape + // EventSourceStreamEvent + options.readableObjectMode = true + + super(options) + + this.state = options.eventSourceSettings || {} + if (options.push) { + this.push = options.push + } + } + + /** + * @param {Buffer} chunk + * @param {string} _encoding + * @param {Function} callback + * @returns {void} + */ + _transform (chunk, _encoding, callback) { + if (chunk.length === 0) { + callback() + return + } + + // Cache the chunk in the buffer, as the data might not be complete while + // processing it + // TODO: Investigate if there is a more performant way to handle + // incoming chunks + // see: https://github.com/nodejs/undici/issues/2630 + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]) + } else { + this.buffer = chunk + } + + // Strip leading byte-order-mark if we opened the stream and started + // the processing of the incoming data + if (this.checkBOM) { + switch (this.buffer.length) { + case 1: + // Check if the first byte is the same as the first byte of the BOM + if (this.buffer[0] === BOM[0]) { + // If it is, we need to wait for more data + callback() + return + } + // Set the checkBOM flag to false as we don't need to check for the + // BOM anymore + this.checkBOM = false + + // The buffer only contains one byte so we need to wait for more data + callback() + return + case 2: + // Check if the first two bytes are the same as the first two bytes + // of the BOM + if ( + this.buffer[0] === BOM[0] && + this.buffer[1] === BOM[1] + ) { + // If it is, we need to wait for more data, because the third byte + // is needed to determine if it is the BOM or not + callback() + return + } + + // Set the checkBOM flag to false as we don't need to check for the + // BOM anymore + this.checkBOM = false + break + case 3: + // Check if the first three bytes are the same as the first three + // bytes of the BOM + if ( + this.buffer[0] === BOM[0] && + this.buffer[1] === BOM[1] && + this.buffer[2] === BOM[2] + ) { + // If it is, we can drop the buffered data, as it is only the BOM + this.buffer = Buffer.alloc(0) + // Set the checkBOM flag to false as we don't need to check for the + // BOM anymore + this.checkBOM = false + + // Await more data + callback() + return + } + // If it is not the BOM, we can start processing the data + this.checkBOM = false + break + default: + // The buffer is longer than 3 bytes, so we can drop the BOM if it is + // present + if ( + this.buffer[0] === BOM[0] && + this.buffer[1] === BOM[1] && + this.buffer[2] === BOM[2] + ) { + // Remove the BOM from the buffer + this.buffer = this.buffer.subarray(3) + } + + // Set the checkBOM flag to false as we don't need to check for the + this.checkBOM = false + break + } + } + + while (this.pos < this.buffer.length) { + // If the previous line ended with an end-of-line, we need to check + // if the next character is also an end-of-line. + if (this.eventEndCheck) { + // If the the current character is an end-of-line, then the event + // is finished and we can process it + + // If the previous line ended with a carriage return, we need to + // check if the current character is a line feed and remove it + // from the buffer. + if (this.crlfCheck) { + // If the current character is a line feed, we can remove it + // from the buffer and reset the crlfCheck flag + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1) + this.pos = 0 + this.crlfCheck = false + + // It is possible that the line feed is not the end of the + // event. We need to check if the next character is an + // end-of-line character to determine if the event is + // finished. We simply continue the loop to check the next + // character. + + // As we removed the line feed from the buffer and set the + // crlfCheck flag to false, we basically don't make any + // distinction between a line feed and a carriage return. + continue + } + this.crlfCheck = false + } + + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + // If the current character is a carriage return, we need to + // set the crlfCheck flag to true, as we need to check if the + // next character is a line feed so we can remove it from the + // buffer + if (this.buffer[this.pos] === CR) { + this.crlfCheck = true + } + + this.buffer = this.buffer.subarray(this.pos + 1) + this.pos = 0 + if ( + this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) { + this.processEvent(this.event) + } + this.clearEvent() + continue + } + // If the current character is not an end-of-line, then the event + // is not finished and we have to reset the eventEndCheck flag + this.eventEndCheck = false + continue + } + + // If the current character is an end-of-line, we can process the + // line + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + // If the current character is a carriage return, we need to + // set the crlfCheck flag to true, as we need to check if the + // next character is a line feed + if (this.buffer[this.pos] === CR) { + this.crlfCheck = true + } + + // In any case, we can process the line as we reached an + // end-of-line character + this.parseLine(this.buffer.subarray(0, this.pos), this.event) + + // Remove the processed line from the buffer + this.buffer = this.buffer.subarray(this.pos + 1) + // Reset the position as we removed the processed line from the buffer + this.pos = 0 + // A line was processed and this could be the end of the event. We need + // to check if the next line is empty to determine if the event is + // finished. + this.eventEndCheck = true + continue + } + + this.pos++ + } + + callback() + } + + /** + * @param {Buffer} line + * @param {EventStreamEvent} event + */ + parseLine (line, event) { + // If the line is empty (a blank line) + // Dispatch the event, as defined below. + // This will be handled in the _transform method + if (line.length === 0) { + return + } + + // If the line starts with a U+003A COLON character (:) + // Ignore the line. + const colonPosition = line.indexOf(COLON) + if (colonPosition === 0) { + return + } + + let field = '' + let value = '' + + // If the line contains a U+003A COLON character (:) + if (colonPosition !== -1) { + // Collect the characters on the line before the first U+003A COLON + // character (:), and let field be that string. + // TODO: Investigate if there is a more performant way to extract the + // field + // see: https://github.com/nodejs/undici/issues/2630 + field = line.subarray(0, colonPosition).toString('utf8') + + // Collect the characters on the line after the first U+003A COLON + // character (:), and let value be that string. + // If value starts with a U+0020 SPACE character, remove it from value. + let valueStart = colonPosition + 1 + if (line[valueStart] === SPACE) { + ++valueStart + } + // TODO: Investigate if there is a more performant way to extract the + // value + // see: https://github.com/nodejs/undici/issues/2630 + value = line.subarray(valueStart).toString('utf8') + + // Otherwise, the string is not empty but does not contain a U+003A COLON + // character (:) + } else { + // Process the field using the steps described below, using the whole + // line as the field name, and the empty string as the field value. + field = line.toString('utf8') + value = '' + } + + // Modify the event with the field name and value. The value is also + // decoded as UTF-8 + switch (field) { + case 'data': + if (event[field] === undefined) { + event[field] = value + } else { + event[field] += `\n${value}` + } + break + case 'retry': + if (isASCIINumber(value)) { + event[field] = value + } + break + case 'id': + if (isValidLastEventId(value)) { + event[field] = value + } + break + case 'event': + if (value.length > 0) { + event[field] = value + } + break + } + } + + /** + * @param {EventSourceStreamEvent} event + */ + processEvent (event) { + if (event.retry && isASCIINumber(event.retry)) { + this.state.reconnectionTime = parseInt(event.retry, 10) + } + + if (event.id && isValidLastEventId(event.id)) { + this.state.lastEventId = event.id + } + + // only dispatch event, when data is provided + if (event.data !== undefined) { + this.push({ + type: event.event || 'message', + options: { + data: event.data, + lastEventId: this.state.lastEventId, + origin: this.state.origin + } + }) + } + } + + clearEvent () { + this.event = { + data: undefined, + event: undefined, + id: undefined, + retry: undefined + } + } +} + +module.exports = { + EventSourceStream +} diff --git a/node_modules/undici/lib/web/eventsource/eventsource.js b/node_modules/undici/lib/web/eventsource/eventsource.js new file mode 100644 index 0000000000000..5a488ffce276a --- /dev/null +++ b/node_modules/undici/lib/web/eventsource/eventsource.js @@ -0,0 +1,480 @@ +'use strict' + +const { pipeline } = require('node:stream') +const { fetching } = require('../fetch') +const { makeRequest } = require('../fetch/request') +const { webidl } = require('../fetch/webidl') +const { EventSourceStream } = require('./eventsource-stream') +const { parseMIMEType } = require('../fetch/data-url') +const { createFastMessageEvent } = require('../websocket/events') +const { isNetworkError } = require('../fetch/response') +const { delay } = require('./util') +const { kEnumerableProperty } = require('../../core/util') +const { environmentSettingsObject } = require('../fetch/util') + +let experimentalWarned = false + +/** + * A reconnection time, in milliseconds. This must initially be an implementation-defined value, + * probably in the region of a few seconds. + * + * In Comparison: + * - Chrome uses 3000ms. + * - Deno uses 5000ms. + * + * @type {3000} + */ +const defaultReconnectionTime = 3000 + +/** + * The readyState attribute represents the state of the connection. + * @enum + * @readonly + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev + */ + +/** + * The connection has not yet been established, or it was closed and the user + * agent is reconnecting. + * @type {0} + */ +const CONNECTING = 0 + +/** + * The user agent has an open connection and is dispatching events as it + * receives them. + * @type {1} + */ +const OPEN = 1 + +/** + * The connection is not open, and the user agent is not trying to reconnect. + * @type {2} + */ +const CLOSED = 2 + +/** + * Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin". + * @type {'anonymous'} + */ +const ANONYMOUS = 'anonymous' + +/** + * Requests for the element will have their mode set to "cors" and their credentials mode set to "include". + * @type {'use-credentials'} + */ +const USE_CREDENTIALS = 'use-credentials' + +/** + * The EventSource interface is used to receive server-sent events. It + * connects to a server over HTTP and receives events in text/event-stream + * format without closing the connection. + * @extends {EventTarget} + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events + * @api public + */ +class EventSource extends EventTarget { + #events = { + open: null, + error: null, + message: null + } + + #url = null + #withCredentials = false + + #readyState = CONNECTING + + #request = null + #controller = null + + #dispatcher + + /** + * @type {import('./eventsource-stream').eventSourceSettings} + */ + #state + + /** + * Creates a new EventSource object. + * @param {string} url + * @param {EventSourceInit} [eventSourceInitDict] + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface + */ + constructor (url, eventSourceInitDict = {}) { + // 1. Let ev be a new EventSource object. + super() + + webidl.util.markAsUncloneable(this) + + const prefix = 'EventSource constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + if (!experimentalWarned) { + experimentalWarned = true + process.emitWarning('EventSource is experimental, expect them to change at any time.', { + code: 'UNDICI-ES' + }) + } + + url = webidl.converters.USVString(url, prefix, 'url') + eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, 'eventSourceInitDict') + + this.#dispatcher = eventSourceInitDict.dispatcher + this.#state = { + lastEventId: '', + reconnectionTime: defaultReconnectionTime + } + + // 2. Let settings be ev's relevant settings object. + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + const settings = environmentSettingsObject + + let urlRecord + + try { + // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings. + urlRecord = new URL(url, settings.settingsObject.baseUrl) + this.#state.origin = urlRecord.origin + } catch (e) { + // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 5. Set ev's url to urlRecord. + this.#url = urlRecord.href + + // 6. Let corsAttributeState be Anonymous. + let corsAttributeState = ANONYMOUS + + // 7. If the value of eventSourceInitDict's withCredentials member is true, + // then set corsAttributeState to Use Credentials and set ev's + // withCredentials attribute to true. + if (eventSourceInitDict.withCredentials) { + corsAttributeState = USE_CREDENTIALS + this.#withCredentials = true + } + + // 8. Let request be the result of creating a potential-CORS request given + // urlRecord, the empty string, and corsAttributeState. + const initRequest = { + redirect: 'follow', + keepalive: true, + // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes + mode: 'cors', + credentials: corsAttributeState === 'anonymous' + ? 'same-origin' + : 'omit', + referrer: 'no-referrer' + } + + // 9. Set request's client to settings. + initRequest.client = environmentSettingsObject.settingsObject + + // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list. + initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]] + + // 11. Set request's cache mode to "no-store". + initRequest.cache = 'no-store' + + // 12. Set request's initiator type to "other". + initRequest.initiator = 'other' + + initRequest.urlList = [new URL(this.#url)] + + // 13. Set ev's request to request. + this.#request = makeRequest(initRequest) + + this.#connect() + } + + /** + * Returns the state of this EventSource object's connection. It can have the + * values described below. + * @returns {0|1|2} + * @readonly + */ + get readyState () { + return this.#readyState + } + + /** + * Returns the URL providing the event stream. + * @readonly + * @returns {string} + */ + get url () { + return this.#url + } + + /** + * Returns a boolean indicating whether the EventSource object was + * instantiated with CORS credentials set (true), or not (false, the default). + */ + get withCredentials () { + return this.#withCredentials + } + + #connect () { + if (this.#readyState === CLOSED) return + + this.#readyState = CONNECTING + + const fetchParams = { + request: this.#request, + dispatcher: this.#dispatcher + } + + // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection. + const processEventSourceEndOfBody = (response) => { + if (isNetworkError(response)) { + this.dispatchEvent(new Event('error')) + this.close() + } + + this.#reconnect() + } + + // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody... + fetchParams.processResponseEndOfBody = processEventSourceEndOfBody + + // and processResponse set to the following steps given response res: + fetchParams.processResponse = (response) => { + // 1. If res is an aborted network error, then fail the connection. + + if (isNetworkError(response)) { + // 1. When a user agent is to fail the connection, the user agent + // must queue a task which, if the readyState attribute is set to a + // value other than CLOSED, sets the readyState attribute to CLOSED + // and fires an event named error at the EventSource object. Once the + // user agent has failed the connection, it does not attempt to + // reconnect. + if (response.aborted) { + this.close() + this.dispatchEvent(new Event('error')) + return + // 2. Otherwise, if res is a network error, then reestablish the + // connection, unless the user agent knows that to be futile, in + // which case the user agent may fail the connection. + } else { + this.#reconnect() + return + } + } + + // 3. Otherwise, if res's status is not 200, or if res's `Content-Type` + // is not `text/event-stream`, then fail the connection. + const contentType = response.headersList.get('content-type', true) + const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure' + const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream' + if ( + response.status !== 200 || + contentTypeValid === false + ) { + this.close() + this.dispatchEvent(new Event('error')) + return + } + + // 4. Otherwise, announce the connection and interpret res's body + // line by line. + + // When a user agent is to announce the connection, the user agent + // must queue a task which, if the readyState attribute is set to a + // value other than CLOSED, sets the readyState attribute to OPEN + // and fires an event named open at the EventSource object. + // @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model + this.#readyState = OPEN + this.dispatchEvent(new Event('open')) + + // If redirected to a different origin, set the origin to the new origin. + this.#state.origin = response.urlList[response.urlList.length - 1].origin + + const eventSourceStream = new EventSourceStream({ + eventSourceSettings: this.#state, + push: (event) => { + this.dispatchEvent(createFastMessageEvent( + event.type, + event.options + )) + } + }) + + pipeline(response.body.stream, + eventSourceStream, + (error) => { + if ( + error?.aborted === false + ) { + this.close() + this.dispatchEvent(new Event('error')) + } + }) + } + + this.#controller = fetching(fetchParams) + } + + /** + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model + * @returns {Promise} + */ + async #reconnect () { + // When a user agent is to reestablish the connection, the user agent must + // run the following steps. These steps are run in parallel, not as part of + // a task. (The tasks that it queues, of course, are run like normal tasks + // and not themselves in parallel.) + + // 1. Queue a task to run the following steps: + + // 1. If the readyState attribute is set to CLOSED, abort the task. + if (this.#readyState === CLOSED) return + + // 2. Set the readyState attribute to CONNECTING. + this.#readyState = CONNECTING + + // 3. Fire an event named error at the EventSource object. + this.dispatchEvent(new Event('error')) + + // 2. Wait a delay equal to the reconnection time of the event source. + await delay(this.#state.reconnectionTime) + + // 5. Queue a task to run the following steps: + + // 1. If the EventSource object's readyState attribute is not set to + // CONNECTING, then return. + if (this.#readyState !== CONNECTING) return + + // 2. Let request be the EventSource object's request. + // 3. If the EventSource object's last event ID string is not the empty + // string, then: + // 1. Let lastEventIDValue be the EventSource object's last event ID + // string, encoded as UTF-8. + // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header + // list. + if (this.#state.lastEventId.length) { + this.#request.headersList.set('last-event-id', this.#state.lastEventId, true) + } + + // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section. + this.#connect() + } + + /** + * Closes the connection, if any, and sets the readyState attribute to + * CLOSED. + */ + close () { + webidl.brandCheck(this, EventSource) + + if (this.#readyState === CLOSED) return + this.#readyState = CLOSED + this.#controller.abort() + this.#request = null + } + + get onopen () { + return this.#events.open + } + + set onopen (fn) { + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) + } + + if (typeof fn === 'function') { + this.#events.open = fn + this.addEventListener('open', fn) + } else { + this.#events.open = null + } + } + + get onmessage () { + return this.#events.message + } + + set onmessage (fn) { + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } + + if (typeof fn === 'function') { + this.#events.message = fn + this.addEventListener('message', fn) + } else { + this.#events.message = null + } + } + + get onerror () { + return this.#events.error + } + + set onerror (fn) { + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) + } + + if (typeof fn === 'function') { + this.#events.error = fn + this.addEventListener('error', fn) + } else { + this.#events.error = null + } + } +} + +const constantsPropertyDescriptors = { + CONNECTING: { + __proto__: null, + configurable: false, + enumerable: true, + value: CONNECTING, + writable: false + }, + OPEN: { + __proto__: null, + configurable: false, + enumerable: true, + value: OPEN, + writable: false + }, + CLOSED: { + __proto__: null, + configurable: false, + enumerable: true, + value: CLOSED, + writable: false + } +} + +Object.defineProperties(EventSource, constantsPropertyDescriptors) +Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors) + +Object.defineProperties(EventSource.prototype, { + close: kEnumerableProperty, + onerror: kEnumerableProperty, + onmessage: kEnumerableProperty, + onopen: kEnumerableProperty, + readyState: kEnumerableProperty, + url: kEnumerableProperty, + withCredentials: kEnumerableProperty +}) + +webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([ + { + key: 'withCredentials', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'dispatcher', // undici only + converter: webidl.converters.any + } +]) + +module.exports = { + EventSource, + defaultReconnectionTime +} diff --git a/node_modules/undici/lib/web/eventsource/util.js b/node_modules/undici/lib/web/eventsource/util.js new file mode 100644 index 0000000000000..727d8660e5f1e --- /dev/null +++ b/node_modules/undici/lib/web/eventsource/util.js @@ -0,0 +1,37 @@ +'use strict' + +/** + * Checks if the given value is a valid LastEventId. + * @param {string} value + * @returns {boolean} + */ +function isValidLastEventId (value) { + // LastEventId should not contain U+0000 NULL + return value.indexOf('\u0000') === -1 +} + +/** + * Checks if the given value is a base 10 digit. + * @param {string} value + * @returns {boolean} + */ +function isASCIINumber (value) { + if (value.length === 0) return false + for (let i = 0; i < value.length; i++) { + if (value.charCodeAt(i) < 0x30 || value.charCodeAt(i) > 0x39) return false + } + return true +} + +// https://github.com/nodejs/undici/issues/2664 +function delay (ms) { + return new Promise((resolve) => { + setTimeout(resolve, ms).unref() + }) +} + +module.exports = { + isValidLastEventId, + isASCIINumber, + delay +} diff --git a/node_modules/undici/lib/web/fetch/LICENSE b/node_modules/undici/lib/web/fetch/LICENSE new file mode 100644 index 0000000000000..294350045bbb5 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Ethan Arrowood + +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. diff --git a/node_modules/undici/lib/web/fetch/body.js b/node_modules/undici/lib/web/fetch/body.js new file mode 100644 index 0000000000000..b1c553d4e0ff7 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/body.js @@ -0,0 +1,529 @@ +'use strict' + +const util = require('../../core/util') +const { + ReadableStreamFrom, + isBlobLike, + isReadableStreamLike, + readableStreamClose, + createDeferredPromise, + fullyReadBody, + extractMimeType, + utf8DecodeBytes +} = require('./util') +const { FormData } = require('./formdata') +const { kState } = require('./symbols') +const { webidl } = require('./webidl') +const { Blob } = require('node:buffer') +const assert = require('node:assert') +const { isErrored, isDisturbed } = require('node:stream') +const { isArrayBuffer } = require('node:util/types') +const { serializeAMimeType } = require('./data-url') +const { multipartFormDataParser } = require('./formdata-parser') +let random + +try { + const crypto = require('node:crypto') + random = (max) => crypto.randomInt(0, max) +} catch { + random = (max) => Math.floor(Math.random(max)) +} + +const textEncoder = new TextEncoder() +function noop () {} + +const hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf('v18') !== 0 +let streamRegistry + +if (hasFinalizationRegistry) { + streamRegistry = new FinalizationRegistry((weakRef) => { + const stream = weakRef.deref() + if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) { + stream.cancel('Response object has been garbage collected').catch(noop) + } + }) +} + +// https://fetch.spec.whatwg.org/#concept-bodyinit-extract +function extractBody (object, keepalive = false) { + // 1. Let stream be null. + let stream = null + + // 2. If object is a ReadableStream object, then set stream to object. + if (object instanceof ReadableStream) { + stream = object + } else if (isBlobLike(object)) { + // 3. Otherwise, if object is a Blob object, set stream to the + // result of running object’s get stream. + stream = object.stream() + } else { + // 4. Otherwise, set stream to a new ReadableStream object, and set + // up stream with byte reading support. + stream = new ReadableStream({ + async pull (controller) { + const buffer = typeof source === 'string' ? textEncoder.encode(source) : source + + if (buffer.byteLength) { + controller.enqueue(buffer) + } + + queueMicrotask(() => readableStreamClose(controller)) + }, + start () {}, + type: 'bytes' + }) + } + + // 5. Assert: stream is a ReadableStream object. + assert(isReadableStreamLike(stream)) + + // 6. Let action be null. + let action = null + + // 7. Let source be null. + let source = null + + // 8. Let length be null. + let length = null + + // 9. Let type be null. + let type = null + + // 10. Switch on object: + if (typeof object === 'string') { + // Set source to the UTF-8 encoding of object. + // Note: setting source to a Uint8Array here breaks some mocking assumptions. + source = object + + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8' + } else if (object instanceof URLSearchParams) { + // URLSearchParams + + // spec says to run application/x-www-form-urlencoded on body.list + // this is implemented in Node.js as apart of an URLSearchParams instance toString method + // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 + // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 + + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString() + + // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. + type = 'application/x-www-form-urlencoded;charset=UTF-8' + } else if (isArrayBuffer(object)) { + // BufferSource/ArrayBuffer + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.slice()) + } else if (ArrayBuffer.isView(object)) { + // BufferSource/ArrayBufferView + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) + } else if (util.isFormDataLike(object)) { + const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` + const prefix = `--${boundary}\r\nContent-Disposition: form-data` + + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + const escape = (str) => + str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') + const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') + + // Set action to this step: run the multipart/form-data + // encoding algorithm, with object’s entry list and UTF-8. + // - This ensures that the body is immutable and can't be changed afterwords + // - That the content-length is calculated in advance. + // - And that all parts are pre-encoded and ready to be sent. + + const blobParts = [] + const rn = new Uint8Array([13, 10]) // '\r\n' + length = 0 + let hasUnknownSizeValue = false + + for (const [name, value] of object) { + if (typeof value === 'string') { + const chunk = textEncoder.encode(prefix + + `; name="${escape(normalizeLinefeeds(name))}"` + + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) + blobParts.push(chunk) + length += chunk.byteLength + } else { + const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + + `Content-Type: ${ + value.type || 'application/octet-stream' + }\r\n\r\n`) + blobParts.push(chunk, value, rn) + if (typeof value.size === 'number') { + length += chunk.byteLength + value.size + rn.byteLength + } else { + hasUnknownSizeValue = true + } + } + } + + // CRLF is appended to the body to function with legacy servers and match other implementations. + // https://github.com/curl/curl/blob/3434c6b46e682452973972e8313613dfa58cd690/lib/mime.c#L1029-L1030 + // https://github.com/form-data/form-data/issues/63 + const chunk = textEncoder.encode(`--${boundary}--\r\n`) + blobParts.push(chunk) + length += chunk.byteLength + if (hasUnknownSizeValue) { + length = null + } + + // Set source to object. + source = object + + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream() + } else { + yield part + } + } + } + + // Set type to `multipart/form-data; boundary=`, + // followed by the multipart/form-data boundary string generated + // by the multipart/form-data encoding algorithm. + type = `multipart/form-data; boundary=${boundary}` + } else if (isBlobLike(object)) { + // Blob + + // Set source to object. + source = object + + // Set length to object’s size. + length = object.size + + // If object’s type attribute is not the empty byte sequence, set + // type to its value. + if (object.type) { + type = object.type + } + } else if (typeof object[Symbol.asyncIterator] === 'function') { + // If keepalive is true, then throw a TypeError. + if (keepalive) { + throw new TypeError('keepalive') + } + + // If object is disturbed or locked, then throw a TypeError. + if (util.isDisturbed(object) || object.locked) { + throw new TypeError( + 'Response body object should not be disturbed or locked' + ) + } + + stream = + object instanceof ReadableStream ? object : ReadableStreamFrom(object) + } + + // 11. If source is a byte sequence, then set action to a + // step that returns source and length to source’s length. + if (typeof source === 'string' || util.isBuffer(source)) { + length = Buffer.byteLength(source) + } + + // 12. If action is non-null, then run these steps in in parallel: + if (action != null) { + // Run action. + let iterator + stream = new ReadableStream({ + async start () { + iterator = action(object)[Symbol.asyncIterator]() + }, + async pull (controller) { + const { value, done } = await iterator.next() + if (done) { + // When running action is done, close stream. + queueMicrotask(() => { + controller.close() + controller.byobRequest?.respond(0) + }) + } else { + // Whenever one or more bytes are available and stream is not errored, + // enqueue a Uint8Array wrapping an ArrayBuffer containing the available + // bytes into stream. + if (!isErrored(stream)) { + const buffer = new Uint8Array(value) + if (buffer.byteLength) { + controller.enqueue(buffer) + } + } + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + }, + type: 'bytes' + }) + } + + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length } + + // 14. Return (body, type). + return [body, type] +} + +// https://fetch.spec.whatwg.org/#bodyinit-safely-extract +function safelyExtractBody (object, keepalive = false) { + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: + + // 1. If object is a ReadableStream object, then: + if (object instanceof ReadableStream) { + // Assert: object is neither disturbed nor locked. + // istanbul ignore next + assert(!util.isDisturbed(object), 'The body has already been consumed.') + // istanbul ignore next + assert(!object.locked, 'The stream is locked.') + } + + // 2. Return the results of extracting object. + return extractBody(object, keepalive) +} + +function cloneBody (instance, body) { + // To clone a body body, run these steps: + + // https://fetch.spec.whatwg.org/#concept-body-clone + + // 1. Let « out1, out2 » be the result of teeing body’s stream. + const [out1, out2] = body.stream.tee() + + // 2. Set body’s stream to out1. + body.stream = out1 + + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: out2, + length: body.length, + source: body.source + } +} + +function throwIfAborted (state) { + if (state.aborted) { + throw new DOMException('The operation was aborted.', 'AbortError') + } +} + +function bodyMixinMethods (instance) { + const methods = { + blob () { + // The blob() method steps are to return the result of + // running consume body with this and the following step + // given a byte sequence bytes: return a Blob whose + // contents are bytes and whose type attribute is this’s + // MIME type. + return consumeBody(this, (bytes) => { + let mimeType = bodyMimeType(this) + + if (mimeType === null) { + mimeType = '' + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType) + } + + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance) + }, + + arrayBuffer () { + // The arrayBuffer() method steps are to return the result + // of running consume body with this and the following step + // given a byte sequence bytes: return a new ArrayBuffer + // whose contents are bytes. + return consumeBody(this, (bytes) => { + return new Uint8Array(bytes).buffer + }, instance) + }, + + text () { + // The text() method steps are to return the result of running + // consume body with this and UTF-8 decode. + return consumeBody(this, utf8DecodeBytes, instance) + }, + + json () { + // The json() method steps are to return the result of running + // consume body with this and parse JSON from bytes. + return consumeBody(this, parseJSONFromBytes, instance) + }, + + formData () { + // The formData() method steps are to return the result of running + // consume body with this and the following step given a byte sequence bytes: + return consumeBody(this, (value) => { + // 1. Let mimeType be the result of get the MIME type with this. + const mimeType = bodyMimeType(this) + + // 2. If mimeType is non-null, then switch on mimeType’s essence and run + // the corresponding steps: + if (mimeType !== null) { + switch (mimeType.essence) { + case 'multipart/form-data': { + // 1. ... [long step] + const parsed = multipartFormDataParser(value, mimeType) + + // 2. If that fails for some reason, then throw a TypeError. + if (parsed === 'failure') { + throw new TypeError('Failed to parse body as FormData.') + } + + // 3. Return a new FormData object, appending each entry, + // resulting from the parsing operation, to its entry list. + const fd = new FormData() + fd[kState] = parsed + + return fd + } + case 'application/x-www-form-urlencoded': { + // 1. Let entries be the result of parsing bytes. + const entries = new URLSearchParams(value.toString()) + + // 2. If entries is failure, then throw a TypeError. + + // 3. Return a new FormData object whose entry list is entries. + const fd = new FormData() + + for (const [name, value] of entries) { + fd.append(name, value) + } + + return fd + } + } + } + + // 3. Throw a TypeError. + throw new TypeError( + 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".' + ) + }, instance) + }, + + bytes () { + // The bytes() method steps are to return the result of running consume body + // with this and the following step given a byte sequence bytes: return the + // result of creating a Uint8Array from bytes in this’s relevant realm. + return consumeBody(this, (bytes) => { + return new Uint8Array(bytes) + }, instance) + } + } + + return methods +} + +function mixinBody (prototype) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param {Response|Request} object + * @param {(value: unknown) => unknown} convertBytesToJSValue + * @param {Response|Request} instance + */ +async function consumeBody (object, convertBytesToJSValue, instance) { + webidl.brandCheck(object, instance) + + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(object)) { + throw new TypeError('Body is unusable: Body has already been read') + } + + throwIfAborted(object[kState]) + + // 2. Let promise be a new promise. + const promise = createDeferredPromise() + + // 3. Let errorSteps given error be to reject promise with error. + const errorSteps = (error) => promise.reject(error) + + // 4. Let successSteps given a byte sequence data be to resolve + // promise with the result of running convertBytesToJSValue + // with data. If that threw an exception, then run errorSteps + // with that exception. + const successSteps = (data) => { + try { + promise.resolve(convertBytesToJSValue(data)) + } catch (e) { + errorSteps(e) + } + } + + // 5. If object’s body is null, then run successSteps with an + // empty byte sequence. + if (object[kState].body == null) { + successSteps(Buffer.allocUnsafe(0)) + return promise.promise + } + + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + await fullyReadBody(object[kState].body, successSteps, errorSteps) + + // 7. Return promise. + return promise.promise +} + +// https://fetch.spec.whatwg.org/#body-unusable +function bodyUnusable (object) { + const body = object[kState].body + + // An object including the Body interface mixin is + // said to be unusable if its body is non-null and + // its body’s stream is disturbed or locked. + return body != null && (body.stream.locked || util.isDisturbed(body.stream)) +} + +/** + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes + */ +function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-mime-type + * @param {import('./response').Response|import('./request').Request} requestOrResponse + */ +function bodyMimeType (requestOrResponse) { + // 1. Let headers be null. + // 2. If requestOrResponse is a Request object, then set headers to requestOrResponse’s request’s header list. + // 3. Otherwise, set headers to requestOrResponse’s response’s header list. + /** @type {import('./headers').HeadersList} */ + const headers = requestOrResponse[kState].headersList + + // 4. Let mimeType be the result of extracting a MIME type from headers. + const mimeType = extractMimeType(headers) + + // 5. If mimeType is failure, then return null. + if (mimeType === 'failure') { + return null + } + + // 6. Return mimeType. + return mimeType +} + +module.exports = { + extractBody, + safelyExtractBody, + cloneBody, + mixinBody, + streamRegistry, + hasFinalizationRegistry, + bodyUnusable +} diff --git a/node_modules/undici/lib/web/fetch/constants.js b/node_modules/undici/lib/web/fetch/constants.js new file mode 100644 index 0000000000000..1f285e06283e1 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/constants.js @@ -0,0 +1,124 @@ +'use strict' + +const corsSafeListedMethods = /** @type {const} */ (['GET', 'HEAD', 'POST']) +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) + +const nullBodyStatus = /** @type {const} */ ([101, 204, 205, 304]) + +const redirectStatus = /** @type {const} */ ([301, 302, 303, 307, 308]) +const redirectStatusSet = new Set(redirectStatus) + +/** + * @see https://fetch.spec.whatwg.org/#block-bad-port + */ +const badPorts = /** @type {const} */ ([ + '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', + '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', + '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', + '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', + '2049', '3659', '4045', '4190', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6679', + '6697', '10080' +]) +const badPortsSet = new Set(badPorts) + +/** + * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policies + */ +const referrerPolicy = /** @type {const} */ ([ + '', + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' +]) +const referrerPolicySet = new Set(referrerPolicy) + +const requestRedirect = /** @type {const} */ (['follow', 'manual', 'error']) + +const safeMethods = /** @type {const} */ (['GET', 'HEAD', 'OPTIONS', 'TRACE']) +const safeMethodsSet = new Set(safeMethods) + +const requestMode = /** @type {const} */ (['navigate', 'same-origin', 'no-cors', 'cors']) + +const requestCredentials = /** @type {const} */ (['omit', 'same-origin', 'include']) + +const requestCache = /** @type {const} */ ([ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' +]) + +/** + * @see https://fetch.spec.whatwg.org/#request-body-header-name + */ +const requestBodyHeader = /** @type {const} */ ([ + 'content-encoding', + 'content-language', + 'content-location', + 'content-type', + // See https://github.com/nodejs/undici/issues/2021 + // 'Content-Length' is a forbidden header name, which is typically + // removed in the Headers implementation. However, undici doesn't + // filter out headers, so we add it here. + 'content-length' +]) + +/** + * @see https://fetch.spec.whatwg.org/#enumdef-requestduplex + */ +const requestDuplex = /** @type {const} */ ([ + 'half' +]) + +/** + * @see http://fetch.spec.whatwg.org/#forbidden-method + */ +const forbiddenMethods = /** @type {const} */ (['CONNECT', 'TRACE', 'TRACK']) +const forbiddenMethodsSet = new Set(forbiddenMethods) + +const subresource = /** @type {const} */ ([ + 'audio', + 'audioworklet', + 'font', + 'image', + 'manifest', + 'paintworklet', + 'script', + 'style', + 'track', + 'video', + 'xslt', + '' +]) +const subresourceSet = new Set(subresource) + +module.exports = { + subresource, + forbiddenMethods, + requestBodyHeader, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + redirectStatus, + corsSafeListedMethods, + nullBodyStatus, + safeMethods, + badPorts, + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet +} diff --git a/node_modules/undici/lib/web/fetch/data-url.js b/node_modules/undici/lib/web/fetch/data-url.js new file mode 100644 index 0000000000000..7a74db6bde89c --- /dev/null +++ b/node_modules/undici/lib/web/fetch/data-url.js @@ -0,0 +1,744 @@ +'use strict' + +const assert = require('node:assert') + +const encoder = new TextEncoder() + +/** + * @see https://mimesniff.spec.whatwg.org/#http-token-code-point + */ +const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\-.^_|~A-Za-z0-9]+$/ +const HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/ // eslint-disable-line +const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line +/** + * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point + */ +const HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/ // eslint-disable-line + +// https://fetch.spec.whatwg.org/#data-url-processor +/** @param {URL} dataURL */ +function dataURLProcessor (dataURL) { + // 1. Assert: dataURL’s scheme is "data". + assert(dataURL.protocol === 'data:') + + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true) + + // 3. Remove the leading "data:" string from input. + input = input.slice(5) + + // 4. Let position point at the start of input. + const position = { position: 0 } + + // 5. Let mimeType be the result of collecting a + // sequence of code points that are not equal + // to U+002C (,), given position. + let mimeType = collectASequenceOfCodePointsFast( + ',', + input, + position + ) + + // 6. Strip leading and trailing ASCII whitespace + // from mimeType. + // Undici implementation note: we need to store the + // length because if the mimetype has spaces removed, + // the wrong amount will be sliced from the input in + // step #9 + const mimeTypeLength = mimeType.length + mimeType = removeASCIIWhitespace(mimeType, true, true) + + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' + } + + // 8. Advance position by 1. + position.position++ + + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1) + + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody) + + // 11. If mimeType ends with U+003B (;), followed by + // zero or more U+0020 SPACE, followed by an ASCII + // case-insensitive match for "base64", then: + if (/;(\u0020){0,}base64$/i.test(mimeType)) { + // 1. Let stringBody be the isomorphic decode of body. + const stringBody = isomorphicDecode(body) + + // 2. Set body to the forgiving-base64 decode of + // stringBody. + body = forgivingBase64(stringBody) + + // 3. If body is failure, then return failure. + if (body === 'failure') { + return 'failure' + } + + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6) + + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020)+$/, '') + + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1) + } + + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType + } + + // 13. Let mimeTypeRecord be the result of parsing + // mimeType. + let mimeTypeRecord = parseMIMEType(mimeType) + + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + } + + // 15. Return a new data: URL struct whose MIME + // type is mimeTypeRecord and body is body. + // https://fetch.spec.whatwg.org/#data-url-struct + return { mimeType: mimeTypeRecord, body } +} + +// https://url.spec.whatwg.org/#concept-url-serializer +/** + * @param {URL} url + * @param {boolean} excludeFragment + */ +function URLSerializer (url, excludeFragment = false) { + if (!excludeFragment) { + return url.href + } + + const href = url.href + const hashLength = url.hash.length + + const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength) + + if (!hashLength && href.endsWith('#')) { + return serialized.slice(0, -1) + } + + return serialized +} + +// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points +/** + * @param {(char: string) => boolean} condition + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePoints (condition, input, position) { + // 1. Let result be the empty string. + let result = '' + + // 2. While position doesn’t point past the end of input and the + // code point at position within input meets the condition condition: + while (position.position < input.length && condition(input[position.position])) { + // 1. Append that code point to the end of result. + result += input[position.position] + + // 2. Advance position by 1. + position.position++ + } + + // 3. Return result. + return result +} + +/** + * A faster collectASequenceOfCodePoints that only works when comparing a single character. + * @param {string} char + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePointsFast (char, input, position) { + const idx = input.indexOf(char, position.position) + const start = position.position + + if (idx === -1) { + position.position = input.length + return input.slice(start) + } + + position.position = idx + return input.slice(start, position.position) +} + +// https://url.spec.whatwg.org/#string-percent-decode +/** @param {string} input */ +function stringPercentDecode (input) { + // 1. Let bytes be the UTF-8 encoding of input. + const bytes = encoder.encode(input) + + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) +} + +/** + * @param {number} byte + */ +function isHexCharByte (byte) { + // 0-9 A-F a-f + return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66) +} + +/** + * @param {number} byte + */ +function hexByteToNumber (byte) { + return ( + // 0-9 + byte >= 0x30 && byte <= 0x39 + ? (byte - 48) + // Convert to uppercase + // ((byte & 0xDF) - 65) + 10 + : ((byte & 0xDF) - 55) + ) +} + +// https://url.spec.whatwg.org/#percent-decode +/** @param {Uint8Array} input */ +function percentDecode (input) { + const length = input.length + // 1. Let output be an empty byte sequence. + /** @type {Uint8Array} */ + const output = new Uint8Array(length) + let j = 0 + // 2. For each byte byte in input: + for (let i = 0; i < length; ++i) { + const byte = input[i] + + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output[j++] = byte + + // 2. Otherwise, if byte is 0x25 (%) and the next two bytes + // after byte in input are not in the ranges + // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), + // and 0x61 (a) to 0x66 (f), all inclusive, append byte + // to output. + } else if ( + byte === 0x25 && + !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2])) + ) { + output[j++] = 0x25 + + // 3. Otherwise: + } else { + // 1. Let bytePoint be the two bytes after byte in input, + // decoded, and then interpreted as hexadecimal number. + // 2. Append a byte whose value is bytePoint to output. + output[j++] = (hexByteToNumber(input[i + 1]) << 4) | hexByteToNumber(input[i + 2]) + + // 3. Skip the next two bytes in input. + i += 2 + } + } + + // 3. Return output. + return length === j ? output : output.subarray(0, j) +} + +// https://mimesniff.spec.whatwg.org/#parse-a-mime-type +/** @param {string} input */ +function parseMIMEType (input) { + // 1. Remove any leading and trailing HTTP whitespace + // from input. + input = removeHTTPWhitespace(input, true, true) + + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 } + + // 3. Let type be the result of collecting a sequence + // of code points that are not U+002F (/) from + // input, given position. + const type = collectASequenceOfCodePointsFast( + '/', + input, + position + ) + + // 4. If type is the empty string or does not solely + // contain HTTP token code points, then return failure. + // https://mimesniff.spec.whatwg.org/#http-token-code-point + if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { + return 'failure' + } + + // 5. If position is past the end of input, then return + // failure + if (position.position > input.length) { + return 'failure' + } + + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++ + + // 7. Let subtype be the result of collecting a sequence of + // code points that are not U+003B (;) from input, given + // position. + let subtype = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true) + + // 9. If subtype is the empty string or does not solely + // contain HTTP token code points, then return failure. + if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { + return 'failure' + } + + const typeLowercase = type.toLowerCase() + const subtypeLowercase = subtype.toLowerCase() + + // 10. Let mimeType be a new MIME type record whose type + // is type, in ASCII lowercase, and subtype is subtype, + // in ASCII lowercase. + // https://mimesniff.spec.whatwg.org/#mime-type + const mimeType = { + type: typeLowercase, + subtype: subtypeLowercase, + /** @type {Map} */ + parameters: new Map(), + // https://mimesniff.spec.whatwg.org/#mime-type-essence + essence: `${typeLowercase}/${subtypeLowercase}` + } + + // 11. While position is not past the end of input: + while (position.position < input.length) { + // 1. Advance position by 1. (This skips past U+003B (;).) + position.position++ + + // 2. Collect a sequence of code points that are HTTP + // whitespace from input given position. + collectASequenceOfCodePoints( + // https://fetch.spec.whatwg.org/#http-whitespace + char => HTTP_WHITESPACE_REGEX.test(char), + input, + position + ) + + // 3. Let parameterName be the result of collecting a + // sequence of code points that are not U+003B (;) + // or U+003D (=) from input, given position. + let parameterName = collectASequenceOfCodePoints( + (char) => char !== ';' && char !== '=', + input, + position + ) + + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase() + + // 5. If position is not past the end of input, then: + if (position.position < input.length) { + // 1. If the code point at position within input is + // U+003B (;), then continue. + if (input[position.position] === ';') { + continue + } + + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++ + } + + // 6. If position is past the end of input, then break. + if (position.position > input.length) { + break + } + + // 7. Let parameterValue be null. + let parameterValue = null + + // 8. If the code point at position within input is + // U+0022 ("), then: + if (input[position.position] === '"') { + // 1. Set parameterValue to the result of collecting + // an HTTP quoted string from input, given position + // and the extract-value flag. + parameterValue = collectAnHTTPQuotedString(input, position, true) + + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 9. Otherwise: + } else { + // 1. Set parameterValue to the result of collecting + // a sequence of code points that are not U+003B (;) + // from input, given position. + parameterValue = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 2. Remove any trailing HTTP whitespace from parameterValue. + parameterValue = removeHTTPWhitespace(parameterValue, false, true) + + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue + } + } + + // 10. If all of the following are true + // - parameterName is not the empty string + // - parameterName solely contains HTTP token code points + // - parameterValue solely contains HTTP quoted-string token code points + // - mimeType’s parameters[parameterName] does not exist + // then set mimeType’s parameters[parameterName] to parameterValue. + if ( + parameterName.length !== 0 && + HTTP_TOKEN_CODEPOINTS.test(parameterName) && + (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && + !mimeType.parameters.has(parameterName) + ) { + mimeType.parameters.set(parameterName, parameterValue) + } + } + + // 12. Return mimeType. + return mimeType +} + +// https://infra.spec.whatwg.org/#forgiving-base64-decode +/** @param {string} data */ +function forgivingBase64 (data) { + // 1. Remove all ASCII whitespace from data. + data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') // eslint-disable-line + + let dataLength = data.length + // 2. If data’s code point length divides by 4 leaving + // no remainder, then: + if (dataLength % 4 === 0) { + // 1. If data ends with one or two U+003D (=) code points, + // then remove them from data. + if (data.charCodeAt(dataLength - 1) === 0x003D) { + --dataLength + if (data.charCodeAt(dataLength - 1) === 0x003D) { + --dataLength + } + } + } + + // 3. If data’s code point length divides by 4 leaving + // a remainder of 1, then return failure. + if (dataLength % 4 === 1) { + return 'failure' + } + + // 4. If data contains a code point that is not one of + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // then return failure. + if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) { + return 'failure' + } + + const buffer = Buffer.from(data, 'base64') + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) +} + +// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string +// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string +/** + * @param {string} input + * @param {{ position: number }} position + * @param {boolean?} extractValue + */ +function collectAnHTTPQuotedString (input, position, extractValue) { + // 1. Let positionStart be position. + const positionStart = position.position + + // 2. Let value be the empty string. + let value = '' + + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"') + + // 4. Advance position by 1. + position.position++ + + // 5. While true: + while (true) { + // 1. Append the result of collecting a sequence of code points + // that are not U+0022 (") or U+005C (\) from input, given + // position, to value. + value += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== '\\', + input, + position + ) + + // 2. If position is past the end of input, then break. + if (position.position >= input.length) { + break + } + + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position] + + // 4. Advance position by 1. + position.position++ + + // 5. If quoteOrBackslash is U+005C (\), then: + if (quoteOrBackslash === '\\') { + // 1. If position is past the end of input, then append + // U+005C (\) to value and break. + if (position.position >= input.length) { + value += '\\' + break + } + + // 2. Append the code point at position within input to value. + value += input[position.position] + + // 3. Advance position by 1. + position.position++ + + // 6. Otherwise: + } else { + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"') + + // 2. Break. + break + } + } + + // 6. If the extract-value flag is set, then return value. + if (extractValue) { + return value + } + + // 7. Return the code points from positionStart to position, + // inclusive, within input. + return input.slice(positionStart, position.position) +} + +/** + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +function serializeAMimeType (mimeType) { + assert(mimeType !== 'failure') + const { parameters, essence } = mimeType + + // 1. Let serialization be the concatenation of mimeType’s + // type, U+002F (/), and mimeType’s subtype. + let serialization = essence + + // 2. For each name → value of mimeType’s parameters: + for (let [name, value] of parameters.entries()) { + // 1. Append U+003B (;) to serialization. + serialization += ';' + + // 2. Append name to serialization. + serialization += name + + // 3. Append U+003D (=) to serialization. + serialization += '=' + + // 4. If value does not solely contain HTTP token code + // points or value is the empty string, then: + if (!HTTP_TOKEN_CODEPOINTS.test(value)) { + // 1. Precede each occurrence of U+0022 (") or + // U+005C (\) in value with U+005C (\). + value = value.replace(/(\\|")/g, '\\$1') + + // 2. Prepend U+0022 (") to value. + value = '"' + value + + // 3. Append U+0022 (") to value. + value += '"' + } + + // 5. Append value to serialization. + serialization += value + } + + // 3. Return serialization. + return serialization +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {number} char + */ +function isHTTPWhiteSpace (char) { + // "\r\n\t " + return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x020 +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} str + * @param {boolean} [leading=true] + * @param {boolean} [trailing=true] + */ +function removeHTTPWhitespace (str, leading = true, trailing = true) { + return removeChars(str, leading, trailing, isHTTPWhiteSpace) +} + +/** + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * @param {number} char + */ +function isASCIIWhitespace (char) { + // "\r\n\t\f " + return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x00c || char === 0x020 +} + +/** + * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace + * @param {string} str + * @param {boolean} [leading=true] + * @param {boolean} [trailing=true] + */ +function removeASCIIWhitespace (str, leading = true, trailing = true) { + return removeChars(str, leading, trailing, isASCIIWhitespace) +} + +/** + * @param {string} str + * @param {boolean} leading + * @param {boolean} trailing + * @param {(charCode: number) => boolean} predicate + * @returns + */ +function removeChars (str, leading, trailing, predicate) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + while (lead < str.length && predicate(str.charCodeAt(lead))) lead++ + } + + if (trailing) { + while (trail > 0 && predicate(str.charCodeAt(trail))) trail-- + } + + return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1) +} + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-decode + * @param {Uint8Array} input + * @returns {string} + */ +function isomorphicDecode (input) { + // 1. To isomorphic decode a byte sequence input, return a string whose code point + // length is equal to input’s length and whose code points have the same values + // as the values of input’s bytes, in the same order. + const length = input.length + if ((2 << 15) - 1 > length) { + return String.fromCharCode.apply(null, input) + } + let result = ''; let i = 0 + let addition = (2 << 15) - 1 + while (i < length) { + if (i + addition > length) { + addition = length - i + } + result += String.fromCharCode.apply(null, input.subarray(i, i += addition)) + } + return result +} + +/** + * @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type + * @param {Exclude, 'failure'>} mimeType + */ +function minimizeSupportedMimeType (mimeType) { + switch (mimeType.essence) { + case 'application/ecmascript': + case 'application/javascript': + case 'application/x-ecmascript': + case 'application/x-javascript': + case 'text/ecmascript': + case 'text/javascript': + case 'text/javascript1.0': + case 'text/javascript1.1': + case 'text/javascript1.2': + case 'text/javascript1.3': + case 'text/javascript1.4': + case 'text/javascript1.5': + case 'text/jscript': + case 'text/livescript': + case 'text/x-ecmascript': + case 'text/x-javascript': + // 1. If mimeType is a JavaScript MIME type, then return "text/javascript". + return 'text/javascript' + case 'application/json': + case 'text/json': + // 2. If mimeType is a JSON MIME type, then return "application/json". + return 'application/json' + case 'image/svg+xml': + // 3. If mimeType’s essence is "image/svg+xml", then return "image/svg+xml". + return 'image/svg+xml' + case 'text/xml': + case 'application/xml': + // 4. If mimeType is an XML MIME type, then return "application/xml". + return 'application/xml' + } + + // 2. If mimeType is a JSON MIME type, then return "application/json". + if (mimeType.subtype.endsWith('+json')) { + return 'application/json' + } + + // 4. If mimeType is an XML MIME type, then return "application/xml". + if (mimeType.subtype.endsWith('+xml')) { + return 'application/xml' + } + + // 5. If mimeType is supported by the user agent, then return mimeType’s essence. + // Technically, node doesn't support any mimetypes. + + // 6. Return the empty string. + return '' +} + +module.exports = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType, + removeChars, + removeHTTPWhitespace, + minimizeSupportedMimeType, + HTTP_TOKEN_CODEPOINTS, + isomorphicDecode +} diff --git a/node_modules/undici/lib/web/fetch/dispatcher-weakref.js b/node_modules/undici/lib/web/fetch/dispatcher-weakref.js new file mode 100644 index 0000000000000..6ac5f37499257 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/dispatcher-weakref.js @@ -0,0 +1,46 @@ +'use strict' + +const { kConnected, kSize } = require('../../core/symbols') + +class CompatWeakRef { + constructor (value) { + this.value = value + } + + deref () { + return this.value[kConnected] === 0 && this.value[kSize] === 0 + ? undefined + : this.value + } +} + +class CompatFinalizer { + constructor (finalizer) { + this.finalizer = finalizer + } + + register (dispatcher, key) { + if (dispatcher.on) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key) + } + }) + } + } + + unregister (key) {} +} + +module.exports = function () { + // FIXME: remove workaround when the Node bug is backported to v18 + // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 + if (process.env.NODE_V8_COVERAGE && process.version.startsWith('v18')) { + process._rawDebug('Using compatibility WeakRef and FinalizationRegistry') + return { + WeakRef: CompatWeakRef, + FinalizationRegistry: CompatFinalizer + } + } + return { WeakRef, FinalizationRegistry } +} diff --git a/node_modules/undici/lib/web/fetch/file.js b/node_modules/undici/lib/web/fetch/file.js new file mode 100644 index 0000000000000..31ba40718ec27 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/file.js @@ -0,0 +1,126 @@ +'use strict' + +const { Blob, File } = require('node:buffer') +const { kState } = require('./symbols') +const { webidl } = require('./webidl') + +// TODO(@KhafraDev): remove +class FileLike { + constructor (blobLike, fileName, options = {}) { + // TODO: argument idl type check + + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + + // 2. Let n be the fileName argument to the constructor. + const n = fileName + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // TODO + const t = options.type + + // 2. Convert every character in t to ASCII lowercase. + // TODO + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + const d = options.lastModified ?? Date.now() + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + this[kState] = { + blobLike, + name: n, + type: t, + lastModified: d + } + } + + stream (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.stream(...args) + } + + arrayBuffer (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.arrayBuffer(...args) + } + + slice (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.slice(...args) + } + + text (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.text(...args) + } + + get size () { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.size + } + + get type () { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.type + } + + get name () { + webidl.brandCheck(this, FileLike) + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, FileLike) + + return this[kState].lastModified + } + + get [Symbol.toStringTag] () { + return 'File' + } +} + +webidl.converters.Blob = webidl.interfaceConverter(Blob) + +// If this function is moved to ./util.js, some tools (such as +// rollup) will warn about circular dependencies. See: +// https://github.com/nodejs/undici/issues/1629 +function isFileLike (object) { + return ( + (object instanceof File) || + ( + object && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + object[Symbol.toStringTag] === 'File' + ) + ) +} + +module.exports = { FileLike, isFileLike } diff --git a/node_modules/undici/lib/web/fetch/formdata-parser.js b/node_modules/undici/lib/web/fetch/formdata-parser.js new file mode 100644 index 0000000000000..315a4626da577 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/formdata-parser.js @@ -0,0 +1,474 @@ +'use strict' + +const { isUSVString, bufferToLowerCasedHeaderName } = require('../../core/util') +const { utf8DecodeBytes } = require('./util') +const { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = require('./data-url') +const { isFileLike } = require('./file') +const { makeEntry } = require('./formdata') +const assert = require('node:assert') +const { File: NodeFile } = require('node:buffer') + +const File = globalThis.File ?? NodeFile + +const formDataNameBuffer = Buffer.from('form-data; name="') +const filenameBuffer = Buffer.from('; filename') +const dd = Buffer.from('--') +const ddcrlf = Buffer.from('--\r\n') + +/** + * @param {string} chars + */ +function isAsciiString (chars) { + for (let i = 0; i < chars.length; ++i) { + if ((chars.charCodeAt(i) & ~0x7F) !== 0) { + return false + } + } + return true +} + +/** + * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-boundary + * @param {string} boundary + */ +function validateBoundary (boundary) { + const length = boundary.length + + // - its length is greater or equal to 27 and lesser or equal to 70, and + if (length < 27 || length > 70) { + return false + } + + // - it is composed by bytes in the ranges 0x30 to 0x39, 0x41 to 0x5A, or + // 0x61 to 0x7A, inclusive (ASCII alphanumeric), or which are 0x27 ('), + // 0x2D (-) or 0x5F (_). + for (let i = 0; i < length; ++i) { + const cp = boundary.charCodeAt(i) + + if (!( + (cp >= 0x30 && cp <= 0x39) || + (cp >= 0x41 && cp <= 0x5a) || + (cp >= 0x61 && cp <= 0x7a) || + cp === 0x27 || + cp === 0x2d || + cp === 0x5f + )) { + return false + } + } + + return true +} + +/** + * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-parser + * @param {Buffer} input + * @param {ReturnType} mimeType + */ +function multipartFormDataParser (input, mimeType) { + // 1. Assert: mimeType’s essence is "multipart/form-data". + assert(mimeType !== 'failure' && mimeType.essence === 'multipart/form-data') + + const boundaryString = mimeType.parameters.get('boundary') + + // 2. If mimeType’s parameters["boundary"] does not exist, return failure. + // Otherwise, let boundary be the result of UTF-8 decoding mimeType’s + // parameters["boundary"]. + if (boundaryString === undefined) { + return 'failure' + } + + const boundary = Buffer.from(`--${boundaryString}`, 'utf8') + + // 3. Let entry list be an empty entry list. + const entryList = [] + + // 4. Let position be a pointer to a byte in input, initially pointing at + // the first byte. + const position = { position: 0 } + + // Note: undici addition, allows leading and trailing CRLFs. + while (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { + position.position += 2 + } + + let trailing = input.length + + while (input[trailing - 1] === 0x0a && input[trailing - 2] === 0x0d) { + trailing -= 2 + } + + if (trailing !== input.length) { + input = input.subarray(0, trailing) + } + + // 5. While true: + while (true) { + // 5.1. If position points to a sequence of bytes starting with 0x2D 0x2D + // (`--`) followed by boundary, advance position by 2 + the length of + // boundary. Otherwise, return failure. + // Note: boundary is padded with 2 dashes already, no need to add 2. + if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) { + position.position += boundary.length + } else { + return 'failure' + } + + // 5.2. If position points to the sequence of bytes 0x2D 0x2D 0x0D 0x0A + // (`--` followed by CR LF) followed by the end of input, return entry list. + // Note: a body does NOT need to end with CRLF. It can end with --. + if ( + (position.position === input.length - 2 && bufferStartsWith(input, dd, position)) || + (position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position)) + ) { + return entryList + } + + // 5.3. If position does not point to a sequence of bytes starting with 0x0D + // 0x0A (CR LF), return failure. + if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { + return 'failure' + } + + // 5.4. Advance position by 2. (This skips past the newline.) + position.position += 2 + + // 5.5. Let name, filename and contentType be the result of parsing + // multipart/form-data headers on input and position, if the result + // is not failure. Otherwise, return failure. + const result = parseMultipartFormDataHeaders(input, position) + + if (result === 'failure') { + return 'failure' + } + + let { name, filename, contentType, encoding } = result + + // 5.6. Advance position by 2. (This skips past the empty line that marks + // the end of the headers.) + position.position += 2 + + // 5.7. Let body be the empty byte sequence. + let body + + // 5.8. Body loop: While position is not past the end of input: + // TODO: the steps here are completely wrong + { + const boundaryIndex = input.indexOf(boundary.subarray(2), position.position) + + if (boundaryIndex === -1) { + return 'failure' + } + + body = input.subarray(position.position, boundaryIndex - 4) + + position.position += body.length + + // Note: position must be advanced by the body's length before being + // decoded, otherwise the parsing will fail. + if (encoding === 'base64') { + body = Buffer.from(body.toString(), 'base64') + } + } + + // 5.9. If position does not point to a sequence of bytes starting with + // 0x0D 0x0A (CR LF), return failure. Otherwise, advance position by 2. + if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { + return 'failure' + } else { + position.position += 2 + } + + // 5.10. If filename is not null: + let value + + if (filename !== null) { + // 5.10.1. If contentType is null, set contentType to "text/plain". + contentType ??= 'text/plain' + + // 5.10.2. If contentType is not an ASCII string, set contentType to the empty string. + + // Note: `buffer.isAscii` can be used at zero-cost, but converting a string to a buffer is a high overhead. + // Content-Type is a relatively small string, so it is faster to use `String#charCodeAt`. + if (!isAsciiString(contentType)) { + contentType = '' + } + + // 5.10.3. Let value be a new File object with name filename, type contentType, and body body. + value = new File([body], filename, { type: contentType }) + } else { + // 5.11. Otherwise: + + // 5.11.1. Let value be the UTF-8 decoding without BOM of body. + value = utf8DecodeBytes(Buffer.from(body)) + } + + // 5.12. Assert: name is a scalar value string and value is either a scalar value string or a File object. + assert(isUSVString(name)) + assert((typeof value === 'string' && isUSVString(value)) || isFileLike(value)) + + // 5.13. Create an entry with name and value, and append it to entry list. + entryList.push(makeEntry(name, value, filename)) + } +} + +/** + * @see https://andreubotella.github.io/multipart-form-data/#parse-multipart-form-data-headers + * @param {Buffer} input + * @param {{ position: number }} position + */ +function parseMultipartFormDataHeaders (input, position) { + // 1. Let name, filename and contentType be null. + let name = null + let filename = null + let contentType = null + let encoding = null + + // 2. While true: + while (true) { + // 2.1. If position points to a sequence of bytes starting with 0x0D 0x0A (CR LF): + if (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { + // 2.1.1. If name is null, return failure. + if (name === null) { + return 'failure' + } + + // 2.1.2. Return name, filename and contentType. + return { name, filename, contentType, encoding } + } + + // 2.2. Let header name be the result of collecting a sequence of bytes that are + // not 0x0A (LF), 0x0D (CR) or 0x3A (:), given position. + let headerName = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d && char !== 0x3a, + input, + position + ) + + // 2.3. Remove any HTTP tab or space bytes from the start or end of header name. + headerName = removeChars(headerName, true, true, (char) => char === 0x9 || char === 0x20) + + // 2.4. If header name does not match the field-name token production, return failure. + if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) { + return 'failure' + } + + // 2.5. If the byte at position is not 0x3A (:), return failure. + if (input[position.position] !== 0x3a) { + return 'failure' + } + + // 2.6. Advance position by 1. + position.position++ + + // 2.7. Collect a sequence of bytes that are HTTP tab or space bytes given position. + // (Do nothing with those bytes.) + collectASequenceOfBytes( + (char) => char === 0x20 || char === 0x09, + input, + position + ) + + // 2.8. Byte-lowercase header name and switch on the result: + switch (bufferToLowerCasedHeaderName(headerName)) { + case 'content-disposition': { + // 1. Set name and filename to null. + name = filename = null + + // 2. If position does not point to a sequence of bytes starting with + // `form-data; name="`, return failure. + if (!bufferStartsWith(input, formDataNameBuffer, position)) { + return 'failure' + } + + // 3. Advance position so it points at the byte after the next 0x22 (") + // byte (the one in the sequence of bytes matched above). + position.position += 17 + + // 4. Set name to the result of parsing a multipart/form-data name given + // input and position, if the result is not failure. Otherwise, return + // failure. + name = parseMultipartFormDataName(input, position) + + if (name === null) { + return 'failure' + } + + // 5. If position points to a sequence of bytes starting with `; filename="`: + if (bufferStartsWith(input, filenameBuffer, position)) { + // Note: undici also handles filename* + let check = position.position + filenameBuffer.length + + if (input[check] === 0x2a) { + position.position += 1 + check += 1 + } + + if (input[check] !== 0x3d || input[check + 1] !== 0x22) { // =" + return 'failure' + } + + // 1. Advance position so it points at the byte after the next 0x22 (") byte + // (the one in the sequence of bytes matched above). + position.position += 12 + + // 2. Set filename to the result of parsing a multipart/form-data name given + // input and position, if the result is not failure. Otherwise, return failure. + filename = parseMultipartFormDataName(input, position) + + if (filename === null) { + return 'failure' + } + } + + break + } + case 'content-type': { + // 1. Let header value be the result of collecting a sequence of bytes that are + // not 0x0A (LF) or 0x0D (CR), given position. + let headerValue = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d, + input, + position + ) + + // 2. Remove any HTTP tab or space bytes from the end of header value. + headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20) + + // 3. Set contentType to the isomorphic decoding of header value. + contentType = isomorphicDecode(headerValue) + + break + } + case 'content-transfer-encoding': { + let headerValue = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d, + input, + position + ) + + headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20) + + encoding = isomorphicDecode(headerValue) + + break + } + default: { + // Collect a sequence of bytes that are not 0x0A (LF) or 0x0D (CR), given position. + // (Do nothing with those bytes.) + collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d, + input, + position + ) + } + } + + // 2.9. If position does not point to a sequence of bytes starting with 0x0D 0x0A + // (CR LF), return failure. Otherwise, advance position by 2 (past the newline). + if (input[position.position] !== 0x0d && input[position.position + 1] !== 0x0a) { + return 'failure' + } else { + position.position += 2 + } + } +} + +/** + * @see https://andreubotella.github.io/multipart-form-data/#parse-a-multipart-form-data-name + * @param {Buffer} input + * @param {{ position: number }} position + */ +function parseMultipartFormDataName (input, position) { + // 1. Assert: The byte at (position - 1) is 0x22 ("). + assert(input[position.position - 1] === 0x22) + + // 2. Let name be the result of collecting a sequence of bytes that are not 0x0A (LF), 0x0D (CR) or 0x22 ("), given position. + /** @type {string | Buffer} */ + let name = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d && char !== 0x22, + input, + position + ) + + // 3. If the byte at position is not 0x22 ("), return failure. Otherwise, advance position by 1. + if (input[position.position] !== 0x22) { + return null // name could be 'failure' + } else { + position.position++ + } + + // 4. Replace any occurrence of the following subsequences in name with the given byte: + // - `%0A`: 0x0A (LF) + // - `%0D`: 0x0D (CR) + // - `%22`: 0x22 (") + name = new TextDecoder().decode(name) + .replace(/%0A/ig, '\n') + .replace(/%0D/ig, '\r') + .replace(/%22/g, '"') + + // 5. Return the UTF-8 decoding without BOM of name. + return name +} + +/** + * @param {(char: number) => boolean} condition + * @param {Buffer} input + * @param {{ position: number }} position + */ +function collectASequenceOfBytes (condition, input, position) { + let start = position.position + + while (start < input.length && condition(input[start])) { + ++start + } + + return input.subarray(position.position, (position.position = start)) +} + +/** + * @param {Buffer} buf + * @param {boolean} leading + * @param {boolean} trailing + * @param {(charCode: number) => boolean} predicate + * @returns {Buffer} + */ +function removeChars (buf, leading, trailing, predicate) { + let lead = 0 + let trail = buf.length - 1 + + if (leading) { + while (lead < buf.length && predicate(buf[lead])) lead++ + } + + if (trailing) { + while (trail > 0 && predicate(buf[trail])) trail-- + } + + return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1) +} + +/** + * Checks if {@param buffer} starts with {@param start} + * @param {Buffer} buffer + * @param {Buffer} start + * @param {{ position: number }} position + */ +function bufferStartsWith (buffer, start, position) { + if (buffer.length < start.length) { + return false + } + + for (let i = 0; i < start.length; i++) { + if (start[i] !== buffer[position.position + i]) { + return false + } + } + + return true +} + +module.exports = { + multipartFormDataParser, + validateBoundary +} diff --git a/node_modules/undici/lib/web/fetch/formdata.js b/node_modules/undici/lib/web/fetch/formdata.js new file mode 100644 index 0000000000000..544e412551938 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/formdata.js @@ -0,0 +1,252 @@ +'use strict' + +const { isBlobLike, iteratorMixin } = require('./util') +const { kState } = require('./symbols') +const { kEnumerableProperty } = require('../../core/util') +const { FileLike, isFileLike } = require('./file') +const { webidl } = require('./webidl') +const { File: NativeFile } = require('node:buffer') +const nodeUtil = require('node:util') + +/** @type {globalThis['File']} */ +const File = globalThis.File ?? NativeFile + +// https://xhr.spec.whatwg.org/#formdata +class FormData { + constructor (form) { + webidl.util.markAsUncloneable(this) + + if (form !== undefined) { + throw webidl.errors.conversionFailed({ + prefix: 'FormData constructor', + argument: 'Argument 1', + types: ['undefined'] + }) + } + + this[kState] = [] + } + + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.append' + webidl.argumentLengthCheck(arguments, 2, prefix) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name, prefix, 'name') + value = isBlobLike(value) + ? webidl.converters.Blob(value, prefix, 'value', { strict: false }) + : webidl.converters.USVString(value, prefix, 'value') + filename = arguments.length === 3 + ? webidl.converters.USVString(filename, prefix, 'filename') + : undefined + + // 2. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename) + + // 3. Append entry to this’s entry list. + this[kState].push(entry) + } + + delete (name) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.delete' + webidl.argumentLengthCheck(arguments, 1, prefix) + + name = webidl.converters.USVString(name, prefix, 'name') + + // The delete(name) method steps are to remove all entries whose name + // is name from this’s entry list. + this[kState] = this[kState].filter(entry => entry.name !== name) + } + + get (name) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.get' + webidl.argumentLengthCheck(arguments, 1, prefix) + + name = webidl.converters.USVString(name, prefix, 'name') + + // 1. If there is no entry whose name is name in this’s entry list, + // then return null. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx === -1) { + return null + } + + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this[kState][idx].value + } + + getAll (name) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.getAll' + webidl.argumentLengthCheck(arguments, 1, prefix) + + name = webidl.converters.USVString(name, prefix, 'name') + + // 1. If there is no entry whose name is name in this’s entry list, + // then return the empty list. + // 2. Return the values of all entries whose name is name, in order, + // from this’s entry list. + return this[kState] + .filter((entry) => entry.name === name) + .map((entry) => entry.value) + } + + has (name) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.has' + webidl.argumentLengthCheck(arguments, 1, prefix) + + name = webidl.converters.USVString(name, prefix, 'name') + + // The has(name) method steps are to return true if there is an entry + // whose name is name in this’s entry list; otherwise false. + return this[kState].findIndex((entry) => entry.name === name) !== -1 + } + + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.set' + webidl.argumentLengthCheck(arguments, 2, prefix) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // The set(name, value) and set(name, blobValue, filename) method steps + // are: + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name, prefix, 'name') + value = isBlobLike(value) + ? webidl.converters.Blob(value, prefix, 'name', { strict: false }) + : webidl.converters.USVString(value, prefix, 'name') + filename = arguments.length === 3 + ? webidl.converters.USVString(filename, prefix, 'name') + : undefined + + // 2. Let entry be the result of creating an entry with name, value, and + // filename if given. + const entry = makeEntry(name, value, filename) + + // 3. If there are entries in this’s entry list whose name is name, then + // replace the first such entry with entry and remove the others. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx !== -1) { + this[kState] = [ + ...this[kState].slice(0, idx), + entry, + ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) + ] + } else { + // 4. Otherwise, append entry to this’s entry list. + this[kState].push(entry) + } + } + + [nodeUtil.inspect.custom] (depth, options) { + const state = this[kState].reduce((a, b) => { + if (a[b.name]) { + if (Array.isArray(a[b.name])) { + a[b.name].push(b.value) + } else { + a[b.name] = [a[b.name], b.value] + } + } else { + a[b.name] = b.value + } + + return a + }, { __proto__: null }) + + options.depth ??= depth + options.colors ??= true + + const output = nodeUtil.formatWithOptions(options, state) + + // remove [Object null prototype] + return `FormData ${output.slice(output.indexOf(']') + 2)}` + } +} + +iteratorMixin('FormData', FormData, kState, 'name', 'value') + +Object.defineProperties(FormData.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + getAll: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FormData', + configurable: true + } +}) + +/** + * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry + * @param {string} name + * @param {string|Blob} value + * @param {?string} filename + * @returns + */ +function makeEntry (name, value, filename) { + // 1. Set name to the result of converting name into a scalar value string. + // Note: This operation was done by the webidl converter USVString. + + // 2. If value is a string, then set value to the result of converting + // value into a scalar value string. + if (typeof value === 'string') { + // Note: This operation was done by the webidl converter USVString. + } else { + // 3. Otherwise: + + // 1. If value is not a File object, then set value to a new File object, + // representing the same bytes, whose name attribute value is "blob" + if (!isFileLike(value)) { + value = value instanceof Blob + ? new File([value], 'blob', { type: value.type }) + : new FileLike(value, 'blob', { type: value.type }) + } + + // 2. If filename is given, then set value to a new File object, + // representing the same bytes, whose name attribute is filename. + if (filename !== undefined) { + /** @type {FilePropertyBag} */ + const options = { + type: value.type, + lastModified: value.lastModified + } + + value = value instanceof NativeFile + ? new File([value], filename, options) + : new FileLike(value, filename, options) + } + } + + // 4. Return an entry whose name is name and whose value is value. + return { name, value } +} + +module.exports = { FormData, makeEntry } diff --git a/node_modules/undici/lib/web/fetch/global.js b/node_modules/undici/lib/web/fetch/global.js new file mode 100644 index 0000000000000..1df6f1227bc26 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/global.js @@ -0,0 +1,40 @@ +'use strict' + +// In case of breaking changes, increase the version +// number to avoid conflicts. +const globalOrigin = Symbol.for('undici.globalOrigin.1') + +function getGlobalOrigin () { + return globalThis[globalOrigin] +} + +function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }) + + return + } + + const parsedURL = new URL(newOrigin) + + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + } + + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }) +} + +module.exports = { + getGlobalOrigin, + setGlobalOrigin +} diff --git a/node_modules/undici/lib/web/fetch/headers.js b/node_modules/undici/lib/web/fetch/headers.js new file mode 100644 index 0000000000000..a68daf4a5d473 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/headers.js @@ -0,0 +1,687 @@ +// https://github.com/Ethan-Arrowood/undici-fetch + +'use strict' + +const { kConstruct } = require('../../core/symbols') +const { kEnumerableProperty } = require('../../core/util') +const { + iteratorMixin, + isValidHeaderName, + isValidHeaderValue +} = require('./util') +const { webidl } = require('./webidl') +const assert = require('node:assert') +const util = require('node:util') + +const kHeadersMap = Symbol('headers map') +const kHeadersSortedMap = Symbol('headers map sorted') + +/** + * @param {number} code + */ +function isHTTPWhiteSpaceCharCode (code) { + return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue + */ +function headerValueNormalize (potentialValue) { + // To normalize a byte sequence potentialValue, remove + // any leading and trailing HTTP whitespace bytes from + // potentialValue. + let i = 0; let j = potentialValue.length + + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i + + return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) +} + +function fill (headers, object) { + // To fill a Headers object headers with a given object object, run these steps: + + // 1. If object is a sequence, then for each header in object: + // Note: webidl conversion to array has already been done. + if (Array.isArray(object)) { + for (let i = 0; i < object.length; ++i) { + const header = object[i] + // 1. If header does not contain exactly two items, then throw a TypeError. + if (header.length !== 2) { + throw webidl.errors.exception({ + header: 'Headers constructor', + message: `expected name/value pair to be length 2, found ${header.length}.` + }) + } + + // 2. Append (header’s first item, header’s second item) to headers. + appendHeader(headers, header[0], header[1]) + } + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw + + // 2. Otherwise, object is a record, then for each key → value in object, + // append (key, value) to headers + const keys = Object.keys(object) + for (let i = 0; i < keys.length; ++i) { + appendHeader(headers, keys[i], object[keys[i]]) + } + } else { + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) + } +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-headers-append + */ +function appendHeader (headers, name, value) { + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value, + type: 'header value' + }) + } + + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if headers’s guard is "request-no-cors": + // TODO + // Note: undici does not implement forbidden header names + if (getHeadersGuard(headers) === 'immutable') { + throw new TypeError('immutable') + } + + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. + + // 7. Append (name, value) to headers’s header list. + return getHeadersList(headers).append(name, value, false) + + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers +} + +function compareHeaderName (a, b) { + return a[0] < b[0] ? -1 : 1 +} + +class HeadersList { + /** @type {[string, string][]|null} */ + cookies = null + + constructor (init) { + if (init instanceof HeadersList) { + this[kHeadersMap] = new Map(init[kHeadersMap]) + this[kHeadersSortedMap] = init[kHeadersSortedMap] + this.cookies = init.cookies === null ? null : [...init.cookies] + } else { + this[kHeadersMap] = new Map(init) + this[kHeadersSortedMap] = null + } + } + + /** + * @see https://fetch.spec.whatwg.org/#header-list-contains + * @param {string} name + * @param {boolean} isLowerCase + */ + contains (name, isLowerCase) { + // A header list list contains a header name name if list + // contains a header whose name is a byte-case-insensitive + // match for name. + + return this[kHeadersMap].has(isLowerCase ? name : name.toLowerCase()) + } + + clear () { + this[kHeadersMap].clear() + this[kHeadersSortedMap] = null + this.cookies = null + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-append + * @param {string} name + * @param {string} value + * @param {boolean} isLowerCase + */ + append (name, value, isLowerCase) { + this[kHeadersSortedMap] = null + + // 1. If list contains name, then set name to the first such + // header’s name. + const lowercaseName = isLowerCase ? name : name.toLowerCase() + const exists = this[kHeadersMap].get(lowercaseName) + + // 2. Append (name, value) to list. + if (exists) { + const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' + this[kHeadersMap].set(lowercaseName, { + name: exists.name, + value: `${exists.value}${delimiter}${value}` + }) + } else { + this[kHeadersMap].set(lowercaseName, { name, value }) + } + + if (lowercaseName === 'set-cookie') { + (this.cookies ??= []).push(value) + } + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-set + * @param {string} name + * @param {string} value + * @param {boolean} isLowerCase + */ + set (name, value, isLowerCase) { + this[kHeadersSortedMap] = null + const lowercaseName = isLowerCase ? name : name.toLowerCase() + + if (lowercaseName === 'set-cookie') { + this.cookies = [value] + } + + // 1. If list contains name, then set the value of + // the first such header to value and remove the + // others. + // 2. Otherwise, append header (name, value) to list. + this[kHeadersMap].set(lowercaseName, { name, value }) + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-delete + * @param {string} name + * @param {boolean} isLowerCase + */ + delete (name, isLowerCase) { + this[kHeadersSortedMap] = null + if (!isLowerCase) name = name.toLowerCase() + + if (name === 'set-cookie') { + this.cookies = null + } + + this[kHeadersMap].delete(name) + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-get + * @param {string} name + * @param {boolean} isLowerCase + * @returns {string | null} + */ + get (name, isLowerCase) { + // 1. If list does not contain name, then return null. + // 2. Return the values of all headers in list whose name + // is a byte-case-insensitive match for name, + // separated from each other by 0x2C 0x20, in order. + return this[kHeadersMap].get(isLowerCase ? name : name.toLowerCase())?.value ?? null + } + + * [Symbol.iterator] () { + // use the lowercased name + for (const { 0: name, 1: { value } } of this[kHeadersMap]) { + yield [name, value] + } + } + + get entries () { + const headers = {} + + if (this[kHeadersMap].size !== 0) { + for (const { name, value } of this[kHeadersMap].values()) { + headers[name] = value + } + } + + return headers + } + + rawValues () { + return this[kHeadersMap].values() + } + + get entriesList () { + const headers = [] + + if (this[kHeadersMap].size !== 0) { + for (const { 0: lowerName, 1: { name, value } } of this[kHeadersMap]) { + if (lowerName === 'set-cookie') { + for (const cookie of this.cookies) { + headers.push([name, cookie]) + } + } else { + headers.push([name, value]) + } + } + } + + return headers + } + + // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set + toSortedArray () { + const size = this[kHeadersMap].size + const array = new Array(size) + // In most cases, you will use the fast-path. + // fast-path: Use binary insertion sort for small arrays. + if (size <= 32) { + if (size === 0) { + // If empty, it is an empty array. To avoid the first index assignment. + return array + } + // Improve performance by unrolling loop and avoiding double-loop. + // Double-loop-less version of the binary insertion sort. + const iterator = this[kHeadersMap][Symbol.iterator]() + const firstValue = iterator.next().value + // set [name, value] to first index. + array[0] = [firstValue[0], firstValue[1].value] + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + // 3.2.2. Assert: value is non-null. + assert(firstValue[1].value !== null) + for ( + let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value; + i < size; + ++i + ) { + // get next value + value = iterator.next().value + // set [name, value] to current index. + x = array[i] = [value[0], value[1].value] + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + // 3.2.2. Assert: value is non-null. + assert(x[1] !== null) + left = 0 + right = i + // binary search + while (left < right) { + // middle index + pivot = left + ((right - left) >> 1) + // compare header name + if (array[pivot][0] <= x[0]) { + left = pivot + 1 + } else { + right = pivot + } + } + if (i !== pivot) { + j = i + while (j > left) { + array[j] = array[--j] + } + array[left] = x + } + } + /* c8 ignore next 4 */ + if (!iterator.next().done) { + // This is for debugging and will never be called. + throw new TypeError('Unreachable') + } + return array + } else { + // This case would be a rare occurrence. + // slow-path: fallback + let i = 0 + for (const { 0: name, 1: { value } } of this[kHeadersMap]) { + array[i++] = [name, value] + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + // 3.2.2. Assert: value is non-null. + assert(value !== null) + } + return array.sort(compareHeaderName) + } + } +} + +// https://fetch.spec.whatwg.org/#headers-class +class Headers { + #guard + #headersList + + constructor (init = undefined) { + webidl.util.markAsUncloneable(this) + + if (init === kConstruct) { + return + } + + this.#headersList = new HeadersList() + + // The new Headers(init) constructor steps are: + + // 1. Set this’s guard to "none". + this.#guard = 'none' + + // 2. If init is given, then fill this with init. + if (init !== undefined) { + init = webidl.converters.HeadersInit(init, 'Headers contructor', 'init') + fill(this, init) + } + } + + // https://fetch.spec.whatwg.org/#dom-headers-append + append (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, 'Headers.append') + + const prefix = 'Headers.append' + name = webidl.converters.ByteString(name, prefix, 'name') + value = webidl.converters.ByteString(value, prefix, 'value') + + return appendHeader(this, name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, 'Headers.delete') + + const prefix = 'Headers.delete' + name = webidl.converters.ByteString(name, prefix, 'name') + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.delete', + value: name, + type: 'header name' + }) + } + + // 2. If this’s guard is "immutable", then throw a TypeError. + // 3. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 4. Otherwise, if this’s guard is "request-no-cors", name + // is not a no-CORS-safelisted request-header name, and + // name is not a privileged no-CORS request-header name, + // return. + // 5. Otherwise, if this’s guard is "response" and name is + // a forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this.#guard === 'immutable') { + throw new TypeError('immutable') + } + + // 6. If this’s header list does not contain name, then + // return. + if (!this.#headersList.contains(name, false)) { + return + } + + // 7. Delete name from this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this. + this.#headersList.delete(name, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, 'Headers.get') + + const prefix = 'Headers.get' + name = webidl.converters.ByteString(name, prefix, 'name') + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: 'header name' + }) + } + + // 2. Return the result of getting name from this’s header + // list. + return this.#headersList.get(name, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-has + has (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, 'Headers.has') + + const prefix = 'Headers.has' + name = webidl.converters.ByteString(name, prefix, 'name') + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: 'header name' + }) + } + + // 2. Return true if this’s header list contains name; + // otherwise false. + return this.#headersList.contains(name, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, 'Headers.set') + + const prefix = 'Headers.set' + name = webidl.converters.ByteString(name, prefix, 'name') + value = webidl.converters.ByteString(value, prefix, 'value') + + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix, + value, + type: 'header value' + }) + } + + // 3. If this’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if this’s guard is "request-no-cors" and + // name/value is not a no-CORS-safelisted request-header, + // return. + // 6. Otherwise, if this’s guard is "response" and name is a + // forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this.#guard === 'immutable') { + throw new TypeError('immutable') + } + + // 7. Set (name, value) in this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this + this.#headersList.set(name, value, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers) + + // 1. If this’s header list does not contain `Set-Cookie`, then return « ». + // 2. Return the values of all headers in this’s header list whose name is + // a byte-case-insensitive match for `Set-Cookie`, in order. + + const list = this.#headersList.cookies + + if (list) { + return [...list] + } + + return [] + } + + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + get [kHeadersSortedMap] () { + if (this.#headersList[kHeadersSortedMap]) { + return this.#headersList[kHeadersSortedMap] + } + + // 1. Let headers be an empty list of headers with the key being the name + // and value the value. + const headers = [] + + // 2. Let names be the result of convert header names to a sorted-lowercase + // set with all the names of the headers in list. + const names = this.#headersList.toSortedArray() + + const cookies = this.#headersList.cookies + + // fast-path + if (cookies === null || cookies.length === 1) { + // Note: The non-null assertion of value has already been done by `HeadersList#toSortedArray` + return (this.#headersList[kHeadersSortedMap] = names) + } + + // 3. For each name of names: + for (let i = 0; i < names.length; ++i) { + const { 0: name, 1: value } = names[i] + // 1. If name is `set-cookie`, then: + if (name === 'set-cookie') { + // 1. Let values be a list of all values of headers in list whose name + // is a byte-case-insensitive match for name, in order. + + // 2. For each value of values: + // 1. Append (name, value) to headers. + for (let j = 0; j < cookies.length; ++j) { + headers.push([name, cookies[j]]) + } + } else { + // 2. Otherwise: + + // 1. Let value be the result of getting name from list. + + // 2. Assert: value is non-null. + // Note: This operation was done by `HeadersList#toSortedArray`. + + // 3. Append (name, value) to headers. + headers.push([name, value]) + } + } + + // 4. Return headers. + return (this.#headersList[kHeadersSortedMap] = headers) + } + + [util.inspect.custom] (depth, options) { + options.depth ??= depth + + return `Headers ${util.formatWithOptions(options, this.#headersList.entries)}` + } + + static getHeadersGuard (o) { + return o.#guard + } + + static setHeadersGuard (o, guard) { + o.#guard = guard + } + + static getHeadersList (o) { + return o.#headersList + } + + static setHeadersList (o, list) { + o.#headersList = list + } +} + +const { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers +Reflect.deleteProperty(Headers, 'getHeadersGuard') +Reflect.deleteProperty(Headers, 'setHeadersGuard') +Reflect.deleteProperty(Headers, 'getHeadersList') +Reflect.deleteProperty(Headers, 'setHeadersList') + +iteratorMixin('Headers', Headers, kHeadersSortedMap, 0, 1) + +Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + getSetCookie: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Headers', + configurable: true + }, + [util.inspect.custom]: { + enumerable: false + } +}) + +webidl.converters.HeadersInit = function (V, prefix, argument) { + if (webidl.util.Type(V) === 'Object') { + const iterator = Reflect.get(V, Symbol.iterator) + + // A work-around to ensure we send the properly-cased Headers when V is a Headers object. + // Read https://github.com/nodejs/undici/pull/3159#issuecomment-2075537226 before touching, please. + if (!util.types.isProxy(V) && iterator === Headers.prototype.entries) { // Headers object + try { + return getHeadersList(V).entriesList + } catch { + // fall-through + } + } + + if (typeof iterator === 'function') { + return webidl.converters['sequence>'](V, prefix, argument, iterator.bind(V)) + } + + return webidl.converters['record'](V, prefix, argument) + } + + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) +} + +module.exports = { + fill, + // for test. + compareHeaderName, + Headers, + HeadersList, + getHeadersGuard, + setHeadersGuard, + setHeadersList, + getHeadersList +} diff --git a/node_modules/undici/lib/web/fetch/index.js b/node_modules/undici/lib/web/fetch/index.js new file mode 100644 index 0000000000000..9a685d680a1c3 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/index.js @@ -0,0 +1,2272 @@ +// https://github.com/Ethan-Arrowood/undici-fetch + +'use strict' + +const { + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse, + fromInnerResponse +} = require('./response') +const { HeadersList } = require('./headers') +const { Request, cloneRequest } = require('./request') +const zlib = require('node:zlib') +const { + bytesMatch, + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + createDeferredPromise, + isBlobLike, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlIsHttpHttpsScheme, + urlHasHttpsScheme, + clampAndCoarsenConnectionTimingInfo, + simpleRangeHeaderValue, + buildContentRange, + createInflate, + extractMimeType +} = require('./util') +const { kState, kDispatcher } = require('./symbols') +const assert = require('node:assert') +const { safelyExtractBody, extractBody } = require('./body') +const { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet +} = require('./constants') +const EE = require('node:events') +const { Readable, pipeline, finished } = require('node:stream') +const { addAbortListener, isErrored, isReadable, bufferToLowerCasedHeaderName } = require('../../core/util') +const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require('./data-url') +const { getGlobalDispatcher } = require('../../global') +const { webidl } = require('./webidl') +const { STATUS_CODES } = require('node:http') +const GET_OR_HEAD = ['GET', 'HEAD'] + +const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined' + ? 'node' + : 'undici' + +/** @type {import('buffer').resolveObjectURL} */ +let resolveObjectURL + +class Fetch extends EE { + constructor (dispatcher) { + super() + + this.dispatcher = dispatcher + this.connection = null + this.dump = false + this.state = 'ongoing' + } + + terminate (reason) { + if (this.state !== 'ongoing') { + return + } + + this.state = 'terminated' + this.connection?.destroy(reason) + this.emit('terminated', reason) + } + + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return + } + + // 1. Set controller’s state to "aborted". + this.state = 'aborted' + + // 2. Let fallbackError be an "AbortError" DOMException. + // 3. Set error to fallbackError if it is not given. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). + + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error + + this.connection?.destroy(error) + this.emit('terminated', error) + } +} + +function handleFetchDone (response) { + finalizeAndReportTiming(response, 'fetch') +} + +// https://fetch.spec.whatwg.org/#fetch-method +function fetch (input, init = undefined) { + webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch') + + // 1. Let p be a new promise. + let p = createDeferredPromise() + + // 2. Let requestObject be the result of invoking the initial value of + // Request as constructor with input and init as arguments. If this throws + // an exception, reject p with it and return p. + let requestObject + + try { + requestObject = new Request(input, init) + } catch (e) { + p.reject(e) + return p.promise + } + + // 3. Let request be requestObject’s request. + const request = requestObject[kState] + + // 4. If requestObject’s signal’s aborted flag is set, then: + if (requestObject.signal.aborted) { + // 1. Abort the fetch() call with p, request, null, and + // requestObject’s signal’s abort reason. + abortFetch(p, request, null, requestObject.signal.reason) + + // 2. Return p. + return p.promise + } + + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject + + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none' + } + + // 7. Let responseObject be null. + let responseObject = null + + // 8. Let relevantRealm be this’s relevant Realm. + + // 9. Let locallyAborted be false. + let locallyAborted = false + + // 10. Let controller be null. + let controller = null + + // 11. Add the following abort steps to requestObject’s signal: + addAbortListener( + requestObject.signal, + () => { + // 1. Set locallyAborted to true. + locallyAborted = true + + // 2. Assert: controller is non-null. + assert(controller != null) + + // 3. Abort controller with requestObject’s signal’s abort reason. + controller.abort(requestObject.signal.reason) + + const realResponse = responseObject?.deref() + + // 4. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, realResponse, requestObject.signal.reason) + } + ) + + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + // see function handleFetchDone + + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: + + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return + } + + // 2. If response’s aborted flag is set, then: + if (response.aborted) { + // 1. Let deserializedError be the result of deserialize a serialized + // abort reason given controller’s serialized abort reason and + // relevantRealm. + + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. + + abortFetch(p, request, responseObject, controller.serializedAbortReason) + return + } + + // 3. If response is a network error, then reject p with a TypeError + // and terminate these substeps. + if (response.type === 'error') { + p.reject(new TypeError('fetch failed', { cause: response.error })) + return + } + + // 4. Set responseObject to the result of creating a Response object, + // given response, "immutable", and relevantRealm. + responseObject = new WeakRef(fromInnerResponse(response, 'immutable')) + + // 5. Resolve p with responseObject. + p.resolve(responseObject.deref()) + p = null + } + + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: requestObject[kDispatcher] // undici + }) + + // 14. Return p. + return p.promise +} + +// https://fetch.spec.whatwg.org/#finalize-and-report-timing +function finalizeAndReportTiming (response, initiatorType = 'other') { + // 1. If response is an aborted network error, then return. + if (response.type === 'error' && response.aborted) { + return + } + + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return + } + + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0] + + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo + + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState + + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return + } + + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } + + // 8. If response’s timing allow passed flag is not set, then: + if (!response.timingAllowPassed) { + // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }) + + // 2. Set cacheState to the empty string. + cacheState = '' + } + + // 9. Set timingInfo’s end time to the coarsened shared current time + // given global’s relevant settings object’s cross-origin isolated + // capability. + // TODO: given global’s relevant settings object’s cross-origin isolated + // capability? + timingInfo.endTime = coarsenedSharedCurrentTime() + + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL.href, + initiatorType, + globalThis, + cacheState + ) +} + +// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing +const markResourceTiming = performance.markResourceTiming + +// https://fetch.spec.whatwg.org/#abort-fetch +function abortFetch (p, request, responseObject, error) { + // 1. Reject promise with error. + if (p) { + // We might have already resolved the promise at this stage + p.reject(error) + } + + // 2. If request’s body is not null and is readable, then cancel request’s + // body with error. + if (request.body != null && isReadable(request.body?.stream)) { + request.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } + + // 3. If responseObject is null, then return. + if (responseObject == null) { + return + } + + // 4. Let response be responseObject’s response. + const response = responseObject[kState] + + // 5. If response’s body is not null and is readable, then error response’s + // body with error. + if (response.body != null && isReadable(response.body?.stream)) { + response.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } +} + +// https://fetch.spec.whatwg.org/#fetching +function fetching ({ + request, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseEndOfBody, + processResponseConsumeBody, + useParallelQueue = false, + dispatcher = getGlobalDispatcher() // undici +}) { + // Ensure that the dispatcher is set accordingly + assert(dispatcher) + + // 1. Let taskDestination be null. + let taskDestination = null + + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false + + // 3. If request’s client is non-null, then: + if (request.client != null) { + // 1. Set taskDestination to request’s client’s global object. + taskDestination = request.client.globalObject + + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability + } + + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO + + // 5. Let timingInfo be a new fetch timing info whose start time and + // post-redirect start time are the coarsened shared current time given + // crossOriginIsolatedCapability. + const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) + const timingInfo = createOpaqueTimingInfo({ + startTime: currentTime + }) + + // 6. Let fetchParams be a new fetch params whose + // request is request, + // timing info is timingInfo, + // process request body chunk length is processRequestBodyChunkLength, + // process request end-of-body is processRequestEndOfBody, + // process response is processResponse, + // process response consume body is processResponseConsumeBody, + // process response end-of-body is processResponseEndOfBody, + // task destination is taskDestination, + // and cross-origin isolated capability is crossOriginIsolatedCapability. + const fetchParams = { + controller: new Fetch(dispatcher), + request, + timingInfo, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseConsumeBody, + processResponseEndOfBody, + taskDestination, + crossOriginIsolatedCapability + } + + // 7. If request’s body is a byte sequence, then set request’s body to + // request’s body as a body. + // NOTE: Since fetching is only called from fetch, body should already be + // extracted. + assert(!request.body || request.body.stream) + + // 8. If request’s window is "client", then set request’s window to request’s + // client, if request’s client’s global object is a Window object; otherwise + // "no-window". + if (request.window === 'client') { + // TODO: What if request.client is null? + request.window = + request.client?.globalObject?.constructor?.name === 'Window' + ? request.client + : 'no-window' + } + + // 9. If request’s origin is "client", then set request’s origin to request’s + // client’s origin. + if (request.origin === 'client') { + request.origin = request.client.origin + } + + // 10. If all of the following conditions are true: + // TODO + + // 11. If request’s policy container is "client", then: + if (request.policyContainer === 'client') { + // 1. If request’s client is non-null, then set request’s policy + // container to a clone of request’s client’s policy container. [HTML] + if (request.client != null) { + request.policyContainer = clonePolicyContainer( + request.client.policyContainer + ) + } else { + // 2. Otherwise, set request’s policy container to a new policy + // container. + request.policyContainer = makePolicyContainer() + } + } + + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept', true)) { + // 1. Let value be `*/*`. + const value = '*/*' + + // 2. A user agent should set value to the first matching statement, if + // any, switching on request’s destination: + // "document" + // "frame" + // "iframe" + // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` + // "image" + // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` + // "style" + // `text/css,*/*;q=0.1` + // TODO + + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value, true) + } + + // 13. If request’s header list does not contain `Accept-Language`, then + // user agents should append `Accept-Language`/an appropriate value to + // request’s header list. + if (!request.headersList.contains('accept-language', true)) { + request.headersList.append('accept-language', '*', true) + } + + // 14. If request’s priority is null, then use request’s initiator and + // destination appropriately in setting request’s priority to a + // user-agent-defined object. + if (request.priority === null) { + // TODO + } + + // 15. If request is a subresource request, then: + if (subresourceSet.has(request.destination)) { + // TODO + } + + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams) + .catch(err => { + fetchParams.controller.terminate(err) + }) + + // 17. Return fetchParam's controller + return fetchParams.controller +} + +// https://fetch.spec.whatwg.org/#concept-main-fetch +async function mainFetch (fetchParams, recursive = false) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. If request’s local-URLs-only flag is set and request’s current URL is + // not local, then set response to a network error. + if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { + response = makeNetworkError('local URLs only') + } + + // 4. Run report Content Security Policy violations for request. + // TODO + + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request) + + // 6. If should request be blocked due to a bad port, should fetching request + // be blocked as mixed content, or should request be blocked by Content + // Security Policy returns blocked, then set response to a network error. + if (requestBadPort(request) === 'blocked') { + response = makeNetworkError('bad port') + } + // TODO: should fetching request be blocked as mixed content? + // TODO: should request be blocked by Content Security Policy? + + // 7. If request’s referrer policy is the empty string, then set request’s + // referrer policy to request’s policy container’s referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = request.policyContainer.referrerPolicy + } + + // 8. If request’s referrer is not "no-referrer", then set request’s + // referrer to the result of invoking determine request’s referrer. + if (request.referrer !== 'no-referrer') { + request.referrer = determineRequestsReferrer(request) + } + + // 9. Set request’s current URL’s scheme to "https" if all of the following + // conditions are true: + // - request’s current URL’s scheme is "http" + // - request’s current URL’s host is a domain + // - Matching request’s current URL’s host per Known HSTS Host Domain Name + // Matching results in either a superdomain match with an asserted + // includeSubDomains directive or a congruent match (with or without an + // asserted includeSubDomains directive). [HSTS] + // TODO + + // 10. If recursive is false, then run the remaining steps in parallel. + // TODO + + // 11. If response is null, then set response to the result of running + // the steps corresponding to the first matching statement: + if (response === null) { + response = await (async () => { + const currentURL = requestCurrentURL(request) + + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || + // request’s current URL’s scheme is "data" + (currentURL.protocol === 'data:') || + // - request’s mode is "navigate" or "websocket" + (request.mode === 'navigate' || request.mode === 'websocket') + ) { + // 1. Set request’s response tainting to "basic". + request.responseTainting = 'basic' + + // 2. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s mode is "same-origin" + if (request.mode === 'same-origin') { + // 1. Return a network error. + return makeNetworkError('request mode cannot be "same-origin"') + } + + // request’s mode is "no-cors" + if (request.mode === 'no-cors') { + // 1. If request’s redirect mode is not "follow", then return a network + // error. + if (request.redirect !== 'follow') { + return makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ) + } + + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque' + + // 3. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s current URL’s scheme is not an HTTP(S) scheme + if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { + // Return a network error. + return makeNetworkError('URL scheme must be a HTTP(S) scheme') + } + + // - request’s use-CORS-preflight flag is set + // - request’s unsafe-request flag is set and either request’s method is + // not a CORS-safelisted method or CORS-unsafe request-header names with + // request’s header list is not empty + // 1. Set request’s response tainting to "cors". + // 2. Let corsWithPreflightResponse be the result of running HTTP fetch + // given fetchParams and true. + // 3. If corsWithPreflightResponse is a network error, then clear cache + // entries using request. + // 4. Return corsWithPreflightResponse. + // TODO + + // Otherwise + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors' + + // 2. Return the result of running HTTP fetch given fetchParams. + return await httpFetch(fetchParams) + })() + } + + // 12. If recursive is true, then return response. + if (recursive) { + return response + } + + // 13. If response is not a network error and response is not a filtered + // response, then: + if (response.status !== 0 && !response.internalResponse) { + // If request’s response tainting is "cors", then: + if (request.responseTainting === 'cors') { + // 1. Let headerNames be the result of extracting header list values + // given `Access-Control-Expose-Headers` and response’s header list. + // TODO + // 2. If request’s credentials mode is not "include" and headerNames + // contains `*`, then set response’s CORS-exposed header-name list to + // all unique header names in response’s header list. + // TODO + // 3. Otherwise, if headerNames is not null or failure, then set + // response’s CORS-exposed header-name list to headerNames. + // TODO + } + + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (request.responseTainting === 'basic') { + response = filterResponse(response, 'basic') + } else if (request.responseTainting === 'cors') { + response = filterResponse(response, 'cors') + } else if (request.responseTainting === 'opaque') { + response = filterResponse(response, 'opaque') + } else { + assert(false) + } + } + + // 14. Let internalResponse be response, if response is a network error, + // and response’s internal response otherwise. + let internalResponse = + response.status === 0 ? response : response.internalResponse + + // 15. If internalResponse’s URL list is empty, then set it to a clone of + // request’s URL list. + if (internalResponse.urlList.length === 0) { + internalResponse.urlList.push(...request.urlList) + } + + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true + } + + // 17. If response is not a network error and any of the following returns + // blocked + // - should internalResponse to request be blocked as mixed content + // - should internalResponse to request be blocked by Content Security Policy + // - should internalResponse to request be blocked due to its MIME type + // - should internalResponse to request be blocked due to nosniff + // TODO + + // 18. If response’s type is "opaque", internalResponse’s status is 206, + // internalResponse’s range-requested flag is set, and request’s header + // list does not contain `Range`, then set response and internalResponse + // to a network error. + if ( + response.type === 'opaque' && + internalResponse.status === 206 && + internalResponse.rangeRequested && + !request.headers.contains('range', true) + ) { + response = internalResponse = makeNetworkError() + } + + // 19. If response is not a network error and either request’s method is + // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, + // set internalResponse’s body to null and disregard any enqueuing toward + // it (if any). + if ( + response.status !== 0 && + (request.method === 'HEAD' || + request.method === 'CONNECT' || + nullBodyStatus.includes(internalResponse.status)) + ) { + internalResponse.body = null + fetchParams.controller.dump = true + } + + // 20. If request’s integrity metadata is not the empty string, then: + if (request.integrity) { + // 1. Let processBodyError be this step: run fetch finale given fetchParams + // and a network error. + const processBodyError = (reason) => + fetchFinale(fetchParams, makeNetworkError(reason)) + + // 2. If request’s response tainting is "opaque", or response’s body is null, + // then run processBodyError and abort these steps. + if (request.responseTainting === 'opaque' || response.body == null) { + processBodyError(response.error) + return + } + + // 3. Let processBody given bytes be these steps: + const processBody = (bytes) => { + // 1. If bytes do not match request’s integrity metadata, + // then run processBodyError and abort these steps. [SRI] + if (!bytesMatch(bytes, request.integrity)) { + processBodyError('integrity mismatch') + return + } + + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0] + + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } + + // 4. Fully read response’s body given processBody and processBodyError. + await fullyReadBody(response.body, processBody, processBodyError) + } else { + // 21. Otherwise, run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } +} + +// https://fetch.spec.whatwg.org/#concept-scheme-fetch +// given a fetch params fetchParams +function schemeFetch (fetchParams) { + // Note: since the connection is destroyed on redirect, which sets fetchParams to a + // cancelled state, we do not want this condition to trigger *unless* there have been + // no redirects. See https://github.com/nodejs/undici/issues/1776 + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) + } + + // 2. Let request be fetchParams’s request. + const { request } = fetchParams + + const { protocol: scheme } = requestCurrentURL(request) + + // 3. Switch on request’s current URL’s scheme and run the associated steps: + switch (scheme) { + case 'about:': { + // If request’s current URL’s path is the string "blank", then return a new response + // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », + // and body is the empty byte sequence as a body. + + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) + } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = require('node:buffer').resolveObjectURL + } + + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request) + + // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 + // Buffer.resolveObjectURL does not ignore URL queries. + if (blobURLEntry.search.length !== 0) { + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) + } + + const blob = resolveObjectURL(blobURLEntry.toString()) + + // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s + // object is not a Blob object, then return a network error. + if (request.method !== 'GET' || !isBlobLike(blob)) { + return Promise.resolve(makeNetworkError('invalid method')) + } + + // 3. Let blob be blobURLEntry’s object. + // Note: done above + + // 4. Let response be a new response. + const response = makeResponse() + + // 5. Let fullLength be blob’s size. + const fullLength = blob.size + + // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded. + const serializedFullLength = isomorphicEncode(`${fullLength}`) + + // 7. Let type be blob’s type. + const type = blob.type + + // 8. If request’s header list does not contain `Range`: + // 9. Otherwise: + if (!request.headersList.contains('range', true)) { + // 1. Let bodyWithType be the result of safely extracting blob. + // Note: in the FileAPI a blob "object" is a Blob *or* a MediaSource. + // In node, this can only ever be a Blob. Therefore we can safely + // use extractBody directly. + const bodyWithType = extractBody(blob) + + // 2. Set response’s status message to `OK`. + response.statusText = 'OK' + + // 3. Set response’s body to bodyWithType’s body. + response.body = bodyWithType[0] + + // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ». + response.headersList.set('content-length', serializedFullLength, true) + response.headersList.set('content-type', type, true) + } else { + // 1. Set response’s range-requested flag. + response.rangeRequested = true + + // 2. Let rangeHeader be the result of getting `Range` from request’s header list. + const rangeHeader = request.headersList.get('range', true) + + // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true. + const rangeValue = simpleRangeHeaderValue(rangeHeader, true) + + // 4. If rangeValue is failure, then return a network error. + if (rangeValue === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } + + // 5. Let (rangeStart, rangeEnd) be rangeValue. + let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue + + // 6. If rangeStart is null: + // 7. Otherwise: + if (rangeStart === null) { + // 1. Set rangeStart to fullLength − rangeEnd. + rangeStart = fullLength - rangeEnd + + // 2. Set rangeEnd to rangeStart + rangeEnd − 1. + rangeEnd = rangeStart + rangeEnd - 1 + } else { + // 1. If rangeStart is greater than or equal to fullLength, then return a network error. + if (rangeStart >= fullLength) { + return Promise.resolve(makeNetworkError('Range start is greater than the blob\'s size.')) + } + + // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set + // rangeEnd to fullLength − 1. + if (rangeEnd === null || rangeEnd >= fullLength) { + rangeEnd = fullLength - 1 + } + } + + // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart, + // rangeEnd + 1, and type. + const slicedBlob = blob.slice(rangeStart, rangeEnd, type) + + // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob. + // Note: same reason as mentioned above as to why we use extractBody + const slicedBodyWithType = extractBody(slicedBlob) + + // 10. Set response’s body to slicedBodyWithType’s body. + response.body = slicedBodyWithType[0] + + // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded. + const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`) + + // 12. Let contentRange be the result of invoking build a content range given rangeStart, + // rangeEnd, and fullLength. + const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength) + + // 13. Set response’s status to 206. + response.status = 206 + + // 14. Set response’s status message to `Partial Content`. + response.statusText = 'Partial Content' + + // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength), + // (`Content-Type`, type), (`Content-Range`, contentRange) ». + response.headersList.set('content-length', serializedSlicedLength, true) + response.headersList.set('content-type', type, true) + response.headersList.set('content-range', contentRange, true) + } + + // 10. Return response. + return Promise.resolve(response) + } + case 'data:': { + // 1. Let dataURLStruct be the result of running the + // data: URL processor on request’s current URL. + const currentURL = requestCurrentURL(request) + const dataURLStruct = dataURLProcessor(currentURL) + + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } + + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType) + + // 4. Return a response whose status message is `OK`, + // header list is « (`Content-Type`, mimeType) », + // and body is dataURLStruct’s body as a body. + return Promise.resolve(makeResponse({ + statusText: 'OK', + headersList: [ + ['content-type', { name: 'Content-Type', value: mimeType }] + ], + body: safelyExtractBody(dataURLStruct.body)[0] + })) + } + case 'file:': { + // For now, unfortunate as it is, file URLs are left as an exercise for the reader. + // When in doubt, return a network error. + return Promise.resolve(makeNetworkError('not implemented... yet...')) + } + case 'http:': + case 'https:': { + // Return the result of running HTTP fetch given fetchParams. + + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) + } + } +} + +// https://fetch.spec.whatwg.org/#finalize-response +function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // 2, If fetchParams’s process response done is not null, then queue a fetch + // task to run fetchParams’s process response done given response, with + // fetchParams’s task destination. + if (fetchParams.processResponseDone != null) { + queueMicrotask(() => fetchParams.processResponseDone(response)) + } +} + +// https://fetch.spec.whatwg.org/#fetch-finale +function fetchFinale (fetchParams, response) { + // 1. Let timingInfo be fetchParams’s timing info. + let timingInfo = fetchParams.timingInfo + + // 2. If response is not a network error and fetchParams’s request’s client is a secure context, + // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting + // `Server-Timing` from response’s internal response’s header list. + // TODO + + // 3. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Let unsafeEndTime be the unsafe shared current time. + const unsafeEndTime = Date.now() // ? + + // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s + // full timing info to fetchParams’s timing info. + if (fetchParams.request.destination === 'document') { + fetchParams.controller.fullTimingInfo = timingInfo + } + + // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global: + fetchParams.controller.reportTimingSteps = () => { + // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return. + if (fetchParams.request.url.protocol !== 'https:') { + return + } + + // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global. + timingInfo.endTime = unsafeEndTime + + // 3. Let cacheState be response’s cache state. + let cacheState = response.cacheState + + // 4. Let bodyInfo be response’s body info. + const bodyInfo = response.bodyInfo + + // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an + // opaque timing info for timingInfo and set cacheState to the empty string. + if (!response.timingAllowPassed) { + timingInfo = createOpaqueTimingInfo(timingInfo) + + cacheState = '' + } + + // 6. Let responseStatus be 0. + let responseStatus = 0 + + // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false: + if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) { + // 1. Set responseStatus to response’s status. + responseStatus = response.status + + // 2. Let mimeType be the result of extracting a MIME type from response’s header list. + const mimeType = extractMimeType(response.headersList) + + // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType. + if (mimeType !== 'failure') { + bodyInfo.contentType = minimizeSupportedMimeType(mimeType) + } + } + + // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo, + // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo, + // and responseStatus. + if (fetchParams.request.initiatorType != null) { + // TODO: update markresourcetiming + markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus) + } + } + + // 4. Let processResponseEndOfBodyTask be the following steps: + const processResponseEndOfBodyTask = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process + // response end-of-body given response. + if (fetchParams.processResponseEndOfBody != null) { + queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) + } + + // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s + // global object is fetchParams’s task destination, then run fetchParams’s controller’s report + // timing steps given fetchParams’s request’s client’s global object. + if (fetchParams.request.initiatorType != null) { + fetchParams.controller.reportTimingSteps() + } + } + + // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination + queueMicrotask(() => processResponseEndOfBodyTask()) + } + + // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s + // process response given response, with fetchParams’s task destination. + if (fetchParams.processResponse != null) { + queueMicrotask(() => { + fetchParams.processResponse(response) + fetchParams.processResponse = null + }) + } + + // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response. + const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response) + + // 6. If internalResponse’s body is null, then run processResponseEndOfBody. + // 7. Otherwise: + if (internalResponse.body == null) { + processResponseEndOfBody() + } else { + // mcollina: all the following steps of the specs are skipped. + // The internal transform stream is not needed. + // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541 + + // 1. Let transformStream be a new TransformStream. + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream. + // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm + // set to processResponseEndOfBody. + // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream. + + finished(internalResponse.body.stream, () => { + processResponseEndOfBody() + }) + } +} + +// https://fetch.spec.whatwg.org/#http-fetch +async function httpFetch (fetchParams) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let actualResponse be null. + let actualResponse = null + + // 4. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 5. If request’s service-workers mode is "all", then: + if (request.serviceWorkers === 'all') { + // TODO + } + + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO + + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none' + } + + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) + + // 4. If request’s response tainting is "cors" and a CORS check + // for request and response returns failure, then return a network error. + if ( + request.responseTainting === 'cors' && + corsCheck(request, response) === 'failure' + ) { + return makeNetworkError('cors failure') + } + + // 5. If the TAO check for request and response returns failure, then set + // request’s timing allow failed flag. + if (TAOCheck(request, response) === 'failure') { + request.timingAllowFailed = true + } + } + + // 7. If either request’s response tainting or response’s type + // is "opaque", and the cross-origin resource policy check with + // request’s origin, request’s client, request’s destination, + // and actualResponse returns blocked, then return a network error. + if ( + (request.responseTainting === 'opaque' || response.type === 'opaque') && + crossOriginResourcePolicyCheck( + request.origin, + request.client, + request.destination, + actualResponse + ) === 'blocked' + ) { + return makeNetworkError('blocked') + } + + // 8. If actualResponse’s status is a redirect status, then: + if (redirectStatusSet.has(actualResponse.status)) { + // 1. If actualResponse’s status is not 303, request’s body is not null, + // and the connection uses HTTP/2, then user agents may, and are even + // encouraged to, transmit an RST_STREAM frame. + // See, https://github.com/whatwg/fetch/issues/1288 + if (request.redirect !== 'manual') { + fetchParams.controller.connection.destroy(undefined, false) + } + + // 2. Switch on request’s redirect mode: + if (request.redirect === 'error') { + // Set response to a network error. + response = makeNetworkError('unexpected redirect') + } else if (request.redirect === 'manual') { + // Set response to an opaque-redirect filtered response whose internal + // response is actualResponse. + // NOTE(spec): On the web this would return an `opaqueredirect` response, + // but that doesn't make sense server side. + // See https://github.com/nodejs/undici/issues/1193. + response = actualResponse + } else if (request.redirect === 'follow') { + // Set response to the result of running HTTP-redirect fetch given + // fetchParams and response. + response = await httpRedirectFetch(fetchParams, response) + } else { + assert(false) + } + } + + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 10. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-redirect-fetch +function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let actualResponse be response, if response is not a filtered response, + // and response’s internal response otherwise. + const actualResponse = response.internalResponse + ? response.internalResponse + : response + + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL + + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ) + + // 4. If locationURL is null, then return response. + if (locationURL == null) { + return response + } + } catch (err) { + // 5. If locationURL is failure, then return a network error. + return Promise.resolve(makeNetworkError(err)) + } + + // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network + // error. + if (!urlIsHttpHttpsScheme(locationURL)) { + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) + } + + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return Promise.resolve(makeNetworkError('redirect count exceeded')) + } + + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1 + + // 9. If request’s mode is "cors", locationURL includes credentials, and + // request’s origin is not same origin with locationURL’s origin, then return + // a network error. + if ( + request.mode === 'cors' && + (locationURL.username || locationURL.password) && + !sameOrigin(request, locationURL) + ) { + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) + } + + // 10. If request’s response tainting is "cors" and locationURL includes + // credentials, then return a network error. + if ( + request.responseTainting === 'cors' && + (locationURL.username || locationURL.password) + ) { + return Promise.resolve(makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + )) + } + + // 11. If actualResponse’s status is not 303, request’s body is non-null, + // and request’s body’s source is null, then return a network error. + if ( + actualResponse.status !== 303 && + request.body != null && + request.body.source == null + ) { + return Promise.resolve(makeNetworkError()) + } + + // 12. If one of the following is true + // - actualResponse’s status is 301 or 302 and request’s method is `POST` + // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` + if ( + ([301, 302].includes(actualResponse.status) && request.method === 'POST') || + (actualResponse.status === 303 && + !GET_OR_HEAD.includes(request.method)) + ) { + // then: + // 1. Set request’s method to `GET` and request’s body to null. + request.method = 'GET' + request.body = null + + // 2. For each headerName of request-body-header name, delete headerName from + // request’s header list. + for (const headerName of requestBodyHeader) { + request.headersList.delete(headerName) + } + } + + // 13. If request’s current URL’s origin is not same origin with locationURL’s + // origin, then for each headerName of CORS non-wildcard request-header name, + // delete headerName from request’s header list. + if (!sameOrigin(requestCurrentURL(request), locationURL)) { + // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name + request.headersList.delete('authorization', true) + + // https://fetch.spec.whatwg.org/#authentication-entries + request.headersList.delete('proxy-authorization', true) + + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie', true) + request.headersList.delete('host', true) + } + + // 14. If request’s body is non-null, then set request’s body to the first return + // value of safely extracting request’s body’s source. + if (request.body != null) { + assert(request.body.source != null) + request.body = safelyExtractBody(request.body.source)[0] + } + + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 16. Set timingInfo’s redirect end time and post-redirect start time to the + // coarsened shared current time given fetchParams’s cross-origin isolated + // capability. + timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = + coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + + // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s + // redirect start time to timingInfo’s start time. + if (timingInfo.redirectStartTime === 0) { + timingInfo.redirectStartTime = timingInfo.startTime + } + + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL) + + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse) + + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) +} + +// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch +async function httpNetworkOrCacheFetch ( + fetchParams, + isAuthenticationFetch = false, + isNewConnectionFetch = false +) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let httpFetchParams be null. + let httpFetchParams = null + + // 3. Let httpRequest be null. + let httpRequest = null + + // 4. Let response be null. + let response = null + + // 5. Let storedResponse be null. + // TODO: cache + + // 6. Let httpCache be null. + const httpCache = null + + // 7. Let the revalidatingFlag be unset. + const revalidatingFlag = false + + // 8. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If request’s window is "no-window" and request’s redirect mode is + // "error", then set httpFetchParams to fetchParams and httpRequest to + // request. + if (request.window === 'no-window' && request.redirect === 'error') { + httpFetchParams = fetchParams + httpRequest = request + } else { + // Otherwise: + + // 1. Set httpRequest to a clone of request. + httpRequest = cloneRequest(request) + + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams } + + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest + } + + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic') + + // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s + // body is non-null; otherwise null. + const contentLength = httpRequest.body ? httpRequest.body.length : null + + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null + + // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or + // `PUT`, then set contentLengthHeaderValue to `0`. + if ( + httpRequest.body == null && + ['POST', 'PUT'].includes(httpRequest.method) + ) { + contentLengthHeaderValue = '0' + } + + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) + } + + // 8. If contentLengthHeaderValue is non-null, then append + // `Content-Length`/contentLengthHeaderValue to httpRequest’s header + // list. + if (contentLengthHeaderValue != null) { + httpRequest.headersList.append('content-length', contentLengthHeaderValue, true) + } + + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. + + // 10. If contentLength is non-null and httpRequest’s keepalive is true, + // then: + if (contentLength != null && httpRequest.keepalive) { + // NOTE: keepalive is a noop outside of browser context. + } + + // 11. If httpRequest’s referrer is a URL, then append + // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, + // to httpRequest’s header list. + if (httpRequest.referrer instanceof URL) { + httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true) + } + + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest) + + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest) + + // 14. If httpRequest’s header list does not contain `User-Agent`, then + // user agents should append `User-Agent`/default `User-Agent` value to + // httpRequest’s header list. + if (!httpRequest.headersList.contains('user-agent', true)) { + httpRequest.headersList.append('user-agent', defaultUserAgent) + } + + // 15. If httpRequest’s cache mode is "default" and httpRequest’s header + // list contains `If-Modified-Since`, `If-None-Match`, + // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set + // httpRequest’s cache mode to "no-store". + if ( + httpRequest.cache === 'default' && + (httpRequest.headersList.contains('if-modified-since', true) || + httpRequest.headersList.contains('if-none-match', true) || + httpRequest.headersList.contains('if-unmodified-since', true) || + httpRequest.headersList.contains('if-match', true) || + httpRequest.headersList.contains('if-range', true)) + ) { + httpRequest.cache = 'no-store' + } + + // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent + // no-cache cache-control header modification flag is unset, and + // httpRequest’s header list does not contain `Cache-Control`, then append + // `Cache-Control`/`max-age=0` to httpRequest’s header list. + if ( + httpRequest.cache === 'no-cache' && + !httpRequest.preventNoCacheCacheControlHeaderModification && + !httpRequest.headersList.contains('cache-control', true) + ) { + httpRequest.headersList.append('cache-control', 'max-age=0', true) + } + + // 17. If httpRequest’s cache mode is "no-store" or "reload", then: + if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { + // 1. If httpRequest’s header list does not contain `Pragma`, then append + // `Pragma`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('pragma', true)) { + httpRequest.headersList.append('pragma', 'no-cache', true) + } + + // 2. If httpRequest’s header list does not contain `Cache-Control`, + // then append `Cache-Control`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('cache-control', true)) { + httpRequest.headersList.append('cache-control', 'no-cache', true) + } + } + + // 18. If httpRequest’s header list contains `Range`, then append + // `Accept-Encoding`/`identity` to httpRequest’s header list. + if (httpRequest.headersList.contains('range', true)) { + httpRequest.headersList.append('accept-encoding', 'identity', true) + } + + // 19. Modify httpRequest’s header list per HTTP. Do not append a given + // header if httpRequest’s header list contains that header’s name. + // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 + if (!httpRequest.headersList.contains('accept-encoding', true)) { + if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { + httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true) + } else { + httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true) + } + } + + httpRequest.headersList.delete('host', true) + + // 20. If includeCredentials is true, then: + if (includeCredentials) { + // 1. If the user agent is not configured to block cookies for httpRequest + // (see section 7 of [COOKIES]), then: + // TODO: credentials + // 2. If httpRequest’s header list does not contain `Authorization`, then: + // TODO: credentials + } + + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication + + // 22. Set httpCache to the result of determining the HTTP cache + // partition, given httpRequest. + // TODO: cache + + // 23. If httpCache is null, then set httpRequest’s cache mode to + // "no-store". + if (httpCache == null) { + httpRequest.cache = 'no-store' + } + + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') { + // TODO: cache + } + + // 9. If aborted, then return the appropriate network error for fetchParams. + // TODO + + // 10. If response is null, then: + if (response == null) { + // 1. If httpRequest’s cache mode is "only-if-cached", then return a + // network error. + if (httpRequest.cache === 'only-if-cached') { + return makeNetworkError('only if cached') + } + + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ) + + // 3. If httpRequest’s method is unsafe and forwardResponse’s status is + // in the range 200 to 399, inclusive, invalidate appropriate stored + // responses in httpCache, as per the "Invalidation" chapter of HTTP + // Caching, and set storedResponse to null. [HTTP-CACHING] + if ( + !safeMethodsSet.has(httpRequest.method) && + forwardResponse.status >= 200 && + forwardResponse.status <= 399 + ) { + // TODO: cache + } + + // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, + // then: + if (revalidatingFlag && forwardResponse.status === 304) { + // TODO: cache + } + + // 5. If response is null, then: + if (response == null) { + // 1. Set response to forwardResponse. + response = forwardResponse + + // 2. Store httpRequest and forwardResponse in httpCache, as per the + // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] + // TODO: cache + } + } + + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList] + + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range', true)) { + response.rangeRequested = true + } + + // 13. Set response’s request-includes-credentials to includeCredentials. + response.requestIncludesCredentials = includeCredentials + + // 14. If response’s status is 401, httpRequest’s response tainting is not + // "cors", includeCredentials is true, and request’s window is an environment + // settings object, then: + // TODO + + // 15. If response’s status is 407, then: + if (response.status === 407) { + // 1. If request’s window is "no-window", then return a network error. + if (request.window === 'no-window') { + return makeNetworkError() + } + + // 2. ??? + + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 4. Prompt the end user as appropriate in request’s window and store + // the result as a proxy-authentication entry. [HTTP-AUTH] + // TODO: Invoke some kind of callback? + + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') + } + + // 16. If all of the following are true + if ( + // response’s status is 421 + response.status === 421 && + // isNewConnectionFetch is false + !isNewConnectionFetch && + // request’s body is null, or request’s body is non-null and request’s body’s source is non-null + (request.body == null || request.body.source != null) + ) { + // then: + + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. + + // TODO (spec): The spec doesn't specify this but we need to cancel + // the active response before we can start a new one. + // https://github.com/whatwg/fetch/issues/1293 + fetchParams.controller.connection.destroy() + + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ) + } + + // 17. If isAuthenticationFetch is true, then create an authentication entry + if (isAuthenticationFetch) { + // TODO + } + + // 18. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-network-fetch +async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false +) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) + + fetchParams.controller.connection = { + abort: null, + destroyed: false, + destroy (err, abort = true) { + if (!this.destroyed) { + this.destroyed = true + if (abort) { + this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) + } + } + } + } + + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 4. Let httpCache be the result of determining the HTTP cache partition, + // given request. + // TODO: cache + const httpCache = null + + // 5. If httpCache is null, then set request’s cache mode to "no-store". + if (httpCache == null) { + request.cache = 'no-store' + } + + // 6. Let networkPartitionKey be the result of determining the network + // partition key given request. + // TODO + + // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise + // "no". + const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars + + // 8. Switch on request’s mode: + if (request.mode === 'websocket') { + // Let connection be the result of obtaining a WebSocket connection, + // given request’s current URL. + // TODO + } else { + // Let connection be the result of obtaining a connection, given + // networkPartitionKey, request’s current URL’s origin, + // includeCredentials, and forceNewConnection. + // TODO + } + + // 9. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If connection is failure, then return a network error. + + // 2. Set timingInfo’s final connection timing info to the result of + // calling clamp and coarsen connection timing info with connection’s + // timing info, timingInfo’s post-redirect start time, and fetchParams’s + // cross-origin isolated capability. + + // 3. If connection is not an HTTP/2 connection, request’s body is non-null, + // and request’s body’s source is null, then append (`Transfer-Encoding`, + // `chunked`) to request’s header list. + + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. + + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: + + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] + + // - If request’s body is non-null, and request’s body’s source is null, + // then the user agent may have a buffer of up to 64 kibibytes and store + // a part of request’s body in that buffer. If the user agent reads from + // request’s body beyond that buffer’s size and the user agent needs to + // resend request, then instead return a network error. + + // - Set timingInfo’s final network-response start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated capability, + // immediately after the user agent’s HTTP parser receives the first byte + // of the response (e.g., frame header bytes for HTTP/2 or response status + // line for HTTP/1.x). + + // - Wait until all the headers are transmitted. + + // - Any responses whose status is in the range 100 to 199, inclusive, + // and is not 101, are to be ignored, except for the purposes of setting + // timingInfo’s final network-response start time above. + + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. + + // - If the HTTP request results in a TLS client certificate dialog, then: + + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. + + // 2. Otherwise, return a network error. + + // To transmit request’s body body, run these steps: + let requestBody = null + // 1. If body is null and fetchParams’s process request end-of-body is + // non-null, then queue a fetch task given fetchParams’s process request + // end-of-body and fetchParams’s task destination. + if (request.body == null && fetchParams.processRequestEndOfBody) { + queueMicrotask(() => fetchParams.processRequestEndOfBody()) + } else if (request.body != null) { + // 2. Otherwise, if body is non-null: + + // 1. Let processBodyChunk given bytes be these steps: + const processBodyChunk = async function * (bytes) { + // 1. If the ongoing fetch is terminated, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. Run this step in parallel: transmit bytes. + yield bytes + + // 3. If fetchParams’s process request body is non-null, then run + // fetchParams’s process request body given bytes’s length. + fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) + } + + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If fetchParams’s process request end-of-body is non-null, + // then run fetchParams’s process request end-of-body. + if (fetchParams.processRequestEndOfBody) { + fetchParams.processRequestEndOfBody() + } + } + + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort() + } else { + fetchParams.controller.terminate(e) + } + } + + // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, + // processBodyError, and fetchParams’s task destination. + requestBody = (async function * () { + try { + for await (const bytes of request.body.stream) { + yield * processBodyChunk(bytes) + } + processEndOfBody() + } catch (err) { + processBodyError(err) + } + })() + } + + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) + + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }) + } else { + const iterator = body[Symbol.asyncIterator]() + fetchParams.controller.next = () => iterator.next() + + response = makeResponse({ status, statusText, headersList }) + } + } catch (err) { + // 10. If aborted, then: + if (err.name === 'AbortError') { + // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. + fetchParams.controller.connection.destroy() + + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) + } + + return makeNetworkError(err) + } + + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = async () => { + await fetchParams.controller.resume() + } + + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + // If the aborted fetch was already terminated, then we do not + // need to do anything. + if (!isCancelled(fetchParams)) { + fetchParams.controller.abort(reason) + } + } + + // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by + // the user agent. + // TODO + + // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object + // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. + // TODO + + // 15. Let stream be a new ReadableStream. + // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm, + // cancelAlgorithm set to cancelAlgorithm. + const stream = new ReadableStream( + { + async start (controller) { + fetchParams.controller.controller = controller + }, + async pull (controller) { + await pullAlgorithm(controller) + }, + async cancel (reason) { + await cancelAlgorithm(reason) + }, + type: 'bytes' + } + ) + + // 17. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. Set response’s body to a new body whose stream is stream. + response.body = { stream, source: null, length: null } + + // 2. If response is not a network error and request’s cache mode is + // not "no-store", then update response in httpCache for request. + // TODO + + // 3. If includeCredentials is true and the user agent is not configured + // to block cookies for request (see section 7 of [COOKIES]), then run the + // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on + // the value of each header whose name is a byte-case-insensitive match for + // `Set-Cookie` in response’s header list, if any, and request’s current URL. + // TODO + + // 18. If aborted, then: + // TODO + + // 19. Run these steps in parallel: + + // 1. Run these steps, but abort when fetchParams is canceled: + fetchParams.controller.onAborted = onAborted + fetchParams.controller.on('terminated', onAborted) + fetchParams.controller.resume = async () => { + // 1. While true + while (true) { + // 1-3. See onData... + + // 4. Set bytes to the result of handling content codings given + // codings and bytes. + let bytes + let isFailure + try { + const { done, value } = await fetchParams.controller.next() + + if (isAborted(fetchParams)) { + break + } + + bytes = done ? undefined : value + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined + } else { + bytes = err + + // err may be propagated from the result of calling readablestream.cancel, + // which might not be an error. https://github.com/nodejs/undici/issues/2009 + isFailure = true + } + } + + if (bytes === undefined) { + // 2. Otherwise, if the bytes transmission for response’s message + // body is done normally and stream is readable, then close + // stream, finalize response for fetchParams and response, and + // abort these in-parallel steps. + readableStreamClose(fetchParams.controller.controller) + + finalizeResponse(fetchParams, response) + + return + } + + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0 + + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes) + return + } + + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + const buffer = new Uint8Array(bytes) + if (buffer.byteLength) { + fetchParams.controller.controller.enqueue(buffer) + } + + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate() + return + } + + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (fetchParams.controller.controller.desiredSize <= 0) { + return + } + } + } + + // 2. If aborted, then: + function onAborted (reason) { + // 2. If fetchParams is aborted, then: + if (isAborted(fetchParams)) { + // 1. Set response’s aborted flag. + response.aborted = true + + // 2. If stream is readable, then error stream with the result of + // deserialize a serialized abort reason given fetchParams’s + // controller’s serialized abort reason and an + // implementation-defined realm. + if (isReadable(stream)) { + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ) + } + } else { + // 3. Otherwise, if stream is readable, error stream with a TypeError. + if (isReadable(stream)) { + fetchParams.controller.controller.error(new TypeError('terminated', { + cause: isErrorLike(reason) ? reason : undefined + })) + } + } + + // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. + // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. + fetchParams.controller.connection.destroy() + } + + // 20. Return response. + return response + + function dispatch ({ body }) { + const url = requestCurrentURL(request) + /** @type {import('../..').Agent} */ + const agent = fetchParams.controller.dispatcher + + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body, + headers: request.headersList.entries, + maxRedirections: 0, + upgrade: request.mode === 'websocket' ? 'websocket' : undefined + }, + { + body: null, + abort: null, + + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller + + // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen + // connection timing info with connection’s timing info, timingInfo’s post-redirect start + // time, and fetchParams’s cross-origin isolated capability. + // TODO: implement connection timing + timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability) + + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')) + } else { + fetchParams.controller.on('terminated', abort) + this.abort = connection.abort = abort + } + + // Set timingInfo’s final network-request start time to the coarsened shared current time given + // fetchParams’s cross-origin isolated capability. + timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + }, + + onResponseStarted () { + // Set timingInfo’s final network-response start time to the coarsened shared current + // time given fetchParams’s cross-origin isolated capability, immediately after the + // user agent’s HTTP parser receives the first byte of the response (e.g., frame header + // bytes for HTTP/2 or response status line for HTTP/1.x). + timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + }, + + onHeaders (status, rawHeaders, resume, statusText) { + if (status < 200) { + return + } + + let location = '' + + const headersList = new HeadersList() + + for (let i = 0; i < rawHeaders.length; i += 2) { + headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true) + } + location = headersList.get('location', true) + + this.body = new Readable({ read: resume }) + + const decoders = [] + + const willFollow = location && request.redirect === 'follow' && + redirectStatusSet.has(status) + + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + const contentEncoding = headersList.get('content-encoding', true) + // "All content-coding values are case-insensitive..." + /** @type {string[]} */ + const codings = contentEncoding ? contentEncoding.toLowerCase().split(',') : [] + + // Limit the number of content-encodings to prevent resource exhaustion. + // CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206). + const maxContentEncodings = 5 + if (codings.length > maxContentEncodings) { + reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`)) + return true + } + + for (let i = codings.length - 1; i >= 0; --i) { + const coding = codings[i].trim() + // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 + if (coding === 'x-gzip' || coding === 'gzip') { + decoders.push(zlib.createGunzip({ + // 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. + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })) + } else if (coding === 'deflate') { + decoders.push(createInflate({ + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })) + } else if (coding === 'br') { + decoders.push(zlib.createBrotliDecompress({ + flush: zlib.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH + })) + } else { + decoders.length = 0 + break + } + } + } + + const onError = this.onError.bind(this) + + resolve({ + status, + statusText, + headersList, + body: decoders.length + ? pipeline(this.body, ...decoders, (err) => { + if (err) { + this.onError(err) + } + }).on('error', onError) + : this.body.on('error', onError) + }) + + return true + }, + + onData (chunk) { + if (fetchParams.controller.dump) { + return + } + + // 1. If one or more bytes have been transmitted from response’s + // message body, then: + + // 1. Let bytes be the transmitted bytes. + const bytes = chunk + + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. + + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength + + // 4. See pullAlgorithm... + + return this.body.push(bytes) + }, + + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + if (fetchParams.controller.onAborted) { + fetchParams.controller.off('terminated', fetchParams.controller.onAborted) + } + + fetchParams.controller.ended = true + + this.body.push(null) + }, + + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + this.body?.destroy(error) + + fetchParams.controller.terminate(error) + + reject(error) + }, + + onUpgrade (status, rawHeaders, socket) { + if (status !== 101) { + return + } + + const headersList = new HeadersList() + + for (let i = 0; i < rawHeaders.length; i += 2) { + headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true) + } + + resolve({ + status, + statusText: STATUS_CODES[status], + headersList, + socket + }) + + return true + } + } + )) + } +} + +module.exports = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming +} diff --git a/node_modules/undici/lib/web/fetch/request.js b/node_modules/undici/lib/web/fetch/request.js new file mode 100644 index 0000000000000..ee3ce488774c5 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/request.js @@ -0,0 +1,1037 @@ +/* globals AbortController */ + +'use strict' + +const { extractBody, mixinBody, cloneBody, bodyUnusable } = require('./body') +const { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require('./headers') +const { FinalizationRegistry } = require('./dispatcher-weakref')() +const util = require('../../core/util') +const nodeUtil = require('node:util') +const { + isValidHTTPToken, + sameOrigin, + environmentSettingsObject +} = require('./util') +const { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex +} = require('./constants') +const { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util +const { kHeaders, kSignal, kState, kDispatcher } = require('./symbols') +const { webidl } = require('./webidl') +const { URLSerializer } = require('./data-url') +const { kConstruct } = require('../../core/symbols') +const assert = require('node:assert') +const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = require('node:events') + +const kAbortController = Symbol('abortController') + +const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort) +}) + +const dependentControllerMap = new WeakMap() + +function buildAbort (acRef) { + return abort + + function abort () { + const ac = acRef.deref() + if (ac !== undefined) { + // Currently, there is a problem with FinalizationRegistry. + // https://github.com/nodejs/node/issues/49344 + // https://github.com/nodejs/node/issues/47748 + // In the case of abort, the first step is to unregister from it. + // If the controller can refer to it, it is still registered. + // It will be removed in the future. + requestFinalizer.unregister(abort) + + // Unsubscribe a listener. + // FinalizationRegistry will no longer be called, so this must be done. + this.removeEventListener('abort', abort) + + ac.abort(this.reason) + + const controllerList = dependentControllerMap.get(ac.signal) + + if (controllerList !== undefined) { + if (controllerList.size !== 0) { + for (const ref of controllerList) { + const ctrl = ref.deref() + if (ctrl !== undefined) { + ctrl.abort(this.reason) + } + } + controllerList.clear() + } + dependentControllerMap.delete(ac.signal) + } + } + } +} + +let patchMethodWarning = false + +// https://fetch.spec.whatwg.org/#request-class +class Request { + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = {}) { + webidl.util.markAsUncloneable(this) + if (input === kConstruct) { + return + } + + const prefix = 'Request constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + input = webidl.converters.RequestInfo(input, prefix, 'input') + init = webidl.converters.RequestInit(init, prefix, 'init') + + // 1. Let request be null. + let request = null + + // 2. Let fallbackMode be null. + let fallbackMode = null + + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = environmentSettingsObject.settingsObject.baseUrl + + // 4. Let signal be null. + let signal = null + + // 5. If input is a string, then: + if (typeof input === 'string') { + this[kDispatcher] = init.dispatcher + + // 1. Let parsedURL be the result of parsing input with baseURL. + // 2. If parsedURL is failure, then throw a TypeError. + let parsedURL + try { + parsedURL = new URL(input, baseUrl) + } catch (err) { + throw new TypeError('Failed to parse URL from ' + input, { cause: err }) + } + + // 3. If parsedURL includes credentials, then throw a TypeError. + if (parsedURL.username || parsedURL.password) { + throw new TypeError( + 'Request cannot be constructed from a URL that includes credentials: ' + + input + ) + } + + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }) + + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors' + } else { + this[kDispatcher] = init.dispatcher || input[kDispatcher] + + // 6. Otherwise: + + // 7. Assert: input is a Request object. + assert(input instanceof Request) + + // 8. Set request to input’s request. + request = input[kState] + + // 9. Set signal to input’s signal. + signal = input[kSignal] + } + + // 7. Let origin be this’s relevant settings object’s origin. + const origin = environmentSettingsObject.settingsObject.origin + + // 8. Let window be "client". + let window = 'client' + + // 9. If request’s window is an environment settings object and its origin + // is same origin with origin, then set window to request’s window. + if ( + request.window?.constructor?.name === 'EnvironmentSettingsObject' && + sameOrigin(request.window, origin) + ) { + window = request.window + } + + // 10. If init["window"] exists and is non-null, then throw a TypeError. + if (init.window != null) { + throw new TypeError(`'window' option '${window}' must be null`) + } + + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window' + } + + // 12. Set request to a new request with the following properties: + request = makeRequest({ + // URL request’s URL. + // undici implementation note: this is set as the first item in request's urlList in makeRequest + // method request’s method. + method: request.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest + headersList: request.headersList, + // unsafe-request flag Set. + unsafeRequest: request.unsafeRequest, + // client This’s relevant settings object. + client: environmentSettingsObject.settingsObject, + // window window. + window, + // priority request’s priority. + priority: request.priority, + // origin request’s origin. The propagation of the origin is only significant for navigation requests + // being handled by a service worker. In this scenario a request can have an origin that is different + // from the current client. + origin: request.origin, + // referrer request’s referrer. + referrer: request.referrer, + // referrer policy request’s referrer policy. + referrerPolicy: request.referrerPolicy, + // mode request’s mode. + mode: request.mode, + // credentials mode request’s credentials mode. + credentials: request.credentials, + // cache mode request’s cache mode. + cache: request.cache, + // redirect mode request’s redirect mode. + redirect: request.redirect, + // integrity metadata request’s integrity metadata. + integrity: request.integrity, + // keepalive request’s keepalive. + keepalive: request.keepalive, + // reload-navigation flag request’s reload-navigation flag. + reloadNavigation: request.reloadNavigation, + // history-navigation flag request’s history-navigation flag. + historyNavigation: request.historyNavigation, + // URL list A clone of request’s URL list. + urlList: [...request.urlList] + }) + + const initHasKey = Object.keys(init).length !== 0 + + // 13. If init is not empty, then: + if (initHasKey) { + // 1. If request’s mode is "navigate", then set it to "same-origin". + if (request.mode === 'navigate') { + request.mode = 'same-origin' + } + + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false + + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false + + // 4. Set request’s origin to "client". + request.origin = 'client' + + // 5. Set request’s referrer to "client" + request.referrer = 'client' + + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = '' + + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1] + + // 8. Set request’s URL list to « request’s URL ». + request.urlList = [request.url] + } + + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer + + // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". + if (referrer === '') { + request.referrer = 'no-referrer' + } else { + // 1. Let parsedReferrer be the result of parsing referrer with + // baseURL. + // 2. If parsedReferrer is failure, then throw a TypeError. + let parsedReferrer + try { + parsedReferrer = new URL(referrer, baseUrl) + } catch (err) { + throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) + } + + // 3. If one of the following is true + // - parsedReferrer’s scheme is "about" and path is the string "client" + // - parsedReferrer’s origin is not same origin with origin + // then set request’s referrer to "client". + if ( + (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || + (origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) + ) { + request.referrer = 'client' + } else { + // 4. Otherwise, set request’s referrer to parsedReferrer. + request.referrer = parsedReferrer + } + } + } + + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy + } + + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode + if (init.mode !== undefined) { + mode = init.mode + } else { + mode = fallbackMode + } + + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) + } + + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode + } + + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials + } + + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache + } + + // 21. If request’s cache mode is "only-if-cached" and request’s mode is + // not "same-origin", then throw a TypeError. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ) + } + + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect + } + + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity != null) { + request.integrity = String(init.integrity) + } + + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive) + } + + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method + + const mayBeNormalized = normalizedMethodRecords[method] + + if (mayBeNormalized !== undefined) { + // Note: Bypass validation DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH and these lowercase ones + request.method = mayBeNormalized + } else { + // 2. If method is not a method or method is a forbidden method, then + // throw a TypeError. + if (!isValidHTTPToken(method)) { + throw new TypeError(`'${method}' is not a valid HTTP method.`) + } + + const upperCase = method.toUpperCase() + + if (forbiddenMethodsSet.has(upperCase)) { + throw new TypeError(`'${method}' HTTP method is unsupported.`) + } + + // 3. Normalize method. + // https://fetch.spec.whatwg.org/#concept-method-normalize + // Note: must be in uppercase + method = normalizedMethodRecordsBase[upperCase] ?? method + + // 4. Set request’s method to method. + request.method = method + } + + if (!patchMethodWarning && request.method === 'patch') { + process.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', { + code: 'UNDICI-FETCH-patch' + }) + + patchMethodWarning = true + } + } + + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal + } + + // 27. Set this’s request to request. + this[kState] = request + + // 28. Set this’s signal to a new AbortSignal object with this’s relevant + // Realm. + // TODO: could this be simplified with AbortSignal.any + // (https://dom.spec.whatwg.org/#dom-abortsignal-any) + const ac = new AbortController() + this[kSignal] = ac.signal + + // 29. If signal is not null, then make this’s signal follow signal. + if (signal != null) { + if ( + !signal || + typeof signal.aborted !== 'boolean' || + typeof signal.addEventListener !== 'function' + ) { + throw new TypeError( + "Failed to construct 'Request': member signal is not of type AbortSignal." + ) + } + + if (signal.aborted) { + ac.abort(signal.reason) + } else { + // Keep a strong ref to ac while request object + // is alive. This is needed to prevent AbortController + // from being prematurely garbage collected. + // See, https://github.com/nodejs/undici/issues/1926. + this[kAbortController] = ac + + const acRef = new WeakRef(ac) + const abort = buildAbort(acRef) + + // Third-party AbortControllers may not work with these. + // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. + try { + // If the max amount of listeners is equal to the default, increase it + // This is only available in node >= v19.9.0 + if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { + setMaxListeners(1500, signal) + } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { + setMaxListeners(1500, signal) + } + } catch {} + + util.addAbortListener(signal, abort) + // The third argument must be a registry key to be unregistered. + // Without it, you cannot unregister. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + // abort is used as the unregister key. (because it is unique) + requestFinalizer.register(ac, { signal, abort }, abort) + } + } + + // 30. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is request’s header list and guard is + // "request". + this[kHeaders] = new Headers(kConstruct) + setHeadersList(this[kHeaders], request.headersList) + setHeadersGuard(this[kHeaders], 'request') + + // 31. If this’s request’s mode is "no-cors", then: + if (mode === 'no-cors') { + // 1. If this’s request’s method is not a CORS-safelisted method, + // then throw a TypeError. + if (!corsSafeListedMethodsSet.has(request.method)) { + throw new TypeError( + `'${request.method} is unsupported in no-cors mode.` + ) + } + + // 2. Set this’s headers’s guard to "request-no-cors". + setHeadersGuard(this[kHeaders], 'request-no-cors') + } + + // 32. If init is not empty, then: + if (initHasKey) { + /** @type {HeadersList} */ + const headersList = getHeadersList(this[kHeaders]) + // 1. Let headers be a copy of this’s headers and its associated header + // list. + // 2. If init["headers"] exists, then set headers to init["headers"]. + const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) + + // 3. Empty this’s headers’s header list. + headersList.clear() + + // 4. If headers is a Headers object, then for each header in its header + // list, append header’s name/header’s value to this’s headers. + if (headers instanceof HeadersList) { + for (const { name, value } of headers.rawValues()) { + headersList.append(name, value, false) + } + // Note: Copy the `set-cookie` meta-data. + headersList.cookies = headers.cookies + } else { + // 5. Otherwise, fill this’s headers with headers. + fillHeaders(this[kHeaders], headers) + } + } + + // 33. Let inputBody be input’s request’s body if input is a Request + // object; otherwise null. + const inputBody = input instanceof Request ? input[kState].body : null + + // 34. If either init["body"] exists and is non-null or inputBody is + // non-null, and request’s method is `GET` or `HEAD`, then throw a + // TypeError. + if ( + (init.body != null || inputBody != null) && + (request.method === 'GET' || request.method === 'HEAD') + ) { + throw new TypeError('Request with GET/HEAD method cannot have body.') + } + + // 35. Let initBody be null. + let initBody = null + + // 36. If init["body"] exists and is non-null, then: + if (init.body != null) { + // 1. Let Content-Type be null. + // 2. Set initBody and Content-Type to the result of extracting + // init["body"], with keepalive set to request’s keepalive. + const [extractedBody, contentType] = extractBody( + init.body, + request.keepalive + ) + initBody = extractedBody + + // 3, If Content-Type is non-null and this’s headers’s header list does + // not contain `Content-Type`, then append `Content-Type`/Content-Type to + // this’s headers. + if (contentType && !getHeadersList(this[kHeaders]).contains('content-type', true)) { + this[kHeaders].append('content-type', contentType) + } + } + + // 37. Let inputOrInitBody be initBody if it is non-null; otherwise + // inputBody. + const inputOrInitBody = initBody ?? inputBody + + // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is + // null, then: + if (inputOrInitBody != null && inputOrInitBody.source == null) { + // 1. If initBody is non-null and init["duplex"] does not exist, + // then throw a TypeError. + if (initBody != null && init.duplex == null) { + throw new TypeError('RequestInit: duplex option is required when sending a body.') + } + + // 2. If this’s request’s mode is neither "same-origin" nor "cors", + // then throw a TypeError. + if (request.mode !== 'same-origin' && request.mode !== 'cors') { + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ) + } + + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true + } + + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody + + // 40. If initBody is null and inputBody is non-null, then: + if (initBody == null && inputBody != null) { + // 1. If input is unusable, then throw a TypeError. + if (bodyUnusable(input)) { + throw new TypeError( + 'Cannot construct a Request with a Request object that has already been used.' + ) + } + + // 2. Set finalBody to the result of creating a proxy for inputBody. + // https://streams.spec.whatwg.org/#readablestream-create-a-proxy + const identityTransform = new TransformStream() + inputBody.stream.pipeThrough(identityTransform) + finalBody = { + source: inputBody.source, + length: inputBody.length, + stream: identityTransform.readable + } + } + + // 41. Set this’s request’s body to finalBody. + this[kState].body = finalBody + } + + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request) + + // The method getter steps are to return this’s request’s method. + return this[kState].method + } + + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request) + + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this[kState].url) + } + + // Returns a Headers object consisting of the headers associated with request. + // Note that headers added in the network layer by the user agent will not + // be accounted for in this object, e.g., the "Host" header. + get headers () { + webidl.brandCheck(this, Request) + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request) + + // The destination getter are to return this’s request’s destination. + return this[kState].destination + } + + // Returns the referrer of request. Its value can be a same-origin URL if + // explicitly set in init, the empty string to indicate no referrer, and + // "about:client" when defaulting to the global’s default. This is used + // during fetching to determine the value of the `Referer` header of the + // request being made. + get referrer () { + webidl.brandCheck(this, Request) + + // 1. If this’s request’s referrer is "no-referrer", then return the + // empty string. + if (this[kState].referrer === 'no-referrer') { + return '' + } + + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this[kState].referrer === 'client') { + return 'about:client' + } + + // Return this’s request’s referrer, serialized. + return this[kState].referrer.toString() + } + + // Returns the referrer policy associated with request. + // This is used during fetching to compute the value of the request’s + // referrer. + get referrerPolicy () { + webidl.brandCheck(this, Request) + + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this[kState].referrerPolicy + } + + // Returns the mode associated with request, which is a string indicating + // whether the request will use CORS, or will be restricted to same-origin + // URLs. + get mode () { + webidl.brandCheck(this, Request) + + // The mode getter steps are to return this’s request’s mode. + return this[kState].mode + } + + // Returns the credentials mode associated with request, + // which is a string indicating whether credentials will be sent with the + // request always, never, or only when sent to a same-origin URL. + get credentials () { + // The credentials getter steps are to return this’s request’s credentials mode. + return this[kState].credentials + } + + // Returns the cache mode associated with request, + // which is a string indicating how the request will + // interact with the browser’s cache when fetching. + get cache () { + webidl.brandCheck(this, Request) + + // The cache getter steps are to return this’s request’s cache mode. + return this[kState].cache + } + + // Returns the redirect mode associated with request, + // which is a string indicating how redirects for the + // request will be handled during fetching. A request + // will follow redirects by default. + get redirect () { + webidl.brandCheck(this, Request) + + // The redirect getter steps are to return this’s request’s redirect mode. + return this[kState].redirect + } + + // Returns request’s subresource integrity metadata, which is a + // cryptographic hash of the resource being fetched. Its value + // consists of multiple hashes separated by whitespace. [SRI] + get integrity () { + webidl.brandCheck(this, Request) + + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this[kState].integrity + } + + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request) + + // The keepalive getter steps are to return this’s request’s keepalive. + return this[kState].keepalive + } + + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request) + + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this[kState].reloadNavigation + } + + // Returns a boolean indicating whether or not request is for a history + // navigation (a.k.a. back-forward navigation). + get isHistoryNavigation () { + webidl.brandCheck(this, Request) + + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this[kState].historyNavigation + } + + // Returns the signal associated with request, which is an AbortSignal + // object indicating whether or not request has been aborted, and its + // abort event handler. + get signal () { + webidl.brandCheck(this, Request) + + // The signal getter steps are to return this’s signal. + return this[kSignal] + } + + get body () { + webidl.brandCheck(this, Request) + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Request) + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + get duplex () { + webidl.brandCheck(this, Request) + + return 'half' + } + + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request) + + // 1. If this is unusable, then throw a TypeError. + if (bodyUnusable(this)) { + throw new TypeError('unusable') + } + + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this[kState]) + + // 3. Let clonedRequestObject be the result of creating a Request object, + // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. + // 4. Make clonedRequestObject’s signal follow this’s signal. + const ac = new AbortController() + if (this.signal.aborted) { + ac.abort(this.signal.reason) + } else { + let list = dependentControllerMap.get(this.signal) + if (list === undefined) { + list = new Set() + dependentControllerMap.set(this.signal, list) + } + const acRef = new WeakRef(ac) + list.add(acRef) + util.addAbortListener( + ac.signal, + buildAbort(acRef) + ) + } + + // 4. Return clonedRequestObject. + return fromInnerRequest(clonedRequest, ac.signal, getHeadersGuard(this[kHeaders])) + } + + [nodeUtil.inspect.custom] (depth, options) { + if (options.depth === null) { + options.depth = 2 + } + + options.colors ??= true + + const properties = { + method: this.method, + url: this.url, + headers: this.headers, + destination: this.destination, + referrer: this.referrer, + referrerPolicy: this.referrerPolicy, + mode: this.mode, + credentials: this.credentials, + cache: this.cache, + redirect: this.redirect, + integrity: this.integrity, + keepalive: this.keepalive, + isReloadNavigation: this.isReloadNavigation, + isHistoryNavigation: this.isHistoryNavigation, + signal: this.signal + } + + return `Request ${nodeUtil.formatWithOptions(options, properties)}` + } +} + +mixinBody(Request) + +// https://fetch.spec.whatwg.org/#requests +function makeRequest (init) { + return { + method: init.method ?? 'GET', + localURLsOnly: init.localURLsOnly ?? false, + unsafeRequest: init.unsafeRequest ?? false, + body: init.body ?? null, + client: init.client ?? null, + reservedClient: init.reservedClient ?? null, + replacesClientId: init.replacesClientId ?? '', + window: init.window ?? 'client', + keepalive: init.keepalive ?? false, + serviceWorkers: init.serviceWorkers ?? 'all', + initiator: init.initiator ?? '', + destination: init.destination ?? '', + priority: init.priority ?? null, + origin: init.origin ?? 'client', + policyContainer: init.policyContainer ?? 'client', + referrer: init.referrer ?? 'client', + referrerPolicy: init.referrerPolicy ?? '', + mode: init.mode ?? 'no-cors', + useCORSPreflightFlag: init.useCORSPreflightFlag ?? false, + credentials: init.credentials ?? 'same-origin', + useCredentials: init.useCredentials ?? false, + cache: init.cache ?? 'default', + redirect: init.redirect ?? 'follow', + integrity: init.integrity ?? '', + cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? '', + parserMetadata: init.parserMetadata ?? '', + reloadNavigation: init.reloadNavigation ?? false, + historyNavigation: init.historyNavigation ?? false, + userActivation: init.userActivation ?? false, + taintedOrigin: init.taintedOrigin ?? false, + redirectCount: init.redirectCount ?? 0, + responseTainting: init.responseTainting ?? 'basic', + preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false, + done: init.done ?? false, + timingAllowFailed: init.timingAllowFailed ?? false, + urlList: init.urlList, + url: init.urlList[0], + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList() + } +} + +// https://fetch.spec.whatwg.org/#concept-request-clone +function cloneRequest (request) { + // To clone a request request, run these steps: + + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }) + + // 2. If request’s body is non-null, set newRequest’s body to the + // result of cloning request’s body. + if (request.body != null) { + newRequest.body = cloneBody(newRequest, request.body) + } + + // 3. Return newRequest. + return newRequest +} + +/** + * @see https://fetch.spec.whatwg.org/#request-create + * @param {any} innerRequest + * @param {AbortSignal} signal + * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard + * @returns {Request} + */ +function fromInnerRequest (innerRequest, signal, guard) { + const request = new Request(kConstruct) + request[kState] = innerRequest + request[kSignal] = signal + request[kHeaders] = new Headers(kConstruct) + setHeadersList(request[kHeaders], innerRequest.headersList) + setHeadersGuard(request[kHeaders], guard) + return request +} + +Object.defineProperties(Request.prototype, { + method: kEnumerableProperty, + url: kEnumerableProperty, + headers: kEnumerableProperty, + redirect: kEnumerableProperty, + clone: kEnumerableProperty, + signal: kEnumerableProperty, + duplex: kEnumerableProperty, + destination: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + isHistoryNavigation: kEnumerableProperty, + isReloadNavigation: kEnumerableProperty, + keepalive: kEnumerableProperty, + integrity: kEnumerableProperty, + cache: kEnumerableProperty, + credentials: kEnumerableProperty, + attribute: kEnumerableProperty, + referrerPolicy: kEnumerableProperty, + referrer: kEnumerableProperty, + mode: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Request', + configurable: true + } +}) + +webidl.converters.Request = webidl.interfaceConverter( + Request +) + +// https://fetch.spec.whatwg.org/#requestinfo +webidl.converters.RequestInfo = function (V, prefix, argument) { + if (typeof V === 'string') { + return webidl.converters.USVString(V, prefix, argument) + } + + if (V instanceof Request) { + return webidl.converters.Request(V, prefix, argument) + } + + return webidl.converters.USVString(V, prefix, argument) +} + +webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal +) + +// https://fetch.spec.whatwg.org/#requestinit +webidl.converters.RequestInit = webidl.dictionaryConverter([ + { + key: 'method', + converter: webidl.converters.ByteString + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + }, + { + key: 'body', + converter: webidl.nullableConverter( + webidl.converters.BodyInit + ) + }, + { + key: 'referrer', + converter: webidl.converters.USVString + }, + { + key: 'referrerPolicy', + converter: webidl.converters.DOMString, + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy + allowedValues: referrerPolicy + }, + { + key: 'mode', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#concept-request-mode + allowedValues: requestMode + }, + { + key: 'credentials', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcredentials + allowedValues: requestCredentials + }, + { + key: 'cache', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcache + allowedValues: requestCache + }, + { + key: 'redirect', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestredirect + allowedValues: requestRedirect + }, + { + key: 'integrity', + converter: webidl.converters.DOMString + }, + { + key: 'keepalive', + converter: webidl.converters.boolean + }, + { + key: 'signal', + converter: webidl.nullableConverter( + (signal) => webidl.converters.AbortSignal( + signal, + 'RequestInit', + 'signal', + { strict: false } + ) + ) + }, + { + key: 'window', + converter: webidl.converters.any + }, + { + key: 'duplex', + converter: webidl.converters.DOMString, + allowedValues: requestDuplex + }, + { + key: 'dispatcher', // undici specific option + converter: webidl.converters.any + } +]) + +module.exports = { Request, makeRequest, fromInnerRequest, cloneRequest } diff --git a/node_modules/undici/lib/web/fetch/response.js b/node_modules/undici/lib/web/fetch/response.js new file mode 100644 index 0000000000000..3abaa8bd6d5ef --- /dev/null +++ b/node_modules/undici/lib/web/fetch/response.js @@ -0,0 +1,610 @@ +'use strict' + +const { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require('./headers') +const { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = require('./body') +const util = require('../../core/util') +const nodeUtil = require('node:util') +const { kEnumerableProperty } = util +const { + isValidReasonPhrase, + isCancelled, + isAborted, + isBlobLike, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode, + environmentSettingsObject: relevantRealm +} = require('./util') +const { + redirectStatusSet, + nullBodyStatus +} = require('./constants') +const { kState, kHeaders } = require('./symbols') +const { webidl } = require('./webidl') +const { FormData } = require('./formdata') +const { URLSerializer } = require('./data-url') +const { kConstruct } = require('../../core/symbols') +const assert = require('node:assert') +const { types } = require('node:util') + +const textEncoder = new TextEncoder('utf-8') + +// https://fetch.spec.whatwg.org/#response-class +class Response { + // Creates network error Response. + static error () { + // The static error() method steps are to return the result of creating a + // Response object, given a new network error, "immutable", and this’s + // relevant Realm. + const responseObject = fromInnerResponse(makeNetworkError(), 'immutable') + + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response-json + static json (data, init = {}) { + webidl.argumentLengthCheck(arguments, 1, 'Response.json') + + if (init !== null) { + init = webidl.converters.ResponseInit(init) + } + + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ) + + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes) + + // 3. Let responseObject be the result of creating a Response object, given a new response, + // "response", and this’s relevant Realm. + const responseObject = fromInnerResponse(makeResponse({}), 'response') + + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) + + // 5. Return responseObject. + return responseObject + } + + // Creates a redirect Response that redirects to url with status status. + static redirect (url, status = 302) { + webidl.argumentLengthCheck(arguments, 1, 'Response.redirect') + + url = webidl.converters.USVString(url) + status = webidl.converters['unsigned short'](status) + + // 1. Let parsedURL be the result of parsing url with current settings + // object’s API base URL. + // 2. If parsedURL is failure, then throw a TypeError. + // TODO: base-URL? + let parsedURL + try { + parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl) + } catch (err) { + throw new TypeError(`Failed to parse URL from ${url}`, { cause: err }) + } + + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatusSet.has(status)) { + throw new RangeError(`Invalid status code ${status}`) + } + + // 4. Let responseObject be the result of creating a Response object, + // given a new response, "immutable", and this’s relevant Realm. + const responseObject = fromInnerResponse(makeResponse({}), 'immutable') + + // 5. Set responseObject’s response’s status to status. + responseObject[kState].status = status + + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)) + + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject[kState].headersList.append('location', value, true) + + // 8. Return responseObject. + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = {}) { + webidl.util.markAsUncloneable(this) + if (body === kConstruct) { + return + } + + if (body !== null) { + body = webidl.converters.BodyInit(body) + } + + init = webidl.converters.ResponseInit(init) + + // 1. Set this’s response to a new response. + this[kState] = makeResponse({}) + + // 2. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is this’s response’s header list and guard + // is "response". + this[kHeaders] = new Headers(kConstruct) + setHeadersGuard(this[kHeaders], 'response') + setHeadersList(this[kHeaders], this[kState].headersList) + + // 3. Let bodyWithType be null. + let bodyWithType = null + + // 4. If body is non-null, then set bodyWithType to the result of extracting body. + if (body != null) { + const [extractedBody, type] = extractBody(body) + bodyWithType = { body: extractedBody, type } + } + + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType) + } + + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response) + + // The type getter steps are to return this’s response’s type. + return this[kState].type + } + + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response) + + const urlList = this[kState].urlList + + // The url getter steps are to return the empty string if this’s + // response’s URL is null; otherwise this’s response’s URL, + // serialized with exclude fragment set to true. + const url = urlList[urlList.length - 1] ?? null + + if (url === null) { + return '' + } + + return URLSerializer(url, true) + } + + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response) + + // The redirected getter steps are to return true if this’s response’s URL + // list has more than one item; otherwise false. + return this[kState].urlList.length > 1 + } + + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response) + + // The status getter steps are to return this’s response’s status. + return this[kState].status + } + + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response) + + // The ok getter steps are to return true if this’s response’s status is an + // ok status; otherwise false. + return this[kState].status >= 200 && this[kState].status <= 299 + } + + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response) + + // The statusText getter steps are to return this’s response’s status + // message. + return this[kState].statusText + } + + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response) + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + get body () { + webidl.brandCheck(this, Response) + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Response) + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response) + + // 1. If this is unusable, then throw a TypeError. + if (bodyUnusable(this)) { + throw webidl.errors.exception({ + header: 'Response.clone', + message: 'Body has already been consumed.' + }) + } + + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this[kState]) + + // Note: To re-register because of a new stream. + if (hasFinalizationRegistry && this[kState].body?.stream) { + streamRegistry.register(this, new WeakRef(this[kState].body.stream)) + } + + // 3. Return the result of creating a Response object, given + // clonedResponse, this’s headers’s guard, and this’s relevant Realm. + return fromInnerResponse(clonedResponse, getHeadersGuard(this[kHeaders])) + } + + [nodeUtil.inspect.custom] (depth, options) { + if (options.depth === null) { + options.depth = 2 + } + + options.colors ??= true + + const properties = { + status: this.status, + statusText: this.statusText, + headers: this.headers, + body: this.body, + bodyUsed: this.bodyUsed, + ok: this.ok, + redirected: this.redirected, + type: this.type, + url: this.url + } + + return `Response ${nodeUtil.formatWithOptions(options, properties)}` + } +} + +mixinBody(Response) + +Object.defineProperties(Response.prototype, { + type: kEnumerableProperty, + url: kEnumerableProperty, + status: kEnumerableProperty, + ok: kEnumerableProperty, + redirected: kEnumerableProperty, + statusText: kEnumerableProperty, + headers: kEnumerableProperty, + clone: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Response', + configurable: true + } +}) + +Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty +}) + +// https://fetch.spec.whatwg.org/#concept-response-clone +function cloneResponse (response) { + // To clone a response response, run these steps: + + // 1. If response is a filtered response, then return a new identical + // filtered response whose internal response is a clone of response’s + // internal response. + if (response.internalResponse) { + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ) + } + + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, body: null }) + + // 3. If response’s body is non-null, then set newResponse’s body to the + // result of cloning response’s body. + if (response.body != null) { + newResponse.body = cloneBody(newResponse, response.body) + } + + // 4. Return newResponse. + return newResponse +} + +function makeResponse (init) { + return { + aborted: false, + rangeRequested: false, + timingAllowPassed: false, + requestIncludesCredentials: false, + type: 'default', + status: 200, + timingInfo: null, + cacheState: '', + statusText: '', + ...init, + headersList: init?.headersList + ? new HeadersList(init?.headersList) + : new HeadersList(), + urlList: init?.urlList ? [...init.urlList] : [] + } +} + +function makeNetworkError (reason) { + const isError = isErrorLike(reason) + return makeResponse({ + type: 'error', + status: 0, + error: isError + ? reason + : new Error(reason ? String(reason) : reason), + aborted: reason && reason.name === 'AbortError' + }) +} + +// @see https://fetch.spec.whatwg.org/#concept-network-error +function isNetworkError (response) { + return ( + // A network error is a response whose type is "error", + response.type === 'error' && + // status is 0 + response.status === 0 + ) +} + +function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state + } + + return new Proxy(response, { + get (target, p) { + return p in state ? state[p] : target[p] + }, + set (target, p, value) { + assert(!(p in state)) + target[p] = value + return true + } + }) +} + +// https://fetch.spec.whatwg.org/#concept-filtered-response +function filterResponse (response, type) { + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (type === 'basic') { + // A basic filtered response is a filtered response whose type is "basic" + // and header list excludes any headers in internal response’s header list + // whose name is a forbidden response-header name. + + // Note: undici does not implement forbidden response-header names + return makeFilteredResponse(response, { + type: 'basic', + headersList: response.headersList + }) + } else if (type === 'cors') { + // A CORS filtered response is a filtered response whose type is "cors" + // and header list excludes any headers in internal response’s header + // list whose name is not a CORS-safelisted response-header name, given + // internal response’s CORS-exposed header-name list. + + // Note: undici does not implement CORS-safelisted response-header names + return makeFilteredResponse(response, { + type: 'cors', + headersList: response.headersList + }) + } else if (type === 'opaque') { + // An opaque filtered response is a filtered response whose type is + // "opaque", URL list is the empty list, status is 0, status message + // is the empty byte sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaque', + urlList: Object.freeze([]), + status: 0, + statusText: '', + body: null + }) + } else if (type === 'opaqueredirect') { + // An opaque-redirect filtered response is a filtered response whose type + // is "opaqueredirect", status is 0, status message is the empty byte + // sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false) + } +} + +// https://fetch.spec.whatwg.org/#appropriate-network-error +function makeAppropriateNetworkError (fetchParams, err = null) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)) + + // 2. Return an aborted network error if fetchParams is aborted; + // otherwise return a network error. + return isAborted(fetchParams) + ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) + : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) +} + +// https://whatpr.org/fetch/1392.html#initialize-a-response +function initializeResponse (response, init, body) { + // 1. If init["status"] is not in the range 200 to 599, inclusive, then + // throw a RangeError. + if (init.status !== null && (init.status < 200 || init.status > 599)) { + throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') + } + + // 2. If init["statusText"] does not match the reason-phrase token production, + // then throw a TypeError. + if ('statusText' in init && init.statusText != null) { + // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: + // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) + if (!isValidReasonPhrase(String(init.statusText))) { + throw new TypeError('Invalid statusText') + } + } + + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + response[kState].status = init.status + } + + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + response[kState].statusText = init.statusText + } + + // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. + if ('headers' in init && init.headers != null) { + fill(response[kHeaders], init.headers) + } + + // 6. If body was given, then: + if (body) { + // 1. If response's status is a null body status, then throw a TypeError. + if (nullBodyStatus.includes(response.status)) { + throw webidl.errors.exception({ + header: 'Response constructor', + message: `Invalid response status code ${response.status}` + }) + } + + // 2. Set response's body to body's body. + response[kState].body = body.body + + // 3. If body's type is non-null and response's header list does not contain + // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. + if (body.type != null && !response[kState].headersList.contains('content-type', true)) { + response[kState].headersList.append('content-type', body.type, true) + } + } +} + +/** + * @see https://fetch.spec.whatwg.org/#response-create + * @param {any} innerResponse + * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard + * @returns {Response} + */ +function fromInnerResponse (innerResponse, guard) { + const response = new Response(kConstruct) + response[kState] = innerResponse + response[kHeaders] = new Headers(kConstruct) + setHeadersList(response[kHeaders], innerResponse.headersList) + setHeadersGuard(response[kHeaders], guard) + + if (hasFinalizationRegistry && innerResponse.body?.stream) { + // If the target (response) is reclaimed, the cleanup callback may be called at some point with + // the held value provided for it (innerResponse.body.stream). The held value can be any value: + // a primitive or an object, even undefined. If the held value is an object, the registry keeps + // a strong reference to it (so it can pass it to the cleanup callback later). Reworded from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + streamRegistry.register(response, new WeakRef(innerResponse.body.stream)) + } + + return response +} + +webidl.converters.ReadableStream = webidl.interfaceConverter( + ReadableStream +) + +webidl.converters.FormData = webidl.interfaceConverter( + FormData +) + +webidl.converters.URLSearchParams = webidl.interfaceConverter( + URLSearchParams +) + +// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit +webidl.converters.XMLHttpRequestBodyInit = function (V, prefix, name) { + if (typeof V === 'string') { + return webidl.converters.USVString(V, prefix, name) + } + + if (isBlobLike(V)) { + return webidl.converters.Blob(V, prefix, name, { strict: false }) + } + + if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) { + return webidl.converters.BufferSource(V, prefix, name) + } + + if (util.isFormDataLike(V)) { + return webidl.converters.FormData(V, prefix, name, { strict: false }) + } + + if (V instanceof URLSearchParams) { + return webidl.converters.URLSearchParams(V, prefix, name) + } + + return webidl.converters.DOMString(V, prefix, name) +} + +// https://fetch.spec.whatwg.org/#bodyinit +webidl.converters.BodyInit = function (V, prefix, argument) { + if (V instanceof ReadableStream) { + return webidl.converters.ReadableStream(V, prefix, argument) + } + + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V + } + + return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument) +} + +webidl.converters.ResponseInit = webidl.dictionaryConverter([ + { + key: 'status', + converter: webidl.converters['unsigned short'], + defaultValue: () => 200 + }, + { + key: 'statusText', + converter: webidl.converters.ByteString, + defaultValue: () => '' + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + } +]) + +module.exports = { + isNetworkError, + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response, + cloneResponse, + fromInnerResponse +} diff --git a/node_modules/undici/lib/web/fetch/symbols.js b/node_modules/undici/lib/web/fetch/symbols.js new file mode 100644 index 0000000000000..32e360e490fba --- /dev/null +++ b/node_modules/undici/lib/web/fetch/symbols.js @@ -0,0 +1,9 @@ +'use strict' + +module.exports = { + kUrl: Symbol('url'), + kHeaders: Symbol('headers'), + kSignal: Symbol('signal'), + kState: Symbol('state'), + kDispatcher: Symbol('dispatcher') +} diff --git a/node_modules/undici/lib/web/fetch/util.js b/node_modules/undici/lib/web/fetch/util.js new file mode 100644 index 0000000000000..5101324a80cf7 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/util.js @@ -0,0 +1,1632 @@ +'use strict' + +const { Transform } = require('node:stream') +const zlib = require('node:zlib') +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require('./constants') +const { getGlobalOrigin } = require('./global') +const { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = require('./data-url') +const { performance } = require('node:perf_hooks') +const { isBlobLike, ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = require('../../core/util') +const assert = require('node:assert') +const { isUint8Array } = require('node:util/types') +const { webidl } = require('./webidl') + +let supportedHashes = [] + +// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable +/** @type {import('crypto')} */ +let crypto +try { + crypto = require('node:crypto') + const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] + supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) +/* c8 ignore next 3 */ +} catch { + +} + +function responseURL (response) { + // https://fetch.spec.whatwg.org/#responses + // A response has an associated URL. It is a pointer to the last URL + // in response’s URL list and null if response’s URL list is empty. + const urlList = response.urlList + const length = urlList.length + return length === 0 ? null : urlList[length - 1].toString() +} + +// https://fetch.spec.whatwg.org/#concept-response-location-url +function responseLocationURL (response, requestFragment) { + // 1. If response’s status is not a redirect status, then return null. + if (!redirectStatusSet.has(response.status)) { + return null + } + + // 2. Let location be the result of extracting header list values given + // `Location` and response’s header list. + let location = response.headersList.get('location', true) + + // 3. If location is a header value, then set location to the result of + // parsing location with response’s URL. + if (location !== null && isValidHeaderValue(location)) { + if (!isValidEncodedURL(location)) { + // Some websites respond location header in UTF-8 form without encoding them as ASCII + // and major browsers redirect them to correctly UTF-8 encoded addresses. + // Here, we handle that behavior in the same way. + location = normalizeBinaryStringToUtf8(location) + } + location = new URL(location, responseURL(response)) + } + + // 4. If location is a URL whose fragment is null, then set location’s + // fragment to requestFragment. + if (location && !location.hash) { + location.hash = requestFragment + } + + // 5. Return location. + return location +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc1738#section-2.2 + * @param {string} url + * @returns {boolean} + */ +function isValidEncodedURL (url) { + for (let i = 0; i < url.length; ++i) { + const code = url.charCodeAt(i) + + if ( + code > 0x7E || // Non-US-ASCII + DEL + code < 0x20 // Control characters NUL - US + ) { + return false + } + } + return true +} + +/** + * If string contains non-ASCII characters, assumes it's UTF-8 encoded and decodes it. + * Since UTF-8 is a superset of ASCII, this will work for ASCII strings as well. + * @param {string} value + * @returns {string} + */ +function normalizeBinaryStringToUtf8 (value) { + return Buffer.from(value, 'binary').toString('utf8') +} + +/** @returns {URL} */ +function requestCurrentURL (request) { + return request.urlList[request.urlList.length - 1] +} + +function requestBadPort (request) { + // 1. Let url be request’s current URL. + const url = requestCurrentURL(request) + + // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, + // then return blocked. + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { + return 'blocked' + } + + // 3. Return allowed. + return 'allowed' +} + +function isErrorLike (object) { + return object instanceof Error || ( + object?.constructor?.name === 'Error' || + object?.constructor?.name === 'DOMException' + ) +} + +// Check whether |statusText| is a ByteString and +// matches the Reason-Phrase token production. +// RFC 2616: https://tools.ietf.org/html/rfc2616 +// RFC 7230: https://tools.ietf.org/html/rfc7230 +// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" +// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 +function isValidReasonPhrase (statusText) { + for (let i = 0; i < statusText.length; ++i) { + const c = statusText.charCodeAt(i) + if ( + !( + ( + c === 0x09 || // HTAB + (c >= 0x20 && c <= 0x7e) || // SP / VCHAR + (c >= 0x80 && c <= 0xff) + ) // obs-text + ) + ) { + return false + } + } + return true +} + +/** + * @see https://fetch.spec.whatwg.org/#header-name + * @param {string} potentialValue + */ +const isValidHeaderName = isValidHTTPToken + +/** + * @see https://fetch.spec.whatwg.org/#header-value + * @param {string} potentialValue + */ +function isValidHeaderValue (potentialValue) { + // - Has no leading or trailing HTTP tab or space bytes. + // - Contains no 0x00 (NUL) or HTTP newline bytes. + return ( + potentialValue[0] === '\t' || + potentialValue[0] === ' ' || + potentialValue[potentialValue.length - 1] === '\t' || + potentialValue[potentialValue.length - 1] === ' ' || + potentialValue.includes('\n') || + potentialValue.includes('\r') || + potentialValue.includes('\0') + ) === false +} + +// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect +function setRequestReferrerPolicyOnRedirect (request, actualResponse) { + // Given a request request and a response actualResponse, this algorithm + // updates request’s referrer policy according to the Referrer-Policy + // header (if any) in actualResponse. + + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. + + // 8.1 Parse a referrer policy from a Referrer-Policy header + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. + const { headersList } = actualResponse + // 2. Let policy be the empty string. + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. + // 4. Return policy. + const policyHeader = (headersList.get('referrer-policy', true) ?? '').split(',') + + // Note: As the referrer-policy can contain multiple policies + // separated by comma, we need to loop through all of them + // and pick the first valid one. + // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy + let policy = '' + if (policyHeader.length > 0) { + // The right-most policy takes precedence. + // The left-most policy is the fallback. + for (let i = policyHeader.length; i !== 0; i--) { + const token = policyHeader[i - 1].trim() + if (referrerPolicyTokens.has(token)) { + policy = token + break + } + } + } + + // 2. If policy is not the empty string, then set request’s referrer policy to policy. + if (policy !== '') { + request.referrerPolicy = policy + } +} + +// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check +function crossOriginResourcePolicyCheck () { + // TODO + return 'allowed' +} + +// https://fetch.spec.whatwg.org/#concept-cors-check +function corsCheck () { + // TODO + return 'success' +} + +// https://fetch.spec.whatwg.org/#concept-tao-check +function TAOCheck () { + // TODO + return 'success' +} + +function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header + + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO + + // 2. Let header be a Structured Header whose value is a token. + let header = null + + // 3. Set header’s value to r’s mode. + header = httpRequest.mode + + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header, true) + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO +} + +// https://fetch.spec.whatwg.org/#append-a-request-origin-header +function appendRequestOriginHeader (request) { + // 1. Let serializedOrigin be the result of byte-serializing a request origin + // with request. + // TODO: implement "byte-serializing a request origin" + let serializedOrigin = request.origin + + // - "'client' is changed to an origin during fetching." + // This doesn't happen in undici (in most cases) because undici, by default, + // has no concept of origin. + // - request.origin can also be set to request.client.origin (client being + // an environment settings object), which is undefined without using + // setGlobalOrigin. + if (serializedOrigin === 'client' || serializedOrigin === undefined) { + return + } + + // 2. If request’s response tainting is "cors" or request’s mode is "websocket", + // then append (`Origin`, serializedOrigin) to request’s header list. + // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: + if (request.responseTainting === 'cors' || request.mode === 'websocket') { + request.headersList.append('origin', serializedOrigin, true) + } else if (request.method !== 'GET' && request.method !== 'HEAD') { + // 1. Switch on request’s referrer policy: + switch (request.referrerPolicy) { + case 'no-referrer': + // Set serializedOrigin to `null`. + serializedOrigin = null + break + case 'no-referrer-when-downgrade': + case 'strict-origin': + case 'strict-origin-when-cross-origin': + // If request’s origin is a tuple origin, its scheme is "https", and + // request’s current URL’s scheme is not "https", then set + // serializedOrigin to `null`. + if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { + serializedOrigin = null + } + break + case 'same-origin': + // If request’s origin is not same origin with request’s current URL’s + // origin, then set serializedOrigin to `null`. + if (!sameOrigin(request, requestCurrentURL(request))) { + serializedOrigin = null + } + break + default: + // Do nothing. + } + + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin, true) + } +} + +// https://w3c.github.io/hr-time/#dfn-coarsen-time +function coarsenTime (timestamp, crossOriginIsolatedCapability) { + // TODO + return timestamp +} + +// https://fetch.spec.whatwg.org/#clamp-and-coarsen-connection-timing-info +function clampAndCoarsenConnectionTimingInfo (connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) { + if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) { + return { + domainLookupStartTime: defaultStartTime, + domainLookupEndTime: defaultStartTime, + connectionStartTime: defaultStartTime, + connectionEndTime: defaultStartTime, + secureConnectionStartTime: defaultStartTime, + ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol + } + } + + return { + domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability), + domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability), + connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability), + connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability), + secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability), + ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol + } +} + +// https://w3c.github.io/hr-time/#dfn-coarsened-shared-current-time +function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + return coarsenTime(performance.now(), crossOriginIsolatedCapability) +} + +// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info +function createOpaqueTimingInfo (timingInfo) { + return { + startTime: timingInfo.startTime ?? 0, + redirectStartTime: 0, + redirectEndTime: 0, + postRedirectStartTime: timingInfo.startTime ?? 0, + finalServiceWorkerStartTime: 0, + finalNetworkResponseStartTime: 0, + finalNetworkRequestStartTime: 0, + endTime: 0, + encodedBodySize: 0, + decodedBodySize: 0, + finalConnectionTimingInfo: null + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#policy-container +function makePolicyContainer () { + // Note: the fetch spec doesn't make use of embedder policy or CSP list + return { + referrerPolicy: 'strict-origin-when-cross-origin' + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container +function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } +} + +// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer +function determineRequestsReferrer (request) { + // 1. Let policy be request's referrer policy. + const policy = request.referrerPolicy + + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy) + + // 2. Let environment be request’s client. + + let referrerSource = null + + // 3. Switch on request’s referrer: + if (request.referrer === 'client') { + // Note: node isn't a browser and doesn't implement document/iframes, + // so we bypass this step and replace it with our own. + + const globalOrigin = getGlobalOrigin() + + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' + } + + // note: we need to clone it as it's mutated + referrerSource = new URL(globalOrigin) + } else if (request.referrer instanceof URL) { + // Let referrerSource be request’s referrer. + referrerSource = request.referrer + } + + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource) + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as + // a referrer, with the origin-only flag set to true. + const referrerOrigin = stripURLForReferrer(referrerSource, true) + + // 6. If the result of serializing referrerURL is a string whose length is + // greater than 4096, set referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin + } + + const areSameOrigin = sameOrigin(request, referrerURL) + const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && + !isURLPotentiallyTrustworthy(request.url) + + // 8. Execute the switch statements corresponding to the value of policy: + switch (policy) { + case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) + case 'unsafe-url': return referrerURL + case 'same-origin': + return areSameOrigin ? referrerOrigin : 'no-referrer' + case 'origin-when-cross-origin': + return areSameOrigin ? referrerURL : referrerOrigin + case 'strict-origin-when-cross-origin': { + const currentURL = requestCurrentURL(request) + + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(referrerURL, currentURL)) { + return referrerURL + } + + // 2. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + + // 3. Return referrerOrigin. + return referrerOrigin + } + case 'strict-origin': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + case 'no-referrer-when-downgrade': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + + default: // eslint-disable-line + return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin + } +} + +/** + * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url + * @param {URL} url + * @param {boolean|undefined} originOnly + */ +function stripURLForReferrer (url, originOnly) { + // 1. Assert: url is a URL. + assert(url instanceof URL) + + url = new URL(url) + + // 2. If url’s scheme is a local scheme, then return no referrer. + if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { + return 'no-referrer' + } + + // 3. Set url’s username to the empty string. + url.username = '' + + // 4. Set url’s password to the empty string. + url.password = '' + + // 5. Set url’s fragment to null. + url.hash = '' + + // 6. If the origin-only flag is true, then: + if (originOnly) { + // 1. Set url’s path to « the empty string ». + url.pathname = '' + + // 2. Set url’s query to null. + url.search = '' + } + + // 7. Return url. + return url +} + +function isURLPotentiallyTrustworthy (url) { + if (!(url instanceof URL)) { + return false + } + + // If child of about, return true + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true + } + + // If scheme is data, return true + if (url.protocol === 'data:') return true + + // If file, return true + if (url.protocol === 'file:') return true + + return isOriginPotentiallyTrustworthy(url.origin) + + function isOriginPotentiallyTrustworthy (origin) { + // If origin is explicitly null, return false + if (origin == null || origin === 'null') return false + + const originAsURL = new URL(origin) + + // If secure, return true + if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { + return true + } + + // If localhost or variants, return true + if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || + (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || + (originAsURL.hostname.endsWith('.localhost'))) { + return true + } + + // If any other, return false + return false + } +} + +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist + * @param {Uint8Array} bytes + * @param {string} metadataList + */ +function bytesMatch (bytes, metadataList) { + // If node is not built with OpenSSL support, we cannot check + // a request's integrity, so allow it by default (the spec will + // allow requests if an invalid hash is given, as precedence). + /* istanbul ignore if: only if node is built with --without-ssl */ + if (crypto === undefined) { + return true + } + + // 1. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList) + + // 2. If parsedMetadata is no metadata, return true. + if (parsedMetadata === 'no metadata') { + return true + } + + // 3. If response is not eligible for integrity validation, return false. + // TODO + + // 4. If parsedMetadata is the empty set, return true. + if (parsedMetadata.length === 0) { + return true + } + + // 5. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const strongest = getStrongestMetadata(parsedMetadata) + const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) + + // 6. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the alg component of item. + const algorithm = item.algo + + // 2. Let expectedValue be the val component of item. + const expectedValue = item.hash + + // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e + // "be liberal with padding". This is annoying, and it's not even in the spec. + + // 3. Let actualValue be the result of applying algorithm to bytes. + let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') + + if (actualValue[actualValue.length - 1] === '=') { + if (actualValue[actualValue.length - 2] === '=') { + actualValue = actualValue.slice(0, -2) + } else { + actualValue = actualValue.slice(0, -1) + } + } + + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (compareBase64Mixed(actualValue, expectedValue)) { + return true + } + } + + // 7. Return false. + return false +} + +// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options +// https://www.w3.org/TR/CSP2/#source-list-syntax +// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 +const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i + +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata + * @param {string} metadata + */ +function parseMetadata (metadata) { + // 1. Let result be the empty set. + /** @type {{ algo: string, hash: string }[]} */ + const result = [] + + // 2. Let empty be equal to true. + let empty = true + + // 3. For each token returned by splitting metadata on spaces: + for (const token of metadata.split(' ')) { + // 1. Set empty to false. + empty = false + + // 2. Parse token as a hash-with-options. + const parsedToken = parseHashWithOptions.exec(token) + + // 3. If token does not parse, continue to the next token. + if ( + parsedToken === null || + parsedToken.groups === undefined || + parsedToken.groups.algo === undefined + ) { + // Note: Chromium blocks the request at this point, but Firefox + // gives a warning that an invalid integrity was given. The + // correct behavior is to ignore these, and subsequently not + // check the integrity of the resource. + continue + } + + // 4. Let algorithm be the hash-algo component of token. + const algorithm = parsedToken.groups.algo.toLowerCase() + + // 5. If algorithm is a hash function recognized by the user + // agent, add the parsed token to result. + if (supportedHashes.includes(algorithm)) { + result.push(parsedToken.groups) + } + } + + // 4. Return no metadata if empty is true, otherwise return result. + if (empty === true) { + return 'no metadata' + } + + return result +} + +/** + * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList + */ +function getStrongestMetadata (metadataList) { + // Let algorithm be the algo component of the first item in metadataList. + // Can be sha256 + let algorithm = metadataList[0].algo + // If the algorithm is sha512, then it is the strongest + // and we can return immediately + if (algorithm[3] === '5') { + return algorithm + } + + for (let i = 1; i < metadataList.length; ++i) { + const metadata = metadataList[i] + // If the algorithm is sha512, then it is the strongest + // and we can break the loop immediately + if (metadata.algo[3] === '5') { + algorithm = 'sha512' + break + // If the algorithm is sha384, then a potential sha256 or sha384 is ignored + } else if (algorithm[3] === '3') { + continue + // algorithm is sha256, check if algorithm is sha384 and if so, set it as + // the strongest + } else if (metadata.algo[3] === '3') { + algorithm = 'sha384' + } + } + return algorithm +} + +function filterMetadataListByAlgorithm (metadataList, algorithm) { + if (metadataList.length === 1) { + return metadataList + } + + let pos = 0 + for (let i = 0; i < metadataList.length; ++i) { + if (metadataList[i].algo === algorithm) { + metadataList[pos++] = metadataList[i] + } + } + + metadataList.length = pos + + return metadataList +} + +/** + * Compares two base64 strings, allowing for base64url + * in the second string. + * +* @param {string} actualValue always base64 + * @param {string} expectedValue base64 or base64url + * @returns {boolean} + */ +function compareBase64Mixed (actualValue, expectedValue) { + if (actualValue.length !== expectedValue.length) { + return false + } + for (let i = 0; i < actualValue.length; ++i) { + if (actualValue[i] !== expectedValue[i]) { + if ( + (actualValue[i] === '+' && expectedValue[i] === '-') || + (actualValue[i] === '/' && expectedValue[i] === '_') + ) { + continue + } + return false + } + } + + return true +} + +// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request +function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO +} + +/** + * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} + * @param {URL} A + * @param {URL} B + */ +function sameOrigin (A, B) { + // 1. If A and B are the same opaque origin, then return true. + if (A.origin === B.origin && A.origin === 'null') { + return true + } + + // 2. If A and B are both tuple origins and their schemes, + // hosts, and port are identical, then return true. + if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { + return true + } + + // 3. Return false. + return false +} + +function createDeferredPromise () { + let res + let rej + const promise = new Promise((resolve, reject) => { + res = resolve + rej = reject + }) + + return { promise, resolve: res, reject: rej } +} + +function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' +} + +function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-method-normalize + * @param {string} method + */ +function normalizeMethod (method) { + return normalizedMethodRecordsBase[method.toLowerCase()] ?? method +} + +// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string +function serializeJavascriptValueToJSONString (value) { + // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). + const result = JSON.stringify(value) + + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') + } + + // 3. Assert: result is a string. + assert(typeof result === 'string') + + // 4. Return result. + return result +} + +// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object +const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) + +/** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {string} name name of the instance + * @param {symbol} kInternalIterator + * @param {string | number} [keyIndex] + * @param {string | number} [valueIndex] + */ +function createIterator (name, kInternalIterator, keyIndex = 0, valueIndex = 1) { + class FastIterableIterator { + /** @type {any} */ + #target + /** @type {'key' | 'value' | 'key+value'} */ + #kind + /** @type {number} */ + #index + + /** + * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object + * @param {unknown} target + * @param {'key' | 'value' | 'key+value'} kind + */ + constructor (target, kind) { + this.#target = target + this.#kind = kind + this.#index = 0 + } + + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. + // 2. Let thisValue be the this value. + // 3. Let object be ? ToObject(thisValue). + // 4. If object is a platform object, then perform a security + // check, passing: + // 5. If object is not a default iterator object for interface, + // then throw a TypeError. + if (typeof this !== 'object' || this === null || !(#target in this)) { + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ) + } + + // 6. Let index be object’s index. + // 7. Let kind be object’s kind. + // 8. Let values be object’s target's value pairs to iterate over. + const index = this.#index + const values = this.#target[kInternalIterator] + + // 9. Let len be the length of values. + const len = values.length + + // 10. If index is greater than or equal to len, then return + // CreateIterResultObject(undefined, true). + if (index >= len) { + return { + value: undefined, + done: true + } + } + + // 11. Let pair be the entry in values at index index. + const { [keyIndex]: key, [valueIndex]: value } = values[index] + + // 12. Set object’s index to index + 1. + this.#index = index + 1 + + // 13. Return the iterator result for pair and kind. + + // https://webidl.spec.whatwg.org/#iterator-result + + // 1. Let result be a value determined by the value of kind: + let result + switch (this.#kind) { + case 'key': + // 1. Let idlKey be pair’s key. + // 2. Let key be the result of converting idlKey to an + // ECMAScript value. + // 3. result is key. + result = key + break + case 'value': + // 1. Let idlValue be pair’s value. + // 2. Let value be the result of converting idlValue to + // an ECMAScript value. + // 3. result is value. + result = value + break + case 'key+value': + // 1. Let idlKey be pair’s key. + // 2. Let idlValue be pair’s value. + // 3. Let key be the result of converting idlKey to an + // ECMAScript value. + // 4. Let value be the result of converting idlValue to + // an ECMAScript value. + // 5. Let array be ! ArrayCreate(2). + // 6. Call ! CreateDataProperty(array, "0", key). + // 7. Call ! CreateDataProperty(array, "1", value). + // 8. result is array. + result = [key, value] + break + } + + // 2. Return CreateIterResultObject(result, false). + return { + value: result, + done: false + } + } + } + + // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + // @ts-ignore + delete FastIterableIterator.prototype.constructor + + Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype) + + Object.defineProperties(FastIterableIterator.prototype, { + [Symbol.toStringTag]: { + writable: false, + enumerable: false, + configurable: true, + value: `${name} Iterator` + }, + next: { writable: true, enumerable: true, configurable: true } + }) + + /** + * @param {unknown} target + * @param {'key' | 'value' | 'key+value'} kind + * @returns {IterableIterator} + */ + return function (target, kind) { + return new FastIterableIterator(target, kind) + } +} + +/** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {string} name name of the instance + * @param {any} object class + * @param {symbol} kInternalIterator + * @param {string | number} [keyIndex] + * @param {string | number} [valueIndex] + */ +function iteratorMixin (name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) { + const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex) + + const properties = { + keys: { + writable: true, + enumerable: true, + configurable: true, + value: function keys () { + webidl.brandCheck(this, object) + return makeIterator(this, 'key') + } + }, + values: { + writable: true, + enumerable: true, + configurable: true, + value: function values () { + webidl.brandCheck(this, object) + return makeIterator(this, 'value') + } + }, + entries: { + writable: true, + enumerable: true, + configurable: true, + value: function entries () { + webidl.brandCheck(this, object) + return makeIterator(this, 'key+value') + } + }, + forEach: { + writable: true, + enumerable: true, + configurable: true, + value: function forEach (callbackfn, thisArg = globalThis) { + webidl.brandCheck(this, object) + webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`) + if (typeof callbackfn !== 'function') { + throw new TypeError( + `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.` + ) + } + for (const { 0: key, 1: value } of makeIterator(this, 'key+value')) { + callbackfn.call(thisArg, value, key, this) + } + } + } + } + + return Object.defineProperties(object.prototype, { + ...properties, + [Symbol.iterator]: { + writable: true, + enumerable: false, + configurable: true, + value: properties.entries.value + } + }) +} + +/** + * @see https://fetch.spec.whatwg.org/#body-fully-read + */ +async function fullyReadBody (body, processBody, processBodyError) { + // 1. If taskDestination is null, then set taskDestination to + // the result of starting a new parallel queue. + + // 2. Let successSteps given a byte sequence bytes be to queue a + // fetch task to run processBody given bytes, with taskDestination. + const successSteps = processBody + + // 3. Let errorSteps be to queue a fetch task to run processBodyError, + // with taskDestination. + const errorSteps = processBodyError + + // 4. Let reader be the result of getting a reader for body’s stream. + // If that threw an exception, then run errorSteps with that + // exception and return. + let reader + + try { + reader = body.stream.getReader() + } catch (e) { + errorSteps(e) + return + } + + // 5. Read all bytes from reader, given successSteps and errorSteps. + try { + successSteps(await readAllBytes(reader)) + } catch (e) { + errorSteps(e) + } +} + +function isReadableStreamLike (stream) { + return stream instanceof ReadableStream || ( + stream[Symbol.toStringTag] === 'ReadableStream' && + typeof stream.tee === 'function' + ) +} + +/** + * @param {ReadableStreamController} controller + */ +function readableStreamClose (controller) { + try { + controller.close() + controller.byobRequest?.respond(0) + } catch (err) { + // TODO: add comment explaining why this error occurs. + if (!err.message.includes('Controller is already closed') && !err.message.includes('ReadableStream is already closed')) { + throw err + } + } +} + +const invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/ // eslint-disable-line + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-encode + * @param {string} input + */ +function isomorphicEncode (input) { + // 1. Assert: input contains no code points greater than U+00FF. + assert(!invalidIsomorphicEncodeValueRegex.test(input)) + + // 2. Return a byte sequence whose length is equal to input’s code + // point length and whose bytes have the same values as the + // values of input’s code points, in the same order + return input +} + +/** + * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes + * @see https://streams.spec.whatwg.org/#read-loop + * @param {ReadableStreamDefaultReader} reader + */ +async function readAllBytes (reader) { + const bytes = [] + let byteLength = 0 + + while (true) { + const { done, value: chunk } = await reader.read() + + if (done) { + // 1. Call successSteps with bytes. + return Buffer.concat(bytes, byteLength) + } + + // 1. If chunk is not a Uint8Array object, call failureSteps + // with a TypeError and abort these steps. + if (!isUint8Array(chunk)) { + throw new TypeError('Received non-Uint8Array chunk') + } + + // 2. Append the bytes represented by chunk to bytes. + bytes.push(chunk) + byteLength += chunk.length + + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. + } +} + +/** + * @see https://fetch.spec.whatwg.org/#is-local + * @param {URL} url + */ +function urlIsLocal (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' +} + +/** + * @param {string|URL} url + * @returns {boolean} + */ +function urlHasHttpsScheme (url) { + return ( + ( + typeof url === 'string' && + url[5] === ':' && + url[0] === 'h' && + url[1] === 't' && + url[2] === 't' && + url[3] === 'p' && + url[4] === 's' + ) || + url.protocol === 'https:' + ) +} + +/** + * @see https://fetch.spec.whatwg.org/#http-scheme + * @param {URL} url + */ +function urlIsHttpHttpsScheme (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + return protocol === 'http:' || protocol === 'https:' +} + +/** + * @see https://fetch.spec.whatwg.org/#simple-range-header-value + * @param {string} value + * @param {boolean} allowWhitespace + */ +function simpleRangeHeaderValue (value, allowWhitespace) { + // 1. Let data be the isomorphic decoding of value. + // Note: isomorphic decoding takes a sequence of bytes (ie. a Uint8Array) and turns it into a string, + // nothing more. We obviously don't need to do that if value is a string already. + const data = value + + // 2. If data does not start with "bytes", then return failure. + if (!data.startsWith('bytes')) { + return 'failure' + } + + // 3. Let position be a position variable for data, initially pointing at the 5th code point of data. + const position = { position: 5 } + + // 4. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, + // from data given position. + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ) + } + + // 5. If the code point at position within data is not U+003D (=), then return failure. + if (data.charCodeAt(position.position) !== 0x3D) { + return 'failure' + } + + // 6. Advance position by 1. + position.position++ + + // 7. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, from + // data given position. + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ) + } + + // 8. Let rangeStart be the result of collecting a sequence of code points that are ASCII digits, + // from data given position. + const rangeStart = collectASequenceOfCodePoints( + (char) => { + const code = char.charCodeAt(0) + + return code >= 0x30 && code <= 0x39 + }, + data, + position + ) + + // 9. Let rangeStartValue be rangeStart, interpreted as decimal number, if rangeStart is not the + // empty string; otherwise null. + const rangeStartValue = rangeStart.length ? Number(rangeStart) : null + + // 10. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, + // from data given position. + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ) + } + + // 11. If the code point at position within data is not U+002D (-), then return failure. + if (data.charCodeAt(position.position) !== 0x2D) { + return 'failure' + } + + // 12. Advance position by 1. + position.position++ + + // 13. If allowWhitespace is true, collect a sequence of code points that are HTTP tab + // or space, from data given position. + // Note from Khafra: its the same step as in #8 again lol + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ) + } + + // 14. Let rangeEnd be the result of collecting a sequence of code points that are + // ASCII digits, from data given position. + // Note from Khafra: you wouldn't guess it, but this is also the same step as #8 + const rangeEnd = collectASequenceOfCodePoints( + (char) => { + const code = char.charCodeAt(0) + + return code >= 0x30 && code <= 0x39 + }, + data, + position + ) + + // 15. Let rangeEndValue be rangeEnd, interpreted as decimal number, if rangeEnd + // is not the empty string; otherwise null. + // Note from Khafra: THE SAME STEP, AGAIN!!! + // Note: why interpret as a decimal if we only collect ascii digits? + const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null + + // 16. If position is not past the end of data, then return failure. + if (position.position < data.length) { + return 'failure' + } + + // 17. If rangeEndValue and rangeStartValue are null, then return failure. + if (rangeEndValue === null && rangeStartValue === null) { + return 'failure' + } + + // 18. If rangeStartValue and rangeEndValue are numbers, and rangeStartValue is + // greater than rangeEndValue, then return failure. + // Note: ... when can they not be numbers? + if (rangeStartValue > rangeEndValue) { + return 'failure' + } + + // 19. Return (rangeStartValue, rangeEndValue). + return { rangeStartValue, rangeEndValue } +} + +/** + * @see https://fetch.spec.whatwg.org/#build-a-content-range + * @param {number} rangeStart + * @param {number} rangeEnd + * @param {number} fullLength + */ +function buildContentRange (rangeStart, rangeEnd, fullLength) { + // 1. Let contentRange be `bytes `. + let contentRange = 'bytes ' + + // 2. Append rangeStart, serialized and isomorphic encoded, to contentRange. + contentRange += isomorphicEncode(`${rangeStart}`) + + // 3. Append 0x2D (-) to contentRange. + contentRange += '-' + + // 4. Append rangeEnd, serialized and isomorphic encoded to contentRange. + contentRange += isomorphicEncode(`${rangeEnd}`) + + // 5. Append 0x2F (/) to contentRange. + contentRange += '/' + + // 6. Append fullLength, serialized and isomorphic encoded to contentRange. + contentRange += isomorphicEncode(`${fullLength}`) + + // 7. Return contentRange. + return contentRange +} + +// A Stream, which pipes the response to zlib.createInflate() or +// zlib.createInflateRaw() depending on the first byte of the Buffer. +// If the lower byte of the first byte is 0x08, then the stream is +// interpreted as a zlib stream, otherwise it's interpreted as a +// raw deflate stream. +class InflateStream extends Transform { + #zlibOptions + + /** @param {zlib.ZlibOptions} [zlibOptions] */ + constructor (zlibOptions) { + super() + this.#zlibOptions = zlibOptions + } + + _transform (chunk, encoding, callback) { + if (!this._inflateStream) { + if (chunk.length === 0) { + callback() + return + } + this._inflateStream = (chunk[0] & 0x0F) === 0x08 + ? zlib.createInflate(this.#zlibOptions) + : zlib.createInflateRaw(this.#zlibOptions) + + this._inflateStream.on('data', this.push.bind(this)) + this._inflateStream.on('end', () => this.push(null)) + this._inflateStream.on('error', (err) => this.destroy(err)) + } + + this._inflateStream.write(chunk, encoding, callback) + } + + _final (callback) { + if (this._inflateStream) { + this._inflateStream.end() + this._inflateStream = null + } + callback() + } +} + +/** + * @param {zlib.ZlibOptions} [zlibOptions] + * @returns {InflateStream} + */ +function createInflate (zlibOptions) { + return new InflateStream(zlibOptions) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-extract-mime-type + * @param {import('./headers').HeadersList} headers + */ +function extractMimeType (headers) { + // 1. Let charset be null. + let charset = null + + // 2. Let essence be null. + let essence = null + + // 3. Let mimeType be null. + let mimeType = null + + // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers. + const values = getDecodeSplit('content-type', headers) + + // 5. If values is null, then return failure. + if (values === null) { + return 'failure' + } + + // 6. For each value of values: + for (const value of values) { + // 6.1. Let temporaryMimeType be the result of parsing value. + const temporaryMimeType = parseMIMEType(value) + + // 6.2. If temporaryMimeType is failure or its essence is "*/*", then continue. + if (temporaryMimeType === 'failure' || temporaryMimeType.essence === '*/*') { + continue + } + + // 6.3. Set mimeType to temporaryMimeType. + mimeType = temporaryMimeType + + // 6.4. If mimeType’s essence is not essence, then: + if (mimeType.essence !== essence) { + // 6.4.1. Set charset to null. + charset = null + + // 6.4.2. If mimeType’s parameters["charset"] exists, then set charset to + // mimeType’s parameters["charset"]. + if (mimeType.parameters.has('charset')) { + charset = mimeType.parameters.get('charset') + } + + // 6.4.3. Set essence to mimeType’s essence. + essence = mimeType.essence + } else if (!mimeType.parameters.has('charset') && charset !== null) { + // 6.5. Otherwise, if mimeType’s parameters["charset"] does not exist, and + // charset is non-null, set mimeType’s parameters["charset"] to charset. + mimeType.parameters.set('charset', charset) + } + } + + // 7. If mimeType is null, then return failure. + if (mimeType == null) { + return 'failure' + } + + // 8. Return mimeType. + return mimeType +} + +/** + * @see https://fetch.spec.whatwg.org/#header-value-get-decode-and-split + * @param {string|null} value + */ +function gettingDecodingSplitting (value) { + // 1. Let input be the result of isomorphic decoding value. + const input = value + + // 2. Let position be a position variable for input, initially pointing at the start of input. + const position = { position: 0 } + + // 3. Let values be a list of strings, initially empty. + const values = [] + + // 4. Let temporaryValue be the empty string. + let temporaryValue = '' + + // 5. While position is not past the end of input: + while (position.position < input.length) { + // 5.1. Append the result of collecting a sequence of code points that are not U+0022 (") + // or U+002C (,) from input, given position, to temporaryValue. + temporaryValue += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== ',', + input, + position + ) + + // 5.2. If position is not past the end of input, then: + if (position.position < input.length) { + // 5.2.1. If the code point at position within input is U+0022 ("), then: + if (input.charCodeAt(position.position) === 0x22) { + // 5.2.1.1. Append the result of collecting an HTTP quoted string from input, given position, to temporaryValue. + temporaryValue += collectAnHTTPQuotedString( + input, + position + ) + + // 5.2.1.2. If position is not past the end of input, then continue. + if (position.position < input.length) { + continue + } + } else { + // 5.2.2. Otherwise: + + // 5.2.2.1. Assert: the code point at position within input is U+002C (,). + assert(input.charCodeAt(position.position) === 0x2C) + + // 5.2.2.2. Advance position by 1. + position.position++ + } + } + + // 5.3. Remove all HTTP tab or space from the start and end of temporaryValue. + temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 0x9 || char === 0x20) + + // 5.4. Append temporaryValue to values. + values.push(temporaryValue) + + // 5.6. Set temporaryValue to the empty string. + temporaryValue = '' + } + + // 6. Return values. + return values +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split + * @param {string} name lowercase header name + * @param {import('./headers').HeadersList} list + */ +function getDecodeSplit (name, list) { + // 1. Let value be the result of getting name from list. + const value = list.get(name, true) + + // 2. If value is null, then return null. + if (value === null) { + return null + } + + // 3. Return the result of getting, decoding, and splitting value. + return gettingDecodingSplitting(value) +} + +const textDecoder = new TextDecoder() + +/** + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Buffer} buffer + */ +function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' + } + + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. + + // 2. If buffer is 0xEF 0xBB 0xBF, then read three + // bytes from ioQueue. (Do nothing with those bytes.) + if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + buffer = buffer.subarray(3) + } + + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = textDecoder.decode(buffer) + + // 4. Return output. + return output +} + +class EnvironmentSettingsObjectBase { + get baseUrl () { + return getGlobalOrigin() + } + + get origin () { + return this.baseUrl?.origin + } + + policyContainer = makePolicyContainer() +} + +class EnvironmentSettingsObject { + settingsObject = new EnvironmentSettingsObjectBase() +} + +const environmentSettingsObject = new EnvironmentSettingsObject() + +module.exports = { + isAborted, + isCancelled, + isValidEncodedURL, + createDeferredPromise, + ReadableStreamFrom, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + clampAndCoarsenConnectionTimingInfo, + coarsenedSharedCurrentTime, + determineRequestsReferrer, + makePolicyContainer, + clonePolicyContainer, + appendFetchMetadata, + appendRequestOriginHeader, + TAOCheck, + corsCheck, + crossOriginResourcePolicyCheck, + createOpaqueTimingInfo, + setRequestReferrerPolicyOnRedirect, + isValidHTTPToken, + requestBadPort, + requestCurrentURL, + responseURL, + responseLocationURL, + isBlobLike, + isURLPotentiallyTrustworthy, + isValidReasonPhrase, + sameOrigin, + normalizeMethod, + serializeJavascriptValueToJSONString, + iteratorMixin, + createIterator, + isValidHeaderName, + isValidHeaderValue, + isErrorLike, + fullyReadBody, + bytesMatch, + isReadableStreamLike, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlHasHttpsScheme, + urlIsHttpHttpsScheme, + readAllBytes, + simpleRangeHeaderValue, + buildContentRange, + parseMetadata, + createInflate, + extractMimeType, + getDecodeSplit, + utf8DecodeBytes, + environmentSettingsObject +} diff --git a/node_modules/undici/lib/web/fetch/webidl.js b/node_modules/undici/lib/web/fetch/webidl.js new file mode 100644 index 0000000000000..cd5cb14454c34 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/webidl.js @@ -0,0 +1,695 @@ +'use strict' + +const { types, inspect } = require('node:util') +const { markAsUncloneable } = require('node:worker_threads') +const { toUSVString } = require('../../core/util') + +/** @type {import('../../../types/webidl').Webidl} */ +const webidl = {} +webidl.converters = {} +webidl.util = {} +webidl.errors = {} + +webidl.errors.exception = function (message) { + return new TypeError(`${message.header}: ${message.message}`) +} + +webidl.errors.conversionFailed = function (context) { + const plural = context.types.length === 1 ? '' : ' one of' + const message = + `${context.argument} could not be converted to` + + `${plural}: ${context.types.join(', ')}.` + + return webidl.errors.exception({ + header: context.prefix, + message + }) +} + +webidl.errors.invalidArgument = function (context) { + return webidl.errors.exception({ + header: context.prefix, + message: `"${context.value}" is an invalid ${context.type}.` + }) +} + +// https://webidl.spec.whatwg.org/#implements +webidl.brandCheck = function (V, I, opts) { + if (opts?.strict !== false) { + if (!(V instanceof I)) { + const err = new TypeError('Illegal invocation') + err.code = 'ERR_INVALID_THIS' // node compat. + throw err + } + } else { + if (V?.[Symbol.toStringTag] !== I.prototype[Symbol.toStringTag]) { + const err = new TypeError('Illegal invocation') + err.code = 'ERR_INVALID_THIS' // node compat. + throw err + } + } +} + +webidl.argumentLengthCheck = function ({ length }, min, ctx) { + if (length < min) { + throw webidl.errors.exception({ + message: `${min} argument${min !== 1 ? 's' : ''} required, ` + + `but${length ? ' only' : ''} ${length} found.`, + header: ctx + }) + } +} + +webidl.illegalConstructor = function () { + throw webidl.errors.exception({ + header: 'TypeError', + message: 'Illegal constructor' + }) +} + +// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values +webidl.util.Type = function (V) { + switch (typeof V) { + case 'undefined': return 'Undefined' + case 'boolean': return 'Boolean' + case 'string': return 'String' + case 'symbol': return 'Symbol' + case 'number': return 'Number' + case 'bigint': return 'BigInt' + case 'function': + case 'object': { + if (V === null) { + return 'Null' + } + + return 'Object' + } + } +} + +webidl.util.markAsUncloneable = markAsUncloneable || (() => {}) +// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint +webidl.util.ConvertToInt = function (V, bitLength, signedness, opts) { + let upperBound + let lowerBound + + // 1. If bitLength is 64, then: + if (bitLength === 64) { + // 1. Let upperBound be 2^53 − 1. + upperBound = Math.pow(2, 53) - 1 + + // 2. If signedness is "unsigned", then let lowerBound be 0. + if (signedness === 'unsigned') { + lowerBound = 0 + } else { + // 3. Otherwise let lowerBound be −2^53 + 1. + lowerBound = Math.pow(-2, 53) + 1 + } + } else if (signedness === 'unsigned') { + // 2. Otherwise, if signedness is "unsigned", then: + + // 1. Let lowerBound be 0. + lowerBound = 0 + + // 2. Let upperBound be 2^bitLength − 1. + upperBound = Math.pow(2, bitLength) - 1 + } else { + // 3. Otherwise: + + // 1. Let lowerBound be -2^bitLength − 1. + lowerBound = Math.pow(-2, bitLength) - 1 + + // 2. Let upperBound be 2^bitLength − 1 − 1. + upperBound = Math.pow(2, bitLength - 1) - 1 + } + + // 4. Let x be ? ToNumber(V). + let x = Number(V) + + // 5. If x is −0, then set x to +0. + if (x === 0) { + x = 0 + } + + // 6. If the conversion is to an IDL type associated + // with the [EnforceRange] extended attribute, then: + if (opts?.enforceRange === true) { + // 1. If x is NaN, +∞, or −∞, then throw a TypeError. + if ( + Number.isNaN(x) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Could not convert ${webidl.util.Stringify(V)} to an integer.` + }) + } + + // 2. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 3. If x < lowerBound or x > upperBound, then + // throw a TypeError. + if (x < lowerBound || x > upperBound) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` + }) + } + + // 4. Return x. + return x + } + + // 7. If x is not NaN and the conversion is to an IDL + // type associated with the [Clamp] extended + // attribute, then: + if (!Number.isNaN(x) && opts?.clamp === true) { + // 1. Set x to min(max(x, lowerBound), upperBound). + x = Math.min(Math.max(x, lowerBound), upperBound) + + // 2. Round x to the nearest integer, choosing the + // even integer if it lies halfway between two, + // and choosing +0 rather than −0. + if (Math.floor(x) % 2 === 0) { + x = Math.floor(x) + } else { + x = Math.ceil(x) + } + + // 3. Return x. + return x + } + + // 8. If x is NaN, +0, +∞, or −∞, then return +0. + if ( + Number.isNaN(x) || + (x === 0 && Object.is(0, x)) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + return 0 + } + + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength) + + // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, + // then return x − 2^bitLength. + if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { + return x - Math.pow(2, bitLength) + } + + // 12. Otherwise, return x. + return x +} + +// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart +webidl.util.IntegerPart = function (n) { + // 1. Let r be floor(abs(n)). + const r = Math.floor(Math.abs(n)) + + // 2. If n < 0, then return -1 × r. + if (n < 0) { + return -1 * r + } + + // 3. Otherwise, return r. + return r +} + +webidl.util.Stringify = function (V) { + const type = webidl.util.Type(V) + + switch (type) { + case 'Symbol': + return `Symbol(${V.description})` + case 'Object': + return inspect(V) + case 'String': + return `"${V}"` + default: + return `${V}` + } +} + +// https://webidl.spec.whatwg.org/#es-sequence +webidl.sequenceConverter = function (converter) { + return (V, prefix, argument, Iterable) => { + // 1. If Type(V) is not Object, throw a TypeError. + if (webidl.util.Type(V) !== 'Object') { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.` + }) + } + + // 2. Let method be ? GetMethod(V, @@iterator). + /** @type {Generator} */ + const method = typeof Iterable === 'function' ? Iterable() : V?.[Symbol.iterator]?.() + const seq = [] + let index = 0 + + // 3. If method is undefined, throw a TypeError. + if ( + method === undefined || + typeof method.next !== 'function' + ) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} is not iterable.` + }) + } + + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next() + + if (done) { + break + } + + seq.push(converter(value, prefix, `${argument}[${index++}]`)) + } + + return seq + } +} + +// https://webidl.spec.whatwg.org/#es-to-record +webidl.recordConverter = function (keyConverter, valueConverter) { + return (O, prefix, argument) => { + // 1. If Type(O) is not Object, throw a TypeError. + if (webidl.util.Type(O) !== 'Object') { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} ("${webidl.util.Type(O)}") is not an Object.` + }) + } + + // 2. Let result be a new empty instance of record. + const result = {} + + if (!types.isProxy(O)) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const keys = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)] + + for (const key of keys) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key, prefix, argument) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key], prefix, argument) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + + // 5. Return result. + return result + } + + // 3. Let keys be ? O.[[OwnPropertyKeys]](). + const keys = Reflect.ownKeys(O) + + // 4. For each key of keys. + for (const key of keys) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const desc = Reflect.getOwnPropertyDescriptor(O, key) + + // 2. If desc is not undefined and desc.[[Enumerable]] is true: + if (desc?.enumerable) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key, prefix, argument) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key], prefix, argument) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + } + + // 5. Return result. + return result + } +} + +webidl.interfaceConverter = function (i) { + return (V, prefix, argument, opts) => { + if (opts?.strict !== false && !(V instanceof i)) { + throw webidl.errors.exception({ + header: prefix, + message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${i.name}.` + }) + } + + return V + } +} + +webidl.dictionaryConverter = function (converters) { + return (dictionary, prefix, argument) => { + const type = webidl.util.Type(dictionary) + const dict = {} + + if (type === 'Null' || type === 'Undefined') { + return dict + } else if (type !== 'Object') { + throw webidl.errors.exception({ + header: prefix, + message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` + }) + } + + for (const options of converters) { + const { key, defaultValue, required, converter } = options + + if (required === true) { + if (!Object.hasOwn(dictionary, key)) { + throw webidl.errors.exception({ + header: prefix, + message: `Missing required key "${key}".` + }) + } + } + + let value = dictionary[key] + const hasDefault = Object.hasOwn(options, 'defaultValue') + + // Only use defaultValue if value is undefined and + // a defaultValue options was provided. + if (hasDefault && value !== null) { + value ??= defaultValue() + } + + // A key can be optional and have no default value. + // When this happens, do not perform a conversion, + // and do not assign the key a value. + if (required || hasDefault || value !== undefined) { + value = converter(value, prefix, `${argument}.${key}`) + + if ( + options.allowedValues && + !options.allowedValues.includes(value) + ) { + throw webidl.errors.exception({ + header: prefix, + message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` + }) + } + + dict[key] = value + } + } + + return dict + } +} + +webidl.nullableConverter = function (converter) { + return (V, prefix, argument) => { + if (V === null) { + return V + } + + return converter(V, prefix, argument) + } +} + +// https://webidl.spec.whatwg.org/#es-DOMString +webidl.converters.DOMString = function (V, prefix, argument, opts) { + // 1. If V is null and the conversion is to an IDL type + // associated with the [LegacyNullToEmptyString] + // extended attribute, then return the DOMString value + // that represents the empty string. + if (V === null && opts?.legacyNullToEmptyString) { + return '' + } + + // 2. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} is a symbol, which cannot be converted to a DOMString.` + }) + } + + // 3. Return the IDL DOMString value that represents the + // same sequence of code units as the one the + // ECMAScript String value x represents. + return String(V) +} + +// https://webidl.spec.whatwg.org/#es-ByteString +webidl.converters.ByteString = function (V, prefix, argument) { + // 1. Let x be ? ToString(V). + // Note: DOMString converter perform ? ToString(V) + const x = webidl.converters.DOMString(V, prefix, argument) + + // 2. If the value of any element of x is greater than + // 255, then throw a TypeError. + for (let index = 0; index < x.length; index++) { + if (x.charCodeAt(index) > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` + ) + } + } + + // 3. Return an IDL ByteString value whose length is the + // length of x, and where the value of each element is + // the value of the corresponding element of x. + return x +} + +// https://webidl.spec.whatwg.org/#es-USVString +// TODO: rewrite this so we can control the errors thrown +webidl.converters.USVString = toUSVString + +// https://webidl.spec.whatwg.org/#es-boolean +webidl.converters.boolean = function (V) { + // 1. Let x be the result of computing ToBoolean(V). + const x = Boolean(V) + + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x +} + +// https://webidl.spec.whatwg.org/#es-any +webidl.converters.any = function (V) { + return V +} + +// https://webidl.spec.whatwg.org/#es-long-long +webidl.converters['long long'] = function (V, prefix, argument) { + // 1. Let x be ? ConvertToInt(V, 64, "signed"). + const x = webidl.util.ConvertToInt(V, 64, 'signed', undefined, prefix, argument) + + // 2. Return the IDL long long value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long-long +webidl.converters['unsigned long long'] = function (V, prefix, argument) { + // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). + const x = webidl.util.ConvertToInt(V, 64, 'unsigned', undefined, prefix, argument) + + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long +webidl.converters['unsigned long'] = function (V, prefix, argument) { + // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). + const x = webidl.util.ConvertToInt(V, 32, 'unsigned', undefined, prefix, argument) + + // 2. Return the IDL unsigned long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-short +webidl.converters['unsigned short'] = function (V, prefix, argument, opts) { + // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). + const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts, prefix, argument) + + // 2. Return the IDL unsigned short value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#idl-ArrayBuffer +webidl.converters.ArrayBuffer = function (V, prefix, argument, opts) { + // 1. If Type(V) is not Object, or V does not have an + // [[ArrayBufferData]] internal slot, then throw a + // TypeError. + // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances + // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances + if ( + webidl.util.Type(V) !== 'Object' || + !types.isAnyArrayBuffer(V) + ) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ['ArrayBuffer'] + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V) is true, then throw a + // TypeError. + if (opts?.allowShared === false && types.isSharedArrayBuffer(V)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V) is true, then throw a + // TypeError. + if (V.resizable || V.growable) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'Received a resizable ArrayBuffer.' + }) + } + + // 4. Return the IDL ArrayBuffer value that is a + // reference to the same object as V. + return V +} + +webidl.converters.TypedArray = function (V, T, prefix, name, opts) { + // 1. Let T be the IDL type V is being converted to. + + // 2. If Type(V) is not Object, or V does not have a + // [[TypedArrayName]] internal slot with a value + // equal to T’s name, then throw a TypeError. + if ( + webidl.util.Type(V) !== 'Object' || + !types.isTypedArray(V) || + V.constructor.name !== T.name + ) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${name} ("${webidl.util.Stringify(V)}")`, + types: [T.name] + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 4. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (V.buffer.resizable || V.buffer.growable) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'Received a resizable ArrayBuffer.' + }) + } + + // 5. Return the IDL value of type T that is a reference + // to the same object as V. + return V +} + +webidl.converters.DataView = function (V, prefix, name, opts) { + // 1. If Type(V) is not Object, or V does not have a + // [[DataView]] internal slot, then throw a TypeError. + if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { + throw webidl.errors.exception({ + header: prefix, + message: `${name} is not a DataView.` + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, + // then throw a TypeError. + if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (V.buffer.resizable || V.buffer.growable) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'Received a resizable ArrayBuffer.' + }) + } + + // 4. Return the IDL DataView value that is a reference + // to the same object as V. + return V +} + +// https://webidl.spec.whatwg.org/#BufferSource +webidl.converters.BufferSource = function (V, prefix, name, opts) { + if (types.isAnyArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, prefix, name, { ...opts, allowShared: false }) + } + + if (types.isTypedArray(V)) { + return webidl.converters.TypedArray(V, V.constructor, prefix, name, { ...opts, allowShared: false }) + } + + if (types.isDataView(V)) { + return webidl.converters.DataView(V, prefix, name, { ...opts, allowShared: false }) + } + + throw webidl.errors.conversionFailed({ + prefix, + argument: `${name} ("${webidl.util.Stringify(V)}")`, + types: ['BufferSource'] + }) +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.ByteString +) + +webidl.converters['sequence>'] = webidl.sequenceConverter( + webidl.converters['sequence'] +) + +webidl.converters['record'] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString +) + +module.exports = { + webidl +} diff --git a/node_modules/undici/lib/web/fileapi/encoding.js b/node_modules/undici/lib/web/fileapi/encoding.js new file mode 100644 index 0000000000000..1d1d2b6544f9f --- /dev/null +++ b/node_modules/undici/lib/web/fileapi/encoding.js @@ -0,0 +1,290 @@ +'use strict' + +/** + * @see https://encoding.spec.whatwg.org/#concept-encoding-get + * @param {string|undefined} label + */ +function getEncoding (label) { + if (!label) { + return 'failure' + } + + // 1. Remove any leading and trailing ASCII whitespace from label. + // 2. If label is an ASCII case-insensitive match for any of the + // labels listed in the table below, then return the + // corresponding encoding; otherwise return failure. + switch (label.trim().toLowerCase()) { + case 'unicode-1-1-utf-8': + case 'unicode11utf8': + case 'unicode20utf8': + case 'utf-8': + case 'utf8': + case 'x-unicode20utf8': + return 'UTF-8' + case '866': + case 'cp866': + case 'csibm866': + case 'ibm866': + return 'IBM866' + case 'csisolatin2': + case 'iso-8859-2': + case 'iso-ir-101': + case 'iso8859-2': + case 'iso88592': + case 'iso_8859-2': + case 'iso_8859-2:1987': + case 'l2': + case 'latin2': + return 'ISO-8859-2' + case 'csisolatin3': + case 'iso-8859-3': + case 'iso-ir-109': + case 'iso8859-3': + case 'iso88593': + case 'iso_8859-3': + case 'iso_8859-3:1988': + case 'l3': + case 'latin3': + return 'ISO-8859-3' + case 'csisolatin4': + case 'iso-8859-4': + case 'iso-ir-110': + case 'iso8859-4': + case 'iso88594': + case 'iso_8859-4': + case 'iso_8859-4:1988': + case 'l4': + case 'latin4': + return 'ISO-8859-4' + case 'csisolatincyrillic': + case 'cyrillic': + case 'iso-8859-5': + case 'iso-ir-144': + case 'iso8859-5': + case 'iso88595': + case 'iso_8859-5': + case 'iso_8859-5:1988': + return 'ISO-8859-5' + case 'arabic': + case 'asmo-708': + case 'csiso88596e': + case 'csiso88596i': + case 'csisolatinarabic': + case 'ecma-114': + case 'iso-8859-6': + case 'iso-8859-6-e': + case 'iso-8859-6-i': + case 'iso-ir-127': + case 'iso8859-6': + case 'iso88596': + case 'iso_8859-6': + case 'iso_8859-6:1987': + return 'ISO-8859-6' + case 'csisolatingreek': + case 'ecma-118': + case 'elot_928': + case 'greek': + case 'greek8': + case 'iso-8859-7': + case 'iso-ir-126': + case 'iso8859-7': + case 'iso88597': + case 'iso_8859-7': + case 'iso_8859-7:1987': + case 'sun_eu_greek': + return 'ISO-8859-7' + case 'csiso88598e': + case 'csisolatinhebrew': + case 'hebrew': + case 'iso-8859-8': + case 'iso-8859-8-e': + case 'iso-ir-138': + case 'iso8859-8': + case 'iso88598': + case 'iso_8859-8': + case 'iso_8859-8:1988': + case 'visual': + return 'ISO-8859-8' + case 'csiso88598i': + case 'iso-8859-8-i': + case 'logical': + return 'ISO-8859-8-I' + case 'csisolatin6': + case 'iso-8859-10': + case 'iso-ir-157': + case 'iso8859-10': + case 'iso885910': + case 'l6': + case 'latin6': + return 'ISO-8859-10' + case 'iso-8859-13': + case 'iso8859-13': + case 'iso885913': + return 'ISO-8859-13' + case 'iso-8859-14': + case 'iso8859-14': + case 'iso885914': + return 'ISO-8859-14' + case 'csisolatin9': + case 'iso-8859-15': + case 'iso8859-15': + case 'iso885915': + case 'iso_8859-15': + case 'l9': + return 'ISO-8859-15' + case 'iso-8859-16': + return 'ISO-8859-16' + case 'cskoi8r': + case 'koi': + case 'koi8': + case 'koi8-r': + case 'koi8_r': + return 'KOI8-R' + case 'koi8-ru': + case 'koi8-u': + return 'KOI8-U' + case 'csmacintosh': + case 'mac': + case 'macintosh': + case 'x-mac-roman': + return 'macintosh' + case 'iso-8859-11': + case 'iso8859-11': + case 'iso885911': + case 'tis-620': + case 'windows-874': + return 'windows-874' + case 'cp1250': + case 'windows-1250': + case 'x-cp1250': + return 'windows-1250' + case 'cp1251': + case 'windows-1251': + case 'x-cp1251': + return 'windows-1251' + case 'ansi_x3.4-1968': + case 'ascii': + case 'cp1252': + case 'cp819': + case 'csisolatin1': + case 'ibm819': + case 'iso-8859-1': + case 'iso-ir-100': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'iso_8859-1:1987': + case 'l1': + case 'latin1': + case 'us-ascii': + case 'windows-1252': + case 'x-cp1252': + return 'windows-1252' + case 'cp1253': + case 'windows-1253': + case 'x-cp1253': + return 'windows-1253' + case 'cp1254': + case 'csisolatin5': + case 'iso-8859-9': + case 'iso-ir-148': + case 'iso8859-9': + case 'iso88599': + case 'iso_8859-9': + case 'iso_8859-9:1989': + case 'l5': + case 'latin5': + case 'windows-1254': + case 'x-cp1254': + return 'windows-1254' + case 'cp1255': + case 'windows-1255': + case 'x-cp1255': + return 'windows-1255' + case 'cp1256': + case 'windows-1256': + case 'x-cp1256': + return 'windows-1256' + case 'cp1257': + case 'windows-1257': + case 'x-cp1257': + return 'windows-1257' + case 'cp1258': + case 'windows-1258': + case 'x-cp1258': + return 'windows-1258' + case 'x-mac-cyrillic': + case 'x-mac-ukrainian': + return 'x-mac-cyrillic' + case 'chinese': + case 'csgb2312': + case 'csiso58gb231280': + case 'gb2312': + case 'gb_2312': + case 'gb_2312-80': + case 'gbk': + case 'iso-ir-58': + case 'x-gbk': + return 'GBK' + case 'gb18030': + return 'gb18030' + case 'big5': + case 'big5-hkscs': + case 'cn-big5': + case 'csbig5': + case 'x-x-big5': + return 'Big5' + case 'cseucpkdfmtjapanese': + case 'euc-jp': + case 'x-euc-jp': + return 'EUC-JP' + case 'csiso2022jp': + case 'iso-2022-jp': + return 'ISO-2022-JP' + case 'csshiftjis': + case 'ms932': + case 'ms_kanji': + case 'shift-jis': + case 'shift_jis': + case 'sjis': + case 'windows-31j': + case 'x-sjis': + return 'Shift_JIS' + case 'cseuckr': + case 'csksc56011987': + case 'euc-kr': + case 'iso-ir-149': + case 'korean': + case 'ks_c_5601-1987': + case 'ks_c_5601-1989': + case 'ksc5601': + case 'ksc_5601': + case 'windows-949': + return 'EUC-KR' + case 'csiso2022kr': + case 'hz-gb-2312': + case 'iso-2022-cn': + case 'iso-2022-cn-ext': + case 'iso-2022-kr': + case 'replacement': + return 'replacement' + case 'unicodefffe': + case 'utf-16be': + return 'UTF-16BE' + case 'csunicode': + case 'iso-10646-ucs-2': + case 'ucs-2': + case 'unicode': + case 'unicodefeff': + case 'utf-16': + case 'utf-16le': + return 'UTF-16LE' + case 'x-user-defined': + return 'x-user-defined' + default: return 'failure' + } +} + +module.exports = { + getEncoding +} diff --git a/node_modules/undici/lib/web/fileapi/filereader.js b/node_modules/undici/lib/web/fileapi/filereader.js new file mode 100644 index 0000000000000..ccebe692a6f49 --- /dev/null +++ b/node_modules/undici/lib/web/fileapi/filereader.js @@ -0,0 +1,344 @@ +'use strict' + +const { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} = require('./util') +const { + kState, + kError, + kResult, + kEvents, + kAborted +} = require('./symbols') +const { webidl } = require('../fetch/webidl') +const { kEnumerableProperty } = require('../../core/util') + +class FileReader extends EventTarget { + constructor () { + super() + + this[kState] = 'empty' + this[kResult] = null + this[kError] = null + this[kEvents] = { + loadend: null, + error: null, + abort: null, + load: null, + progress: null, + loadstart: null + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer + * @param {import('buffer').Blob} blob + */ + readAsArrayBuffer (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsArrayBuffer') + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsArrayBuffer(blob) method, when invoked, + // must initiate a read operation for blob with ArrayBuffer. + readOperation(this, blob, 'ArrayBuffer') + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsBinaryString + * @param {import('buffer').Blob} blob + */ + readAsBinaryString (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsBinaryString') + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsBinaryString(blob) method, when invoked, + // must initiate a read operation for blob with BinaryString. + readOperation(this, blob, 'BinaryString') + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsDataText + * @param {import('buffer').Blob} blob + * @param {string?} encoding + */ + readAsText (blob, encoding = undefined) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsText') + + blob = webidl.converters.Blob(blob, { strict: false }) + + if (encoding !== undefined) { + encoding = webidl.converters.DOMString(encoding, 'FileReader.readAsText', 'encoding') + } + + // The readAsText(blob, encoding) method, when invoked, + // must initiate a read operation for blob with Text and encoding. + readOperation(this, blob, 'Text', encoding) + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL + * @param {import('buffer').Blob} blob + */ + readAsDataURL (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsDataURL') + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsDataURL(blob) method, when invoked, must + // initiate a read operation for blob with DataURL. + readOperation(this, blob, 'DataURL') + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-abort + */ + abort () { + // 1. If this's state is "empty" or if this's state is + // "done" set this's result to null and terminate + // this algorithm. + if (this[kState] === 'empty' || this[kState] === 'done') { + this[kResult] = null + return + } + + // 2. If this's state is "loading" set this's state to + // "done" and set this's result to null. + if (this[kState] === 'loading') { + this[kState] = 'done' + this[kResult] = null + } + + // 3. If there are any tasks from this on the file reading + // task source in an affiliated task queue, then remove + // those tasks from that task queue. + this[kAborted] = true + + // 4. Terminate the algorithm for the read method being processed. + // TODO + + // 5. Fire a progress event called abort at this. + fireAProgressEvent('abort', this) + + // 6. If this's state is not "loading", fire a progress + // event called loadend at this. + if (this[kState] !== 'loading') { + fireAProgressEvent('loadend', this) + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate + */ + get readyState () { + webidl.brandCheck(this, FileReader) + + switch (this[kState]) { + case 'empty': return this.EMPTY + case 'loading': return this.LOADING + case 'done': return this.DONE + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-result + */ + get result () { + webidl.brandCheck(this, FileReader) + + // The result attribute’s getter, when invoked, must return + // this's result. + return this[kResult] + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-error + */ + get error () { + webidl.brandCheck(this, FileReader) + + // The error attribute’s getter, when invoked, must return + // this's error. + return this[kError] + } + + get onloadend () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].loadend + } + + set onloadend (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadend) { + this.removeEventListener('loadend', this[kEvents].loadend) + } + + if (typeof fn === 'function') { + this[kEvents].loadend = fn + this.addEventListener('loadend', fn) + } else { + this[kEvents].loadend = null + } + } + + get onerror () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].error + } + + set onerror (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].error) { + this.removeEventListener('error', this[kEvents].error) + } + + if (typeof fn === 'function') { + this[kEvents].error = fn + this.addEventListener('error', fn) + } else { + this[kEvents].error = null + } + } + + get onloadstart () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].loadstart + } + + set onloadstart (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadstart) { + this.removeEventListener('loadstart', this[kEvents].loadstart) + } + + if (typeof fn === 'function') { + this[kEvents].loadstart = fn + this.addEventListener('loadstart', fn) + } else { + this[kEvents].loadstart = null + } + } + + get onprogress () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].progress + } + + set onprogress (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].progress) { + this.removeEventListener('progress', this[kEvents].progress) + } + + if (typeof fn === 'function') { + this[kEvents].progress = fn + this.addEventListener('progress', fn) + } else { + this[kEvents].progress = null + } + } + + get onload () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].load + } + + set onload (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].load) { + this.removeEventListener('load', this[kEvents].load) + } + + if (typeof fn === 'function') { + this[kEvents].load = fn + this.addEventListener('load', fn) + } else { + this[kEvents].load = null + } + } + + get onabort () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].abort + } + + set onabort (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].abort) { + this.removeEventListener('abort', this[kEvents].abort) + } + + if (typeof fn === 'function') { + this[kEvents].abort = fn + this.addEventListener('abort', fn) + } else { + this[kEvents].abort = null + } + } +} + +// https://w3c.github.io/FileAPI/#dom-filereader-empty +FileReader.EMPTY = FileReader.prototype.EMPTY = 0 +// https://w3c.github.io/FileAPI/#dom-filereader-loading +FileReader.LOADING = FileReader.prototype.LOADING = 1 +// https://w3c.github.io/FileAPI/#dom-filereader-done +FileReader.DONE = FileReader.prototype.DONE = 2 + +Object.defineProperties(FileReader.prototype, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors, + readAsArrayBuffer: kEnumerableProperty, + readAsBinaryString: kEnumerableProperty, + readAsText: kEnumerableProperty, + readAsDataURL: kEnumerableProperty, + abort: kEnumerableProperty, + readyState: kEnumerableProperty, + result: kEnumerableProperty, + error: kEnumerableProperty, + onloadstart: kEnumerableProperty, + onprogress: kEnumerableProperty, + onload: kEnumerableProperty, + onabort: kEnumerableProperty, + onerror: kEnumerableProperty, + onloadend: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FileReader', + writable: false, + enumerable: false, + configurable: true + } +}) + +Object.defineProperties(FileReader, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors +}) + +module.exports = { + FileReader +} diff --git a/node_modules/undici/lib/web/fileapi/progressevent.js b/node_modules/undici/lib/web/fileapi/progressevent.js new file mode 100644 index 0000000000000..2d09d18107de7 --- /dev/null +++ b/node_modules/undici/lib/web/fileapi/progressevent.js @@ -0,0 +1,78 @@ +'use strict' + +const { webidl } = require('../fetch/webidl') + +const kState = Symbol('ProgressEvent state') + +/** + * @see https://xhr.spec.whatwg.org/#progressevent + */ +class ProgressEvent extends Event { + constructor (type, eventInitDict = {}) { + type = webidl.converters.DOMString(type, 'ProgressEvent constructor', 'type') + eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) + + super(type, eventInitDict) + + this[kState] = { + lengthComputable: eventInitDict.lengthComputable, + loaded: eventInitDict.loaded, + total: eventInitDict.total + } + } + + get lengthComputable () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].lengthComputable + } + + get loaded () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].loaded + } + + get total () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].total + } +} + +webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ + { + key: 'lengthComputable', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'loaded', + converter: webidl.converters['unsigned long long'], + defaultValue: () => 0 + }, + { + key: 'total', + converter: webidl.converters['unsigned long long'], + defaultValue: () => 0 + }, + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: () => false + } +]) + +module.exports = { + ProgressEvent +} diff --git a/node_modules/undici/lib/web/fileapi/symbols.js b/node_modules/undici/lib/web/fileapi/symbols.js new file mode 100644 index 0000000000000..dd11746de389c --- /dev/null +++ b/node_modules/undici/lib/web/fileapi/symbols.js @@ -0,0 +1,10 @@ +'use strict' + +module.exports = { + kState: Symbol('FileReader state'), + kResult: Symbol('FileReader result'), + kError: Symbol('FileReader error'), + kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), + kEvents: Symbol('FileReader events'), + kAborted: Symbol('FileReader aborted') +} diff --git a/node_modules/undici/lib/web/fileapi/util.js b/node_modules/undici/lib/web/fileapi/util.js new file mode 100644 index 0000000000000..9110b872a817d --- /dev/null +++ b/node_modules/undici/lib/web/fileapi/util.js @@ -0,0 +1,391 @@ +'use strict' + +const { + kState, + kError, + kResult, + kAborted, + kLastProgressEventFired +} = require('./symbols') +const { ProgressEvent } = require('./progressevent') +const { getEncoding } = require('./encoding') +const { serializeAMimeType, parseMIMEType } = require('../fetch/data-url') +const { types } = require('node:util') +const { StringDecoder } = require('string_decoder') +const { btoa } = require('node:buffer') + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +/** + * @see https://w3c.github.io/FileAPI/#readOperation + * @param {import('./filereader').FileReader} fr + * @param {import('buffer').Blob} blob + * @param {string} type + * @param {string?} encodingName + */ +function readOperation (fr, blob, type, encodingName) { + // 1. If fr’s state is "loading", throw an InvalidStateError + // DOMException. + if (fr[kState] === 'loading') { + throw new DOMException('Invalid state', 'InvalidStateError') + } + + // 2. Set fr’s state to "loading". + fr[kState] = 'loading' + + // 3. Set fr’s result to null. + fr[kResult] = null + + // 4. Set fr’s error to null. + fr[kError] = null + + // 5. Let stream be the result of calling get stream on blob. + /** @type {import('stream/web').ReadableStream} */ + const stream = blob.stream() + + // 6. Let reader be the result of getting a reader from stream. + const reader = stream.getReader() + + // 7. Let bytes be an empty byte sequence. + /** @type {Uint8Array[]} */ + const bytes = [] + + // 8. Let chunkPromise be the result of reading a chunk from + // stream with reader. + let chunkPromise = reader.read() + + // 9. Let isFirstChunk be true. + let isFirstChunk = true + + // 10. In parallel, while true: + // Note: "In parallel" just means non-blocking + // Note 2: readOperation itself cannot be async as double + // reading the body would then reject the promise, instead + // of throwing an error. + ;(async () => { + while (!fr[kAborted]) { + // 1. Wait for chunkPromise to be fulfilled or rejected. + try { + const { done, value } = await chunkPromise + + // 2. If chunkPromise is fulfilled, and isFirstChunk is + // true, queue a task to fire a progress event called + // loadstart at fr. + if (isFirstChunk && !fr[kAborted]) { + queueMicrotask(() => { + fireAProgressEvent('loadstart', fr) + }) + } + + // 3. Set isFirstChunk to false. + isFirstChunk = false + + // 4. If chunkPromise is fulfilled with an object whose + // done property is false and whose value property is + // a Uint8Array object, run these steps: + if (!done && types.isUint8Array(value)) { + // 1. Let bs be the byte sequence represented by the + // Uint8Array object. + + // 2. Append bs to bytes. + bytes.push(value) + + // 3. If roughly 50ms have passed since these steps + // were last invoked, queue a task to fire a + // progress event called progress at fr. + if ( + ( + fr[kLastProgressEventFired] === undefined || + Date.now() - fr[kLastProgressEventFired] >= 50 + ) && + !fr[kAborted] + ) { + fr[kLastProgressEventFired] = Date.now() + queueMicrotask(() => { + fireAProgressEvent('progress', fr) + }) + } + + // 4. Set chunkPromise to the result of reading a + // chunk from stream with reader. + chunkPromise = reader.read() + } else if (done) { + // 5. Otherwise, if chunkPromise is fulfilled with an + // object whose done property is true, queue a task + // to run the following steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Let result be the result of package data given + // bytes, type, blob’s type, and encodingName. + try { + const result = packageData(bytes, type, blob.type, encodingName) + + // 4. Else: + + if (fr[kAborted]) { + return + } + + // 1. Set fr’s result to result. + fr[kResult] = result + + // 2. Fire a progress event called load at the fr. + fireAProgressEvent('load', fr) + } catch (error) { + // 3. If package data threw an exception error: + + // 1. Set fr’s error to error. + fr[kError] = error + + // 2. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + } + + // 5. If fr’s state is not "loading", fire a progress + // event called loadend at the fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } catch (error) { + if (fr[kAborted]) { + return + } + + // 6. Otherwise, if chunkPromise is rejected with an + // error error, queue a task to run the following + // steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Set fr’s error to error. + fr[kError] = error + + // 3. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + + // 4. If fr’s state is not "loading", fire a progress + // event called loadend at fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } + })() +} + +/** + * @see https://w3c.github.io/FileAPI/#fire-a-progress-event + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e The name of the event + * @param {import('./filereader').FileReader} reader + */ +function fireAProgressEvent (e, reader) { + // The progress event e does not bubble. e.bubbles must be false + // The progress event e is NOT cancelable. e.cancelable must be false + const event = new ProgressEvent(e, { + bubbles: false, + cancelable: false + }) + + reader.dispatchEvent(event) +} + +/** + * @see https://w3c.github.io/FileAPI/#blob-package-data + * @param {Uint8Array[]} bytes + * @param {string} type + * @param {string?} mimeType + * @param {string?} encodingName + */ +function packageData (bytes, type, mimeType, encodingName) { + // 1. A Blob has an associated package data algorithm, given + // bytes, a type, a optional mimeType, and a optional + // encodingName, which switches on type and runs the + // associated steps: + + switch (type) { + case 'DataURL': { + // 1. Return bytes as a DataURL [RFC2397] subject to + // the considerations below: + // * Use mimeType as part of the Data URL if it is + // available in keeping with the Data URL + // specification [RFC2397]. + // * If mimeType is not available return a Data URL + // without a media-type. [RFC2397]. + + // https://datatracker.ietf.org/doc/html/rfc2397#section-3 + // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data + // mediatype := [ type "/" subtype ] *( ";" parameter ) + // data := *urlchar + // parameter := attribute "=" value + let dataURL = 'data:' + + const parsed = parseMIMEType(mimeType || 'application/octet-stream') + + if (parsed !== 'failure') { + dataURL += serializeAMimeType(parsed) + } + + dataURL += ';base64,' + + const decoder = new StringDecoder('latin1') + + for (const chunk of bytes) { + dataURL += btoa(decoder.write(chunk)) + } + + dataURL += btoa(decoder.end()) + + return dataURL + } + case 'Text': { + // 1. Let encoding be failure + let encoding = 'failure' + + // 2. If the encodingName is present, set encoding to the + // result of getting an encoding from encodingName. + if (encodingName) { + encoding = getEncoding(encodingName) + } + + // 3. If encoding is failure, and mimeType is present: + if (encoding === 'failure' && mimeType) { + // 1. Let type be the result of parse a MIME type + // given mimeType. + const type = parseMIMEType(mimeType) + + // 2. If type is not failure, set encoding to the result + // of getting an encoding from type’s parameters["charset"]. + if (type !== 'failure') { + encoding = getEncoding(type.parameters.get('charset')) + } + } + + // 4. If encoding is failure, then set encoding to UTF-8. + if (encoding === 'failure') { + encoding = 'UTF-8' + } + + // 5. Decode bytes using fallback encoding encoding, and + // return the result. + return decode(bytes, encoding) + } + case 'ArrayBuffer': { + // Return a new ArrayBuffer whose contents are bytes. + const sequence = combineByteSequences(bytes) + + return sequence.buffer + } + case 'BinaryString': { + // Return bytes as a binary string, in which every byte + // is represented by a code unit of equal value [0..255]. + let binaryString = '' + + const decoder = new StringDecoder('latin1') + + for (const chunk of bytes) { + binaryString += decoder.write(chunk) + } + + binaryString += decoder.end() + + return binaryString + } + } +} + +/** + * @see https://encoding.spec.whatwg.org/#decode + * @param {Uint8Array[]} ioQueue + * @param {string} encoding + */ +function decode (ioQueue, encoding) { + const bytes = combineByteSequences(ioQueue) + + // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. + const BOMEncoding = BOMSniffing(bytes) + + let slice = 0 + + // 2. If BOMEncoding is non-null: + if (BOMEncoding !== null) { + // 1. Set encoding to BOMEncoding. + encoding = BOMEncoding + + // 2. Read three bytes from ioQueue, if BOMEncoding is + // UTF-8; otherwise read two bytes. + // (Do nothing with those bytes.) + slice = BOMEncoding === 'UTF-8' ? 3 : 2 + } + + // 3. Process a queue with an instance of encoding’s + // decoder, ioQueue, output, and "replacement". + + // 4. Return output. + + const sliced = bytes.slice(slice) + return new TextDecoder(encoding).decode(sliced) +} + +/** + * @see https://encoding.spec.whatwg.org/#bom-sniff + * @param {Uint8Array} ioQueue + */ +function BOMSniffing (ioQueue) { + // 1. Let BOM be the result of peeking 3 bytes from ioQueue, + // converted to a byte sequence. + const [a, b, c] = ioQueue + + // 2. For each of the rows in the table below, starting with + // the first one and going down, if BOM starts with the + // bytes given in the first column, then return the + // encoding given in the cell in the second column of that + // row. Otherwise, return null. + if (a === 0xEF && b === 0xBB && c === 0xBF) { + return 'UTF-8' + } else if (a === 0xFE && b === 0xFF) { + return 'UTF-16BE' + } else if (a === 0xFF && b === 0xFE) { + return 'UTF-16LE' + } + + return null +} + +/** + * @param {Uint8Array[]} sequences + */ +function combineByteSequences (sequences) { + const size = sequences.reduce((a, b) => { + return a + b.byteLength + }, 0) + + let offset = 0 + + return sequences.reduce((a, b) => { + a.set(b, offset) + offset += b.byteLength + return a + }, new Uint8Array(size)) +} + +module.exports = { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} diff --git a/node_modules/undici/lib/web/websocket/connection.js b/node_modules/undici/lib/web/websocket/connection.js new file mode 100644 index 0000000000000..bb87d361e4b74 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/connection.js @@ -0,0 +1,371 @@ +'use strict' + +const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require('./constants') +const { + kReadyState, + kSentClose, + kByteParser, + kReceivedClose, + kResponse +} = require('./symbols') +const { fireEvent, failWebsocketConnection, isClosing, isClosed, isEstablished, parseExtensions } = require('./util') +const { channels } = require('../../core/diagnostics') +const { CloseEvent } = require('./events') +const { makeRequest } = require('../fetch/request') +const { fetching } = require('../fetch/index') +const { Headers, getHeadersList } = require('../fetch/headers') +const { getDecodeSplit } = require('../fetch/util') +const { WebsocketFrameSend } = require('./frame') + +/** @type {import('crypto')} */ +let crypto +try { + crypto = require('node:crypto') +/* c8 ignore next 3 */ +} catch { + +} + +/** + * @see https://websockets.spec.whatwg.org/#concept-websocket-establish + * @param {URL} url + * @param {string|string[]} protocols + * @param {import('./websocket').WebSocket} ws + * @param {(response: any, extensions: string[] | undefined) => void} onEstablish + * @param {Partial} options + */ +function establishWebSocketConnection (url, protocols, client, ws, onEstablish, options) { + // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s + // scheme is "ws", and to "https" otherwise. + const requestURL = url + + requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' + + // 2. Let request be a new request, whose URL is requestURL, client is client, + // service-workers mode is "none", referrer is "no-referrer", mode is + // "websocket", credentials mode is "include", cache mode is "no-store" , + // and redirect mode is "error". + const request = makeRequest({ + urlList: [requestURL], + client, + serviceWorkers: 'none', + referrer: 'no-referrer', + mode: 'websocket', + credentials: 'include', + cache: 'no-store', + redirect: 'error' + }) + + // Note: undici extension, allow setting custom headers. + if (options.headers) { + const headersList = getHeadersList(new Headers(options.headers)) + + request.headersList = headersList + } + + // 3. Append (`Upgrade`, `websocket`) to request’s header list. + // 4. Append (`Connection`, `Upgrade`) to request’s header list. + // Note: both of these are handled by undici currently. + // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 + + // 5. Let keyValue be a nonce consisting of a randomly selected + // 16-byte value that has been forgiving-base64-encoded and + // isomorphic encoded. + const keyValue = crypto.randomBytes(16).toString('base64') + + // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s + // header list. + request.headersList.append('sec-websocket-key', keyValue) + + // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s + // header list. + request.headersList.append('sec-websocket-version', '13') + + // 8. For each protocol in protocols, combine + // (`Sec-WebSocket-Protocol`, protocol) in request’s header + // list. + for (const protocol of protocols) { + request.headersList.append('sec-websocket-protocol', protocol) + } + + // 9. Let permessageDeflate be a user-agent defined + // "permessage-deflate" extension header value. + // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 + const permessageDeflate = 'permessage-deflate; client_max_window_bits' + + // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to + // request’s header list. + request.headersList.append('sec-websocket-extensions', permessageDeflate) + + // 11. Fetch request with useParallelQueue set to true, and + // processResponse given response being these steps: + const controller = fetching({ + request, + useParallelQueue: true, + dispatcher: options.dispatcher, + processResponse (response) { + // 1. If response is a network error or its status is not 101, + // fail the WebSocket connection. + if (response.type === 'error' || response.status !== 101) { + failWebsocketConnection(ws, 'Received network error or non-101 status code.') + return + } + + // 2. If protocols is not the empty list and extracting header + // list values given `Sec-WebSocket-Protocol` and response’s + // header list results in null, failure, or the empty byte + // sequence, then fail the WebSocket connection. + if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Server did not respond with sent protocols.') + return + } + + // 3. Follow the requirements stated step 2 to step 6, inclusive, + // of the last set of steps in section 4.1 of The WebSocket + // Protocol to validate response. This either results in fail + // the WebSocket connection or the WebSocket connection is + // established. + + // 2. If the response lacks an |Upgrade| header field or the |Upgrade| + // header field contains a value that is not an ASCII case- + // insensitive match for the value "websocket", the client MUST + // _Fail the WebSocket Connection_. + if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { + failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') + return + } + + // 3. If the response lacks a |Connection| header field or the + // |Connection| header field doesn't contain a token that is an + // ASCII case-insensitive match for the value "Upgrade", the client + // MUST _Fail the WebSocket Connection_. + if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { + failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') + return + } + + // 4. If the response lacks a |Sec-WebSocket-Accept| header field or + // the |Sec-WebSocket-Accept| contains a value other than the + // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- + // Key| (as a string, not base64-decoded) with the string "258EAFA5- + // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and + // trailing whitespace, the client MUST _Fail the WebSocket + // Connection_. + const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') + const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') + if (secWSAccept !== digest) { + failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') + return + } + + // 5. If the response includes a |Sec-WebSocket-Extensions| header + // field and this header field indicates the use of an extension + // that was not present in the client's handshake (the server has + // indicated an extension not requested by the client), the client + // MUST _Fail the WebSocket Connection_. (The parsing of this + // header field to determine which extensions are requested is + // discussed in Section 9.1.) + const secExtension = response.headersList.get('Sec-WebSocket-Extensions') + let extensions + + if (secExtension !== null) { + extensions = parseExtensions(secExtension) + + if (!extensions.has('permessage-deflate')) { + failWebsocketConnection(ws, 'Sec-WebSocket-Extensions header does not match.') + return + } + } + + // 6. If the response includes a |Sec-WebSocket-Protocol| header field + // and this header field indicates the use of a subprotocol that was + // not present in the client's handshake (the server has indicated a + // subprotocol not requested by the client), the client MUST _Fail + // the WebSocket Connection_. + const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') + + if (secProtocol !== null) { + const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList) + + // The client can request that the server use a specific subprotocol by + // including the |Sec-WebSocket-Protocol| field in its handshake. If it + // is specified, the server needs to include the same field and one of + // the selected subprotocol values in its response for the connection to + // be established. + if (!requestProtocols.includes(secProtocol)) { + failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') + return + } + } + + response.socket.on('data', onSocketData) + response.socket.on('close', onSocketClose) + response.socket.on('error', onSocketError) + + if (channels.open.hasSubscribers) { + channels.open.publish({ + address: response.socket.address(), + protocol: secProtocol, + extensions: secExtension + }) + } + + onEstablish(response, extensions) + } + }) + + return controller +} + +function closeWebSocketConnection (ws, code, reason, reasonByteLength) { + if (isClosing(ws) || isClosed(ws)) { + // If this's ready state is CLOSING (2) or CLOSED (3) + // Do nothing. + } else if (!isEstablished(ws)) { + // If the WebSocket connection is not yet established + // Fail the WebSocket connection and set this's ready state + // to CLOSING (2). + failWebsocketConnection(ws, 'Connection was closed before it was established.') + ws[kReadyState] = states.CLOSING + } else if (ws[kSentClose] === sentCloseFrameState.NOT_SENT) { + // If the WebSocket closing handshake has not yet been started + // Start the WebSocket closing handshake and set this's ready + // state to CLOSING (2). + // - If neither code nor reason is present, the WebSocket Close + // message must not have a body. + // - If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + // - If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + + ws[kSentClose] = sentCloseFrameState.PROCESSING + + const frame = new WebsocketFrameSend() + + // If neither code nor reason is present, the WebSocket Close + // message must not have a body. + + // If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + if (code !== undefined && reason === undefined) { + frame.frameData = Buffer.allocUnsafe(2) + frame.frameData.writeUInt16BE(code, 0) + } else if (code !== undefined && reason !== undefined) { + // If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) + frame.frameData.writeUInt16BE(code, 0) + // the body MAY contain UTF-8-encoded data with value /reason/ + frame.frameData.write(reason, 2, 'utf-8') + } else { + frame.frameData = emptyBuffer + } + + /** @type {import('stream').Duplex} */ + const socket = ws[kResponse].socket + + socket.write(frame.createFrame(opcodes.CLOSE)) + + ws[kSentClose] = sentCloseFrameState.SENT + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + ws[kReadyState] = states.CLOSING + } else { + // Otherwise + // Set this's ready state to CLOSING (2). + ws[kReadyState] = states.CLOSING + } +} + +/** + * @param {Buffer} chunk + */ +function onSocketData (chunk) { + if (!this.ws[kByteParser].write(chunk)) { + this.pause() + } +} + +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + */ +function onSocketClose () { + const { ws } = this + const { [kResponse]: response } = ws + + response.socket.off('data', onSocketData) + response.socket.off('close', onSocketClose) + response.socket.off('error', onSocketError) + + // If the TCP connection was closed after the + // WebSocket closing handshake was completed, the WebSocket connection + // is said to have been closed _cleanly_. + const wasClean = ws[kSentClose] === sentCloseFrameState.SENT && ws[kReceivedClose] + + let code = 1005 + let reason = '' + + const result = ws[kByteParser].closingInfo + + if (result && !result.error) { + code = result.code ?? 1005 + reason = result.reason + } else if (!ws[kReceivedClose]) { + // If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + code = 1006 + } + + // 1. Change the ready state to CLOSED (3). + ws[kReadyState] = states.CLOSED + + // 2. If the user agent was required to fail the WebSocket + // connection, or if the WebSocket connection was closed + // after being flagged as full, fire an event named error + // at the WebSocket object. + // TODO + + // 3. Fire an event named close at the WebSocket object, + // using CloseEvent, with the wasClean attribute + // initialized to true if the connection closed cleanly + // and false otherwise, the code attribute initialized to + // the WebSocket connection close code, and the reason + // attribute initialized to the result of applying UTF-8 + // decode without BOM to the WebSocket connection close + // reason. + // TODO: process.nextTick + fireEvent('close', ws, (type, init) => new CloseEvent(type, init), { + wasClean, code, reason + }) + + if (channels.close.hasSubscribers) { + channels.close.publish({ + websocket: ws, + code, + reason + }) + } +} + +function onSocketError (error) { + const { ws } = this + + ws[kReadyState] = states.CLOSING + + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(error) + } + + this.destroy() +} + +module.exports = { + establishWebSocketConnection, + closeWebSocketConnection +} diff --git a/node_modules/undici/lib/web/websocket/constants.js b/node_modules/undici/lib/web/websocket/constants.js new file mode 100644 index 0000000000000..2019b5b67a7ef --- /dev/null +++ b/node_modules/undici/lib/web/websocket/constants.js @@ -0,0 +1,66 @@ +'use strict' + +// This is a Globally Unique Identifier unique used +// to validate that the endpoint accepts websocket +// connections. +// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 +const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +const states = { + CONNECTING: 0, + OPEN: 1, + CLOSING: 2, + CLOSED: 3 +} + +const sentCloseFrameState = { + NOT_SENT: 0, + PROCESSING: 1, + SENT: 2 +} + +const opcodes = { + CONTINUATION: 0x0, + TEXT: 0x1, + BINARY: 0x2, + CLOSE: 0x8, + PING: 0x9, + PONG: 0xA +} + +const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 + +const parserStates = { + INFO: 0, + PAYLOADLENGTH_16: 2, + PAYLOADLENGTH_64: 3, + READ_DATA: 4 +} + +const emptyBuffer = Buffer.allocUnsafe(0) + +const sendHints = { + string: 1, + typedArray: 2, + arrayBuffer: 3, + blob: 4 +} + +module.exports = { + uid, + sentCloseFrameState, + staticPropertyDescriptors, + states, + opcodes, + maxUnsigned16Bit, + parserStates, + emptyBuffer, + sendHints +} diff --git a/node_modules/undici/lib/web/websocket/events.js b/node_modules/undici/lib/web/websocket/events.js new file mode 100644 index 0000000000000..f899c21d42bbe --- /dev/null +++ b/node_modules/undici/lib/web/websocket/events.js @@ -0,0 +1,329 @@ +'use strict' + +const { webidl } = require('../fetch/webidl') +const { kEnumerableProperty } = require('../../core/util') +const { kConstruct } = require('../../core/symbols') +const { MessagePort } = require('node:worker_threads') + +/** + * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent + */ +class MessageEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + if (type === kConstruct) { + super(arguments[1], arguments[2]) + webidl.util.markAsUncloneable(this) + return + } + + const prefix = 'MessageEvent constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + type = webidl.converters.DOMString(type, prefix, 'type') + eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, 'eventInitDict') + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + webidl.util.markAsUncloneable(this) + } + + get data () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.data + } + + get origin () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.origin + } + + get lastEventId () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.lastEventId + } + + get source () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.source + } + + get ports () { + webidl.brandCheck(this, MessageEvent) + + if (!Object.isFrozen(this.#eventInit.ports)) { + Object.freeze(this.#eventInit.ports) + } + + return this.#eventInit.ports + } + + initMessageEvent ( + type, + bubbles = false, + cancelable = false, + data = null, + origin = '', + lastEventId = '', + source = null, + ports = [] + ) { + webidl.brandCheck(this, MessageEvent) + + webidl.argumentLengthCheck(arguments, 1, 'MessageEvent.initMessageEvent') + + return new MessageEvent(type, { + bubbles, cancelable, data, origin, lastEventId, source, ports + }) + } + + static createFastMessageEvent (type, init) { + const messageEvent = new MessageEvent(kConstruct, type, init) + messageEvent.#eventInit = init + messageEvent.#eventInit.data ??= null + messageEvent.#eventInit.origin ??= '' + messageEvent.#eventInit.lastEventId ??= '' + messageEvent.#eventInit.source ??= null + messageEvent.#eventInit.ports ??= [] + return messageEvent + } +} + +const { createFastMessageEvent } = MessageEvent +delete MessageEvent.createFastMessageEvent + +/** + * @see https://websockets.spec.whatwg.org/#the-closeevent-interface + */ +class CloseEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + const prefix = 'CloseEvent constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + type = webidl.converters.DOMString(type, prefix, 'type') + eventInitDict = webidl.converters.CloseEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + webidl.util.markAsUncloneable(this) + } + + get wasClean () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.wasClean + } + + get code () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.code + } + + get reason () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.reason + } +} + +// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface +class ErrorEvent extends Event { + #eventInit + + constructor (type, eventInitDict) { + const prefix = 'ErrorEvent constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + super(type, eventInitDict) + webidl.util.markAsUncloneable(this) + + type = webidl.converters.DOMString(type, prefix, 'type') + eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) + + this.#eventInit = eventInitDict + } + + get message () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.message + } + + get filename () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.filename + } + + get lineno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.lineno + } + + get colno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.colno + } + + get error () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.error + } +} + +Object.defineProperties(MessageEvent.prototype, { + [Symbol.toStringTag]: { + value: 'MessageEvent', + configurable: true + }, + data: kEnumerableProperty, + origin: kEnumerableProperty, + lastEventId: kEnumerableProperty, + source: kEnumerableProperty, + ports: kEnumerableProperty, + initMessageEvent: kEnumerableProperty +}) + +Object.defineProperties(CloseEvent.prototype, { + [Symbol.toStringTag]: { + value: 'CloseEvent', + configurable: true + }, + reason: kEnumerableProperty, + code: kEnumerableProperty, + wasClean: kEnumerableProperty +}) + +Object.defineProperties(ErrorEvent.prototype, { + [Symbol.toStringTag]: { + value: 'ErrorEvent', + configurable: true + }, + message: kEnumerableProperty, + filename: kEnumerableProperty, + lineno: kEnumerableProperty, + colno: kEnumerableProperty, + error: kEnumerableProperty +}) + +webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.MessagePort +) + +const eventInit = [ + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: () => false + } +] + +webidl.converters.MessageEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'data', + converter: webidl.converters.any, + defaultValue: () => null + }, + { + key: 'origin', + converter: webidl.converters.USVString, + defaultValue: () => '' + }, + { + key: 'lastEventId', + converter: webidl.converters.DOMString, + defaultValue: () => '' + }, + { + key: 'source', + // Node doesn't implement WindowProxy or ServiceWorker, so the only + // valid value for source is a MessagePort. + converter: webidl.nullableConverter(webidl.converters.MessagePort), + defaultValue: () => null + }, + { + key: 'ports', + converter: webidl.converters['sequence'], + defaultValue: () => new Array(0) + } +]) + +webidl.converters.CloseEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'wasClean', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'code', + converter: webidl.converters['unsigned short'], + defaultValue: () => 0 + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: () => '' + } +]) + +webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'message', + converter: webidl.converters.DOMString, + defaultValue: () => '' + }, + { + key: 'filename', + converter: webidl.converters.USVString, + defaultValue: () => '' + }, + { + key: 'lineno', + converter: webidl.converters['unsigned long'], + defaultValue: () => 0 + }, + { + key: 'colno', + converter: webidl.converters['unsigned long'], + defaultValue: () => 0 + }, + { + key: 'error', + converter: webidl.converters.any + } +]) + +module.exports = { + MessageEvent, + CloseEvent, + ErrorEvent, + createFastMessageEvent +} diff --git a/node_modules/undici/lib/web/websocket/frame.js b/node_modules/undici/lib/web/websocket/frame.js new file mode 100644 index 0000000000000..b062ffde8ecb0 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/frame.js @@ -0,0 +1,96 @@ +'use strict' + +const { maxUnsigned16Bit } = require('./constants') + +const BUFFER_SIZE = 16386 + +/** @type {import('crypto')} */ +let crypto +let buffer = null +let bufIdx = BUFFER_SIZE + +try { + crypto = require('node:crypto') +/* c8 ignore next 3 */ +} catch { + crypto = { + // not full compatibility, but minimum. + randomFillSync: function randomFillSync (buffer, _offset, _size) { + for (let i = 0; i < buffer.length; ++i) { + buffer[i] = Math.random() * 255 | 0 + } + return buffer + } + } +} + +function generateMask () { + if (bufIdx === BUFFER_SIZE) { + bufIdx = 0 + crypto.randomFillSync((buffer ??= Buffer.allocUnsafe(BUFFER_SIZE)), 0, BUFFER_SIZE) + } + return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]] +} + +class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data + } + + createFrame (opcode) { + const frameData = this.frameData + const maskKey = generateMask() + const bodyLength = frameData?.byteLength ?? 0 + + /** @type {number} */ + let payloadLength = bodyLength // 0-125 + let offset = 6 + + if (bodyLength > maxUnsigned16Bit) { + offset += 8 // payload length is next 8 bytes + payloadLength = 127 + } else if (bodyLength > 125) { + offset += 2 // payload length is next 2 bytes + payloadLength = 126 + } + + const buffer = Buffer.allocUnsafe(bodyLength + offset) + + // Clear first 2 bytes, everything else is overwritten + buffer[0] = buffer[1] = 0 + buffer[0] |= 0x80 // FIN + buffer[0] = (buffer[0] & 0xF0) + opcode // opcode + + /*! ws. MIT License. Einar Otto Stangvik */ + buffer[offset - 4] = maskKey[0] + buffer[offset - 3] = maskKey[1] + buffer[offset - 2] = maskKey[2] + buffer[offset - 1] = maskKey[3] + + buffer[1] = payloadLength + + if (payloadLength === 126) { + buffer.writeUInt16BE(bodyLength, 2) + } else if (payloadLength === 127) { + // Clear extended payload length + buffer[2] = buffer[3] = 0 + buffer.writeUIntBE(bodyLength, 4, 6) + } + + buffer[1] |= 0x80 // MASK + + // mask body + for (let i = 0; i < bodyLength; ++i) { + buffer[offset + i] = frameData[i] ^ maskKey[i & 3] + } + + return buffer + } +} + +module.exports = { + WebsocketFrameSend +} diff --git a/node_modules/undici/lib/web/websocket/permessage-deflate.js b/node_modules/undici/lib/web/websocket/permessage-deflate.js new file mode 100644 index 0000000000000..6a6e43899c5a9 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/permessage-deflate.js @@ -0,0 +1,100 @@ +'use strict' + +const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = require('node:zlib') +const { isValidClientWindowBits } = require('./util') +const { MessageSizeExceededError } = require('../../core/errors') + +const tail = Buffer.from([0x00, 0x00, 0xff, 0xff]) +const kBuffer = Symbol('kBuffer') +const kLength = Symbol('kLength') + +class PerMessageDeflate { + /** @type {import('node:zlib').InflateRaw} */ + #inflate + + #options = {} + + #maxPayloadSize = 0 + + /** + * @param {Map} extensions + */ + constructor (extensions, options) { + this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover') + this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits') + + this.#maxPayloadSize = options.maxPayloadSize + } + + /** + * Decompress a compressed payload. + * @param {Buffer} chunk Compressed data + * @param {boolean} fin Final fragment flag + * @param {Function} callback Callback function + */ + decompress (chunk, fin, callback) { + // An endpoint uses the following algorithm to decompress a message. + // 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the + // payload of the message. + // 2. Decompress the resulting data using DEFLATE. + if (!this.#inflate) { + let windowBits = Z_DEFAULT_WINDOWBITS + + if (this.#options.serverMaxWindowBits) { // empty values default to Z_DEFAULT_WINDOWBITS + if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) { + callback(new Error('Invalid server_max_window_bits')) + return + } + + windowBits = Number.parseInt(this.#options.serverMaxWindowBits) + } + + try { + this.#inflate = createInflateRaw({ windowBits }) + } catch (err) { + callback(err) + return + } + this.#inflate[kBuffer] = [] + this.#inflate[kLength] = 0 + + this.#inflate.on('data', (data) => { + this.#inflate[kLength] += data.length + + if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { + callback(new MessageSizeExceededError()) + this.#inflate.removeAllListeners() + this.#inflate = null + return + } + + this.#inflate[kBuffer].push(data) + }) + + this.#inflate.on('error', (err) => { + this.#inflate = null + callback(err) + }) + } + + this.#inflate.write(chunk) + if (fin) { + this.#inflate.write(tail) + } + + this.#inflate.flush(() => { + if (!this.#inflate) { + return + } + + const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]) + + this.#inflate[kBuffer].length = 0 + this.#inflate[kLength] = 0 + + callback(null, full) + }) + } +} + +module.exports = { PerMessageDeflate } diff --git a/node_modules/undici/lib/web/websocket/receiver.js b/node_modules/undici/lib/web/websocket/receiver.js new file mode 100644 index 0000000000000..53e427eb2e464 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/receiver.js @@ -0,0 +1,490 @@ +'use strict' + +const { Writable } = require('node:stream') +const assert = require('node:assert') +const { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require('./constants') +const { kReadyState, kSentClose, kResponse, kReceivedClose } = require('./symbols') +const { channels } = require('../../core/diagnostics') +const { + isValidStatusCode, + isValidOpcode, + failWebsocketConnection, + websocketMessageReceived, + utf8Decode, + isControlFrame, + isTextBinaryFrame, + isContinuationFrame +} = require('./util') +const { WebsocketFrameSend } = require('./frame') +const { closeWebSocketConnection } = require('./connection') +const { PerMessageDeflate } = require('./permessage-deflate') +const { MessageSizeExceededError } = require('../../core/errors') + +// This code was influenced by ws released under the MIT license. +// Copyright (c) 2011 Einar Otto Stangvik +// Copyright (c) 2013 Arnout Kazemier and contributors +// Copyright (c) 2016 Luigi Pinca and contributors + +class ByteParser extends Writable { + #buffers = [] + #fragmentsBytes = 0 + #byteOffset = 0 + #loop = false + + #state = parserStates.INFO + + #info = {} + #fragments = [] + + /** @type {Map} */ + #extensions + + /** @type {number} */ + #maxPayloadSize + + /** + * @param {import('./websocket').WebSocket} ws + * @param {Map|null} extensions + * @param {{ maxPayloadSize?: number }} [options] + */ + constructor (ws, extensions, options = {}) { + super() + + this.ws = ws + this.#extensions = extensions == null ? new Map() : extensions + this.#maxPayloadSize = options.maxPayloadSize ?? 0 + + if (this.#extensions.has('permessage-deflate')) { + this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions, options)) + } + } + + /** + * @param {Buffer} chunk + * @param {() => void} callback + */ + _write (chunk, _, callback) { + this.#buffers.push(chunk) + this.#byteOffset += chunk.length + this.#loop = true + + this.run(callback) + } + + #validatePayloadLength () { + if ( + this.#maxPayloadSize > 0 && + !isControlFrame(this.#info.opcode) && + this.#info.payloadLength > this.#maxPayloadSize + ) { + failWebsocketConnection(this.ws, 'Payload size exceeds maximum allowed size') + return false + } + + return true + } + + /** + * Runs whenever a new chunk is received. + * Callback is called whenever there are no more chunks buffering, + * or not enough bytes are buffered to parse. + */ + run (callback) { + while (this.#loop) { + if (this.#state === parserStates.INFO) { + // If there aren't enough bytes to parse the payload length, etc. + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + const fin = (buffer[0] & 0x80) !== 0 + const opcode = buffer[0] & 0x0F + const masked = (buffer[1] & 0x80) === 0x80 + + const fragmented = !fin && opcode !== opcodes.CONTINUATION + const payloadLength = buffer[1] & 0x7F + + const rsv1 = buffer[0] & 0x40 + const rsv2 = buffer[0] & 0x20 + const rsv3 = buffer[0] & 0x10 + + if (!isValidOpcode(opcode)) { + failWebsocketConnection(this.ws, 'Invalid opcode received') + return callback() + } + + if (masked) { + failWebsocketConnection(this.ws, 'Frame cannot be masked') + return callback() + } + + // MUST be 0 unless an extension is negotiated that defines meanings + // for non-zero values. If a nonzero value is received and none of + // the negotiated extensions defines the meaning of such a nonzero + // value, the receiving endpoint MUST _Fail the WebSocket + // Connection_. + // This document allocates the RSV1 bit of the WebSocket header for + // PMCEs and calls the bit the "Per-Message Compressed" bit. On a + // WebSocket connection where a PMCE is in use, this bit indicates + // whether a message is compressed or not. + if (rsv1 !== 0 && !this.#extensions.has('permessage-deflate')) { + failWebsocketConnection(this.ws, 'Expected RSV1 to be clear.') + return + } + + if (rsv2 !== 0 || rsv3 !== 0) { + failWebsocketConnection(this.ws, 'RSV1, RSV2, RSV3 must be clear') + return + } + + if (fragmented && !isTextBinaryFrame(opcode)) { + // Only text and binary frames can be fragmented + failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') + return + } + + // If we are already parsing a text/binary frame and do not receive either + // a continuation frame or close frame, fail the connection. + if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) { + failWebsocketConnection(this.ws, 'Expected continuation frame') + return + } + + if (this.#info.fragmented && fragmented) { + // A fragmented frame can't be fragmented itself + failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') + return + } + + // "All control frames MUST have a payload length of 125 bytes or less + // and MUST NOT be fragmented." + if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) { + failWebsocketConnection(this.ws, 'Control frame either too large or fragmented') + return + } + + if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) { + failWebsocketConnection(this.ws, 'Unexpected continuation frame') + return + } + + if (payloadLength <= 125) { + this.#info.payloadLength = payloadLength + this.#state = parserStates.READ_DATA + + if (!this.#validatePayloadLength()) { + return + } + } else if (payloadLength === 126) { + this.#state = parserStates.PAYLOADLENGTH_16 + } else if (payloadLength === 127) { + this.#state = parserStates.PAYLOADLENGTH_64 + } + + if (isTextBinaryFrame(opcode)) { + this.#info.binaryType = opcode + this.#info.compressed = rsv1 !== 0 + } + + this.#info.opcode = opcode + this.#info.masked = masked + this.#info.fin = fin + this.#info.fragmented = fragmented + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + + this.#info.payloadLength = buffer.readUInt16BE(0) + this.#state = parserStates.READ_DATA + + if (!this.#validatePayloadLength()) { + return + } + } else if (this.#state === parserStates.PAYLOADLENGTH_64) { + if (this.#byteOffset < 8) { + return callback() + } + + const buffer = this.consume(8) + const upper = buffer.readUInt32BE(0) + const lower = buffer.readUInt32BE(4) + + // 2^31 is the maximum bytes an arraybuffer can contain + // on 32-bit systems. Although, on 64-bit systems, this is + // 2^53-1 bytes. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e + if (upper !== 0 || lower > 2 ** 31 - 1) { + failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') + return + } + + this.#info.payloadLength = lower + this.#state = parserStates.READ_DATA + + if (!this.#validatePayloadLength()) { + return + } + } else if (this.#state === parserStates.READ_DATA) { + if (this.#byteOffset < this.#info.payloadLength) { + return callback() + } + + const body = this.consume(this.#info.payloadLength) + + if (isControlFrame(this.#info.opcode)) { + this.#loop = this.parseControlFrame(body) + this.#state = parserStates.INFO + } else { + if (!this.#info.compressed) { + this.writeFragments(body) + + if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { + failWebsocketConnection(this.ws, new MessageSizeExceededError().message) + return + } + + // If the frame is not fragmented, a message has been received. + // If the frame is fragmented, it will terminate with a fin bit set + // and an opcode of 0 (continuation), therefore we handle that when + // parsing continuation frames, not here. + if (!this.#info.fragmented && this.#info.fin) { + websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()) + } + + this.#state = parserStates.INFO + } else { + this.#extensions.get('permessage-deflate').decompress( + body, + this.#info.fin, + (error, data) => { + if (error) { + failWebsocketConnection(this.ws, error.message) + return + } + + this.writeFragments(data) + + if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { + failWebsocketConnection(this.ws, new MessageSizeExceededError().message) + return + } + + if (!this.#info.fin) { + this.#state = parserStates.INFO + this.#loop = true + this.run(callback) + return + } + + websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()) + + this.#loop = true + this.#state = parserStates.INFO + this.run(callback) + } + ) + + this.#loop = false + break + } + } + } + } + } + + /** + * Take n bytes from the buffered Buffers + * @param {number} n + * @returns {Buffer} + */ + consume (n) { + if (n > this.#byteOffset) { + throw new Error('Called consume() before buffers satiated.') + } else if (n === 0) { + return emptyBuffer + } + + if (this.#buffers[0].length === n) { + this.#byteOffset -= this.#buffers[0].length + return this.#buffers.shift() + } + + const buffer = Buffer.allocUnsafe(n) + let offset = 0 + + while (offset !== n) { + const next = this.#buffers[0] + const { length } = next + + if (length + offset === n) { + buffer.set(this.#buffers.shift(), offset) + break + } else if (length + offset > n) { + buffer.set(next.subarray(0, n - offset), offset) + this.#buffers[0] = next.subarray(n - offset) + break + } else { + buffer.set(this.#buffers.shift(), offset) + offset += next.length + } + } + + this.#byteOffset -= n + + return buffer + } + + writeFragments (fragment) { + this.#fragmentsBytes += fragment.length + this.#fragments.push(fragment) + } + + consumeFragments () { + const fragments = this.#fragments + + if (fragments.length === 1) { + this.#fragmentsBytes = 0 + return fragments.shift() + } + + const output = Buffer.concat(fragments, this.#fragmentsBytes) + this.#fragments = [] + this.#fragmentsBytes = 0 + + return output + } + + parseCloseBody (data) { + assert(data.length !== 1) + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code + + if (data.length >= 2) { + // _The WebSocket Connection Close Code_ is + // defined as the status code (Section 7.4) contained in the first Close + // control frame received by the application + code = data.readUInt16BE(0) + } + + if (code !== undefined && !isValidStatusCode(code)) { + return { code: 1002, reason: 'Invalid status code', error: true } + } + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2) + + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3) + } + + try { + reason = utf8Decode(reason) + } catch { + return { code: 1007, reason: 'Invalid UTF-8', error: true } + } + + return { code, reason, error: false } + } + + /** + * Parses control frames. + * @param {Buffer} body + */ + parseControlFrame (body) { + const { opcode, payloadLength } = this.#info + + if (opcode === opcodes.CLOSE) { + if (payloadLength === 1) { + failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') + return false + } + + this.#info.closeInfo = this.parseCloseBody(body) + + if (this.#info.closeInfo.error) { + const { code, reason } = this.#info.closeInfo + + closeWebSocketConnection(this.ws, code, reason, reason.length) + failWebsocketConnection(this.ws, reason) + return false + } + + if (this.ws[kSentClose] !== sentCloseFrameState.SENT) { + // If an endpoint receives a Close frame and did not previously send a + // Close frame, the endpoint MUST send a Close frame in response. (When + // sending a Close frame in response, the endpoint typically echos the + // status code it received.) + let body = emptyBuffer + if (this.#info.closeInfo.code) { + body = Buffer.allocUnsafe(2) + body.writeUInt16BE(this.#info.closeInfo.code, 0) + } + const closeFrame = new WebsocketFrameSend(body) + + this.ws[kResponse].socket.write( + closeFrame.createFrame(opcodes.CLOSE), + (err) => { + if (!err) { + this.ws[kSentClose] = sentCloseFrameState.SENT + } + } + ) + } + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this.ws[kReadyState] = states.CLOSING + this.ws[kReceivedClose] = true + + return false + } else if (opcode === opcodes.PING) { + // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in + // response, unless it already received a Close frame. + // A Pong frame sent in response to a Ping frame must have identical + // "Application data" + + if (!this.ws[kReceivedClose]) { + const frame = new WebsocketFrameSend(body) + + this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) + + if (channels.ping.hasSubscribers) { + channels.ping.publish({ + payload: body + }) + } + } + } else if (opcode === opcodes.PONG) { + // A Pong frame MAY be sent unsolicited. This serves as a + // unidirectional heartbeat. A response to an unsolicited Pong frame is + // not expected. + + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body + }) + } + } + + return true + } + + get closingInfo () { + return this.#info.closeInfo + } +} + +module.exports = { + ByteParser +} diff --git a/node_modules/undici/lib/web/websocket/sender.js b/node_modules/undici/lib/web/websocket/sender.js new file mode 100644 index 0000000000000..1b1468d4ab900 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/sender.js @@ -0,0 +1,104 @@ +'use strict' + +const { WebsocketFrameSend } = require('./frame') +const { opcodes, sendHints } = require('./constants') +const FixedQueue = require('../../dispatcher/fixed-queue') + +/** @type {typeof Uint8Array} */ +const FastBuffer = Buffer[Symbol.species] + +/** + * @typedef {object} SendQueueNode + * @property {Promise | null} promise + * @property {((...args: any[]) => any)} callback + * @property {Buffer | null} frame + */ + +class SendQueue { + /** + * @type {FixedQueue} + */ + #queue = new FixedQueue() + + /** + * @type {boolean} + */ + #running = false + + /** @type {import('node:net').Socket} */ + #socket + + constructor (socket) { + this.#socket = socket + } + + add (item, cb, hint) { + if (hint !== sendHints.blob) { + const frame = createFrame(item, hint) + if (!this.#running) { + // fast-path + this.#socket.write(frame, cb) + } else { + /** @type {SendQueueNode} */ + const node = { + promise: null, + callback: cb, + frame + } + this.#queue.push(node) + } + return + } + + /** @type {SendQueueNode} */ + const node = { + promise: item.arrayBuffer().then((ab) => { + node.promise = null + node.frame = createFrame(ab, hint) + }), + callback: cb, + frame: null + } + + this.#queue.push(node) + + if (!this.#running) { + this.#run() + } + } + + async #run () { + this.#running = true + const queue = this.#queue + while (!queue.isEmpty()) { + const node = queue.shift() + // wait pending promise + if (node.promise !== null) { + await node.promise + } + // write + this.#socket.write(node.frame, node.callback) + // cleanup + node.callback = node.frame = null + } + this.#running = false + } +} + +function createFrame (data, hint) { + return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.string ? opcodes.TEXT : opcodes.BINARY) +} + +function toBuffer (data, hint) { + switch (hint) { + case sendHints.string: + return Buffer.from(data) + case sendHints.arrayBuffer: + case sendHints.blob: + return new FastBuffer(data) + case sendHints.typedArray: + return new FastBuffer(data.buffer, data.byteOffset, data.byteLength) + } +} + +module.exports = { SendQueue } diff --git a/node_modules/undici/lib/web/websocket/symbols.js b/node_modules/undici/lib/web/websocket/symbols.js new file mode 100644 index 0000000000000..11d03e38a8660 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/symbols.js @@ -0,0 +1,12 @@ +'use strict' + +module.exports = { + kWebSocketURL: Symbol('url'), + kReadyState: Symbol('ready state'), + kController: Symbol('controller'), + kResponse: Symbol('response'), + kBinaryType: Symbol('binary type'), + kSentClose: Symbol('sent close'), + kReceivedClose: Symbol('received close'), + kByteParser: Symbol('byte parser') +} diff --git a/node_modules/undici/lib/web/websocket/util.js b/node_modules/undici/lib/web/websocket/util.js new file mode 100644 index 0000000000000..2a04887f26329 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/util.js @@ -0,0 +1,322 @@ +'use strict' + +const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require('./symbols') +const { states, opcodes } = require('./constants') +const { ErrorEvent, createFastMessageEvent } = require('./events') +const { isUtf8 } = require('node:buffer') +const { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = require('../fetch/data-url') + +/* globals Blob */ + +/** + * @param {import('./websocket').WebSocket} ws + * @returns {boolean} + */ +function isConnecting (ws) { + // If the WebSocket connection is not yet established, and the connection + // is not yet closed, then the WebSocket connection is in the CONNECTING state. + return ws[kReadyState] === states.CONNECTING +} + +/** + * @param {import('./websocket').WebSocket} ws + * @returns {boolean} + */ +function isEstablished (ws) { + // If the server's response is validated as provided for above, it is + // said that _The WebSocket Connection is Established_ and that the + // WebSocket Connection is in the OPEN state. + return ws[kReadyState] === states.OPEN +} + +/** + * @param {import('./websocket').WebSocket} ws + * @returns {boolean} + */ +function isClosing (ws) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + return ws[kReadyState] === states.CLOSING +} + +/** + * @param {import('./websocket').WebSocket} ws + * @returns {boolean} + */ +function isClosed (ws) { + return ws[kReadyState] === states.CLOSED +} + +/** + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e + * @param {EventTarget} target + * @param {(...args: ConstructorParameters) => Event} eventFactory + * @param {EventInit | undefined} eventInitDict + */ +function fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) { + // 1. If eventConstructor is not given, then let eventConstructor be Event. + + // 2. Let event be the result of creating an event given eventConstructor, + // in the relevant realm of target. + // 3. Initialize event’s type attribute to e. + const event = eventFactory(e, eventInitDict) + + // 4. Initialize any other IDL attributes of event as described in the + // invocation of this algorithm. + + // 5. Return the result of dispatching event at target, with legacy target + // override flag set if set. + target.dispatchEvent(event) +} + +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @param {import('./websocket').WebSocket} ws + * @param {number} type Opcode + * @param {Buffer} data application data + */ +function websocketMessageReceived (ws, type, data) { + // 1. If ready state is not OPEN (1), then return. + if (ws[kReadyState] !== states.OPEN) { + return + } + + // 2. Let dataForEvent be determined by switching on type and binary type: + let dataForEvent + + if (type === opcodes.TEXT) { + // -> type indicates that the data is Text + // a new DOMString containing data + try { + dataForEvent = utf8Decode(data) + } catch { + failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') + return + } + } else if (type === opcodes.BINARY) { + if (ws[kBinaryType] === 'blob') { + // -> type indicates that the data is Binary and binary type is "blob" + // a new Blob object, created in the relevant Realm of the WebSocket + // object, that represents data as its raw data + dataForEvent = new Blob([data]) + } else { + // -> type indicates that the data is Binary and binary type is "arraybuffer" + // a new ArrayBuffer object, created in the relevant Realm of the + // WebSocket object, whose contents are data + dataForEvent = toArrayBuffer(data) + } + } + + // 3. Fire an event named message at the WebSocket object, using MessageEvent, + // with the origin attribute initialized to the serialization of the WebSocket + // object’s url's origin, and the data attribute initialized to dataForEvent. + fireEvent('message', ws, createFastMessageEvent, { + origin: ws[kWebSocketURL].origin, + data: dataForEvent + }) +} + +function toArrayBuffer (buffer) { + if (buffer.byteLength === buffer.buffer.byteLength) { + return buffer.buffer + } + return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength) +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455 + * @see https://datatracker.ietf.org/doc/html/rfc2616 + * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 + * @param {string} protocol + */ +function isValidSubprotocol (protocol) { + // If present, this value indicates one + // or more comma-separated subprotocol the client wishes to speak, + // ordered by preference. The elements that comprise this value + // MUST be non-empty strings with characters in the range U+0021 to + // U+007E not including separator characters as defined in + // [RFC2616] and MUST all be unique strings. + if (protocol.length === 0) { + return false + } + + for (let i = 0; i < protocol.length; ++i) { + const code = protocol.charCodeAt(i) + + if ( + code < 0x21 || // CTL, contains SP (0x20) and HT (0x09) + code > 0x7E || + code === 0x22 || // " + code === 0x28 || // ( + code === 0x29 || // ) + code === 0x2C || // , + code === 0x2F || // / + code === 0x3A || // : + code === 0x3B || // ; + code === 0x3C || // < + code === 0x3D || // = + code === 0x3E || // > + code === 0x3F || // ? + code === 0x40 || // @ + code === 0x5B || // [ + code === 0x5C || // \ + code === 0x5D || // ] + code === 0x7B || // { + code === 0x7D // } + ) { + return false + } + } + + return true +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 + * @param {number} code + */ +function isValidStatusCode (code) { + if (code >= 1000 && code < 1015) { + return ( + code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006 // "MUST NOT be set as a status code" + ) + } + + return code >= 3000 && code <= 4999 +} + +/** + * @param {import('./websocket').WebSocket} ws + * @param {string|undefined} reason + */ +function failWebsocketConnection (ws, reason) { + const { [kController]: controller, [kResponse]: response } = ws + + controller.abort() + + if (response?.socket && !response.socket.destroyed) { + response.socket.destroy() + } + + if (reason) { + // TODO: process.nextTick + fireEvent('error', ws, (type, init) => new ErrorEvent(type, init), { + error: new Error(reason), + message: reason + }) + } +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5 + * @param {number} opcode + */ +function isControlFrame (opcode) { + return ( + opcode === opcodes.CLOSE || + opcode === opcodes.PING || + opcode === opcodes.PONG + ) +} + +function isContinuationFrame (opcode) { + return opcode === opcodes.CONTINUATION +} + +function isTextBinaryFrame (opcode) { + return opcode === opcodes.TEXT || opcode === opcodes.BINARY +} + +function isValidOpcode (opcode) { + return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode) +} + +/** + * Parses a Sec-WebSocket-Extensions header value. + * @param {string} extensions + * @returns {Map} + */ +// TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 +function parseExtensions (extensions) { + const position = { position: 0 } + const extensionList = new Map() + + while (position.position < extensions.length) { + const pair = collectASequenceOfCodePointsFast(';', extensions, position) + const [name, value = ''] = pair.split('=') + + extensionList.set( + removeHTTPWhitespace(name, true, false), + removeHTTPWhitespace(value, false, true) + ) + + position.position++ + } + + return extensionList +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2 + * @description "client-max-window-bits = 1*DIGIT" + * @param {string} value + */ +function isValidClientWindowBits (value) { + // Must have at least one character + if (value.length === 0) { + return false + } + + // Check all characters are ASCII digits + for (let i = 0; i < value.length; i++) { + const byte = value.charCodeAt(i) + + if (byte < 0x30 || byte > 0x39) { + return false + } + } + + // Check numeric range: zlib requires windowBits in range 8-15 + const num = Number.parseInt(value, 10) + return num >= 8 && num <= 15 +} + +// https://nodejs.org/api/intl.html#detecting-internationalization-support +const hasIntl = typeof process.versions.icu === 'string' +const fatalDecoder = hasIntl ? new TextDecoder('utf-8', { fatal: true }) : undefined + +/** + * Converts a Buffer to utf-8, even on platforms without icu. + * @param {Buffer} buffer + */ +const utf8Decode = hasIntl + ? fatalDecoder.decode.bind(fatalDecoder) + : function (buffer) { + if (isUtf8(buffer)) { + return buffer.toString('utf-8') + } + throw new TypeError('Invalid utf-8 received.') + } + +module.exports = { + isConnecting, + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + failWebsocketConnection, + websocketMessageReceived, + utf8Decode, + isControlFrame, + isContinuationFrame, + isTextBinaryFrame, + isValidOpcode, + parseExtensions, + isValidClientWindowBits +} diff --git a/node_modules/undici/lib/web/websocket/websocket.js b/node_modules/undici/lib/web/websocket/websocket.js new file mode 100644 index 0000000000000..ccedb792169a1 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/websocket.js @@ -0,0 +1,592 @@ +'use strict' + +const { webidl } = require('../fetch/webidl') +const { URLSerializer } = require('../fetch/data-url') +const { environmentSettingsObject } = require('../fetch/util') +const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints } = require('./constants') +const { + kWebSocketURL, + kReadyState, + kController, + kBinaryType, + kResponse, + kSentClose, + kByteParser +} = require('./symbols') +const { + isConnecting, + isEstablished, + isClosing, + isValidSubprotocol, + fireEvent +} = require('./util') +const { establishWebSocketConnection, closeWebSocketConnection } = require('./connection') +const { ByteParser } = require('./receiver') +const { kEnumerableProperty, isBlobLike } = require('../../core/util') +const { getGlobalDispatcher } = require('../../global') +const { types } = require('node:util') +const { ErrorEvent, CloseEvent } = require('./events') +const { SendQueue } = require('./sender') + +// https://websockets.spec.whatwg.org/#interface-definition +class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } + + #bufferedAmount = 0 + #protocol = '' + #extensions = '' + + /** @type {SendQueue} */ + #sendQueue + + /** + * @param {string} url + * @param {string|string[]} protocols + */ + constructor (url, protocols = []) { + super() + + webidl.util.markAsUncloneable(this) + + const prefix = 'WebSocket constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols, prefix, 'options') + + url = webidl.converters.USVString(url, prefix, 'url') + protocols = options.protocols + + // 1. Let baseURL be this's relevant settings object's API base URL. + const baseURL = environmentSettingsObject.settingsObject.baseUrl + + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. + let urlRecord + + try { + urlRecord = new URL(url, baseURL) + } catch (e) { + // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". + if (urlRecord.protocol === 'http:') { + urlRecord.protocol = 'ws:' + } else if (urlRecord.protocol === 'https:') { + // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". + urlRecord.protocol = 'wss:' + } + + // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. + if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { + throw new DOMException( + `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, + 'SyntaxError' + ) + } + + // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" + // DOMException. + if (urlRecord.hash || urlRecord.href.endsWith('#')) { + throw new DOMException('Got fragment', 'SyntaxError') + } + + // 8. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols] + } + + // 9. If any of the values in protocols occur more than once or otherwise + // fail to match the requirements for elements that comprise the value + // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket + // protocol, then throw a "SyntaxError" DOMException. + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 10. Set this's url to urlRecord. + this[kWebSocketURL] = new URL(urlRecord.href) + + // 11. Let client be this's relevant settings object. + const client = environmentSettingsObject.settingsObject + + // 12. Run this step in parallel: + + // 1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + client, + this, + (response, extensions) => this.#onConnectionEstablished(response, extensions), + options + ) + + // Each WebSocket object has an associated ready state, which is a + // number representing the state of the connection. Initially it must + // be CONNECTING (0). + this[kReadyState] = WebSocket.CONNECTING + + this[kSentClose] = sentCloseFrameState.NOT_SENT + + // The extensions attribute must initially return the empty string. + + // The protocol attribute must initially return the empty string. + + // Each WebSocket object has an associated binary type, which is a + // BinaryType. Initially it must be "blob". + this[kBinaryType] = 'blob' + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ + close (code = undefined, reason = undefined) { + webidl.brandCheck(this, WebSocket) + + const prefix = 'WebSocket.close' + + if (code !== undefined) { + code = webidl.converters['unsigned short'](code, prefix, 'code', { clamp: true }) + } + + if (reason !== undefined) { + reason = webidl.converters.USVString(reason, prefix, 'reason') + } + + // 1. If code is present, but is neither an integer equal to 1000 nor an + // integer in the range 3000 to 4999, inclusive, throw an + // "InvalidAccessError" DOMException. + if (code !== undefined) { + if (code !== 1000 && (code < 3000 || code > 4999)) { + throw new DOMException('invalid code', 'InvalidAccessError') + } + } + + let reasonByteLength = 0 + + // 2. If reason is present, then run these substeps: + if (reason !== undefined) { + // 1. Let reasonBytes be the result of encoding reason. + // 2. If reasonBytes is longer than 123 bytes, then throw a + // "SyntaxError" DOMException. + reasonByteLength = Buffer.byteLength(reason) + + if (reasonByteLength > 123) { + throw new DOMException( + `Reason must be less than 123 bytes; received ${reasonByteLength}`, + 'SyntaxError' + ) + } + } + + // 3. Run the first matching steps from the following list: + closeWebSocketConnection(this, code, reason, reasonByteLength) + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-send + * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + */ + send (data) { + webidl.brandCheck(this, WebSocket) + + const prefix = 'WebSocket.send' + webidl.argumentLengthCheck(arguments, 1, prefix) + + data = webidl.converters.WebSocketSendData(data, prefix, 'data') + + // 1. If this's ready state is CONNECTING, then throw an + // "InvalidStateError" DOMException. + if (isConnecting(this)) { + throw new DOMException('Sent before connected.', 'InvalidStateError') + } + + // 2. Run the appropriate set of steps from the following list: + // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 + // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + + if (!isEstablished(this) || isClosing(this)) { + return + } + + // If data is a string + if (typeof data === 'string') { + // If the WebSocket connection is established and the WebSocket + // closing handshake has not yet started, then the user agent + // must send a WebSocket Message comprised of the data argument + // using a text frame opcode; if the data cannot be sent, e.g. + // because it would need to be buffered but the buffer is full, + // the user agent must flag the WebSocket as full and then close + // the WebSocket connection. Any invocation of this method with a + // string argument that does not throw an exception must increase + // the bufferedAmount attribute by the number of bytes needed to + // express the argument as UTF-8. + + const length = Buffer.byteLength(data) + + this.#bufferedAmount += length + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= length + }, sendHints.string) + } else if (types.isArrayBuffer(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need + // to be buffered but the buffer is full, the user agent must flag + // the WebSocket as full and then close the WebSocket connection. + // The data to be sent is the data stored in the buffer described + // by the ArrayBuffer object. Any invocation of this method with an + // ArrayBuffer argument that does not throw an exception must + // increase the bufferedAmount attribute by the length of the + // ArrayBuffer in bytes. + + this.#bufferedAmount += data.byteLength + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.byteLength + }, sendHints.arrayBuffer) + } else if (ArrayBuffer.isView(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The + // data to be sent is the data stored in the section of the buffer + // described by the ArrayBuffer object that data references. Any + // invocation of this method with this kind of argument that does + // not throw an exception must increase the bufferedAmount attribute + // by the length of data’s buffer in bytes. + + this.#bufferedAmount += data.byteLength + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.byteLength + }, sendHints.typedArray) + } else if (isBlobLike(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The data + // to be sent is the raw data represented by the Blob object. Any + // invocation of this method with a Blob argument that does not throw + // an exception must increase the bufferedAmount attribute by the size + // of the Blob object’s raw data, in bytes. + + this.#bufferedAmount += data.size + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.size + }, sendHints.blob) + } + } + + get readyState () { + webidl.brandCheck(this, WebSocket) + + // The readyState getter steps are to return this's ready state. + return this[kReadyState] + } + + get bufferedAmount () { + webidl.brandCheck(this, WebSocket) + + return this.#bufferedAmount + } + + get url () { + webidl.brandCheck(this, WebSocket) + + // The url getter steps are to return this's url, serialized. + return URLSerializer(this[kWebSocketURL]) + } + + get extensions () { + webidl.brandCheck(this, WebSocket) + + return this.#extensions + } + + get protocol () { + webidl.brandCheck(this, WebSocket) + + return this.#protocol + } + + get onopen () { + webidl.brandCheck(this, WebSocket) + + return this.#events.open + } + + set onopen (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) + } + + if (typeof fn === 'function') { + this.#events.open = fn + this.addEventListener('open', fn) + } else { + this.#events.open = null + } + } + + get onerror () { + webidl.brandCheck(this, WebSocket) + + return this.#events.error + } + + set onerror (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) + } + + if (typeof fn === 'function') { + this.#events.error = fn + this.addEventListener('error', fn) + } else { + this.#events.error = null + } + } + + get onclose () { + webidl.brandCheck(this, WebSocket) + + return this.#events.close + } + + set onclose (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.close) { + this.removeEventListener('close', this.#events.close) + } + + if (typeof fn === 'function') { + this.#events.close = fn + this.addEventListener('close', fn) + } else { + this.#events.close = null + } + } + + get onmessage () { + webidl.brandCheck(this, WebSocket) + + return this.#events.message + } + + set onmessage (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } + + if (typeof fn === 'function') { + this.#events.message = fn + this.addEventListener('message', fn) + } else { + this.#events.message = null + } + } + + get binaryType () { + webidl.brandCheck(this, WebSocket) + + return this[kBinaryType] + } + + set binaryType (type) { + webidl.brandCheck(this, WebSocket) + + if (type !== 'blob' && type !== 'arraybuffer') { + this[kBinaryType] = 'blob' + } else { + this[kBinaryType] = type + } + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ + #onConnectionEstablished (response, parsedExtensions) { + // processResponse is called when the "response's header list has been received and initialized." + // once this happens, the connection is open + this[kResponse] = response + + const maxPayloadSize = this[kController]?.dispatcher?.webSocketOptions?.maxPayloadSize + + const parser = new ByteParser(this, parsedExtensions, { + maxPayloadSize + }) + parser.on('drain', onParserDrain) + parser.on('error', onParserError.bind(this)) + + response.socket.ws = this + this[kByteParser] = parser + + this.#sendQueue = new SendQueue(response.socket) + + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN + + // 2. Change the extensions attribute’s value to the extensions in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 + const extensions = response.headersList.get('sec-websocket-extensions') + + if (extensions !== null) { + this.#extensions = extensions + } + + // 3. Change the protocol attribute’s value to the subprotocol in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 + const protocol = response.headersList.get('sec-websocket-protocol') + + if (protocol !== null) { + this.#protocol = protocol + } + + // 4. Fire an event named open at the WebSocket object. + fireEvent('open', this) + } +} + +// https://websockets.spec.whatwg.org/#dom-websocket-connecting +WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING +// https://websockets.spec.whatwg.org/#dom-websocket-open +WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN +// https://websockets.spec.whatwg.org/#dom-websocket-closing +WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING +// https://websockets.spec.whatwg.org/#dom-websocket-closed +WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED + +Object.defineProperties(WebSocket.prototype, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors, + url: kEnumerableProperty, + readyState: kEnumerableProperty, + bufferedAmount: kEnumerableProperty, + onopen: kEnumerableProperty, + onerror: kEnumerableProperty, + onclose: kEnumerableProperty, + close: kEnumerableProperty, + onmessage: kEnumerableProperty, + binaryType: kEnumerableProperty, + send: kEnumerableProperty, + extensions: kEnumerableProperty, + protocol: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocket', + writable: false, + enumerable: false, + configurable: true + } +}) + +Object.defineProperties(WebSocket, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors +}) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.DOMString +) + +webidl.converters['DOMString or sequence'] = function (V, prefix, argument) { + if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { + return webidl.converters['sequence'](V) + } + + return webidl.converters.DOMString(V, prefix, argument) +} + +// This implements the proposal made in https://github.com/whatwg/websockets/issues/42 +webidl.converters.WebSocketInit = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.converters['DOMString or sequence'], + defaultValue: () => new Array(0) + }, + { + key: 'dispatcher', + converter: webidl.converters.any, + defaultValue: () => getGlobalDispatcher() + }, + { + key: 'headers', + converter: webidl.nullableConverter(webidl.converters.HeadersInit) + } +]) + +webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { + if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { + return webidl.converters.WebSocketInit(V) + } + + return { protocols: webidl.converters['DOMString or sequence'](V) } +} + +webidl.converters.WebSocketSendData = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) { + return webidl.converters.BufferSource(V) + } + } + + return webidl.converters.USVString(V) +} + +function onParserDrain () { + this.ws[kResponse].socket.resume() +} + +function onParserError (err) { + let message + let code + + if (err instanceof CloseEvent) { + message = err.reason + code = err.code + } else { + message = err.message + } + + fireEvent('error', this, () => new ErrorEvent('error', { error: err, message })) + + closeWebSocketConnection(this, code) +} + +module.exports = { + WebSocket +} diff --git a/node_modules/undici/package.json b/node_modules/undici/package.json new file mode 100644 index 0000000000000..d1eef502c4169 --- /dev/null +++ b/node_modules/undici/package.json @@ -0,0 +1,160 @@ +{ + "name": "undici", + "version": "6.26.0", + "description": "An HTTP/1.1 client, written from scratch for Node.js", + "homepage": "https://undici.nodejs.org", + "bugs": { + "url": "https://github.com/nodejs/undici/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/undici.git" + }, + "license": "MIT", + "contributors": [ + { + "name": "Daniele Belardi", + "url": "https://github.com/dnlup", + "author": true + }, + { + "name": "Ethan Arrowood", + "url": "https://github.com/ethan-arrowood", + "author": true + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina", + "author": true + }, + { + "name": "Matthew Aitken", + "url": "https://github.com/KhafraDev", + "author": true + }, + { + "name": "Robert Nagy", + "url": "https://github.com/ronag", + "author": true + }, + { + "name": "Szymon Marczak", + "url": "https://github.com/szmarczak", + "author": true + }, + { + "name": "Tomas Della Vedova", + "url": "https://github.com/delvedor", + "author": true + } + ], + "keywords": [ + "fetch", + "http", + "https", + "promise", + "request", + "curl", + "wget", + "xhr", + "whatwg" + ], + "main": "index.js", + "types": "index.d.ts", + "scripts": { + "build:node": "npx esbuild@0.19.10 index-fetch.js --bundle --platform=node --outfile=undici-fetch.js --define:esbuildDetection=1 --keep-names && node scripts/strip-comments.js", + "prebuild:wasm": "node build/wasm.js --prebuild", + "build:wasm": "node build/wasm.js --docker", + "lint": "standard | snazzy", + "lint:fix": "standard --fix | snazzy", + "test": "npm run test:javascript && cross-env NODE_V8_COVERAGE= npm run test:typescript", + "test:javascript": "node scripts/generate-pem && npm run test:unit && npm run test:node-fetch && npm run test:cache && npm run test:interceptors && npm run test:fetch && npm run test:cookies && npm run test:eventsource && npm run test:wpt && npm run test:websocket && npm run test:node-test && npm run test:jest", + "test:javascript:withoutintl": "node scripts/generate-pem && npm run test:unit && npm run test:node-fetch && npm run test:fetch:nobuild && npm run test:cache && npm run test:interceptors && npm run test:cookies && npm run test:eventsource:nobuild && npm run test:wpt:withoutintl && npm run test:node-test", + "test:busboy": "borp -p \"test/busboy/*.js\"", + "test:cache": "borp -p \"test/cache/*.js\"", + "test:cookies": "borp -p \"test/cookie/*.js\"", + "test:eventsource": "npm run build:node && npm run test:eventsource:nobuild", + "test:eventsource:nobuild": "borp --expose-gc -p \"test/eventsource/*.js\"", + "test:fuzzing": "node test/fuzzing/fuzzing.test.js", + "test:fetch": "npm run build:node && npm run test:fetch:nobuild", + "test:fetch:nobuild": "borp --timeout 180000 --expose-gc --concurrency 1 -p \"test/fetch/*.js\" && npm run test:webidl && npm run test:busboy", + "test:h2": "npm run test:h2:core && npm run test:h2:fetch", + "test:h2:core": "borp -p \"test/http2*.js\"", + "test:h2:fetch": "npm run build:node && borp -p \"test/fetch/http2*.js\"", + "test:interceptors": "borp -p \"test/interceptors/*.js\"", + "test:jest": "cross-env NODE_V8_COVERAGE= jest", + "test:unit": "borp --expose-gc -p \"test/*.js\"", + "test:node-fetch": "borp -p \"test/node-fetch/**/*.js\"", + "test:node-test": "borp -p \"test/node-test/**/*.js\"", + "test:tdd": "borp --expose-gc -p \"test/*.js\"", + "test:tdd:node-test": "borp -p \"test/node-test/**/*.js\" -w", + "test:typescript": "tsd && tsc test/imports/undici-import.ts --typeRoots ./types && tsc ./types/*.d.ts --noEmit --typeRoots ./types", + "test:webidl": "borp -p \"test/webidl/*.js\"", + "test:websocket": "borp -p \"test/websocket/*.js\"", + "test:websocket:autobahn": "node test/autobahn/client.js", + "test:websocket:autobahn:report": "node test/autobahn/report.js", + "test:wpt": "node test/wpt/start-fetch.mjs && node test/wpt/start-FileAPI.mjs && node test/wpt/start-mimesniff.mjs && node test/wpt/start-xhr.mjs && node test/wpt/start-websockets.mjs && node test/wpt/start-cacheStorage.mjs && node test/wpt/start-eventsource.mjs", + "test:wpt:withoutintl": "node test/wpt/start-fetch.mjs && node test/wpt/start-mimesniff.mjs && node test/wpt/start-xhr.mjs && node test/wpt/start-cacheStorage.mjs && node test/wpt/start-eventsource.mjs", + "coverage": "npm run coverage:clean && cross-env NODE_V8_COVERAGE=./coverage/tmp npm run test:javascript && npm run coverage:report", + "coverage:ci": "npm run coverage:clean && cross-env NODE_V8_COVERAGE=./coverage/tmp npm run test:javascript && npm run coverage:report:ci", + "coverage:clean": "node ./scripts/clean-coverage.js", + "coverage:report": "cross-env NODE_V8_COVERAGE= c8 report", + "coverage:report:ci": "c8 report", + "bench": "echo \"Error: Benchmarks have been moved to '/benchmarks'\" && exit 1", + "serve:website": "echo \"Error: Documentation has been moved to '/docs'\" && exit 1", + "prepare": "husky && node ./scripts/platform-shell.js" + }, + "devDependencies": { + "@fastify/busboy": "2.1.1", + "@matteo.collina/tspl": "^0.1.1", + "@metcoder95/https-pem": "^1.0.0", + "@sinonjs/fake-timers": "^11.1.0", + "@types/node": "~18.19.50", + "abort-controller": "^3.0.0", + "borp": "^0.15.0", + "c8": "^10.0.0", + "cross-env": "^7.0.3", + "dns-packet": "^5.4.0", + "fast-check": "^3.17.1", + "form-data": "^4.0.0", + "formdata-node": "^6.0.3", + "husky": "^9.0.7", + "jest": "^29.0.2", + "jsdom": "^24.0.0", + "node-forge": "^1.3.1", + "pre-commit": "^1.2.2", + "proxy": "^2.1.1", + "snazzy": "^9.0.0", + "standard": "^17.0.0", + "tsd": "^0.31.0", + "typescript": "^5.0.2", + "ws": "^8.11.0" + }, + "engines": { + "node": ">=18.17" + }, + "standard": { + "env": [ + "jest" + ], + "ignore": [ + "lib/llhttp/constants.js", + "lib/llhttp/utils.js", + "test/fixtures/wpt" + ] + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "esModuleInterop": true, + "lib": [ + "esnext" + ] + } + }, + "jest": { + "testMatch": [ + "/test/jest/**" + ] + } +} diff --git a/node_modules/undici/scripts/strip-comments.js b/node_modules/undici/scripts/strip-comments.js new file mode 100644 index 0000000000000..9e4396a5dea8e --- /dev/null +++ b/node_modules/undici/scripts/strip-comments.js @@ -0,0 +1,8 @@ +'use strict' + +const { readFileSync, writeFileSync } = require('node:fs') +const { transcode } = require('node:buffer') + +const buffer = transcode(readFileSync('./undici-fetch.js'), 'utf8', 'latin1') + +writeFileSync('./undici-fetch.js', buffer.toString('latin1')) diff --git a/node_modules/unique-filename/LICENSE b/node_modules/unique-filename/LICENSE deleted file mode 100644 index 69619c125ea7e..0000000000000 --- a/node_modules/unique-filename/LICENSE +++ /dev/null @@ -1,5 +0,0 @@ -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. diff --git a/node_modules/unique-filename/lib/index.js b/node_modules/unique-filename/lib/index.js deleted file mode 100644 index d067d2e709809..0000000000000 --- a/node_modules/unique-filename/lib/index.js +++ /dev/null @@ -1,7 +0,0 @@ -var path = require('path') - -var uniqueSlug = require('unique-slug') - -module.exports = function (filepath, prefix, uniq) { - return path.join(filepath, (prefix ? prefix + '-' : '') + uniqueSlug(uniq)) -} diff --git a/node_modules/unique-filename/package.json b/node_modules/unique-filename/package.json deleted file mode 100644 index b2fbf0666489a..0000000000000 --- a/node_modules/unique-filename/package.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "unique-filename", - "version": "3.0.0", - "description": "Generate a unique filename for use in temporary directories or caches.", - "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/unique-filename.git" - }, - "keywords": [], - "author": "GitHub Inc.", - "license": "ISC", - "bugs": { - "url": "https://github.com/iarna/unique-filename/issues" - }, - "homepage": "https://github.com/iarna/unique-filename", - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.5.1", - "tap": "^16.3.0" - }, - "dependencies": { - "unique-slug": "^4.0.0" - }, - "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.5.1" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/unique-slug/LICENSE b/node_modules/unique-slug/LICENSE deleted file mode 100644 index 7953647e7760b..0000000000000 --- a/node_modules/unique-slug/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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 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. diff --git a/node_modules/unique-slug/lib/index.js b/node_modules/unique-slug/lib/index.js deleted file mode 100644 index 1bac84d95d730..0000000000000 --- a/node_modules/unique-slug/lib/index.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict' -var MurmurHash3 = require('imurmurhash') - -module.exports = function (uniq) { - if (uniq) { - var hash = new MurmurHash3(uniq) - return ('00000000' + hash.result().toString(16)).slice(-8) - } else { - return (Math.random().toString(16) + '0000000').slice(2, 10) - } -} diff --git a/node_modules/unique-slug/package.json b/node_modules/unique-slug/package.json deleted file mode 100644 index 33732cdbb4285..0000000000000 --- a/node_modules/unique-slug/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "unique-slug", - "version": "4.0.0", - "description": "Generate a unique character string suitible for use in files and URLs.", - "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", - "devDependencies": { - "@npmcli/eslint-config": "^3.1.0", - "@npmcli/template-oss": "4.5.1", - "tap": "^16.3.0" - }, - "repository": { - "type": "git", - "url": "https://github.com/npm/unique-slug.git" - }, - "dependencies": { - "imurmurhash": "^0.1.4" - }, - "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.5.1" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/validate-npm-package-license/LICENSE b/node_modules/validate-npm-package-license/LICENSE deleted file mode 100644 index d645695673349..0000000000000 --- a/node_modules/validate-npm-package-license/LICENSE +++ /dev/null @@ -1,202 +0,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 [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. diff --git a/node_modules/validate-npm-package-license/index.js b/node_modules/validate-npm-package-license/index.js deleted file mode 100644 index 35eaa732559ce..0000000000000 --- a/node_modules/validate-npm-package-license/index.js +++ /dev/null @@ -1,86 +0,0 @@ -var parse = require('spdx-expression-parse'); -var correct = require('spdx-correct'); - -var genericWarning = ( - 'license should be ' + - 'a valid SPDX license expression (without "LicenseRef"), ' + - '"UNLICENSED", or ' + - '"SEE LICENSE IN "' -); - -var fileReferenceRE = /^SEE LICEN[CS]E IN (.+)$/; - -function startsWith(prefix, string) { - return string.slice(0, prefix.length) === prefix; -} - -function usesLicenseRef(ast) { - if (ast.hasOwnProperty('license')) { - var license = ast.license; - return ( - startsWith('LicenseRef', license) || - startsWith('DocumentRef', license) - ); - } else { - return ( - usesLicenseRef(ast.left) || - usesLicenseRef(ast.right) - ); - } -} - -module.exports = function(argument) { - var ast; - - try { - ast = parse(argument); - } catch (e) { - var match - if ( - argument === 'UNLICENSED' || - argument === 'UNLICENCED' - ) { - return { - validForOldPackages: true, - validForNewPackages: true, - unlicensed: true - }; - } else if (match = fileReferenceRE.exec(argument)) { - return { - validForOldPackages: true, - validForNewPackages: true, - inFile: match[1] - }; - } else { - var result = { - validForOldPackages: false, - validForNewPackages: false, - warnings: [genericWarning] - }; - if (argument.trim().length !== 0) { - var corrected = correct(argument); - if (corrected) { - result.warnings.push( - 'license is similar to the valid expression "' + corrected + '"' - ); - } - } - return result; - } - } - - if (usesLicenseRef(ast)) { - return { - validForNewPackages: false, - validForOldPackages: false, - spdx: true, - warnings: [genericWarning] - }; - } else { - return { - validForNewPackages: true, - validForOldPackages: true, - spdx: true - }; - } -}; diff --git a/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/AUTHORS b/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/AUTHORS deleted file mode 100644 index 257a76b9484c1..0000000000000 --- a/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/AUTHORS +++ /dev/null @@ -1,4 +0,0 @@ -C. Scott Ananian (http://cscott.net) -Kyle E. Mitchell (https://kemitchell.com) -Shinnosuke Watanabe -Antoine Motet diff --git a/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/LICENSE b/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/LICENSE deleted file mode 100644 index 831618eaba6c8..0000000000000 --- a/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License - -Copyright (c) 2015 Kyle E. Mitchell & other authors listed in AUTHORS - -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. diff --git a/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/index.js b/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/index.js deleted file mode 100644 index 52fab560aea70..0000000000000 --- a/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/index.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict' - -var scan = require('./scan') -var parse = require('./parse') - -module.exports = function (source) { - return parse(scan(source)) -} diff --git a/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/package.json b/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/package.json deleted file mode 100644 index c9edc9f939cdf..0000000000000 --- a/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "spdx-expression-parse", - "description": "parse SPDX license expressions", - "version": "3.0.1", - "author": "Kyle E. Mitchell (https://kemitchell.com)", - "files": [ - "AUTHORS", - "index.js", - "parse.js", - "scan.js" - ], - "dependencies": { - "spdx-exceptions": "^2.1.0", - "spdx-license-ids": "^3.0.0" - }, - "devDependencies": { - "defence-cli": "^3.0.1", - "replace-require-self": "^1.0.0", - "standard": "^14.1.0" - }, - "keywords": [ - "SPDX", - "law", - "legal", - "license", - "metadata", - "package", - "package.json", - "standards" - ], - "license": "MIT", - "repository": "jslicense/spdx-expression-parse.js", - "scripts": { - "lint": "standard", - "test:readme": "defence -i javascript README.md | replace-require-self | node", - "test:suite": "node test.js", - "test": "npm run test:suite && npm run test:readme" - } -} diff --git a/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/parse.js b/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/parse.js deleted file mode 100644 index 5a00b45c5799c..0000000000000 --- a/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/parse.js +++ /dev/null @@ -1,138 +0,0 @@ -'use strict' - -// The ABNF grammar in the spec is totally ambiguous. -// -// This parser follows the operator precedence defined in the -// `Order of Precedence and Parentheses` section. - -module.exports = function (tokens) { - var index = 0 - - function hasMore () { - return index < tokens.length - } - - function token () { - return hasMore() ? tokens[index] : null - } - - function next () { - if (!hasMore()) { - throw new Error() - } - index++ - } - - function parseOperator (operator) { - var t = token() - if (t && t.type === 'OPERATOR' && operator === t.string) { - next() - return t.string - } - } - - function parseWith () { - if (parseOperator('WITH')) { - var t = token() - if (t && t.type === 'EXCEPTION') { - next() - return t.string - } - throw new Error('Expected exception after `WITH`') - } - } - - function parseLicenseRef () { - // TODO: Actually, everything is concatenated into one string - // for backward-compatibility but it could be better to return - // a nice structure. - var begin = index - var string = '' - var t = token() - if (t.type === 'DOCUMENTREF') { - next() - string += 'DocumentRef-' + t.string + ':' - if (!parseOperator(':')) { - throw new Error('Expected `:` after `DocumentRef-...`') - } - } - t = token() - if (t.type === 'LICENSEREF') { - next() - string += 'LicenseRef-' + t.string - return { license: string } - } - index = begin - } - - function parseLicense () { - var t = token() - if (t && t.type === 'LICENSE') { - next() - var node = { license: t.string } - if (parseOperator('+')) { - node.plus = true - } - var exception = parseWith() - if (exception) { - node.exception = exception - } - return node - } - } - - function parseParenthesizedExpression () { - var left = parseOperator('(') - if (!left) { - return - } - - var expr = parseExpression() - - if (!parseOperator(')')) { - throw new Error('Expected `)`') - } - - return expr - } - - function parseAtom () { - return ( - parseParenthesizedExpression() || - parseLicenseRef() || - parseLicense() - ) - } - - function makeBinaryOpParser (operator, nextParser) { - return function parseBinaryOp () { - var left = nextParser() - if (!left) { - return - } - - if (!parseOperator(operator)) { - return left - } - - var right = parseBinaryOp() - if (!right) { - throw new Error('Expected expression') - } - return { - left: left, - conjunction: operator.toLowerCase(), - right: right - } - } - } - - var parseAnd = makeBinaryOpParser('AND', parseAtom) - var parseExpression = makeBinaryOpParser('OR', parseAnd) - - var node = parseExpression() - if (!node || hasMore()) { - throw new Error('Syntax error') - } - return node -} diff --git a/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/scan.js b/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/scan.js deleted file mode 100644 index b74fce2e2c663..0000000000000 --- a/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/scan.js +++ /dev/null @@ -1,131 +0,0 @@ -'use strict' - -var licenses = [] - .concat(require('spdx-license-ids')) - .concat(require('spdx-license-ids/deprecated')) -var exceptions = require('spdx-exceptions') - -module.exports = function (source) { - var index = 0 - - function hasMore () { - return index < source.length - } - - // `value` can be a regexp or a string. - // If it is recognized, the matching source string is returned and - // the index is incremented. Otherwise `undefined` is returned. - function read (value) { - if (value instanceof RegExp) { - var chars = source.slice(index) - var match = chars.match(value) - if (match) { - index += match[0].length - return match[0] - } - } else { - if (source.indexOf(value, index) === index) { - index += value.length - return value - } - } - } - - function skipWhitespace () { - read(/[ ]*/) - } - - function operator () { - var string - var possibilities = ['WITH', 'AND', 'OR', '(', ')', ':', '+'] - for (var i = 0; i < possibilities.length; i++) { - string = read(possibilities[i]) - if (string) { - break - } - } - - if (string === '+' && index > 1 && source[index - 2] === ' ') { - throw new Error('Space before `+`') - } - - return string && { - type: 'OPERATOR', - string: string - } - } - - function idstring () { - return read(/[A-Za-z0-9-.]+/) - } - - function expectIdstring () { - var string = idstring() - if (!string) { - throw new Error('Expected idstring at offset ' + index) - } - return string - } - - function documentRef () { - if (read('DocumentRef-')) { - var string = expectIdstring() - return { type: 'DOCUMENTREF', string: string } - } - } - - function licenseRef () { - if (read('LicenseRef-')) { - var string = expectIdstring() - return { type: 'LICENSEREF', string: string } - } - } - - function identifier () { - var begin = index - var string = idstring() - - if (licenses.indexOf(string) !== -1) { - return { - type: 'LICENSE', - string: string - } - } else if (exceptions.indexOf(string) !== -1) { - return { - type: 'EXCEPTION', - string: string - } - } - - index = begin - } - - // Tries to read the next token. Returns `undefined` if no token is - // recognized. - function parseToken () { - // Ordering matters - return ( - operator() || - documentRef() || - licenseRef() || - identifier() - ) - } - - var tokens = [] - while (hasMore()) { - skipWhitespace() - if (!hasMore()) { - break - } - - var token = parseToken() - if (!token) { - throw new Error('Unexpected `' + source[index] + - '` at offset ' + index) - } - - tokens.push(token) - } - return tokens -} diff --git a/node_modules/validate-npm-package-license/package.json b/node_modules/validate-npm-package-license/package.json deleted file mode 100644 index 9e92af4f44656..0000000000000 --- a/node_modules/validate-npm-package-license/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "validate-npm-package-license", - "description": "Give me a string and I'll tell you if it's a valid npm package license string", - "version": "3.0.4", - "author": "Kyle E. Mitchell (https://kemitchell.com)", - "contributors": [ - "Mark Stacey " - ], - "dependencies": { - "spdx-correct": "^3.0.0", - "spdx-expression-parse": "^3.0.0" - }, - "devDependencies": { - "defence-cli": "^2.0.1", - "replace-require-self": "^1.0.0" - }, - "keywords": [ - "license", - "npm", - "package", - "validation" - ], - "license": "Apache-2.0", - "repository": "kemitchell/validate-npm-package-license.js", - "scripts": { - "test": "defence README.md | replace-require-self | node" - } -} diff --git a/node_modules/validate-npm-package-name/lib/builtin-modules.json b/node_modules/validate-npm-package-name/lib/builtin-modules.json new file mode 100644 index 0000000000000..252c24f3ec671 --- /dev/null +++ b/node_modules/validate-npm-package-name/lib/builtin-modules.json @@ -0,0 +1 @@ +["_http_agent","_http_client","_http_common","_http_incoming","_http_outgoing","_http_server","_stream_duplex","_stream_passthrough","_stream_readable","_stream_transform","_stream_wrap","_stream_writable","_tls_common","_tls_wrap","assert","assert/strict","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","dns/promises","domain","events","fs","fs/promises","http","http2","https","inspector","inspector/promises","module","net","os","path","path/posix","path/win32","perf_hooks","process","punycode","querystring","readline","readline/promises","repl","stream","stream/consumers","stream/promises","stream/web","string_decoder","sys","timers","timers/promises","tls","trace_events","tty","url","util","util/types","v8","vm","wasi","worker_threads","zlib","node:sea","node:sqlite","node:test","node:test/reporters"] diff --git a/node_modules/validate-npm-package-name/lib/index.js b/node_modules/validate-npm-package-name/lib/index.js index fd800d5a5eae1..93d77b76b3dd2 100644 --- a/node_modules/validate-npm-package-name/lib/index.js +++ b/node_modules/validate-npm-package-name/lib/index.js @@ -1,8 +1,8 @@ 'use strict' -const { builtinModules: builtins } = require('module') +const builtins = require('./builtin-modules.json') var scopedPackagePattern = new RegExp('^(?:@([^/]+?)[/])?([^/]+?)$') -var blacklist = [ +var exclusionList = [ 'node_modules', 'favicon.ico', ] @@ -30,10 +30,14 @@ function validate (name) { errors.push('name length must be greater than zero') } - if (name.match(/^\./)) { + if (name.startsWith('.')) { errors.push('name cannot start with a period') } + if (name.startsWith('-')) { + errors.push('name cannot start with a hyphen') + } + if (name.match(/^_/)) { errors.push('name cannot start with an underscore') } @@ -43,9 +47,9 @@ function validate (name) { } // No funny business - blacklist.forEach(function (blacklistedName) { - if (name.toLowerCase() === blacklistedName) { - errors.push(blacklistedName + ' is a blacklisted name') + exclusionList.forEach(function (excludedName) { + if (name.toLowerCase() === excludedName) { + errors.push(excludedName + ' is not a valid package name') } }) @@ -75,6 +79,11 @@ function validate (name) { if (nameMatch) { var user = nameMatch[1] var pkg = nameMatch[2] + + if (pkg.startsWith('.')) { + errors.push('name cannot start with a period') + } + if (encodeURIComponent(user) === user && encodeURIComponent(pkg) === pkg) { return done(warnings, errors) } diff --git a/node_modules/validate-npm-package-name/package.json b/node_modules/validate-npm-package-name/package.json index 8a38b66e1d3e4..251958718874c 100644 --- a/node_modules/validate-npm-package-name/package.json +++ b/node_modules/validate-npm-package-name/package.json @@ -1,27 +1,30 @@ { "name": "validate-npm-package-name", - "version": "5.0.1", + "version": "8.0.0", "description": "Give me a string and I'll tell you if it's a valid npm package name", "main": "lib/", "directories": { "test": "test" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.1" + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0" }, "scripts": { + "builtin-fixture": "node -e \"console.log(JSON.stringify(require('node:module').builtinModules))\" > ./lib/builtin-modules.json", "cov:test": "TAP_FLAGS='--cov' npm run test:code", "test:code": "tap ${TAP_FLAGS:-'--'} test/*.js", "test:style": "standard", - "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test": "node --test './test/**/*.js'", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" + "lintfix": "npm run eslint -- --fix", + "snap": "node --test --test-update-snapshots './test/**/*.js'", + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "test:node20": "node --test test", + "test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100 './test/**/*.js'" }, "repository": { "type": "git", @@ -44,17 +47,13 @@ "lib/" ], "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] + "version": "5.0.0", + "publish": true, + "testRunner": "node:test", + "latestCiVersion": 24 } } diff --git a/node_modules/walk-up-path/LICENSE b/node_modules/walk-up-path/LICENSE index 05eeeb88c2ef4..d710582667b8b 100644 --- a/node_modules/walk-up-path/LICENSE +++ b/node_modules/walk-up-path/LICENSE @@ -1,6 +1,6 @@ The ISC License -Copyright (c) Isaac Z. Schlueter +Copyright (c) 2020-2023 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 diff --git a/node_modules/walk-up-path/dist/cjs/index.js b/node_modules/walk-up-path/dist/commonjs/index.js similarity index 100% rename from node_modules/walk-up-path/dist/cjs/index.js rename to node_modules/walk-up-path/dist/commonjs/index.js diff --git a/node_modules/walk-up-path/dist/commonjs/package.json b/node_modules/walk-up-path/dist/commonjs/package.json new file mode 100644 index 0000000000000..5bbefffbabee3 --- /dev/null +++ b/node_modules/walk-up-path/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/walk-up-path/dist/mjs/index.js b/node_modules/walk-up-path/dist/esm/index.js similarity index 100% rename from node_modules/walk-up-path/dist/mjs/index.js rename to node_modules/walk-up-path/dist/esm/index.js diff --git a/node_modules/walk-up-path/dist/esm/package.json b/node_modules/walk-up-path/dist/esm/package.json new file mode 100644 index 0000000000000..3dbc1ca591c05 --- /dev/null +++ b/node_modules/walk-up-path/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/walk-up-path/package.json b/node_modules/walk-up-path/package.json index 0931c670a8d04..4f6d95363297e 100644 --- a/node_modules/walk-up-path/package.json +++ b/node_modules/walk-up-path/package.json @@ -1,24 +1,9 @@ { "name": "walk-up-path", - "version": "3.0.1", + "version": "4.0.0", "files": [ "dist" ], - "main": "./dist/cjs/index.js", - "module": "./dist/mjs/index.js", - "types": "./dist/mjs/index.d.ts", - "exports": { - ".": { - "require": { - "types": "./dist/cjs/index.d.ts", - "default": "./dist/cjs/index.js" - }, - "import": { - "types": "./dist/mjs/index.d.ts", - "default": "./dist/mjs/index.js" - } - } - }, "description": "Given a path string, return a generator that walks up the path, emitting each dirname.", "repository": { "type": "git", @@ -30,15 +15,16 @@ "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", - "prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json && bash ./scripts/fixup.sh", + "prepare": "tshy", "pretest": "npm run prepare", "presnap": "npm run prepare", - "test": "c8 tap", - "snap": "c8 tap", - "format": "prettier --write . --loglevel warn", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --log-level warn", "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts" }, "prettier": { + "experimentalTernaries": true, "semi": false, "printWidth": 75, "tabWidth": 2, @@ -49,24 +35,37 @@ "arrowParens": "avoid", "endOfLine": "lf" }, - "tap": { - "coverage": false, - "node-arg": [ - "--no-warnings", - "--loader", - "ts-node/esm" - ], - "ts": false - }, "devDependencies": { - "@types/node": "^18.15.5", - "@types/tap": "^15.0.8", - "c8": "^7.13.0", - "eslint-config-prettier": "^8.8.0", - "prettier": "^2.8.6", - "tap": "^16.3.4", - "ts-node": "^10.9.1", - "typedoc": "^0.23.28", - "typescript": "^5.0.2" + "@types/node": "^20.14.10", + "prettier": "^3.3.2", + "tap": "^20.0.3", + "tshy": "^3.0.0", + "typedoc": "^0.26.3" + }, + "type": "module", + "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", + "module": "./dist/esm/index.js", + "engines": { + "node": "20 || >=22" } } diff --git a/node_modules/which/node_modules/isexe/LICENSE b/node_modules/which/node_modules/isexe/LICENSE deleted file mode 100644 index c925dbe826b67..0000000000000 --- a/node_modules/which/node_modules/isexe/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) 2016-2022 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. diff --git a/node_modules/which/node_modules/isexe/dist/cjs/index.js b/node_modules/which/node_modules/isexe/dist/cjs/index.js deleted file mode 100644 index cefcb66b5c543..0000000000000 --- a/node_modules/which/node_modules/isexe/dist/cjs/index.js +++ /dev/null @@ -1,46 +0,0 @@ -"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.sync = exports.isexe = exports.posix = exports.win32 = void 0; -const posix = __importStar(require("./posix.js")); -exports.posix = posix; -const win32 = __importStar(require("./win32.js")); -exports.win32 = win32; -__exportStar(require("./options.js"), exports); -const platform = process.env._ISEXE_TEST_PLATFORM_ || process.platform; -const impl = platform === 'win32' ? win32 : posix; -/** - * Determine whether a path is executable on the current platform. - */ -exports.isexe = impl.isexe; -/** - * Synchronously determine whether a path is executable on the - * current platform. - */ -exports.sync = impl.sync; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/which/node_modules/isexe/dist/cjs/posix.js b/node_modules/which/node_modules/isexe/dist/cjs/posix.js deleted file mode 100644 index 3bc5e79d7007e..0000000000000 --- a/node_modules/which/node_modules/isexe/dist/cjs/posix.js +++ /dev/null @@ -1,67 +0,0 @@ -"use strict"; -/** - * This is the Posix implementation of isexe, which uses the file - * mode and uid/gid values. - * - * @module - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.sync = exports.isexe = void 0; -const fs_1 = require("fs"); -const promises_1 = require("fs/promises"); -/** - * Determine whether a path is executable according to the mode and - * current (or specified) user and group IDs. - */ -const isexe = async (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat(await (0, promises_1.stat)(path), options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -exports.isexe = isexe; -/** - * Synchronously determine whether a path is executable according to - * the mode and current (or specified) user and group IDs. - */ -const sync = (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat((0, fs_1.statSync)(path), options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -exports.sync = sync; -const checkStat = (stat, options) => stat.isFile() && checkMode(stat, options); -const checkMode = (stat, options) => { - const myUid = options.uid ?? process.getuid?.(); - const myGroups = options.groups ?? process.getgroups?.() ?? []; - const myGid = options.gid ?? process.getgid?.() ?? myGroups[0]; - if (myUid === undefined || myGid === undefined) { - throw new Error('cannot get uid or gid'); - } - const groups = new Set([myGid, ...myGroups]); - const mod = stat.mode; - const uid = stat.uid; - const gid = stat.gid; - const u = parseInt('100', 8); - const g = parseInt('010', 8); - const o = parseInt('001', 8); - const ug = u | g; - return !!(mod & o || - (mod & g && groups.has(gid)) || - (mod & u && uid === myUid) || - (mod & ug && myUid === 0)); -}; -//# sourceMappingURL=posix.js.map \ No newline at end of file diff --git a/node_modules/which/node_modules/isexe/dist/cjs/win32.js b/node_modules/which/node_modules/isexe/dist/cjs/win32.js deleted file mode 100644 index fa7a4d2f7d240..0000000000000 --- a/node_modules/which/node_modules/isexe/dist/cjs/win32.js +++ /dev/null @@ -1,62 +0,0 @@ -"use strict"; -/** - * This is the Windows implementation of isexe, which uses the file - * extension and PATHEXT setting. - * - * @module - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.sync = exports.isexe = void 0; -const fs_1 = require("fs"); -const promises_1 = require("fs/promises"); -/** - * Determine whether a path is executable based on the file extension - * and PATHEXT environment variable (or specified pathExt option) - */ -const isexe = async (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat(await (0, promises_1.stat)(path), path, options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -exports.isexe = isexe; -/** - * Synchronously determine whether a path is executable based on the file - * extension and PATHEXT environment variable (or specified pathExt option) - */ -const sync = (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat((0, fs_1.statSync)(path), path, options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -exports.sync = sync; -const checkPathExt = (path, options) => { - const { pathExt = process.env.PATHEXT || '' } = options; - const peSplit = pathExt.split(';'); - if (peSplit.indexOf('') !== -1) { - return true; - } - for (let i = 0; i < peSplit.length; i++) { - const p = peSplit[i].toLowerCase(); - const ext = path.substring(path.length - p.length).toLowerCase(); - if (p && ext === p) { - return true; - } - } - return false; -}; -const checkStat = (stat, path, options) => stat.isFile() && checkPathExt(path, options); -//# sourceMappingURL=win32.js.map \ No newline at end of file diff --git a/node_modules/which/node_modules/isexe/dist/mjs/posix.js b/node_modules/which/node_modules/isexe/dist/mjs/posix.js deleted file mode 100644 index c453776c0452f..0000000000000 --- a/node_modules/which/node_modules/isexe/dist/mjs/posix.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * This is the Posix implementation of isexe, which uses the file - * mode and uid/gid values. - * - * @module - */ -import { statSync } from 'fs'; -import { stat } from 'fs/promises'; -/** - * Determine whether a path is executable according to the mode and - * current (or specified) user and group IDs. - */ -export const isexe = async (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat(await stat(path), options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -/** - * Synchronously determine whether a path is executable according to - * the mode and current (or specified) user and group IDs. - */ -export const sync = (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat(statSync(path), options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -const checkStat = (stat, options) => stat.isFile() && checkMode(stat, options); -const checkMode = (stat, options) => { - const myUid = options.uid ?? process.getuid?.(); - const myGroups = options.groups ?? process.getgroups?.() ?? []; - const myGid = options.gid ?? process.getgid?.() ?? myGroups[0]; - if (myUid === undefined || myGid === undefined) { - throw new Error('cannot get uid or gid'); - } - const groups = new Set([myGid, ...myGroups]); - const mod = stat.mode; - const uid = stat.uid; - const gid = stat.gid; - const u = parseInt('100', 8); - const g = parseInt('010', 8); - const o = parseInt('001', 8); - const ug = u | g; - return !!(mod & o || - (mod & g && groups.has(gid)) || - (mod & u && uid === myUid) || - (mod & ug && myUid === 0)); -}; -//# sourceMappingURL=posix.js.map \ No newline at end of file diff --git a/node_modules/which/node_modules/isexe/dist/mjs/win32.js b/node_modules/which/node_modules/isexe/dist/mjs/win32.js deleted file mode 100644 index a354ee2a5115c..0000000000000 --- a/node_modules/which/node_modules/isexe/dist/mjs/win32.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * This is the Windows implementation of isexe, which uses the file - * extension and PATHEXT setting. - * - * @module - */ -import { statSync } from 'fs'; -import { stat } from 'fs/promises'; -/** - * Determine whether a path is executable based on the file extension - * and PATHEXT environment variable (or specified pathExt option) - */ -export const isexe = async (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat(await stat(path), path, options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -/** - * Synchronously determine whether a path is executable based on the file - * extension and PATHEXT environment variable (or specified pathExt option) - */ -export const sync = (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat(statSync(path), path, options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -const checkPathExt = (path, options) => { - const { pathExt = process.env.PATHEXT || '' } = options; - const peSplit = pathExt.split(';'); - if (peSplit.indexOf('') !== -1) { - return true; - } - for (let i = 0; i < peSplit.length; i++) { - const p = peSplit[i].toLowerCase(); - const ext = path.substring(path.length - p.length).toLowerCase(); - if (p && ext === p) { - return true; - } - } - return false; -}; -const checkStat = (stat, path, options) => stat.isFile() && checkPathExt(path, options); -//# sourceMappingURL=win32.js.map \ No newline at end of file diff --git a/node_modules/which/node_modules/isexe/package.json b/node_modules/which/node_modules/isexe/package.json deleted file mode 100644 index a0e2cd04bfdbf..0000000000000 --- a/node_modules/which/node_modules/isexe/package.json +++ /dev/null @@ -1,96 +0,0 @@ -{ - "name": "isexe", - "version": "3.1.1", - "description": "Minimal module to check if a file is executable.", - "main": "./dist/cjs/index.js", - "module": "./dist/mjs/index.js", - "types": "./dist/cjs/index.js", - "files": [ - "dist" - ], - "exports": { - ".": { - "import": { - "types": "./dist/mjs/index.d.ts", - "default": "./dist/mjs/index.js" - }, - "require": { - "types": "./dist/cjs/index.d.ts", - "default": "./dist/cjs/index.js" - } - }, - "./posix": { - "import": { - "types": "./dist/mjs/posix.d.ts", - "default": "./dist/mjs/posix.js" - }, - "require": { - "types": "./dist/cjs/posix.d.ts", - "default": "./dist/cjs/posix.js" - } - }, - "./win32": { - "import": { - "types": "./dist/mjs/win32.d.ts", - "default": "./dist/mjs/win32.js" - }, - "require": { - "types": "./dist/cjs/win32.d.ts", - "default": "./dist/cjs/win32.js" - } - }, - "./package.json": "./package.json" - }, - "devDependencies": { - "@types/node": "^20.4.5", - "@types/tap": "^15.0.8", - "c8": "^8.0.1", - "mkdirp": "^0.5.1", - "prettier": "^2.8.8", - "rimraf": "^2.5.0", - "sync-content": "^1.0.2", - "tap": "^16.3.8", - "ts-node": "^10.9.1", - "typedoc": "^0.24.8", - "typescript": "^5.1.6" - }, - "scripts": { - "preversion": "npm test", - "postversion": "npm publish", - "prepublishOnly": "git push origin --follow-tags", - "prepare": "tsc -p tsconfig/cjs.json && tsc -p tsconfig/esm.json && bash ./scripts/fixup.sh", - "pretest": "npm run prepare", - "presnap": "npm run prepare", - "test": "c8 tap", - "snap": "c8 tap", - "format": "prettier --write . --loglevel warn --ignore-path ../../.prettierignore --cache", - "typedoc": "typedoc --tsconfig tsconfig/esm.json ./src/*.ts" - }, - "author": "Isaac Z. Schlueter (http://blog.izs.me/)", - "license": "ISC", - "tap": { - "coverage": false, - "node-arg": [ - "--enable-source-maps", - "--no-warnings", - "--loader", - "ts-node/esm" - ], - "ts": false - }, - "prettier": { - "semi": false, - "printWidth": 75, - "tabWidth": 2, - "useTabs": false, - "singleQuote": true, - "jsxSingleQuote": false, - "bracketSameLine": true, - "arrowParens": "avoid", - "endOfLine": "lf" - }, - "repository": "https://github.com/isaacs/isexe", - "engines": { - "node": ">=16" - } -} diff --git a/node_modules/which/package.json b/node_modules/which/package.json index 515bfb22ca0e1..f65f91b7f8d1b 100644 --- a/node_modules/which/package.json +++ b/node_modules/which/package.json @@ -2,10 +2,10 @@ "author": "GitHub Inc.", "name": "which", "description": "Like which(1) unix command. Find the first instance of an executable in the PATH.", - "version": "4.0.0", + "version": "7.0.0", "repository": { "type": "git", - "url": "https://github.com/npm/node-which.git" + "url": "git+https://github.com/npm/node-which.git" }, "main": "lib/index.js", "bin": { @@ -13,21 +13,22 @@ }, "license": "ISC", "dependencies": { - "isexe": "^3.1.1" + "isexe": "^4.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.18.0", + "@npmcli/eslint-config": "^6.0.0", + "@npmcli/template-oss": "5.0.0", "tap": "^16.3.0" }, "scripts": { "test": "tap", - "lint": "eslint \"**/*.js\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "posttest": "npm run lint" + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "files": [ "bin/", @@ -41,17 +42,11 @@ ] }, "engines": { - "node": "^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "ciVersions": [ - "16.13.0", - "16.x", - "18.0.0", - "18.x" - ], - "version": "4.18.0", + "version": "5.0.0", "publish": "true" } } diff --git a/node_modules/wrap-ansi-cjs/index.js b/node_modules/wrap-ansi-cjs/index.js deleted file mode 100755 index d502255bd15c8..0000000000000 --- a/node_modules/wrap-ansi-cjs/index.js +++ /dev/null @@ -1,216 +0,0 @@ -'use strict'; -const stringWidth = require('string-width'); -const stripAnsi = require('strip-ansi'); -const ansiStyles = require('ansi-styles'); - -const ESCAPES = new Set([ - '\u001B', - '\u009B' -]); - -const END_CODE = 39; - -const ANSI_ESCAPE_BELL = '\u0007'; -const ANSI_CSI = '['; -const ANSI_OSC = ']'; -const ANSI_SGR_TERMINATOR = 'm'; -const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; - -const wrapAnsi = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; -const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; - -// Calculate the length of words split on ' ', ignoring -// the extra characters added by ansi escape codes -const wordLengths = string => string.split(' ').map(character => stringWidth(character)); - -// Wrap a long word across multiple rows -// Ansi escape codes do not count towards length -const wrapWord = (rows, word, columns) => { - const characters = [...word]; - - let isInsideEscape = false; - let isInsideLinkEscape = false; - let visible = stringWidth(stripAnsi(rows[rows.length - 1])); - - for (const [index, character] of characters.entries()) { - const characterLength = stringWidth(character); - - if (visible + characterLength <= columns) { - rows[rows.length - 1] += character; - } else { - rows.push(character); - visible = 0; - } - - if (ESCAPES.has(character)) { - isInsideEscape = true; - isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); - } - - if (isInsideEscape) { - if (isInsideLinkEscape) { - if (character === ANSI_ESCAPE_BELL) { - isInsideEscape = false; - isInsideLinkEscape = false; - } - } else if (character === ANSI_SGR_TERMINATOR) { - isInsideEscape = false; - } - - continue; - } - - visible += characterLength; - - if (visible === columns && index < characters.length - 1) { - rows.push(''); - visible = 0; - } - } - - // It's possible that the last row we copy over is only - // ansi escape characters, handle this edge-case - if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { - rows[rows.length - 2] += rows.pop(); - } -}; - -// Trims spaces from a string ignoring invisible sequences -const stringVisibleTrimSpacesRight = string => { - const words = string.split(' '); - let last = words.length; - - while (last > 0) { - if (stringWidth(words[last - 1]) > 0) { - break; - } - - last--; - } - - if (last === words.length) { - return string; - } - - return words.slice(0, last).join(' ') + words.slice(last).join(''); -}; - -// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode -// -// 'hard' will never allow a string to take up more than columns characters -// -// 'soft' allows long words to expand past the column length -const exec = (string, columns, options = {}) => { - if (options.trim !== false && string.trim() === '') { - return ''; - } - - let returnValue = ''; - let escapeCode; - let escapeUrl; - - const lengths = wordLengths(string); - let rows = ['']; - - for (const [index, word] of string.split(' ').entries()) { - if (options.trim !== false) { - rows[rows.length - 1] = rows[rows.length - 1].trimStart(); - } - - let rowLength = stringWidth(rows[rows.length - 1]); - - if (index !== 0) { - if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { - // If we start with a new word but the current row length equals the length of the columns, add a new row - rows.push(''); - rowLength = 0; - } - - if (rowLength > 0 || options.trim === false) { - rows[rows.length - 1] += ' '; - rowLength++; - } - } - - // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' - if (options.hard && lengths[index] > columns) { - const remainingColumns = (columns - rowLength); - const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); - const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); - if (breaksStartingNextLine < breaksStartingThisLine) { - rows.push(''); - } - - wrapWord(rows, word, columns); - continue; - } - - if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { - if (options.wordWrap === false && rowLength < columns) { - wrapWord(rows, word, columns); - continue; - } - - rows.push(''); - } - - if (rowLength + lengths[index] > columns && options.wordWrap === false) { - wrapWord(rows, word, columns); - continue; - } - - rows[rows.length - 1] += word; - } - - if (options.trim !== false) { - rows = rows.map(stringVisibleTrimSpacesRight); - } - - const pre = [...rows.join('\n')]; - - for (const [index, character] of pre.entries()) { - returnValue += character; - - if (ESCAPES.has(character)) { - const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; - if (groups.code !== undefined) { - const code = Number.parseFloat(groups.code); - escapeCode = code === END_CODE ? undefined : code; - } else if (groups.uri !== undefined) { - escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; - } - } - - const code = ansiStyles.codes.get(Number(escapeCode)); - - if (pre[index + 1] === '\n') { - if (escapeUrl) { - returnValue += wrapAnsiHyperlink(''); - } - - if (escapeCode && code) { - returnValue += wrapAnsi(code); - } - } else if (character === '\n') { - if (escapeCode && code) { - returnValue += wrapAnsi(escapeCode); - } - - if (escapeUrl) { - returnValue += wrapAnsiHyperlink(escapeUrl); - } - } - } - - return returnValue; -}; - -// For each newline, invoke the method separately -module.exports = (string, columns, options) => { - return String(string) - .normalize() - .replace(/\r\n/g, '\n') - .split('\n') - .map(line => exec(line, columns, options)) - .join('\n'); -}; diff --git a/node_modules/wrap-ansi-cjs/license b/node_modules/wrap-ansi-cjs/license deleted file mode 100644 index fa7ceba3eb4a9..0000000000000 --- a/node_modules/wrap-ansi-cjs/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/wrap-ansi-cjs/node_modules/ansi-styles/index.js b/node_modules/wrap-ansi-cjs/node_modules/ansi-styles/index.js deleted file mode 100644 index 5d82581a13f99..0000000000000 --- a/node_modules/wrap-ansi-cjs/node_modules/ansi-styles/index.js +++ /dev/null @@ -1,163 +0,0 @@ -'use strict'; - -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; -}; - -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; -}; - -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; - -const ansi2ansi = n => n; -const rgb2rgb = (r, g, b) => [r, g, b]; - -const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); - - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); - - return value; - }, - enumerable: true, - configurable: true - }); -}; - -/** @type {typeof import('color-convert')} */ -let colorConvert; -const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = require('color-convert'); - } - - const offset = isBackground ? 10 : 0; - const styles = {}; - - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } - - return styles; -}; - -function assembleStyles() { - const codes = new Map(); - 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], - 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], - 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], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - 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'; - - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); diff --git a/node_modules/wrap-ansi-cjs/node_modules/ansi-styles/license b/node_modules/wrap-ansi-cjs/node_modules/ansi-styles/license deleted file mode 100644 index e7af2f77107d7..0000000000000 --- a/node_modules/wrap-ansi-cjs/node_modules/ansi-styles/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/wrap-ansi-cjs/node_modules/ansi-styles/package.json b/node_modules/wrap-ansi-cjs/node_modules/ansi-styles/package.json deleted file mode 100644 index 75393284d7e47..0000000000000 --- a/node_modules/wrap-ansi-cjs/node_modules/ansi-styles/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "ansi-styles", - "version": "4.3.0", - "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": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "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" - ], - "dependencies": { - "color-convert": "^2.0.1" - }, - "devDependencies": { - "@types/color-convert": "^1.9.0", - "ava": "^2.3.0", - "svg-term-cli": "^2.1.1", - "tsd": "^0.11.0", - "xo": "^0.25.3" - } -} diff --git a/node_modules/wrap-ansi-cjs/package.json b/node_modules/wrap-ansi-cjs/package.json deleted file mode 100644 index dfb2f4f108cfb..0000000000000 --- a/node_modules/wrap-ansi-cjs/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "wrap-ansi", - "version": "7.0.0", - "description": "Wordwrap a string with ANSI escape codes", - "license": "MIT", - "repository": "chalk/wrap-ansi", - "funding": "https://github.com/chalk/wrap-ansi?sponsor=1", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "https://sindresorhus.com" - }, - "engines": { - "node": ">=10" - }, - "scripts": { - "test": "xo && nyc ava" - }, - "files": [ - "index.js" - ], - "keywords": [ - "wrap", - "break", - "wordwrap", - "wordbreak", - "linewrap", - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "devDependencies": { - "ava": "^2.1.0", - "chalk": "^4.0.0", - "coveralls": "^3.0.3", - "has-ansi": "^4.0.0", - "nyc": "^15.0.1", - "xo": "^0.29.1" - } -} diff --git a/node_modules/wrap-ansi/index.js b/node_modules/wrap-ansi/index.js deleted file mode 100755 index d80c74c19ca3f..0000000000000 --- a/node_modules/wrap-ansi/index.js +++ /dev/null @@ -1,214 +0,0 @@ -import stringWidth from 'string-width'; -import stripAnsi from 'strip-ansi'; -import ansiStyles from 'ansi-styles'; - -const ESCAPES = new Set([ - '\u001B', - '\u009B', -]); - -const END_CODE = 39; -const ANSI_ESCAPE_BELL = '\u0007'; -const ANSI_CSI = '['; -const ANSI_OSC = ']'; -const ANSI_SGR_TERMINATOR = 'm'; -const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; - -const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; -const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; - -// Calculate the length of words split on ' ', ignoring -// the extra characters added by ansi escape codes -const wordLengths = string => string.split(' ').map(character => stringWidth(character)); - -// Wrap a long word across multiple rows -// Ansi escape codes do not count towards length -const wrapWord = (rows, word, columns) => { - const characters = [...word]; - - let isInsideEscape = false; - let isInsideLinkEscape = false; - let visible = stringWidth(stripAnsi(rows[rows.length - 1])); - - for (const [index, character] of characters.entries()) { - const characterLength = stringWidth(character); - - if (visible + characterLength <= columns) { - rows[rows.length - 1] += character; - } else { - rows.push(character); - visible = 0; - } - - if (ESCAPES.has(character)) { - isInsideEscape = true; - isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); - } - - if (isInsideEscape) { - if (isInsideLinkEscape) { - if (character === ANSI_ESCAPE_BELL) { - isInsideEscape = false; - isInsideLinkEscape = false; - } - } else if (character === ANSI_SGR_TERMINATOR) { - isInsideEscape = false; - } - - continue; - } - - visible += characterLength; - - if (visible === columns && index < characters.length - 1) { - rows.push(''); - visible = 0; - } - } - - // It's possible that the last row we copy over is only - // ansi escape characters, handle this edge-case - if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { - rows[rows.length - 2] += rows.pop(); - } -}; - -// Trims spaces from a string ignoring invisible sequences -const stringVisibleTrimSpacesRight = string => { - const words = string.split(' '); - let last = words.length; - - while (last > 0) { - if (stringWidth(words[last - 1]) > 0) { - break; - } - - last--; - } - - if (last === words.length) { - return string; - } - - return words.slice(0, last).join(' ') + words.slice(last).join(''); -}; - -// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode -// -// 'hard' will never allow a string to take up more than columns characters -// -// 'soft' allows long words to expand past the column length -const exec = (string, columns, options = {}) => { - if (options.trim !== false && string.trim() === '') { - return ''; - } - - let returnValue = ''; - let escapeCode; - let escapeUrl; - - const lengths = wordLengths(string); - let rows = ['']; - - for (const [index, word] of string.split(' ').entries()) { - if (options.trim !== false) { - rows[rows.length - 1] = rows[rows.length - 1].trimStart(); - } - - let rowLength = stringWidth(rows[rows.length - 1]); - - if (index !== 0) { - if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { - // If we start with a new word but the current row length equals the length of the columns, add a new row - rows.push(''); - rowLength = 0; - } - - if (rowLength > 0 || options.trim === false) { - rows[rows.length - 1] += ' '; - rowLength++; - } - } - - // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' - if (options.hard && lengths[index] > columns) { - const remainingColumns = (columns - rowLength); - const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); - const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); - if (breaksStartingNextLine < breaksStartingThisLine) { - rows.push(''); - } - - wrapWord(rows, word, columns); - continue; - } - - if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { - if (options.wordWrap === false && rowLength < columns) { - wrapWord(rows, word, columns); - continue; - } - - rows.push(''); - } - - if (rowLength + lengths[index] > columns && options.wordWrap === false) { - wrapWord(rows, word, columns); - continue; - } - - rows[rows.length - 1] += word; - } - - if (options.trim !== false) { - rows = rows.map(row => stringVisibleTrimSpacesRight(row)); - } - - const pre = [...rows.join('\n')]; - - for (const [index, character] of pre.entries()) { - returnValue += character; - - if (ESCAPES.has(character)) { - const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; - if (groups.code !== undefined) { - const code = Number.parseFloat(groups.code); - escapeCode = code === END_CODE ? undefined : code; - } else if (groups.uri !== undefined) { - escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; - } - } - - const code = ansiStyles.codes.get(Number(escapeCode)); - - if (pre[index + 1] === '\n') { - if (escapeUrl) { - returnValue += wrapAnsiHyperlink(''); - } - - if (escapeCode && code) { - returnValue += wrapAnsiCode(code); - } - } else if (character === '\n') { - if (escapeCode && code) { - returnValue += wrapAnsiCode(escapeCode); - } - - if (escapeUrl) { - returnValue += wrapAnsiHyperlink(escapeUrl); - } - } - } - - return returnValue; -}; - -// For each newline, invoke the method separately -export default function wrapAnsi(string, columns, options) { - return String(string) - .normalize() - .replace(/\r\n/g, '\n') - .split('\n') - .map(line => exec(line, columns, options)) - .join('\n'); -} diff --git a/node_modules/wrap-ansi/license b/node_modules/wrap-ansi/license deleted file mode 100644 index fa7ceba3eb4a9..0000000000000 --- a/node_modules/wrap-ansi/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/wrap-ansi/node_modules/ansi-regex/index.js b/node_modules/wrap-ansi/node_modules/ansi-regex/index.js deleted file mode 100644 index 130a0929b8ce8..0000000000000 --- a/node_modules/wrap-ansi/node_modules/ansi-regex/index.js +++ /dev/null @@ -1,8 +0,0 @@ -export default function ansiRegex({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'); -} diff --git a/node_modules/wrap-ansi/node_modules/ansi-regex/license b/node_modules/wrap-ansi/node_modules/ansi-regex/license deleted file mode 100644 index fa7ceba3eb4a9..0000000000000 --- a/node_modules/wrap-ansi/node_modules/ansi-regex/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/wrap-ansi/node_modules/ansi-regex/package.json b/node_modules/wrap-ansi/node_modules/ansi-regex/package.json deleted file mode 100644 index 7bbb563bf2a70..0000000000000 --- a/node_modules/wrap-ansi/node_modules/ansi-regex/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "ansi-regex", - "version": "6.0.1", - "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", - "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": { - "ava": "^3.15.0", - "tsd": "^0.14.0", - "xo": "^0.38.2" - } -} diff --git a/node_modules/wrap-ansi/node_modules/emoji-regex/LICENSE-MIT.txt b/node_modules/wrap-ansi/node_modules/emoji-regex/LICENSE-MIT.txt deleted file mode 100644 index a41e0a7ef970e..0000000000000 --- a/node_modules/wrap-ansi/node_modules/emoji-regex/LICENSE-MIT.txt +++ /dev/null @@ -1,20 +0,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. diff --git a/node_modules/wrap-ansi/node_modules/emoji-regex/RGI_Emoji.js b/node_modules/wrap-ansi/node_modules/emoji-regex/RGI_Emoji.js deleted file mode 100644 index 3fbe92410063f..0000000000000 --- a/node_modules/wrap-ansi/node_modules/emoji-regex/RGI_Emoji.js +++ /dev/null @@ -1,6 +0,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]/g; -}; diff --git a/node_modules/wrap-ansi/node_modules/emoji-regex/es2015/RGI_Emoji.js b/node_modules/wrap-ansi/node_modules/emoji-regex/es2015/RGI_Emoji.js deleted file mode 100644 index ecf32f177908c..0000000000000 --- a/node_modules/wrap-ansi/node_modules/emoji-regex/es2015/RGI_Emoji.js +++ /dev/null @@ -1,6 +0,0 @@ -"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; -}; diff --git a/node_modules/wrap-ansi/node_modules/emoji-regex/es2015/index.js b/node_modules/wrap-ansi/node_modules/emoji-regex/es2015/index.js deleted file mode 100644 index 1a4fc8d0dcc32..0000000000000 --- a/node_modules/wrap-ansi/node_modules/emoji-regex/es2015/index.js +++ /dev/null @@ -1,6 +0,0 @@ -"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; -}; diff --git a/node_modules/wrap-ansi/node_modules/emoji-regex/es2015/text.js b/node_modules/wrap-ansi/node_modules/emoji-regex/es2015/text.js deleted file mode 100644 index 8e9f985758314..0000000000000 --- a/node_modules/wrap-ansi/node_modules/emoji-regex/es2015/text.js +++ /dev/null @@ -1,6 +0,0 @@ -"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; -}; diff --git a/node_modules/wrap-ansi/node_modules/emoji-regex/index.js b/node_modules/wrap-ansi/node_modules/emoji-regex/index.js deleted file mode 100644 index c0490d4c95ac3..0000000000000 --- a/node_modules/wrap-ansi/node_modules/emoji-regex/index.js +++ /dev/null @@ -1,6 +0,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]|(?:[\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; -}; diff --git a/node_modules/wrap-ansi/node_modules/emoji-regex/package.json b/node_modules/wrap-ansi/node_modules/emoji-regex/package.json deleted file mode 100644 index eac892a16a253..0000000000000 --- a/node_modules/wrap-ansi/node_modules/emoji-regex/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/wrap-ansi/node_modules/emoji-regex/text.js b/node_modules/wrap-ansi/node_modules/emoji-regex/text.js deleted file mode 100644 index 9bc63ce74753f..0000000000000 --- a/node_modules/wrap-ansi/node_modules/emoji-regex/text.js +++ /dev/null @@ -1,6 +0,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; -}; diff --git a/node_modules/wrap-ansi/node_modules/string-width/index.js b/node_modules/wrap-ansi/node_modules/string-width/index.js deleted file mode 100644 index 9294488f88488..0000000000000 --- a/node_modules/wrap-ansi/node_modules/string-width/index.js +++ /dev/null @@ -1,54 +0,0 @@ -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; -} diff --git a/node_modules/wrap-ansi/node_modules/string-width/license b/node_modules/wrap-ansi/node_modules/string-width/license deleted file mode 100644 index fa7ceba3eb4a9..0000000000000 --- a/node_modules/wrap-ansi/node_modules/string-width/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/wrap-ansi/node_modules/string-width/package.json b/node_modules/wrap-ansi/node_modules/string-width/package.json deleted file mode 100644 index f46d6770f9ebb..0000000000000 --- a/node_modules/wrap-ansi/node_modules/string-width/package.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/wrap-ansi/node_modules/strip-ansi/index.js b/node_modules/wrap-ansi/node_modules/strip-ansi/index.js deleted file mode 100644 index ba19750e64e06..0000000000000 --- a/node_modules/wrap-ansi/node_modules/strip-ansi/index.js +++ /dev/null @@ -1,14 +0,0 @@ -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, ''); -} diff --git a/node_modules/wrap-ansi/node_modules/strip-ansi/license b/node_modules/wrap-ansi/node_modules/strip-ansi/license deleted file mode 100644 index fa7ceba3eb4a9..0000000000000 --- a/node_modules/wrap-ansi/node_modules/strip-ansi/license +++ /dev/null @@ -1,9 +0,0 @@ -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. diff --git a/node_modules/wrap-ansi/node_modules/strip-ansi/package.json b/node_modules/wrap-ansi/node_modules/strip-ansi/package.json deleted file mode 100644 index e1f455c325b00..0000000000000 --- a/node_modules/wrap-ansi/node_modules/strip-ansi/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "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" - } -} diff --git a/node_modules/wrap-ansi/package.json b/node_modules/wrap-ansi/package.json deleted file mode 100644 index 198a5dbcb7108..0000000000000 --- a/node_modules/wrap-ansi/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "name": "wrap-ansi", - "version": "8.1.0", - "description": "Wordwrap a string with ANSI escape codes", - "license": "MIT", - "repository": "chalk/wrap-ansi", - "funding": "https://github.com/chalk/wrap-ansi?sponsor=1", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "https://sindresorhus.com" - }, - "type": "module", - "exports": { - "types": "./index.d.ts", - "default": "./index.js" - }, - "engines": { - "node": ">=12" - }, - "scripts": { - "test": "xo && nyc ava && tsd" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "wrap", - "break", - "wordwrap", - "wordbreak", - "linewrap", - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" - }, - "devDependencies": { - "ava": "^3.15.0", - "chalk": "^4.1.2", - "coveralls": "^3.1.1", - "has-ansi": "^5.0.1", - "nyc": "^15.1.0", - "tsd": "^0.25.0", - "xo": "^0.44.0" - } -} diff --git a/node_modules/write-file-atomic/lib/index.js b/node_modules/write-file-atomic/lib/index.js deleted file mode 100644 index 6013894cd1f4f..0000000000000 --- a/node_modules/write-file-atomic/lib/index.js +++ /dev/null @@ -1,267 +0,0 @@ -'use strict' -module.exports = writeFile -module.exports.sync = writeFileSync -module.exports._getTmpname = getTmpname // for testing -module.exports._cleanupOnExit = cleanupOnExit - -const fs = require('fs') -const MurmurHash3 = require('imurmurhash') -const { onExit } = require('signal-exit') -const path = require('path') -const { promisify } = require('util') -const activeFiles = {} - -// if we run inside of a worker_thread, `process.pid` is not unique -/* istanbul ignore next */ -const threadId = (function getId () { - try { - const workerThreads = require('worker_threads') - - /// if we are in main thread, this is set to `0` - return workerThreads.threadId - } catch (e) { - // worker_threads are not available, fallback to 0 - return 0 - } -})() - -let invocations = 0 -function getTmpname (filename) { - return filename + '.' + - MurmurHash3(__filename) - .hash(String(process.pid)) - .hash(String(threadId)) - .hash(String(++invocations)) - .result() -} - -function cleanupOnExit (tmpfile) { - return () => { - try { - fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile) - } catch { - // ignore errors - } - } -} - -function serializeActiveFile (absoluteName) { - return new Promise(resolve => { - // make a queue if it doesn't already exist - if (!activeFiles[absoluteName]) { - activeFiles[absoluteName] = [] - } - - activeFiles[absoluteName].push(resolve) // add this job to the queue - if (activeFiles[absoluteName].length === 1) { - resolve() - } // kick off the first one - }) -} - -// https://github.com/isaacs/node-graceful-fs/blob/master/polyfills.js#L315-L342 -function isChownErrOk (err) { - if (err.code === 'ENOSYS') { - return true - } - - const nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (err.code === 'EINVAL' || err.code === 'EPERM') { - return true - } - } - - return false -} - -async function writeFileAsync (filename, data, options = {}) { - if (typeof options === 'string') { - options = { encoding: options } - } - - let fd - let tmpfile - /* istanbul ignore next -- The closure only gets called when onExit triggers */ - const removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile)) - const absoluteName = path.resolve(filename) - - try { - await serializeActiveFile(absoluteName) - const truename = await promisify(fs.realpath)(filename).catch(() => filename) - tmpfile = getTmpname(truename) - - if (!options.mode || !options.chown) { - // Either mode or chown is not explicitly set - // Default behavior is to copy it from original file - const stats = await promisify(fs.stat)(truename).catch(() => {}) - if (stats) { - if (options.mode == null) { - options.mode = stats.mode - } - - if (options.chown == null && process.getuid) { - options.chown = { uid: stats.uid, gid: stats.gid } - } - } - } - - fd = await promisify(fs.open)(tmpfile, 'w', options.mode) - if (options.tmpfileCreated) { - await options.tmpfileCreated(tmpfile) - } - if (ArrayBuffer.isView(data)) { - await promisify(fs.write)(fd, data, 0, data.length, 0) - } else if (data != null) { - await promisify(fs.write)(fd, String(data), 0, String(options.encoding || 'utf8')) - } - - if (options.fsync !== false) { - await promisify(fs.fsync)(fd) - } - - await promisify(fs.close)(fd) - fd = null - - if (options.chown) { - await promisify(fs.chown)(tmpfile, options.chown.uid, options.chown.gid).catch(err => { - if (!isChownErrOk(err)) { - throw err - } - }) - } - - if (options.mode) { - await promisify(fs.chmod)(tmpfile, options.mode).catch(err => { - if (!isChownErrOk(err)) { - throw err - } - }) - } - - await promisify(fs.rename)(tmpfile, truename) - } finally { - if (fd) { - await promisify(fs.close)(fd).catch( - /* istanbul ignore next */ - () => {} - ) - } - removeOnExitHandler() - await promisify(fs.unlink)(tmpfile).catch(() => {}) - activeFiles[absoluteName].shift() // remove the element added by serializeSameFile - if (activeFiles[absoluteName].length > 0) { - activeFiles[absoluteName][0]() // start next job if one is pending - } else { - delete activeFiles[absoluteName] - } - } -} - -async function writeFile (filename, data, options, callback) { - if (options instanceof Function) { - callback = options - options = {} - } - - const promise = writeFileAsync(filename, data, options) - if (callback) { - try { - const result = await promise - return callback(result) - } catch (err) { - return callback(err) - } - } - - return promise -} - -function writeFileSync (filename, data, options) { - if (typeof options === 'string') { - options = { encoding: options } - } else if (!options) { - options = {} - } - try { - filename = fs.realpathSync(filename) - } catch (ex) { - // it's ok, it'll happen on a not yet existing file - } - const tmpfile = getTmpname(filename) - - if (!options.mode || !options.chown) { - // Either mode or chown is not explicitly set - // Default behavior is to copy it from original file - try { - const stats = fs.statSync(filename) - options = Object.assign({}, options) - if (!options.mode) { - options.mode = stats.mode - } - if (!options.chown && process.getuid) { - options.chown = { uid: stats.uid, gid: stats.gid } - } - } catch (ex) { - // ignore stat errors - } - } - - let fd - const cleanup = cleanupOnExit(tmpfile) - const removeOnExitHandler = onExit(cleanup) - - let threw = true - try { - fd = fs.openSync(tmpfile, 'w', options.mode || 0o666) - if (options.tmpfileCreated) { - options.tmpfileCreated(tmpfile) - } - if (ArrayBuffer.isView(data)) { - fs.writeSync(fd, data, 0, data.length, 0) - } else if (data != null) { - fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8')) - } - if (options.fsync !== false) { - fs.fsyncSync(fd) - } - - fs.closeSync(fd) - fd = null - - if (options.chown) { - try { - fs.chownSync(tmpfile, options.chown.uid, options.chown.gid) - } catch (err) { - if (!isChownErrOk(err)) { - throw err - } - } - } - - if (options.mode) { - try { - fs.chmodSync(tmpfile, options.mode) - } catch (err) { - if (!isChownErrOk(err)) { - throw err - } - } - } - - fs.renameSync(tmpfile, filename) - threw = false - } finally { - if (fd) { - try { - fs.closeSync(fd) - } catch (ex) { - // ignore close errors at this stage, error may have closed fd already. - } - } - removeOnExitHandler() - if (threw) { - cleanup() - } - } -} diff --git a/node_modules/write-file-atomic/package.json b/node_modules/write-file-atomic/package.json deleted file mode 100644 index 54d58d7eeb984..0000000000000 --- a/node_modules/write-file-atomic/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "name": "write-file-atomic", - "version": "5.0.1", - "description": "Write files in an atomic fashion w/configurable ownership", - "main": "./lib/index.js", - "scripts": { - "test": "tap", - "posttest": "npm run lint", - "lint": "eslint \"**/*.js\"", - "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "template-oss-apply": "template-oss-apply --force" - }, - "repository": { - "type": "git", - "url": "https://github.com/npm/write-file-atomic.git" - }, - "keywords": [ - "writeFile", - "atomic" - ], - "author": "GitHub Inc.", - "license": "ISC", - "bugs": { - "url": "https://github.com/npm/write-file-atomic/issues" - }, - "homepage": "https://github.com/npm/write-file-atomic", - "dependencies": { - "imurmurhash": "^0.1.4", - "signal-exit": "^4.0.1" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.14.1", - "tap": "^16.0.1" - }, - "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.", - "windowsCI": false, - "version": "4.14.1", - "publish": "true" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/yallist/LICENSE b/node_modules/yallist/LICENSE deleted file mode 100644 index 19129e315fe59..0000000000000 --- a/node_modules/yallist/LICENSE +++ /dev/null @@ -1,15 +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. diff --git a/node_modules/yallist/LICENSE.md b/node_modules/yallist/LICENSE.md new file mode 100644 index 0000000000000..881248b6d7f0c --- /dev/null +++ b/node_modules/yallist/LICENSE.md @@ -0,0 +1,63 @@ +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.*** diff --git a/node_modules/yallist/dist/commonjs/index.js b/node_modules/yallist/dist/commonjs/index.js new file mode 100644 index 0000000000000..c1e1e4741689d --- /dev/null +++ b/node_modules/yallist/dist/commonjs/index.js @@ -0,0 +1,384 @@ +"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 \ No newline at end of file diff --git a/node_modules/yallist/dist/commonjs/package.json b/node_modules/yallist/dist/commonjs/package.json new file mode 100644 index 0000000000000..5bbefffbabee3 --- /dev/null +++ b/node_modules/yallist/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/yallist/dist/esm/index.js b/node_modules/yallist/dist/esm/index.js new file mode 100644 index 0000000000000..3d81c5113b93a --- /dev/null +++ b/node_modules/yallist/dist/esm/index.js @@ -0,0 +1,379 @@ +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 \ No newline at end of file diff --git a/node_modules/yallist/dist/esm/package.json b/node_modules/yallist/dist/esm/package.json new file mode 100644 index 0000000000000..3dbc1ca591c05 --- /dev/null +++ b/node_modules/yallist/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/yallist/package.json b/node_modules/yallist/package.json index 8a083867d72e0..2f5247808bbea 100644 --- a/node_modules/yallist/package.json +++ b/node_modules/yallist/package.json @@ -1,29 +1,68 @@ { "name": "yallist", - "version": "4.0.0", + "version": "5.0.0", "description": "Yet Another Linked List", - "main": "yallist.js", - "directories": { - "test": "test" - }, "files": [ - "yallist.js", - "iterator.js" + "dist" ], - "dependencies": {}, "devDependencies": { - "tap": "^12.1.0" + "prettier": "^3.2.5", + "tap": "^18.7.2", + "tshy": "^1.13.1", + "typedoc": "^0.25.13" }, "scripts": { - "test": "tap test/*.js --100", "preversion": "npm test", "postversion": "npm publish", - "postpublish": "git push origin --all; git push origin --tags" + "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": "ISC" + "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" + } } diff --git a/package-lock.json b/package-lock.json index 85bb1d93f5cd5..4fd351e167228 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,18 +1,20 @@ { "name": "npm", - "version": "10.8.2", + "version": "12.0.0-pre.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "npm", - "version": "10.8.2", + "version": "12.0.0-pre.1", "bundleDependencies": [ "@isaacs/string-locale-compare", "@npmcli/arborist", "@npmcli/config", "@npmcli/fs", + "@npmcli/git", "@npmcli/map-workspaces", + "@npmcli/metavuln-calculator", "@npmcli/package-json", "@npmcli/promise-spawn", "@npmcli/redact", @@ -20,10 +22,11 @@ "@sigstore/tuf", "abbrev", "archy", + "bin-links", "cacache", "chalk", "ci-info", - "cli-columns", + "diff", "fastest-levenshtein", "fs-minipass", "glob", @@ -37,7 +40,6 @@ "libnpmdiff", "libnpmexec", "libnpmfund", - "libnpmhook", "libnpmorg", "libnpmpack", "libnpmpublish", @@ -51,7 +53,6 @@ "ms", "node-gyp", "nopt", - "normalize-package-data", "npm-audit-report", "npm-install-checks", "npm-package-arg", @@ -74,8 +75,7 @@ "tiny-relative-date", "treeverse", "validate-npm-package-name", - "which", - "write-file-atomic" + "which" ], "license": "Artistic-2.0", "workspaces": [ @@ -87,73 +87,73 @@ ], "dependencies": { "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/arborist": "^7.5.4", - "@npmcli/config": "^8.3.4", - "@npmcli/fs": "^3.1.1", - "@npmcli/map-workspaces": "^3.0.6", - "@npmcli/package-json": "^5.2.0", - "@npmcli/promise-spawn": "^7.0.2", - "@npmcli/redact": "^2.0.1", - "@npmcli/run-script": "^8.1.0", - "@sigstore/tuf": "^2.3.4", - "abbrev": "^2.0.0", + "@npmcli/arborist": "^10.0.0-pre.1", + "@npmcli/config": "^11.0.0-pre.1", + "@npmcli/fs": "^6.0.0", + "@npmcli/git": "^8.0.0", + "@npmcli/map-workspaces": "^6.0.0", + "@npmcli/metavuln-calculator": "^10.0.0", + "@npmcli/package-json": "^8.0.0", + "@npmcli/promise-spawn": "^10.0.0", + "@npmcli/redact": "^5.0.0", + "@npmcli/run-script": "^11.0.0", + "@sigstore/tuf": "^5.0.0", + "abbrev": "^5.0.0", "archy": "~1.0.0", - "cacache": "^18.0.3", - "chalk": "^5.3.0", - "ci-info": "^4.0.0", - "cli-columns": "^4.0.0", + "bin-links": "^7.0.0", + "cacache": "^21.0.1", + "chalk": "^5.6.2", + "ci-info": "^4.4.0", + "diff": "^8.0.2", "fastest-levenshtein": "^1.0.16", "fs-minipass": "^3.0.3", - "glob": "^10.4.2", + "glob": "^13.0.6", "graceful-fs": "^4.2.11", - "hosted-git-info": "^7.0.2", - "ini": "^4.1.3", - "init-package-json": "^6.0.3", - "is-cidr": "^5.1.0", - "json-parse-even-better-errors": "^3.0.2", - "libnpmaccess": "^8.0.6", - "libnpmdiff": "^6.1.4", - "libnpmexec": "^8.1.3", - "libnpmfund": "^5.0.12", - "libnpmhook": "^10.0.5", - "libnpmorg": "^6.0.6", - "libnpmpack": "^7.0.4", - "libnpmpublish": "^9.0.9", - "libnpmsearch": "^7.0.6", - "libnpmteam": "^6.0.5", - "libnpmversion": "^6.0.3", - "make-fetch-happen": "^13.0.1", - "minimatch": "^9.0.5", - "minipass": "^7.1.1", + "hosted-git-info": "^10.1.1", + "ini": "^7.0.0", + "init-package-json": "^9.0.0", + "is-cidr": "^7.0.0", + "json-parse-even-better-errors": "^6.0.0", + "libnpmaccess": "^11.0.0-pre.0", + "libnpmdiff": "^9.0.0-pre.0", + "libnpmexec": "^11.0.0-pre.0", + "libnpmfund": "^8.0.0-pre.0", + "libnpmorg": "^9.0.0-pre.0", + "libnpmpack": "^10.0.0-pre.1", + "libnpmpublish": "^12.0.0-pre.0", + "libnpmsearch": "^10.0.0-pre.0", + "libnpmteam": "^9.0.0-pre.0", + "libnpmversion": "^9.0.0-pre.1", + "make-fetch-happen": "^16.0.1", + "minimatch": "^10.2.5", + "minipass": "^7.1.3", "minipass-pipeline": "^1.2.4", "ms": "^2.1.2", - "node-gyp": "^10.1.0", - "nopt": "^7.2.1", - "normalize-package-data": "^6.0.2", - "npm-audit-report": "^5.0.0", - "npm-install-checks": "^6.3.0", - "npm-package-arg": "^11.0.2", - "npm-pick-manifest": "^9.1.0", - "npm-profile": "^10.0.0", - "npm-registry-fetch": "^17.1.0", - "npm-user-validate": "^2.0.1", - "p-map": "^4.0.0", - "pacote": "^18.0.6", - "parse-conflict-json": "^3.0.1", - "proc-log": "^4.2.0", + "node-gyp": "^13.0.0", + "nopt": "^10.0.1", + "npm-audit-report": "^8.0.0", + "npm-install-checks": "^9.0.0", + "npm-package-arg": "^14.0.0", + "npm-pick-manifest": "^12.0.0", + "npm-profile": "^13.0.1", + "npm-registry-fetch": "^20.0.1", + "npm-user-validate": "^5.0.0", + "p-map": "^7.0.4", + "pacote": "^22.0.0", + "parse-conflict-json": "^6.0.0", + "proc-log": "^7.0.0", "qrcode-terminal": "^0.12.0", - "read": "^3.0.1", - "semver": "^7.6.2", + "read": "^6.0.0", + "semver": "^7.8.4", "spdx-expression-parse": "^4.0.0", - "ssri": "^10.0.6", - "supports-color": "^9.4.0", - "tar": "^6.2.1", + "ssri": "^14.0.0", + "supports-color": "^10.2.2", + "tar": "^7.5.16", "text-table": "~0.2.0", - "tiny-relative-date": "^1.3.0", + "tiny-relative-date": "^2.0.2", "treeverse": "^3.0.0", - "validate-npm-package-name": "^5.0.1", - "which": "^4.0.0", - "write-file-atomic": "^5.0.1" + "validate-npm-package-name": "^8.0.0", + "which": "^7.0.0" }, "bin": { "npm": "bin/npm-cli.js", @@ -161,28 +161,30 @@ }, "devDependencies": { "@npmcli/docs": "^1.0.0", - "@npmcli/eslint-config": "^4.0.2", - "@npmcli/git": "^5.0.8", + "@npmcli/eslint-config": "^5.1.0", + "@npmcli/installed-package-contents": "^5.0.0", "@npmcli/mock-globals": "^1.0.0", "@npmcli/mock-registry": "^1.0.0", - "@npmcli/template-oss": "4.22.0", - "@tufjs/repo-mock": "^2.0.0", + "@npmcli/name-from-folder": "^5.0.0", + "@npmcli/node-gyp": "^6.0.0", + "@npmcli/template-oss": "5.1.1", + "@tufjs/repo-mock": "^5.0.0", "ajv": "^8.12.0", - "ajv-formats": "^2.1.1", + "ajv-formats": "^3.0.1", "ajv-formats-draft2019": "^1.6.1", "cli-table3": "^0.6.4", - "diff": "^5.2.0", - "nock": "^13.4.0", - "npm-packlist": "^8.0.2", - "remark": "^14.0.2", - "remark-gfm": "^3.0.1", - "remark-github": "^11.2.4", - "rimraf": "^5.0.5", + "diff": "^8.0.4", + "nock": "^14.0.0", + "npm-packlist": "^11.3.0", + "remark": "^15.0.1", + "remark-gfm": "^4.0.1", + "remark-github": "^12.0.0", + "rimraf": "^6.0.1", "spawk": "^1.7.1", "tap": "^16.3.9" }, "engines": { - "node": "^18.17.0 || >=20.5.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "docs": { @@ -191,23 +193,102 @@ "license": "ISC", "devDependencies": { "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "front-matter": "^4.0.2", - "ignore-walk": "^6.0.5", - "jsdom": "^24.0.0", - "rehype-stringify": "^9.0.3", - "remark-gfm": "^3.0.1", - "remark-man": "^8.0.1", - "remark-parse": "^10.0.1", - "remark-rehype": "^10.1.0", + "ignore-walk": "^8.0.0", + "jsdom": "27.0.0", + "rehype-stringify": "^10.0.1", + "remark-gfm": "^4.0.1", + "remark-man": "^9.0.0", + "remark-parse": "^11.0.0", + "remark-rehype": "^11.1.2", "semver": "^7.3.8", "tap": "^16.3.8", - "unified": "^10.1.2", + "unified": "^11.0.5", "yaml": "^2.2.1" }, "engines": { - "node": "^18.17.0 || >=20.5.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "docs/node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "docs/node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "docs/node_modules/jsdom": { + "version": "27.0.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-27.0.0.tgz", + "integrity": "sha512-lIHeR1qlIRrIN5VMccd8tI2Sgw6ieYXSVktcSHaNe3Z5nE/tcPQYQWOq00wxMvYOsz+73eAkNenVvmPC6bba9A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/dom-selector": "^6.5.4", + "cssstyle": "^5.3.0", + "data-urls": "^6.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "parse5": "^7.3.0", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^6.0.0", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^8.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^15.0.0", + "ws": "^8.18.2", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "docs/node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" } }, "mock-globals": { @@ -215,12 +296,12 @@ "version": "1.0.0", "license": "ISC", "devDependencies": { - "@npmcli/eslint-config": "^4.0.1", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "tap": "^16.3.8" }, "engines": { - "node": "^18.17.0 || >=20.5.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "mock-registry": { @@ -228,1906 +309,3802 @@ "version": "1.0.0", "license": "ISC", "devDependencies": { - "@npmcli/arborist": "^7.1.0", - "@npmcli/eslint-config": "^4.0.1", - "@npmcli/template-oss": "4.22.0", + "@npmcli/arborist": "^9.1.2", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "json-stringify-safe": "^5.0.1", - "nock": "^13.3.3", - "npm-package-arg": "^11.0.2", - "pacote": "^18.0.6", + "nock": "^14.0.0", + "npm-package-arg": "^14.0.0", + "pacote": "^22.0.0", "tap": "^16.3.8" }, "engines": { - "node": "^18.17.0 || >=20.5.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, - "node_modules/@actions/core": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.10.1.tgz", - "integrity": "sha512-3lBR9EDAY+iYIpTnTIXmWcNbX3T2kCkAEQGIQx4NVQ0575nk2k3GRZDTPQG+vVtS2izSLmINlxXf0uLtnrTP+g==", + "mock-registry/node_modules/@npmcli/agent": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-4.0.2.tgz", + "integrity": "sha512-EUEuWAxnL07Sp5/iC/1X6Xj+XThUvnbei9zfRWZdEXa7lss9RTHMhAHBeg+MZ5To9s/gGaSI+UwZTPdYMvKSeg==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@actions/http-client": "^2.0.1", - "uuid": "^8.3.2" + "agent-base": "^7.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.1", + "lru-cache": "^11.2.1", + "socks-proxy-agent": "^8.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@actions/http-client": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.1.tgz", - "integrity": "sha512-KhC/cZsq7f8I4LfZSJKgCvEwfkE8o1538VoBeoGzokVLLnbFDEAdFD3UhoMklxo2un9NJVBdANOresx7vTHlHw==", + "mock-registry/node_modules/@npmcli/arborist": { + "version": "9.6.0", + "resolved": "https://registry.npmjs.org/@npmcli/arborist/-/arborist-9.6.0.tgz", + "integrity": "sha512-Dku9UWbrrX+UCu8rQ1obGKaQAL4kwdt3hHCNXrd0n0R/4B8oq3CzloUAShwFjfsAGM6KY27gPuNftOUEZ4nhOw==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "tunnel": "^0.0.6", - "undici": "^5.25.4" + "@gar/promise-retry": "^1.0.0", + "@isaacs/string-locale-compare": "^1.1.0", + "@npmcli/fs": "^5.0.0", + "@npmcli/installed-package-contents": "^4.0.0", + "@npmcli/map-workspaces": "^5.0.0", + "@npmcli/metavuln-calculator": "^9.0.2", + "@npmcli/name-from-folder": "^4.0.0", + "@npmcli/node-gyp": "^5.0.0", + "@npmcli/package-json": "^7.0.0", + "@npmcli/query": "^5.0.0", + "@npmcli/redact": "^4.0.0", + "@npmcli/run-script": "^10.0.0", + "bin-links": "^6.0.0", + "cacache": "^20.0.1", + "common-ancestor-path": "^2.0.0", + "hosted-git-info": "^9.0.0", + "json-stringify-nice": "^1.1.4", + "lru-cache": "^11.2.1", + "minimatch": "^10.0.3", + "nopt": "^9.0.0", + "npm-install-checks": "^8.0.0", + "npm-package-arg": "^13.0.0", + "npm-pick-manifest": "^11.0.1", + "npm-registry-fetch": "^19.0.0", + "pacote": "^21.0.2", + "parse-conflict-json": "^5.0.1", + "proc-log": "^6.0.0", + "proggy": "^4.0.0", + "promise-all-reject-late": "^1.0.0", + "promise-call-limit": "^3.0.1", + "semver": "^7.3.7", + "ssri": "^13.0.0", + "treeverse": "^3.0.0", + "walk-up-path": "^4.0.0" + }, + "bin": { + "arborist": "bin/index.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@actions/http-client/node_modules/undici": { - "version": "5.28.4", - "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.4.tgz", - "integrity": "sha512-72RFADWFqKmUb2hmmvNODKL3p9hcB6Gt2DOQMis1SEBaV6a4MH8soBvzg+95CYhCKPFedut2JY9bMfrDl9D23g==", + "mock-registry/node_modules/@npmcli/arborist/node_modules/npm-package-arg": { + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-13.0.2.tgz", + "integrity": "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@fastify/busboy": "^2.0.0" + "hosted-git-info": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^7.0.0" }, "engines": { - "node": ">=14.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@ampproject/remapping": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", - "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", + "mock-registry/node_modules/@npmcli/arborist/node_modules/pacote": { + "version": "21.5.1", + "resolved": "https://registry.npmjs.org/pacote/-/pacote-21.5.1.tgz", + "integrity": "sha512-KvcJ9iy3crysCsgqc4+PknH/w6jkrp8JN36mpZBPwNaDRwTfMZD37YzRazNstiZUOhuF5pno9f78n9mEJBavwg==", "dev": true, - "license": "Apache-2.0", + "license": "ISC", "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" + "@gar/promise-retry": "^1.0.0", + "@npmcli/git": "^7.0.0", + "@npmcli/installed-package-contents": "^4.0.0", + "@npmcli/package-json": "^7.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "@npmcli/run-script": "^10.0.0", + "cacache": "^20.0.0", + "fs-minipass": "^3.0.0", + "minipass": "^7.0.2", + "npm-package-arg": "^13.0.0", + "npm-packlist": "^10.0.1", + "npm-pick-manifest": "^11.0.1", + "npm-registry-fetch": "^19.0.0", + "proc-log": "^6.0.0", + "sigstore": "^4.0.0", + "ssri": "^13.0.0", + "tar": "^7.4.3" + }, + "bin": { + "pacote": "bin/index.js" }, "engines": { - "node": ">=6.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/code-frame": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", - "integrity": "sha512-BcYH1CVJBO9tvyIZ2jVeXgSIMvGZ2FDRvDdOIVQyuklNKSsx+eppDEBq/g47Ayw+RqNFE+URvOShmf+f/qwAlA==", + "mock-registry/node_modules/@npmcli/fs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-5.0.0.tgz", + "integrity": "sha512-7OsC1gNORBEawOa5+j2pXN9vsicaIOH5cPXxoR6fJOmH6/EXpJB2CajXOu1fPRFun2m1lktEFX11+P89hqO/og==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@babel/highlight": "^7.24.7", - "picocolors": "^1.0.0" + "semver": "^7.3.5" }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/compat-data": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.24.7.tgz", - "integrity": "sha512-qJzAIcv03PyaWqxRgO4mSU3lihncDT296vnyuE2O8uA4w3UHWI4S3hgeZd1L8W1Bft40w9JxJ2b412iDUFFRhw==", + "mock-registry/node_modules/@npmcli/git": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-7.0.2.tgz", + "integrity": "sha512-oeolHDjExNAJAnlYP2qzNjMX/Xi9bmu78C9dIGr4xjobrSKbuMYCph8lTzn4vnW3NjIqVmw/f8BCfouqyJXlRg==", "dev": true, - "license": "MIT", + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "ini": "^6.0.0", + "lru-cache": "^11.2.1", + "npm-pick-manifest": "^11.0.1", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "which": "^6.0.0" + }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/core": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.24.7.tgz", - "integrity": "sha512-nykK+LEK86ahTkX/3TgauT0ikKoNCfKHEaZYTUVupJdTLzGNvrblu4u6fa7DhZONAltdf8e662t/abY8idrd/g==", + "mock-registry/node_modules/@npmcli/installed-package-contents": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/installed-package-contents/-/installed-package-contents-4.0.0.tgz", + "integrity": "sha512-yNyAdkBxB72gtZ4GrwXCM0ZUedo9nIbOMKfGjt6Cu6DXf0p8y1PViZAKDC8q8kv/fufx0WTjRBdSlyrvnP7hmA==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.24.7", - "@babel/generator": "^7.24.7", - "@babel/helper-compilation-targets": "^7.24.7", - "@babel/helper-module-transforms": "^7.24.7", - "@babel/helpers": "^7.24.7", - "@babel/parser": "^7.24.7", - "@babel/template": "^7.24.7", - "@babel/traverse": "^7.24.7", - "@babel/types": "^7.24.7", - "convert-source-map": "^2.0.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.3", - "semver": "^6.3.1" + "npm-bundled": "^5.0.0", + "npm-normalize-package-bin": "^5.0.0" }, - "engines": { - "node": ">=6.9.0" + "bin": { + "installed-package-contents": "bin/index.js" }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" + "engines": { + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/core/node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/core/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "mock-registry/node_modules/@npmcli/map-workspaces": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@npmcli/map-workspaces/-/map-workspaces-5.0.3.tgz", + "integrity": "sha512-o2grssXo1e774E5OtEwwrgoszYRh0lqkJH+Pb9r78UcqdGJRDRfhpM8DvZPjzNLLNYeD/rNbjOKM3Ss5UABROw==", "dev": true, "license": "ISC", - "bin": { - "semver": "bin/semver.js" + "dependencies": { + "@npmcli/name-from-folder": "^4.0.0", + "@npmcli/package-json": "^7.0.0", + "glob": "^13.0.0", + "minimatch": "^10.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/generator": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.24.7.tgz", - "integrity": "sha512-oipXieGC3i45Y1A41t4tAqpnEZWgB/lC6Ehh6+rOviR5XWpTtMmLN+fGjz9vOiNRt0p6RtO6DtD0pdU3vpqdSA==", + "mock-registry/node_modules/@npmcli/metavuln-calculator": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/@npmcli/metavuln-calculator/-/metavuln-calculator-9.0.3.tgz", + "integrity": "sha512-94GLSYhLXF2t2LAC7pDwLaM4uCARzxShyAQKsirmlNcpidH89VA4/+K1LbJmRMgz5gy65E/QBBWQdUvGLe2Frg==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@babel/types": "^7.24.7", - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.25", - "jsesc": "^2.5.1" + "cacache": "^20.0.0", + "json-parse-even-better-errors": "^5.0.0", + "pacote": "^21.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5" }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-compilation-targets": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.24.7.tgz", - "integrity": "sha512-ctSdRHBi20qWOfy27RUb4Fhp07KSJ3sXcuSvTrXrc4aG8NSYDo1ici3Vhg9bg69y5bj0Mr1lh0aeEgTvc12rMg==", + "mock-registry/node_modules/@npmcli/metavuln-calculator/node_modules/npm-package-arg": { + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-13.0.2.tgz", + "integrity": "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@babel/compat-data": "^7.24.7", - "@babel/helper-validator-option": "^7.24.7", - "browserslist": "^4.22.2", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" + "hosted-git-info": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^7.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "mock-registry/node_modules/@npmcli/metavuln-calculator/node_modules/pacote": { + "version": "21.5.1", + "resolved": "https://registry.npmjs.org/pacote/-/pacote-21.5.1.tgz", + "integrity": "sha512-KvcJ9iy3crysCsgqc4+PknH/w6jkrp8JN36mpZBPwNaDRwTfMZD37YzRazNstiZUOhuF5pno9f78n9mEJBavwg==", "dev": true, "license": "ISC", "dependencies": { - "yallist": "^3.0.2" + "@gar/promise-retry": "^1.0.0", + "@npmcli/git": "^7.0.0", + "@npmcli/installed-package-contents": "^4.0.0", + "@npmcli/package-json": "^7.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "@npmcli/run-script": "^10.0.0", + "cacache": "^20.0.0", + "fs-minipass": "^3.0.0", + "minipass": "^7.0.2", + "npm-package-arg": "^13.0.0", + "npm-packlist": "^10.0.1", + "npm-pick-manifest": "^11.0.1", + "npm-registry-fetch": "^19.0.0", + "proc-log": "^6.0.0", + "sigstore": "^4.0.0", + "ssri": "^13.0.0", + "tar": "^7.4.3" + }, + "bin": { + "pacote": "bin/index.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-compilation-targets/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "mock-registry/node_modules/@npmcli/name-from-folder": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/name-from-folder/-/name-from-folder-4.0.0.tgz", + "integrity": "sha512-qfrhVlOSqmKM8i6rkNdZzABj8MKEITGFAY+4teqBziksCQAOLutiAxM1wY2BKEd8KjUSpWmWCYxvXr0y4VTlPg==", "dev": true, "license": "ISC", - "bin": { - "semver": "bin/semver.js" + "engines": { + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-compilation-targets/node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "mock-registry/node_modules/@npmcli/node-gyp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/node-gyp/-/node-gyp-5.0.0.tgz", + "integrity": "sha512-uuG5HZFXLfyFKqg8QypsmgLQW7smiRjVc45bqD/ofZZcR/uxEjgQU8qDPv0s9TEeMUiAAU/GC5bR6++UdTirIQ==", "dev": true, - "license": "ISC" + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } }, - "node_modules/@babel/helper-environment-visitor": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.24.7.tgz", - "integrity": "sha512-DoiN84+4Gnd0ncbBOM9AZENV4a5ZiL39HYMyZJGZ/AZEykHYdJw0wW3kdcsh9/Kn+BRXHLkkklZ51ecPKmI1CQ==", + "mock-registry/node_modules/@npmcli/package-json": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/@npmcli/package-json/-/package-json-7.0.5.tgz", + "integrity": "sha512-iVuTlG3ORq2iaVa1IWUxAO/jIp77tUKBhoMjuzYW2kL4MLN1bi/ofqkZ7D7OOwh8coAx1/S2ge0rMdGv8sLSOQ==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@babel/types": "^7.24.7" + "@npmcli/git": "^7.0.0", + "glob": "^13.0.0", + "hosted-git-info": "^9.0.0", + "json-parse-even-better-errors": "^5.0.0", + "proc-log": "^6.0.0", + "semver": "^7.5.3", + "spdx-expression-parse": "^4.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-function-name": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.24.7.tgz", - "integrity": "sha512-FyoJTsj/PEUWu1/TYRiXTIHc8lbw+TDYkZuoE43opPS5TrI7MyONBE1oNvfguEXAD9yhQRrVBnXdXzSLQl9XnA==", + "mock-registry/node_modules/@npmcli/promise-spawn": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/@npmcli/promise-spawn/-/promise-spawn-9.0.1.tgz", + "integrity": "sha512-OLUaoqBuyxeTqUvjA3FZFiXUfYC1alp3Sa99gW3EUDz3tZ3CbXDdcZ7qWKBzicrJleIgucoWamWH1saAmH/l2Q==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@babel/template": "^7.24.7", - "@babel/types": "^7.24.7" + "which": "^6.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-hoist-variables": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.24.7.tgz", - "integrity": "sha512-MJJwhkoGy5c4ehfoRyrJ/owKeMl19U54h27YYftT0o2teQ3FJ3nQUf/I3LlJsX4l3qlw7WRXUmiyajvHXoTubQ==", + "mock-registry/node_modules/@npmcli/redact": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-4.0.0.tgz", + "integrity": "sha512-gOBg5YHMfZy+TfHArfVogwgfBeQnKbbGo3pSUyK/gSI0AVu+pEiDVcKlQb0D8Mg1LNRZILZ6XG8I5dJ4KuAd9Q==", "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.24.7" - }, + "license": "ISC", "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-module-imports": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.24.7.tgz", - "integrity": "sha512-8AyH3C+74cgCVVXow/myrynrAGv+nTVg5vKu2nZph9x7RcRwzmh0VFallJuFTZ9mx6u4eSdXZfcOzSqTUm0HCA==", + "mock-registry/node_modules/@npmcli/run-script": { + "version": "10.0.4", + "resolved": "https://registry.npmjs.org/@npmcli/run-script/-/run-script-10.0.4.tgz", + "integrity": "sha512-mGUWr1uMnf0le2TwfOZY4SFxZGXGfm4Jtay/nwAa2FLNAKXUoUwaGwBMNH36UHPtinWfTSJ3nqFQr0091CxVGg==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@babel/traverse": "^7.24.7", - "@babel/types": "^7.24.7" + "@npmcli/node-gyp": "^5.0.0", + "@npmcli/package-json": "^7.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "node-gyp": "^12.1.0", + "proc-log": "^6.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-module-transforms": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.24.7.tgz", - "integrity": "sha512-1fuJEwIrp+97rM4RWdO+qrRsZlAeL1lQJoPqtCYWv0NL115XM93hIH4CSRln2w52SqvmY5hqdtauB6QFCDiZNQ==", + "mock-registry/node_modules/abbrev": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz", + "integrity": "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==", "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-environment-visitor": "^7.24.7", - "@babel/helper-module-imports": "^7.24.7", - "@babel/helper-simple-access": "^7.24.7", - "@babel/helper-split-export-declaration": "^7.24.7", - "@babel/helper-validator-identifier": "^7.24.7" - }, + "license": "ISC", "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-simple-access": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.24.7.tgz", - "integrity": "sha512-zBAIvbCMh5Ts+b86r/CjU+4XGYIs+R1j951gxI3KmmxBMhCg4oQMsv6ZXQ64XOm/cvzfU1FmoCyt6+owc5QMYg==", + "mock-registry/node_modules/bin-links": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/bin-links/-/bin-links-6.0.2.tgz", + "integrity": "sha512-frE1t78WOwJ45PKV2cF2tNPjTcs9L1J9s6VkrV59wanRP4GlaomuxYPVma7BwthMg8WnfSory4w5PTE6FZZ81w==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@babel/traverse": "^7.24.7", - "@babel/types": "^7.24.7" + "cmd-shim": "^8.0.0", + "npm-normalize-package-bin": "^5.0.0", + "proc-log": "^6.0.0", + "read-cmd-shim": "^6.0.0", + "write-file-atomic": "^7.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-split-export-declaration": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.24.7.tgz", - "integrity": "sha512-oy5V7pD+UvfkEATUKvIjvIAH/xCzfsFVw7ygW2SI6NClZzquT+mwdTfgfdbUiceh6iQO0CHtCPsyze/MZ2YbAA==", + "mock-registry/node_modules/cacache": { + "version": "20.0.4", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-20.0.4.tgz", + "integrity": "sha512-M3Lab8NPYlZU2exsL3bMVvMrMqgwCnMWfdZbK28bn3pK6APT/Te/I8hjRPNu1uwORY9a1eEQoifXbKPQMfMTOA==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@babel/types": "^7.24.7" + "@npmcli/fs": "^5.0.0", + "fs-minipass": "^3.0.0", + "glob": "^13.0.0", + "lru-cache": "^11.1.0", + "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": "^13.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-string-parser": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.24.7.tgz", - "integrity": "sha512-7MbVt6xrwFQbunH2DNQsAP5sTGxfqQtErvBIvIMi6EQnbgUOuVYanvREcmFrOPhoXBrTtjhhP+lW+o5UfK+tDg==", + "mock-registry/node_modules/hosted-git-info": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz", + "integrity": "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==", "dev": true, - "license": "MIT", + "license": "ISC", + "dependencies": { + "lru-cache": "^11.1.0" + }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz", - "integrity": "sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==", + "mock-registry/node_modules/ini": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-6.0.0.tgz", + "integrity": "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==", "dev": true, - "license": "MIT", + "license": "ISC", "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helper-validator-option": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.24.7.tgz", - "integrity": "sha512-yy1/KvjhV/ZCL+SM7hBrvnZJ3ZuT9OuZgIJAGpPEToANvc3iM6iDvBnRjtElWibHU6n8/LPR/EjX9EtIEYO3pw==", + "mock-registry/node_modules/json-parse-even-better-errors": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-5.0.0.tgz", + "integrity": "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ==", "dev": true, "license": "MIT", "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/helpers": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.24.7.tgz", - "integrity": "sha512-NlmJJtvcw72yRJRcnCmGvSi+3jDEg8qFu3z0AFoymmzLx5ERVWyzd9kVXr7Th9/8yIJi2Zc6av4Tqz3wFs8QWg==", + "mock-registry/node_modules/make-fetch-happen": { + "version": "15.0.6", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-15.0.6.tgz", + "integrity": "sha512-Je0fLJ0F5atA7F+eIlLzk+Wkcl57JDf4kf+EW8xiP5E31xOQxkIxTbgf1Oi1Lw9tRI9UEMRdI5Vz2xTzoNU1Jw==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@babel/template": "^7.24.7", - "@babel/types": "^7.24.7" + "@gar/promise-retry": "^1.0.0", + "@npmcli/agent": "^4.0.0", + "@npmcli/redact": "^4.0.0", + "cacache": "^20.0.1", + "http-cache-semantics": "^4.1.1", + "minipass": "^7.0.2", + "minipass-fetch": "^5.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^1.0.0", + "proc-log": "^6.0.0", + "ssri": "^13.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/highlight": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.7.tgz", - "integrity": "sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==", + "mock-registry/node_modules/node-gyp": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.4.0.tgz", + "integrity": "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^7.24.7", - "chalk": "^2.4.2", - "js-tokens": "^4.0.0", - "picocolors": "^1.0.0" - }, - "engines": { - "node": ">=6.9.0" + "env-paths": "^2.2.0", + "exponential-backoff": "^3.1.1", + "graceful-fs": "^4.2.6", + "nopt": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "tar": "^7.5.4", + "tinyglobby": "^0.2.12", + "undici": "^6.25.0", + "which": "^6.0.0" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/highlight/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "mock-registry/node_modules/nopt": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz", + "integrity": "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "color-convert": "^1.9.0" + "abbrev": "^4.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" }, "engines": { - "node": ">=4" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/highlight/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "mock-registry/node_modules/npm-install-checks": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/npm-install-checks/-/npm-install-checks-8.0.0.tgz", + "integrity": "sha512-ScAUdMpyzkbpxoNekQ3tNRdFI8SJ86wgKZSQZdUxT+bj0wVFpsEMWnkXP0twVe1gJyNF5apBWDJhhIbgrIViRA==", "dev": true, - "license": "MIT", + "license": "BSD-2-Clause", "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" + "semver": "^7.1.1" }, "engines": { - "node": ">=4" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/highlight/node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "mock-registry/node_modules/npm-packlist": { + "version": "10.0.4", + "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-10.0.4.tgz", + "integrity": "sha512-uMW73iajD8hiH4ZBxEV3HC+eTnppIqwakjOYuvgddnalIw2lJguKviK1pcUJDlIWm1wSJkchpDZDSVVsZEYRng==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "color-name": "1.1.3" + "ignore-walk": "^8.0.0", + "proc-log": "^6.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/highlight/node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/highlight/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "mock-registry/node_modules/npm-pick-manifest": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/npm-pick-manifest/-/npm-pick-manifest-11.0.3.tgz", + "integrity": "sha512-buzyCfeoGY/PxKqmBqn1IUJrZnUi1VVJTdSSRPGI60tJdUhUoSQFhs0zycJokDdOznQentgrpf8LayEHyyYlqQ==", "dev": true, - "license": "MIT", + "license": "ISC", + "dependencies": { + "npm-install-checks": "^8.0.0", + "npm-normalize-package-bin": "^5.0.0", + "npm-package-arg": "^13.0.0", + "semver": "^7.3.5" + }, "engines": { - "node": ">=0.8.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/highlight/node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "mock-registry/node_modules/npm-pick-manifest/node_modules/npm-package-arg": { + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-13.0.2.tgz", + "integrity": "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "has-flag": "^3.0.0" + "hosted-git-info": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^7.0.0" }, "engines": { - "node": ">=4" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/parser": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.24.7.tgz", - "integrity": "sha512-9uUYRm6OqQrCqQdG1iCBwBPZgN8ciDBro2nIOFaiRz1/BCxaI7CNvQbDHvsArAC7Tw9Hda/B3U+6ui9u4HWXPw==", + "mock-registry/node_modules/npm-registry-fetch": { + "version": "19.1.1", + "resolved": "https://registry.npmjs.org/npm-registry-fetch/-/npm-registry-fetch-19.1.1.tgz", + "integrity": "sha512-TakBap6OM1w0H73VZVDf44iFXsOS3h+L4wVMXmbWOQroZgFhMch0juN6XSzBNlD965yIKvWg2dfu7NSiaYLxtw==", "dev": true, - "license": "MIT", - "bin": { - "parser": "bin/babel-parser.js" + "license": "ISC", + "dependencies": { + "@npmcli/redact": "^4.0.0", + "jsonparse": "^1.3.1", + "make-fetch-happen": "^15.0.0", + "minipass": "^7.0.2", + "minipass-fetch": "^5.0.0", + "minizlib": "^3.0.1", + "npm-package-arg": "^13.0.0", + "proc-log": "^6.0.0" }, "engines": { - "node": ">=6.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/template": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.24.7.tgz", - "integrity": "sha512-jYqfPrU9JTF0PmPy1tLYHW4Mp4KlgxJD9l2nP9fD6yT/ICi554DmrWBAEYpIelzjHf1msDP3PxJIRt/nFNfBig==", + "mock-registry/node_modules/npm-registry-fetch/node_modules/npm-package-arg": { + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-13.0.2.tgz", + "integrity": "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@babel/code-frame": "^7.24.7", - "@babel/parser": "^7.24.7", - "@babel/types": "^7.24.7" + "hosted-git-info": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^7.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/traverse": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.24.7.tgz", - "integrity": "sha512-yb65Ed5S/QAcewNPh0nZczy9JdYXkkAbIsEo+P7BE7yO3txAY30Y/oPa3QkQ5It3xVG2kpKMg9MsdxZaO31uKA==", + "mock-registry/node_modules/parse-conflict-json": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/parse-conflict-json/-/parse-conflict-json-5.0.1.tgz", + "integrity": "sha512-ZHEmNKMq1wyJXNwLxyHnluPfRAFSIliBvbK/UiOceROt4Xh9Pz0fq49NytIaeaCUf5VR86hwQ/34FCcNU5/LKQ==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@babel/code-frame": "^7.24.7", - "@babel/generator": "^7.24.7", - "@babel/helper-environment-visitor": "^7.24.7", - "@babel/helper-function-name": "^7.24.7", - "@babel/helper-hoist-variables": "^7.24.7", - "@babel/helper-split-export-declaration": "^7.24.7", - "@babel/parser": "^7.24.7", - "@babel/types": "^7.24.7", - "debug": "^4.3.1", - "globals": "^11.1.0" + "json-parse-even-better-errors": "^5.0.0", + "just-diff": "^6.0.0", + "just-diff-apply": "^5.2.0" }, "engines": { - "node": ">=6.9.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/traverse/node_modules/globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "mock-registry/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", "dev": true, - "license": "MIT", + "license": "ISC", "engines": { - "node": ">=4" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@babel/types": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.24.7.tgz", - "integrity": "sha512-XEFXSlxiG5td2EJRe8vOmRbaXVgfcBlszKujvVmWIK/UpywWljQCfzAv3RQCGujWQ1RD4YYWEAqDXfuJiy8f5Q==", + "mock-registry/node_modules/socks-proxy-agent": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^7.24.7", - "@babel/helper-validator-identifier": "^7.24.7", - "to-fast-properties": "^2.0.0" + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" }, "engines": { - "node": ">=6.9.0" + "node": ">= 14" } }, - "node_modules/@colors/colors": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", - "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==", + "mock-registry/node_modules/ssri": { + "version": "13.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-13.0.1.tgz", + "integrity": "sha512-QUiRf1+u9wPTL/76GTYlKttDEBWV1ga9ZXW8BG6kfdeyyM8LGPix9gROyg9V2+P0xNyF3X2Go526xKFdMZrHSQ==", "dev": true, - "license": "MIT", - "optional": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, "engines": { - "node": ">=0.1.90" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@commitlint/cli": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/@commitlint/cli/-/cli-19.3.0.tgz", - "integrity": "sha512-LgYWOwuDR7BSTQ9OLZ12m7F/qhNY+NpAyPBgo4YNMkACE7lGuUnuQq1yi9hz1KA4+3VqpOYl8H1rY/LYK43v7g==", + "mock-registry/node_modules/validate-npm-package-name": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-7.0.2.tgz", + "integrity": "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A==", "dev": true, - "license": "MIT", + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "mock-registry/node_modules/which": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", + "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==", + "dev": true, + "license": "ISC", "dependencies": { - "@commitlint/format": "^19.3.0", - "@commitlint/lint": "^19.2.2", - "@commitlint/load": "^19.2.0", - "@commitlint/read": "^19.2.1", - "@commitlint/types": "^19.0.3", - "execa": "^8.0.1", - "yargs": "^17.0.0" + "isexe": "^4.0.0" }, "bin": { - "commitlint": "cli.js" + "node-which": "bin/which.js" }, "engines": { - "node": ">=v18" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@commitlint/config-conventional": { - "version": "19.2.2", - "resolved": "https://registry.npmjs.org/@commitlint/config-conventional/-/config-conventional-19.2.2.tgz", - "integrity": "sha512-mLXjsxUVLYEGgzbxbxicGPggDuyWNkf25Ht23owXIH+zV2pv1eJuzLK3t1gDY5Gp6pxdE60jZnWUY5cvgL3ufw==", + "node_modules/@actions/core": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-2.0.3.tgz", + "integrity": "sha512-Od9Thc3T1mQJYddvVPM4QGiLUewdh+3txmDYHHxoNdkqysR1MbCT+rFOtNUxYAz+7+6RIsqipVahY2GJqGPyxA==", "dev": true, "license": "MIT", "dependencies": { - "@commitlint/types": "^19.0.3", - "conventional-changelog-conventionalcommits": "^7.0.2" - }, - "engines": { - "node": ">=v18" + "@actions/exec": "^2.0.0", + "@actions/http-client": "^3.0.2" } }, - "node_modules/@commitlint/config-validator": { - "version": "19.0.3", - "resolved": "https://registry.npmjs.org/@commitlint/config-validator/-/config-validator-19.0.3.tgz", - "integrity": "sha512-2D3r4PKjoo59zBc2auodrSCaUnCSALCx54yveOFwwP/i2kfEAQrygwOleFWswLqK0UL/F9r07MFi5ev2ohyM4Q==", + "node_modules/@actions/exec": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@actions/exec/-/exec-2.0.0.tgz", + "integrity": "sha512-k8ngrX2voJ/RIN6r9xB82NVqKpnMRtxDoiO+g3olkIUpQNqjArXrCQceduQZCQj3P3xm32pChRLqRrtXTlqhIw==", "dev": true, "license": "MIT", "dependencies": { - "@commitlint/types": "^19.0.3", - "ajv": "^8.11.0" - }, - "engines": { - "node": ">=v18" + "@actions/io": "^2.0.0" } }, - "node_modules/@commitlint/ensure": { - "version": "19.0.3", - "resolved": "https://registry.npmjs.org/@commitlint/ensure/-/ensure-19.0.3.tgz", - "integrity": "sha512-SZEpa/VvBLoT+EFZVb91YWbmaZ/9rPH3ESrINOl0HD2kMYsjvl0tF7nMHh0EpTcv4+gTtZBAe1y/SS6/OhfZzQ==", + "node_modules/@actions/http-client": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-3.0.2.tgz", + "integrity": "sha512-JP38FYYpyqvUsz+Igqlc/JG6YO9PaKuvqjM3iGvaLqFnJ7TFmcLyy2IDrY0bI0qCQug8E9K+elv5ZNfw62ZJzA==", "dev": true, "license": "MIT", "dependencies": { - "@commitlint/types": "^19.0.3", - "lodash.camelcase": "^4.3.0", - "lodash.kebabcase": "^4.1.1", - "lodash.snakecase": "^4.1.1", - "lodash.startcase": "^4.4.0", - "lodash.upperfirst": "^4.3.1" - }, - "engines": { - "node": ">=v18" + "tunnel": "^0.0.6", + "undici": "^6.23.0" } }, - "node_modules/@commitlint/execute-rule": { - "version": "19.0.0", - "resolved": "https://registry.npmjs.org/@commitlint/execute-rule/-/execute-rule-19.0.0.tgz", - "integrity": "sha512-mtsdpY1qyWgAO/iOK0L6gSGeR7GFcdW7tIjcNFxcWkfLDF5qVbPHKuGATFqRMsxcO8OUKNj0+3WOHB7EHm4Jdw==", + "node_modules/@actions/io": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@actions/io/-/io-2.0.0.tgz", + "integrity": "sha512-Jv33IN09XLO+0HS79aaODsvIRyduiF7NY/F6LYeK5oeUmrsz7aFdRphQjFoESF4jS7lMauDOttKALcpapVDIAg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@asamuzakjp/css-color": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-4.1.1.tgz", + "integrity": "sha512-B0Hv6G3gWGMn0xKJ0txEi/jM5iFpT3MfDxmhZFb4W047GvytCf1DHQ1D69W3zHI4yWe2aTZAA0JnbMZ7Xc8DuQ==", "dev": true, "license": "MIT", - "engines": { - "node": ">=v18" + "dependencies": { + "@csstools/css-calc": "^2.1.4", + "@csstools/css-color-parser": "^3.1.0", + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4", + "lru-cache": "^11.2.4" } }, - "node_modules/@commitlint/format": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/@commitlint/format/-/format-19.3.0.tgz", - "integrity": "sha512-luguk5/aF68HiF4H23ACAfk8qS8AHxl4LLN5oxPc24H+2+JRPsNr1OS3Gaea0CrH7PKhArBMKBz5RX9sA5NtTg==", + "node_modules/@asamuzakjp/dom-selector": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-6.8.1.tgz", + "integrity": "sha512-MvRz1nCqW0fsy8Qz4dnLIvhOlMzqDVBabZx6lH+YywFDdjXhMY37SmpV1XFX3JzG5GWHn63j6HX6QPr3lZXHvQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/nwsapi": "^2.3.9", + "bidi-js": "^1.0.3", + "css-tree": "^3.1.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.2.6" + } + }, + "node_modules/@asamuzakjp/nwsapi": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz", + "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", "dev": true, "license": "MIT", "dependencies": { - "@commitlint/types": "^19.0.3", - "chalk": "^5.3.0" + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" }, "engines": { - "node": ">=v18" + "node": ">=6.9.0" } }, - "node_modules/@commitlint/is-ignored": { - "version": "19.2.2", - "resolved": "https://registry.npmjs.org/@commitlint/is-ignored/-/is-ignored-19.2.2.tgz", - "integrity": "sha512-eNX54oXMVxncORywF4ZPFtJoBm3Tvp111tg1xf4zWXGfhBPKpfKG6R+G3G4v5CPlRROXpAOpQ3HMhA9n1Tck1g==", + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", "dev": true, "license": "MIT", - "dependencies": { - "@commitlint/types": "^19.0.3", - "semver": "^7.6.0" + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" }, "engines": { - "node": ">=v18" + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" } }, - "node_modules/@commitlint/lint": { - "version": "19.2.2", - "resolved": "https://registry.npmjs.org/@commitlint/lint/-/lint-19.2.2.tgz", - "integrity": "sha512-xrzMmz4JqwGyKQKTpFzlN0dx0TAiT7Ran1fqEBgEmEj+PU98crOFtysJgY+QdeSagx6EDRigQIXJVnfrI0ratA==", + "node_modules/@babel/core/node_modules/convert-source-map": { + "version": "2.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.1", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz", + "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==", "dev": true, "license": "MIT", "dependencies": { - "@commitlint/is-ignored": "^19.2.2", - "@commitlint/parse": "^19.0.3", - "@commitlint/rules": "^19.0.3", - "@commitlint/types": "^19.0.3" + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" }, "engines": { - "node": ">=v18" + "node": ">=6.9.0" } }, - "node_modules/@commitlint/load": { - "version": "19.2.0", - "resolved": "https://registry.npmjs.org/@commitlint/load/-/load-19.2.0.tgz", - "integrity": "sha512-XvxxLJTKqZojCxaBQ7u92qQLFMMZc4+p9qrIq/9kJDy8DOrEa7P1yx7Tjdc2u2JxIalqT4KOGraVgCE7eCYJyQ==", + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", "dev": true, "license": "MIT", "dependencies": { - "@commitlint/config-validator": "^19.0.3", - "@commitlint/execute-rule": "^19.0.0", - "@commitlint/resolve-extends": "^19.1.0", - "@commitlint/types": "^19.0.3", - "chalk": "^5.3.0", - "cosmiconfig": "^9.0.0", - "cosmiconfig-typescript-loader": "^5.0.0", - "lodash.isplainobject": "^4.0.6", - "lodash.merge": "^4.6.2", - "lodash.uniq": "^4.5.0" + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" }, "engines": { - "node": ">=v18" + "node": ">=6.9.0" } }, - "node_modules/@commitlint/message": { - "version": "19.0.0", - "resolved": "https://registry.npmjs.org/@commitlint/message/-/message-19.0.0.tgz", - "integrity": "sha512-c9czf6lU+9oF9gVVa2lmKaOARJvt4soRsVmbR7Njwp9FpbBgste5i7l/2l5o8MmbwGh4yE1snfnsy2qyA2r/Fw==", + "node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": { + "version": "5.1.1", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.1", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/yallist": { + "version": "3.1.1", + "dev": true, + "license": "ISC" + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", "dev": true, "license": "MIT", "engines": { - "node": ">=v18" + "node": ">=6.9.0" } }, - "node_modules/@commitlint/parse": { - "version": "19.0.3", - "resolved": "https://registry.npmjs.org/@commitlint/parse/-/parse-19.0.3.tgz", - "integrity": "sha512-Il+tNyOb8VDxN3P6XoBBwWJtKKGzHlitEuXA5BP6ir/3loWlsSqDr5aecl6hZcC/spjq4pHqNh0qPlfeWu38QA==", + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", "dev": true, "license": "MIT", "dependencies": { - "@commitlint/types": "^19.0.3", - "conventional-changelog-angular": "^7.0.0", - "conventional-commits-parser": "^5.0.0" + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" }, "engines": { - "node": ">=v18" + "node": ">=6.9.0" } }, - "node_modules/@commitlint/read": { - "version": "19.2.1", - "resolved": "https://registry.npmjs.org/@commitlint/read/-/read-19.2.1.tgz", - "integrity": "sha512-qETc4+PL0EUv7Q36lJbPG+NJiBOGg7SSC7B5BsPWOmei+Dyif80ErfWQ0qXoW9oCh7GTpTNRoaVhiI8RbhuaNw==", + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", "dev": true, "license": "MIT", "dependencies": { - "@commitlint/top-level": "^19.0.0", - "@commitlint/types": "^19.0.3", - "execa": "^8.0.1", - "git-raw-commits": "^4.0.0", - "minimist": "^1.2.8" + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" }, "engines": { - "node": ">=v18" + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" } }, - "node_modules/@commitlint/resolve-extends": { - "version": "19.1.0", - "resolved": "https://registry.npmjs.org/@commitlint/resolve-extends/-/resolve-extends-19.1.0.tgz", - "integrity": "sha512-z2riI+8G3CET5CPgXJPlzftH+RiWYLMYv4C9tSLdLXdr6pBNimSKukYP9MS27ejmscqCTVA4almdLh0ODD2KYg==", + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", "dev": true, "license": "MIT", - "dependencies": { - "@commitlint/config-validator": "^19.0.3", - "@commitlint/types": "^19.0.3", - "global-directory": "^4.0.1", - "import-meta-resolve": "^4.0.0", - "lodash.mergewith": "^4.6.2", - "resolve-from": "^5.0.0" - }, "engines": { - "node": ">=v18" + "node": ">=6.9.0" } }, - "node_modules/@commitlint/rules": { - "version": "19.0.3", - "resolved": "https://registry.npmjs.org/@commitlint/rules/-/rules-19.0.3.tgz", - "integrity": "sha512-TspKb9VB6svklxNCKKwxhELn7qhtY1rFF8ls58DcFd0F97XoG07xugPjjbVnLqmMkRjZDbDIwBKt9bddOfLaPw==", + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", "dev": true, "license": "MIT", - "dependencies": { - "@commitlint/ensure": "^19.0.3", - "@commitlint/message": "^19.0.0", - "@commitlint/to-lines": "^19.0.0", - "@commitlint/types": "^19.0.3", - "execa": "^8.0.1" - }, "engines": { - "node": ">=v18" + "node": ">=6.9.0" } }, - "node_modules/@commitlint/to-lines": { - "version": "19.0.0", - "resolved": "https://registry.npmjs.org/@commitlint/to-lines/-/to-lines-19.0.0.tgz", - "integrity": "sha512-vkxWo+VQU5wFhiP9Ub9Sre0FYe019JxFikrALVoD5UGa8/t3yOJEpEhxC5xKiENKKhUkTpEItMTRAjHw2SCpZw==", + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", "dev": true, "license": "MIT", "engines": { - "node": ">=v18" + "node": ">=6.9.0" } }, - "node_modules/@commitlint/top-level": { - "version": "19.0.0", - "resolved": "https://registry.npmjs.org/@commitlint/top-level/-/top-level-19.0.0.tgz", - "integrity": "sha512-KKjShd6u1aMGNkCkaX4aG1jOGdn7f8ZI8TR1VEuNqUOjWTOdcDSsmglinglJ18JTjuBX5I1PtjrhQCRcixRVFQ==", + "node_modules/@babel/helpers": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", + "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", "dev": true, "license": "MIT", "dependencies": { - "find-up": "^7.0.0" + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.7" }, "engines": { - "node": ">=v18" + "node": ">=6.9.0" } }, - "node_modules/@commitlint/types": { - "version": "19.0.3", - "resolved": "https://registry.npmjs.org/@commitlint/types/-/types-19.0.3.tgz", - "integrity": "sha512-tpyc+7i6bPG9mvaBbtKUeghfyZSDgWquIDfMgqYtTbmZ9Y9VzEm2je9EYcQ0aoz5o7NvGS+rcDec93yO08MHYA==", + "node_modules/@babel/parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz", + "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==", "dev": true, "license": "MIT", "dependencies": { - "@types/conventional-commits-parser": "^5.0.0", - "chalk": "^5.3.0" + "@babel/types": "^7.29.7" + }, + "bin": { + "parser": "bin/babel-parser.js" }, "engines": { - "node": ">=v18" + "node": ">=6.0.0" } }, - "node_modules/@conventional-commits/parser": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@conventional-commits/parser/-/parser-0.4.1.tgz", - "integrity": "sha512-H2ZmUVt6q+KBccXfMBhbBF14NlANeqHTXL4qCL6QGbMzrc4HDXyzWuxPxPNbz71f/5UkR5DrycP5VO9u7crahg==", + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", "dev": true, - "license": "ISC", + "license": "MIT", "dependencies": { - "unist-util-visit": "^2.0.3", - "unist-util-visit-parents": "^3.1.1" + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" } }, - "node_modules/@eslint-community/eslint-utils": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", - "integrity": "sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==", + "node_modules/@babel/traverse": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz", + "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { - "eslint-visitor-keys": "^3.3.0" + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.7", + "debug": "^4.3.1" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + "node": ">=6.9.0" } }, - "node_modules/@eslint-community/regexpp": { - "version": "4.10.1", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.10.1.tgz", - "integrity": "sha512-Zm2NGpWELsQAD1xsJzGQpYfvICSsFkEpU0jxBjfdC6uNEWXcHnfs9hScFWtXVDVl+rBQJGrl4g1vcKIejpH9dA==", + "node_modules/@babel/types": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz", + "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==", "dev": true, "license": "MIT", - "peer": true, + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, "engines": { - "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + "node": ">=6.9.0" } }, - "node_modules/@eslint/eslintrc": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", - "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", + "node_modules/@colors/colors": { + "version": "1.5.0", "dev": true, "license": "MIT", - "peer": true, - "dependencies": { - "ajv": "^6.12.4", - "debug": "^4.3.2", - "espree": "^9.6.0", - "globals": "^13.19.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.1.0", - "minimatch": "^3.1.2", - "strip-json-comments": "^3.1.1" - }, + "optional": true, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" + "node": ">=0.1.90" } }, - "node_modules/@eslint/eslintrc/node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "node_modules/@commitlint/cli": { + "version": "20.5.3", + "resolved": "https://registry.npmjs.org/@commitlint/cli/-/cli-20.5.3.tgz", + "integrity": "sha512-OJdL0EXWD5y9LPa0nr/geOwzaS8BsdaybKkcloB0JgsguGxNv2R+hC2FTPqrAcprg35zF33KOQerY0x8W1aesA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" + "@commitlint/format": "^20.5.0", + "@commitlint/lint": "^20.5.3", + "@commitlint/load": "^20.5.3", + "@commitlint/read": "^20.5.0", + "@commitlint/types": "^20.5.0", + "tinyexec": "^1.0.0", + "yargs": "^17.0.0" }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" + "bin": { + "commitlint": "cli.js" + }, + "engines": { + "node": ">=v18" } }, - "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "node_modules/@commitlint/config-conventional": { + "version": "20.5.3", + "resolved": "https://registry.npmjs.org/@commitlint/config-conventional/-/config-conventional-20.5.3.tgz", + "integrity": "sha512-j34Qqeaa152chJgz2ysyk0BCpHenJn1lV0Rx0VXf8k3ccQcED+48EZrzMvo9jLmJUyBrrBwvu89I+2er4gW7QQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" + "@commitlint/types": "^20.5.0", + "conventional-changelog-conventionalcommits": "^9.2.0" + }, + "engines": { + "node": ">=v18" } }, - "node_modules/@eslint/eslintrc/node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "node_modules/@commitlint/config-validator": { + "version": "20.5.0", + "resolved": "https://registry.npmjs.org/@commitlint/config-validator/-/config-validator-20.5.0.tgz", + "integrity": "sha512-T/Uh6iJUzyx7j35GmHWdIiGRQB+ouZDk0pwAaYq4SXgB54KZhFdJ0vYmxiW6AMYICTIWuyMxDBl1jK74oFp/Gw==", "dev": true, "license": "MIT", - "peer": true - }, - "node_modules/@eslint/eslintrc/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "license": "ISC", - "peer": true, "dependencies": { - "brace-expansion": "^1.1.7" + "@commitlint/types": "^20.5.0", + "ajv": "^8.11.0" }, "engines": { - "node": "*" + "node": ">=v18" } }, - "node_modules/@eslint/js": { - "version": "8.57.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.0.tgz", - "integrity": "sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==", + "node_modules/@commitlint/ensure": { + "version": "20.5.3", + "resolved": "https://registry.npmjs.org/@commitlint/ensure/-/ensure-20.5.3.tgz", + "integrity": "sha512-4i4AgNvH62owG9MwSiWKrle7HGNpBHHdLnWFIp5fTsHUYe5kRuh15t08L/0pdbbrRk8JKXQxxN4hZQcn+szkrw==", "dev": true, "license": "MIT", - "peer": true, + "dependencies": { + "@commitlint/types": "^20.5.0", + "es-toolkit": "^1.46.0" + }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": ">=v18" } }, - "node_modules/@fastify/busboy": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz", - "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==", + "node_modules/@commitlint/execute-rule": { + "version": "20.0.0", + "resolved": "https://registry.npmjs.org/@commitlint/execute-rule/-/execute-rule-20.0.0.tgz", + "integrity": "sha512-xyCoOShoPuPL44gVa+5EdZsBVao/pNzpQhkzq3RdtlFdKZtjWcLlUFQHSWBuhk5utKYykeJPSz2i8ABHQA+ZZw==", "dev": true, "license": "MIT", "engines": { - "node": ">=14" + "node": ">=v18" } }, - "node_modules/@google-automations/git-file-utils": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@google-automations/git-file-utils/-/git-file-utils-2.0.0.tgz", - "integrity": "sha512-F6h8npq7rt60fr3W+cil/zXbIiF9Hj8JzaN3LNh7uBIJpsWnjL9ObV84qW/345boMheDdo/n+cItmvCfsn0lLA==", + "node_modules/@commitlint/format": { + "version": "20.5.0", + "resolved": "https://registry.npmjs.org/@commitlint/format/-/format-20.5.0.tgz", + "integrity": "sha512-TI9EwFU/qZWSK7a5qyXMpKPPv3qta7FO4tKW+Wt2al7sgMbLWTsAcDpX1cU8k16TRdsiiet9aOw0zpvRXNJu7Q==", "dev": true, - "license": "Apache-2.0", + "license": "MIT", "dependencies": { - "@octokit/rest": "^19.0.7", - "@octokit/types": "^9.0.0", - "minimatch": "^5.1.0" + "@commitlint/types": "^20.5.0", + "picocolors": "^1.1.1" }, "engines": { - "node": ">= 18" + "node": ">=v18" } }, - "node_modules/@google-automations/git-file-utils/node_modules/minimatch": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", - "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "node_modules/@commitlint/is-ignored": { + "version": "20.5.0", + "resolved": "https://registry.npmjs.org/@commitlint/is-ignored/-/is-ignored-20.5.0.tgz", + "integrity": "sha512-JWLarAsurHJhPozbuAH6GbP4p/hdOCoqS9zJMfqwswne+/GPs5V0+rrsfOkP68Y8PSLphwtFXV0EzJ+GTXTTGg==", "dev": true, - "license": "ISC", + "license": "MIT", "dependencies": { - "brace-expansion": "^2.0.1" + "@commitlint/types": "^20.5.0", + "semver": "^7.6.0" }, "engines": { - "node": ">=10" + "node": ">=v18" } }, - "node_modules/@humanwhocodes/config-array": { - "version": "0.11.14", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz", - "integrity": "sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg==", - "deprecated": "Use @eslint/config-array instead", + "node_modules/@commitlint/lint": { + "version": "20.5.3", + "resolved": "https://registry.npmjs.org/@commitlint/lint/-/lint-20.5.3.tgz", + "integrity": "sha512-M7JbWBNr2gXKaPc4i/KipsuW1gkDHpj35KPjWtKy3Z+2AQw5wu1gBi1LIO0uoaij67CqY4K8PxPZSGens4evCw==", "dev": true, - "license": "Apache-2.0", - "peer": true, + "license": "MIT", "dependencies": { - "@humanwhocodes/object-schema": "^2.0.2", - "debug": "^4.3.1", - "minimatch": "^3.0.5" + "@commitlint/is-ignored": "^20.5.0", + "@commitlint/parse": "^20.5.0", + "@commitlint/rules": "^20.5.3", + "@commitlint/types": "^20.5.0" }, "engines": { - "node": ">=10.10.0" + "node": ">=v18" } }, - "node_modules/@humanwhocodes/config-array/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "node_modules/@commitlint/load": { + "version": "20.5.3", + "resolved": "https://registry.npmjs.org/@commitlint/load/-/load-20.5.3.tgz", + "integrity": "sha512-1FDZWuKyu98Myb8i7Tp31jPU2rZpOwAdYRyJcy2KoGg7Xk2A+bgHN8smhMaaNSNkmE8fwt53BokywZq8Gv/5XQ==", "dev": true, "license": "MIT", - "peer": true, - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/@humanwhocodes/config-array/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "license": "ISC", - "peer": true, "dependencies": { - "brace-expansion": "^1.1.7" + "@commitlint/config-validator": "^20.5.0", + "@commitlint/execute-rule": "^20.0.0", + "@commitlint/resolve-extends": "^20.5.3", + "@commitlint/types": "^20.5.0", + "cosmiconfig": "^9.0.1", + "cosmiconfig-typescript-loader": "^6.1.0", + "es-toolkit": "^1.46.0", + "is-plain-obj": "^4.1.0", + "picocolors": "^1.1.1" }, "engines": { - "node": "*" - } - }, - "node_modules/@humanwhocodes/module-importer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", - "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", - "dev": true, - "license": "Apache-2.0", - "peer": true, - "engines": { - "node": ">=12.22" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" + "node": ">=v18" } }, - "node_modules/@humanwhocodes/object-schema": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", - "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", - "deprecated": "Use @eslint/object-schema instead", - "dev": true, - "license": "BSD-3-Clause", - "peer": true - }, - "node_modules/@iarna/toml": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@iarna/toml/-/toml-3.0.0.tgz", - "integrity": "sha512-td6ZUkz2oS3VeleBcN+m//Q6HlCFCPrnI0FZhrt/h4XqLEdOyYp2u21nd8MdsR+WJy5r9PTDaHTDDfhf4H4l6Q==", + "node_modules/@commitlint/message": { + "version": "20.4.3", + "resolved": "https://registry.npmjs.org/@commitlint/message/-/message-20.4.3.tgz", + "integrity": "sha512-6akwCYrzcrFcTYz9GyUaWlhisY4lmQ3KvrnabmhoeAV8nRH4dXJAh4+EUQ3uArtxxKQkvxJS78hNX2EU3USgxQ==", "dev": true, - "license": "ISC" - }, - "node_modules/@isaacs/cliui": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", - "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", - "inBundle": true, - "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" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/@isaacs/cliui/node_modules/ansi-regex": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", - "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", - "inBundle": true, "license": "MIT", "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" + "node": ">=v18" } }, - "node_modules/@isaacs/cliui/node_modules/emoji-regex": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", - "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", - "inBundle": true, - "license": "MIT" - }, - "node_modules/@isaacs/cliui/node_modules/string-width": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", - "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", - "inBundle": true, + "node_modules/@commitlint/parse": { + "version": "20.5.0", + "resolved": "https://registry.npmjs.org/@commitlint/parse/-/parse-20.5.0.tgz", + "integrity": "sha512-SeKWHBMk7YOTnnEWUhx+d1a9vHsjjuo6Uo1xRfPNfeY4bdYFasCH1dDpAv13Lyn+dDPOels+jP6D2GRZqzc5fA==", + "dev": true, "license": "MIT", "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" + "@commitlint/types": "^20.5.0", + "conventional-changelog-angular": "^8.2.0", + "conventional-commits-parser": "^6.3.0" }, "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=v18" } }, - "node_modules/@isaacs/cliui/node_modules/strip-ansi": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", - "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", - "inBundle": true, + "node_modules/@commitlint/read": { + "version": "20.5.0", + "resolved": "https://registry.npmjs.org/@commitlint/read/-/read-20.5.0.tgz", + "integrity": "sha512-JDEIJ2+GnWpK8QqwfmW7O42h0aycJEWNqcdkJnyzLD11nf9dW2dWLTVEa8Wtlo4IZFGLPATjR5neA5QlOvIH1w==", + "dev": true, "license": "MIT", "dependencies": { - "ansi-regex": "^6.0.1" + "@commitlint/top-level": "^20.4.3", + "@commitlint/types": "^20.5.0", + "git-raw-commits": "^5.0.0", + "minimist": "^1.2.8", + "tinyexec": "^1.0.0" }, "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" + "node": ">=v18" } }, - "node_modules/@isaacs/string-locale-compare": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@isaacs/string-locale-compare/-/string-locale-compare-1.1.0.tgz", - "integrity": "sha512-SQ7Kzhh9+D+ZW9MA0zkYv3VXhIDNx+LzM6EJ+/65I3QY+enU6Itte7E5XX7EWrqLW2FN4n06GWzBnPoC3th2aQ==", - "inBundle": true, - "license": "ISC" - }, - "node_modules/@istanbuljs/load-nyc-config": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "node_modules/@commitlint/resolve-extends": { + "version": "20.5.3", + "resolved": "https://registry.npmjs.org/@commitlint/resolve-extends/-/resolve-extends-20.5.3.tgz", + "integrity": "sha512-+ogW9v/u9JqpvAgTrLra/YTFo0KkjU6iNblF89pPsj4NebNc+DAWctsludwezI8YnsjBmfHpApSwcXprN/f/ew==", "dev": true, - "license": "ISC", + "license": "MIT", "dependencies": { - "camelcase": "^5.3.1", - "find-up": "^4.1.0", - "get-package-type": "^0.1.0", - "js-yaml": "^3.13.1", + "@commitlint/config-validator": "^20.5.0", + "@commitlint/types": "^20.5.0", + "es-toolkit": "^1.46.0", + "global-directory": "^5.0.0", + "import-meta-resolve": "^4.0.0", "resolve-from": "^5.0.0" }, "engines": { - "node": ">=8" + "node": ">=v18" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "node_modules/@commitlint/rules": { + "version": "20.5.3", + "resolved": "https://registry.npmjs.org/@commitlint/rules/-/rules-20.5.3.tgz", + "integrity": "sha512-MPlMnb9D3wbszYMp+1hPtuhtPJndRo6I6yfkZVA4+jR8w7Kqp0u2u/Y+gzbaItx5Lltq5rw7FSZQWJMoXUC4NQ==", "dev": true, "license": "MIT", "dependencies": { - "sprintf-js": "~1.0.2" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "license": "BSD-2-Clause", - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" + "@commitlint/ensure": "^20.5.3", + "@commitlint/message": "^20.4.3", + "@commitlint/to-lines": "^20.0.0", + "@commitlint/types": "^20.5.0" }, "engines": { - "node": ">=4" + "node": ">=v18" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "node_modules/@commitlint/to-lines": { + "version": "20.0.0", + "resolved": "https://registry.npmjs.org/@commitlint/to-lines/-/to-lines-20.0.0.tgz", + "integrity": "sha512-2l9gmwiCRqZNWgV+pX1X7z4yP0b3ex/86UmUFgoRt672Ez6cAM2lOQeHFRUTuE6sPpi8XBCGnd8Kh3bMoyHwJw==", "dev": true, "license": "MIT", - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, "engines": { - "node": ">=8" + "node": ">=v18" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "node_modules/@commitlint/top-level": { + "version": "20.4.3", + "resolved": "https://registry.npmjs.org/@commitlint/top-level/-/top-level-20.4.3.tgz", + "integrity": "sha512-qD9xfP6dFg5jQ3NMrOhG0/w5y3bBUsVGyJvXxdWEwBm8hyx4WOk3kKXw28T5czBYvyeCVJgJJ6aoJZUWDpaacQ==", "dev": true, "license": "MIT", "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" + "escalade": "^3.2.0" }, - "bin": { - "js-yaml": "bin/js-yaml.js" + "engines": { + "node": ">=v18" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "node_modules/@commitlint/types": { + "version": "20.5.0", + "resolved": "https://registry.npmjs.org/@commitlint/types/-/types-20.5.0.tgz", + "integrity": "sha512-ZJoS8oSq2CAZEpc/YI9SulLrdiIyXeHb/OGqGrkUP6Q7YV+0ouNAa7GjqRdXeQPncHQIDz/jbCTlHScvYvO/gA==", "dev": true, "license": "MIT", "dependencies": { - "p-locate": "^4.1.0" + "conventional-commits-parser": "^6.3.0", + "picocolors": "^1.1.1" }, "engines": { - "node": ">=8" + "node": ">=v18" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "node_modules/@conventional-commits/parser": { + "version": "0.4.1", "dev": true, - "license": "MIT", + "license": "ISC", + "dependencies": { + "unist-util-visit": "^2.0.3", + "unist-util-visit-parents": "^3.1.1" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.4.tgz", + "integrity": "sha512-wgsqt92b7C7tQhIdPNxj0n9zuUbQlvAuI1exyzeNrOKOi62SD7ren8zqszmpVREjAOqg8cD2FqYhQfAuKjk4sw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", + "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "2.1.4", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^9.6.0", + "globals": "^13.19.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@eslint/eslintrc/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", + "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/eslintrc/node_modules/json-schema-traverse": { + "version": "0.4.1", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@eslint/eslintrc/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/js": { + "version": "8.57.1", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/@gar/promise-retry": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@gar/promise-retry/-/promise-retry-1.0.3.tgz", + "integrity": "sha512-GmzA9ckNokPypTg10pgpeHNQe7ph+iIKKmhKu3Ob9ANkswreCx7R3cKmY781K8QK3AqVL3xVh9A42JvIAbkkSA==", + "inBundle": true, + "license": "MIT", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@google-automations/git-file-utils": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@google-automations/git-file-utils/-/git-file-utils-3.0.1.tgz", + "integrity": "sha512-vlQZ8DlBcippB5zTY0M5Rib8tKT4yQ7oBKbs6kcWAzp70oyillKinXLZwlIgNTmfzzZx1J6cez3M0EmrpXFRcw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@octokit/rest": "^20.1.1", + "@octokit/types": "^13.0.0", + "js-yaml": "^4.1.1", + "minimatch": "^10.2.4" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/@google-automations/git-file-utils/node_modules/@octokit/auth-token": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 18" + } + }, + "node_modules/@google-automations/git-file-utils/node_modules/@octokit/core": { + "version": "5.2.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/auth-token": "^4.0.0", + "@octokit/graphql": "^7.1.0", + "@octokit/request": "^8.4.1", + "@octokit/request-error": "^5.1.1", + "@octokit/types": "^13.0.0", + "before-after-hook": "^2.2.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/@google-automations/git-file-utils/node_modules/@octokit/endpoint": { + "version": "9.0.6", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.1.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/@google-automations/git-file-utils/node_modules/@octokit/graphql": { + "version": "7.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/request": "^8.4.1", + "@octokit/types": "^13.0.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/@google-automations/git-file-utils/node_modules/@octokit/openapi-types": { + "version": "24.2.0", + "dev": true, + "license": "MIT" + }, + "node_modules/@google-automations/git-file-utils/node_modules/@octokit/plugin-paginate-rest": { + "version": "11.4.4-cjs.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.7.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@octokit/core": "5" + } + }, + "node_modules/@google-automations/git-file-utils/node_modules/@octokit/plugin-request-log": { + "version": "4.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@octokit/core": "5" + } + }, + "node_modules/@google-automations/git-file-utils/node_modules/@octokit/plugin-rest-endpoint-methods": { + "version": "13.3.2-cjs.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.8.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@octokit/core": "^5" + } + }, + "node_modules/@google-automations/git-file-utils/node_modules/@octokit/request": { + "version": "8.4.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/endpoint": "^9.0.6", + "@octokit/request-error": "^5.1.1", + "@octokit/types": "^13.1.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/@google-automations/git-file-utils/node_modules/@octokit/request-error": { + "version": "5.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.1.0", + "deprecation": "^2.0.0", + "once": "^1.4.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/@google-automations/git-file-utils/node_modules/@octokit/rest": { + "version": "20.1.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/core": "^5.0.2", + "@octokit/plugin-paginate-rest": "11.4.4-cjs.2", + "@octokit/plugin-request-log": "^4.0.0", + "@octokit/plugin-rest-endpoint-methods": "13.3.2-cjs.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/@google-automations/git-file-utils/node_modules/@octokit/types": { + "version": "13.10.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^24.2.0" + } + }, + "node_modules/@google-automations/git-file-utils/node_modules/before-after-hook": { + "version": "2.2.3", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/@google-automations/git-file-utils/node_modules/universal-user-agent": { + "version": "6.0.1", + "dev": true, + "license": "ISC" + }, + "node_modules/@humanwhocodes/config-array": { + "version": "0.13.0", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "@humanwhocodes/object-schema": "^2.0.3", + "debug": "^4.3.1", + "minimatch": "^3.0.5" + }, + "engines": { + "node": ">=10.10.0" + } + }, + "node_modules/@humanwhocodes/config-array/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@humanwhocodes/config-array/node_modules/brace-expansion": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", + "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@humanwhocodes/config-array/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/object-schema": { + "version": "2.0.3", + "dev": true, + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/@iarna/toml": { + "version": "3.0.0", + "dev": true, + "license": "ISC" + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@isaacs/string-locale-compare": { + "version": "1.1.0", + "inBundle": true, + "license": "ISC" + }, + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "dev": true, + "license": "ISC", + "dependencies": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": { + "version": "1.0.10", + "dev": true, + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/find-up": { + "version": "4.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { + "version": "3.14.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", + "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/locate-path": { + "version": "5.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/p-limit": { + "version": "2.3.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/p-locate": { + "version": "4.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/path-exists": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz", + "integrity": "sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@jsep-plugin/assignment": { + "version": "1.3.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.16.0" + }, + "peerDependencies": { + "jsep": "^0.4.0||^1.0.0" + } + }, + "node_modules/@jsep-plugin/regex": { + "version": "1.0.4", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.16.0" + }, + "peerDependencies": { + "jsep": "^0.4.0||^1.0.0" + } + }, + "node_modules/@mswjs/interceptors": { + "version": "0.41.9", + "resolved": "https://registry.npmjs.org/@mswjs/interceptors/-/interceptors-0.41.9.tgz", + "integrity": "sha512-VVPPgHyQ6ShqnrmDWuxjmUIsO9gWyOZFmuOfLd9LfBGQJwZfy0gvv9pbHSJuoFNIYC7ZDX9aoFwowjcdSC4E8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@open-draft/deferred-promise": "^2.2.0", + "@open-draft/logger": "^0.3.0", + "@open-draft/until": "^2.0.0", + "is-node-process": "^1.2.0", + "outvariant": "^1.4.3", + "strict-event-emitter": "^0.5.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@npmcli/agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-5.0.1.tgz", + "integrity": "sha512-PsOUeQRpNOGH+Iks/YPY8AXtttvGVqNqKIo/Cp2LhI0jpeqW32JP14yYRym+OsTg+roH4Avw281YwHMp8X8L2Q==", + "inBundle": true, + "license": "ISC", + "dependencies": { + "agent-base": "^9.0.0", + "http-proxy-agent": "^9.0.0", + "https-proxy-agent": "^9.0.0", + "lru-cache": "^11.2.1", + "socks-proxy-agent": "^10.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/agent/node_modules/agent-base": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz", + "integrity": "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">= 20" + } + }, + "node_modules/@npmcli/agent/node_modules/http-proxy-agent": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-9.1.0.tgz", + "integrity": "sha512-2NxoveTT58mjYT4n3RPTEfCZGLMbidoO8XEieXfpSYxu+PQJ1qpx4ypwH6N+uF9twBPIvRRgvkvW5HUTYWENig==", + "inBundle": true, + "license": "MIT", + "dependencies": { + "agent-base": "9.0.0", + "debug": "^4.3.4", + "proxy-agent-negotiate": "1.1.0" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/@npmcli/agent/node_modules/https-proxy-agent": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz", + "integrity": "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==", + "inBundle": true, + "license": "MIT", + "dependencies": { + "agent-base": "9.0.0", + "debug": "^4.3.4", + "proxy-agent-negotiate": "1.1.0" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/@npmcli/arborist": { + "resolved": "workspaces/arborist", + "link": true + }, + "node_modules/@npmcli/config": { + "resolved": "workspaces/config", + "link": true + }, + "node_modules/@npmcli/docs": { + "resolved": "docs", + "link": true + }, + "node_modules/@npmcli/eslint-config": { + "version": "5.1.0", + "dev": true, + "license": "ISC", + "dependencies": { + "which": "^5.0.0" + }, + "bin": { + "lint": "bin/index.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + }, + "peerDependencies": { + "eslint": "^8.13.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^6.0.0" + } + }, + "node_modules/@npmcli/eslint-config/node_modules/isexe": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", + "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@npmcli/eslint-config/node_modules/which": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", + "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/fs": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-6.0.0.tgz", + "integrity": "sha512-AheOs4swKka/XLtht6xxJDPezlQ7K2IYQ9Y8lST4JLDjnralnWuMM9AE2CdVcgQJ5omrXhsRzM7F7aYmeZBvKQ==", + "inBundle": true, + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/git": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-8.0.0.tgz", + "integrity": "sha512-5P1oo+TbxZNAiiMBtpzHA8QyEGh5D69LYLexNWJEDXLdxnAZvT/SLitGJBXxjtCE4ftAcFOS/Tu2185MeIjooQ==", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@npmcli/promise-spawn": "^10.0.0", + "ini": "^7.0.0", + "lru-cache": "^11.2.1", + "npm-pick-manifest": "^12.0.0", + "proc-log": "^7.0.0", + "semver": "^7.3.5", + "which": "^7.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/installed-package-contents": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/installed-package-contents/-/installed-package-contents-5.0.0.tgz", + "integrity": "sha512-6Ay12sf2Lh7U1ifvnS1mq7TZFeh/rXHMXye+kV7jQrANIubaoVcleeh4HdFumxhsRYwm9OaHycB5lYmSwGrcIQ==", + "inBundle": true, + "license": "ISC", + "dependencies": { + "npm-bundled": "^6.0.0", + "npm-normalize-package-bin": "^6.0.0" + }, + "bin": { + "installed-package-contents": "bin/index.js" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/installed-package-contents/node_modules/npm-bundled": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/npm-bundled/-/npm-bundled-6.0.0.tgz", + "integrity": "sha512-EqdodKEW6pYM+dPxA66TZQfMEqVDiuzjDM9edSjuPI1mXUbUJwVxkgqMZSJvs8RTXz2CGq8HUol/AffTZX5g8w==", + "inBundle": true, + "license": "ISC", + "dependencies": { + "npm-normalize-package-bin": "^6.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/installed-package-contents/node_modules/npm-normalize-package-bin": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-6.0.0.tgz", + "integrity": "sha512-tdt4aFn9QamlhdN3HV2D2ccpBwO5/fyjjbXUxYA6uBjyekMZcZvDq0aSj9t5Jo+tih6AYFnt/cuIRn9013e0Uw==", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/map-workspaces": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/map-workspaces/-/map-workspaces-6.0.0.tgz", + "integrity": "sha512-Dsex7XBea0BoFRbfALMbNuaNqeI3kbZJxiBMQhFvPUNluv0yEeKMd5FLIXy0NCsOuGMYQkLa+i219CadnoqLbg==", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/name-from-folder": "^5.0.0", + "@npmcli/package-json": "^8.0.0", + "glob": "^13.0.0", + "minimatch": "^10.0.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/metavuln-calculator": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/metavuln-calculator/-/metavuln-calculator-10.0.0.tgz", + "integrity": "sha512-fC56lpGOae+unrFx6hoiWeWa0/4q+bLhOQTSrB65qcy+Zm34i1OdBcevAQFJJdUB/3i9uXw7PjdrrRjt0KSKXw==", + "inBundle": true, + "license": "ISC", + "dependencies": { + "cacache": "^21.0.1", + "json-parse-even-better-errors": "^6.0.0", + "pacote": "^22.0.0", + "proc-log": "^7.0.0", + "semver": "^7.3.5" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/mock-globals": { + "resolved": "mock-globals", + "link": true + }, + "node_modules/@npmcli/mock-registry": { + "resolved": "mock-registry", + "link": true + }, + "node_modules/@npmcli/name-from-folder": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/name-from-folder/-/name-from-folder-5.0.0.tgz", + "integrity": "sha512-Mua2i5asmOn4sGGAsANS9Guamo7sgUd4BihhQWzlNGz6l/Ki23CzC2oGe4I94r2k/39ImCjDLbyu/rSJr/SXoA==", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/node-gyp": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/node-gyp/-/node-gyp-6.0.0.tgz", + "integrity": "sha512-MFakpea4pcZNlHSTbMi15HK8RY8zl2UpgDtxhZCWOer+KRN3x7HFIMk/fKpOMgR55L4LIcA2qn8IHeyABhIFtw==", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/package-json": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/package-json/-/package-json-8.0.0.tgz", + "integrity": "sha512-agNZzYQ18MR0wKp3Emg1q5QbcC8CXigYp3Z3CvB0Sax9Ge9aF4cVyyuSG+5SbACSrZUKTvMjVULWiE1RJA38wg==", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/git": "^8.0.0", + "glob": "^13.0.0", + "hosted-git-info": "^10.1.1", + "json-parse-even-better-errors": "^6.0.0", + "proc-log": "^7.0.0", + "semver": "^7.5.3", + "spdx-expression-parse": "^4.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/promise-spawn": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/promise-spawn/-/promise-spawn-10.0.0.tgz", + "integrity": "sha512-llZkSzeTsimFx64U+ThT2xQM2uEce8GIQUYvxgbB6ZFvBhV2LP9LeJJb3HT+syG0uCFLsTCHjV9SfC0WNU1vtA==", + "inBundle": true, + "license": "ISC", + "dependencies": { + "which": "^7.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/query": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/query/-/query-5.0.0.tgz", + "integrity": "sha512-8TZWfTQOsODpLqo9SVhVjHovmKXNpevHU0gO9e+y4V4fRIOneiXy0u0sMP9LmS71XivrEWfZWg50ReH4WRT4aQ==", + "license": "ISC", + "dependencies": { + "postcss-selector-parser": "^7.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/redact": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-5.0.0.tgz", + "integrity": "sha512-3zcN5Q3yEmeyxXBzqB6fXPQFzYa2ROsGFSr69W0ArXIAGJqxl/aFECOVPD2kbkYPm0U/EHxFKgclK3UA9WQg5A==", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/run-script": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/run-script/-/run-script-11.0.0.tgz", + "integrity": "sha512-leBRl6F5F0TvWut8m1/aZcMTUHi2vXjKeMJ/Ik1lW7Q7Yy16Dhtkklu+cEqQww1p1NeLnUNzV3+uwpzqRcy9vw==", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/node-gyp": "^6.0.0", + "@npmcli/package-json": "^8.0.0", + "@npmcli/promise-spawn": "^10.0.0", + "node-gyp": "^13.0.0", + "proc-log": "^7.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/smoke-tests": { + "resolved": "smoke-tests", + "link": true + }, + "node_modules/@npmcli/template-oss": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@npmcli/template-oss/-/template-oss-5.1.1.tgz", + "integrity": "sha512-b+38SQ+Nub8hNQ36wXYWJO4ydve0lyW3xCorUihFf2WgopFCOxOG5gKl0ScV6pG6I9hXhbFNqdl8bvzjGFtM0w==", + "dev": true, + "hasInstallScript": true, + "license": "ISC", + "workspaces": [ + "workspace/test-workspace" + ], + "dependencies": { + "@actions/core": "^2.0.0", + "@commitlint/cli": "^20.1.0", + "@commitlint/config-conventional": "^20.0.0", + "@isaacs/string-locale-compare": "^1.1.0", + "@npmcli/arborist": "^10.0.0-pre.0.0", + "@npmcli/git": "^8.0.0", + "@npmcli/map-workspaces": "^5.0.0", + "@npmcli/package-json": "^8.0.0", + "@octokit/rest": "^22.0.0", + "dedent": "^1.5.1", + "diff": "^8.0.2", + "glob": "^13.0.0", + "handlebars": "^4.7.7", + "hosted-git-info": "^10.1.1", + "ini": "^7.0.0", + "json-parse-even-better-errors": "^6.0.0", + "just-deep-map-values": "^1.1.1", + "just-diff": "^6.0.0", + "just-omit": "^2.2.0", + "lodash": "^4.17.21", + "minimatch": "^10.0.3", + "npm-package-arg": "^14.0.0", + "proc-log": "^7.0.0", + "release-please": "^17.1.1", + "semver": "^7.3.5", + "yaml": "^2.1.1" + }, + "bin": { + "template-oss-apply": "bin/apply.js", + "template-oss-check": "bin/check.js", + "template-oss-release-manager": "bin/release-manager.js", + "template-oss-release-please": "bin/release-please.js" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/agent": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-4.0.2.tgz", + "integrity": "sha512-EUEuWAxnL07Sp5/iC/1X6Xj+XThUvnbei9zfRWZdEXa7lss9RTHMhAHBeg+MZ5To9s/gGaSI+UwZTPdYMvKSeg==", + "dev": true, + "license": "ISC", + "dependencies": { + "agent-base": "^7.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.1", + "lru-cache": "^11.2.1", + "socks-proxy-agent": "^8.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/arborist": { + "version": "10.0.0-pre.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/arborist/-/arborist-10.0.0-pre.0.0.tgz", + "integrity": "sha512-iSyJoqL1gojO4DVk7D/OK6MnGo8qeU0tI0fwE3EsPLTZMLyRwhQOfffFv8pEKIgxRRV1Dom57FDuQSugPfp1OQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@isaacs/string-locale-compare": "^1.1.0", + "@npmcli/fs": "^5.0.0", + "@npmcli/installed-package-contents": "^4.0.0", + "@npmcli/map-workspaces": "^5.0.0", + "@npmcli/metavuln-calculator": "^9.0.2", + "@npmcli/name-from-folder": "^4.0.0", + "@npmcli/node-gyp": "^5.0.0", + "@npmcli/package-json": "^7.0.0", + "@npmcli/query": "^5.0.0", + "@npmcli/redact": "^4.0.0", + "@npmcli/run-script": "^10.0.0", + "bin-links": "^6.0.0", + "cacache": "^20.0.1", + "common-ancestor-path": "^2.0.0", + "hosted-git-info": "^9.0.0", + "json-stringify-nice": "^1.1.4", + "lru-cache": "^11.2.1", + "minimatch": "^10.0.3", + "nopt": "^9.0.0", + "npm-install-checks": "^8.0.0", + "npm-package-arg": "^13.0.0", + "npm-pick-manifest": "^11.0.1", + "npm-registry-fetch": "^19.0.0", + "pacote": "^21.0.2", + "parse-conflict-json": "^5.0.1", + "proc-log": "^6.0.0", + "proggy": "^4.0.0", + "promise-all-reject-late": "^1.0.0", + "promise-call-limit": "^3.0.1", + "semver": "^7.3.7", + "ssri": "^13.0.0", + "treeverse": "^3.0.0", + "walk-up-path": "^4.0.0" + }, + "bin": { + "arborist": "bin/index.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/arborist/node_modules/@npmcli/git": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-7.0.2.tgz", + "integrity": "sha512-oeolHDjExNAJAnlYP2qzNjMX/Xi9bmu78C9dIGr4xjobrSKbuMYCph8lTzn4vnW3NjIqVmw/f8BCfouqyJXlRg==", + "dev": true, + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "ini": "^6.0.0", + "lru-cache": "^11.2.1", + "npm-pick-manifest": "^11.0.1", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "which": "^6.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/arborist/node_modules/@npmcli/package-json": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/@npmcli/package-json/-/package-json-7.0.5.tgz", + "integrity": "sha512-iVuTlG3ORq2iaVa1IWUxAO/jIp77tUKBhoMjuzYW2kL4MLN1bi/ofqkZ7D7OOwh8coAx1/S2ge0rMdGv8sLSOQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "@npmcli/git": "^7.0.0", + "glob": "^13.0.0", + "hosted-git-info": "^9.0.0", + "json-parse-even-better-errors": "^5.0.0", + "proc-log": "^6.0.0", + "semver": "^7.5.3", + "spdx-expression-parse": "^4.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/arborist/node_modules/hosted-git-info": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz", + "integrity": "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==", + "dev": true, + "license": "ISC", + "dependencies": { + "lru-cache": "^11.1.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/arborist/node_modules/ini": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-6.0.0.tgz", + "integrity": "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/arborist/node_modules/json-parse-even-better-errors": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-5.0.0.tgz", + "integrity": "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/arborist/node_modules/npm-package-arg": { + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-13.0.2.tgz", + "integrity": "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA==", + "dev": true, + "license": "ISC", + "dependencies": { + "hosted-git-info": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^7.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/arborist/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/fs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-5.0.0.tgz", + "integrity": "sha512-7OsC1gNORBEawOa5+j2pXN9vsicaIOH5cPXxoR6fJOmH6/EXpJB2CajXOu1fPRFun2m1lktEFX11+P89hqO/og==", + "dev": true, + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/installed-package-contents": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/installed-package-contents/-/installed-package-contents-4.0.0.tgz", + "integrity": "sha512-yNyAdkBxB72gtZ4GrwXCM0ZUedo9nIbOMKfGjt6Cu6DXf0p8y1PViZAKDC8q8kv/fufx0WTjRBdSlyrvnP7hmA==", + "dev": true, + "license": "ISC", + "dependencies": { + "npm-bundled": "^5.0.0", + "npm-normalize-package-bin": "^5.0.0" + }, + "bin": { + "installed-package-contents": "bin/index.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/map-workspaces": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@npmcli/map-workspaces/-/map-workspaces-5.0.3.tgz", + "integrity": "sha512-o2grssXo1e774E5OtEwwrgoszYRh0lqkJH+Pb9r78UcqdGJRDRfhpM8DvZPjzNLLNYeD/rNbjOKM3Ss5UABROw==", + "dev": true, + "license": "ISC", + "dependencies": { + "@npmcli/name-from-folder": "^4.0.0", + "@npmcli/package-json": "^7.0.0", + "glob": "^13.0.0", + "minimatch": "^10.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/map-workspaces/node_modules/@npmcli/git": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-7.0.2.tgz", + "integrity": "sha512-oeolHDjExNAJAnlYP2qzNjMX/Xi9bmu78C9dIGr4xjobrSKbuMYCph8lTzn4vnW3NjIqVmw/f8BCfouqyJXlRg==", + "dev": true, + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "ini": "^6.0.0", + "lru-cache": "^11.2.1", + "npm-pick-manifest": "^11.0.1", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "which": "^6.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/map-workspaces/node_modules/@npmcli/package-json": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/@npmcli/package-json/-/package-json-7.0.5.tgz", + "integrity": "sha512-iVuTlG3ORq2iaVa1IWUxAO/jIp77tUKBhoMjuzYW2kL4MLN1bi/ofqkZ7D7OOwh8coAx1/S2ge0rMdGv8sLSOQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "@npmcli/git": "^7.0.0", + "glob": "^13.0.0", + "hosted-git-info": "^9.0.0", + "json-parse-even-better-errors": "^5.0.0", + "proc-log": "^6.0.0", + "semver": "^7.5.3", + "spdx-expression-parse": "^4.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/map-workspaces/node_modules/hosted-git-info": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz", + "integrity": "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==", + "dev": true, + "license": "ISC", + "dependencies": { + "lru-cache": "^11.1.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/map-workspaces/node_modules/ini": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-6.0.0.tgz", + "integrity": "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/map-workspaces/node_modules/json-parse-even-better-errors": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-5.0.0.tgz", + "integrity": "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/map-workspaces/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/metavuln-calculator": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/@npmcli/metavuln-calculator/-/metavuln-calculator-9.0.3.tgz", + "integrity": "sha512-94GLSYhLXF2t2LAC7pDwLaM4uCARzxShyAQKsirmlNcpidH89VA4/+K1LbJmRMgz5gy65E/QBBWQdUvGLe2Frg==", + "dev": true, + "license": "ISC", "dependencies": { - "p-try": "^2.0.0" + "cacache": "^20.0.0", + "json-parse-even-better-errors": "^5.0.0", + "pacote": "^21.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5" }, "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "node_modules/@npmcli/template-oss/node_modules/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-5.0.0.tgz", + "integrity": "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ==", "dev": true, "license": "MIT", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/metavuln-calculator/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/name-from-folder": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/name-from-folder/-/name-from-folder-4.0.0.tgz", + "integrity": "sha512-qfrhVlOSqmKM8i6rkNdZzABj8MKEITGFAY+4teqBziksCQAOLutiAxM1wY2BKEd8KjUSpWmWCYxvXr0y4VTlPg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/node-gyp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/node-gyp/-/node-gyp-5.0.0.tgz", + "integrity": "sha512-uuG5HZFXLfyFKqg8QypsmgLQW7smiRjVc45bqD/ofZZcR/uxEjgQU8qDPv0s9TEeMUiAAU/GC5bR6++UdTirIQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/promise-spawn": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/@npmcli/promise-spawn/-/promise-spawn-9.0.1.tgz", + "integrity": "sha512-OLUaoqBuyxeTqUvjA3FZFiXUfYC1alp3Sa99gW3EUDz3tZ3CbXDdcZ7qWKBzicrJleIgucoWamWH1saAmH/l2Q==", + "dev": true, + "license": "ISC", "dependencies": { - "p-limit": "^2.2.0" + "which": "^6.0.0" }, "engines": { - "node": ">=8" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/path-exists": { + "node_modules/@npmcli/template-oss/node_modules/@npmcli/redact": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-4.0.0.tgz", + "integrity": "sha512-gOBg5YHMfZy+TfHArfVogwgfBeQnKbbGo3pSUyK/gSI0AVu+pEiDVcKlQb0D8Mg1LNRZILZ6XG8I5dJ4KuAd9Q==", "dev": true, - "license": "MIT", + "license": "ISC", "engines": { - "node": ">=8" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "node_modules/@npmcli/template-oss/node_modules/@npmcli/run-script": { + "version": "10.0.4", + "resolved": "https://registry.npmjs.org/@npmcli/run-script/-/run-script-10.0.4.tgz", + "integrity": "sha512-mGUWr1uMnf0le2TwfOZY4SFxZGXGfm4Jtay/nwAa2FLNAKXUoUwaGwBMNH36UHPtinWfTSJ3nqFQr0091CxVGg==", "dev": true, - "license": "BSD-3-Clause" + "license": "ISC", + "dependencies": { + "@npmcli/node-gyp": "^5.0.0", + "@npmcli/package-json": "^7.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "node-gyp": "^12.1.0", + "proc-log": "^6.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } }, - "node_modules/@istanbuljs/schema": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", - "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "node_modules/@npmcli/template-oss/node_modules/@npmcli/run-script/node_modules/@npmcli/git": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-7.0.2.tgz", + "integrity": "sha512-oeolHDjExNAJAnlYP2qzNjMX/Xi9bmu78C9dIGr4xjobrSKbuMYCph8lTzn4vnW3NjIqVmw/f8BCfouqyJXlRg==", "dev": true, - "license": "MIT", + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "ini": "^6.0.0", + "lru-cache": "^11.2.1", + "npm-pick-manifest": "^11.0.1", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "which": "^6.0.0" + }, "engines": { - "node": ">=8" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", - "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", + "node_modules/@npmcli/template-oss/node_modules/@npmcli/run-script/node_modules/@npmcli/package-json": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/@npmcli/package-json/-/package-json-7.0.5.tgz", + "integrity": "sha512-iVuTlG3ORq2iaVa1IWUxAO/jIp77tUKBhoMjuzYW2kL4MLN1bi/ofqkZ7D7OOwh8coAx1/S2ge0rMdGv8sLSOQ==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "@jridgewell/set-array": "^1.2.1", - "@jridgewell/sourcemap-codec": "^1.4.10", - "@jridgewell/trace-mapping": "^0.3.24" + "@npmcli/git": "^7.0.0", + "glob": "^13.0.0", + "hosted-git-info": "^9.0.0", + "json-parse-even-better-errors": "^5.0.0", + "proc-log": "^6.0.0", + "semver": "^7.5.3", + "spdx-expression-parse": "^4.0.0" }, "engines": { - "node": ">=6.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "node_modules/@npmcli/template-oss/node_modules/@npmcli/run-script/node_modules/hosted-git-info": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz", + "integrity": "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==", "dev": true, - "license": "MIT", + "license": "ISC", + "dependencies": { + "lru-cache": "^11.1.0" + }, "engines": { - "node": ">=6.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@jridgewell/set-array": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", - "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", + "node_modules/@npmcli/template-oss/node_modules/@npmcli/run-script/node_modules/ini": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-6.0.0.tgz", + "integrity": "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/@npmcli/run-script/node_modules/json-parse-even-better-errors": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-5.0.0.tgz", + "integrity": "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ==", "dev": true, "license": "MIT", "engines": { - "node": ">=6.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.4.15", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", - "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "node_modules/@npmcli/template-oss/node_modules/@npmcli/run-script/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", "dev": true, - "license": "MIT" + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.25", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", - "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "node_modules/@npmcli/template-oss/node_modules/abbrev": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz", + "integrity": "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==", "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "node_modules/@npmcli/template-oss/node_modules/bin-links": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/bin-links/-/bin-links-6.0.2.tgz", + "integrity": "sha512-frE1t78WOwJ45PKV2cF2tNPjTcs9L1J9s6VkrV59wanRP4GlaomuxYPVma7BwthMg8WnfSory4w5PTE6FZZ81w==", "dev": true, - "license": "MIT", - "peer": true, + "license": "ISC", "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" + "cmd-shim": "^8.0.0", + "npm-normalize-package-bin": "^5.0.0", + "proc-log": "^6.0.0", + "read-cmd-shim": "^6.0.0", + "write-file-atomic": "^7.0.0" }, "engines": { - "node": ">= 8" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "node_modules/@npmcli/template-oss/node_modules/bin-links/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", "dev": true, - "license": "MIT", - "peer": true, + "license": "ISC", "engines": { - "node": ">= 8" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "node_modules/@npmcli/template-oss/node_modules/cacache": { + "version": "20.0.4", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-20.0.4.tgz", + "integrity": "sha512-M3Lab8NPYlZU2exsL3bMVvMrMqgwCnMWfdZbK28bn3pK6APT/Te/I8hjRPNu1uwORY9a1eEQoifXbKPQMfMTOA==", "dev": true, - "license": "MIT", - "peer": true, + "license": "ISC", "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" + "@npmcli/fs": "^5.0.0", + "fs-minipass": "^3.0.0", + "glob": "^13.0.0", + "lru-cache": "^11.1.0", + "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": "^13.0.0" }, "engines": { - "node": ">= 8" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/agent": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-2.2.2.tgz", - "integrity": "sha512-OrcNPXdpSl9UX7qPVRWbmWMCSXrcDa2M9DvrbOTj7ao1S4PlqVFYv9/yLKMkrJKZ/V5A/kDBC690or307i26Og==", - "inBundle": true, + "node_modules/@npmcli/template-oss/node_modules/make-fetch-happen": { + "version": "15.0.6", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-15.0.6.tgz", + "integrity": "sha512-Je0fLJ0F5atA7F+eIlLzk+Wkcl57JDf4kf+EW8xiP5E31xOQxkIxTbgf1Oi1Lw9tRI9UEMRdI5Vz2xTzoNU1Jw==", + "dev": true, "license": "ISC", "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" + "@gar/promise-retry": "^1.0.0", + "@npmcli/agent": "^4.0.0", + "@npmcli/redact": "^4.0.0", + "cacache": "^20.0.1", + "http-cache-semantics": "^4.1.1", + "minipass": "^7.0.2", + "minipass-fetch": "^5.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^1.0.0", + "proc-log": "^6.0.0", + "ssri": "^13.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/arborist": { - "resolved": "workspaces/arborist", - "link": true + "node_modules/@npmcli/template-oss/node_modules/make-fetch-happen/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } }, - "node_modules/@npmcli/config": { - "resolved": "workspaces/config", - "link": true + "node_modules/@npmcli/template-oss/node_modules/node-gyp": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.4.0.tgz", + "integrity": "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.0", + "exponential-backoff": "^3.1.1", + "graceful-fs": "^4.2.6", + "nopt": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "tar": "^7.5.4", + "tinyglobby": "^0.2.12", + "undici": "^6.25.0", + "which": "^6.0.0" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } }, - "node_modules/@npmcli/docs": { - "resolved": "docs", - "link": true + "node_modules/@npmcli/template-oss/node_modules/node-gyp/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } }, - "node_modules/@npmcli/eslint-config": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@npmcli/eslint-config/-/eslint-config-4.0.4.tgz", - "integrity": "sha512-jl0xDQs9YFPhMFSqxXs4HEzcfDzG1P4dsziJztUJdhKdXPp6jvw8B3zrNXNQs7DUjCv33+S+H7udmbPxIo1TBg==", + "node_modules/@npmcli/template-oss/node_modules/nopt": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz", + "integrity": "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==", "dev": true, "license": "ISC", "dependencies": { - "which": "^3.0.0" + "abbrev": "^4.0.0" }, "bin": { - "lint": "bin/index.js" + "nopt": "bin/nopt.js" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/npm-install-checks": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/npm-install-checks/-/npm-install-checks-8.0.0.tgz", + "integrity": "sha512-ScAUdMpyzkbpxoNekQ3tNRdFI8SJ86wgKZSQZdUxT+bj0wVFpsEMWnkXP0twVe1gJyNF5apBWDJhhIbgrIViRA==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "semver": "^7.1.1" }, - "peerDependencies": { - "eslint": "^8.13.0", - "eslint-plugin-import": "^2.26.0", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^6.0.0" + "engines": { + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/eslint-config/node_modules/which": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/which/-/which-3.0.1.tgz", - "integrity": "sha512-XA1b62dzQzLfaEOSQFTCOd5KFf/1VSzZo7/7TUjnya6u0vGGKzU96UQBZTAThCb2j4/xjBAyii1OhRLJEivHvg==", + "node_modules/@npmcli/template-oss/node_modules/npm-packlist": { + "version": "10.0.4", + "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-10.0.4.tgz", + "integrity": "sha512-uMW73iajD8hiH4ZBxEV3HC+eTnppIqwakjOYuvgddnalIw2lJguKviK1pcUJDlIWm1wSJkchpDZDSVVsZEYRng==", "dev": true, "license": "ISC", "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/which.js" + "ignore-walk": "^8.0.0", + "proc-log": "^6.0.0" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/fs": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-3.1.1.tgz", - "integrity": "sha512-q9CRWjpHCMIh5sVyefoD1cA7PkvILqCZsnSOEUUivORLjxCO/Irmue2DprETiNgEqktDBZaM1Bi+jrarx1XdCg==", - "inBundle": true, + "node_modules/@npmcli/template-oss/node_modules/npm-packlist/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/npm-pick-manifest": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/npm-pick-manifest/-/npm-pick-manifest-11.0.3.tgz", + "integrity": "sha512-buzyCfeoGY/PxKqmBqn1IUJrZnUi1VVJTdSSRPGI60tJdUhUoSQFhs0zycJokDdOznQentgrpf8LayEHyyYlqQ==", + "dev": true, "license": "ISC", "dependencies": { + "npm-install-checks": "^8.0.0", + "npm-normalize-package-bin": "^5.0.0", + "npm-package-arg": "^13.0.0", "semver": "^7.3.5" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/git": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-5.0.8.tgz", - "integrity": "sha512-liASfw5cqhjNW9UFd+ruwwdEf/lbOAQjLL2XY2dFW/bkJheXDYZgOyul/4gVvEV4BWkTXjYGmDqMw9uegdbJNQ==", - "inBundle": true, + "node_modules/@npmcli/template-oss/node_modules/npm-pick-manifest/node_modules/hosted-git-info": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz", + "integrity": "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==", + "dev": true, + "license": "ISC", + "dependencies": { + "lru-cache": "^11.1.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/npm-pick-manifest/node_modules/npm-package-arg": { + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-13.0.2.tgz", + "integrity": "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA==", + "dev": true, + "license": "ISC", + "dependencies": { + "hosted-git-info": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^7.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/npm-pick-manifest/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/npm-registry-fetch": { + "version": "19.1.1", + "resolved": "https://registry.npmjs.org/npm-registry-fetch/-/npm-registry-fetch-19.1.1.tgz", + "integrity": "sha512-TakBap6OM1w0H73VZVDf44iFXsOS3h+L4wVMXmbWOQroZgFhMch0juN6XSzBNlD965yIKvWg2dfu7NSiaYLxtw==", + "dev": true, + "license": "ISC", + "dependencies": { + "@npmcli/redact": "^4.0.0", + "jsonparse": "^1.3.1", + "make-fetch-happen": "^15.0.0", + "minipass": "^7.0.2", + "minipass-fetch": "^5.0.0", + "minizlib": "^3.0.1", + "npm-package-arg": "^13.0.0", + "proc-log": "^6.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/npm-registry-fetch/node_modules/hosted-git-info": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz", + "integrity": "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==", + "dev": true, + "license": "ISC", + "dependencies": { + "lru-cache": "^11.1.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/npm-registry-fetch/node_modules/npm-package-arg": { + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-13.0.2.tgz", + "integrity": "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA==", + "dev": true, "license": "ISC", "dependencies": { - "@npmcli/promise-spawn": "^7.0.0", - "ini": "^4.1.3", - "lru-cache": "^10.0.1", - "npm-pick-manifest": "^9.0.0", - "proc-log": "^4.0.0", - "promise-inflight": "^1.0.1", - "promise-retry": "^2.0.1", + "hosted-git-info": "^9.0.0", + "proc-log": "^6.0.0", "semver": "^7.3.5", - "which": "^4.0.0" + "validate-npm-package-name": "^7.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/installed-package-contents": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@npmcli/installed-package-contents/-/installed-package-contents-2.1.0.tgz", - "integrity": "sha512-c8UuGLeZpm69BryRykLuKRyKFZYJsZSCT4aVY5ds4omyZqJ172ApzgfKJ5eV/r3HgLdUYgFVe54KSFVjKoe27w==", - "inBundle": true, + "node_modules/@npmcli/template-oss/node_modules/npm-registry-fetch/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/pacote": { + "version": "21.5.1", + "resolved": "https://registry.npmjs.org/pacote/-/pacote-21.5.1.tgz", + "integrity": "sha512-KvcJ9iy3crysCsgqc4+PknH/w6jkrp8JN36mpZBPwNaDRwTfMZD37YzRazNstiZUOhuF5pno9f78n9mEJBavwg==", + "dev": true, "license": "ISC", "dependencies": { - "npm-bundled": "^3.0.0", - "npm-normalize-package-bin": "^3.0.0" + "@gar/promise-retry": "^1.0.0", + "@npmcli/git": "^7.0.0", + "@npmcli/installed-package-contents": "^4.0.0", + "@npmcli/package-json": "^7.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "@npmcli/run-script": "^10.0.0", + "cacache": "^20.0.0", + "fs-minipass": "^3.0.0", + "minipass": "^7.0.2", + "npm-package-arg": "^13.0.0", + "npm-packlist": "^10.0.1", + "npm-pick-manifest": "^11.0.1", + "npm-registry-fetch": "^19.0.0", + "proc-log": "^6.0.0", + "sigstore": "^4.0.0", + "ssri": "^13.0.0", + "tar": "^7.4.3" }, "bin": { - "installed-package-contents": "bin/index.js" + "pacote": "bin/index.js" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/map-workspaces": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/@npmcli/map-workspaces/-/map-workspaces-3.0.6.tgz", - "integrity": "sha512-tkYs0OYnzQm6iIRdfy+LcLBjcKuQCeE5YLb8KnrIlutJfheNaPvPpgoFEyEFgbjzl5PLZ3IA/BWAwRU0eHuQDA==", - "inBundle": true, + "node_modules/@npmcli/template-oss/node_modules/pacote/node_modules/@npmcli/git": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-7.0.2.tgz", + "integrity": "sha512-oeolHDjExNAJAnlYP2qzNjMX/Xi9bmu78C9dIGr4xjobrSKbuMYCph8lTzn4vnW3NjIqVmw/f8BCfouqyJXlRg==", + "dev": true, "license": "ISC", "dependencies": { - "@npmcli/name-from-folder": "^2.0.0", - "glob": "^10.2.2", - "minimatch": "^9.0.0", - "read-package-json-fast": "^3.0.0" + "@gar/promise-retry": "^1.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "ini": "^6.0.0", + "lru-cache": "^11.2.1", + "npm-pick-manifest": "^11.0.1", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "which": "^6.0.0" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/metavuln-calculator": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/@npmcli/metavuln-calculator/-/metavuln-calculator-7.1.1.tgz", - "integrity": "sha512-Nkxf96V0lAx3HCpVda7Vw4P23RILgdi/5K1fmj2tZkWIYLpXAN8k2UVVOsW16TsS5F8Ws2I7Cm+PU1/rsVF47g==", + "node_modules/@npmcli/template-oss/node_modules/pacote/node_modules/@npmcli/package-json": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/@npmcli/package-json/-/package-json-7.0.5.tgz", + "integrity": "sha512-iVuTlG3ORq2iaVa1IWUxAO/jIp77tUKBhoMjuzYW2kL4MLN1bi/ofqkZ7D7OOwh8coAx1/S2ge0rMdGv8sLSOQ==", + "dev": true, "license": "ISC", "dependencies": { - "cacache": "^18.0.0", - "json-parse-even-better-errors": "^3.0.0", - "pacote": "^18.0.0", - "proc-log": "^4.1.0", - "semver": "^7.3.5" + "@npmcli/git": "^7.0.0", + "glob": "^13.0.0", + "hosted-git-info": "^9.0.0", + "json-parse-even-better-errors": "^5.0.0", + "proc-log": "^6.0.0", + "semver": "^7.5.3", + "spdx-expression-parse": "^4.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/mock-globals": { - "resolved": "mock-globals", - "link": true - }, - "node_modules/@npmcli/mock-registry": { - "resolved": "mock-registry", - "link": true - }, - "node_modules/@npmcli/name-from-folder": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/name-from-folder/-/name-from-folder-2.0.0.tgz", - "integrity": "sha512-pwK+BfEBZJbKdNYpHHRTNBwBoqrN/iIMO0AiGvYsp3Hoaq0WbgGSWQR6SCldZovoDpY3yje5lkFUe6gsDgJ2vg==", - "inBundle": true, + "node_modules/@npmcli/template-oss/node_modules/pacote/node_modules/hosted-git-info": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz", + "integrity": "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==", + "dev": true, "license": "ISC", + "dependencies": { + "lru-cache": "^11.1.0" + }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/node-gyp": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/node-gyp/-/node-gyp-3.0.0.tgz", - "integrity": "sha512-gp8pRXC2oOxu0DUE1/M3bYtb1b3/DbJ5aM113+XJBgfXdussRAsX0YOrOhdd8WvnAR6auDBvJomGAkLKA5ydxA==", - "inBundle": true, + "node_modules/@npmcli/template-oss/node_modules/pacote/node_modules/ini": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-6.0.0.tgz", + "integrity": "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==", + "dev": true, "license": "ISC", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/package-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@npmcli/package-json/-/package-json-5.2.0.tgz", - "integrity": "sha512-qe/kiqqkW0AGtvBjL8TJKZk/eBBSpnJkUWvHdQ9jM2lKHXRYYJuyNpJPlJw3c8QjC2ow6NZYiLExhUaeJelbxQ==", - "inBundle": true, + "node_modules/@npmcli/template-oss/node_modules/pacote/node_modules/json-parse-even-better-errors": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-5.0.0.tgz", + "integrity": "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/template-oss/node_modules/pacote/node_modules/npm-package-arg": { + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-13.0.2.tgz", + "integrity": "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA==", + "dev": true, "license": "ISC", "dependencies": { - "@npmcli/git": "^5.0.0", - "glob": "^10.2.2", - "hosted-git-info": "^7.0.0", - "json-parse-even-better-errors": "^3.0.0", - "normalize-package-data": "^6.0.0", - "proc-log": "^4.0.0", - "semver": "^7.5.3" + "hosted-git-info": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^7.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/promise-spawn": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@npmcli/promise-spawn/-/promise-spawn-7.0.2.tgz", - "integrity": "sha512-xhfYPXoV5Dy4UkY0D+v2KkwvnDfiA/8Mt3sWCGI/hM03NsYIH8ZaG6QzS9x7pje5vHZBZJ2v6VRFVTWACnqcmQ==", - "inBundle": true, + "node_modules/@npmcli/template-oss/node_modules/pacote/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, "license": "ISC", - "dependencies": { - "which": "^4.0.0" - }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/query": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@npmcli/query/-/query-3.1.0.tgz", - "integrity": "sha512-C/iR0tk7KSKGldibYIB9x8GtO/0Bd0I2mhOaDb8ucQL/bQVTmGoeREaFj64Z5+iCBRf3dQfed0CjJL7I8iTkiQ==", + "node_modules/@npmcli/template-oss/node_modules/parse-conflict-json": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/parse-conflict-json/-/parse-conflict-json-5.0.1.tgz", + "integrity": "sha512-ZHEmNKMq1wyJXNwLxyHnluPfRAFSIliBvbK/UiOceROt4Xh9Pz0fq49NytIaeaCUf5VR86hwQ/34FCcNU5/LKQ==", + "dev": true, "license": "ISC", "dependencies": { - "postcss-selector-parser": "^6.0.10" + "json-parse-even-better-errors": "^5.0.0", + "just-diff": "^6.0.0", + "just-diff-apply": "^5.2.0" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/redact": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-2.0.1.tgz", - "integrity": "sha512-YgsR5jCQZhVmTJvjduTOIHph0L73pK8xwMVaDY0PatySqVM9AZj93jpoXYSJqfHFxFkN9dmqTw6OiqExsS3LPw==", - "inBundle": true, - "license": "ISC", + "node_modules/@npmcli/template-oss/node_modules/parse-conflict-json/node_modules/json-parse-even-better-errors": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-5.0.0.tgz", + "integrity": "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ==", + "dev": true, + "license": "MIT", "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/run-script": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@npmcli/run-script/-/run-script-8.1.0.tgz", - "integrity": "sha512-y7efHHwghQfk28G2z3tlZ67pLG0XdfYbcVG26r7YIXALRsrVQcTq4/tdenSmdOrEsNahIYA/eh8aEVROWGFUDg==", - "inBundle": true, + "node_modules/@npmcli/template-oss/node_modules/socks-proxy-agent": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@npmcli/template-oss/node_modules/ssri": { + "version": "13.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-13.0.1.tgz", + "integrity": "sha512-QUiRf1+u9wPTL/76GTYlKttDEBWV1ga9ZXW8BG6kfdeyyM8LGPix9gROyg9V2+P0xNyF3X2Go526xKFdMZrHSQ==", + "dev": true, "license": "ISC", "dependencies": { - "@npmcli/node-gyp": "^3.0.0", - "@npmcli/package-json": "^5.0.0", - "@npmcli/promise-spawn": "^7.0.0", - "node-gyp": "^10.0.0", - "proc-log": "^4.0.0", - "which": "^4.0.0" + "minipass": "^7.0.3" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/smoke-tests": { - "resolved": "smoke-tests", - "link": true + "node_modules/@npmcli/template-oss/node_modules/validate-npm-package-name": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-7.0.2.tgz", + "integrity": "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } }, - "node_modules/@npmcli/template-oss": { - "version": "4.22.0", - "resolved": "https://registry.npmjs.org/@npmcli/template-oss/-/template-oss-4.22.0.tgz", - "integrity": "sha512-aCvUL/sqMoTcfqLRqe5RjkrhUHeWXuUr+GlADWT0O2t2nf/D5jttP714agVd1+d1UbE/LOhw7tGirvKhNGlC+A==", + "node_modules/@npmcli/template-oss/node_modules/which": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", + "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==", "dev": true, - "hasInstallScript": true, "license": "ISC", - "workspaces": [ - "workspace/test-workspace" - ], "dependencies": { - "@actions/core": "^1.9.1", - "@commitlint/cli": "^19.0.3", - "@commitlint/config-conventional": "^19.2.2", - "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/arborist": "^7.2.1", - "@npmcli/git": "^5.0.3", - "@npmcli/map-workspaces": "^3.0.0", - "@npmcli/package-json": "^5.0.0", - "@octokit/rest": "^19.0.4", - "dedent": "^1.5.1", - "diff": "^5.0.0", - "glob": "^10.1.0", - "handlebars": "^4.7.7", - "hosted-git-info": "^7.0.1", - "ini": "^4.0.0", - "json-parse-even-better-errors": "^3.0.0", - "just-deep-map-values": "^1.1.1", - "just-diff": "^6.0.0", - "just-omit": "^2.2.0", - "lodash": "^4.17.21", - "minimatch": "^9.0.2", - "npm-package-arg": "^11.0.1", - "proc-log": "^4.0.0", - "release-please": "16.10.2", - "semver": "^7.3.5", - "undici": "^6.7.0", - "yaml": "^2.1.1" + "isexe": "^4.0.0" }, "bin": { - "template-oss-apply": "bin/apply.js", - "template-oss-check": "bin/check.js", - "template-oss-release-manager": "bin/release-manager.js", - "template-oss-release-please": "bin/release-please.js" + "node-which": "bin/which.js" }, "engines": { - "node": "^18.17.0 || >=20.5.0" + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/@octokit/auth-token": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-3.0.4.tgz", - "integrity": "sha512-TWFX7cZF2LXoCvdmJWY7XVPi74aSY0+FfBZNSXEXFkMpjcqsQwDSYVv5FhRFaI0V1ECnwbz4j59T/G+rXNWaIQ==", + "version": "6.0.0", "dev": true, "license": "MIT", "engines": { - "node": ">= 14" + "node": ">= 20" } }, "node_modules/@octokit/core": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@octokit/core/-/core-4.2.4.tgz", - "integrity": "sha512-rYKilwgzQ7/imScn3M9/pFfUf4I1AZEH3KhyJmtPdE2zfaXAn2mFfUy4FbKewzc2We5y/LlKLj36fWJLKC2SIQ==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-7.0.6.tgz", + "integrity": "sha512-DhGl4xMVFGVIyMwswXeyzdL4uXD5OGILGX5N8Y+f6W7LhC1Ze2poSNrkF/fedpVDHEEZ+PHFW0vL14I+mm8K3Q==", "dev": true, "license": "MIT", "dependencies": { - "@octokit/auth-token": "^3.0.0", - "@octokit/graphql": "^5.0.0", - "@octokit/request": "^6.0.0", - "@octokit/request-error": "^3.0.0", - "@octokit/types": "^9.0.0", - "before-after-hook": "^2.2.0", - "universal-user-agent": "^6.0.0" + "@octokit/auth-token": "^6.0.0", + "@octokit/graphql": "^9.0.3", + "@octokit/request": "^10.0.6", + "@octokit/request-error": "^7.0.2", + "@octokit/types": "^16.0.0", + "before-after-hook": "^4.0.0", + "universal-user-agent": "^7.0.0" }, "engines": { - "node": ">= 14" + "node": ">= 20" } }, "node_modules/@octokit/endpoint": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-7.0.6.tgz", - "integrity": "sha512-5L4fseVRUsDFGR00tMWD/Trdeeihn999rTMGRMC1G/Ldi1uWlWJzI98H4Iak5DB/RVvQuyMYKqSK/R6mbSOQyg==", + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-11.0.3.tgz", + "integrity": "sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag==", "dev": true, "license": "MIT", "dependencies": { - "@octokit/types": "^9.0.0", - "is-plain-object": "^5.0.0", - "universal-user-agent": "^6.0.0" + "@octokit/types": "^16.0.0", + "universal-user-agent": "^7.0.2" }, "engines": { - "node": ">= 14" + "node": ">= 20" } }, "node_modules/@octokit/graphql": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-5.0.6.tgz", - "integrity": "sha512-Fxyxdy/JH0MnIB5h+UQ3yCoh1FG4kWXfFKkpWqjZHw/p+Kc8Y44Hu/kCgNBT6nU1shNumEchmW/sUO1JuQnPcw==", + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-9.0.3.tgz", + "integrity": "sha512-grAEuupr/C1rALFnXTv6ZQhFuL1D8G5y8CN04RgrO4FIPMrtm+mcZzFG7dcBm+nq+1ppNixu+Jd78aeJOYxlGA==", "dev": true, "license": "MIT", "dependencies": { - "@octokit/request": "^6.0.0", - "@octokit/types": "^9.0.0", - "universal-user-agent": "^6.0.0" + "@octokit/request": "^10.0.6", + "@octokit/types": "^16.0.0", + "universal-user-agent": "^7.0.0" }, "engines": { - "node": ">= 14" + "node": ">= 20" } }, "node_modules/@octokit/openapi-types": { - "version": "18.1.1", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-18.1.1.tgz", - "integrity": "sha512-VRaeH8nCDtF5aXWnjPuEMIYf1itK/s3JYyJcWFJT8X9pSNnBtriDf7wlEWsGuhPLl4QIH4xM8fqTXDwJ3Mu6sw==", + "version": "27.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-27.0.0.tgz", + "integrity": "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA==", "dev": true, "license": "MIT" }, "node_modules/@octokit/plugin-paginate-rest": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-6.1.2.tgz", - "integrity": "sha512-qhrmtQeHU/IivxucOV1bbI/xZyC/iOBhclokv7Sut5vnejAIAEXVcGQeRpQlU39E0WwK9lNvJHphHri/DB6lbQ==", + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-14.0.0.tgz", + "integrity": "sha512-fNVRE7ufJiAA3XUrha2omTA39M6IXIc6GIZLvlbsm8QOQCYvpq/LkMNGyFlB1d8hTDzsAXa3OKtybdMAYsV/fw==", "dev": true, "license": "MIT", "dependencies": { - "@octokit/tsconfig": "^1.0.2", - "@octokit/types": "^9.2.3" + "@octokit/types": "^16.0.0" }, "engines": { - "node": ">= 14" + "node": ">= 20" }, "peerDependencies": { - "@octokit/core": ">=4" + "@octokit/core": ">=6" } }, "node_modules/@octokit/plugin-request-log": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-1.0.4.tgz", - "integrity": "sha512-mLUsMkgP7K/cnFEw07kWqXGF5LKrOkD+lhCrKvPHXWDywAwuDUeDwWBpc69XK3pNX0uKiVt8g5z96PJ6z9xCFA==", + "version": "6.0.0", "dev": true, "license": "MIT", + "engines": { + "node": ">= 20" + }, "peerDependencies": { - "@octokit/core": ">=3" + "@octokit/core": ">=6" } }, "node_modules/@octokit/plugin-rest-endpoint-methods": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-7.2.3.tgz", - "integrity": "sha512-I5Gml6kTAkzVlN7KCtjOM+Ruwe/rQppp0QU372K1GP7kNOYEKe8Xn5BW4sE62JAHdwpq95OQK/qGNyKQMUzVgA==", + "version": "17.0.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-17.0.0.tgz", + "integrity": "sha512-B5yCyIlOJFPqUUeiD0cnBJwWJO8lkJs5d8+ze9QDP6SvfiXSz1BF+91+0MeI1d2yxgOhU/O+CvtiZ9jSkHhFAw==", "dev": true, "license": "MIT", "dependencies": { - "@octokit/types": "^10.0.0" + "@octokit/types": "^16.0.0" }, "engines": { - "node": ">= 14" + "node": ">= 20" }, "peerDependencies": { - "@octokit/core": ">=3" - } - }, - "node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/types": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-10.0.0.tgz", - "integrity": "sha512-Vm8IddVmhCgU1fxC1eyinpwqzXPEYu0NrYzD3YZjlGjyftdLBTeqNblRC0jmJmgxbJIsQlyogVeGnrNaaMVzIg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^18.0.0" + "@octokit/core": ">=6" } }, "node_modules/@octokit/request": { - "version": "6.2.8", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-6.2.8.tgz", - "integrity": "sha512-ow4+pkVQ+6XVVsekSYBzJC0VTVvh/FCTUUgTsboGq+DTeWdyIFV8WSCdo0RIxk6wSkBTHqIK1mYuY7nOBXOchw==", + "version": "10.0.10", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-10.0.10.tgz", + "integrity": "sha512-KxNC2pTqqhszMNrf12ZRd4PonRgyJdsM4F/jySiddQK+DsRcfBtUvqn8t7UsyZhnRJHvX46OohDt5N3VqIWC2w==", "dev": true, "license": "MIT", "dependencies": { - "@octokit/endpoint": "^7.0.0", - "@octokit/request-error": "^3.0.0", - "@octokit/types": "^9.0.0", - "is-plain-object": "^5.0.0", - "node-fetch": "^2.6.7", - "universal-user-agent": "^6.0.0" + "@octokit/endpoint": "^11.0.3", + "@octokit/request-error": "^7.0.2", + "@octokit/types": "^16.0.0", + "content-type": "^2.0.0", + "json-with-bigint": "^3.5.3", + "universal-user-agent": "^7.0.2" }, "engines": { - "node": ">= 14" + "node": ">= 20" } }, "node_modules/@octokit/request-error": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-3.0.3.tgz", - "integrity": "sha512-crqw3V5Iy2uOU5Np+8M/YexTlT8zxCfI+qu+LxUB7SZpje4Qmx3mub5DfEKSO8Ylyk0aogi6TYdf6kxzh2BguQ==", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-7.1.0.tgz", + "integrity": "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw==", "dev": true, "license": "MIT", "dependencies": { - "@octokit/types": "^9.0.0", - "deprecation": "^2.0.0", - "once": "^1.4.0" + "@octokit/types": "^16.0.0" }, "engines": { - "node": ">= 14" + "node": ">= 20" } }, "node_modules/@octokit/rest": { - "version": "19.0.13", - "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-19.0.13.tgz", - "integrity": "sha512-/EzVox5V9gYGdbAI+ovYj3nXQT1TtTHRT+0eZPcuC05UFSWO3mdO9UY1C0i2eLF9Un1ONJkAk+IEtYGAC+TahA==", + "version": "22.0.1", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-22.0.1.tgz", + "integrity": "sha512-Jzbhzl3CEexhnivb1iQ0KJ7s5vvjMWcmRtq5aUsKmKDrRW6z3r84ngmiFKFvpZjpiU/9/S6ITPFRpn5s/3uQJw==", "dev": true, "license": "MIT", "dependencies": { - "@octokit/core": "^4.2.1", - "@octokit/plugin-paginate-rest": "^6.1.2", - "@octokit/plugin-request-log": "^1.0.4", - "@octokit/plugin-rest-endpoint-methods": "^7.1.2" + "@octokit/core": "^7.0.6", + "@octokit/plugin-paginate-rest": "^14.0.0", + "@octokit/plugin-request-log": "^6.0.0", + "@octokit/plugin-rest-endpoint-methods": "^17.0.0" }, "engines": { - "node": ">= 14" + "node": ">= 20" } }, - "node_modules/@octokit/tsconfig": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@octokit/tsconfig/-/tsconfig-1.0.2.tgz", - "integrity": "sha512-I0vDR0rdtP8p2lGMzvsJzbhdOWy405HcGovrspJ8RRibHnyRgggUSNO5AIox5LmqiwmatHKYsvj6VGFHkqS7lA==", + "node_modules/@octokit/types": { + "version": "16.0.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-16.0.0.tgz", + "integrity": "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^27.0.0" + } + }, + "node_modules/@open-draft/deferred-promise": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@open-draft/deferred-promise/-/deferred-promise-2.2.0.tgz", + "integrity": "sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA==", "dev": true, "license": "MIT" }, - "node_modules/@octokit/types": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-9.3.2.tgz", - "integrity": "sha512-D4iHGTdAnEEVsB8fl95m1hiz7D5YiRdQ9b/OEb3BYRVwbLsGHcRVPz+u+BgRLNk0Q0/4iZCBqDN96j2XNxfXrA==", + "node_modules/@open-draft/logger": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@open-draft/logger/-/logger-0.3.0.tgz", + "integrity": "sha512-X2g45fzhxH238HKO4xbSr7+wBS8Fvw6ixhTDuvLd5mqh6bJJCFAPwU9mPDxbcrRtfxv4u5IHCEH77BmxvXmmxQ==", "dev": true, "license": "MIT", "dependencies": { - "@octokit/openapi-types": "^18.0.0" + "is-node-process": "^1.2.0", + "outvariant": "^1.4.0" } }, - "node_modules/@pkgjs/parseargs": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", - "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", - "inBundle": true, + "node_modules/@open-draft/until": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@open-draft/until/-/until-2.1.0.tgz", + "integrity": "sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rtsao/scc": { + "version": "1.1.0", + "dev": true, "license": "MIT", - "optional": true, + "peer": true + }, + "node_modules/@sigstore/bundle": { + "version": "4.0.0", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.5.0" + }, "engines": { - "node": ">=14" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@sigstore/bundle": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/@sigstore/bundle/-/bundle-2.3.2.tgz", - "integrity": "sha512-wueKWDk70QixNLB363yHc2D2ItTgYiMTdPwK8D9dKQMR3ZQ0c35IxP5xnwQ8cNLoCgCRcHf14kE+CLIvNX1zmA==", + "node_modules/@sigstore/core": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@sigstore/core/-/core-3.2.1.tgz", + "integrity": "sha512-qRsxPnCrbC/puegGxKuynfnxgLiHqWStrSjxkoB4YKqq3Z3s4cyZyj42ZdWFAEblNP65C+rBH8EuREHIXoi83g==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@sigstore/protobuf-specs": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/@sigstore/protobuf-specs/-/protobuf-specs-0.5.1.tgz", + "integrity": "sha512-/ScWUhhoFasJsSRGTVBwId1loQjjnjAfE4djL6ZhrXRpNCmPTnUKF5Jokd58ILseOMjzET3UrMOtJPS9sYeI0g==", "inBundle": true, "license": "Apache-2.0", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@sigstore/sign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@sigstore/sign/-/sign-4.1.1.tgz", + "integrity": "sha512-Hf4xglukg0XXQ2RiD5vSoLjdPe8OBUPA8XeVjUObheuDcWdYWrnH/BNmxZCzkAy68MzmNCxXLeurJvs6hcP2OQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@gar/promise-retry": "^1.0.2", + "@sigstore/bundle": "^4.0.0", + "@sigstore/core": "^3.2.0", + "@sigstore/protobuf-specs": "^0.5.0", + "make-fetch-happen": "^15.0.4", + "proc-log": "^6.1.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@sigstore/sign/node_modules/@npmcli/agent": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-4.0.2.tgz", + "integrity": "sha512-EUEuWAxnL07Sp5/iC/1X6Xj+XThUvnbei9zfRWZdEXa7lss9RTHMhAHBeg+MZ5To9s/gGaSI+UwZTPdYMvKSeg==", + "dev": true, + "license": "ISC", + "dependencies": { + "agent-base": "^7.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.1", + "lru-cache": "^11.2.1", + "socks-proxy-agent": "^8.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@sigstore/sign/node_modules/@npmcli/fs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-5.0.0.tgz", + "integrity": "sha512-7OsC1gNORBEawOa5+j2pXN9vsicaIOH5cPXxoR6fJOmH6/EXpJB2CajXOu1fPRFun2m1lktEFX11+P89hqO/og==", + "dev": true, + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@sigstore/sign/node_modules/@npmcli/redact": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-4.0.0.tgz", + "integrity": "sha512-gOBg5YHMfZy+TfHArfVogwgfBeQnKbbGo3pSUyK/gSI0AVu+pEiDVcKlQb0D8Mg1LNRZILZ6XG8I5dJ4KuAd9Q==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@sigstore/sign/node_modules/cacache": { + "version": "20.0.4", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-20.0.4.tgz", + "integrity": "sha512-M3Lab8NPYlZU2exsL3bMVvMrMqgwCnMWfdZbK28bn3pK6APT/Te/I8hjRPNu1uwORY9a1eEQoifXbKPQMfMTOA==", + "dev": true, + "license": "ISC", + "dependencies": { + "@npmcli/fs": "^5.0.0", + "fs-minipass": "^3.0.0", + "glob": "^13.0.0", + "lru-cache": "^11.1.0", + "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": "^13.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@sigstore/sign/node_modules/make-fetch-happen": { + "version": "15.0.6", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-15.0.6.tgz", + "integrity": "sha512-Je0fLJ0F5atA7F+eIlLzk+Wkcl57JDf4kf+EW8xiP5E31xOQxkIxTbgf1Oi1Lw9tRI9UEMRdI5Vz2xTzoNU1Jw==", + "dev": true, + "license": "ISC", "dependencies": { - "@sigstore/protobuf-specs": "^0.3.2" + "@gar/promise-retry": "^1.0.0", + "@npmcli/agent": "^4.0.0", + "@npmcli/redact": "^4.0.0", + "cacache": "^20.0.1", + "http-cache-semantics": "^4.1.1", + "minipass": "^7.0.2", + "minipass-fetch": "^5.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^1.0.0", + "proc-log": "^6.0.0", + "ssri": "^13.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@sigstore/core": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@sigstore/core/-/core-1.1.0.tgz", - "integrity": "sha512-JzBqdVIyqm2FRQCulY6nbQzMpJJpSiJ8XXWMhtOX9eKgaXXpfNOF53lzQEjIydlStnd/eFtuC1dW4VYdD93oRg==", - "inBundle": true, - "license": "Apache-2.0", + "node_modules/@sigstore/sign/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@sigstore/protobuf-specs": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/@sigstore/protobuf-specs/-/protobuf-specs-0.3.2.tgz", - "integrity": "sha512-c6B0ehIWxMI8wiS/bj6rHMPqeFvngFV7cDU/MY+B16P9Z3Mp9k8L93eYZ7BYzSickzuqAQqAq0V956b3Ju6mLw==", - "inBundle": true, - "license": "Apache-2.0", + "node_modules/@sigstore/sign/node_modules/socks-proxy-agent": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": ">= 14" } }, - "node_modules/@sigstore/sign": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/@sigstore/sign/-/sign-2.3.2.tgz", - "integrity": "sha512-5Vz5dPVuunIIvC5vBb0APwo7qKA4G9yM48kPWJT+OEERs40md5GoUR1yedwpekWZ4m0Hhw44m6zU+ObsON+iDA==", - "inBundle": true, - "license": "Apache-2.0", + "node_modules/@sigstore/sign/node_modules/ssri": { + "version": "13.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-13.0.1.tgz", + "integrity": "sha512-QUiRf1+u9wPTL/76GTYlKttDEBWV1ga9ZXW8BG6kfdeyyM8LGPix9gROyg9V2+P0xNyF3X2Go526xKFdMZrHSQ==", + "dev": true, + "license": "ISC", "dependencies": { - "@sigstore/bundle": "^2.3.2", - "@sigstore/core": "^1.0.0", - "@sigstore/protobuf-specs": "^0.3.2", - "make-fetch-happen": "^13.0.1", - "proc-log": "^4.2.0", - "promise-retry": "^2.0.1" + "minipass": "^7.0.3" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/@sigstore/tuf": { - "version": "2.3.4", - "resolved": "https://registry.npmjs.org/@sigstore/tuf/-/tuf-2.3.4.tgz", - "integrity": "sha512-44vtsveTPUpqhm9NCrbU8CWLe3Vck2HO1PNLw7RIajbB7xhtn5RBPm1VNSCMwqGYHhDsBJG8gDF0q4lgydsJvw==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@sigstore/tuf/-/tuf-5.0.0.tgz", + "integrity": "sha512-Zyqg9tcHps3uRAlKHLNmsW4ohsUZAjb9G+31r7lg0ICh/JOcadzmJsIRdjKljlRHpaR0K4aJ2kXXIdywdcdMlA==", "inBundle": true, "license": "Apache-2.0", "dependencies": { - "@sigstore/protobuf-specs": "^0.3.2", - "tuf-js": "^2.2.1" + "@sigstore/protobuf-specs": "^0.5.0", + "tuf-js": "^6.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/@sigstore/verify": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@sigstore/verify/-/verify-1.2.1.tgz", - "integrity": "sha512-8iKx79/F73DKbGfRf7+t4dqrc0bRr0thdPrxAtCKWRm/F0tG71i6O1rvlnScncJLLBZHn3h8M3c1BSUAb9yu8g==", - "inBundle": true, + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@sigstore/verify/-/verify-3.1.1.tgz", + "integrity": "sha512-qv7+G3J2cc6wwFj3yKvXOamzqhMwSk1ogPGmhpS8iXllcPrJaIIBA+4HbttlHVu1pqWTdmaCH/WE7UOC51kdoA==", + "dev": true, "license": "Apache-2.0", "dependencies": { - "@sigstore/bundle": "^2.3.2", - "@sigstore/core": "^1.1.0", - "@sigstore/protobuf-specs": "^0.3.2" + "@sigstore/bundle": "^4.0.0", + "@sigstore/core": "^3.2.1", + "@sigstore/protobuf-specs": "^0.5.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@simple-libs/child-process-utils": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@simple-libs/child-process-utils/-/child-process-utils-1.0.2.tgz", + "integrity": "sha512-/4R8QKnd/8agJynkNdJmNw2MBxuFTRcNFnE5Sg/G+jkSsV8/UBgULMzhizWWW42p8L5H7flImV2ATi79Ove2Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@simple-libs/stream-utils": "^1.2.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://ko-fi.com/dangreen" + } + }, + "node_modules/@simple-libs/stream-utils": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@simple-libs/stream-utils/-/stream-utils-1.2.0.tgz", + "integrity": "sha512-KxXvfapcixpz6rVEB6HPjOUZT22yN6v0vI0urQSk1L8MlEWPDFCZkhw2xmkyoTGYeFw7tWTZd7e3lVzRZRN/EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://ko-fi.com/dangreen" } }, "node_modules/@tufjs/canonical-json": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@tufjs/canonical-json/-/canonical-json-2.0.0.tgz", - "integrity": "sha512-yVtV8zsdo8qFHe+/3kw81dSLyF7D576A5cCFCi4X7B39tWT7SekaEFUnvnWJHz+9qO7qJTah1JbrDjWKqFtdWA==", "inBundle": true, "license": "MIT", "engines": { @@ -2135,47 +4112,51 @@ } }, "node_modules/@tufjs/models": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@tufjs/models/-/models-2.0.1.tgz", - "integrity": "sha512-92F7/SFyufn4DXsha9+QfKnN03JGqtMFMXgSHbZOo8JG59WkTni7UzAouNQDf7AuP9OAMxVOPQcqG3sB7w+kkg==", - "inBundle": true, + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@tufjs/models/-/models-4.1.0.tgz", + "integrity": "sha512-Y8cK9aggNRsqJVaKUlEYs4s7CvQ1b1ta2DVPyAimb0I2qhzjNk+A+mxvll/klL0RlfuIUei8BF7YWiua4kQqww==", + "dev": true, "license": "MIT", "dependencies": { "@tufjs/canonical-json": "2.0.0", - "minimatch": "^9.0.4" + "minimatch": "^10.1.1" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/@tufjs/repo-mock": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@tufjs/repo-mock/-/repo-mock-2.0.1.tgz", - "integrity": "sha512-ZeINpjuIy4BmBv52b4dRPQWRUNlxJiW6+lvN0IYdkqpiW6XPoZ5WegFz/GEhBi9NtzyR+liBQi4Lf0oHQ4qoLw==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@tufjs/repo-mock/-/repo-mock-5.0.0.tgz", + "integrity": "sha512-Dh5V96x0bKkEhwnIl8RgpuzOjn8ll5XgoVUpGM1hXta9b8beZr3EJTmhgCH2d1T8vCbWRJADcjTYpg/ZUz9/rg==", "dev": true, "license": "MIT", "dependencies": { - "@tufjs/models": "2.0.1", - "nock": "^13.5.4" + "@tufjs/models": "5.0.0", + "nock": "^14.0.11" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, - "node_modules/@types/conventional-commits-parser": { + "node_modules/@tufjs/repo-mock/node_modules/@tufjs/models": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@types/conventional-commits-parser/-/conventional-commits-parser-5.0.0.tgz", - "integrity": "sha512-loB369iXNmAZglwWATL+WRe+CRMmmBPtpolYzIebFaX4YA3x+BEfLqhUAV9WanycKI3TG1IMr5bMJDajDKLlUQ==", + "resolved": "https://registry.npmjs.org/@tufjs/models/-/models-5.0.0.tgz", + "integrity": "sha512-U4mVcdFGOi6pt8n38LdWZp67Svn7ppnU1Pj8SGOVaBi1X4gm+G4ztQlLfkoJbKSHfjA6WeaiJp2A4V83AJF6nQ==", "dev": true, "license": "MIT", "dependencies": { - "@types/node": "*" + "@tufjs/canonical-json": "2.0.0", + "minimatch": "^10.2.1" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/@types/debug": { - "version": "4.1.12", - "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz", - "integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==", + "version": "4.1.13", + "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz", + "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==", "dev": true, "license": "MIT", "dependencies": { @@ -2183,89 +4164,69 @@ } }, "node_modules/@types/hast": { - "version": "2.3.10", - "resolved": "https://registry.npmjs.org/@types/hast/-/hast-2.3.10.tgz", - "integrity": "sha512-McWspRw8xx8J9HurkVBfYj0xKoE25tOFlHGdx4MJ5xORQrMGZNqJhVQWaIbm6Oyla5kYOXtDiopzKRJzEOkwJw==", + "version": "3.0.4", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2" + "@types/unist": "*" } }, "node_modules/@types/json5": { "version": "0.0.29", - "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", - "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", "dev": true, "license": "MIT", "peer": true }, "node_modules/@types/mdast": { - "version": "3.0.15", - "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-3.0.15.tgz", - "integrity": "sha512-LnwD+mUEfxWMa1QpDraczIn6k0Ee3SMicuYSSzS6ZYl2gKS09EClnJYGd8Du6rfc5r/GZEk5o1mRb8TaTj03sQ==", + "version": "4.0.4", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2" + "@types/unist": "*" } }, "node_modules/@types/minimist": { "version": "1.2.5", - "resolved": "https://registry.npmjs.org/@types/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-hov8bUuiLiyFPGyFPE1lwWhmzYbirOXQNNo40+y3zow8aFVTeyn3VWL0VFFfdNddA8S4Vf0Tc062rzyNr7Paag==", "dev": true, "license": "MIT" }, "node_modules/@types/ms": { - "version": "0.7.34", - "resolved": "https://registry.npmjs.org/@types/ms/-/ms-0.7.34.tgz", - "integrity": "sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==", + "version": "2.1.0", "dev": true, "license": "MIT" }, "node_modules/@types/node": { - "version": "20.14.6", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.6.tgz", - "integrity": "sha512-JbA0XIJPL1IiNnU7PFxDXyfAwcwVVrOoqyzzyQTyMeVhBzkJVMSkC1LlVsRQ2lpqiY4n6Bb9oCS6lzDKVQxbZw==", + "version": "25.9.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.1.tgz", + "integrity": "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { - "undici-types": "~5.26.4" + "undici-types": ">=7.24.0 <7.24.7" } }, "node_modules/@types/normalize-package-data": { "version": "2.4.4", - "resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.4.tgz", - "integrity": "sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==", "dev": true, "license": "MIT" }, "node_modules/@types/npm-package-arg": { "version": "6.1.4", - "resolved": "https://registry.npmjs.org/@types/npm-package-arg/-/npm-package-arg-6.1.4.tgz", - "integrity": "sha512-vDgdbMy2QXHnAruzlv68pUtXCjmqUk3WrBAsRboRovsOmxbfn/WiYCjmecyKjGztnMps5dWp4Uq2prp+Ilo17Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/parse5": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/@types/parse5/-/parse5-6.0.3.tgz", - "integrity": "sha512-SuT16Q1K51EAVPz1K29DJ/sXjhSQ0zjvsypYJ6tlwVsRV9jwW5Adq2ch8Dq8kDBCkYnELS7N7VNCSB5nC56t/g==", "dev": true, "license": "MIT" }, "node_modules/@types/unist": { - "version": "2.0.10", - "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.10.tgz", - "integrity": "sha512-IfYcSBWE3hLpBg8+X2SEa8LVkJdJEkT2Ese2aaLs3ptGdVtABxndrMaxuFlQ1qdFf9Q5rDvDpxI3WwgvKFAsQA==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", "dev": true, "license": "MIT" }, "node_modules/@types/yargs": { - "version": "16.0.9", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-16.0.9.tgz", - "integrity": "sha512-tHhzvkFXZQeTECenFoRljLBYPZJ7jAVxqqtEI0qTLOmuultnFp4I9yKE17vTuhf7BkhCu7I4XuemPgikDVuYqA==", + "version": "16.0.11", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-16.0.11.tgz", + "integrity": "sha512-sbtvk8wDN+JvEdabmZExoW/HNr1cB7D/j4LT08rMiuikfA7m/JNJg7ATQcgzs34zHnoScDkY0ZRSl29Fkmk36g==", "dev": true, "license": "MIT", "dependencies": { @@ -2274,23 +4235,20 @@ }, "node_modules/@types/yargs-parser": { "version": "21.0.3", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", - "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", "dev": true, "license": "MIT" }, "node_modules/@ungap/structured-clone": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.2.0.tgz", - "integrity": "sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.1.tgz", + "integrity": "sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/@xmldom/xmldom": { - "version": "0.8.10", - "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.10.tgz", - "integrity": "sha512-2WALfTl4xo2SkGCYRt6rDTFfk9R1czmBvUQy12gK2KuRKIpWEhcbbzy8EZXtz/jkRqHX8bFEc6FC1HjX4TUWYw==", + "version": "0.8.13", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz", + "integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==", "dev": true, "license": "MIT", "engines": { @@ -2298,19 +4256,19 @@ } }, "node_modules/abbrev": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-2.0.0.tgz", - "integrity": "sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-5.0.0.tgz", + "integrity": "sha512-/XrFJgzQQQHpti1raDJC6m4ws6aNktmjBlhk8Fdlk7LwCEuDoieEJJY9OFHjfiFJFFRM2tK+Ky/IsfbbmlMu1w==", "inBundle": true, "license": "ISC", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/acorn": { - "version": "8.12.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.0.tgz", - "integrity": "sha512-RTvkC4w+KNXrM39/lWCUaG0IbRkWdCv7W/IOW9oU6SawyxulvkQy5HQPVTKxEjczcUvapcrw3cFx/60VN/NRNw==", + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", "dev": true, "license": "MIT", "peer": true, @@ -2323,8 +4281,6 @@ }, "node_modules/acorn-jsx": { "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", "dev": true, "license": "MIT", "peer": true, @@ -2333,23 +4289,16 @@ } }, "node_modules/agent-base": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", - "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", - "inBundle": true, + "version": "7.1.4", + "dev": true, "license": "MIT", - "dependencies": { - "debug": "^4.3.4" - }, "engines": { "node": ">= 14" } }, "node_modules/aggregate-error": { "version": "3.1.0", - "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", - "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", - "inBundle": true, + "dev": true, "license": "MIT", "dependencies": { "clean-stack": "^2.0.0", @@ -2360,16 +4309,16 @@ } }, "node_modules/ajv": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.16.0.tgz", - "integrity": "sha512-F0twR8U1ZU67JIEtekUcLkXkoO5mMMmgGD8sK/xUFzJ805jxHQl92hImFAqqXMyMYjSPOyUPAwHYhB72g5sTXw==", + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", "dev": true, "license": "MIT", "dependencies": { "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2", - "uri-js": "^4.4.1" + "require-from-string": "^2.0.2" }, "funding": { "type": "github", @@ -2377,9 +4326,7 @@ } }, "node_modules/ajv-formats": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", - "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", + "version": "3.0.1", "dev": true, "license": "MIT", "dependencies": { @@ -2396,8 +4343,6 @@ }, "node_modules/ajv-formats-draft2019": { "version": "1.6.1", - "resolved": "https://registry.npmjs.org/ajv-formats-draft2019/-/ajv-formats-draft2019-1.6.1.tgz", - "integrity": "sha512-JQPvavpkWDvIsBp2Z33UkYCtXCSpW4HD3tAZ+oL4iEFOk9obQZffx0yANwECt6vzr6ET+7HN5czRyqXbnq/u0Q==", "dev": true, "license": "MIT", "dependencies": { @@ -2412,31 +4357,14 @@ }, "node_modules/ansi-regex": { "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "inBundle": true, + "dev": true, "license": "MIT", "engines": { "node": ">=8" } }, - "node_modules/ansi-styles": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", - "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", - "inBundle": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, "node_modules/anymatch": { "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", "dev": true, "license": "ISC", "dependencies": { @@ -2449,8 +4377,6 @@ }, "node_modules/append-transform": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/append-transform/-/append-transform-2.0.0.tgz", - "integrity": "sha512-7yeyCEurROLQJFv5Xj4lEGTy0borxepjFv1g22oAdqFu//SrAlDl1O1Nxx15SH1RoliUml6p8dwJW9jvZughhg==", "dev": true, "license": "MIT", "dependencies": { @@ -2461,29 +4387,21 @@ } }, "node_modules/aproba": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", - "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==", + "version": "2.1.0", "license": "ISC" }, "node_modules/archy": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/archy/-/archy-1.0.0.tgz", - "integrity": "sha512-Xg+9RwCg/0p32teKdGMPTPnVXKD0w3DfHnFTficozsAgsvq2XenPJq/MYpzzQ/v8zrOyJn6Ds39VA4JIDwFfqw==", "inBundle": true, "license": "MIT" }, "node_modules/argparse": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "dev": true, "license": "Python-2.0" }, "node_modules/args": { "version": "5.0.3", - "resolved": "https://registry.npmjs.org/args/-/args-5.0.3.tgz", - "integrity": "sha512-h6k/zfFgusnv3i5TU08KQkVKuCPBtL/PWQbWkHUxvJrZ2nAyeaUupneemcrgn1xmqxPQsPIzwkUhOpoqPDRZuA==", "dev": true, "license": "MIT", "dependencies": { @@ -2498,8 +4416,6 @@ }, "node_modules/args/node_modules/ansi-styles": { "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", "dev": true, "license": "MIT", "dependencies": { @@ -2511,8 +4427,6 @@ }, "node_modules/args/node_modules/camelcase": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.0.0.tgz", - "integrity": "sha512-faqwZqnWxbxn+F1d399ygeamQNy3lPp/H9H6rNrqYh4FSVCtcY+3cub1MxA8o9mDd55mM8Aghuu/kuyYA6VTsA==", "dev": true, "license": "MIT", "engines": { @@ -2521,8 +4435,6 @@ }, "node_modules/args/node_modules/chalk": { "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "dev": true, "license": "MIT", "dependencies": { @@ -2536,8 +4448,6 @@ }, "node_modules/args/node_modules/color-convert": { "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", "dev": true, "license": "MIT", "dependencies": { @@ -2546,25 +4456,27 @@ }, "node_modules/args/node_modules/color-name": { "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", "dev": true, "license": "MIT" }, "node_modules/args/node_modules/escape-string-regexp": { "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", "dev": true, "license": "MIT", "engines": { "node": ">=0.8.0" } }, + "node_modules/args/node_modules/has-flag": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/args/node_modules/mri": { "version": "1.1.4", - "resolved": "https://registry.npmjs.org/mri/-/mri-1.1.4.tgz", - "integrity": "sha512-6y7IjGPm8AzlvoUrwAaw1tLnUBudaS3752vcd8JtrpGGQn+rXIe63LFVHm/YMwtqAuh+LJPCFdlLYPWM1nYn6w==", "dev": true, "license": "MIT", "engines": { @@ -2573,8 +4485,6 @@ }, "node_modules/args/node_modules/supports-color": { "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "dev": true, "license": "MIT", "dependencies": { @@ -2585,15 +4495,13 @@ } }, "node_modules/array-buffer-byte-length": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.1.tgz", - "integrity": "sha512-ahC5W1xgou+KTXix4sAO8Ki12Q+jf4i0+tmk3sC+zgcynshkHxzpXdImBehiUYKKKDwvfFiJl1tZt6ewscS1Mg==", + "version": "1.0.2", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.5", - "is-array-buffer": "^3.0.4" + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" }, "engines": { "node": ">= 0.4" @@ -2604,25 +4512,23 @@ }, "node_modules/array-ify": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/array-ify/-/array-ify-1.0.0.tgz", - "integrity": "sha512-c5AMf34bKdvPhQ7tBGhqkgKNUzMr4WUs+WDtC2ZUGOUncbxKMTvqxYctiseW3+L4bA8ec+GcZ6/A/FW4m8ukng==", "dev": true, "license": "MIT" }, "node_modules/array-includes": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.8.tgz", - "integrity": "sha512-itaWrbYbqpGXkGhZPGUulwnhVf5Hpy1xiCFsGqyIGglbBxmG5vSjxQen3/WGOjPpNEv1RtBLKxbmVXm8HpJStQ==", + "version": "3.1.9", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", "define-properties": "^1.2.1", - "es-abstract": "^1.23.2", - "es-object-atoms": "^1.0.0", - "get-intrinsic": "^1.2.4", - "is-string": "^1.0.7" + "es-abstract": "^1.24.0", + "es-object-atoms": "^1.1.1", + "get-intrinsic": "^1.3.0", + "is-string": "^1.1.1", + "math-intrinsics": "^1.1.0" }, "engines": { "node": ">= 0.4" @@ -2632,19 +4538,18 @@ } }, "node_modules/array.prototype.findlastindex": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.5.tgz", - "integrity": "sha512-zfETvRFA8o7EiNn++N5f/kaCw221hrpGsDmcpndVupkPzEc1Wuf3VgC0qby1BbHs7f5DVYjgtEU2LLh5bqeGfQ==", + "version": "1.2.6", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", "define-properties": "^1.2.1", - "es-abstract": "^1.23.2", + "es-abstract": "^1.23.9", "es-errors": "^1.3.0", - "es-object-atoms": "^1.0.0", - "es-shim-unscopables": "^1.0.2" + "es-object-atoms": "^1.1.1", + "es-shim-unscopables": "^1.1.0" }, "engines": { "node": ">= 0.4" @@ -2654,17 +4559,15 @@ } }, "node_modules/array.prototype.flat": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.2.tgz", - "integrity": "sha512-djYB+Zx2vLewY8RWlNCUdHjDXs2XOgm602S9E7P/UpHgfeHL00cRiIF+IN/G/aUJ7kGPb6yO/ErDI5V2s8iycA==", + "version": "1.3.3", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.2.0", - "es-abstract": "^1.22.1", - "es-shim-unscopables": "^1.0.0" + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -2674,17 +4577,15 @@ } }, "node_modules/array.prototype.flatmap": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.2.tgz", - "integrity": "sha512-Ewyx0c9PmpcsByhSW4r+9zDU7sGjFc86qf/kKtuSCRdhfbk0SNLLkaT5qvcHnRGgc5NP/ly/y+qkXkqONX54CQ==", + "version": "1.3.3", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.2.0", - "es-abstract": "^1.22.1", - "es-shim-unscopables": "^1.0.0" + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -2694,21 +4595,18 @@ } }, "node_modules/arraybuffer.prototype.slice": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.3.tgz", - "integrity": "sha512-bMxMKAjg13EBSVscxTaYA4mRc5t1UAXa2kXiGTNfZ079HIWXEkKmkgFrh/nJqamaLSrXO5H4WFFkPEaLJWbs3A==", + "version": "1.0.4", "dev": true, "license": "MIT", "peer": true, "dependencies": { "array-buffer-byte-length": "^1.0.1", - "call-bind": "^1.0.5", + "call-bind": "^1.0.8", "define-properties": "^1.2.1", - "es-abstract": "^1.22.3", - "es-errors": "^1.2.1", - "get-intrinsic": "^1.2.3", - "is-array-buffer": "^3.0.4", - "is-shared-array-buffer": "^1.0.2" + "es-abstract": "^1.23.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "is-array-buffer": "^3.0.4" }, "engines": { "node": ">= 0.4" @@ -2719,18 +4617,23 @@ }, "node_modules/arrify": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", - "integrity": "sha512-3CYzex9M9FGQjCGMGyi6/31c8GJbgb0qGyrx5HWxPd0aCwh4cB2YjMb2Xf9UuoogrMrlO9cTqnB5rI5GHZTcUA==", "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" } }, + "node_modules/async-function": { + "version": "1.0.0", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/async-hook-domain": { "version": "2.0.4", - "resolved": "https://registry.npmjs.org/async-hook-domain/-/async-hook-domain-2.0.4.tgz", - "integrity": "sha512-14LjCmlK1PK8eDtTezR6WX8TMaYNIzBIsd2D1sGoGjgx0BuNMMoSdk7i/drlbtamy0AWv9yv2tkB+ASdmeqFIw==", "dev": true, "license": "ISC", "engines": { @@ -2739,35 +4642,14 @@ }, "node_modules/async-retry": { "version": "1.3.3", - "resolved": "https://registry.npmjs.org/async-retry/-/async-retry-1.3.3.tgz", - "integrity": "sha512-wfr/jstw9xNi/0teMHrRW7dsz3Lt5ARhYNZ2ewpadnhaIp5mbALhOAP+EAdsC7t4Z6wqsDVv9+W6gm1Dk9mEyw==", "dev": true, "license": "MIT", "dependencies": { "retry": "0.13.1" } }, - "node_modules/async-retry/node_modules/retry": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", - "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true, - "license": "MIT" - }, "node_modules/available-typed-arrays": { "version": "1.0.7", - "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", - "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", "dev": true, "license": "MIT", "peer": true, @@ -2782,16 +4664,22 @@ } }, "node_modules/b4a": { - "version": "1.6.6", - "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.6.tgz", - "integrity": "sha512-5Tk1HLk6b6ctmjIkAcU/Ujv/1WqiDl0F0JdRCR80VsOcUlHcu7pWeWRlOqQLHfDEsVx9YH/aif5AG4ehoCtTmg==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.8.1.tgz", + "integrity": "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==", "dev": true, - "license": "Apache-2.0" + "license": "Apache-2.0", + "peerDependencies": { + "react-native-b4a": "*" + }, + "peerDependenciesMeta": { + "react-native-b4a": { + "optional": true + } + } }, "node_modules/bail": { "version": "2.0.2", - "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz", - "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==", "dev": true, "license": "MIT", "funding": { @@ -2800,66 +4688,220 @@ } }, "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", "inBundle": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } }, "node_modules/bare-events": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.4.2.tgz", - "integrity": "sha512-qMKFd2qG/36aA4GwvKq8MxnPgCQAmBWmSyLWsJcbn8v03wvIPQ/hG1Ms8bPzndZxMDoHpxez5VOS+gC9Yi24/Q==", + "version": "2.8.3", + "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.8.3.tgz", + "integrity": "sha512-HdUm8EMQBLaJvGUdidNNbqpA1kYkwNcb+MYxkxCLAPJGQzlv9J0C24h8V65Z4c5GLd/JEALDvpFCQgpLJqc0zw==", + "dev": true, + "license": "Apache-2.0", + "peerDependencies": { + "bare-abort-controller": "*" + }, + "peerDependenciesMeta": { + "bare-abort-controller": { + "optional": true + } + } + }, + "node_modules/bare-fs": { + "version": "4.7.1", + "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.7.1.tgz", + "integrity": "sha512-WDRsyVN52eAx/lBamKD6uyw8H4228h/x0sGGGegOamM2cd7Pag88GfMQalobXI+HaEUxpCkbKQUDOQqt9wawRw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "bare-events": "^2.5.4", + "bare-path": "^3.0.0", + "bare-stream": "^2.6.4", + "bare-url": "^2.2.2", + "fast-fifo": "^1.3.2" + }, + "engines": { + "bare": ">=1.16.0" + }, + "peerDependencies": { + "bare-buffer": "*" + }, + "peerDependenciesMeta": { + "bare-buffer": { + "optional": true + } + } + }, + "node_modules/bare-os": { + "version": "3.9.1", + "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.9.1.tgz", + "integrity": "sha512-6M5XjcnsygQNPMCMPXSK379xrJFiZ/AEMNBmFEmQW8d/789VQATvriyi5r0HYTL9TkQ26rn3kgdTG3aisbrXkQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "bare": ">=1.14.0" + } + }, + "node_modules/bare-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.0.0.tgz", + "integrity": "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "bare-os": "^3.0.1" + } + }, + "node_modules/bare-stream": { + "version": "2.13.1", + "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.1.tgz", + "integrity": "sha512-Vp0cnjYyrEC4whYTymQ+YZi6pBpfiICZO3cfRG8sy67ZNWe951urv1x4eW1BKNngw3U+3fPYb5JQvHbCtxH7Ow==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "streamx": "^2.25.0", + "teex": "^1.0.1" + }, + "peerDependencies": { + "bare-abort-controller": "*", + "bare-buffer": "*", + "bare-events": "*" + }, + "peerDependenciesMeta": { + "bare-abort-controller": { + "optional": true + }, + "bare-buffer": { + "optional": true + }, + "bare-events": { + "optional": true + } + } + }, + "node_modules/bare-url": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.4.3.tgz", + "integrity": "sha512-Kccpc7ACfXaxfeInfqKcZtW4pT5YBn1mesc4sCsun6sRwtbJ4h+sNOaksUpYEJUKfN65YWC6Bw2OJEFiKxq8nQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "bare-path": "^3.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.10.32", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.32.tgz", + "integrity": "sha512-wbPvpyjJPC0zdfdKXxqEL3Ea+bOMD/87X4lftiJkkaBiuG6ALQy1SLmEd7BSmVCuwCQsBrCamgBoLyfFDD1EPg==", "dev": true, "license": "Apache-2.0", - "optional": true + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } }, "node_modules/basic-auth-parser": { "version": "0.0.2-1", - "resolved": "https://registry.npmjs.org/basic-auth-parser/-/basic-auth-parser-0.0.2-1.tgz", - "integrity": "sha512-GFj8iVxo9onSU6BnnQvVwqvxh60UcSHJEDnIk3z4B6iOjsKSmqe+ibW0Rsz7YO7IE1HG3D3tqCNIidP46SZVdQ==", "dev": true }, "node_modules/before-after-hook": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.3.tgz", - "integrity": "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==", + "version": "4.0.0", "dev": true, "license": "Apache-2.0" }, "node_modules/benchmark": { "version": "2.1.4", - "resolved": "https://registry.npmjs.org/benchmark/-/benchmark-2.1.4.tgz", - "integrity": "sha512-l9MlfN4M1K/H2fbhfMy3B7vJd6AGKJVQn2h6Sg/Yx+KckoUA7ewS5Vv6TjSq18ooE1kS9hhAlQRH3AkXIh/aOQ==", "dev": true, "license": "MIT", "dependencies": { - "lodash": "^4.17.4", - "platform": "^1.3.3" + "lodash": "^4.17.4", + "platform": "^1.3.3" + } + }, + "node_modules/bidi-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", + "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" } }, "node_modules/bin-links": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/bin-links/-/bin-links-4.0.4.tgz", - "integrity": "sha512-cMtq4W5ZsEwcutJrVId+a/tjt8GSbS+h0oNkdl6+6rBuEv8Ot33Bevj5KPm40t309zuhVic8NjpuL42QCiJWWA==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/bin-links/-/bin-links-7.0.0.tgz", + "integrity": "sha512-kEk4UROE3064ebMhwmW1qx5BFSBWzmqMe0UwUzn5gsbDyXHmqMUSO8MW6sieYNiRJsindpdnjg4U0D9iXUkIxQ==", + "inBundle": true, "license": "ISC", "dependencies": { - "cmd-shim": "^6.0.0", - "npm-normalize-package-bin": "^3.0.0", - "read-cmd-shim": "^4.0.0", - "write-file-atomic": "^5.0.0" + "cmd-shim": "^9.0.0", + "npm-normalize-package-bin": "^6.0.0", + "proc-log": "^7.0.0", + "read-cmd-shim": "^7.0.0", + "write-file-atomic": "^8.0.0" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/bin-links/node_modules/cmd-shim": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cmd-shim/-/cmd-shim-9.0.1.tgz", + "integrity": "sha512-DlNenY05gnF6cQ8Tc7thKq1vsWJ6gqBPJHDfJpnegsAW/CFOJ98M3rz7dVqs0xjQORrTGRpjpbKt+3DXlBz41w==", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/bin-links/node_modules/npm-normalize-package-bin": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-6.0.0.tgz", + "integrity": "sha512-tdt4aFn9QamlhdN3HV2D2ccpBwO5/fyjjbXUxYA6uBjyekMZcZvDq0aSj9t5Jo+tih6AYFnt/cuIRn9013e0Uw==", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/bin-links/node_modules/read-cmd-shim": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/read-cmd-shim/-/read-cmd-shim-7.0.0.tgz", + "integrity": "sha512-GkU4W2VYxlMQqyn9JQQm8opl/UIXRzCS7iau12zNZm//CperjtK9CtpNhIh7hzU807BSdcmJIcRWeu0LIkTkYQ==", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/bin-links/node_modules/write-file-atomic": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-8.0.0.tgz", + "integrity": "sha512-dYwyZredl67GyLLIHJnRM3h2PcOmN5SkcgC7eM5DPDEOEl6dLFqVrMg3F1Ea32usj4VSVZtd2H4MtKTNOf6nPg==", + "inBundle": true, + "license": "ISC", + "dependencies": { + "signal-exit": "^4.0.1" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/binary-extensions": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", - "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-3.1.0.tgz", + "integrity": "sha512-Jvvd9hy1w+xUad8+ckQsWA/V1AoyubOvqn0aygjMOVM4BfIaRav1NFS3LsTSDaV4n4FtcCtQXvzep1E6MboqwQ==", "license": "MIT", "engines": { - "node": ">=8" + "node": ">=18.20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -2867,8 +4909,6 @@ }, "node_modules/bind-obj-methods": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/bind-obj-methods/-/bind-obj-methods-3.0.0.tgz", - "integrity": "sha512-nLEaaz3/sEzNSyPWRsN9HNsqwk1AUyECtGj+XwGdIi3xABnEqecvXtIJ0wehQXuuER5uZ/5fTs2usONgYjG+iw==", "dev": true, "license": "ISC", "engines": { @@ -2877,25 +4917,24 @@ }, "node_modules/boolbase": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", - "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", "dev": true, "license": "ISC" }, "node_modules/brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", + "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", "inBundle": true, "license": "MIT", "dependencies": { - "balanced-match": "^1.0.0" + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" } }, "node_modules/braces": { "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "dev": true, "license": "MIT", "dependencies": { @@ -2906,9 +4945,9 @@ } }, "node_modules/browserslist": { - "version": "4.23.1", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.1.tgz", - "integrity": "sha512-TUfofFo/KsK/bWZ9TWQ5O26tsWW4Uhmt8IYklbnUa70udB6P2wA7w7o4PY4muaEPBQaAX+CEnmmIA41NVHtPVw==", + "version": "4.28.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz", + "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==", "dev": true, "funding": [ { @@ -2926,10 +4965,11 @@ ], "license": "MIT", "dependencies": { - "caniuse-lite": "^1.0.30001629", - "electron-to-chromium": "^1.4.796", - "node-releases": "^2.0.14", - "update-browserslist-db": "^1.0.16" + "baseline-browser-mapping": "^2.10.12", + "caniuse-lite": "^1.0.30001782", + "electron-to-chromium": "^1.5.328", + "node-releases": "^2.0.36", + "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" @@ -2940,39 +4980,33 @@ }, "node_modules/buffer-from": { "version": "1.1.2", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true, "license": "MIT" }, "node_modules/cacache": { - "version": "18.0.3", - "resolved": "https://registry.npmjs.org/cacache/-/cacache-18.0.3.tgz", - "integrity": "sha512-qXCd4rh6I07cnDqh8V48/94Tc/WSfj+o3Gn6NZ0aZovS255bUx8O13uKxRFd2eWG0xgsco7+YItQNPaa5E85hg==", + "version": "21.0.1", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-21.0.1.tgz", + "integrity": "sha512-pTwz/uj3Jyp6WXdJ6fWhR+7LVxVs6RyroQSn7KJwHsSxXuyGSp0pcMVcwSwTpCFq1X2YG8QBe0W+vN+cr0SwzA==", "inBundle": true, "license": "ISC", "dependencies": { - "@npmcli/fs": "^3.1.0", + "@npmcli/fs": "^6.0.0", "fs-minipass": "^3.0.0", - "glob": "^10.2.2", - "lru-cache": "^10.0.1", + "glob": "^13.0.0", + "lru-cache": "^11.1.0", "minipass": "^7.0.3", "minipass-collect": "^2.0.1", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", - "p-map": "^4.0.0", - "ssri": "^10.0.0", - "tar": "^6.1.11", - "unique-filename": "^3.0.0" + "p-map": "^7.0.2", + "ssri": "^14.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/caching-transform": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/caching-transform/-/caching-transform-4.0.0.tgz", - "integrity": "sha512-kpqOvwXnjjN44D89K5ccQC+RUrsy7jB/XLlRrx0D7/2HNcTPqzsb6XgYoErwko6QsV184CA2YgS1fxDiiDZMWA==", "dev": true, "license": "MIT", "dependencies": { @@ -2987,15 +5021,11 @@ }, "node_modules/caching-transform/node_modules/signal-exit": { "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true, "license": "ISC" }, "node_modules/caching-transform/node_modules/write-file-atomic": { "version": "3.0.3", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", - "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", "dev": true, "license": "ISC", "dependencies": { @@ -3006,18 +5036,46 @@ } }, "node_modules/call-bind": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", - "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "es-define-property": "^1.0.0", "es-errors": "^1.3.0", - "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.4", - "set-function-length": "^1.2.1" + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" }, "engines": { "node": ">= 0.4" @@ -3028,15 +5086,11 @@ }, "node_modules/caller": { "version": "1.1.0", - "resolved": "https://registry.npmjs.org/caller/-/caller-1.1.0.tgz", - "integrity": "sha512-n+21IZC3j06YpCWaxmUy5AnVqhmCIM2bQtqQyy00HJlmStRt6kwDX5F9Z97pqwAB+G/tgSz6q/kUBbNyQzIubw==", "dev": true, "license": "MIT" }, "node_modules/callsites": { "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", "dev": true, "license": "MIT", "engines": { @@ -3045,8 +5099,6 @@ }, "node_modules/camelcase": { "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", "dev": true, "license": "MIT", "engines": { @@ -3055,8 +5107,6 @@ }, "node_modules/camelcase-keys": { "version": "6.2.2", - "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-6.2.2.tgz", - "integrity": "sha512-YrwaA0vEKazPBkn0ipTiMpSajYDSe+KjQfrjhcBMxJt/znbvlHd8Pw/Vamaz5EB4Wfhs3SUR3Z9mwRu/P3s3Yg==", "dev": true, "license": "MIT", "dependencies": { @@ -3072,9 +5122,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001636", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001636.tgz", - "integrity": "sha512-bMg2vmr8XBsbL6Lr0UHXy/21m84FTxDLWn2FSqMd5PrlbMxwJlQnC2YWYxVgp66PZE+BBNF2jYQUBKCo1FDeZg==", + "version": "1.0.30001793", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001793.tgz", + "integrity": "sha512-iwSsYWaCOoh26cV8NwNRViHlrfUvYsHDfRVcbtmw0Kg6PJIZZXwMkj1442FYLBGkeUf1juAsU3DTfxW579mrPA==", "dev": true, "funding": [ { @@ -3094,8 +5144,6 @@ }, "node_modules/ccount": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", - "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", "dev": true, "license": "MIT", "funding": { @@ -3104,9 +5152,7 @@ } }, "node_modules/chalk": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", - "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", + "version": "5.6.2", "inBundle": true, "license": "MIT", "engines": { @@ -3118,8 +5164,6 @@ }, "node_modules/character-entities": { "version": "2.0.2", - "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", - "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==", "dev": true, "license": "MIT", "funding": { @@ -3129,8 +5173,6 @@ }, "node_modules/character-entities-html4": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", - "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", "dev": true, "license": "MIT", "funding": { @@ -3140,8 +5182,6 @@ }, "node_modules/character-entities-legacy": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", - "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", "dev": true, "license": "MIT", "funding": { @@ -3151,8 +5191,6 @@ }, "node_modules/chokidar": { "version": "3.6.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", - "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", "dev": true, "license": "MIT", "dependencies": { @@ -3176,8 +5214,6 @@ }, "node_modules/chokidar/node_modules/glob-parent": { "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, "license": "ISC", "dependencies": { @@ -3188,19 +5224,19 @@ } }, "node_modules/chownr": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", - "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", "inBundle": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "engines": { - "node": ">=10" + "node": ">=18" } }, "node_modules/ci-info": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.0.0.tgz", - "integrity": "sha512-TdHqgGf9odd8SXNuxtUBVx8Nv+qZOejE6qyqiy5NtbYYQOeFa6zmHkxlPzmaLxWWHsU6nJmB7AETdVPi+2NBUg==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", + "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", "funding": [ { "type": "github", @@ -3214,46 +5250,25 @@ } }, "node_modules/cidr-regex": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/cidr-regex/-/cidr-regex-4.1.1.tgz", - "integrity": "sha512-ekKcVp+iRB9zlKFXyx7io7nINgb0oRjgRdXNEodp1OuxRui8FXr/CA40Tz1voWUp9DPPrMyQKy01vJhDo4N1lw==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cidr-regex/-/cidr-regex-6.0.0.tgz", + "integrity": "sha512-zEbNjf8/Un85X0XYUR9e99CYxZrq6ko4F6Xd6wnrxpgVi9F0Y7096+H2T+RDxYGSYHP6DUptmQE4j6RdRe+f7w==", "inBundle": true, "license": "BSD-2-Clause", - "dependencies": { - "ip-regex": "^5.0.0" - }, "engines": { - "node": ">=14" + "node": ">=22" } }, "node_modules/clean-stack": { "version": "2.2.0", - "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", - "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", - "inBundle": true, + "dev": true, "license": "MIT", "engines": { "node": ">=6" } }, - "node_modules/cli-columns": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/cli-columns/-/cli-columns-4.0.0.tgz", - "integrity": "sha512-XW2Vg+w+L9on9wtwKpyzluIPCWXjaBahI7mTcYjx+BVIYD9c3yqcv/yKC7CmdCZat4rq2yiE1UMSJC5ivKfMtQ==", - "inBundle": true, - "license": "MIT", - "dependencies": { - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">= 10" - } - }, "node_modules/cli-table3": { "version": "0.6.5", - "resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz", - "integrity": "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==", "dev": true, "license": "MIT", "dependencies": { @@ -3268,8 +5283,6 @@ }, "node_modules/cliui": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", "dev": true, "license": "ISC", "dependencies": { @@ -3283,8 +5296,6 @@ }, "node_modules/cliui/node_modules/ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "license": "MIT", "dependencies": { @@ -3299,8 +5310,6 @@ }, "node_modules/cliui/node_modules/wrap-ansi": { "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, "license": "MIT", "dependencies": { @@ -3316,25 +5325,26 @@ } }, "node_modules/cmd-shim": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/cmd-shim/-/cmd-shim-6.0.3.tgz", - "integrity": "sha512-FMabTRlc5t5zjdenF6mS0MBeFZm0XqHqeOkcskKFb/LYCcRQ5fVgLOHVc4Lq9CqABd9zhjwPjMBCJvMCziSVtA==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/cmd-shim/-/cmd-shim-8.0.0.tgz", + "integrity": "sha512-Jk/BK6NCapZ58BKUxlSI+ouKRbjH1NLZCgJkYoab+vEHUY3f6OzpNBN9u7HFSv9J6TRDGs4PLOHezoKGaFRSCA==", + "dev": true, "license": "ISC", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/code-suggester": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/code-suggester/-/code-suggester-4.3.3.tgz", - "integrity": "sha512-cNyJBkjM3w78shs2RdXhCJ5M2pWYHuDdHQi0whKqiw5fdMvDs7sHLvfZUC7mR9klNpwOlkJgX+UbF/ZGXvCyYg==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/code-suggester/-/code-suggester-5.0.1.tgz", + "integrity": "sha512-8qJiiSCfkbPNWvjEFzdG1UW3axL+Bs0ldV1/TdlBKmF9I/a/WooSQZQCi9M44HoXbVTQesn/IQr6+nIWNnVIWA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@octokit/rest": "^19.0.5", + "@octokit/rest": "^20.1.2", "@types/yargs": "^16.0.0", "async-retry": "^1.3.1", - "diff": "^5.0.0", + "diff": "^8.0.3", "glob": "^7.1.6", "parse-diff": "^0.11.0", "yargs": "^16.0.0" @@ -3343,13 +5353,154 @@ "code-suggester": "build/src/bin/code-suggester.js" }, "engines": { - "node": ">=14.0.0" + "node": ">=18.0.0" + } + }, + "node_modules/code-suggester/node_modules/@octokit/auth-token": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 18" + } + }, + "node_modules/code-suggester/node_modules/@octokit/core": { + "version": "5.2.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/auth-token": "^4.0.0", + "@octokit/graphql": "^7.1.0", + "@octokit/request": "^8.4.1", + "@octokit/request-error": "^5.1.1", + "@octokit/types": "^13.0.0", + "before-after-hook": "^2.2.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/code-suggester/node_modules/@octokit/endpoint": { + "version": "9.0.6", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.1.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/code-suggester/node_modules/@octokit/graphql": { + "version": "7.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/request": "^8.4.1", + "@octokit/types": "^13.0.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/code-suggester/node_modules/@octokit/openapi-types": { + "version": "24.2.0", + "dev": true, + "license": "MIT" + }, + "node_modules/code-suggester/node_modules/@octokit/plugin-paginate-rest": { + "version": "11.4.4-cjs.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.7.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@octokit/core": "5" + } + }, + "node_modules/code-suggester/node_modules/@octokit/plugin-request-log": { + "version": "4.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@octokit/core": "5" + } + }, + "node_modules/code-suggester/node_modules/@octokit/plugin-rest-endpoint-methods": { + "version": "13.3.2-cjs.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.8.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@octokit/core": "^5" + } + }, + "node_modules/code-suggester/node_modules/@octokit/request": { + "version": "8.4.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/endpoint": "^9.0.6", + "@octokit/request-error": "^5.1.1", + "@octokit/types": "^13.1.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/code-suggester/node_modules/@octokit/request-error": { + "version": "5.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.1.0", + "deprecation": "^2.0.0", + "once": "^1.4.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/code-suggester/node_modules/@octokit/rest": { + "version": "20.1.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/core": "^5.0.2", + "@octokit/plugin-paginate-rest": "11.4.4-cjs.2", + "@octokit/plugin-request-log": "^4.0.0", + "@octokit/plugin-rest-endpoint-methods": "13.3.2-cjs.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/code-suggester/node_modules/@octokit/types": { + "version": "13.10.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^24.2.0" } }, "node_modules/code-suggester/node_modules/ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "license": "MIT", "dependencies": { @@ -3362,10 +5513,22 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/code-suggester/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/code-suggester/node_modules/before-after-hook": { + "version": "2.2.3", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/code-suggester/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", + "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", "dev": true, "license": "MIT", "dependencies": { @@ -3375,8 +5538,6 @@ }, "node_modules/code-suggester/node_modules/cliui": { "version": "7.0.4", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", "dev": true, "license": "ISC", "dependencies": { @@ -3387,9 +5548,6 @@ }, "node_modules/code-suggester/node_modules/glob": { "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", "dev": true, "license": "ISC", "dependencies": { @@ -3408,9 +5566,9 @@ } }, "node_modules/code-suggester/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "dependencies": { @@ -3420,10 +5578,13 @@ "node": "*" } }, + "node_modules/code-suggester/node_modules/universal-user-agent": { + "version": "6.0.1", + "dev": true, + "license": "ISC" + }, "node_modules/code-suggester/node_modules/wrap-ansi": { "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, "license": "MIT", "dependencies": { @@ -3440,8 +5601,6 @@ }, "node_modules/code-suggester/node_modules/yargs": { "version": "16.2.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", - "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", "dev": true, "license": "MIT", "dependencies": { @@ -3459,8 +5618,6 @@ }, "node_modules/code-suggester/node_modules/yargs-parser": { "version": "20.2.9", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", - "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", "dev": true, "license": "ISC", "engines": { @@ -3469,9 +5626,7 @@ }, "node_modules/color-convert": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "inBundle": true, + "dev": true, "license": "MIT", "dependencies": { "color-name": "~1.1.4" @@ -3482,38 +5637,19 @@ }, "node_modules/color-name": { "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "inBundle": true, + "dev": true, "license": "MIT" }, "node_modules/color-support": { "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", - "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", "dev": true, "license": "ISC", "bin": { "color-support": "bin.js" } }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dev": true, - "license": "MIT", - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/comma-separated-tokens": { "version": "2.0.3", - "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", - "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", "dev": true, "license": "MIT", "funding": { @@ -3523,28 +5659,25 @@ }, "node_modules/commander": { "version": "2.20.3", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", - "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", "dev": true, "license": "MIT" }, "node_modules/common-ancestor-path": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/common-ancestor-path/-/common-ancestor-path-1.0.1.tgz", - "integrity": "sha512-L3sHRo1pXXEqX8VU28kfgUY+YGsk09hPqZiZmLacNib6XNTCM8ubYeT7ryXQw8asB1sKgcU5lkB7ONug08aB8w==", - "license": "ISC" + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/common-ancestor-path/-/common-ancestor-path-2.0.0.tgz", + "integrity": "sha512-dnN3ibLeoRf2HNC+OlCiNc5d2zxbLJXOtiZUudNFSXZrNSydxcCsSpRzXwfu7BBWCIfHPw+xTayeBvJCP/D8Ng==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">= 18" + } }, "node_modules/commondir": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", - "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", "dev": true, "license": "MIT" }, "node_modules/compare-func": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/compare-func/-/compare-func-2.0.0.tgz", - "integrity": "sha512-zHig5N+tPWARooBnb0Zx1MFcdfpyJrfTJ3Y5L+IFvUm8rM74hHz66z0gw0x4tijh5CorKkKUCnW82R2vmpeCRA==", "dev": true, "license": "MIT", "dependencies": { @@ -3552,43 +5685,53 @@ "dot-prop": "^5.1.0" } }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true, - "license": "MIT" - }, + "node_modules/concat-map": { + "version": "0.0.1", + "dev": true, + "license": "MIT" + }, + "node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/conventional-changelog-angular": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/conventional-changelog-angular/-/conventional-changelog-angular-7.0.0.tgz", - "integrity": "sha512-ROjNchA9LgfNMTTFSIWPzebCwOGFdgkEq45EnvvrmSLvCtAw0HSmrCs7/ty+wAeYUZyNay0YMUNYFTRL72PkBQ==", + "version": "8.3.1", + "resolved": "https://registry.npmjs.org/conventional-changelog-angular/-/conventional-changelog-angular-8.3.1.tgz", + "integrity": "sha512-6gfI3otXK5Ph5DfCOI1dblr+kN3FAm5a97hYoQkqNZxOaYa5WKfXH+AnpsmS+iUH2mgVC2Cg2Qw9m5OKcmNrIg==", "dev": true, "license": "ISC", "dependencies": { "compare-func": "^2.0.0" }, "engines": { - "node": ">=16" + "node": ">=18" } }, "node_modules/conventional-changelog-conventionalcommits": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/conventional-changelog-conventionalcommits/-/conventional-changelog-conventionalcommits-7.0.2.tgz", - "integrity": "sha512-NKXYmMR/Hr1DevQegFB4MwfM5Vv0m4UIxKZTTYuD98lpTknaZlSRrDOG4X7wIXpGkfsYxZTghUN+Qq+T0YQI7w==", + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/conventional-changelog-conventionalcommits/-/conventional-changelog-conventionalcommits-9.3.1.tgz", + "integrity": "sha512-dTYtpIacRpcZgrvBYvBfArMmK2xvIpv2TaxM0/ZI5CBtNUzvF2x0t15HsbRABWprS6UPmvj+PzHVjSx4qAVKyw==", "dev": true, "license": "ISC", "dependencies": { "compare-func": "^2.0.0" }, "engines": { - "node": ">=16" + "node": ">=18" } }, "node_modules/conventional-changelog-writer": { "version": "6.0.1", - "resolved": "https://registry.npmjs.org/conventional-changelog-writer/-/conventional-changelog-writer-6.0.1.tgz", - "integrity": "sha512-359t9aHorPw+U+nHzUXHS5ZnPBOizRxfQsWT5ZDHBfvfxQOAik+yfuhKXG66CN5LEWPpMNnIMHUTCKeYNprvHQ==", "dev": true, "license": "MIT", "dependencies": { @@ -3609,8 +5752,6 @@ }, "node_modules/conventional-changelog-writer/node_modules/hosted-git-info": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz", - "integrity": "sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==", "dev": true, "license": "ISC", "dependencies": { @@ -3622,8 +5763,6 @@ }, "node_modules/conventional-changelog-writer/node_modules/lru-cache": { "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", "dev": true, "license": "ISC", "dependencies": { @@ -3635,8 +5774,6 @@ }, "node_modules/conventional-changelog-writer/node_modules/meow": { "version": "8.1.2", - "resolved": "https://registry.npmjs.org/meow/-/meow-8.1.2.tgz", - "integrity": "sha512-r85E3NdZ+mpYk1C6RjPFEMSE+s1iZMuHtsHAqY0DT3jZczl0diWUZ8g6oU7h0M9cD2EL+PzaYghhCLzR0ZNn5Q==", "dev": true, "license": "MIT", "dependencies": { @@ -3661,8 +5798,6 @@ }, "node_modules/conventional-changelog-writer/node_modules/normalize-package-data": { "version": "3.0.3", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-3.0.3.tgz", - "integrity": "sha512-p2W1sgqij3zMMyRC067Dg16bfzVH+w7hyegmpIvZ4JNjqtGOVAIvLmjBx3yP7YTe9vKJgkoNOPjwQGogDoMXFA==", "dev": true, "license": "BSD-2-Clause", "dependencies": { @@ -3677,8 +5812,6 @@ }, "node_modules/conventional-changelog-writer/node_modules/type-fest": { "version": "0.18.1", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.18.1.tgz", - "integrity": "sha512-OIAYXk8+ISY+qTOwkHtKqzAuxchoMiD9Udx+FSGQDuiRR+PJKJHc2NJAXlbhkGwTt/4/nKZxELY1w3ReWOL8mw==", "dev": true, "license": "(MIT OR CC0-1.0)", "engines": { @@ -3688,10 +5821,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/conventional-changelog-writer/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true, + "license": "ISC" + }, "node_modules/conventional-changelog-writer/node_modules/yargs-parser": { "version": "20.2.9", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", - "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", "dev": true, "license": "ISC", "engines": { @@ -3700,8 +5838,6 @@ }, "node_modules/conventional-commits-filter": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/conventional-commits-filter/-/conventional-commits-filter-3.0.0.tgz", - "integrity": "sha512-1ymej8b5LouPx9Ox0Dw/qAO2dVdfpRFq28e5Y0jJEU8ZrLdy0vOSkkIInwmxErFGhg6SALro60ZrwYFVTUDo4Q==", "dev": true, "license": "MIT", "dependencies": { @@ -3713,35 +5849,31 @@ } }, "node_modules/conventional-commits-parser": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/conventional-commits-parser/-/conventional-commits-parser-5.0.0.tgz", - "integrity": "sha512-ZPMl0ZJbw74iS9LuX9YIAiW8pfM5p3yh2o/NbXHbkFuZzY5jvdi5jFycEOkmBW5H5I7nA+D6f3UcsCLP2vvSEA==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/conventional-commits-parser/-/conventional-commits-parser-6.4.0.tgz", + "integrity": "sha512-tvRg7FIBNlyPzjdG8wWRlPHQJJHI7DylhtRGeU9Lq+JuoPh5BKpPRX83ZdLrvXuOSu5Eo/e7SzOQhU4Hd2Miuw==", "dev": true, "license": "MIT", "dependencies": { - "is-text-path": "^2.0.0", - "JSONStream": "^1.3.5", - "meow": "^12.0.1", - "split2": "^4.0.0" + "@simple-libs/stream-utils": "^1.2.0", + "meow": "^13.0.0" }, "bin": { - "conventional-commits-parser": "cli.mjs" + "conventional-commits-parser": "dist/cli/index.js" }, "engines": { - "node": ">=16" + "node": ">=18" } }, "node_modules/convert-source-map": { "version": "1.9.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", - "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", "dev": true, "license": "MIT" }, "node_modules/cosmiconfig": { - "version": "9.0.0", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.0.tgz", - "integrity": "sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg==", + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.1.tgz", + "integrity": "sha512-hr4ihw+DBqcvrsEDioRO31Z17x71pUYoNe/4h6Z0wB72p7MU7/9gH8Q3s12NFhHPfYBBOV3qyfUxmr/Yn3shnQ==", "dev": true, "license": "MIT", "dependencies": { @@ -3766,28 +5898,26 @@ } }, "node_modules/cosmiconfig-typescript-loader": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/cosmiconfig-typescript-loader/-/cosmiconfig-typescript-loader-5.0.0.tgz", - "integrity": "sha512-+8cK7jRAReYkMwMiG+bxhcNKiHJDM6bR9FD/nGBXOWdMLuYawjF5cGrtLilJ+LGd3ZjCXnJjR5DkfWPoIVlqJA==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/cosmiconfig-typescript-loader/-/cosmiconfig-typescript-loader-6.3.0.tgz", + "integrity": "sha512-Akr82WH1Wfqatyiqpj8HDkO2o2KmJRu1FhKfSNJP3K4IdXwHfEyL7MOb62i1AGQVLtIQM+iCE9CGOtrfhR+mmA==", "dev": true, "license": "MIT", "dependencies": { - "jiti": "^1.19.1" + "jiti": "2.6.1" }, "engines": { - "node": ">=v16" + "node": ">=v18" }, "peerDependencies": { "@types/node": "*", - "cosmiconfig": ">=8.2", - "typescript": ">=4" + "cosmiconfig": ">=9", + "typescript": ">=5" } }, "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", - "inBundle": true, + "version": "7.0.6", + "dev": true, "license": "MIT", "dependencies": { "path-key": "^3.1.0", @@ -3798,11 +5928,14 @@ "node": ">= 8" } }, + "node_modules/cross-spawn/node_modules/isexe": { + "version": "2.0.0", + "dev": true, + "license": "ISC" + }, "node_modules/cross-spawn/node_modules/which": { "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "inBundle": true, + "dev": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" @@ -3815,9 +5948,7 @@ } }, "node_modules/css-select": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.1.0.tgz", - "integrity": "sha512-nwoRF1rvRRnnCqqY7updORDsuqKzqYJ28+oSMaJMMgOauh3fvwHqMS7EZpIPqK8GL+g9mKxF1vP/ZjSeNjEVHg==", + "version": "5.2.2", "dev": true, "license": "BSD-2-Clause", "dependencies": { @@ -3831,10 +5962,22 @@ "url": "https://github.com/sponsors/fb55" } }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, "node_modules/css-what": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz", - "integrity": "sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==", + "version": "6.2.2", "dev": true, "license": "BSD-2-Clause", "engines": { @@ -3846,8 +5989,6 @@ }, "node_modules/cssesc": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", - "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", "license": "MIT", "bin": { "cssesc": "bin/cssesc" @@ -3857,100 +5998,54 @@ } }, "node_modules/cssstyle": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.0.1.tgz", - "integrity": "sha512-8ZYiJ3A/3OkDd093CBT/0UKDWry7ak4BdPTFP2+QEP7cmhouyq/Up709ASSj2cK02BbZiMgk7kYjZNS4QP5qrQ==", + "version": "5.3.7", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-5.3.7.tgz", + "integrity": "sha512-7D2EPVltRrsTkhpQmksIu+LxeWAIEk6wRDMJ1qljlv+CKHJM+cJLlfhWIzNA44eAsHXSNe3+vO6DW1yCYx8SuQ==", "dev": true, "license": "MIT", "dependencies": { - "rrweb-cssom": "^0.6.0" + "@asamuzakjp/css-color": "^4.1.1", + "@csstools/css-syntax-patches-for-csstree": "^1.0.21", + "css-tree": "^3.1.0", + "lru-cache": "^11.2.4" }, "engines": { - "node": ">=18" - } - }, - "node_modules/cssstyle/node_modules/rrweb-cssom": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.6.0.tgz", - "integrity": "sha512-APM0Gt1KoXBz0iIkkdB/kfvGOwC4UuJFeG/c+yV7wSc7q96cG/kJ0HiYCnzivD9SB53cLV1MlHFNfOuPaadYSw==", - "dev": true, - "license": "MIT" - }, - "node_modules/dargs": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/dargs/-/dargs-8.1.0.tgz", - "integrity": "sha512-wAV9QHOsNbwnWdNW2FYvE1P56wtgSbM+3SZcdGiWQILwVjACCXDCI3Ai8QlCjMDB8YK5zySiXZYBiwGmNY3lnw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=20" } }, "node_modules/data-urls": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", - "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-6.0.1.tgz", + "integrity": "sha512-euIQENZg6x8mj3fO6o9+fOW8MimUI4PpD/fZBhJfeioZVy9TUpM4UY7KjQNVZFlqwJ0UdzRDzkycB997HEq1BQ==", "dev": true, "license": "MIT", "dependencies": { - "whatwg-mimetype": "^4.0.0", - "whatwg-url": "^14.0.0" + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^15.1.0" }, "engines": { - "node": ">=18" + "node": ">=20" } }, - "node_modules/data-urls/node_modules/tr46": { + "node_modules/data-urls/node_modules/whatwg-mimetype": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.0.0.tgz", - "integrity": "sha512-tk2G5R2KRwBd+ZN0zaEXpmzdKyOYksXwywulIX95MBODjSzMIuQnQ3m8JxgbhnL1LeVo7lqQKsYa1O3Htl7K5g==", - "dev": true, - "license": "MIT", - "dependencies": { - "punycode": "^2.3.1" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/data-urls/node_modules/webidl-conversions": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", - "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" - } - }, - "node_modules/data-urls/node_modules/whatwg-url": { - "version": "14.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.0.0.tgz", - "integrity": "sha512-1lfMEm2IEr7RIV+f4lUNPOqfFL+pO+Xw3fJSqmjX9AbXcXcYOkCe1P6+9VBZB6n94af16NfZf+sSk0JCBZC9aw==", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", "dev": true, "license": "MIT", - "dependencies": { - "tr46": "^5.0.0", - "webidl-conversions": "^7.0.0" - }, "engines": { - "node": ">=18" + "node": ">=20" } }, "node_modules/data-view-buffer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.1.tgz", - "integrity": "sha512-0lht7OugA5x3iJLOWFhWK/5ehONdprk0ISXqVFn/NFrDu+cuc8iADFrGQz5BnRK7LLU3JmkbXSxaqX+/mXYtUA==", + "version": "1.0.2", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.6", + "call-bound": "^1.0.3", "es-errors": "^1.3.0", - "is-data-view": "^1.0.1" + "is-data-view": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -3960,33 +6055,29 @@ } }, "node_modules/data-view-byte-length": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.1.tgz", - "integrity": "sha512-4J7wRJD3ABAzr8wP+OcIcqq2dlUKp4DVflx++hs5h5ZKydWMI6/D/fAot+yh6g2tHh8fLFTvNOaVN357NvSrOQ==", + "version": "1.0.2", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.7", + "call-bound": "^1.0.3", "es-errors": "^1.3.0", - "is-data-view": "^1.0.1" + "is-data-view": "^1.0.2" }, "engines": { "node": ">= 0.4" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://github.com/sponsors/inspect-js" } }, "node_modules/data-view-byte-offset": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.0.tgz", - "integrity": "sha512-t/Ygsytq+R995EJ5PZlD4Cu56sWa8InXySaViRzw9apusqsOO2bQP+SbYzAhR0pFKoB+43lYy8rWban9JSuXnA==", + "version": "1.0.1", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.6", + "call-bound": "^1.0.2", "es-errors": "^1.3.0", "is-data-view": "^1.0.1" }, @@ -3999,8 +6090,6 @@ }, "node_modules/dateformat": { "version": "3.0.3", - "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-3.0.3.tgz", - "integrity": "sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q==", "dev": true, "license": "MIT", "engines": { @@ -4008,13 +6097,11 @@ } }, "node_modules/debug": { - "version": "4.3.5", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.5.tgz", - "integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==", + "version": "4.4.3", "inBundle": true, "license": "MIT", "dependencies": { - "ms": "2.1.2" + "ms": "^2.1.3" }, "engines": { "node": ">=6.0" @@ -4025,17 +6112,8 @@ } } }, - "node_modules/debug/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "inBundle": true, - "license": "MIT" - }, "node_modules/decamelize": { "version": "1.2.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", - "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", "dev": true, "license": "MIT", "engines": { @@ -4044,8 +6122,6 @@ }, "node_modules/decamelize-keys": { "version": "1.1.1", - "resolved": "https://registry.npmjs.org/decamelize-keys/-/decamelize-keys-1.1.1.tgz", - "integrity": "sha512-WiPxgEirIV0/eIOMcnFBA3/IJZAZqKnwAwWyvvdi4lsr1WCN22nhdf/3db3DoZcUjTV2SqfzIwNyp6y2xs3nmg==", "dev": true, "license": "MIT", "dependencies": { @@ -4061,8 +6137,6 @@ }, "node_modules/decamelize-keys/node_modules/map-obj": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", - "integrity": "sha512-7N/q3lyZ+LVCp7PzuxrJr4KMbBE2hW7BT7YNia330OFxIf4d3r5zVpicP2650l7CPN6RM9zOJRl3NGpqSiw3Eg==", "dev": true, "license": "MIT", "engines": { @@ -4070,16 +6144,14 @@ } }, "node_modules/decimal.js": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.4.3.tgz", - "integrity": "sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==", + "version": "10.6.0", "dev": true, "license": "MIT" }, "node_modules/decode-named-character-reference": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.0.2.tgz", - "integrity": "sha512-O8x12RzrUF8xyVcY0KJowWsmaJxQbmy0/EtnNtHRpsOcT7dFk5W598coHqBVpmWo1oQQfsCqfCmkZN5DJrZVdg==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", + "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==", "dev": true, "license": "MIT", "dependencies": { @@ -4091,9 +6163,9 @@ } }, "node_modules/dedent": { - "version": "1.5.3", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.5.3.tgz", - "integrity": "sha512-NHQtfOOW68WD8lgypbLA5oT+Bt0xXJhiYvoR6SmmNXZfpzOGXwdKWmcwG8N7PwVVWV3eF/68nmD9BaJSsTBhyQ==", + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz", + "integrity": "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==", "dev": true, "license": "MIT", "peerDependencies": { @@ -4107,15 +6179,12 @@ }, "node_modules/deep-is": { "version": "0.1.4", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/default-require-extensions": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/default-require-extensions/-/default-require-extensions-3.0.1.tgz", - "integrity": "sha512-eXTJmRbm2TIt9MgWTsOH1wEuhew6XGZcMeGKCtLedIg/NCsg1iBePXkceTdK4Fii7pzmN9tGsZhKzZ4h7O/fxw==", "dev": true, "license": "MIT", "dependencies": { @@ -4130,8 +6199,6 @@ }, "node_modules/define-data-property": { "version": "1.1.4", - "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", - "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", "dev": true, "license": "MIT", "peer": true, @@ -4149,8 +6216,6 @@ }, "node_modules/define-properties": { "version": "1.2.1", - "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", - "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", "dev": true, "license": "MIT", "peer": true, @@ -4166,27 +6231,13 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/deprecation": { "version": "2.3.1", - "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", - "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==", "dev": true, "license": "ISC" }, "node_modules/dequal": { "version": "2.0.3", - "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", - "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", "dev": true, "license": "MIT", "engines": { @@ -4195,18 +6246,29 @@ }, "node_modules/detect-indent": { "version": "6.1.0", - "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-6.1.0.tgz", - "integrity": "sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA==", "dev": true, "license": "MIT", "engines": { "node": ">=8" } }, + "node_modules/devlop": { + "version": "1.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/diff": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/diff/-/diff-5.2.0.tgz", - "integrity": "sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A==", + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz", + "integrity": "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==", + "inBundle": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.3.1" @@ -4214,15 +6276,11 @@ }, "node_modules/discontinuous-range": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/discontinuous-range/-/discontinuous-range-1.0.0.tgz", - "integrity": "sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ==", "dev": true, "license": "MIT" }, "node_modules/doctrine": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", "dev": true, "license": "Apache-2.0", "peer": true, @@ -4235,8 +6293,6 @@ }, "node_modules/dom-serializer": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", - "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", "dev": true, "license": "MIT", "dependencies": { @@ -4250,8 +6306,6 @@ }, "node_modules/domelementtype": { "version": "2.3.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", - "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", "dev": true, "funding": [ { @@ -4263,8 +6317,6 @@ }, "node_modules/domhandler": { "version": "5.0.3", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", - "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", "dev": true, "license": "BSD-2-Clause", "dependencies": { @@ -4278,9 +6330,7 @@ } }, "node_modules/domutils": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.1.0.tgz", - "integrity": "sha512-H78uMmQtI2AhgDJjWeQmHwJJ2bLPD3GMmO7Zja/ZZh84wkm+4ut+IUnUdRa8uCGX88DiVx1j6FRe1XfxEgjEZA==", + "version": "3.2.2", "dev": true, "license": "BSD-2-Clause", "dependencies": { @@ -4294,8 +6344,6 @@ }, "node_modules/dot-prop": { "version": "5.3.0", - "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-5.3.0.tgz", - "integrity": "sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q==", "dev": true, "license": "MIT", "dependencies": { @@ -4305,42 +6353,34 @@ "node": ">=8" } }, - "node_modules/eastasianwidth": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", - "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", - "inBundle": true, - "license": "MIT" + "node_modules/dunder-proto": { + "version": "1.0.1", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } }, "node_modules/electron-to-chromium": { - "version": "1.4.807", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.807.tgz", - "integrity": "sha512-kSmJl2ZwhNf/bcIuCH/imtNOKlpkLDn2jqT5FJ+/0CXjhnFaOa9cOe9gHKKy71eM49izwuQjZhKk+lWQ1JxB7A==", + "version": "1.5.362", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.362.tgz", + "integrity": "sha512-PUY2DrLvkjkUuWqq+KPL2iWshrJsZOcIojzRQ7eXFacc9dWga7MGMJAa15VbiejSZB1PAXaRLAiKgruHP8LB1w==", "dev": true, "license": "ISC" }, "node_modules/emoji-regex": { "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "inBundle": true, + "dev": true, "license": "MIT" }, - "node_modules/encoding": { - "version": "0.1.13", - "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", - "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==", - "inBundle": true, - "license": "MIT", - "optional": true, - "dependencies": { - "iconv-lite": "^0.6.2" - } - }, "node_modules/entities": { "version": "4.5.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", - "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", "dev": true, "license": "BSD-2-Clause", "engines": { @@ -4352,25 +6392,14 @@ }, "node_modules/env-paths": { "version": "2.2.1", - "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", - "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", "inBundle": true, "license": "MIT", "engines": { "node": ">=6" } }, - "node_modules/err-code": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz", - "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==", - "inBundle": true, - "license": "MIT" - }, "node_modules/error-ex": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", - "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "version": "1.3.4", "dev": true, "license": "MIT", "dependencies": { @@ -4378,59 +6407,67 @@ } }, "node_modules/es-abstract": { - "version": "1.23.3", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.23.3.tgz", - "integrity": "sha512-e+HfNH61Bj1X9/jLc5v1owaLYuHdeHHSQlkhCBiTK8rBvKaULl/beGMxwrMXjpYrv4pz22BlY570vVePA2ho4A==", + "version": "1.24.2", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.2.tgz", + "integrity": "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "array-buffer-byte-length": "^1.0.1", - "arraybuffer.prototype.slice": "^1.0.3", + "array-buffer-byte-length": "^1.0.2", + "arraybuffer.prototype.slice": "^1.0.4", "available-typed-arrays": "^1.0.7", - "call-bind": "^1.0.7", - "data-view-buffer": "^1.0.1", - "data-view-byte-length": "^1.0.1", - "data-view-byte-offset": "^1.0.0", - "es-define-property": "^1.0.0", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "data-view-buffer": "^1.0.2", + "data-view-byte-length": "^1.0.2", + "data-view-byte-offset": "^1.0.1", + "es-define-property": "^1.0.1", "es-errors": "^1.3.0", - "es-object-atoms": "^1.0.0", - "es-set-tostringtag": "^2.0.3", - "es-to-primitive": "^1.2.1", - "function.prototype.name": "^1.1.6", - "get-intrinsic": "^1.2.4", - "get-symbol-description": "^1.0.2", - "globalthis": "^1.0.3", - "gopd": "^1.0.1", + "es-object-atoms": "^1.1.1", + "es-set-tostringtag": "^2.1.0", + "es-to-primitive": "^1.3.0", + "function.prototype.name": "^1.1.8", + "get-intrinsic": "^1.3.0", + "get-proto": "^1.0.1", + "get-symbol-description": "^1.1.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", "has-property-descriptors": "^1.0.2", - "has-proto": "^1.0.3", - "has-symbols": "^1.0.3", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", "hasown": "^2.0.2", - "internal-slot": "^1.0.7", - "is-array-buffer": "^3.0.4", + "internal-slot": "^1.1.0", + "is-array-buffer": "^3.0.5", "is-callable": "^1.2.7", - "is-data-view": "^1.0.1", + "is-data-view": "^1.0.2", "is-negative-zero": "^2.0.3", - "is-regex": "^1.1.4", - "is-shared-array-buffer": "^1.0.3", - "is-string": "^1.0.7", - "is-typed-array": "^1.1.13", - "is-weakref": "^1.0.2", - "object-inspect": "^1.13.1", + "is-regex": "^1.2.1", + "is-set": "^2.0.3", + "is-shared-array-buffer": "^1.0.4", + "is-string": "^1.1.1", + "is-typed-array": "^1.1.15", + "is-weakref": "^1.1.1", + "math-intrinsics": "^1.1.0", + "object-inspect": "^1.13.4", "object-keys": "^1.1.1", - "object.assign": "^4.1.5", - "regexp.prototype.flags": "^1.5.2", - "safe-array-concat": "^1.1.2", - "safe-regex-test": "^1.0.3", - "string.prototype.trim": "^1.2.9", - "string.prototype.trimend": "^1.0.8", + "object.assign": "^4.1.7", + "own-keys": "^1.0.1", + "regexp.prototype.flags": "^1.5.4", + "safe-array-concat": "^1.1.3", + "safe-push-apply": "^1.0.0", + "safe-regex-test": "^1.1.0", + "set-proto": "^1.0.0", + "stop-iteration-iterator": "^1.1.0", + "string.prototype.trim": "^1.2.10", + "string.prototype.trimend": "^1.0.9", "string.prototype.trimstart": "^1.0.8", - "typed-array-buffer": "^1.0.2", - "typed-array-byte-length": "^1.0.1", - "typed-array-byte-offset": "^1.0.2", - "typed-array-length": "^1.0.6", - "unbox-primitive": "^1.0.2", - "which-typed-array": "^1.1.15" + "typed-array-buffer": "^1.0.3", + "typed-array-byte-length": "^1.0.3", + "typed-array-byte-offset": "^1.0.4", + "typed-array-length": "^1.0.7", + "unbox-primitive": "^1.1.0", + "which-typed-array": "^1.1.19" }, "engines": { "node": ">= 0.4" @@ -4440,34 +6477,26 @@ } }, "node_modules/es-define-property": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", - "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "version": "1.0.1", "dev": true, "license": "MIT", "peer": true, - "dependencies": { - "get-intrinsic": "^1.2.4" - }, "engines": { "node": ">= 0.4" } }, "node_modules/es-errors": { "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">= 0.4" } }, "node_modules/es-object-atoms": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz", - "integrity": "sha512-MZ4iQ6JwHOBQjahnjwaC1ZtIBH+2ohjamzAO3oaHcXYup7qxjF2fixyH+Q71voWHeOkI2q/TnJao/KfXYIZWbw==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", "dev": true, "license": "MIT", "peer": true, @@ -4479,187 +6508,87 @@ } }, "node_modules/es-set-tostringtag": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.3.tgz", - "integrity": "sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "get-intrinsic": "^1.2.4", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.1" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-shim-unscopables": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.2.tgz", - "integrity": "sha512-J3yBRXCzDu4ULnQwxyToo/OjdMx6akgVC7K6few0a7F/0wLtmKKN7I73AH5T2836UuXRqN7Qg+IIUw/+YJksRw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "hasown": "^2.0.0" - } - }, - "node_modules/es-to-primitive": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", - "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "is-callable": "^1.1.4", - "is-date-object": "^1.0.1", - "is-symbol": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/es6-error": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz", - "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", - "dev": true, - "license": "MIT" - }, - "node_modules/escalade": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", - "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/escodegen": { - "version": "1.14.3", - "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.14.3.tgz", - "integrity": "sha512-qFcX0XJkdg+PB3xjZZG/wKSuT1PnQWx57+TVSjIMmILd2yC/6ByYElPwJnslDsuWuSAp4AwJGumarAAmJch5Kw==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "esprima": "^4.0.1", - "estraverse": "^4.2.0", - "esutils": "^2.0.2", - "optionator": "^0.8.1" - }, - "bin": { - "escodegen": "bin/escodegen.js", - "esgenerate": "bin/esgenerate.js" - }, - "engines": { - "node": ">=4.0" - }, - "optionalDependencies": { - "source-map": "~0.6.1" - } - }, - "node_modules/escodegen/node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "license": "BSD-2-Clause", - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/escodegen/node_modules/estraverse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "version": "2.1.0", "dev": true, - "license": "BSD-2-Clause", + "license": "MIT", + "peer": true, + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, "engines": { - "node": ">=4.0" + "node": ">= 0.4" } }, - "node_modules/escodegen/node_modules/levn": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", - "integrity": "sha512-0OO4y2iOHix2W6ujICbKIaEQXvFQHue65vUG3pb5EUomzPI90z9hsA1VsO/dbIIpC53J8gxM9Q4Oho0jrCM/yA==", + "node_modules/es-shim-unscopables": { + "version": "1.1.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2" + "hasown": "^2.0.2" }, "engines": { - "node": ">= 0.8.0" + "node": ">= 0.4" } }, - "node_modules/escodegen/node_modules/optionator": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", - "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "node_modules/es-to-primitive": { + "version": "1.3.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { - "deep-is": "~0.1.3", - "fast-levenshtein": "~2.0.6", - "levn": "~0.3.0", - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2", - "word-wrap": "~1.2.3" + "is-callable": "^1.2.7", + "is-date-object": "^1.0.5", + "is-symbol": "^1.0.4" }, "engines": { - "node": ">= 0.8.0" + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/escodegen/node_modules/prelude-ls": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", - "integrity": "sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w==", + "node_modules/es-toolkit": { + "version": "1.47.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.47.0.tgz", + "integrity": "sha512-n1GuoD0WEQZMBk5tttoZSqwgyLx01oqa5XsBmCHwPyNe1S9jPBEmtR2pSgp2kJuWE3ciFZ6yRHmY4pM4C3OOkw==", + "dev": true, + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/es6-error": { + "version": "4.1.1", "dev": true, + "license": "MIT" + }, + "node_modules/escalade": { + "version": "3.2.0", + "dev": true, + "license": "MIT", "engines": { - "node": ">= 0.8.0" + "node": ">=6" } }, - "node_modules/escodegen/node_modules/type-check": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", - "integrity": "sha512-ZCmOJdvOWDBYJlzAoFkC+Q0+bUyEOS1ltgp1MGU03fqHG+dbi9tBFU2Rd9QKiDZFAYrhPh2JUf7rZRIuHRKtOg==", + "node_modules/escape-string-regexp": { + "version": "4.0.0", "dev": true, "license": "MIT", - "dependencies": { - "prelude-ls": "~1.1.2" - }, + "peer": true, "engines": { - "node": ">= 0.8.0" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/eslint": { - "version": "8.57.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.0.tgz", - "integrity": "sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ==", + "version": "8.57.1", "dev": true, "license": "MIT", "peer": true, @@ -4667,8 +6596,8 @@ "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.57.0", - "@humanwhocodes/config-array": "^0.11.14", + "@eslint/js": "8.57.1", + "@humanwhocodes/config-array": "^0.13.0", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", "@ungap/structured-clone": "^1.2.0", @@ -4714,22 +6643,20 @@ } }, "node_modules/eslint-import-resolver-node": { - "version": "0.3.9", - "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", - "integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==", + "version": "0.3.10", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.10.tgz", + "integrity": "sha512-tRrKqFyCaKict5hOd244sL6EQFNycnMQnBe+j8uqGNXYzsImGbGUU4ibtoaBmv5FLwJwcFJNeg1GeVjQfbMrDQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { "debug": "^3.2.7", - "is-core-module": "^2.13.0", - "resolve": "^1.22.4" + "is-core-module": "^2.16.1", + "resolve": "^2.0.0-next.6" } }, "node_modules/eslint-import-resolver-node/node_modules/debug": { "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", "dev": true, "license": "MIT", "peer": true, @@ -4737,10 +6664,33 @@ "ms": "^2.1.1" } }, + "node_modules/eslint-import-resolver-node/node_modules/resolve": { + "version": "2.0.0-next.7", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.7.tgz", + "integrity": "sha512-tqt+NBWwyaMgw3zDsnygx4CByWjQEJHOPMdslYhppaQSJUtL/D4JO9CcBBlhPoI8lz9oJIDXkwXfhF4aWqP8xQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.16.2", + "node-exports-info": "^1.6.0", + "object-keys": "^1.1.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/eslint-module-utils": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.8.1.tgz", - "integrity": "sha512-rXDXR3h7cs7dy9RNpUlQf80nX31XWJEyGq1tRMo+6GsO5VmTe4UTwtmonAD4ZkAsrfMVDA2wlGJ3790Ys+D49Q==", + "version": "2.12.1", "dev": true, "license": "MIT", "peer": true, @@ -4758,8 +6708,6 @@ }, "node_modules/eslint-module-utils/node_modules/debug": { "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", "dev": true, "license": "MIT", "peer": true, @@ -4769,8 +6717,6 @@ }, "node_modules/eslint-plugin-es": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-es/-/eslint-plugin-es-3.0.1.tgz", - "integrity": "sha512-GUmAsJaN4Fc7Gbtl8uOBlayo2DqhwWvEzykMHSCZHU3XdJ+NSzzZcVhXh3VxX5icqQ+oQdIEawXX8xkR3mIFmQ==", "dev": true, "license": "MIT", "peer": true, @@ -4789,42 +6735,50 @@ } }, "node_modules/eslint-plugin-import": { - "version": "2.29.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.29.1.tgz", - "integrity": "sha512-BbPC0cuExzhiMo4Ff1BTVwHpjjv28C5R+btTOGaCRC7UEz801up0JadwkeSk5Ued6TG34uaczuVuH6qyy5YUxw==", + "version": "2.32.0", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "array-includes": "^3.1.7", - "array.prototype.findlastindex": "^1.2.3", - "array.prototype.flat": "^1.3.2", - "array.prototype.flatmap": "^1.3.2", + "@rtsao/scc": "^1.1.0", + "array-includes": "^3.1.9", + "array.prototype.findlastindex": "^1.2.6", + "array.prototype.flat": "^1.3.3", + "array.prototype.flatmap": "^1.3.3", "debug": "^3.2.7", "doctrine": "^2.1.0", "eslint-import-resolver-node": "^0.3.9", - "eslint-module-utils": "^2.8.0", - "hasown": "^2.0.0", - "is-core-module": "^2.13.1", + "eslint-module-utils": "^2.12.1", + "hasown": "^2.0.2", + "is-core-module": "^2.16.1", "is-glob": "^4.0.3", "minimatch": "^3.1.2", - "object.fromentries": "^2.0.7", - "object.groupby": "^1.0.1", - "object.values": "^1.1.7", + "object.fromentries": "^2.0.8", + "object.groupby": "^1.0.3", + "object.values": "^1.2.1", "semver": "^6.3.1", + "string.prototype.trimend": "^1.0.9", "tsconfig-paths": "^3.15.0" }, "engines": { "node": ">=4" }, "peerDependencies": { - "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8" + "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9" } }, + "node_modules/eslint-plugin-import/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/eslint-plugin-import/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", + "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", "dev": true, "license": "MIT", "peer": true, @@ -4835,8 +6789,6 @@ }, "node_modules/eslint-plugin-import/node_modules/debug": { "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", "dev": true, "license": "MIT", "peer": true, @@ -4846,8 +6798,6 @@ }, "node_modules/eslint-plugin-import/node_modules/doctrine": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", - "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", "dev": true, "license": "Apache-2.0", "peer": true, @@ -4859,9 +6809,9 @@ } }, "node_modules/eslint-plugin-import/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "peer": true, @@ -4874,8 +6824,6 @@ }, "node_modules/eslint-plugin-import/node_modules/semver": { "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", "dev": true, "license": "ISC", "peer": true, @@ -4885,8 +6833,6 @@ }, "node_modules/eslint-plugin-node": { "version": "11.1.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz", - "integrity": "sha512-oUwtPJ1W0SKD0Tr+wqu92c5xuCeQqB3hSCHasn/ZgjFdA9iDGNkNf2Zi9ztY7X+hNuMib23LNGRm6+uN+KLE3g==", "dev": true, "license": "MIT", "peer": true, @@ -4905,10 +6851,18 @@ "eslint": ">=5.16.0" } }, + "node_modules/eslint-plugin-node/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/eslint-plugin-node/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", + "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", "dev": true, "license": "MIT", "peer": true, @@ -4918,9 +6872,9 @@ } }, "node_modules/eslint-plugin-node/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "peer": true, @@ -4933,8 +6887,6 @@ }, "node_modules/eslint-plugin-node/node_modules/semver": { "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", "dev": true, "license": "ISC", "peer": true, @@ -4943,9 +6895,7 @@ } }, "node_modules/eslint-plugin-promise": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-promise/-/eslint-plugin-promise-6.2.0.tgz", - "integrity": "sha512-QmAqwizauvnKOlifxyDj2ObfULpHQawlg/zQdgEixur9vl0CvZGv/LCJV2rtj3210QCoeGBzVMfMXqGAOr/4fA==", + "version": "6.6.0", "dev": true, "license": "ISC", "peer": true, @@ -4961,8 +6911,6 @@ }, "node_modules/eslint-scope": { "version": "7.2.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", - "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", "dev": true, "license": "BSD-2-Clause", "peer": true, @@ -4979,8 +6927,6 @@ }, "node_modules/eslint-utils": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz", - "integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==", "dev": true, "license": "MIT", "peer": true, @@ -4996,8 +6942,6 @@ }, "node_modules/eslint-utils/node_modules/eslint-visitor-keys": { "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", "dev": true, "license": "Apache-2.0", "peer": true, @@ -5007,8 +6951,6 @@ }, "node_modules/eslint-visitor-keys": { "version": "3.4.3", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", - "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", "dev": true, "license": "Apache-2.0", "peer": true, @@ -5020,9 +6962,9 @@ } }, "node_modules/eslint/node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", "dev": true, "license": "MIT", "peer": true, @@ -5039,8 +6981,6 @@ }, "node_modules/eslint/node_modules/ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "license": "MIT", "peer": true, @@ -5054,10 +6994,18 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/eslint/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/eslint/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", + "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", "dev": true, "license": "MIT", "peer": true, @@ -5068,8 +7016,6 @@ }, "node_modules/eslint/node_modules/chalk": { "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, "license": "MIT", "peer": true, @@ -5086,8 +7032,6 @@ }, "node_modules/eslint/node_modules/find-up": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", "dev": true, "license": "MIT", "peer": true, @@ -5102,29 +7046,14 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint/node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=8" - } - }, "node_modules/eslint/node_modules/json-schema-traverse": { "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", "dev": true, "license": "MIT", "peer": true }, "node_modules/eslint/node_modules/locate-path": { "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", "dev": true, "license": "MIT", "peer": true, @@ -5139,9 +7068,9 @@ } }, "node_modules/eslint/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "peer": true, @@ -5154,8 +7083,6 @@ }, "node_modules/eslint/node_modules/p-limit": { "version": "3.1.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", "dev": true, "license": "MIT", "peer": true, @@ -5171,8 +7098,6 @@ }, "node_modules/eslint/node_modules/p-locate": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", "dev": true, "license": "MIT", "peer": true, @@ -5188,8 +7113,6 @@ }, "node_modules/eslint/node_modules/path-exists": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true, "license": "MIT", "peer": true, @@ -5199,8 +7122,6 @@ }, "node_modules/eslint/node_modules/supports-color": { "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "license": "MIT", "peer": true, @@ -5213,8 +7134,6 @@ }, "node_modules/eslint/node_modules/yocto-queue": { "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", "dev": true, "license": "MIT", "peer": true, @@ -5227,8 +7146,6 @@ }, "node_modules/espree": { "version": "9.6.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", - "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", "dev": true, "license": "BSD-2-Clause", "peer": true, @@ -5245,22 +7162,21 @@ } }, "node_modules/esprima": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-1.2.2.tgz", - "integrity": "sha512-+JpPZam9w5DuJ3Q67SqsMGtiHKENSMRVoxvArfJZK01/BfLEObtZ6orJa/MtoGNR/rfMgp5837T41PAmTwAv/A==", + "version": "4.0.1", "dev": true, + "license": "BSD-2-Clause", "bin": { "esparse": "bin/esparse.js", "esvalidate": "bin/esvalidate.js" }, "engines": { - "node": ">=0.4.0" + "node": ">=4" } }, "node_modules/esquery": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.5.0.tgz", - "integrity": "sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", "dev": true, "license": "BSD-3-Clause", "peer": true, @@ -5273,8 +7189,6 @@ }, "node_modules/esrecurse": { "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", "dev": true, "license": "BSD-2-Clause", "peer": true, @@ -5287,8 +7201,6 @@ }, "node_modules/estraverse": { "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true, "license": "BSD-2-Clause", "peer": true, @@ -5298,92 +7210,81 @@ }, "node_modules/esutils": { "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", "dev": true, "license": "BSD-2-Clause", + "peer": true, "engines": { "node": ">=0.10.0" } }, "node_modules/events-to-array": { "version": "1.1.2", - "resolved": "https://registry.npmjs.org/events-to-array/-/events-to-array-1.1.2.tgz", - "integrity": "sha512-inRWzRY7nG+aXZxBzEqYKB3HPgwflZRopAjDCHv0whhRx+MTUr1ei0ICZUypdyE0HRm4L2d5VEcIqLD6yl+BFA==", "dev": true, "license": "ISC" }, - "node_modules/execa": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", - "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==", + "node_modules/events-universal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz", + "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==", "dev": true, - "license": "MIT", + "license": "Apache-2.0", "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^8.0.1", - "human-signals": "^5.0.0", - "is-stream": "^3.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^5.1.0", - "onetime": "^6.0.0", - "signal-exit": "^4.1.0", - "strip-final-newline": "^3.0.0" - }, - "engines": { - "node": ">=16.17" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" + "bare-events": "^2.7.0" } }, "node_modules/exponential-backoff": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.1.tgz", - "integrity": "sha512-dX7e/LHVJ6W3DE1MHWi9S1EYzDESENfLrYohG2G++ovZrYOkm4Knwa0mc1cn84xJOR4KEU0WSchhLbd0UklbHw==", + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz", + "integrity": "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==", "inBundle": true, "license": "Apache-2.0" }, "node_modules/extend": { "version": "3.0.2", - "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", - "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "dev": true, "license": "MIT" }, "node_modules/fast-deep-equal": { "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "dev": true, "license": "MIT" }, "node_modules/fast-fifo": { "version": "1.3.2", - "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz", - "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==", "dev": true, "license": "MIT" }, "node_modules/fast-json-stable-stringify": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", "dev": true, "license": "MIT", "peer": true }, "node_modules/fast-levenshtein": { "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true + }, + "node_modules/fast-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz", + "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" }, "node_modules/fastest-levenshtein": { "version": "1.0.16", - "resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz", - "integrity": "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==", "inBundle": true, "license": "MIT", "engines": { @@ -5391,9 +7292,9 @@ } }, "node_modules/fastq": { - "version": "1.17.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.17.1.tgz", - "integrity": "sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==", + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", + "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", "dev": true, "license": "ISC", "peer": true, @@ -5403,8 +7304,6 @@ }, "node_modules/figures": { "version": "3.2.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", - "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", "dev": true, "license": "MIT", "dependencies": { @@ -5419,8 +7318,6 @@ }, "node_modules/figures/node_modules/escape-string-regexp": { "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", "dev": true, "license": "MIT", "engines": { @@ -5429,8 +7326,6 @@ }, "node_modules/file-entry-cache": { "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", "dev": true, "license": "MIT", "peer": true, @@ -5443,8 +7338,6 @@ }, "node_modules/fill-range": { "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "dev": true, "license": "MIT", "dependencies": { @@ -5456,8 +7349,6 @@ }, "node_modules/find-cache-dir": { "version": "3.3.2", - "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.2.tgz", - "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==", "dev": true, "license": "MIT", "dependencies": { @@ -5472,35 +7363,13 @@ "url": "https://github.com/avajs/find-cache-dir?sponsor=1" } }, - "node_modules/find-up": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-7.0.0.tgz", - "integrity": "sha512-YyZM99iHrqLKjmt4LJDj58KI+fYyufRLBSYcqycxf//KpBk9FoewoGX0450m9nB44qrZnovzC2oeP5hUibxc/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "locate-path": "^7.2.0", - "path-exists": "^5.0.0", - "unicorn-magic": "^0.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/findit": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/findit/-/findit-2.0.0.tgz", - "integrity": "sha512-ENZS237/Hr8bjczn5eKuBohLgaD0JyUd0arxretR1f9RO46vZHA1b2y0VorgGV3WaOT3c+78P8h7v4JGJ1i/rg==", "dev": true, "license": "MIT" }, "node_modules/flat-cache": { "version": "3.2.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", - "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", "dev": true, "license": "MIT", "peer": true, @@ -5513,10 +7382,18 @@ "node": "^10.12.0 || >=12.0.0" } }, + "node_modules/flat-cache/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/flat-cache/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", + "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", "dev": true, "license": "MIT", "peer": true, @@ -5527,9 +7404,6 @@ }, "node_modules/flat-cache/node_modules/glob": { "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", "dev": true, "license": "ISC", "peer": true, @@ -5549,9 +7423,9 @@ } }, "node_modules/flat-cache/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "peer": true, @@ -5564,9 +7438,6 @@ }, "node_modules/flat-cache/node_modules/rimraf": { "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", "peer": true, @@ -5581,60 +7452,30 @@ } }, "node_modules/flatted": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.1.tgz", - "integrity": "sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==", + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", + "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", "dev": true, "license": "ISC", "peer": true }, "node_modules/for-each": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", - "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "version": "0.3.5", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "is-callable": "^1.1.3" - } - }, - "node_modules/foreground-child": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.2.1.tgz", - "integrity": "sha512-PXUUyLqrR2XCWICfv6ukppP96sdFwWbNEnfEMt7jNsISjMsvaLNinAHNDYyvkyU+SZG2BTSbT5NjG+vZslfGTA==", - "inBundle": true, - "license": "ISC", - "dependencies": { - "cross-spawn": "^7.0.0", - "signal-exit": "^4.0.1" + "is-callable": "^1.2.7" }, "engines": { - "node": ">=14" + "node": ">= 0.4" }, "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "dev": true, - "license": "MIT", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/fromentries": { "version": "1.3.2", - "resolved": "https://registry.npmjs.org/fromentries/-/fromentries-1.3.2.tgz", - "integrity": "sha512-cHEpEQHUg0f8XdtZCc2ZAhrHzKzT0MrFUTcvx+hfxYu7rGMDc5SKoXFh+n4YigxsHXRzc6OrCshdR1bWH6HHyg==", "dev": true, "funding": [ { @@ -5654,8 +7495,6 @@ }, "node_modules/front-matter": { "version": "4.0.2", - "resolved": "https://registry.npmjs.org/front-matter/-/front-matter-4.0.2.tgz", - "integrity": "sha512-I8ZuJ/qG92NWX8i5x1Y8qyj3vizhXS31OxjKDu3LKP+7/qBgfIKValiZIEwoVoJKUHlhWtYrktkxV1XsX+pPlg==", "dev": true, "license": "MIT", "dependencies": { @@ -5664,32 +7503,16 @@ }, "node_modules/front-matter/node_modules/argparse": { "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", "dev": true, "license": "MIT", "dependencies": { "sprintf-js": "~1.0.2" } }, - "node_modules/front-matter/node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "license": "BSD-2-Clause", - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/front-matter/node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "version": "3.14.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", + "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", "dev": true, "license": "MIT", "dependencies": { @@ -5700,24 +7523,13 @@ "js-yaml": "bin/js-yaml.js" } }, - "node_modules/front-matter/node_modules/sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", - "dev": true, - "license": "BSD-3-Clause" - }, "node_modules/fs-exists-cached": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-exists-cached/-/fs-exists-cached-1.0.0.tgz", - "integrity": "sha512-kSxoARUDn4F2RPXX48UXnaFKwVU7Ivd/6qpzZL29MCDmr9sTvybv4gFCp+qaI4fM9m0z9fgz/yJvi56GAz+BZg==", "dev": true, "license": "ISC" }, "node_modules/fs-minipass": { "version": "3.0.3", - "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz", - "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==", "inBundle": true, "license": "ISC", "dependencies": { @@ -5729,8 +7541,6 @@ }, "node_modules/fs.realpath": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", "dev": true, "license": "ISC" }, @@ -5751,8 +7561,6 @@ }, "node_modules/function-bind": { "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", "dev": true, "license": "MIT", "funding": { @@ -5761,23 +7569,21 @@ }, "node_modules/function-loop": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/function-loop/-/function-loop-2.0.1.tgz", - "integrity": "sha512-ktIR+O6i/4h+j/ZhZJNdzeI4i9lEPeEK6UPR2EVyTVBqOwcU3Za9xYKLH64ZR9HmcROyRrOkizNyjjtWJzDDkQ==", "dev": true, "license": "ISC" }, "node_modules/function.prototype.name": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.6.tgz", - "integrity": "sha512-Z5kx79swU5P27WEayXM1tBi5Ze/lbIyiNgU3qyXUOf9b2rgXYyF9Dy9Cx+IQv/Lc8WCG6L82zwUPpSS9hGehIg==", + "version": "1.1.8", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.2.0", - "es-abstract": "^1.22.1", - "functions-have-names": "^1.2.3" + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "functions-have-names": "^1.2.3", + "hasown": "^2.0.2", + "is-callable": "^1.2.7" }, "engines": { "node": ">= 0.4" @@ -5788,8 +7594,6 @@ }, "node_modules/functions-have-names": { "version": "1.2.3", - "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", - "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", "dev": true, "license": "MIT", "peer": true, @@ -5797,10 +7601,19 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/generator-function": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz", + "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/gensync": { "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", "dev": true, "license": "MIT", "engines": { @@ -5809,8 +7622,6 @@ }, "node_modules/get-caller-file": { "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true, "license": "ISC", "engines": { @@ -5818,18 +7629,23 @@ } }, "node_modules/get-intrinsic": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", - "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", - "has-proto": "^1.0.1", - "has-symbols": "^1.0.3", - "hasown": "^2.0.0" + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" }, "engines": { "node": ">= 0.4" @@ -5840,38 +7656,34 @@ }, "node_modules/get-package-type": { "version": "0.1.0", - "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", - "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", "dev": true, "license": "MIT", "engines": { "node": ">=8.0.0" } }, - "node_modules/get-stream": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", - "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", + "node_modules/get-proto": { + "version": "1.0.1", "dev": true, "license": "MIT", - "engines": { - "node": ">=16" + "peer": true, + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "engines": { + "node": ">= 0.4" } }, "node_modules/get-symbol-description": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.2.tgz", - "integrity": "sha512-g0QYk1dZBxGwk+Ngc+ltRH2IBp2f7zBkBMBJZCDerh6EhlhSR6+9irMCuT/09zD6qkarHUSn529sK/yL4S27mg==", + "version": "1.1.0", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.5", + "call-bound": "^1.0.3", "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.4" + "get-intrinsic": "^1.2.6" }, "engines": { "node": ">= 0.4" @@ -5881,49 +7693,67 @@ } }, "node_modules/git-raw-commits": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/git-raw-commits/-/git-raw-commits-4.0.0.tgz", - "integrity": "sha512-ICsMM1Wk8xSGMowkOmPrzo2Fgmfo4bMHLNX6ytHjajRJUqvHOw/TFapQ+QG75c3X/tTDDhOSRPGC52dDbNM8FQ==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/git-raw-commits/-/git-raw-commits-5.0.1.tgz", + "integrity": "sha512-Y+csSm2GD/PCSh6Isd/WiMjNAydu0VBiG9J7EdQsNA5P9uXvLayqjmTsNlK5Gs9IhblFZqOU0yid5Il5JPoLiQ==", "dev": true, "license": "MIT", "dependencies": { - "dargs": "^8.0.0", - "meow": "^12.0.1", - "split2": "^4.0.0" + "@conventional-changelog/git-client": "^2.6.0", + "meow": "^13.0.0" }, "bin": { - "git-raw-commits": "cli.mjs" + "git-raw-commits": "src/cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/git-raw-commits/node_modules/@conventional-changelog/git-client": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/@conventional-changelog/git-client/-/git-client-2.7.0.tgz", + "integrity": "sha512-j7A8/LBEQ+3rugMzPXoKYzyUPpw/0CBQCyvtTR7Lmu4olG4yRC/Tfkq79Mr3yuPs0SUitlO2HwGP3gitMJnRFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@simple-libs/child-process-utils": "^1.0.0", + "@simple-libs/stream-utils": "^1.2.0", + "semver": "^7.5.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "conventional-commits-filter": "^5.0.0", + "conventional-commits-parser": "^6.4.0" }, - "engines": { - "node": ">=16" + "peerDependenciesMeta": { + "conventional-commits-filter": { + "optional": true + }, + "conventional-commits-parser": { + "optional": true + } } }, "node_modules/github-slugger": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/github-slugger/-/github-slugger-1.5.0.tgz", - "integrity": "sha512-wIh+gKBI9Nshz2o46B0B3f5k/W+WI9ZAv6y5Dn5WJ5SK1t0TnDimB4WE5rmTD05ZAIn8HALCZVmCsvj0w0v0lw==", + "version": "2.0.0", "dev": true, "license": "ISC" }, "node_modules/glob": { - "version": "10.4.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.2.tgz", - "integrity": "sha512-GwMlUF6PkPo3Gk21UxkCohOv0PLcIXVtKyLlpEI28R/cO/4eNOdmLk3CMW1wROV/WR/EsZOWAfBbBOqYvs88/w==", + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", "inBundle": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "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" - }, - "bin": { - "glob": "dist/esm/bin.mjs" + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" }, "engines": { - "node": ">=16 || 14 >=14.18" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -5931,8 +7761,6 @@ }, "node_modules/glob-parent": { "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", "dev": true, "license": "ISC", "peer": true, @@ -5944,35 +7772,33 @@ } }, "node_modules/global-directory": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/global-directory/-/global-directory-4.0.1.tgz", - "integrity": "sha512-wHTUcDUoZ1H5/0iVqEudYW4/kAlN5cZ3j/bXn0Dpbizl9iaUVeWSHqiOjsgk6OW2bkLclbBjzewBz6weQ1zA2Q==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/global-directory/-/global-directory-5.0.0.tgz", + "integrity": "sha512-1pgFdhK3J2LeM+dVf2Pd424yHx2ou338lC0ErNP2hPx4j8eW1Sp0XqSjNxtk6Tc4Kr5wlWtSvz8cn2yb7/SG/w==", "dev": true, "license": "MIT", "dependencies": { - "ini": "4.1.1" + "ini": "6.0.0" }, "engines": { - "node": ">=18" + "node": ">=20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/global-directory/node_modules/ini": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.1.tgz", - "integrity": "sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-6.0.0.tgz", + "integrity": "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==", "dev": true, "license": "ISC", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/globals": { "version": "13.24.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", - "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", "dev": true, "license": "MIT", "peer": true, @@ -5988,8 +7814,6 @@ }, "node_modules/globalthis": { "version": "1.0.4", - "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", - "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", "dev": true, "license": "MIT", "peer": true, @@ -6005,14 +7829,12 @@ } }, "node_modules/gopd": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", - "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "version": "1.2.0", "dev": true, "license": "MIT", "peer": true, - "dependencies": { - "get-intrinsic": "^1.1.3" + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -6020,23 +7842,17 @@ }, "node_modules/graceful-fs": { "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", "inBundle": true, "license": "ISC" }, "node_modules/graphemer": { "version": "1.4.0", - "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", - "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", "dev": true, "license": "MIT", "peer": true }, "node_modules/groff-escape": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/groff-escape/-/groff-escape-2.0.1.tgz", - "integrity": "sha512-S0nG+mLFTu1buDKQsRlBtIxZU/dMvrdCURJg/zSLKpL333yi1Fs5bLUYk+v3pRYlc+qmHtukMAM2slB0AKFKAw==", "dev": true, "license": "MIT", "funding": { @@ -6045,9 +7861,9 @@ } }, "node_modules/handlebars": { - "version": "4.7.8", - "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.8.tgz", - "integrity": "sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ==", + "version": "4.7.9", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.9.tgz", + "integrity": "sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==", "dev": true, "license": "MIT", "dependencies": { @@ -6068,8 +7884,6 @@ }, "node_modules/hard-rejection": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/hard-rejection/-/hard-rejection-2.1.0.tgz", - "integrity": "sha512-VIZB+ibDhx7ObhAe7OVtoEbuP4h/MuOTHJ+J8h/eBXotJYl0fBgR72xDFCKgIh22OJZIOVNxBMWuhAr10r8HdA==", "dev": true, "license": "MIT", "engines": { @@ -6077,30 +7891,27 @@ } }, "node_modules/has-bigints": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", - "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", + "version": "1.1.0", "dev": true, "license": "MIT", "peer": true, + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "version": "4.0.0", "dev": true, "license": "MIT", "engines": { - "node": ">=4" + "node": ">=8" } }, "node_modules/has-property-descriptors": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", - "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", "dev": true, "license": "MIT", "peer": true, @@ -6112,12 +7923,13 @@ } }, "node_modules/has-proto": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", - "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "version": "1.2.0", "dev": true, "license": "MIT", "peer": true, + "dependencies": { + "dunder-proto": "^1.0.0" + }, "engines": { "node": ">= 0.4" }, @@ -6126,9 +7938,7 @@ } }, "node_modules/has-symbols": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", - "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "version": "1.1.0", "dev": true, "license": "MIT", "peer": true, @@ -6141,8 +7951,6 @@ }, "node_modules/has-tostringtag": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", - "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", "dev": true, "license": "MIT", "peer": true, @@ -6158,8 +7966,6 @@ }, "node_modules/hasha": { "version": "5.2.2", - "resolved": "https://registry.npmjs.org/hasha/-/hasha-5.2.2.tgz", - "integrity": "sha512-Hrp5vIK/xr5SkeN2onO32H0MgNZ0f17HRNH39WfL0SYUNOTZ5Lz1TJ8Pajo/87dYGEFlLMm7mIc/k/s6Bvz9HQ==", "dev": true, "license": "MIT", "dependencies": { @@ -6173,23 +7979,8 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/hasha/node_modules/is-stream": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/hasha/node_modules/type-fest": { "version": "0.8.1", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", - "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", "dev": true, "license": "(MIT OR CC0-1.0)", "engines": { @@ -6197,9 +7988,9 @@ } }, "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", + "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", "dev": true, "license": "MIT", "dependencies": { @@ -6209,117 +8000,19 @@ "node": ">= 0.4" } }, - "node_modules/hast-util-from-parse5": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/hast-util-from-parse5/-/hast-util-from-parse5-7.1.2.tgz", - "integrity": "sha512-Nz7FfPBuljzsN3tCQ4kCBKqdNhQE2l0Tn+X1ubgKBPRoiDIu1mL08Cfw4k7q71+Duyaw7DXDN+VTAp4Vh3oCOw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^2.0.0", - "@types/unist": "^2.0.0", - "hastscript": "^7.0.0", - "property-information": "^6.0.0", - "vfile": "^5.0.0", - "vfile-location": "^4.0.0", - "web-namespaces": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/hast-util-parse-selector": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/hast-util-parse-selector/-/hast-util-parse-selector-3.1.1.tgz", - "integrity": "sha512-jdlwBjEexy1oGz0aJ2f4GKMaVKkA9jwjr4MjAAI22E5fM/TXVZHuS5OpONtdeIkRKqAaryQ2E9xNQxijoThSZA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/hast-util-raw": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/hast-util-raw/-/hast-util-raw-7.2.3.tgz", - "integrity": "sha512-RujVQfVsOrxzPOPSzZFiwofMArbQke6DJjnFfceiEbFh7S05CbPt0cYN+A5YeD3pso0JQk6O1aHBnx9+Pm2uqg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^2.0.0", - "@types/parse5": "^6.0.0", - "hast-util-from-parse5": "^7.0.0", - "hast-util-to-parse5": "^7.0.0", - "html-void-elements": "^2.0.0", - "parse5": "^6.0.0", - "unist-util-position": "^4.0.0", - "unist-util-visit": "^4.0.0", - "vfile": "^5.0.0", - "web-namespaces": "^2.0.0", - "zwitch": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/hast-util-raw/node_modules/parse5": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", - "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", - "dev": true, - "license": "MIT" - }, - "node_modules/hast-util-raw/node_modules/unist-util-visit": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-4.1.2.tgz", - "integrity": "sha512-MSd8OUGISqHdVvfY9TPhyK2VdUrPgxkUtWSuMHF6XAAFuL4LokseigBnZtPnJMu+FbynTkFNnFlyjxpVKujMRg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0", - "unist-util-visit-parents": "^5.1.1" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/hast-util-raw/node_modules/unist-util-visit-parents": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-5.1.3.tgz", - "integrity": "sha512-x6+y8g7wWMyQhL1iZfhIPhDAs7Xwbn9nRosDXl7qoPTSCy0yNxnKc+hWokFifWQIDGi154rdUqKvbCa4+1kLhg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, "node_modules/hast-util-to-html": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-8.0.4.tgz", - "integrity": "sha512-4tpQTUOr9BMjtYyNlt0P50mH7xj0Ks2xpo8M943Vykljf99HW6EzulIoJP1N3eKOSScEHzyzi9dm7/cn0RfGwA==", + "version": "9.0.5", "dev": true, "license": "MIT", "dependencies": { - "@types/hast": "^2.0.0", - "@types/unist": "^2.0.0", + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", - "hast-util-raw": "^7.0.0", - "hast-util-whitespace": "^2.0.0", - "html-void-elements": "^2.0.0", - "property-information": "^6.0.0", + "hast-util-whitespace": "^3.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" @@ -6329,48 +8022,12 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/hast-util-to-parse5": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/hast-util-to-parse5/-/hast-util-to-parse5-7.1.0.tgz", - "integrity": "sha512-YNRgAJkH2Jky5ySkIqFXTQiaqcAtJyVE+D5lkN6CdtOqrnkLfGYYrEcKuHOJZlp+MwjSwuD3fZuawI+sic/RBw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^2.0.0", - "comma-separated-tokens": "^2.0.0", - "property-information": "^6.0.0", - "space-separated-tokens": "^2.0.0", - "web-namespaces": "^2.0.0", - "zwitch": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, "node_modules/hast-util-whitespace": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-2.0.1.tgz", - "integrity": "sha512-nAxA0v8+vXSBDt3AnRUNjyRIQ0rD+ntpbAp4LnPkumc5M9yUbSMa4XDU9Q6etY4f1Wp4bNgvc1yjiZtsTTrSng==", - "dev": true, - "license": "MIT", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/hastscript": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/hastscript/-/hastscript-7.2.0.tgz", - "integrity": "sha512-TtYPq24IldU8iKoJQqvZOuhi5CyCQRAbvDOX0x1eW6rsHSxa/1i2CCiptNTotGHJ3VoHRGmqiv6/D3q113ikkw==", + "version": "3.0.0", "dev": true, "license": "MIT", "dependencies": { - "@types/hast": "^2.0.0", - "comma-separated-tokens": "^2.0.0", - "hast-util-parse-selector": "^3.0.0", - "property-information": "^6.0.0", - "space-separated-tokens": "^2.0.0" + "@types/hast": "^3.0.0" }, "funding": { "type": "opencollective", @@ -6379,8 +8036,6 @@ }, "node_modules/he": { "version": "1.2.0", - "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", - "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", "dev": true, "license": "MIT", "bin": { @@ -6388,42 +8043,25 @@ } }, "node_modules/hosted-git-info": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-7.0.2.tgz", - "integrity": "sha512-puUZAUKT5m8Zzvs72XWy3HtvVbTWljRE66cP60bxJzAqf2DgICo7lYTY2IHUmLnNpjYvw5bvmoHvPc0QO2a62w==", + "version": "10.1.1", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-10.1.1.tgz", + "integrity": "sha512-DeOnSPAvOndYKfw075gt8yZzQ7S2hNztw34zBTfhIzLhmBTswIBg5/y+pqu/VD5cYWm5goAFTusDmUEmKZ0PEQ==", "inBundle": true, "license": "ISC", "dependencies": { - "lru-cache": "^10.0.1" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/html-encoding-sniffer": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", - "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "whatwg-encoding": "^3.1.1" + "lru-cache": "^11.1.0" }, "engines": { - "node": ">=18" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/html-escaper": { "version": "2.0.2", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", "dev": true, "license": "MIT" }, "node_modules/html-void-elements": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-2.0.1.tgz", - "integrity": "sha512-0quDb7s97CfemeJAnW9wC0hw78MtW7NU3hqtCD75g2vFlDLt36llsYD7uB7SUzojLMP24N5IatXf7ylGXiGG9A==", + "version": "3.0.0", "dev": true, "license": "MIT", "funding": { @@ -6432,17 +8070,13 @@ } }, "node_modules/http-cache-semantics": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz", - "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==", + "version": "4.2.0", "inBundle": true, "license": "BSD-2-Clause" }, "node_modules/http-proxy-agent": { "version": "7.0.2", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", - "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", - "inBundle": true, + "dev": true, "license": "MIT", "dependencies": { "agent-base": "^7.1.0", @@ -6453,47 +8087,37 @@ } }, "node_modules/https-proxy-agent": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", - "integrity": "sha512-1e4Wqeblerz+tMKPIq2EMGiiWW1dIjZOksyHWSUm1rmuvw/how9hBHZ38lAGj5ID4Ik6EdkOw7NmWPy6LAwalw==", - "inBundle": true, + "version": "7.0.6", + "dev": true, "license": "MIT", "dependencies": { - "agent-base": "^7.0.2", + "agent-base": "^7.1.2", "debug": "4" }, "engines": { "node": ">= 14" } }, - "node_modules/human-signals": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", - "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=16.17.0" - } - }, "node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "devOptional": true, + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", "inBundle": true, "license": "MIT", + "optional": true, "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" }, "engines": { "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/ignore": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.1.tgz", - "integrity": "sha512-5Fytz/IraMjqpwfd34ke28PTVMjZjJG2MPn5t7OE4eUCUNf8BAa7b5WUS9/Qvr6mwOQS7Mk6vdsMno5he+T8Xw==", + "version": "5.3.2", "dev": true, "license": "MIT", "peer": true, @@ -6502,22 +8126,18 @@ } }, "node_modules/ignore-walk": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/ignore-walk/-/ignore-walk-6.0.5.tgz", - "integrity": "sha512-VuuG0wCnjhnylG1ABXT3dAuIpTNDs/G8jlpmwXY03fXoXy/8ZK8/T+hMzt8L4WnrLCJgdybqgPagnF/f97cg3A==", - "inBundle": true, + "version": "8.0.0", + "dev": true, "license": "ISC", "dependencies": { - "minimatch": "^9.0.0" + "minimatch": "^10.0.3" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/import-fresh": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", - "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", + "version": "3.3.1", "dev": true, "license": "MIT", "dependencies": { @@ -6533,8 +8153,6 @@ }, "node_modules/import-fresh/node_modules/resolve-from": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", "dev": true, "license": "MIT", "engines": { @@ -6542,9 +8160,9 @@ } }, "node_modules/import-meta-resolve": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.1.0.tgz", - "integrity": "sha512-I6fiaX09Xivtk+THaMfAwnA3MVA5Big1WHF1Dfx9hFuvNIWpXnorlkzhcQf6ehrqQiiZECRt1poOAkPmer3ruw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", + "integrity": "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==", "dev": true, "license": "MIT", "funding": { @@ -6554,9 +8172,7 @@ }, "node_modules/imurmurhash": { "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "inBundle": true, + "dev": true, "license": "MIT", "engines": { "node": ">=0.8.19" @@ -6564,9 +8180,7 @@ }, "node_modules/indent-string": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", - "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", - "inBundle": true, + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -6574,9 +8188,6 @@ }, "node_modules/inflight": { "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", "dev": true, "license": "ISC", "dependencies": { @@ -6586,93 +8197,70 @@ }, "node_modules/inherits": { "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true, "license": "ISC" }, "node_modules/ini": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.3.tgz", - "integrity": "sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-7.0.0.tgz", + "integrity": "sha512-ifK0CgjALofS5bkrcTy4RaQ9Vx2Knf/eLeIO+NaswQEpH1UblrtTSCIvN71qQDMq0PeQ/SSPojvEJp9vvvfr+w==", "inBundle": true, "license": "ISC", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/init-package-json": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/init-package-json/-/init-package-json-6.0.3.tgz", - "integrity": "sha512-Zfeb5ol+H+eqJWHTaGca9BovufyGeIfr4zaaBorPmJBMrJ+KBnN+kQx2ZtXdsotUTgldHmHQV44xvUWOUA7E2w==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/init-package-json/-/init-package-json-9.0.0.tgz", + "integrity": "sha512-aYDqz4jgX1plB2GDCFYStlOh67QXVpAIeNgDq8rRGVDYMvLE39yYlf8+CjYY2chVOVfqLsSIycFYznHWozZ9CA==", "inBundle": true, "license": "ISC", "dependencies": { - "@npmcli/package-json": "^5.0.0", - "npm-package-arg": "^11.0.0", - "promzard": "^1.0.0", - "read": "^3.0.1", - "semver": "^7.3.5", - "validate-npm-package-license": "^3.0.4", - "validate-npm-package-name": "^5.0.0" + "@npmcli/package-json": "^8.0.0", + "npm-package-arg": "^14.0.0", + "promzard": "^4.0.0", + "read": "^6.0.0", + "semver": "^7.7.2", + "validate-npm-package-name": "^8.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/internal-slot": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.7.tgz", - "integrity": "sha512-NGnrKwXzSms2qUUih/ILZ5JBqNTSa1+ZmP6flaIp6KmSElgE9qdndzS3cqjrDovwFdmwsGsLdeFgB6suw+1e9g==", + "version": "1.1.0", "dev": true, "license": "MIT", "peer": true, "dependencies": { "es-errors": "^1.3.0", - "hasown": "^2.0.0", - "side-channel": "^1.0.4" + "hasown": "^2.0.2", + "side-channel": "^1.1.0" }, "engines": { "node": ">= 0.4" } }, "node_modules/ip-address": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-9.0.5.tgz", - "integrity": "sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g==", + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz", + "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==", "inBundle": true, "license": "MIT", - "dependencies": { - "jsbn": "1.1.0", - "sprintf-js": "^1.1.3" - }, "engines": { "node": ">= 12" } }, - "node_modules/ip-regex": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-5.0.0.tgz", - "integrity": "sha512-fOCG6lhoKKakwv+C6KdsOnGvgXnmgfmp0myi3bcNwj3qfwPAxRKWEuFhvEFF7ceYIz6+1jRZ+yguLFAmUNPEfw==", - "inBundle": true, - "license": "MIT", - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/is-array-buffer": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.4.tgz", - "integrity": "sha512-wcjaerHw0ydZwfhiKbXJWLDY8A7yV7KhjQOpb83hGgGfId/aQa4TOvwyzn2PuswW2gPCYEL/nEAiSVpdOj1lXw==", + "version": "3.0.5", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.2", - "get-intrinsic": "^1.2.1" + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" }, "engines": { "node": ">= 0.4" @@ -6683,20 +8271,38 @@ }, "node_modules/is-arrayish": { "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", "dev": true, "license": "MIT" }, + "node_modules/is-async-function": { + "version": "2.1.1", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "async-function": "^1.0.0", + "call-bound": "^1.0.3", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-bigint": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", - "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", + "version": "1.1.0", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "has-bigints": "^1.0.1" + "has-bigints": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -6704,8 +8310,6 @@ }, "node_modules/is-binary-path": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", - "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", "dev": true, "license": "MIT", "dependencies": { @@ -6715,52 +8319,35 @@ "node": ">=8" } }, - "node_modules/is-boolean-object": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", - "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", + "node_modules/is-binary-path/node_modules/binary-extensions": { + "version": "2.3.0", "dev": true, "license": "MIT", - "peer": true, - "dependencies": { - "call-bind": "^1.0.2", - "has-tostringtag": "^1.0.0" - }, "engines": { - "node": ">= 0.4" + "node": ">=8" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/is-buffer": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.5.tgz", - "integrity": "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], + "node_modules/is-boolean-object": { + "version": "1.2.2", + "dev": true, "license": "MIT", + "peer": true, + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, "engines": { - "node": ">=4" + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-callable": { "version": "1.2.7", - "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", - "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", "dev": true, "license": "MIT", "peer": true, @@ -6772,39 +8359,42 @@ } }, "node_modules/is-cidr": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/is-cidr/-/is-cidr-5.1.0.tgz", - "integrity": "sha512-OkVS+Ht2ssF27d48gZdB+ho1yND1VbkJRKKS6Pc1/Cw7uqkd9IOJg8/bTwBDQL6tfBhSdguPRnlGiE8pU/X5NQ==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-cidr/-/is-cidr-7.0.0.tgz", + "integrity": "sha512-PkjeSTr7ZiDQ73R3TbGJBEOWWdC58ew5k9DCLBpYR1QtmiAPqF73TRTcXs5uZVoe3q5vMGAnl7Htp+cxnLfj7g==", "inBundle": true, "license": "BSD-2-Clause", "dependencies": { - "cidr-regex": "^4.1.1" + "cidr-regex": "^6.0.0" }, "engines": { - "node": ">=14" + "node": ">=22" } }, "node_modules/is-core-module": { - "version": "2.13.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.1.tgz", - "integrity": "sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==", + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz", + "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", "dev": true, "license": "MIT", "dependencies": { - "hasown": "^2.0.0" + "hasown": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-data-view": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.1.tgz", - "integrity": "sha512-AHkaJrsUVW6wq6JS8y3JnM/GJF/9cf+k20+iDzlSaJrinEo5+7vRiteOSwBhHRiAyQATN1AmY4hwzxJKPmYf+w==", + "version": "1.0.2", "dev": true, "license": "MIT", "peer": true, "dependencies": { + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", "is-typed-array": "^1.1.13" }, "engines": { @@ -6815,14 +8405,13 @@ } }, "node_modules/is-date-object": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", - "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "version": "1.1.0", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "has-tostringtag": "^1.0.0" + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -6833,28 +8422,58 @@ }, "node_modules/is-extglob": { "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" } }, + "node_modules/is-finalizationregistry": { + "version": "1.1.1", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "inBundle": true, + "dev": true, "license": "MIT", "engines": { "node": ">=8" } }, + "node_modules/is-generator-function": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", + "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bound": "^1.0.4", + "generator-function": "^2.0.0", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-glob": { "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dev": true, "license": "MIT", "dependencies": { @@ -6864,17 +8483,20 @@ "node": ">=0.10.0" } }, - "node_modules/is-lambda": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-lambda/-/is-lambda-1.0.1.tgz", - "integrity": "sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ==", - "inBundle": true, - "license": "MIT" + "node_modules/is-map": { + "version": "2.0.3", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/is-negative-zero": { "version": "2.0.3", - "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", - "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", "dev": true, "license": "MIT", "peer": true, @@ -6885,10 +8507,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-node-process": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/is-node-process/-/is-node-process-1.2.0.tgz", + "integrity": "sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw==", + "dev": true, + "license": "MIT" + }, "node_modules/is-number": { "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "dev": true, "license": "MIT", "engines": { @@ -6896,14 +8523,13 @@ } }, "node_modules/is-number-object": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", - "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", + "version": "1.1.1", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "has-tostringtag": "^1.0.0" + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -6914,8 +8540,6 @@ }, "node_modules/is-obj": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", - "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", "dev": true, "license": "MIT", "engines": { @@ -6924,8 +8548,6 @@ }, "node_modules/is-path-inside": { "version": "3.0.3", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", - "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", "dev": true, "license": "MIT", "peer": true, @@ -6935,8 +8557,6 @@ }, "node_modules/is-plain-obj": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", - "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==", "dev": true, "license": "MIT", "engines": { @@ -6946,34 +8566,34 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/is-plain-object": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz", - "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/is-potential-custom-element-name": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", - "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", "dev": true, "license": "MIT" }, "node_modules/is-regex": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", - "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "version": "1.2.1", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.2", - "has-tostringtag": "^1.0.0" + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "dev": true, + "license": "MIT", + "peer": true, "engines": { "node": ">= 0.4" }, @@ -6982,14 +8602,12 @@ } }, "node_modules/is-shared-array-buffer": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.3.tgz", - "integrity": "sha512-nA2hv5XIhLR3uVzDDfCIknerhx8XUKnstuOERPNNIinXG7v9u+ohXF67vxm4TPTEPU6lm61ZkwP3c9PCB97rhg==", + "version": "1.0.4", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.7" + "call-bound": "^1.0.3" }, "engines": { "node": ">= 0.4" @@ -6999,27 +8617,24 @@ } }, "node_modules/is-stream": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", - "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", + "version": "2.0.1", "dev": true, "license": "MIT", "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + "node": ">=8" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-string": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", - "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", + "version": "1.1.1", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "has-tostringtag": "^1.0.0" + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -7029,14 +8644,14 @@ } }, "node_modules/is-symbol": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", - "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", + "version": "1.1.1", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "has-symbols": "^1.0.2" + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" }, "engines": { "node": ">= 0.4" @@ -7045,28 +8660,13 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-text-path": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-text-path/-/is-text-path-2.0.0.tgz", - "integrity": "sha512-+oDTluR6WEjdXEJMnC2z6A4FRwFoYuvShVVEGsS7ewc0UTi2QtAKMDJuL4BDEVt+5T7MjFo12RP8ghOM75oKJw==", - "dev": true, - "license": "MIT", - "dependencies": { - "text-extensions": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/is-typed-array": { - "version": "1.1.13", - "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.13.tgz", - "integrity": "sha512-uZ25/bUAlUY5fR4OKT4rZQEBrzQWYV9ZJYGGsUmEJ6thodVJ1HX64ePQ6Z0qPWP+m+Uq6e9UugrE38jeYsDSMw==", + "version": "1.1.15", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "which-typed-array": "^1.1.14" + "which-typed-array": "^1.1.16" }, "engines": { "node": ">= 0.4" @@ -7077,20 +8677,47 @@ }, "node_modules/is-typedarray": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==", "dev": true, "license": "MIT" }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-weakref": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz", - "integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==", + "version": "1.1.1", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.4", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.2" + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -7098,8 +8725,6 @@ }, "node_modules/is-windows": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", - "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", "dev": true, "license": "MIT", "engines": { @@ -7108,23 +8733,22 @@ }, "node_modules/isarray": { "version": "2.0.5", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", - "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", "dev": true, "license": "MIT", "peer": true }, "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz", + "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==", "inBundle": true, - "license": "ISC" + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=20" + } }, "node_modules/istanbul-lib-coverage": { "version": "3.2.2", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", - "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", "dev": true, "license": "BSD-3-Clause", "engines": { @@ -7133,8 +8757,6 @@ }, "node_modules/istanbul-lib-hook": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/istanbul-lib-hook/-/istanbul-lib-hook-3.0.0.tgz", - "integrity": "sha512-Pt/uge1Q9s+5VAZ+pCo16TYMWPBIl+oaNIjgLQxcX0itS6ueeaA+pEfThZpH8WxhFgCiEb8sAJY6MdUKgiIWaQ==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -7146,8 +8768,6 @@ }, "node_modules/istanbul-lib-instrument": { "version": "4.0.3", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-4.0.3.tgz", - "integrity": "sha512-BXgQl9kf4WTCPCCpmFGoJkz/+uhvm7h7PFKUYxh7qarQd3ER33vHG//qaE8eN25l07YqZPpHXU9I09l/RD5aGQ==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -7162,8 +8782,6 @@ }, "node_modules/istanbul-lib-instrument/node_modules/semver": { "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", "dev": true, "license": "ISC", "bin": { @@ -7172,8 +8790,6 @@ }, "node_modules/istanbul-lib-processinfo": { "version": "2.0.3", - "resolved": "https://registry.npmjs.org/istanbul-lib-processinfo/-/istanbul-lib-processinfo-2.0.3.tgz", - "integrity": "sha512-NkwHbo3E00oybX6NGJi6ar0B29vxyvNwoC7eJ4G4Yq28UfY758Hgn/heV8VRFhevPED4LXfFz0DQ8z/0kw9zMg==", "dev": true, "license": "ISC", "dependencies": { @@ -7188,10 +8804,17 @@ "node": ">=8" } }, + "node_modules/istanbul-lib-processinfo/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, "node_modules/istanbul-lib-processinfo/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", + "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", "dev": true, "license": "MIT", "dependencies": { @@ -7201,9 +8824,6 @@ }, "node_modules/istanbul-lib-processinfo/node_modules/glob": { "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", "dev": true, "license": "ISC", "dependencies": { @@ -7222,9 +8842,9 @@ } }, "node_modules/istanbul-lib-processinfo/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "dependencies": { @@ -7236,8 +8856,6 @@ }, "node_modules/istanbul-lib-processinfo/node_modules/p-map": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-3.0.0.tgz", - "integrity": "sha512-d3qXVTF/s+W+CdJ5A29wywV2n8CQQYahlgz2bFiA+4eVNJbHJodPZ+/gXwPGh0bOqA+j8S+6+ckmvLGPk1QpxQ==", "dev": true, "license": "MIT", "dependencies": { @@ -7249,9 +8867,6 @@ }, "node_modules/istanbul-lib-processinfo/node_modules/rimraf": { "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", "dependencies": { @@ -7266,8 +8881,6 @@ }, "node_modules/istanbul-lib-report": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", - "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -7279,20 +8892,8 @@ "node": ">=10" } }, - "node_modules/istanbul-lib-report/node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/istanbul-lib-report/node_modules/make-dir": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", - "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", "dev": true, "license": "MIT", "dependencies": { @@ -7307,8 +8908,6 @@ }, "node_modules/istanbul-lib-report/node_modules/supports-color": { "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "license": "MIT", "dependencies": { @@ -7320,8 +8919,6 @@ }, "node_modules/istanbul-lib-source-maps": { "version": "4.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -7334,9 +8931,7 @@ } }, "node_modules/istanbul-reports": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.7.tgz", - "integrity": "sha512-BewmUXImeuRk2YY0PVbxgKAysvhRPUQE0h5QRM++nVWyubKGV0l8qQ5op8+B2DOmwSe63Jivj0BjkPQVf8fP5g==", + "version": "3.2.0", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -7347,46 +8942,25 @@ "node": ">=8" } }, - "node_modules/jackspeak": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.0.tgz", - "integrity": "sha512-JVYhQnN59LVPFCEcVa2C3CrEKYacvjRfqIQl+h8oi91aLYQVWRYbxjPcv1bUiUy/kLmQaANrYfNMCO3kuEDHfw==", - "inBundle": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/cliui": "^8.0.2" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - }, - "optionalDependencies": { - "@pkgjs/parseargs": "^0.11.0" - } - }, "node_modules/jiti": { - "version": "1.21.6", - "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.6.tgz", - "integrity": "sha512-2yTgeWTWzMWkHu6Jp9NKgePDaYHbntiwvYuuJLbbN9vl7DC9DvXKOB2BC3ZZ92D3cvV/aflH0osDfwpHepQ53w==", + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", + "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==", "dev": true, "license": "MIT", "bin": { - "jiti": "bin/jiti.js" + "jiti": "lib/jiti-cli.mjs" } }, "node_modules/js-tokens": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", "dev": true, "license": "MIT" }, "node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", "dev": true, "license": "MIT", "dependencies": { @@ -7396,141 +8970,54 @@ "js-yaml": "bin/js-yaml.js" } }, - "node_modules/jsbn": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz", - "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==", - "inBundle": true, - "license": "MIT" - }, - "node_modules/jsdom": { - "version": "24.1.0", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-24.1.0.tgz", - "integrity": "sha512-6gpM7pRXCwIOKxX47cgOyvyQDN/Eh0f1MeKySBV2xGdKtqJBLj8P25eY3EVCWo2mglDDzozR2r2MW4T+JiNUZA==", - "dev": true, - "license": "MIT", - "dependencies": { - "cssstyle": "^4.0.1", - "data-urls": "^5.0.0", - "decimal.js": "^10.4.3", - "form-data": "^4.0.0", - "html-encoding-sniffer": "^4.0.0", - "http-proxy-agent": "^7.0.2", - "https-proxy-agent": "^7.0.4", - "is-potential-custom-element-name": "^1.0.1", - "nwsapi": "^2.2.10", - "parse5": "^7.1.2", - "rrweb-cssom": "^0.7.0", - "saxes": "^6.0.0", - "symbol-tree": "^3.2.4", - "tough-cookie": "^4.1.4", - "w3c-xmlserializer": "^5.0.0", - "webidl-conversions": "^7.0.0", - "whatwg-encoding": "^3.1.1", - "whatwg-mimetype": "^4.0.0", - "whatwg-url": "^14.0.0", - "ws": "^8.17.0", - "xml-name-validator": "^5.0.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "canvas": "^2.11.2" - }, - "peerDependenciesMeta": { - "canvas": { - "optional": true - } - } - }, - "node_modules/jsdom/node_modules/tr46": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.0.0.tgz", - "integrity": "sha512-tk2G5R2KRwBd+ZN0zaEXpmzdKyOYksXwywulIX95MBODjSzMIuQnQ3m8JxgbhnL1LeVo7lqQKsYa1O3Htl7K5g==", - "dev": true, - "license": "MIT", - "dependencies": { - "punycode": "^2.3.1" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/jsdom/node_modules/webidl-conversions": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", - "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" - } - }, - "node_modules/jsdom/node_modules/whatwg-url": { - "version": "14.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.0.0.tgz", - "integrity": "sha512-1lfMEm2IEr7RIV+f4lUNPOqfFL+pO+Xw3fJSqmjX9AbXcXcYOkCe1P6+9VBZB6n94af16NfZf+sSk0JCBZC9aw==", + "node_modules/jsep": { + "version": "1.4.0", "dev": true, "license": "MIT", - "dependencies": { - "tr46": "^5.0.0", - "webidl-conversions": "^7.0.0" - }, "engines": { - "node": ">=18" + "node": ">= 10.16.0" } }, "node_modules/jsesc": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "version": "3.1.0", "dev": true, "license": "MIT", "bin": { "jsesc": "bin/jsesc" }, "engines": { - "node": ">=4" + "node": ">=6" } }, "node_modules/json-buffer": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", - "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", "dev": true, "license": "MIT", "peer": true }, "node_modules/json-parse-even-better-errors": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-3.0.2.tgz", - "integrity": "sha512-fi0NG4bPjCHunUJffmLd0gxssIgkNmArMvis4iNah6Owg1MCJjWhEcDLmsK6iGkJq3tHwbDkTlce70/tmXN4cQ==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-6.0.0.tgz", + "integrity": "sha512-2/8adwnK1/+Fdjyts4r6wSpfANWw8zdNhU9U/Llk59c6O+DjSisPWPykwoL8gZmocP9Dy64S7oie2g+Mia123A==", "inBundle": true, "license": "MIT", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/json-schema-traverse": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "dev": true, "license": "MIT" }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", "dev": true, "license": "MIT", "peer": true }, "node_modules/json-stringify-nice": { "version": "1.1.4", - "resolved": "https://registry.npmjs.org/json-stringify-nice/-/json-stringify-nice-1.1.4.tgz", - "integrity": "sha512-5Z5RFW63yxReJ7vANgW6eZFGWaQvnPE3WNmZoOJrSkGju2etKA2L5rrOa1sm877TVTFt57A80BH1bArcmlLfPw==", "license": "ISC", "funding": { "url": "https://github.com/sponsors/isaacs" @@ -7538,15 +9025,18 @@ }, "node_modules/json-stringify-safe": { "version": "5.0.1", - "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", - "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", "dev": true, "license": "ISC" }, + "node_modules/json-with-bigint": { + "version": "3.5.8", + "resolved": "https://registry.npmjs.org/json-with-bigint/-/json-with-bigint-3.5.8.tgz", + "integrity": "sha512-eq/4KP6K34kwa7TcFdtvnftvHCD9KvHOGGICWwMFc4dOOKF5t4iYqnfLK8otCRCRv06FXOzGGyqE8h8ElMvvdw==", + "dev": true, + "license": "MIT" + }, "node_modules/json5": { "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", "dev": true, "license": "MIT", "bin": { @@ -7558,89 +9048,63 @@ }, "node_modules/jsonparse": { "version": "1.3.1", - "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", - "integrity": "sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==", "engines": [ "node >= 0.2.0" ], "inBundle": true, "license": "MIT" }, - "node_modules/jsonpath": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/jsonpath/-/jsonpath-1.1.1.tgz", - "integrity": "sha512-l6Cg7jRpixfbgoWgkrl77dgEj8RPvND0wMH6TwQmi9Qs4TFfS9u5cUFnbeKTwj5ga5Y3BTGGNI28k117LJ009w==", + "node_modules/jsonpath-plus": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/jsonpath-plus/-/jsonpath-plus-10.4.0.tgz", + "integrity": "sha512-T92WWatJXmhBbKsgH/0hl+jxjdXrifi5IKeMY02DWggRxX0UElcbVzPlmgLTbvsPeW1PasQ6xE2Q75stkhGbsA==", "dev": true, "license": "MIT", "dependencies": { - "esprima": "1.2.2", - "static-eval": "2.0.2", - "underscore": "1.12.1" - } - }, - "node_modules/JSONStream": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-1.3.5.tgz", - "integrity": "sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==", - "dev": true, - "license": "(MIT OR Apache-2.0)", - "dependencies": { - "jsonparse": "^1.2.0", - "through": ">=2.2.7 <3" + "@jsep-plugin/assignment": "^1.3.0", + "@jsep-plugin/regex": "^1.0.4", + "jsep": "^1.4.0" }, "bin": { - "JSONStream": "bin.js" + "jsonpath": "bin/jsonpath-cli.js", + "jsonpath-plus": "bin/jsonpath-cli.js" }, "engines": { - "node": "*" + "node": ">=18.0.0" } }, "node_modules/just-deep-map-values": { "version": "1.2.0", - "resolved": "https://registry.npmjs.org/just-deep-map-values/-/just-deep-map-values-1.2.0.tgz", - "integrity": "sha512-4vpPBzHHis4UW/EbH5kHZn0gJvKP+EiMpbjD669ZSxdwx+EoAlQLMbLR08SEtydcq/MjDPPtwGiPo9R893iHVA==", "dev": true, "license": "MIT" }, "node_modules/just-diff": { "version": "6.0.2", - "resolved": "https://registry.npmjs.org/just-diff/-/just-diff-6.0.2.tgz", - "integrity": "sha512-S59eriX5u3/QhMNq3v/gm8Kd0w8OS6Tz2FS1NG4blv+z0MuQcBRJyFWjdovM0Rad4/P4aUPFtnkNjMjyMlMSYA==", "inBundle": true, "license": "MIT" }, "node_modules/just-diff-apply": { "version": "5.5.0", - "resolved": "https://registry.npmjs.org/just-diff-apply/-/just-diff-apply-5.5.0.tgz", - "integrity": "sha512-OYTthRfSh55WOItVqwpefPtNt2VdKsq5AnAK6apdtR6yCH8pr0CmSr710J0Mf+WdQy7K/OzMy7K2MgAfdQURDw==", "inBundle": true, "license": "MIT" }, "node_modules/just-extend": { "version": "6.2.0", - "resolved": "https://registry.npmjs.org/just-extend/-/just-extend-6.2.0.tgz", - "integrity": "sha512-cYofQu2Xpom82S6qD778jBDpwvvy39s1l/hrYij2u9AMdQcGRpaBu6kY4mVhuno5kJVi1DAz4aiphA2WI1/OAw==", "dev": true, "license": "MIT" }, "node_modules/just-omit": { "version": "2.2.0", - "resolved": "https://registry.npmjs.org/just-omit/-/just-omit-2.2.0.tgz", - "integrity": "sha512-Js7+HxDOGcB3RhI38Mird/RgyMf3t0DAJFda1QWqqlAKTa36NeSYIufJXxrZUbysFTRcTOFcoMCiFK5FwCoI7Q==", "dev": true, "license": "MIT" }, "node_modules/just-safe-set": { "version": "4.2.1", - "resolved": "https://registry.npmjs.org/just-safe-set/-/just-safe-set-4.2.1.tgz", - "integrity": "sha512-La5CP41Ycv52+E4g7w1sRV8XXk7Sp8a/TwWQAYQKn6RsQz1FD4Z/rDRRmqV3wJznS1MDF3YxK7BCudX1J8FxLg==", "dev": true, "license": "MIT" }, "node_modules/keyv": { "version": "4.5.4", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", - "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", "dev": true, "license": "MIT", "peer": true, @@ -7650,28 +9114,14 @@ }, "node_modules/kind-of": { "version": "6.0.3", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", - "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/kleur": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", - "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", "dev": true, "license": "MIT", "engines": { - "node": ">=6" + "node": ">=0.10.0" } }, "node_modules/leven": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/leven/-/leven-2.1.0.tgz", - "integrity": "sha512-nvVPLpIHUxCUoRLrFqTgSxXJ614d8AgQoWl7zPe/2VadE8+1dpU3LBhowRuBAcuwruWtOdD8oYC9jDNJjXDPyA==", "dev": true, "license": "MIT", "engines": { @@ -7680,8 +9130,6 @@ }, "node_modules/levn": { "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", "dev": true, "license": "MIT", "peer": true, @@ -7709,10 +9157,6 @@ "resolved": "workspaces/libnpmfund", "link": true }, - "node_modules/libnpmhook": { - "resolved": "workspaces/libnpmhook", - "link": true - }, "node_modules/libnpmorg": { "resolved": "workspaces/libnpmorg", "link": true @@ -7739,8 +9183,6 @@ }, "node_modules/libtap": { "version": "1.4.1", - "resolved": "https://registry.npmjs.org/libtap/-/libtap-1.4.1.tgz", - "integrity": "sha512-S9v19shLTigoMn3c02V7LZ4t09zxmVP3r3RbEAwuHFYeKgF+ESFJxoQ0PMFKW4XdgQhcjVBEwDoopG6WROq/gw==", "dev": true, "license": "ISC", "dependencies": { @@ -7766,9 +9208,9 @@ } }, "node_modules/libtap/node_modules/diff": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", - "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", + "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==", "dev": true, "license": "BSD-3-Clause", "engines": { @@ -7777,8 +9219,6 @@ }, "node_modules/libtap/node_modules/minipass": { "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", "dev": true, "license": "ISC", "dependencies": { @@ -7790,122 +9230,46 @@ }, "node_modules/libtap/node_modules/signal-exit": { "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/libtap/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true, "license": "ISC" }, "node_modules/lines-and-columns": { "version": "1.2.4", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "dev": true, "license": "MIT" }, - "node_modules/locate-path": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-7.2.0.tgz", - "integrity": "sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^6.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.camelcase": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", - "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", "dev": true, "license": "MIT" }, "node_modules/lodash.flattendeep": { "version": "4.4.0", - "resolved": "https://registry.npmjs.org/lodash.flattendeep/-/lodash.flattendeep-4.4.0.tgz", - "integrity": "sha512-uHaJFihxmJcEX3kT4I23ABqKKalJ/zDrDg0lsFtc1h+3uw49SIJ5beyhx5ExVRti3AvKoOJngIj7xz3oylPdWQ==", "dev": true, "license": "MIT" }, "node_modules/lodash.ismatch": { "version": "4.4.0", - "resolved": "https://registry.npmjs.org/lodash.ismatch/-/lodash.ismatch-4.4.0.tgz", - "integrity": "sha512-fPMfXjGQEV9Xsq/8MTSgUf255gawYRbjwMyDbcvDhXgV7enSZA0hynz6vMPnpAb5iONEzBHBPsT+0zes5Z301g==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.isplainobject": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", - "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.kebabcase": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lodash.kebabcase/-/lodash.kebabcase-4.1.1.tgz", - "integrity": "sha512-N8XRTIMMqqDgSy4VLKPnJ/+hpGZN+PHQiJnSenYqPaVV/NCqEogTnAdZLQiGKhxX+JCs8waWq2t1XHWKOmlY8g==", "dev": true, "license": "MIT" }, "node_modules/lodash.merge": { "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.mergewith": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.mergewith/-/lodash.mergewith-4.6.2.tgz", - "integrity": "sha512-GK3g5RPZWTRSeLSpgP8Xhra+pnjBC56q9FZYe1d5RN3TJ35dbkGy3YqBSMbyCrlbi+CM9Z3Jk5yTL7RCsqboyQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.snakecase": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", - "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.startcase": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/lodash.startcase/-/lodash.startcase-4.4.0.tgz", - "integrity": "sha512-+WKqsK294HMSc2jEbNgpHpd0JfIBhp7rEV4aqXWqFr6AlXov+SlcgB1Fv01y2kGe3Gc8nMW7VA0SrGuSkRfIEg==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.uniq": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", - "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.upperfirst": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/lodash.upperfirst/-/lodash.upperfirst-4.3.1.tgz", - "integrity": "sha512-sReKOYJIJf74dhJONhU4e0/shzi1trVbSWDOhKYE5XV2O+H7Sb2Dihwuc7xWxVl+DgFPyTqIN3zMfT9cq5iWDg==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/longest-streak": { "version": "3.1.0", - "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz", - "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==", "dev": true, "license": "MIT", "funding": { @@ -7914,19 +9278,17 @@ } }, "node_modules/lru-cache": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.2.tgz", - "integrity": "sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ==", + "version": "11.5.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz", + "integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==", "inBundle": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "engines": { - "node": "14 || >=16.14" + "node": "20 || >=22" } }, "node_modules/make-dir": { "version": "3.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", - "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", "dev": true, "license": "MIT", "dependencies": { @@ -7941,8 +9303,6 @@ }, "node_modules/make-dir/node_modules/semver": { "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", "dev": true, "license": "ISC", "bin": { @@ -7950,33 +9310,49 @@ } }, "node_modules/make-fetch-happen": { - "version": "13.0.1", - "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-13.0.1.tgz", - "integrity": "sha512-cKTUFc/rbKUd/9meOvgrpJ2WrNzymt6jfRDdwg5UCnVzv9dTpEj9JS5m3wtziXVCjluIXyL8pcaukYqezIzZQA==", + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-16.0.1.tgz", + "integrity": "sha512-uUv1yxHzaKVVEPfcFeGSNov/Cehjv08ovlY8ImTljgL7Q+SiA0dAYLQ6SYVa2kkKqNj4Y3aZEI7xv2teadie0A==", "inBundle": true, "license": "ISC", "dependencies": { - "@npmcli/agent": "^2.0.0", - "cacache": "^18.0.0", + "@gar/promise-retry": "^1.0.0", + "@npmcli/agent": "^5.0.0", + "@npmcli/redact": "^5.0.0", + "cacache": "^21.0.0", "http-cache-semantics": "^4.1.1", - "is-lambda": "^1.0.1", "minipass": "^7.0.2", - "minipass-fetch": "^3.0.0", + "minipass-fetch": "^6.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", - "negotiator": "^0.6.3", - "proc-log": "^4.2.0", - "promise-retry": "^2.0.1", - "ssri": "^10.0.0" + "negotiator": "^1.0.0", + "proc-log": "^7.0.0", + "ssri": "^14.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/make-fetch-happen/node_modules/minipass-fetch": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-6.0.0.tgz", + "integrity": "sha512-AWI8bKapGmgx/J0E6IGYSKj8TiHebZkmKWSs8raPSw8KXwgEAJ+Bw3+LSdXHR6T/RHKAWCOYk2MiLrYluaUU6w==", + "inBundle": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.0.3", + "minipass-sized": "^2.0.0", + "minizlib": "^3.0.1" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "optionalDependencies": { + "iconv-lite": "^0.7.2" } }, "node_modules/map-obj": { "version": "4.3.0", - "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-4.3.0.tgz", - "integrity": "sha512-hdN1wVrZbb29eBGiGjJbeP8JbKjq1urkHJ/LIP/NY48MZ1QVXUsQBV1G1zvYFHn1XE06cwjBsOI2K3Ulnj1YXQ==", "dev": true, "license": "MIT", "engines": { @@ -7987,9 +9363,7 @@ } }, "node_modules/markdown-table": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.3.tgz", - "integrity": "sha512-Z1NL3Tb1M9wH4XESsCDEksWoKTdlUafKc4pt0GRwjUyXaCFZ+dc3g2erqB6zm3szA2IUSi7VnPI+o/9jnxh9hw==", + "version": "3.0.4", "dev": true, "license": "MIT", "funding": { @@ -7997,64 +9371,24 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/mdast-util-definitions": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/mdast-util-definitions/-/mdast-util-definitions-5.1.2.tgz", - "integrity": "sha512-8SVPMuHqlPME/z3gqVwWY4zVXn8lqKv/pAhC57FuJ40ImXyBpmO5ukh98zB2v7Blql2FiHjHv9LVztSIqjY+MA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/mdast": "^3.0.0", - "@types/unist": "^2.0.0", - "unist-util-visit": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-definitions/node_modules/unist-util-visit": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-4.1.2.tgz", - "integrity": "sha512-MSd8OUGISqHdVvfY9TPhyK2VdUrPgxkUtWSuMHF6XAAFuL4LokseigBnZtPnJMu+FbynTkFNnFlyjxpVKujMRg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0", - "unist-util-visit-parents": "^5.1.1" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-definitions/node_modules/unist-util-visit-parents": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-5.1.3.tgz", - "integrity": "sha512-x6+y8g7wWMyQhL1iZfhIPhDAs7Xwbn9nRosDXl7qoPTSCy0yNxnKc+hWokFifWQIDGi154rdUqKvbCa4+1kLhg==", + "node_modules/math-intrinsics": { + "version": "1.1.0", "dev": true, "license": "MIT", - "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" + "peer": true, + "engines": { + "node": ">= 0.4" } }, "node_modules/mdast-util-find-and-replace": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-2.2.2.tgz", - "integrity": "sha512-MTtdFRz/eMDHXzeK6W3dO7mXUlF82Gom4y0oOgvHhh/HXZAGvIQDUvQ0SuUx+j2tv44b8xTHOm8K/9OoRFnXKw==", + "version": "3.0.2", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", + "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", - "unist-util-is": "^5.0.0", - "unist-util-visit-parents": "^5.0.0" + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" }, "funding": { "type": "opencollective", @@ -8063,8 +9397,6 @@ }, "node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", - "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", "dev": true, "license": "MIT", "engines": { @@ -8075,14 +9407,14 @@ } }, "node_modules/mdast-util-find-and-replace/node_modules/unist-util-visit-parents": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-5.1.3.tgz", - "integrity": "sha512-x6+y8g7wWMyQhL1iZfhIPhDAs7Xwbn9nRosDXl7qoPTSCy0yNxnKc+hWokFifWQIDGi154rdUqKvbCa4+1kLhg==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", + "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0" + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" }, "funding": { "type": "opencollective", @@ -8090,24 +9422,24 @@ } }, "node_modules/mdast-util-from-markdown": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-1.3.1.tgz", - "integrity": "sha512-4xTO/M8c82qBcnQc1tgpNtubGUW/Y1tBQ1B0i5CtSoelOLKFYlElIr3bvgREYYO5iRqbMY1YuqZng0GVOI8Qww==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz", + "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", - "@types/unist": "^2.0.0", + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", - "mdast-util-to-string": "^3.1.0", - "micromark": "^3.0.0", - "micromark-util-decode-numeric-character-reference": "^1.0.0", - "micromark-util-decode-string": "^1.0.0", - "micromark-util-normalize-identifier": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0", - "unist-util-stringify-position": "^3.0.0", - "uvu": "^0.5.0" + "devlop": "^1.0.0", + "mdast-util-to-string": "^4.0.0", + "micromark": "^4.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-decode-string": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unist-util-stringify-position": "^4.0.0" }, "funding": { "type": "opencollective", @@ -8115,19 +9447,17 @@ } }, "node_modules/mdast-util-gfm": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-2.0.2.tgz", - "integrity": "sha512-qvZ608nBppZ4icQlhQQIAdc6S3Ffj9RGmzwUKUWuEICFnd1LVkN3EktF7ZHAgfcEdvZB5owU9tQgt99e2TlLjg==", + "version": "3.1.0", "dev": true, "license": "MIT", "dependencies": { - "mdast-util-from-markdown": "^1.0.0", - "mdast-util-gfm-autolink-literal": "^1.0.0", - "mdast-util-gfm-footnote": "^1.0.0", - "mdast-util-gfm-strikethrough": "^1.0.0", - "mdast-util-gfm-table": "^1.0.0", - "mdast-util-gfm-task-list-item": "^1.0.0", - "mdast-util-to-markdown": "^1.0.0" + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-gfm-autolink-literal": "^2.0.0", + "mdast-util-gfm-footnote": "^2.0.0", + "mdast-util-gfm-strikethrough": "^2.0.0", + "mdast-util-gfm-table": "^2.0.0", + "mdast-util-gfm-task-list-item": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8135,16 +9465,15 @@ } }, "node_modules/mdast-util-gfm-autolink-literal": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-1.0.3.tgz", - "integrity": "sha512-My8KJ57FYEy2W2LyNom4n3E7hKTuQk/0SES0u16tjA9Z3oFkF4RrC/hPAPgjlSpezsOvI8ObcXcElo92wn5IGA==", + "version": "2.0.1", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", + "@types/mdast": "^4.0.0", "ccount": "^2.0.0", - "mdast-util-find-and-replace": "^2.0.0", - "micromark-util-character": "^1.0.0" + "devlop": "^1.0.0", + "mdast-util-find-and-replace": "^3.0.0", + "micromark-util-character": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8152,15 +9481,15 @@ } }, "node_modules/mdast-util-gfm-footnote": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-1.0.2.tgz", - "integrity": "sha512-56D19KOGbE00uKVj3sgIykpwKL179QsVFwx/DCW0u/0+URsryacI4MAdNJl0dh+u2PSsD9FtxPFbHCzJ78qJFQ==", + "version": "2.1.0", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", - "mdast-util-to-markdown": "^1.3.0", - "micromark-util-normalize-identifier": "^1.0.0" + "@types/mdast": "^4.0.0", + "devlop": "^1.1.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8168,14 +9497,13 @@ } }, "node_modules/mdast-util-gfm-strikethrough": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-1.0.3.tgz", - "integrity": "sha512-DAPhYzTYrRcXdMjUtUjKvW9z/FNAMTdU0ORyMcbmkwYNbKocDpdk+PX1L1dQgOID/+vVs1uBQ7ElrBQfZ0cuiQ==", + "version": "2.0.0", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", - "mdast-util-to-markdown": "^1.3.0" + "@types/mdast": "^4.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8183,16 +9511,15 @@ } }, "node_modules/mdast-util-gfm-table": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-1.0.7.tgz", - "integrity": "sha512-jjcpmNnQvrmN5Vx7y7lEc2iIOEytYv7rTvu+MeyAsSHTASGCCRA79Igg2uKssgOs1i1po8s3plW0sTu1wkkLGg==", + "version": "2.0.0", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", "markdown-table": "^3.0.0", - "mdast-util-from-markdown": "^1.0.0", - "mdast-util-to-markdown": "^1.3.0" + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8200,14 +9527,14 @@ } }, "node_modules/mdast-util-gfm-task-list-item": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-1.0.2.tgz", - "integrity": "sha512-PFTA1gzfp1B1UaiJVyhJZA1rm0+Tzn690frc/L8vNX1Jop4STZgOE6bxUhnzdVSB+vm2GU1tIsuQcA9bxTQpMQ==", + "version": "2.0.0", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", - "mdast-util-to-markdown": "^1.3.0" + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8215,14 +9542,12 @@ } }, "node_modules/mdast-util-phrasing": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-3.0.1.tgz", - "integrity": "sha512-WmI1gTXUBJo4/ZmSk79Wcb2HcjPJBzM1nlI/OUWA8yk2X9ik3ffNbBGsU+09BFmXaL1IBb9fiuvq6/KMiNycSg==", + "version": "4.1.0", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", - "unist-util-is": "^5.0.0" + "@types/mdast": "^4.0.0", + "unist-util-is": "^6.0.0" }, "funding": { "type": "opencollective", @@ -8230,20 +9555,21 @@ } }, "node_modules/mdast-util-to-hast": { - "version": "12.3.0", - "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-12.3.0.tgz", - "integrity": "sha512-pits93r8PhnIoU4Vy9bjW39M2jJ6/tdHyja9rrot9uujkN7UTU9SDnE6WNJz/IGyQk3XHX6yNNtrBH6cQzm8Hw==", + "version": "13.2.1", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", + "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==", "dev": true, "license": "MIT", "dependencies": { - "@types/hast": "^2.0.0", - "@types/mdast": "^3.0.0", - "mdast-util-definitions": "^5.0.0", - "micromark-util-sanitize-uri": "^1.1.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", - "unist-util-generated": "^2.0.0", - "unist-util-position": "^4.0.0", - "unist-util-visit": "^4.0.0" + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" }, "funding": { "type": "opencollective", @@ -8251,15 +9577,15 @@ } }, "node_modules/mdast-util-to-hast/node_modules/unist-util-visit": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-4.1.2.tgz", - "integrity": "sha512-MSd8OUGISqHdVvfY9TPhyK2VdUrPgxkUtWSuMHF6XAAFuL4LokseigBnZtPnJMu+FbynTkFNnFlyjxpVKujMRg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz", + "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0", - "unist-util-visit-parents": "^5.1.1" + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" }, "funding": { "type": "opencollective", @@ -8267,14 +9593,14 @@ } }, "node_modules/mdast-util-to-hast/node_modules/unist-util-visit-parents": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-5.1.3.tgz", - "integrity": "sha512-x6+y8g7wWMyQhL1iZfhIPhDAs7Xwbn9nRosDXl7qoPTSCy0yNxnKc+hWokFifWQIDGi154rdUqKvbCa4+1kLhg==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", + "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0" + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" }, "funding": { "type": "opencollective", @@ -8282,19 +9608,18 @@ } }, "node_modules/mdast-util-to-markdown": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-1.5.0.tgz", - "integrity": "sha512-bbv7TPv/WC49thZPg3jXuqzuvI45IL2EVAr/KxF0BSdHsU0ceFHOmwQn6evxAh1GaoK/6GQ1wp4R4oW2+LFL/A==", + "version": "2.1.2", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", - "@types/unist": "^2.0.0", + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", "longest-streak": "^3.0.0", - "mdast-util-phrasing": "^3.0.0", - "mdast-util-to-string": "^3.0.0", - "micromark-util-decode-string": "^1.0.0", - "unist-util-visit": "^4.0.0", + "mdast-util-phrasing": "^4.0.0", + "mdast-util-to-string": "^4.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-decode-string": "^2.0.0", + "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" }, "funding": { @@ -8303,15 +9628,15 @@ } }, "node_modules/mdast-util-to-markdown/node_modules/unist-util-visit": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-4.1.2.tgz", - "integrity": "sha512-MSd8OUGISqHdVvfY9TPhyK2VdUrPgxkUtWSuMHF6XAAFuL4LokseigBnZtPnJMu+FbynTkFNnFlyjxpVKujMRg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz", + "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0", - "unist-util-visit-parents": "^5.1.1" + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" }, "funding": { "type": "opencollective", @@ -8319,14 +9644,14 @@ } }, "node_modules/mdast-util-to-markdown/node_modules/unist-util-visit-parents": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-5.1.3.tgz", - "integrity": "sha512-x6+y8g7wWMyQhL1iZfhIPhDAs7Xwbn9nRosDXl7qoPTSCy0yNxnKc+hWokFifWQIDGi154rdUqKvbCa4+1kLhg==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", + "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0" + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" }, "funding": { "type": "opencollective", @@ -8334,43 +9659,39 @@ } }, "node_modules/mdast-util-to-string": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-3.2.0.tgz", - "integrity": "sha512-V4Zn/ncyN1QNSqSBxTrMOLpjr+IKdHl2v3KVLoWmDPscP4r9GcCi71gjgvUV1SFSKh92AjAG4peFuBl2/YgCJg==", + "version": "4.0.0", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0" + "@types/mdast": "^4.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/unified" } }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, "node_modules/meow": { - "version": "12.1.1", - "resolved": "https://registry.npmjs.org/meow/-/meow-12.1.1.tgz", - "integrity": "sha512-BhXM0Au22RwUneMPwSCnyhTOizdWoIEPU9sp0Aqa1PnDMR5Wv2FGXYDjuzJEIX+Eo2Rb8xuYe5jrnm5QowQFkw==", + "version": "13.2.0", + "resolved": "https://registry.npmjs.org/meow/-/meow-13.2.0.tgz", + "integrity": "sha512-pxQJQzB6djGPXh08dacEloMFopsOqGVRKFPYvPOt9XDZ1HasbgDZA74CJGreSU4G3Ak7EFJGoiH2auq+yXISgA==", "dev": true, "license": "MIT", "engines": { - "node": ">=16.10" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true, - "license": "MIT" - }, "node_modules/micromark": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/micromark/-/micromark-3.2.0.tgz", - "integrity": "sha512-uD66tJj54JLYq0De10AhWycZWGQNUvDI55xPgk2sQM5kn1JYlhbCMTtEeT27+vAhW2FBQxLlOmS3pmA7/2z4aA==", + "version": "4.0.2", "dev": true, "funding": [ { @@ -8387,26 +9708,24 @@ "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", - "micromark-core-commonmark": "^1.0.1", - "micromark-factory-space": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-chunked": "^1.0.0", - "micromark-util-combine-extensions": "^1.0.0", - "micromark-util-decode-numeric-character-reference": "^1.0.0", - "micromark-util-encode": "^1.0.0", - "micromark-util-normalize-identifier": "^1.0.0", - "micromark-util-resolve-all": "^1.0.0", - "micromark-util-sanitize-uri": "^1.0.0", - "micromark-util-subtokenize": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.1", - "uvu": "^0.5.0" + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, "node_modules/micromark-core-commonmark": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-1.1.0.tgz", - "integrity": "sha512-BgHO1aRbolh2hcrzL2d1La37V0Aoz73ymF8rAcKnohLy93titmv62E0gP8Hrx9PKcKrqCZ1BbLGbP3bEhoXYlw==", + "version": "2.0.3", "dev": true, "funding": [ { @@ -8421,38 +9740,36 @@ "license": "MIT", "dependencies": { "decode-named-character-reference": "^1.0.0", - "micromark-factory-destination": "^1.0.0", - "micromark-factory-label": "^1.0.0", - "micromark-factory-space": "^1.0.0", - "micromark-factory-title": "^1.0.0", - "micromark-factory-whitespace": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-chunked": "^1.0.0", - "micromark-util-classify-character": "^1.0.0", - "micromark-util-html-tag-name": "^1.0.0", - "micromark-util-normalize-identifier": "^1.0.0", - "micromark-util-resolve-all": "^1.0.0", - "micromark-util-subtokenize": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.1", - "uvu": "^0.5.0" + "devlop": "^1.0.0", + "micromark-factory-destination": "^2.0.0", + "micromark-factory-label": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-factory-title": "^2.0.0", + "micromark-factory-whitespace": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-html-tag-name": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, "node_modules/micromark-extension-gfm": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-2.0.3.tgz", - "integrity": "sha512-vb9OoHqrhCmbRidQv/2+Bc6pkP0FrtlhurxZofvOEy5o8RtuuvTq+RQ1Vw5ZDNrVraQZu3HixESqbG+0iKk/MQ==", + "version": "3.0.0", "dev": true, "license": "MIT", "dependencies": { - "micromark-extension-gfm-autolink-literal": "^1.0.0", - "micromark-extension-gfm-footnote": "^1.0.0", - "micromark-extension-gfm-strikethrough": "^1.0.0", - "micromark-extension-gfm-table": "^1.0.0", - "micromark-extension-gfm-tagfilter": "^1.0.0", - "micromark-extension-gfm-task-list-item": "^1.0.0", - "micromark-util-combine-extensions": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-extension-gfm-autolink-literal": "^2.0.0", + "micromark-extension-gfm-footnote": "^2.0.0", + "micromark-extension-gfm-strikethrough": "^2.0.0", + "micromark-extension-gfm-table": "^2.0.0", + "micromark-extension-gfm-tagfilter": "^2.0.0", + "micromark-extension-gfm-task-list-item": "^2.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-types": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8460,16 +9777,14 @@ } }, "node_modules/micromark-extension-gfm-autolink-literal": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-1.0.5.tgz", - "integrity": "sha512-z3wJSLrDf8kRDOh2qBtoTRD53vJ+CWIyo7uyZuxf/JAbNJjiHsOpG1y5wxk8drtv3ETAHutCu6N3thkOOgueWg==", + "version": "2.1.0", "dev": true, "license": "MIT", "dependencies": { - "micromark-util-character": "^1.0.0", - "micromark-util-sanitize-uri": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-character": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8477,20 +9792,18 @@ } }, "node_modules/micromark-extension-gfm-footnote": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-1.1.2.tgz", - "integrity": "sha512-Yxn7z7SxgyGWRNa4wzf8AhYYWNrwl5q1Z8ii+CSTTIqVkmGZF1CElX2JI8g5yGoM3GAman9/PVCUFUSJ0kB/8Q==", + "version": "2.1.0", "dev": true, "license": "MIT", "dependencies": { - "micromark-core-commonmark": "^1.0.0", - "micromark-factory-space": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-normalize-identifier": "^1.0.0", - "micromark-util-sanitize-uri": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0", - "uvu": "^0.5.0" + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8498,18 +9811,16 @@ } }, "node_modules/micromark-extension-gfm-strikethrough": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-1.0.7.tgz", - "integrity": "sha512-sX0FawVE1o3abGk3vRjOH50L5TTLr3b5XMqnP9YDRb34M0v5OoZhG+OHFz1OffZ9dlwgpTBKaT4XW/AsUVnSDw==", + "version": "2.1.0", "dev": true, "license": "MIT", "dependencies": { - "micromark-util-chunked": "^1.0.0", - "micromark-util-classify-character": "^1.0.0", - "micromark-util-resolve-all": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0", - "uvu": "^0.5.0" + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8517,17 +9828,15 @@ } }, "node_modules/micromark-extension-gfm-table": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-1.0.7.tgz", - "integrity": "sha512-3ZORTHtcSnMQEKtAOsBQ9/oHp9096pI/UvdPtN7ehKvrmZZ2+bbWhi0ln+I9drmwXMt5boocn6OlwQzNXeVeqw==", + "version": "2.1.1", "dev": true, "license": "MIT", "dependencies": { - "micromark-factory-space": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0", - "uvu": "^0.5.0" + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8535,13 +9844,11 @@ } }, "node_modules/micromark-extension-gfm-tagfilter": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-1.0.2.tgz", - "integrity": "sha512-5XWB9GbAUSHTn8VPU8/1DBXMuKYT5uOgEjJb8gN3mW0PNW5OPHpSdojoqf+iq1xo7vWzw/P8bAHY0n6ijpXF7g==", + "version": "2.0.0", "dev": true, "license": "MIT", "dependencies": { - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8549,17 +9856,15 @@ } }, "node_modules/micromark-extension-gfm-task-list-item": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-1.0.5.tgz", - "integrity": "sha512-RMFXl2uQ0pNQy6Lun2YBYT9g9INXtWJULgbt01D/x8/6yJ2qpKyzdZD3pi6UIkzF++Da49xAelVKUeUMqd5eIQ==", + "version": "2.1.0", "dev": true, "license": "MIT", "dependencies": { - "micromark-factory-space": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0", - "uvu": "^0.5.0" + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" }, "funding": { "type": "opencollective", @@ -8567,9 +9872,7 @@ } }, "node_modules/micromark-factory-destination": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-1.1.0.tgz", - "integrity": "sha512-XaNDROBgx9SgSChd69pjiGKbV+nfHGDPVYFs5dOoDd7ZnMAE+Cuu91BCpsY8RT2NP9vo/B8pds2VQNCLiu0zhg==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8583,15 +9886,13 @@ ], "license": "MIT", "dependencies": { - "micromark-util-character": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, "node_modules/micromark-factory-label": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-1.1.0.tgz", - "integrity": "sha512-OLtyez4vZo/1NjxGhcpDSbHQ+m0IIGnT8BoPamh+7jVlzLJBH98zzuCoUeMxvM6WsNeh8wx8cKvqLiPHEACn0w==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8605,16 +9906,14 @@ ], "license": "MIT", "dependencies": { - "micromark-util-character": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0", - "uvu": "^0.5.0" + "devlop": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, "node_modules/micromark-factory-space": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-1.1.0.tgz", - "integrity": "sha512-cRzEj7c0OL4Mw2v6nwzttyOZe8XY/Z8G0rzmWQZTBi/jjwyw/U4uqKtUORXQrR5bAZZnbTI/feRV/R7hc4jQYQ==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8628,14 +9927,12 @@ ], "license": "MIT", "dependencies": { - "micromark-util-character": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, "node_modules/micromark-factory-title": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-1.1.0.tgz", - "integrity": "sha512-J7n9R3vMmgjDOCY8NPw55jiyaQnH5kBdV2/UXCtZIpnHH3P6nHUKaH7XXEYuWwx/xUJcawa8plLBEjMPU24HzQ==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8649,16 +9946,14 @@ ], "license": "MIT", "dependencies": { - "micromark-factory-space": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, "node_modules/micromark-factory-whitespace": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-1.1.0.tgz", - "integrity": "sha512-v2WlmiymVSp5oMg+1Q0N1Lxmt6pMhIHD457whWM7/GUlEks1hI9xj5w3zbc4uuMKXGisksZk8DzP2UyGbGqNsQ==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8672,16 +9967,14 @@ ], "license": "MIT", "dependencies": { - "micromark-factory-space": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, "node_modules/micromark-util-character": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-1.2.0.tgz", - "integrity": "sha512-lXraTwcX3yH/vMDaFWCQJP1uIszLVebzUa3ZHdrgxr7KEU/9mL4mVgCpGbyhvNLNlauROiNUq7WN5u7ndbY6xg==", + "version": "2.1.1", "dev": true, "funding": [ { @@ -8695,14 +9988,12 @@ ], "license": "MIT", "dependencies": { - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, "node_modules/micromark-util-chunked": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-1.1.0.tgz", - "integrity": "sha512-Ye01HXpkZPNcV6FiyoW2fGZDUw4Yc7vT0E9Sad83+bEDiCJ1uXu0S3mr8WLpsz3HaG3x2q0HM6CTuPdcZcluFQ==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8716,13 +10007,11 @@ ], "license": "MIT", "dependencies": { - "micromark-util-symbol": "^1.0.0" + "micromark-util-symbol": "^2.0.0" } }, "node_modules/micromark-util-classify-character": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-1.1.0.tgz", - "integrity": "sha512-SL0wLxtKSnklKSUplok1WQFoGhUdWYKggKUiqhX+Swala+BtptGCu5iPRc+xvzJ4PXE/hwM3FNXsfEVgoZsWbw==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8736,15 +10025,13 @@ ], "license": "MIT", "dependencies": { - "micromark-util-character": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, "node_modules/micromark-util-combine-extensions": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-1.1.0.tgz", - "integrity": "sha512-Q20sp4mfNf9yEqDL50WwuWZHUrCO4fEyeDCnMGmG5Pr0Cz15Uo7KBs6jq+dq0EgX4DPwwrh9m0X+zPV1ypFvUA==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8758,14 +10045,12 @@ ], "license": "MIT", "dependencies": { - "micromark-util-chunked": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-chunked": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, "node_modules/micromark-util-decode-numeric-character-reference": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-1.1.0.tgz", - "integrity": "sha512-m9V0ExGv0jB1OT21mrWcuf4QhP46pH1KkfWy9ZEezqHKAxkj4mPCy3nIH1rkbdMlChLHX531eOrymlwyZIf2iw==", + "version": "2.0.2", "dev": true, "funding": [ { @@ -8779,13 +10064,11 @@ ], "license": "MIT", "dependencies": { - "micromark-util-symbol": "^1.0.0" + "micromark-util-symbol": "^2.0.0" } }, "node_modules/micromark-util-decode-string": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-1.1.0.tgz", - "integrity": "sha512-YphLGCK8gM1tG1bd54azwyrQRjCFcmgj2S2GoJDNnh4vYtnL38JS8M4gpxzOPNyHdNEpheyWXCTnnTDY3N+NVQ==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8800,15 +10083,13 @@ "license": "MIT", "dependencies": { "decode-named-character-reference": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-decode-numeric-character-reference": "^1.0.0", - "micromark-util-symbol": "^1.0.0" + "micromark-util-character": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-symbol": "^2.0.0" } }, "node_modules/micromark-util-encode": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-1.1.0.tgz", - "integrity": "sha512-EuEzTWSTAj9PA5GOAs992GzNh2dGQO52UvAbtSOMvXTxv3Criqb6IOzJUBCmEqrrXSblJIJBbFFv6zPxpreiJw==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8823,9 +10104,7 @@ "license": "MIT" }, "node_modules/micromark-util-html-tag-name": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-1.2.0.tgz", - "integrity": "sha512-VTQzcuQgFUD7yYztuQFKXT49KghjtETQ+Wv/zUjGSGBioZnkA4P1XXZPT1FHeJA6RwRXSF47yvJ1tsJdoxwO+Q==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8840,9 +10119,7 @@ "license": "MIT" }, "node_modules/micromark-util-normalize-identifier": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-1.1.0.tgz", - "integrity": "sha512-N+w5vhqrBihhjdpM8+5Xsxy71QWqGn7HYNUvch71iV2PM7+E3uWGox1Qp90loa1ephtCxG2ftRV/Conitc6P2Q==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8856,13 +10133,11 @@ ], "license": "MIT", "dependencies": { - "micromark-util-symbol": "^1.0.0" + "micromark-util-symbol": "^2.0.0" } }, "node_modules/micromark-util-resolve-all": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-1.1.0.tgz", - "integrity": "sha512-b/G6BTMSg+bX+xVCshPTPyAu2tmA0E4X98NSR7eIbeC6ycCqCeE7wjfDIgzEbkzdEVJXRtOG4FbEm/uGbCRouA==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8876,13 +10151,11 @@ ], "license": "MIT", "dependencies": { - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^2.0.0" } }, "node_modules/micromark-util-sanitize-uri": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-1.2.0.tgz", - "integrity": "sha512-QO4GXv0XZfWey4pYFndLUKEAktKkG5kZTdUNaTAkzbuJxn2tNBOr+QtxR2XpWaMhbImT2dPzyLrPXLlPhph34A==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8896,15 +10169,13 @@ ], "license": "MIT", "dependencies": { - "micromark-util-character": "^1.0.0", - "micromark-util-encode": "^1.0.0", - "micromark-util-symbol": "^1.0.0" + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" } }, "node_modules/micromark-util-subtokenize": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-1.1.0.tgz", - "integrity": "sha512-kUQHyzRoxvZO2PuLzMt2P/dwVsTiivCK8icYTeR+3WgbuPqfHgPPy7nFKbeqRivBvn/3N3GBiNC+JRTMSxEC7A==", + "version": "2.1.0", "dev": true, "funding": [ { @@ -8918,16 +10189,14 @@ ], "license": "MIT", "dependencies": { - "micromark-util-chunked": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0", - "uvu": "^0.5.0" + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, "node_modules/micromark-util-symbol": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-1.1.0.tgz", - "integrity": "sha512-uEjpEYY6KMs1g7QfJ2eX1SQEV+ZT4rUD3UcF6l57acZvLNK7PBZL+ty82Z1qhK1/yXIY4bdx04FKMgR0g4IAag==", + "version": "2.0.1", "dev": true, "funding": [ { @@ -8942,9 +10211,7 @@ "license": "MIT" }, "node_modules/micromark-util-types": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-1.1.0.tgz", - "integrity": "sha512-ukRBgie8TIAcacscVHSiddHjO4k/q3pnedmzMQ4iwDcK0FtFCohKOlFbaOL/mPgfnPsL3C1ZyxJa4sbWrBl3jg==", + "version": "2.0.2", "dev": true, "funding": [ { @@ -8958,46 +10225,8 @@ ], "license": "MIT" }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dev": true, - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mimic-fn": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", - "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/min-indent": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", - "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", "dev": true, "license": "MIT", "engines": { @@ -9005,26 +10234,24 @@ } }, "node_modules/minify-registry-metadata": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/minify-registry-metadata/-/minify-registry-metadata-3.0.0.tgz", - "integrity": "sha512-EvM09tT0saeVP2Tlu9WEUDUgTYi684LsBbC+nbU3XEENgnzz+aEskigZR+OYG8LJPat1FdSIKMkJLMojg0FIiQ==", + "version": "4.0.0", "dev": true, "license": "ISC", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^18.17.0 || >=20.5.0" } }, "node_modules/minimatch": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", - "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", "inBundle": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^2.0.1" + "brace-expansion": "^5.0.5" }, "engines": { - "node": ">=16 || 14 >=14.17" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -9032,8 +10259,6 @@ }, "node_modules/minimist": { "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", "dev": true, "license": "MIT", "funding": { @@ -9042,8 +10267,6 @@ }, "node_modules/minimist-options": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/minimist-options/-/minimist-options-4.1.0.tgz", - "integrity": "sha512-Q4r8ghd80yhO/0j1O3B2BjweX3fiHg9cdOwjJd2J76Q135c+NDxGCqdYKQ1SKBuFfgWbAUzBfvYjPUEeNgqN1A==", "dev": true, "license": "MIT", "dependencies": { @@ -9057,8 +10280,6 @@ }, "node_modules/minimist-options/node_modules/is-plain-obj": { "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-1.1.0.tgz", - "integrity": "sha512-yvkRyxmFKEOQ4pNXCmJG5AEQNlXJS5LaONXo5/cLdTZdWvsZ1ioJEonLGAosKlMWE8lwUy/bJzMjcw8az73+Fg==", "dev": true, "license": "MIT", "engines": { @@ -9066,19 +10287,17 @@ } }, "node_modules/minipass": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", - "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", "inBundle": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "engines": { "node": ">=16 || 14 >=14.17" } }, "node_modules/minipass-collect": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-2.0.1.tgz", - "integrity": "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw==", "inBundle": true, "license": "ISC", "dependencies": { @@ -9089,53 +10308,38 @@ } }, "node_modules/minipass-fetch": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-3.0.5.tgz", - "integrity": "sha512-2N8elDQAtSnFV0Dk7gt15KHsS0Fyz6CbYZ360h0WTYV1Ty46li3rAXVOQj1THMNLdmrD9Vt5pBPtWtVkpwGBqg==", - "inBundle": true, + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-5.0.2.tgz", + "integrity": "sha512-2d0q2a8eCi2IRg/IGubCNRJoYbA1+YPXAzQVRFmB45gdGZafyivnZ5YSEfo3JikbjGxOdntGFvBQGqaSMXlAFQ==", + "dev": true, "license": "MIT", "dependencies": { "minipass": "^7.0.3", - "minipass-sized": "^1.0.3", - "minizlib": "^2.1.2" + "minipass-sized": "^2.0.0", + "minizlib": "^3.0.1" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" }, "optionalDependencies": { - "encoding": "^0.1.13" - } - }, - "node_modules/minipass-flush": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.5.tgz", - "integrity": "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==", - "inBundle": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">= 8" + "iconv-lite": "^0.7.2" } }, - "node_modules/minipass-flush/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "node_modules/minipass-flush": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.6.tgz", + "integrity": "sha512-7Uf5gMJZ2kTkFisE3toGxT991s+cg+vMh42nbZGM2bNxfYVpkpqRudf1QrcOy72a3PwcL4JYqL+4NY7t0Hdd0A==", "inBundle": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "dependencies": { - "yallist": "^4.0.0" + "minipass": "^7.1.3" }, "engines": { - "node": ">=8" + "node": ">=16 || 14 >=14.17" } }, "node_modules/minipass-pipeline": { "version": "1.2.4", - "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", - "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", "inBundle": true, "license": "ISC", "dependencies": { @@ -9147,8 +10351,6 @@ }, "node_modules/minipass-pipeline/node_modules/minipass": { "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", "inBundle": true, "license": "ISC", "dependencies": { @@ -9158,76 +10360,41 @@ "node": ">=8" } }, - "node_modules/minipass-sized": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-1.0.3.tgz", - "integrity": "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==", + "node_modules/minipass-pipeline/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "inBundle": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">=8" - } + "license": "ISC" }, - "node_modules/minipass-sized/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "node_modules/minipass-sized": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-2.0.0.tgz", + "integrity": "sha512-zSsHhto5BcUVM2m1LurnXY6M//cGhVaegT71OfOXoprxT6o780GZd792ea6FfrQkuU4usHZIUczAQMRUE2plzA==", "inBundle": true, "license": "ISC", "dependencies": { - "yallist": "^4.0.0" + "minipass": "^7.1.2" }, "engines": { "node": ">=8" } }, "node_modules/minizlib": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", - "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", "inBundle": true, "license": "MIT", "dependencies": { - "minipass": "^3.0.0", - "yallist": "^4.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/minizlib/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "inBundle": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/mkdirp": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", - "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", - "inBundle": true, - "license": "MIT", - "bin": { - "mkdirp": "bin/cmd.js" + "minipass": "^7.1.2" }, "engines": { - "node": ">=10" + "node": ">= 18" } }, "node_modules/modify-values": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/modify-values/-/modify-values-1.0.1.tgz", - "integrity": "sha512-xV2bxeN6F7oYjZWTe/YPAy6MN2M+sL4u/Rlm2AHCIVGfo2p1yGmBHQ6vHehl4bRTZBdHu3TSkWdYgkwpYzAGSw==", "dev": true, "license": "MIT", "engines": { @@ -9236,8 +10403,6 @@ }, "node_modules/months": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/months/-/months-2.1.0.tgz", - "integrity": "sha512-2M9gdDB/uVt304/hJ3k2UIquJhOV5dRjp9BovHmZSINaRp7pdJuHXxOcuSjmJaKNomFyYyu0y3LBigdWiAUEmQ==", "dev": true, "license": "MIT", "engines": { @@ -9245,51 +10410,35 @@ } }, "node_modules/moo": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.2.tgz", - "integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q==", + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.3.tgz", + "integrity": "sha512-m2fmM2dDm7GZQsY7KK2cme8agi+AAljILjQnof7p1ZMDe6dQ4bdnSMx0cPppudoeNv5hEFQirN6u+O4fDE0IWA==", "dev": true, "license": "BSD-3-Clause" }, - "node_modules/mri": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", - "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, "node_modules/ms": { "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "inBundle": true, "license": "MIT" }, "node_modules/mute-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-1.0.0.tgz", - "integrity": "sha512-avsJQhyd+680gKXyG/sQc0nXaC6rBkPOfyHYcFb9+hdkqQkR9bdnkJ0AMZhke0oesPqIO+mFFJ+IdBc7mst4IA==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-4.0.0.tgz", + "integrity": "sha512-gSrprq0fJ3EiOErzjdIZrjysVVmJ4uu1QWfCDss5LypA5OXvrMje5Ym5z6V6RLyJ2eF87lasX7t6a0AnFvZblg==", "inBundle": true, "license": "ISC", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/natural-compare": { "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", "dev": true, "license": "MIT", "peer": true }, "node_modules/nearley": { "version": "2.20.1", - "resolved": "https://registry.npmjs.org/nearley/-/nearley-2.20.1.tgz", - "integrity": "sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ==", "dev": true, "license": "MIT", "dependencies": { @@ -9310,9 +10459,7 @@ } }, "node_modules/negotiator": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", - "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "version": "1.0.0", "inBundle": true, "license": "MIT", "engines": { @@ -9321,86 +10468,82 @@ }, "node_modules/neo-async": { "version": "2.6.2", - "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", - "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", "dev": true, "license": "MIT" }, "node_modules/nock": { - "version": "13.5.4", - "resolved": "https://registry.npmjs.org/nock/-/nock-13.5.4.tgz", - "integrity": "sha512-yAyTfdeNJGGBFxWdzSKCBYxs5FxLbCg5X5Q4ets974hcQzG1+qCxvIyOo4j2Ry6MUlhWVMX4OoYDefAIIwupjw==", + "version": "14.0.15", + "resolved": "https://registry.npmjs.org/nock/-/nock-14.0.15.tgz", + "integrity": "sha512-S0a47C9pLvcYx/Ugf0H30BVBEcUgMMBDk9VJIDlJ8XGrfH2QDUD4Tgdp45qDIiHttokBG+IbsOtsvIjGR/j3bg==", "dev": true, "license": "MIT", "dependencies": { - "debug": "^4.1.0", + "@mswjs/interceptors": "^0.41.0", "json-stringify-safe": "^5.0.1", "propagate": "^2.0.0" }, "engines": { - "node": ">= 10.13" + "node": ">=18.20.0 <20 || >=20.12.1" } }, - "node_modules/node-fetch": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", - "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "node_modules/node-exports-info": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/node-exports-info/-/node-exports-info-1.6.0.tgz", + "integrity": "sha512-pyFS63ptit/P5WqUkt+UUfe+4oevH+bFeIiPPdfb0pFeYEu/1ELnJu5l+5EcTKYL5M7zaAa7S8ddywgXypqKCw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { - "whatwg-url": "^5.0.0" + "array.prototype.flatmap": "^1.3.3", + "es-errors": "^1.3.0", + "object.entries": "^1.1.9", + "semver": "^6.3.1" }, "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" + "node": ">= 0.4" }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/node-exports-info/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "peer": true, + "bin": { + "semver": "bin/semver.js" } }, "node_modules/node-gyp": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-10.1.0.tgz", - "integrity": "sha512-B4J5M1cABxPc5PwfjhbV5hoy2DP9p8lFXASnEN6hugXOa61416tnTZ29x9sSwAd0o99XNIcpvDDy1swAExsVKA==", + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-13.0.0.tgz", + "integrity": "sha512-FYYyBDWdc+kzoyPd5PqHUgM9DGs1C/Z4jxBZAOnA2GRUVXPivKRREq5q+VVPXVr9aGVqGMaMqyFHbviy/yb7Hg==", "inBundle": true, "license": "MIT", "dependencies": { "env-paths": "^2.2.0", "exponential-backoff": "^3.1.1", - "glob": "^10.3.10", "graceful-fs": "^4.2.6", - "make-fetch-happen": "^13.0.0", - "nopt": "^7.0.0", - "proc-log": "^3.0.0", + "nopt": "^10.0.0", + "proc-log": "^7.0.0", "semver": "^7.3.5", - "tar": "^6.1.2", - "which": "^4.0.0" + "tar": "^7.5.4", + "tinyglobby": "^0.2.12", + "undici": "^6.25.0", + "which": "^7.0.0" }, "bin": { "node-gyp": "bin/node-gyp.js" }, "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/node-gyp/node_modules/proc-log": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-3.0.0.tgz", - "integrity": "sha512-++Vn7NS4Xf9NacaU9Xq3URUuqZETPsf8L4j5/ckhaRYsfPeRyzGw+iDjFhV/Jr3uNmTvvddEJFWh5R1gRgUH8A==", - "inBundle": true, - "license": "ISC", - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/node-html-parser": { "version": "6.1.13", - "resolved": "https://registry.npmjs.org/node-html-parser/-/node-html-parser-6.1.13.tgz", - "integrity": "sha512-qIsTMOY4C/dAa5Q5vsobRpOOvPfC4pB61UVW2uSwZNUp0QU/jCekTal1vMmbO0DgdHeLUJpv/ARmDqErVxA3Sg==", "dev": true, "license": "MIT", "dependencies": { @@ -9410,8 +10553,6 @@ }, "node_modules/node-preload": { "version": "0.2.1", - "resolved": "https://registry.npmjs.org/node-preload/-/node-preload-0.2.1.tgz", - "integrity": "sha512-RM5oyBy45cLEoHqCeh+MNuFAxO0vTFBLskvQbOKnEE7YTTSN4tbN8QWDIPQ6L+WvKsB/qLEGpYe2ZZ9d4W9OIQ==", "dev": true, "license": "MIT", "dependencies": { @@ -9422,47 +10563,33 @@ } }, "node_modules/node-releases": { - "version": "2.0.14", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz", - "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==", + "version": "2.0.46", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.46.tgz", + "integrity": "sha512-GYVXHE2KnrzAfsAjl4uP++evGFCrAU1jta4ubEjIG7YWt/64Gqv66a30yKwWczVjA6j3bM4nBwH7Pk1JmDHaxQ==", "dev": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": ">=18" + } }, "node_modules/nopt": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/nopt/-/nopt-7.2.1.tgz", - "integrity": "sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w==", + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-10.0.1.tgz", + "integrity": "sha512-df3sBr/6ax9hSGuC3CspvLlbnX8cP5L5nZwXF8cGN8l0zSWR6BvzmQ6jPUKjvo6+/xdpkNvEcucBNUdBeeV13g==", "inBundle": true, "license": "ISC", "dependencies": { - "abbrev": "^2.0.0" + "abbrev": "^5.0.0" }, "bin": { "nopt": "bin/nopt.js" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/normalize-package-data": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-6.0.2.tgz", - "integrity": "sha512-V6gygoYb/5EmNI+MEGrWkC+e6+Rr7mTmfHrxDbLzxQogBkgzo76rkok0Am6thgSF7Mv2nLOajAJj5vDJZEFn7g==", - "inBundle": true, - "license": "BSD-2-Clause", - "dependencies": { - "hosted-git-info": "^7.0.0", - "semver": "^7.3.5", - "validate-npm-package-license": "^3.0.4" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/normalize-path": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", "dev": true, "license": "MIT", "engines": { @@ -9470,173 +10597,185 @@ } }, "node_modules/npm-audit-report": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/npm-audit-report/-/npm-audit-report-5.0.0.tgz", - "integrity": "sha512-EkXrzat7zERmUhHaoren1YhTxFwsOu5jypE84k6632SXTHcQE1z8V51GC6GVZt8LxkC+tbBcKMUBZAgk8SUSbw==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/npm-audit-report/-/npm-audit-report-8.0.0.tgz", + "integrity": "sha512-LrRtLB4NKdXin5dw4yxcES8GDXncfoVVcYzkn8bdwc0etpHmxtKKwwI1YTWpQ9+lEmzEnZo10Lzb11QLxuuBnA==", "inBundle": true, "license": "ISC", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/npm-bundled": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/npm-bundled/-/npm-bundled-3.0.1.tgz", - "integrity": "sha512-+AvaheE/ww1JEwRHOrn4WHNzOxGtVp+adrg2AeZS/7KuxGUYFuBta98wYpfHBbJp6Tg6j1NKSEVHNcfZzJHQwQ==", - "inBundle": true, + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/npm-bundled/-/npm-bundled-5.0.0.tgz", + "integrity": "sha512-JLSpbzh6UUXIEoqPsYBvVNVmyrjVZ1fzEFbqxKkTJQkWBO3xFzFT+KDnSKQWwOQNbuWRwt5LSD6HOTLGIWzfrw==", + "dev": true, "license": "ISC", "dependencies": { - "npm-normalize-package-bin": "^3.0.0" + "npm-normalize-package-bin": "^5.0.0" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/npm-install-checks": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/npm-install-checks/-/npm-install-checks-6.3.0.tgz", - "integrity": "sha512-W29RiK/xtpCGqn6f3ixfRYGk+zRyr+Ew9F2E20BfXxT5/euLdA/Nm7fO7OeTGuAmTs30cpgInyJ0cYe708YTZw==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/npm-install-checks/-/npm-install-checks-9.0.0.tgz", + "integrity": "sha512-t05Izcgi7p15cpldqoiXYpjzlkTTvBw33sgjmL/JjcvtV0ydbm2O4iEXO8A6smqComu5FAQhUas86HTMQ6Z1Uw==", "inBundle": true, "license": "BSD-2-Clause", "dependencies": { "semver": "^7.1.1" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/npm-normalize-package-bin": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-3.0.1.tgz", - "integrity": "sha512-dMxCf+zZ+3zeQZXKxmyuCKlIDPGuv8EF940xbkC4kQVDTtqoh6rJFO+JTKSA6/Rwi0getWmtuy4Itup0AMcaDQ==", - "inBundle": true, + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-5.0.0.tgz", + "integrity": "sha512-CJi3OS4JLsNMmr2u07OJlhcrPxCeOeP/4xq67aWNai6TNWWbTrlNDgl8NcFKVlcBKp18GPj+EzbNIgrBfZhsag==", + "dev": true, "license": "ISC", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/npm-package-arg": { - "version": "11.0.2", - "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-11.0.2.tgz", - "integrity": "sha512-IGN0IAwmhDJwy13Wc8k+4PEbTPhpJnMtfR53ZbOyjkvmEcLS4nCwp6mvMWjS5sUjeiW3mpx6cHmuhKEu9XmcQw==", + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-14.0.0.tgz", + "integrity": "sha512-69XQh3k+dtGa1p+7RaR57IuG3rCko96xr/nUfN4yDYBXbTYICiWcOpsFKLN2GtGE9cyIljE+f1exnaYt9MvM+Q==", "inBundle": true, "license": "ISC", "dependencies": { - "hosted-git-info": "^7.0.0", - "proc-log": "^4.0.0", + "hosted-git-info": "^10.1.0", + "proc-log": "^7.0.0", "semver": "^7.3.5", - "validate-npm-package-name": "^5.0.0" + "validate-npm-package-name": "^8.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/npm-packlist": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-8.0.2.tgz", - "integrity": "sha512-shYrPFIS/JLP4oQmAwDyk5HcyysKW8/JLTEA32S0Z5TzvpaeeX2yMFfoK1fjEBnCBvVyIB/Jj/GBFdm0wsgzbA==", + "version": "11.3.0", + "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-11.3.0.tgz", + "integrity": "sha512-cS1yVkyriZgQAbiK8PtwhZHEtsFOsKHsCg5Ww2ONckAvXIspgqd6o4WirOzvkupU24iMRZ4xtO4kb2iK2rbnag==", "inBundle": true, "license": "ISC", "dependencies": { - "ignore-walk": "^6.0.4" + "glob": "^13.0.6", + "ignore-walk": "^9.0.0", + "proc-log": "^7.0.0" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/npm-packlist/node_modules/ignore-walk": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/ignore-walk/-/ignore-walk-9.0.0.tgz", + "integrity": "sha512-tCBEZV2z2FNpIDl2vrhiWzIHzs4qOAuIDEO85eS02vZ3L1U3P56qpPL8GuGGAijDktAEaq2swMkO/Fmbo7YmfQ==", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minimatch": "^10.0.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/npm-pick-manifest": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/npm-pick-manifest/-/npm-pick-manifest-9.1.0.tgz", - "integrity": "sha512-nkc+3pIIhqHVQr085X9d2JzPzLyjzQS96zbruppqC9aZRm/x8xx6xhI98gHtsfELP2bE+loHq8ZaHFHhe+NauA==", + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/npm-pick-manifest/-/npm-pick-manifest-12.0.0.tgz", + "integrity": "sha512-8Fs3YLrnNOhrCdPNZy18MzNgVC58LTDAFzq1FdZO/p3BHeCC/coz+t4F5Pxabys8HJpyTUorMea26GkXsb4J/Q==", "inBundle": true, "license": "ISC", "dependencies": { - "npm-install-checks": "^6.0.0", - "npm-normalize-package-bin": "^3.0.0", - "npm-package-arg": "^11.0.0", + "npm-install-checks": "^9.0.0", + "npm-normalize-package-bin": "^6.0.0", + "npm-package-arg": "^14.0.0", "semver": "^7.3.5" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/npm-pick-manifest/node_modules/npm-normalize-package-bin": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-6.0.0.tgz", + "integrity": "sha512-tdt4aFn9QamlhdN3HV2D2ccpBwO5/fyjjbXUxYA6uBjyekMZcZvDq0aSj9t5Jo+tih6AYFnt/cuIRn9013e0Uw==", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/npm-profile": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/npm-profile/-/npm-profile-10.0.0.tgz", - "integrity": "sha512-DXnge3nHYnEnPxmVd/kPmgcXKXwVUqFihGnU+EJUiu5mIOs3awq6zEm0rRp3kSQNhFsoqdLu8L1TIfRyeBOCog==", + "version": "13.0.1", + "resolved": "https://registry.npmjs.org/npm-profile/-/npm-profile-13.0.1.tgz", + "integrity": "sha512-buFDWLwggBSiT5wsjhoSHNvGy+KHaBI5n8ilvSOBkrQUbEsyKYdCV6PloJGFsQ53ZqXCqhwds/8dbvyHQuH3IA==", "inBundle": true, "license": "ISC", "dependencies": { - "npm-registry-fetch": "^17.0.1", - "proc-log": "^4.0.0" + "npm-registry-fetch": "^20.0.0", + "proc-log": "^7.0.0" }, "engines": { - "node": ">=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/npm-registry-fetch": { - "version": "17.1.0", - "resolved": "https://registry.npmjs.org/npm-registry-fetch/-/npm-registry-fetch-17.1.0.tgz", - "integrity": "sha512-5+bKQRH0J1xG1uZ1zMNvxW0VEyoNWgJpY9UDuluPFLKDfJ9u2JmmjmTJV1srBGQOROfdBMiVvnH2Zvpbm+xkVA==", + "version": "20.0.1", + "resolved": "https://registry.npmjs.org/npm-registry-fetch/-/npm-registry-fetch-20.0.1.tgz", + "integrity": "sha512-vzc1svxw/kw1IRjFsLi6gaxe1Olqm88V0tIfu2u5raL0b1gChe6ZEXNkyUlKxUC7s/egt5NxZHkbY18tMKKLfQ==", "inBundle": true, "license": "ISC", "dependencies": { - "@npmcli/redact": "^2.0.0", + "@npmcli/redact": "^5.0.0", "jsonparse": "^1.3.1", - "make-fetch-happen": "^13.0.0", + "make-fetch-happen": "^16.0.0", "minipass": "^7.0.2", - "minipass-fetch": "^3.0.0", - "minizlib": "^2.1.2", - "npm-package-arg": "^11.0.0", - "proc-log": "^4.0.0" + "minipass-fetch": "^6.0.0", + "minizlib": "^3.0.1", + "npm-package-arg": "^14.0.0", + "proc-log": "^7.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, - "node_modules/npm-run-path": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz", - "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==", - "dev": true, + "node_modules/npm-registry-fetch/node_modules/minipass-fetch": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-6.0.0.tgz", + "integrity": "sha512-AWI8bKapGmgx/J0E6IGYSKj8TiHebZkmKWSs8raPSw8KXwgEAJ+Bw3+LSdXHR6T/RHKAWCOYk2MiLrYluaUU6w==", + "inBundle": true, "license": "MIT", "dependencies": { - "path-key": "^4.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + "minipass": "^7.0.3", + "minipass-sized": "^2.0.0", + "minizlib": "^3.0.1" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/npm-run-path/node_modules/path-key": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", - "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", - "dev": true, - "license": "MIT", "engines": { - "node": ">=12" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "optionalDependencies": { + "iconv-lite": "^0.7.2" } }, "node_modules/npm-user-validate": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/npm-user-validate/-/npm-user-validate-2.0.1.tgz", - "integrity": "sha512-d17PKaF2h8LSGFl5j4b1gHOJt1fgH7YUcCm1kNSJvaLWWKXlBsuUvx0bBEkr0qhsVA9XP5LtRZ83hdlhm2QkgA==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/npm-user-validate/-/npm-user-validate-5.0.0.tgz", + "integrity": "sha512-yZKlDPJOukQIRzXL+qYyuczXtnQTSF732zT6umGfy/8DxXEAdnv22eA/UpBsC0Fv9s4yfDYkK1pLnCPB0GxsqQ==", "inBundle": true, "license": "BSD-2-Clause", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/nth-check": { "version": "2.1.1", - "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", - "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", "dev": true, "license": "BSD-2-Clause", "dependencies": { @@ -9646,17 +10785,8 @@ "url": "https://github.com/fb55/nth-check?sponsor=1" } }, - "node_modules/nwsapi": { - "version": "2.2.10", - "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.10.tgz", - "integrity": "sha512-QK0sRs7MKv0tKe1+5uZIQk/C8XGza4DAnztJG8iD+TpJIORARrCxczA738awHrZoHeTjSSoHqao2teO0dC/gFQ==", - "dev": true, - "license": "MIT" - }, "node_modules/nyc": { "version": "15.1.0", - "resolved": "https://registry.npmjs.org/nyc/-/nyc-15.1.0.tgz", - "integrity": "sha512-jMW04n9SxKdKi1ZMGhvUTHBN0EICCRkHemEoE5jm6mTYcqcdas0ATzgUgejlQUHMvpnOZqGB5Xxsv9KxJW1j8A==", "dev": true, "license": "ISC", "dependencies": { @@ -9697,8 +10827,6 @@ }, "node_modules/nyc/node_modules/ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "license": "MIT", "dependencies": { @@ -9711,10 +10839,17 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/nyc/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, "node_modules/nyc/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", + "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", "dev": true, "license": "MIT", "dependencies": { @@ -9724,8 +10859,6 @@ }, "node_modules/nyc/node_modules/cliui": { "version": "6.0.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", - "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", "dev": true, "license": "ISC", "dependencies": { @@ -9736,8 +10869,6 @@ }, "node_modules/nyc/node_modules/find-up": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "license": "MIT", "dependencies": { @@ -9750,8 +10881,6 @@ }, "node_modules/nyc/node_modules/foreground-child": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-2.0.0.tgz", - "integrity": "sha512-dCIq9FpEcyQyXKCkyzmlPTFNgrCzPudOe+mhvJU5zAtlBnGVy2yKxtfsxK2tQBThwq225jcvBjpw1Gr40uzZCA==", "dev": true, "license": "ISC", "dependencies": { @@ -9764,9 +10893,6 @@ }, "node_modules/nyc/node_modules/glob": { "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", "dev": true, "license": "ISC", "dependencies": { @@ -9786,8 +10912,6 @@ }, "node_modules/nyc/node_modules/locate-path": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "license": "MIT", "dependencies": { @@ -9798,9 +10922,9 @@ } }, "node_modules/nyc/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "dependencies": { @@ -9812,8 +10936,6 @@ }, "node_modules/nyc/node_modules/p-limit": { "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, "license": "MIT", "dependencies": { @@ -9828,8 +10950,6 @@ }, "node_modules/nyc/node_modules/p-locate": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "license": "MIT", "dependencies": { @@ -9841,8 +10961,6 @@ }, "node_modules/nyc/node_modules/p-map": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-3.0.0.tgz", - "integrity": "sha512-d3qXVTF/s+W+CdJ5A29wywV2n8CQQYahlgz2bFiA+4eVNJbHJodPZ+/gXwPGh0bOqA+j8S+6+ckmvLGPk1QpxQ==", "dev": true, "license": "MIT", "dependencies": { @@ -9854,8 +10972,6 @@ }, "node_modules/nyc/node_modules/path-exists": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true, "license": "MIT", "engines": { @@ -9864,9 +10980,6 @@ }, "node_modules/nyc/node_modules/rimraf": { "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", "dependencies": { @@ -9881,15 +10994,11 @@ }, "node_modules/nyc/node_modules/signal-exit": { "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true, "license": "ISC" }, "node_modules/nyc/node_modules/wrap-ansi": { "version": "6.2.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", - "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", "dev": true, "license": "MIT", "dependencies": { @@ -9903,15 +11012,11 @@ }, "node_modules/nyc/node_modules/y18n": { "version": "4.0.3", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", - "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", "dev": true, "license": "ISC" }, "node_modules/nyc/node_modules/yargs": { "version": "15.4.1", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", - "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", "dev": true, "license": "MIT", "dependencies": { @@ -9933,8 +11038,6 @@ }, "node_modules/nyc/node_modules/yargs-parser": { "version": "18.1.3", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", - "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", "dev": true, "license": "ISC", "dependencies": { @@ -9946,20 +11049,19 @@ } }, "node_modules/object-inspect": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", - "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", + "version": "1.13.4", "dev": true, "license": "MIT", "peer": true, + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/object-keys": { "version": "1.1.1", - "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", - "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", "dev": true, "license": "MIT", "peer": true, @@ -9968,16 +11070,16 @@ } }, "node_modules/object.assign": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.5.tgz", - "integrity": "sha512-byy+U7gp+FVwmyzKPYhW2h5l3crpmGsxl7X2s8y43IgxvG4g3QZ6CffDtsNQy1WsmZpQbO+ybo0AlW7TY6DcBQ==", + "version": "4.1.7", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.5", + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", "define-properties": "^1.2.1", - "has-symbols": "^1.0.3", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", "object-keys": "^1.1.1" }, "engines": { @@ -9987,10 +11089,25 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/object.entries": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.9.tgz", + "integrity": "sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/object.fromentries": { "version": "2.0.8", - "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz", - "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==", "dev": true, "license": "MIT", "peer": true, @@ -10009,8 +11126,6 @@ }, "node_modules/object.groupby": { "version": "1.0.3", - "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz", - "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==", "dev": true, "license": "MIT", "peer": true, @@ -10024,14 +11139,13 @@ } }, "node_modules/object.values": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.0.tgz", - "integrity": "sha512-yBYjY9QX2hnRmZHAjG/f13MzmBzxzYgQhFrke06TTyKY5zSTEqkOeukBzIdVA3j3ulu8Qa3MbVFShV7T2RmGtQ==", + "version": "1.2.1", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0" }, @@ -10044,34 +11158,14 @@ }, "node_modules/once": { "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", "dev": true, "license": "ISC", "dependencies": { "wrappy": "1" } }, - "node_modules/onetime": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", - "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "mimic-fn": "^4.0.0" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/opener": { "version": "1.5.2", - "resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz", - "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==", "dev": true, "license": "(WTFPL OR MIT)", "bin": { @@ -10080,8 +11174,6 @@ }, "node_modules/optionator": { "version": "0.9.4", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", - "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", "dev": true, "license": "MIT", "peer": true, @@ -10097,66 +11189,51 @@ "node": ">= 0.8.0" } }, - "node_modules/own-or": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/own-or/-/own-or-1.0.0.tgz", - "integrity": "sha512-NfZr5+Tdf6MB8UI9GLvKRs4cXY8/yB0w3xtt84xFdWy8hkGjn+JFc60VhzS/hFRfbyxFcGYMTjnF4Me+RbbqrA==", - "dev": true, - "license": "ISC" - }, - "node_modules/own-or-env": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/own-or-env/-/own-or-env-1.0.2.tgz", - "integrity": "sha512-NQ7v0fliWtK7Lkb+WdFqe6ky9XAzYmlkXthQrBbzlYbmFKoAYbDDcwmOm6q8kOuwSRXW8bdL5ORksploUJmWgw==", + "node_modules/outvariant": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/outvariant/-/outvariant-1.4.3.tgz", + "integrity": "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA==", "dev": true, - "license": "ISC", - "dependencies": { - "own-or": "^1.0.0" - } + "license": "MIT" }, - "node_modules/p-limit": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-4.0.0.tgz", - "integrity": "sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==", + "node_modules/own-keys": { + "version": "1.0.1", "dev": true, "license": "MIT", + "peer": true, "dependencies": { - "yocto-queue": "^1.0.0" + "get-intrinsic": "^1.2.6", + "object-keys": "^1.1.1", + "safe-push-apply": "^1.0.0" }, "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + "node": ">= 0.4" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/p-locate": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-6.0.0.tgz", - "integrity": "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==", + "node_modules/own-or": { + "version": "1.0.0", "dev": true, - "license": "MIT", + "license": "ISC" + }, + "node_modules/own-or-env": { + "version": "1.0.2", + "dev": true, + "license": "ISC", "dependencies": { - "p-limit": "^4.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "own-or": "^1.0.0" } }, "node_modules/p-map": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", - "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==", - "inBundle": true, - "license": "MIT", - "dependencies": { - "aggregate-error": "^3.0.0" - }, + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.0.4.tgz", + "integrity": "sha512-tkAQEw8ysMzmkhgw8k+1U/iPhWNhykKnSk4Rd5zLoPJCuJaGRPo6YposrZgaxHKzDHdDWWZvE/Sk7hsL2X/CpQ==", + "inBundle": true, + "license": "MIT", "engines": { - "node": ">=10" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -10164,8 +11241,6 @@ }, "node_modules/p-try": { "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", "dev": true, "license": "MIT", "engines": { @@ -10174,8 +11249,6 @@ }, "node_modules/package-hash": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/package-hash/-/package-hash-4.0.0.tgz", - "integrity": "sha512-whdkPIooSu/bASggZ96BWVvZTRMOFxnyUG5PnTSGKoJE2gd5mbVNmR2Nj20QFzxYYgAXpoqC+AiXzl+UMRh7zQ==", "dev": true, "license": "ISC", "dependencies": { @@ -10189,48 +11262,118 @@ } }, "node_modules/package-json-from-dist": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.0.tgz", - "integrity": "sha512-dATvCeZN/8wQsGywez1mzHtTlP22H8OEfPrVMLNr4/eGa+ijtLn/6M5f0dY8UKNrC2O9UCU6SSoG3qRKnt7STw==", - "inBundle": true, + "version": "1.0.1", + "dev": true, "license": "BlueOak-1.0.0" }, "node_modules/pacote": { - "version": "18.0.6", - "resolved": "https://registry.npmjs.org/pacote/-/pacote-18.0.6.tgz", - "integrity": "sha512-+eK3G27SMwsB8kLIuj4h1FUhHtwiEUo21Tw8wNjmvdlpOEr613edv+8FUsTj/4F/VN5ywGE19X18N7CC2EJk6A==", + "version": "22.0.0", + "resolved": "https://registry.npmjs.org/pacote/-/pacote-22.0.0.tgz", + "integrity": "sha512-++VqeOZeL03uGM2MFLk96jGCSt1owBGkyFKoPr+trwNlZhCpjN2RrvwYxt8nTbs1wNMqSFYurq0TafVWkAIHig==", "inBundle": true, "license": "ISC", "dependencies": { - "@npmcli/git": "^5.0.0", - "@npmcli/installed-package-contents": "^2.0.1", - "@npmcli/package-json": "^5.1.0", - "@npmcli/promise-spawn": "^7.0.0", - "@npmcli/run-script": "^8.0.0", - "cacache": "^18.0.0", + "@gar/promise-retry": "^1.0.0", + "@npmcli/git": "^8.0.0", + "@npmcli/installed-package-contents": "^5.0.0", + "@npmcli/package-json": "^8.0.0", + "@npmcli/promise-spawn": "^10.0.0", + "@npmcli/run-script": "^11.0.0", + "cacache": "^21.0.1", "fs-minipass": "^3.0.0", "minipass": "^7.0.2", - "npm-package-arg": "^11.0.0", - "npm-packlist": "^8.0.0", - "npm-pick-manifest": "^9.0.0", - "npm-registry-fetch": "^17.0.0", - "proc-log": "^4.0.0", - "promise-retry": "^2.0.1", - "sigstore": "^2.2.0", - "ssri": "^10.0.0", - "tar": "^6.1.11" + "npm-package-arg": "^14.0.0", + "npm-packlist": "^11.2.0", + "npm-pick-manifest": "^12.0.0", + "npm-registry-fetch": "^20.0.1", + "proc-log": "^7.0.0", + "sigstore": "^5.0.0", + "ssri": "^14.0.0", + "tar": "^7.4.3" }, "bin": { "pacote": "bin/index.js" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/pacote/node_modules/@sigstore/bundle": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@sigstore/bundle/-/bundle-5.0.0.tgz", + "integrity": "sha512-wefjygudENbzbQMks1t5u34EP0fFoD0XvaEP7DOUP/sXKvogzEJYFw5E6pegGyp3onGWzVEYKVa3bNZWyTYX+A==", + "inBundle": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.5.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/pacote/node_modules/@sigstore/core": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sigstore/core/-/core-4.0.0.tgz", + "integrity": "sha512-uFGJpKiMCKXV+61jsxQ0ECfr0wjDP+8qnT6pgfsOXbIk0j/KPfBSp2Dks/YcNcT/S4e3P267JKPL6gAwygJRuw==", + "inBundle": true, + "license": "Apache-2.0", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/pacote/node_modules/@sigstore/sign": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@sigstore/sign/-/sign-5.0.0.tgz", + "integrity": "sha512-DSFivqz9/i5AkwZ5fq0YdjaJlc4o1WeS2Zffon0kqtChx0vy4W9NOjkEet9bF2vkzOufX72eVH8kZBIGtcBp1w==", + "inBundle": true, + "license": "Apache-2.0", + "dependencies": { + "@gar/promise-retry": "^1.0.2", + "@sigstore/bundle": "^5.0.0", + "@sigstore/core": "^4.0.0", + "@sigstore/protobuf-specs": "^0.5.0", + "make-fetch-happen": "^16.0.0", + "proc-log": "^7.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/pacote/node_modules/@sigstore/verify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sigstore/verify/-/verify-4.0.0.tgz", + "integrity": "sha512-yYQTYQkjkdp69M5f+XGOhX45RvgCwh0cz6r++hGRHi7G/NVPmIK7ISxY73fM5WVerIiYe/ZbVlMu47dDodBP6A==", + "inBundle": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^5.0.0", + "@sigstore/core": "^4.0.0", + "@sigstore/protobuf-specs": "^0.5.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/pacote/node_modules/sigstore": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/sigstore/-/sigstore-5.0.0.tgz", + "integrity": "sha512-hJqJfoG/e4qFQaauQL00c6J6FrHLBGKtkFvW3JbTSIEFOhLrSjdSM/gWd/yUOfYo/gsERehTXGC1VZWX+9X4Dg==", + "inBundle": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^5.0.0", + "@sigstore/core": "^4.0.0", + "@sigstore/protobuf-specs": "^0.5.0", + "@sigstore/sign": "^5.0.0", + "@sigstore/tuf": "^5.0.0", + "@sigstore/verify": "^4.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/parent-module": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", "dev": true, "license": "MIT", "dependencies": { @@ -10241,38 +11384,32 @@ } }, "node_modules/parse-conflict-json": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/parse-conflict-json/-/parse-conflict-json-3.0.1.tgz", - "integrity": "sha512-01TvEktc68vwbJOtWZluyWeVGWjP+bZwXtPDMQVbBKzbJ/vZBif0L69KH1+cHv1SZ6e0FKLvjyHe8mqsIqYOmw==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/parse-conflict-json/-/parse-conflict-json-6.0.0.tgz", + "integrity": "sha512-JIdsITvN0yVRpYxiip9DpCduYi75AryIDSCf6ez/Yul6PV46L0B/8SxSvLiMmWiUZKopLrD1BZgexxCfufoT9w==", "inBundle": true, "license": "ISC", "dependencies": { - "json-parse-even-better-errors": "^3.0.0", + "json-parse-even-better-errors": "^6.0.0", "just-diff": "^6.0.0", "just-diff-apply": "^5.2.0" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/parse-diff": { "version": "0.11.1", - "resolved": "https://registry.npmjs.org/parse-diff/-/parse-diff-0.11.1.tgz", - "integrity": "sha512-Oq4j8LAOPOcssanQkIjxosjATBIEJhCxMCxPhMu+Ci4wdNmAEdx0O+a7gzbR2PyKXgKPvRLIN5g224+dJAsKHA==", "dev": true, "license": "MIT" }, "node_modules/parse-github-repo-url": { "version": "1.4.1", - "resolved": "https://registry.npmjs.org/parse-github-repo-url/-/parse-github-repo-url-1.4.1.tgz", - "integrity": "sha512-bSWyzBKqcSL4RrncTpGsEKoJ7H8a4L3++ifTAbTFeMHyq2wRV+42DGmQcHIrJIvdcacjIOxEuKH/w4tthF17gg==", "dev": true, "license": "MIT" }, "node_modules/parse-json": { "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", "dev": true, "license": "MIT", "dependencies": { @@ -10290,38 +11427,11 @@ }, "node_modules/parse-json/node_modules/json-parse-even-better-errors": { "version": "2.3.1", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", "dev": true, "license": "MIT" }, - "node_modules/parse5": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz", - "integrity": "sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==", - "dev": true, - "license": "MIT", - "dependencies": { - "entities": "^4.4.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, - "node_modules/path-exists": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-5.0.0.tgz", - "integrity": "sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - } - }, "node_modules/path-is-absolute": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", "dev": true, "license": "MIT", "engines": { @@ -10330,9 +11440,7 @@ }, "node_modules/path-key": { "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "inBundle": true, + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -10340,39 +11448,35 @@ }, "node_modules/path-parse": { "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", "dev": true, "license": "MIT" }, "node_modules/path-scurry": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", - "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", "inBundle": true, "license": "BlueOak-1.0.0", "dependencies": { - "lru-cache": "^10.2.0", - "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" }, "engines": { - "node": ">=16 || 14 >=14.18" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/picocolors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.1.tgz", - "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==", + "version": "1.1.1", "dev": true, "license": "ISC" }, "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", "dev": true, "license": "MIT", "engines": { @@ -10384,8 +11488,6 @@ }, "node_modules/pkg-dir": { "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", "dev": true, "license": "MIT", "dependencies": { @@ -10397,8 +11499,6 @@ }, "node_modules/pkg-dir/node_modules/find-up": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "license": "MIT", "dependencies": { @@ -10411,8 +11511,6 @@ }, "node_modules/pkg-dir/node_modules/locate-path": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "license": "MIT", "dependencies": { @@ -10424,8 +11522,6 @@ }, "node_modules/pkg-dir/node_modules/p-limit": { "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, "license": "MIT", "dependencies": { @@ -10440,8 +11536,6 @@ }, "node_modules/pkg-dir/node_modules/p-locate": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "license": "MIT", "dependencies": { @@ -10453,8 +11547,6 @@ }, "node_modules/pkg-dir/node_modules/path-exists": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true, "license": "MIT", "engines": { @@ -10463,15 +11555,11 @@ }, "node_modules/platform": { "version": "1.3.6", - "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", - "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", "dev": true, "license": "MIT" }, "node_modules/possible-typed-array-names": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz", - "integrity": "sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==", + "version": "1.1.0", "dev": true, "license": "MIT", "peer": true, @@ -10480,9 +11568,9 @@ } }, "node_modules/postcss-selector-parser": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.0.tgz", - "integrity": "sha512-UMz42UD0UY0EApS0ZL9o1XnLhSTtvvvLe5Dc2H2O56fvRZi+KulDyf5ctDhhtYJBGKStV2FL1fy6253cmLgqVQ==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -10494,8 +11582,6 @@ }, "node_modules/prelude-ls": { "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true, "license": "MIT", "peer": true, @@ -10504,19 +11590,17 @@ } }, "node_modules/proc-log": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-4.2.0.tgz", - "integrity": "sha512-g8+OnU/L2v+wyiVK+D5fA34J7EH8jZ8DDlvwhRCMxmMj7UCBvxiO1mGeN+36JXIKF4zevU4kRBd8lVgG9vLelA==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-7.0.0.tgz", + "integrity": "sha512-FYgfaA69XZ93zaXLoMNQ+ViDXGGBgR8aLh03txzcFhV+9xOXx7+8DLCULrKKpR9+GsH9ZfHm82aSUPpozX0Ztg==", "inBundle": true, "license": "ISC", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/process-on-spawn": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/process-on-spawn/-/process-on-spawn-1.0.0.tgz", - "integrity": "sha512-1WsPDsUSMmZH5LeMLegqkPDrsGgsWwk1Exipy2hvB0o/F0ASzbpIctSCcZIK1ykJvtTJULEH+20WOFjMvGnCTg==", + "version": "1.1.0", "dev": true, "license": "MIT", "dependencies": { @@ -10527,70 +11611,43 @@ } }, "node_modules/proggy": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/proggy/-/proggy-2.0.0.tgz", - "integrity": "sha512-69agxLtnI8xBs9gUGqEnK26UfiexpHy+KUpBQWabiytQjnn5wFY8rklAi7GRfABIuPNnQ/ik48+LGLkYYJcy4A==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/proggy/-/proggy-4.0.0.tgz", + "integrity": "sha512-MbA4R+WQT76ZBm/5JUpV9yqcJt92175+Y0Bodg3HgiXzrmKu7Ggq+bpn6y6wHH+gN9NcyKn3yg1+d47VaKwNAQ==", "license": "ISC", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/promise-all-reject-late": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/promise-all-reject-late/-/promise-all-reject-late-1.0.1.tgz", - "integrity": "sha512-vuf0Lf0lOxyQREH7GDIOUMLS7kz+gs8i6B+Yi8dC68a2sychGrHTJYghMBD6k7eUcH0H5P73EckCA48xijWqXw==", "license": "ISC", "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/promise-call-limit": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/promise-call-limit/-/promise-call-limit-3.0.1.tgz", - "integrity": "sha512-utl+0x8gIDasV5X+PI5qWEPqH6fJS0pFtQ/4gZ95xfEFb/89dmh+/b895TbFDBLiafBvxD/PGTKfvxl4kH/pQg==", + "version": "3.0.2", "license": "ISC", "funding": { "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/promise-inflight": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", - "integrity": "sha512-6zWPyEOFaQBJYcGMHBKTKJ3u6TBsnMFOIZSa6ce1e/ZrrsOlnHRHbabMjLiBYKp+n44X9eUI6VUPaukCXHuG4g==", - "inBundle": true, - "license": "ISC" - }, - "node_modules/promise-retry": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz", - "integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==", - "inBundle": true, - "license": "MIT", - "dependencies": { - "err-code": "^2.0.2", - "retry": "^0.12.0" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/promzard": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/promzard/-/promzard-1.0.2.tgz", - "integrity": "sha512-2FPputGL+mP3jJ3UZg/Dl9YOkovB7DX0oOr+ck5QbZ5MtORtds8k/BZdn+02peDLI8/YWbmzx34k5fA+fHvCVQ==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/promzard/-/promzard-4.0.0.tgz", + "integrity": "sha512-zqf38XGznB+ECFHQPGt0RNQCh0YF+r5iac0EZloSQlEWDxt0vCS39PEtUShBJOZU0tcJ+USPvmnyGo+3CEFwcQ==", "inBundle": true, "license": "ISC", "dependencies": { - "read": "^3.0.1" + "read": "^6.0.0" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/propagate": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/propagate/-/propagate-2.0.1.tgz", - "integrity": "sha512-vGrhOavPSTz4QVNuBNdcNXePNdNMaO1xj9yBeH1ScQPjk/rhg9sSlCXPhMkFuaNNW/syTvYqsnbIJxMBfRbbag==", "dev": true, "license": "MIT", "engines": { @@ -10598,9 +11655,7 @@ } }, "node_modules/property-information": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/property-information/-/property-information-6.5.0.tgz", - "integrity": "sha512-PgTgs/BlvHxOu8QuEN7wi5A0OmXaBcHpmCSTehcs6Uuu9IkDIEo13Hy7n898RHfrQ49vKCoGeWZSaAK01nwVig==", + "version": "7.1.0", "dev": true, "license": "MIT", "funding": { @@ -10609,9 +11664,7 @@ } }, "node_modules/proxy": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/proxy/-/proxy-2.1.1.tgz", - "integrity": "sha512-nLgd7zdUAOpB3ZO/xCkU8gy74UER7P0aihU8DkUsDS5ZoFwVCX7u8dy+cv5tVK8UaB/yminU1GiLWE26TKPYpg==", + "version": "2.2.0", "dev": true, "license": "MIT", "dependencies": { @@ -10619,21 +11672,33 @@ "basic-auth-parser": "0.0.2-1", "debug": "^4.3.4" }, + "bin": { + "proxy": "dist/bin/proxy.js" + }, "engines": { "node": ">= 14" } }, - "node_modules/psl": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", - "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==", - "dev": true, - "license": "MIT" + "node_modules/proxy-agent-negotiate": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-agent-negotiate/-/proxy-agent-negotiate-1.1.0.tgz", + "integrity": "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "kerberos": "^2.0.0" + }, + "peerDependenciesMeta": { + "kerberos": { + "optional": true + } + } }, "node_modules/punycode": { "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", "dev": true, "license": "MIT", "engines": { @@ -10642,24 +11707,13 @@ }, "node_modules/qrcode-terminal": { "version": "0.12.0", - "resolved": "https://registry.npmjs.org/qrcode-terminal/-/qrcode-terminal-0.12.0.tgz", - "integrity": "sha512-EXtzRZmC+YGmGlDFbXKxQiMZNwCLEO6BANKXG4iCtSIM0yqc/pappSx3RIKr4r0uh5JsBckOXeKrB3Iz7mdQpQ==", "inBundle": true, "bin": { "qrcode-terminal": "bin/qrcode-terminal.js" } }, - "node_modules/querystringify": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", - "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", - "dev": true, - "license": "MIT" - }, "node_modules/queue-microtask": { "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", "dev": true, "funding": [ { @@ -10678,17 +11732,8 @@ "license": "MIT", "peer": true }, - "node_modules/queue-tick": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz", - "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==", - "dev": true, - "license": "MIT" - }, "node_modules/quick-lru": { "version": "4.0.1", - "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-4.0.1.tgz", - "integrity": "sha512-ARhCpm70fzdcvNQfPoy49IaanKkTlRWF2JMzqhcJbhSFRZv7nPTvZJdcY7301IPmvW+/p0RgIWnQDLJxifsQ7g==", "dev": true, "license": "MIT", "engines": { @@ -10697,15 +11742,11 @@ }, "node_modules/railroad-diagrams": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/railroad-diagrams/-/railroad-diagrams-1.0.0.tgz", - "integrity": "sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A==", "dev": true, "license": "CC0-1.0" }, "node_modules/randexp": { "version": "0.4.6", - "resolved": "https://registry.npmjs.org/randexp/-/randexp-0.4.6.tgz", - "integrity": "sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==", "dev": true, "license": "MIT", "dependencies": { @@ -10717,45 +11758,30 @@ } }, "node_modules/read": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/read/-/read-3.0.1.tgz", - "integrity": "sha512-SLBrDU/Srs/9EoWhU5GdbAoxG1GzpQHo/6qiGItaoLJ1thmYpcNIM1qISEUvyHBzfGlWIyd6p2DNi1oV1VmAuw==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/read/-/read-6.0.0.tgz", + "integrity": "sha512-Tg/LaEke7h9SDbp0xJJj53oa4s1VPPySVnxQF9nUS9DgA25M/ZCLk7RVF1kHjytC87XbkgQKmQ/79+DQgEIqLA==", "inBundle": true, "license": "ISC", "dependencies": { - "mute-stream": "^1.0.0" + "mute-stream": "^4.0.0" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/read-cmd-shim": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/read-cmd-shim/-/read-cmd-shim-4.0.0.tgz", - "integrity": "sha512-yILWifhaSEEytfXI76kB9xEEiG1AiozaCJZ83A87ytjRiN+jVibXjedjCRNjoZviinhG+4UkalO3mWTd8u5O0Q==", - "license": "ISC", - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/read-package-json-fast": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/read-package-json-fast/-/read-package-json-fast-3.0.2.tgz", - "integrity": "sha512-0J+Msgym3vrLOUB3hzQCuZHII0xkNGCtz/HJH9xZshwv9DbDwkw1KaE3gx/e2J5rpEY5rtOy6cyhKOPrkP7FZw==", - "inBundle": true, + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/read-cmd-shim/-/read-cmd-shim-6.0.0.tgz", + "integrity": "sha512-1zM5HuOfagXCBWMN83fuFI/x+T/UhZ7k+KIzhrHXcQoeX5+7gmaDYjELQHmmzIodumBHeByBJT4QYS7ufAgs7A==", + "dev": true, "license": "ISC", - "dependencies": { - "json-parse-even-better-errors": "^3.0.0", - "npm-normalize-package-bin": "^3.0.0" - }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/read-pkg": { "version": "5.2.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-5.2.0.tgz", - "integrity": "sha512-Ug69mNOpfvKDAc2Q8DRpMjjzdtrnv9HcSMX+4VsZxD1aZ6ZzrIE7rlzXBtWTyhULSMKg076AW6WR5iZpD0JiOg==", "dev": true, "license": "MIT", "dependencies": { @@ -10770,8 +11796,6 @@ }, "node_modules/read-pkg-up": { "version": "7.0.1", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-7.0.1.tgz", - "integrity": "sha512-zK0TB7Xd6JpCLmlLmufqykGE+/TlOePD6qKClNW7hHDKFh/J7/7gCWGR7joEQEW1bKq3a3yUZSObOoWLFQ4ohg==", "dev": true, "license": "MIT", "dependencies": { @@ -10788,8 +11812,6 @@ }, "node_modules/read-pkg-up/node_modules/find-up": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "license": "MIT", "dependencies": { @@ -10802,8 +11824,6 @@ }, "node_modules/read-pkg-up/node_modules/locate-path": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "license": "MIT", "dependencies": { @@ -10815,8 +11835,6 @@ }, "node_modules/read-pkg-up/node_modules/p-limit": { "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, "license": "MIT", "dependencies": { @@ -10831,8 +11849,6 @@ }, "node_modules/read-pkg-up/node_modules/p-locate": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "license": "MIT", "dependencies": { @@ -10844,8 +11860,6 @@ }, "node_modules/read-pkg-up/node_modules/path-exists": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true, "license": "MIT", "engines": { @@ -10854,8 +11868,6 @@ }, "node_modules/read-pkg-up/node_modules/type-fest": { "version": "0.8.1", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", - "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", "dev": true, "license": "(MIT OR CC0-1.0)", "engines": { @@ -10864,15 +11876,11 @@ }, "node_modules/read-pkg/node_modules/hosted-git-info": { "version": "2.8.9", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", - "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", "dev": true, "license": "ISC" }, "node_modules/read-pkg/node_modules/normalize-package-data": { "version": "2.5.0", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", - "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", "dev": true, "license": "BSD-2-Clause", "dependencies": { @@ -10884,8 +11892,6 @@ }, "node_modules/read-pkg/node_modules/semver": { "version": "5.7.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", - "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", "dev": true, "license": "ISC", "bin": { @@ -10894,8 +11900,6 @@ }, "node_modules/read-pkg/node_modules/type-fest": { "version": "0.6.0", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.6.0.tgz", - "integrity": "sha512-q+MB8nYR1KDLrgr4G5yemftpMC7/QLqVndBmEEdqzmNj5dcFOO4Oo8qlwZE3ULT3+Zim1F8Kq4cBnikNhlCMlg==", "dev": true, "license": "(MIT OR CC0-1.0)", "engines": { @@ -10904,8 +11908,6 @@ }, "node_modules/readdirp": { "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", "dev": true, "license": "MIT", "dependencies": { @@ -10917,8 +11919,6 @@ }, "node_modules/redent": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", - "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", "dev": true, "license": "MIT", "dependencies": { @@ -10929,18 +11929,40 @@ "node": ">=8" } }, + "node_modules/reflect.getprototypeof": { + "version": "1.0.10", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.7", + "get-proto": "^1.0.1", + "which-builtin-type": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/regexp.prototype.flags": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.2.tgz", - "integrity": "sha512-NcDiDkTLuPR+++OCKB0nWafEmhg/Da8aUPLPMQbK+bxKKCm1/S5he+AqYa4PlMCVBalb4/yxIRub6qkEx5yJbw==", + "version": "1.5.4", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.6", + "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-errors": "^1.3.0", - "set-function-name": "^2.0.1" + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "set-function-name": "^2.0.2" }, "engines": { "node": ">= 0.4" @@ -10951,8 +11973,6 @@ }, "node_modules/regexpp": { "version": "3.2.0", - "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", - "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", "dev": true, "license": "MIT", "peer": true, @@ -10964,15 +11984,13 @@ } }, "node_modules/rehype-stringify": { - "version": "9.0.4", - "resolved": "https://registry.npmjs.org/rehype-stringify/-/rehype-stringify-9.0.4.tgz", - "integrity": "sha512-Uk5xu1YKdqobe5XpSskwPvo1XeHUUucWEQSl8hTrXt5selvca1e8K1EZ37E6YoZ4BT8BCqCdVfQW7OfHfthtVQ==", + "version": "10.0.1", "dev": true, "license": "MIT", "dependencies": { - "@types/hast": "^2.0.0", - "hast-util-to-html": "^8.0.0", - "unified": "^10.0.0" + "@types/hast": "^3.0.0", + "hast-util-to-html": "^9.0.0", + "unified": "^11.0.0" }, "funding": { "type": "opencollective", @@ -10980,33 +11998,33 @@ } }, "node_modules/release-please": { - "version": "16.10.2", - "resolved": "https://registry.npmjs.org/release-please/-/release-please-16.10.2.tgz", - "integrity": "sha512-OX6N7xx3F3ZCd1+B7yq2Ix6KfuA7zXxMP04q3xYic3Hb0X/dOzy8p50xnrxzFpIVJridp1Dn74dUgzjImK6Mdg==", + "version": "17.6.1", + "resolved": "https://registry.npmjs.org/release-please/-/release-please-17.6.1.tgz", + "integrity": "sha512-4KtlVBnvccYZWepgFuRO5qVLc3Y0NicyBM4nqSt+sTKRWvagEJbPXUgErcWLJLW63KHzDphdwZQbbRmyqt2eIQ==", "dev": true, "license": "Apache-2.0", "dependencies": { "@conventional-commits/parser": "^0.4.1", - "@google-automations/git-file-utils": "^2.0.0", + "@google-automations/git-file-utils": "^3.0.0", "@iarna/toml": "^3.0.0", - "@octokit/graphql": "^5.0.0", - "@octokit/request": "^6.0.0", - "@octokit/request-error": "^3.0.0", - "@octokit/rest": "^19.0.0", + "@octokit/graphql": "^7.1.0", + "@octokit/request": "^8.3.1", + "@octokit/request-error": "^5.1.0", + "@octokit/rest": "^20.1.1", "@types/npm-package-arg": "^6.1.0", "@xmldom/xmldom": "^0.8.4", "chalk": "^4.0.0", - "code-suggester": "^4.2.0", + "code-suggester": "^5.0.0", "conventional-changelog-conventionalcommits": "^6.0.0", "conventional-changelog-writer": "^6.0.0", "conventional-commits-filter": "^3.0.0", "detect-indent": "^6.1.0", - "diff": "^5.0.0", + "diff": "^8.0.3", "figures": "^3.0.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.0", "js-yaml": "^4.0.0", - "jsonpath": "^1.1.1", + "jsonpath-plus": "^10.0.0", "node-html-parser": "^6.0.0", "parse-github-repo-url": "^1.4.1", "semver": "^7.5.3", @@ -11022,13 +12040,154 @@ "release-please": "build/src/bin/release-please.js" }, "engines": { - "node": ">=18.0.0" + "node": ">=20.0.0" + } + }, + "node_modules/release-please/node_modules/@octokit/auth-token": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 18" + } + }, + "node_modules/release-please/node_modules/@octokit/core": { + "version": "5.2.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/auth-token": "^4.0.0", + "@octokit/graphql": "^7.1.0", + "@octokit/request": "^8.4.1", + "@octokit/request-error": "^5.1.1", + "@octokit/types": "^13.0.0", + "before-after-hook": "^2.2.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/release-please/node_modules/@octokit/endpoint": { + "version": "9.0.6", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.1.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/release-please/node_modules/@octokit/graphql": { + "version": "7.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/request": "^8.4.1", + "@octokit/types": "^13.0.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/release-please/node_modules/@octokit/openapi-types": { + "version": "24.2.0", + "dev": true, + "license": "MIT" + }, + "node_modules/release-please/node_modules/@octokit/plugin-paginate-rest": { + "version": "11.4.4-cjs.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.7.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@octokit/core": "5" + } + }, + "node_modules/release-please/node_modules/@octokit/plugin-request-log": { + "version": "4.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@octokit/core": "5" + } + }, + "node_modules/release-please/node_modules/@octokit/plugin-rest-endpoint-methods": { + "version": "13.3.2-cjs.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.8.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@octokit/core": "^5" + } + }, + "node_modules/release-please/node_modules/@octokit/request": { + "version": "8.4.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/endpoint": "^9.0.6", + "@octokit/request-error": "^5.1.1", + "@octokit/types": "^13.1.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/release-please/node_modules/@octokit/request-error": { + "version": "5.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.1.0", + "deprecation": "^2.0.0", + "once": "^1.4.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/release-please/node_modules/@octokit/rest": { + "version": "20.1.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/core": "^5.0.2", + "@octokit/plugin-paginate-rest": "11.4.4-cjs.2", + "@octokit/plugin-request-log": "^4.0.0", + "@octokit/plugin-rest-endpoint-methods": "13.3.2-cjs.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/release-please/node_modules/@octokit/types": { + "version": "13.10.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^24.2.0" } }, "node_modules/release-please/node_modules/ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "license": "MIT", "dependencies": { @@ -11041,10 +12200,13 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/release-please/node_modules/before-after-hook": { + "version": "2.2.3", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/release-please/node_modules/chalk": { "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, "license": "MIT", "dependencies": { @@ -11060,8 +12222,6 @@ }, "node_modules/release-please/node_modules/conventional-changelog-conventionalcommits": { "version": "6.1.0", - "resolved": "https://registry.npmjs.org/conventional-changelog-conventionalcommits/-/conventional-changelog-conventionalcommits-6.1.0.tgz", - "integrity": "sha512-3cS3GEtR78zTfMzk0AizXKKIdN4OvSh7ibNz6/DPbhWWQu7LqE/8+/GqSodV+sywUR2gpJAdP/1JFf4XtN7Zpw==", "dev": true, "license": "ISC", "dependencies": { @@ -11071,20 +12231,8 @@ "node": ">=14" } }, - "node_modules/release-please/node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/release-please/node_modules/supports-color": { "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "license": "MIT", "dependencies": { @@ -11096,8 +12244,6 @@ }, "node_modules/release-please/node_modules/type-fest": { "version": "3.13.1", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-3.13.1.tgz", - "integrity": "sha512-tLq3bSNx+xSpwvAJnzrK0Ep5CLNWjvFTOp71URMaAEWBfRb9nnJiBoUe0tF8bI4ZFO3omgBR6NvnbzVUT3Ly4g==", "dev": true, "license": "(MIT OR CC0-1.0)", "engines": { @@ -11109,8 +12255,6 @@ }, "node_modules/release-please/node_modules/typescript": { "version": "4.9.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", - "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", "dev": true, "license": "Apache-2.0", "bin": { @@ -11121,10 +12265,13 @@ "node": ">=4.2.0" } }, + "node_modules/release-please/node_modules/universal-user-agent": { + "version": "6.0.1", + "dev": true, + "license": "ISC" + }, "node_modules/release-zalgo": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/release-zalgo/-/release-zalgo-1.0.0.tgz", - "integrity": "sha512-gUAyHVHPPC5wdqX/LG4LWtRYtgjxyX78oanFNTMMyFEfOqdC54s3eE82imuWKbOeqYht2CrNf64Qb8vgmmtZGA==", "dev": true, "license": "ISC", "dependencies": { @@ -11135,16 +12282,14 @@ } }, "node_modules/remark": { - "version": "14.0.3", - "resolved": "https://registry.npmjs.org/remark/-/remark-14.0.3.tgz", - "integrity": "sha512-bfmJW1dmR2LvaMJuAnE88pZP9DktIFYXazkTfOIKZzi3Knk9lT0roItIA24ydOucI3bV/g/tXBA6hzqq3FV9Ew==", + "version": "15.0.1", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", - "remark-parse": "^10.0.0", - "remark-stringify": "^10.0.0", - "unified": "^10.0.0" + "@types/mdast": "^4.0.0", + "remark-parse": "^11.0.0", + "remark-stringify": "^11.0.0", + "unified": "^11.0.0" }, "funding": { "type": "opencollective", @@ -11152,16 +12297,16 @@ } }, "node_modules/remark-gfm": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-3.0.1.tgz", - "integrity": "sha512-lEFDoi2PICJyNrACFOfDD3JlLkuSbOa5Wd8EPt06HUdptv8Gn0bxYTdbU/XXQ3swAPkEaGxxPN9cbnMHvVu1Ig==", + "version": "4.0.1", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", - "mdast-util-gfm": "^2.0.0", - "micromark-extension-gfm": "^2.0.0", - "unified": "^10.0.0" + "@types/mdast": "^4.0.0", + "mdast-util-gfm": "^3.0.0", + "micromark-extension-gfm": "^3.0.0", + "remark-parse": "^11.0.0", + "remark-stringify": "^11.0.0", + "unified": "^11.0.0" }, "funding": { "type": "opencollective", @@ -11169,17 +12314,16 @@ } }, "node_modules/remark-github": { - "version": "11.2.4", - "resolved": "https://registry.npmjs.org/remark-github/-/remark-github-11.2.4.tgz", - "integrity": "sha512-GJjWFpwqdrHHhPWqMbb8+lqFLiHQ9pCzUmXmRrhMFXGpYov5n2ljsZzuWgXlfzArfQYkiKIZczA2I8IHYMHqCA==", + "version": "12.0.0", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", - "mdast-util-find-and-replace": "^2.0.0", - "mdast-util-to-string": "^3.0.0", - "unified": "^10.0.0", - "unist-util-visit": "^4.0.0" + "@types/mdast": "^4.0.0", + "mdast-util-find-and-replace": "^3.0.0", + "mdast-util-to-string": "^4.0.0", + "to-vfile": "^8.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" }, "funding": { "type": "opencollective", @@ -11187,15 +12331,15 @@ } }, "node_modules/remark-github/node_modules/unist-util-visit": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-4.1.2.tgz", - "integrity": "sha512-MSd8OUGISqHdVvfY9TPhyK2VdUrPgxkUtWSuMHF6XAAFuL4LokseigBnZtPnJMu+FbynTkFNnFlyjxpVKujMRg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz", + "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0", - "unist-util-visit-parents": "^5.1.1" + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" }, "funding": { "type": "opencollective", @@ -11203,14 +12347,14 @@ } }, "node_modules/remark-github/node_modules/unist-util-visit-parents": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-5.1.3.tgz", - "integrity": "sha512-x6+y8g7wWMyQhL1iZfhIPhDAs7Xwbn9nRosDXl7qoPTSCy0yNxnKc+hWokFifWQIDGi154rdUqKvbCa4+1kLhg==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", + "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0" + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" }, "funding": { "type": "opencollective", @@ -11218,21 +12362,19 @@ } }, "node_modules/remark-man": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/remark-man/-/remark-man-8.0.1.tgz", - "integrity": "sha512-F/BbNaEF/QiZXoMiC43/qb8kAgGBKIS3yA+Br4CObgyoD+9Bioq1v+LmrLVbkwy9BErircQQ4J8yR2vFD34fBA==", + "version": "9.0.0", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", - "@types/unist": "^2.0.0", - "github-slugger": "^1.0.0", + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "github-slugger": "^2.0.0", "groff-escape": "^2.0.0", - "mdast-util-definitions": "^5.0.0", - "mdast-util-to-string": "^3.0.0", + "mdast-util-definitions": "^6.0.0", + "mdast-util-to-string": "^4.0.0", "months": "^2.0.0", - "unified": "^10.0.0", - "unist-util-visit": "^4.0.0", + "unified": "^11.0.0", + "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" }, "funding": { @@ -11240,16 +12382,30 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/remark-man/node_modules/mdast-util-definitions": { + "version": "6.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "unist-util-visit": "^5.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/remark-man/node_modules/unist-util-visit": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-4.1.2.tgz", - "integrity": "sha512-MSd8OUGISqHdVvfY9TPhyK2VdUrPgxkUtWSuMHF6XAAFuL4LokseigBnZtPnJMu+FbynTkFNnFlyjxpVKujMRg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz", + "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0", - "unist-util-visit-parents": "^5.1.1" + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" }, "funding": { "type": "opencollective", @@ -11257,14 +12413,14 @@ } }, "node_modules/remark-man/node_modules/unist-util-visit-parents": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-5.1.3.tgz", - "integrity": "sha512-x6+y8g7wWMyQhL1iZfhIPhDAs7Xwbn9nRosDXl7qoPTSCy0yNxnKc+hWokFifWQIDGi154rdUqKvbCa4+1kLhg==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", + "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0" + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" }, "funding": { "type": "opencollective", @@ -11272,15 +12428,14 @@ } }, "node_modules/remark-parse": { - "version": "10.0.2", - "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-10.0.2.tgz", - "integrity": "sha512-3ydxgHa/ZQzG8LvC7jTXccARYDcRld3VfcgIIFs7bI6vbRSxJJmzgLEIIoYKyrfhaY+ujuWaf/PJiMZXoiCXgw==", + "version": "11.0.0", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", - "mdast-util-from-markdown": "^1.0.0", - "unified": "^10.0.0" + "@types/mdast": "^4.0.0", + "mdast-util-from-markdown": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unified": "^11.0.0" }, "funding": { "type": "opencollective", @@ -11288,16 +12443,15 @@ } }, "node_modules/remark-rehype": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-10.1.0.tgz", - "integrity": "sha512-EFmR5zppdBp0WQeDVZ/b66CWJipB2q2VLNFMabzDSGR66Z2fQii83G5gTBbgGEnEEA0QRussvrFHxk1HWGJskw==", + "version": "11.1.2", "dev": true, "license": "MIT", "dependencies": { - "@types/hast": "^2.0.0", - "@types/mdast": "^3.0.0", - "mdast-util-to-hast": "^12.1.0", - "unified": "^10.0.0" + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "mdast-util-to-hast": "^13.0.0", + "unified": "^11.0.0", + "vfile": "^6.0.0" }, "funding": { "type": "opencollective", @@ -11305,15 +12459,13 @@ } }, "node_modules/remark-stringify": { - "version": "10.0.3", - "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-10.0.3.tgz", - "integrity": "sha512-koyOzCMYoUHudypbj4XpnAKFbkddRMYZHwghnxd7ue5210WzGw6kOBwauJTRUMq16jsovXx8dYNvSSWP89kZ3A==", + "version": "11.0.0", "dev": true, "license": "MIT", "dependencies": { - "@types/mdast": "^3.0.0", - "mdast-util-to-markdown": "^1.0.0", - "unified": "^10.0.0" + "@types/mdast": "^4.0.0", + "mdast-util-to-markdown": "^2.0.0", + "unified": "^11.0.0" }, "funding": { "type": "opencollective", @@ -11322,8 +12474,6 @@ }, "node_modules/require-directory": { "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", "dev": true, "license": "MIT", "engines": { @@ -11332,8 +12482,6 @@ }, "node_modules/require-from-string": { "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", "dev": true, "license": "MIT", "engines": { @@ -11342,8 +12490,6 @@ }, "node_modules/require-inject": { "version": "1.4.4", - "resolved": "https://registry.npmjs.org/require-inject/-/require-inject-1.4.4.tgz", - "integrity": "sha512-5Y5ctRN84+I4iOZO61gm+48tgP/6Hcd3VZydkaEM3MCuOvnHRsTJYQBOc01faI/Z9at5nsCAJVHhlfPA6Pc0Og==", "dev": true, "license": "ISC", "dependencies": { @@ -11352,40 +12498,33 @@ }, "node_modules/require-main-filename": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "dev": true, "license": "ISC" }, - "node_modules/requires-port": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", - "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", - "dev": true, - "license": "MIT" - }, "node_modules/resolve": { - "version": "1.22.8", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", - "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "version": "1.22.12", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", + "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", "dev": true, "license": "MIT", "dependencies": { - "is-core-module": "^2.13.0", + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" }, + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/resolve-from": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", "dev": true, "license": "MIT", "engines": { @@ -11394,8 +12533,6 @@ }, "node_modules/ret": { "version": "0.1.15", - "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", - "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", "dev": true, "license": "MIT", "engines": { @@ -11403,19 +12540,17 @@ } }, "node_modules/retry": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", - "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==", - "inBundle": true, + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "dev": true, "license": "MIT", "engines": { "node": ">= 4" } }, "node_modules/reusify": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", - "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "version": "1.1.0", "dev": true, "license": "MIT", "peer": true, @@ -11425,35 +12560,34 @@ } }, "node_modules/rimraf": { - "version": "5.0.7", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-5.0.7.tgz", - "integrity": "sha512-nV6YcJo5wbLW77m+8KjH8aB/7/rxQy9SZ0HY5shnwULfS+9nmTtVXAJET5NdZmCzA4fPI/Hm1wo/Po/4mopOdg==", + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.3.tgz", + "integrity": "sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==", "dev": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "dependencies": { - "glob": "^10.3.7" + "glob": "^13.0.3", + "package-json-from-dist": "^1.0.1" }, "bin": { "rimraf": "dist/esm/bin.mjs" }, "engines": { - "node": ">=14.18" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/rrweb-cssom": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.7.1.tgz", - "integrity": "sha512-TrEMa7JGdVm0UThDJSx7ddw5nVm3UJS9o9CCIZ72B1vSyEZoziDqBYP3XIoi/12lKrJR8rE3jeFHMok2F/Mnsg==", + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", "dev": true, "license": "MIT" }, "node_modules/run-parallel": { "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", "dev": true, "funding": [ { @@ -11475,50 +12609,52 @@ "queue-microtask": "^1.2.2" } }, - "node_modules/sade": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", - "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", + "node_modules/safe-array-concat": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.4.tgz", + "integrity": "sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { - "mri": "^1.1.0" + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "get-intrinsic": "^1.3.0", + "has-symbols": "^1.1.0", + "isarray": "^2.0.5" }, "engines": { - "node": ">=6" + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/safe-array-concat": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz", - "integrity": "sha512-vj6RsCsWBCf19jIeHEfkRMw8DPiBb+DMXklQ/1SGDHOMlHdPUkZXFQ2YdplS23zESTijAcurb1aSgJA3AgMu1Q==", + "node_modules/safe-push-apply": { + "version": "1.0.0", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.7", - "get-intrinsic": "^1.2.4", - "has-symbols": "^1.0.3", + "es-errors": "^1.3.0", "isarray": "^2.0.5" }, "engines": { - "node": ">=0.4" + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/safe-regex-test": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.3.tgz", - "integrity": "sha512-CdASjNJPvRa7roO6Ra/gLYBTzYzzPyyBXxIMdGW3USQLyjWEls2RgW5UBTXaQVp+OrpeCK3bLem8smtmheoRuw==", + "version": "1.1.0", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.6", + "call-bound": "^1.0.2", "es-errors": "^1.3.0", - "is-regex": "^1.1.4" + "is-regex": "^1.2.1" }, "engines": { "node": ">= 0.4" @@ -11529,16 +12665,12 @@ }, "node_modules/safer-buffer": { "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "devOptional": true, "inBundle": true, "license": "MIT" }, "node_modules/saxes": { "version": "6.0.0", - "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", - "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", "dev": true, "license": "ISC", "dependencies": { @@ -11550,8 +12682,6 @@ }, "node_modules/schemes": { "version": "1.4.0", - "resolved": "https://registry.npmjs.org/schemes/-/schemes-1.4.0.tgz", - "integrity": "sha512-ImFy9FbCsQlVgnE3TCWmLPCFnVzx0lHL/l+umHplDqAKd0dzFpnS6lFZIpagBlYhKwzVmlV36ec0Y1XTu8JBAQ==", "dev": true, "license": "MIT", "dependencies": { @@ -11559,9 +12689,9 @@ } }, "node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.4.tgz", + "integrity": "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==", "inBundle": true, "license": "ISC", "bin": { @@ -11573,15 +12703,11 @@ }, "node_modules/set-blocking": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", - "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", "dev": true, "license": "ISC" }, "node_modules/set-function-length": { "version": "1.2.2", - "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", - "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", "dev": true, "license": "MIT", "peer": true, @@ -11599,8 +12725,6 @@ }, "node_modules/set-function-name": { "version": "2.0.2", - "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", - "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", "dev": true, "license": "MIT", "peer": true, @@ -11614,11 +12738,23 @@ "node": ">= 0.4" } }, + "node_modules/set-proto": { + "version": "1.0.0", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "dunder-proto": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/shebang-command": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "inBundle": true, + "dev": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -11629,26 +12765,78 @@ }, "node_modules/shebang-regex": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "inBundle": true, + "dev": true, "license": "MIT", "engines": { "node": ">=8" } }, "node_modules/side-channel": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", - "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "version": "1.1.0", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.7", "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.4", - "object-inspect": "^1.13.1" + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" }, "engines": { "node": ">= 0.4" @@ -11659,8 +12847,6 @@ }, "node_modules/signal-exit": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", "inBundle": true, "license": "ISC", "engines": { @@ -11671,21 +12857,174 @@ } }, "node_modules/sigstore": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/sigstore/-/sigstore-2.3.1.tgz", - "integrity": "sha512-8G+/XDU8wNsJOQS5ysDVO0Etg9/2uA5gR9l4ZwijjlwxBcrU6RPfwi2+jJmbP+Ap1Hlp/nVAaEO4Fj22/SL2gQ==", - "inBundle": true, + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/sigstore/-/sigstore-4.1.1.tgz", + "integrity": "sha512-endqECJkfhozrXMK5ngu/UAA0xVcVEFdnHJCElGaExypjW+HK5i6zu3NteLoaX/iFbRUbC3+DjttQs0GARr+5w==", + "dev": true, "license": "Apache-2.0", "dependencies": { - "@sigstore/bundle": "^2.3.2", - "@sigstore/core": "^1.0.0", - "@sigstore/protobuf-specs": "^0.3.2", - "@sigstore/sign": "^2.3.2", - "@sigstore/tuf": "^2.3.4", - "@sigstore/verify": "^1.2.1" + "@sigstore/bundle": "^4.0.0", + "@sigstore/core": "^3.2.1", + "@sigstore/protobuf-specs": "^0.5.0", + "@sigstore/sign": "^4.1.1", + "@sigstore/tuf": "^4.0.2", + "@sigstore/verify": "^3.1.1" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/sigstore/node_modules/@npmcli/agent": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-4.0.2.tgz", + "integrity": "sha512-EUEuWAxnL07Sp5/iC/1X6Xj+XThUvnbei9zfRWZdEXa7lss9RTHMhAHBeg+MZ5To9s/gGaSI+UwZTPdYMvKSeg==", + "dev": true, + "license": "ISC", + "dependencies": { + "agent-base": "^7.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.1", + "lru-cache": "^11.2.1", + "socks-proxy-agent": "^8.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/sigstore/node_modules/@npmcli/fs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-5.0.0.tgz", + "integrity": "sha512-7OsC1gNORBEawOa5+j2pXN9vsicaIOH5cPXxoR6fJOmH6/EXpJB2CajXOu1fPRFun2m1lktEFX11+P89hqO/og==", + "dev": true, + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/sigstore/node_modules/@npmcli/redact": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-4.0.0.tgz", + "integrity": "sha512-gOBg5YHMfZy+TfHArfVogwgfBeQnKbbGo3pSUyK/gSI0AVu+pEiDVcKlQb0D8Mg1LNRZILZ6XG8I5dJ4KuAd9Q==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/sigstore/node_modules/@sigstore/tuf": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@sigstore/tuf/-/tuf-4.0.2.tgz", + "integrity": "sha512-TCAzTy0xzdP79EnxSjq9KQ3eaR7+FmudLC6eRKknVKZbV7ZNlGLClAAQb/HMNJ5n2OBNk2GT1tEmU0xuPr+SLQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.5.0", + "tuf-js": "^4.1.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/sigstore/node_modules/cacache": { + "version": "20.0.4", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-20.0.4.tgz", + "integrity": "sha512-M3Lab8NPYlZU2exsL3bMVvMrMqgwCnMWfdZbK28bn3pK6APT/Te/I8hjRPNu1uwORY9a1eEQoifXbKPQMfMTOA==", + "dev": true, + "license": "ISC", + "dependencies": { + "@npmcli/fs": "^5.0.0", + "fs-minipass": "^3.0.0", + "glob": "^13.0.0", + "lru-cache": "^11.1.0", + "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": "^13.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/sigstore/node_modules/make-fetch-happen": { + "version": "15.0.6", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-15.0.6.tgz", + "integrity": "sha512-Je0fLJ0F5atA7F+eIlLzk+Wkcl57JDf4kf+EW8xiP5E31xOQxkIxTbgf1Oi1Lw9tRI9UEMRdI5Vz2xTzoNU1Jw==", + "dev": true, + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@npmcli/agent": "^4.0.0", + "@npmcli/redact": "^4.0.0", + "cacache": "^20.0.1", + "http-cache-semantics": "^4.1.1", + "minipass": "^7.0.2", + "minipass-fetch": "^5.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^1.0.0", + "proc-log": "^6.0.0", + "ssri": "^13.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/sigstore/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/sigstore/node_modules/socks-proxy-agent": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/sigstore/node_modules/ssri": { + "version": "13.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-13.0.1.tgz", + "integrity": "sha512-QUiRf1+u9wPTL/76GTYlKttDEBWV1ga9ZXW8BG6kfdeyyM8LGPix9gROyg9V2+P0xNyF3X2Go526xKFdMZrHSQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/sigstore/node_modules/tuf-js": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/tuf-js/-/tuf-js-4.1.0.tgz", + "integrity": "sha512-50QV99kCKH5P/Vs4E2Gzp7BopNV+KzTXqWeaxrfu5IQJBOULRsTIS9seSsOVT8ZnGXzCyx55nYWAi4qJzpZKEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tufjs/models": "4.1.0", + "debug": "^4.4.3", + "make-fetch-happen": "^15.0.1" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/smart-buffer": { @@ -11700,9 +13039,7 @@ } }, "node_modules/smtp-address-parser": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/smtp-address-parser/-/smtp-address-parser-1.0.10.tgz", - "integrity": "sha512-Osg9LmvGeAG/hyao4mldbflLOkkr3a+h4m1lwKCK5U8M6ZAr7tdXEz/+/vr752TSGE4MNUlUl9cIK2cB8cgzXg==", + "version": "1.1.0", "dev": true, "license": "MIT", "dependencies": { @@ -11713,13 +13050,13 @@ } }, "node_modules/socks": { - "version": "2.8.3", - "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.3.tgz", - "integrity": "sha512-l5x7VUUWbjVFbafGLxPWkYsHIhEvmF85tbIeFZWc8ZPtoMyybuEhL7Jye/ooC4/d48FgOjSJXgsF/AJPYCW8Zw==", + "version": "2.8.9", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.9.tgz", + "integrity": "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw==", "inBundle": true, "license": "MIT", "dependencies": { - "ip-address": "^9.0.5", + "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" }, "engines": { @@ -11728,24 +13065,42 @@ } }, "node_modules/socks-proxy-agent": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.4.tgz", - "integrity": "sha512-GNAq/eg8Udq2x0eNiFkr9gRg5bA7PXEWagQdeRX4cPSG+X/8V38v637gim9bjFptMk1QWsCTr0ttrJEiXbNnRw==", + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-10.1.0.tgz", + "integrity": "sha512-WlMj/67cEJ6MDI1OcsnjuYKDNDoyPCCYZ249kuuXPiMDw9F8PXkVaQ7YWu3siTydfQ/4BEZcvGzu+aYvz7dDCQ==", "inBundle": true, "license": "MIT", "dependencies": { - "agent-base": "^7.1.1", + "agent-base": "9.0.0", "debug": "^4.3.4", "socks": "^2.8.3" }, "engines": { - "node": ">= 14" + "node": ">= 20" + } + }, + "node_modules/socks-proxy-agent/node_modules/agent-base": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz", + "integrity": "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">= 20" } }, "node_modules/source-map": { "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", "dev": true, "license": "BSD-3-Clause", "engines": { @@ -11754,8 +13109,6 @@ }, "node_modules/source-map-support": { "version": "0.5.21", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", - "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", "dev": true, "license": "MIT", "dependencies": { @@ -11765,8 +13118,6 @@ }, "node_modules/space-separated-tokens": { "version": "2.0.2", - "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", - "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", "dev": true, "license": "MIT", "funding": { @@ -11776,8 +13127,6 @@ }, "node_modules/spawk": { "version": "1.8.2", - "resolved": "https://registry.npmjs.org/spawk/-/spawk-1.8.2.tgz", - "integrity": "sha512-3Dl+ekoMHRvXo+Xc3EUSnjySawnc9SpkaBuA3kU2wYiuSEAIYB4b5cGjvmq5olexBsO/fCLZUKHjSMQlzSU4Ww==", "dev": true, "license": "MIT", "engines": { @@ -11786,8 +13135,6 @@ }, "node_modules/spawn-wrap": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/spawn-wrap/-/spawn-wrap-2.0.0.tgz", - "integrity": "sha512-EeajNjfN9zMnULLwhZZQU3GWBoFNkbngTUPfaawT4RkMiviTxcX0qfhVbGey39mfctfDHkWtuecgQ8NJcyQWHg==", "dev": true, "license": "ISC", "dependencies": { @@ -11802,10 +13149,17 @@ "node": ">=8" } }, + "node_modules/spawn-wrap/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, "node_modules/spawn-wrap/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", + "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", "dev": true, "license": "MIT", "dependencies": { @@ -11815,8 +13169,6 @@ }, "node_modules/spawn-wrap/node_modules/foreground-child": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-2.0.0.tgz", - "integrity": "sha512-dCIq9FpEcyQyXKCkyzmlPTFNgrCzPudOe+mhvJU5zAtlBnGVy2yKxtfsxK2tQBThwq225jcvBjpw1Gr40uzZCA==", "dev": true, "license": "ISC", "dependencies": { @@ -11829,9 +13181,6 @@ }, "node_modules/spawn-wrap/node_modules/glob": { "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", "dev": true, "license": "ISC", "dependencies": { @@ -11849,10 +13198,15 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/spawn-wrap/node_modules/isexe": { + "version": "2.0.0", + "dev": true, + "license": "ISC" + }, "node_modules/spawn-wrap/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "dependencies": { @@ -11864,9 +13218,6 @@ }, "node_modules/spawn-wrap/node_modules/rimraf": { "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", "dependencies": { @@ -11881,15 +13232,11 @@ }, "node_modules/spawn-wrap/node_modules/signal-exit": { "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true, "license": "ISC" }, "node_modules/spawn-wrap/node_modules/which": { "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dev": true, "license": "ISC", "dependencies": { @@ -11904,9 +13251,7 @@ }, "node_modules/spdx-correct": { "version": "3.2.0", - "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz", - "integrity": "sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA==", - "inBundle": true, + "dev": true, "license": "Apache-2.0", "dependencies": { "spdx-expression-parse": "^3.0.0", @@ -11915,9 +13260,7 @@ }, "node_modules/spdx-correct/node_modules/spdx-expression-parse": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", - "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", - "inBundle": true, + "dev": true, "license": "MIT", "dependencies": { "spdx-exceptions": "^2.1.0", @@ -11926,15 +13269,11 @@ }, "node_modules/spdx-exceptions": { "version": "2.5.0", - "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.5.0.tgz", - "integrity": "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==", "inBundle": true, "license": "CC-BY-3.0" }, "node_modules/spdx-expression-parse": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-4.0.0.tgz", - "integrity": "sha512-Clya5JIij/7C6bRR22+tnGXbc4VKlibKSVj2iHvVeX5iMW7s1SIQlqu699JkODJJIhh/pUu8L0/VLh8xflD+LQ==", "inBundle": true, "license": "MIT", "dependencies": { @@ -11943,16 +13282,14 @@ } }, "node_modules/spdx-license-ids": { - "version": "3.0.18", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.18.tgz", - "integrity": "sha512-xxRs31BqRYHwiMzudOrpSiHtZ8i/GeionCBDSilhYRj+9gIcI8wCZTlXZKu9vZIVqViP3dcp9qE5G6AlIaD+TQ==", + "version": "3.0.23", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.23.tgz", + "integrity": "sha512-CWLcCCH7VLu13TgOH+r8p1O/Znwhqv/dbb6lqWy67G+pT1kHmeD/+V36AVb/vq8QMIQwVShJ6Ssl5FPh0fuSdw==", "inBundle": true, "license": "CC0-1.0" }, "node_modules/split": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz", - "integrity": "sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg==", "dev": true, "license": "MIT", "dependencies": { @@ -11962,40 +13299,26 @@ "node": "*" } }, - "node_modules/split2": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", - "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">= 10.x" - } - }, "node_modules/sprintf-js": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", - "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", - "inBundle": true, + "version": "1.0.3", + "dev": true, "license": "BSD-3-Clause" }, "node_modules/ssri": { - "version": "10.0.6", - "resolved": "https://registry.npmjs.org/ssri/-/ssri-10.0.6.tgz", - "integrity": "sha512-MGrFH9Z4NP9Iyhqn16sDtBpRRNJ0Y2hNa6D65h736fVSaPCHr4DM4sWUNvVaSuC+0OBGhwsrydQwmgfg5LncqQ==", + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-14.0.0.tgz", + "integrity": "sha512-jQxKI0yx0ZnTKrqjKkLDV2DXkBQn3k49JVmVqDGcDwKDtGDbImD/GXsq04KD0VVzCQQ9wZJYal3RwR1GzWTSow==", "inBundle": true, "license": "ISC", "dependencies": { "minipass": "^7.0.3" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/stack-utils": { "version": "2.0.6", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", - "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", "dev": true, "license": "MIT", "dependencies": { @@ -12007,60 +13330,47 @@ }, "node_modules/stack-utils/node_modules/escape-string-regexp": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", "dev": true, "license": "MIT", "engines": { "node": ">=8" } }, - "node_modules/static-eval": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/static-eval/-/static-eval-2.0.2.tgz", - "integrity": "sha512-N/D219Hcr2bPjLxPiV+TQE++Tsmrady7TqAJugLy7Xk1EumfDWS/f5dtBbkRCGE7wKKXuYockQoj8Rm2/pVKyg==", + "node_modules/stop-iteration-iterator": { + "version": "1.1.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { - "escodegen": "^1.8.1" + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" } }, "node_modules/streamx": { - "version": "2.18.0", - "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.18.0.tgz", - "integrity": "sha512-LLUC1TWdjVdn1weXGcSxyTR3T4+acB6tVGXT95y0nGbca4t4o/ng1wKAGTljm9VicuCVLvRlqFYXYy5GwgM7sQ==", + "version": "2.26.0", + "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.26.0.tgz", + "integrity": "sha512-VvNG1K72Po/xwJzxZFnZ++Tbrv4lwSptsbkFuzXCJAYZvCK5nnxsvXU6ajqkv7chyiI1Y0YXq2Jh8Iy8Y7NF/A==", "dev": true, "license": "MIT", "dependencies": { + "events-universal": "^1.0.0", "fast-fifo": "^1.3.2", - "queue-tick": "^1.0.1", "text-decoder": "^1.1.0" - }, - "optionalDependencies": { - "bare-events": "^2.2.0" } }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "inBundle": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } + "node_modules/strict-event-emitter": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/strict-event-emitter/-/strict-event-emitter-0.5.1.tgz", + "integrity": "sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ==", + "dev": true, + "license": "MIT" }, - "node_modules/string-width-cjs": { - "name": "string-width", + "node_modules/string-width": { "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "inBundle": true, + "dev": true, "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", @@ -12072,17 +13382,18 @@ } }, "node_modules/string.prototype.trim": { - "version": "1.2.9", - "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz", - "integrity": "sha512-klHuCNxiMZ8MlsOihJhJEBJAiMVqU3Z2nEXWfWnIqjN0gEFS9J9+IxKozWWtQGcgoa1WUZzLjKPTr4ZHNFTFxw==", + "version": "1.2.10", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "define-data-property": "^1.1.4", "define-properties": "^1.2.1", - "es-abstract": "^1.23.0", - "es-object-atoms": "^1.0.0" + "es-abstract": "^1.23.5", + "es-object-atoms": "^1.0.0", + "has-property-descriptors": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -12092,25 +13403,25 @@ } }, "node_modules/string.prototype.trimend": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.8.tgz", - "integrity": "sha512-p73uL5VCHCO2BZZ6krwwQE3kCzM7NKmis8S//xEC6fQonchbum4eP6kR4DLEjQFO3Wnj3Fuo8NM0kOSjVdHjZQ==", + "version": "1.0.9", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0" }, + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/string.prototype.trimstart": { "version": "1.0.8", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", - "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", "dev": true, "license": "MIT", "peer": true, @@ -12128,8 +13439,6 @@ }, "node_modules/stringify-entities": { "version": "4.0.4", - "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", - "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", "dev": true, "license": "MIT", "dependencies": { @@ -12143,23 +13452,7 @@ }, "node_modules/strip-ansi": { "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "inBundle": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi-cjs": { - "name": "strip-ansi", - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "inBundle": true, + "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" @@ -12170,31 +13463,14 @@ }, "node_modules/strip-bom": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", - "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", "dev": true, "license": "MIT", "engines": { "node": ">=8" } }, - "node_modules/strip-final-newline": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", - "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/strip-indent": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", - "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", "dev": true, "license": "MIT", "dependencies": { @@ -12206,8 +13482,6 @@ }, "node_modules/strip-json-comments": { "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true, "license": "MIT", "peer": true, @@ -12219,13 +13493,11 @@ } }, "node_modules/supports-color": { - "version": "9.4.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-9.4.0.tgz", - "integrity": "sha512-VL+lNrEoIXww1coLPOmiEmK/0sGigko5COxI09KzHc2VJXJsQ37UaQ+8quuxjDeA7+KnLGTWRyOXSLLR2Wb4jw==", + "version": "10.2.2", "inBundle": true, "license": "MIT", "engines": { - "node": ">=12" + "node": ">=18" }, "funding": { "url": "https://github.com/chalk/supports-color?sponsor=1" @@ -12233,8 +13505,6 @@ }, "node_modules/supports-preserve-symlinks-flag": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", "dev": true, "license": "MIT", "engines": { @@ -12246,15 +13516,11 @@ }, "node_modules/symbol-tree": { "version": "3.2.4", - "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", - "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true, "license": "MIT" }, "node_modules/tap": { "version": "16.3.10", - "resolved": "https://registry.npmjs.org/tap/-/tap-16.3.10.tgz", - "integrity": "sha512-q5Am+PpGHS6JSjk/Zn4bCRBihmZVM15v/MYXUy60wenw5HDe7pVrevLCEoMEz7tuw6jaPOJJqni1y8apN23IGw==", "bundleDependencies": [ "ink", "treport", @@ -12324,8 +13590,6 @@ }, "node_modules/tap-mocha-reporter": { "version": "5.0.4", - "resolved": "https://registry.npmjs.org/tap-mocha-reporter/-/tap-mocha-reporter-5.0.4.tgz", - "integrity": "sha512-J+YMO8B7lq1O6Zxd/jeuG27vJ+Y4tLiRMKPSb7KR6FVh86k3Rq1TwYc2GKPyIjCbzzdMdReh3Vfz9L5cg1Z2Bw==", "dev": true, "license": "ISC", "dependencies": { @@ -12345,10 +13609,17 @@ "node": ">= 8" } }, + "node_modules/tap-mocha-reporter/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, "node_modules/tap-mocha-reporter/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", + "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", "dev": true, "license": "MIT", "dependencies": { @@ -12357,9 +13628,9 @@ } }, "node_modules/tap-mocha-reporter/node_modules/diff": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", - "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", + "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==", "dev": true, "license": "BSD-3-Clause", "engines": { @@ -12368,8 +13639,6 @@ }, "node_modules/tap-mocha-reporter/node_modules/escape-string-regexp": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", "dev": true, "license": "MIT", "engines": { @@ -12378,9 +13647,6 @@ }, "node_modules/tap-mocha-reporter/node_modules/glob": { "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", "dev": true, "license": "ISC", "dependencies": { @@ -12399,9 +13665,9 @@ } }, "node_modules/tap-mocha-reporter/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "dependencies": { @@ -12413,8 +13679,6 @@ }, "node_modules/tap-parser": { "version": "11.0.2", - "resolved": "https://registry.npmjs.org/tap-parser/-/tap-parser-11.0.2.tgz", - "integrity": "sha512-6qGlC956rcORw+fg7Fv1iCRAY8/bU9UabUAhs3mXRH6eRmVZcNPLheSXCYaVaYeSwx5xa/1HXZb1537YSvwDZg==", "dev": true, "license": "MIT", "dependencies": { @@ -12431,8 +13695,6 @@ }, "node_modules/tap-parser/node_modules/minipass": { "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", "dev": true, "license": "ISC", "dependencies": { @@ -12442,10 +13704,15 @@ "node": ">=8" } }, + "node_modules/tap-parser/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true, + "license": "ISC" + }, "node_modules/tap-yaml": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/tap-yaml/-/tap-yaml-1.0.2.tgz", - "integrity": "sha512-GegASpuqBnRNdT1U+yuUPZ8rEU64pL35WPBpCISWwff4dErS2/438barz7WFJl4Nzh3Y05tfPidZnH+GaV1wMg==", "dev": true, "license": "ISC", "dependencies": { @@ -12453,9 +13720,9 @@ } }, "node_modules/tap-yaml/node_modules/yaml": { - "version": "1.10.2", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", - "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", + "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", "dev": true, "license": "ISC", "engines": { @@ -13227,8 +14494,6 @@ }, "node_modules/tap/node_modules/cliui": { "version": "7.0.4", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", "dev": true, "license": "ISC", "dependencies": { @@ -13239,8 +14504,6 @@ }, "node_modules/tap/node_modules/cliui/node_modules/ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "license": "MIT", "dependencies": { @@ -13255,8 +14518,6 @@ }, "node_modules/tap/node_modules/cliui/node_modules/color-convert": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "license": "MIT", "dependencies": { @@ -13268,15 +14529,11 @@ }, "node_modules/tap/node_modules/cliui/node_modules/color-name": { "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true, "license": "MIT" }, "node_modules/tap/node_modules/cliui/node_modules/wrap-ansi": { "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, "license": "MIT", "dependencies": { @@ -13449,8 +14706,6 @@ }, "node_modules/tap/node_modules/foreground-child": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-2.0.0.tgz", - "integrity": "sha512-dCIq9FpEcyQyXKCkyzmlPTFNgrCzPudOe+mhvJU5zAtlBnGVy2yKxtfsxK2tQBThwq225jcvBjpw1Gr40uzZCA==", "dev": true, "license": "ISC", "dependencies": { @@ -13673,10 +14928,13 @@ "node": ">=8" } }, + "node_modules/tap/node_modules/isexe": { + "version": "2.0.0", + "dev": true, + "license": "ISC" + }, "node_modules/tap/node_modules/jackspeak": { "version": "1.4.2", - "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-1.4.2.tgz", - "integrity": "sha512-GHeGTmnuaHnvS+ZctRB01bfxARuu9wW83ENbuiweu07SFcVlZrJpcshSre/keGT7YGBhLHg/+rXCNSrsEHKU4Q==", "dev": true, "license": "ISC", "dependencies": { @@ -13809,6 +15067,17 @@ "inBundle": true, "license": "ISC" }, + "node_modules/tap/node_modules/mkdirp": { + "version": "1.0.4", + "dev": true, + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/tap/node_modules/ms": { "version": "2.1.2", "dev": true, @@ -14344,8 +15613,6 @@ }, "node_modules/tap/node_modules/which": { "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dev": true, "license": "ISC", "dependencies": { @@ -14472,75 +15739,37 @@ } }, "node_modules/tar": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", - "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", + "version": "7.5.16", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.16.tgz", + "integrity": "sha512-56adEpPMouktRlBLXiaYFFzZ/3+JXa8P9n7WbR+ibIjtviN55mEaOkiysCnPnWm+7kkui1Dn8J9l+g6zV8731w==", "inBundle": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "dependencies": { - "chownr": "^2.0.0", - "fs-minipass": "^2.0.0", - "minipass": "^5.0.0", - "minizlib": "^2.1.1", - "mkdirp": "^1.0.3", - "yallist": "^4.0.0" + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" }, "engines": { - "node": ">=10" + "node": ">=18" } }, "node_modules/tar-stream": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.7.tgz", - "integrity": "sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.0.tgz", + "integrity": "sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg==", "dev": true, "license": "MIT", "dependencies": { "b4a": "^1.6.4", + "bare-fs": "^4.5.5", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, - "node_modules/tar/node_modules/fs-minipass": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", - "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", - "inBundle": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/tar/node_modules/fs-minipass/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "inBundle": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/tar/node_modules/minipass": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", - "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", - "inBundle": true, - "license": "ISC", - "engines": { - "node": ">=8" - } - }, "node_modules/tcompare": { "version": "5.0.7", - "resolved": "https://registry.npmjs.org/tcompare/-/tcompare-5.0.7.tgz", - "integrity": "sha512-d9iddt6YYGgyxJw5bjsN7UJUO1kGOtjSlNy/4PoGYAjQS5pAT/hzIoLf1bZCw+uUxRmZJh7Yy1aA7xKVRT9B4w==", "dev": true, "license": "ISC", "dependencies": { @@ -14551,19 +15780,27 @@ } }, "node_modules/tcompare/node_modules/diff": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", - "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", + "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==", "dev": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.3.1" } }, + "node_modules/teex": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz", + "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "streamx": "^2.12.5" + } + }, "node_modules/test-exclude": { "version": "6.0.0", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", - "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", "dev": true, "license": "ISC", "dependencies": { @@ -14575,10 +15812,17 @@ "node": ">=8" } }, + "node_modules/test-exclude/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, "node_modules/test-exclude/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", + "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", "dev": true, "license": "MIT", "dependencies": { @@ -14588,9 +15832,6 @@ }, "node_modules/test-exclude/node_modules/glob": { "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", "dev": true, "license": "ISC", "dependencies": { @@ -14609,9 +15850,9 @@ } }, "node_modules/test-exclude/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "dependencies": { @@ -14622,99 +15863,157 @@ } }, "node_modules/text-decoder": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.1.0.tgz", - "integrity": "sha512-TmLJNj6UgX8xcUZo4UDStGQtDiTzF7BzWlzn9g7UWrjkpHr5uJTK1ld16wZ3LXb2vb6jH8qU89dW5whuMdXYdw==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz", + "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==", "dev": true, "license": "Apache-2.0", "dependencies": { "b4a": "^1.6.4" } }, - "node_modules/text-extensions": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/text-extensions/-/text-extensions-2.4.0.tgz", - "integrity": "sha512-te/NtwBwfiNRLf9Ijqx3T0nlqZiQ2XrrtBvu+cLL8ZRrGkO0NHTug8MYFKyoSrv/sHTaSKfilUkizV6XhxMJ3g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/text-table": { "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", "inBundle": true, "license": "MIT" }, "node_modules/through": { "version": "2.3.8", - "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", - "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", "dev": true, "license": "MIT" }, "node_modules/tiny-relative-date": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/tiny-relative-date/-/tiny-relative-date-1.3.0.tgz", - "integrity": "sha512-MOQHpzllWxDCHHaDno30hhLfbouoYlOI8YlMNtvKe1zXbjEVhbcEovQxvZrPvtiYW630GQDoMMarCnjfyfHA+A==", + "version": "2.0.2", "inBundle": true, "license": "MIT" }, - "node_modules/to-fast-properties": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "node_modules/tinyexec": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.2.tgz", + "integrity": "sha512-M/Q0B2cp4K7kynaT/vnED1j8TlLY+Pp7C6Wl2bl/7u/F0mUVwdyOpwomQb8JpYLitHUssAJRmLZdMCGsrx7i+g==", "dev": true, "license": "MIT", "engines": { - "node": ">=4" + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.16", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", + "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==", + "inBundle": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/tldts": { + "version": "7.4.0", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.0.tgz", + "integrity": "sha512-yHBe+zVfzNZ3QfTPW/Z6KK1G2t340gFjMHqI/4KKSt/abzYydzuCnpqdaF5gCCABby+9Yfbj59oR5F2Fd5CBzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.4.0" + }, + "bin": { + "tldts": "bin/cli.js" } }, + "node_modules/tldts-core": { + "version": "7.4.0", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.0.tgz", + "integrity": "sha512-/mb9kRld+x1sIMXxWNOAp5m6C+D4GrAORWlJkOJ5dElvxdN1eutz/o7qHLp9gFvDF4Y3/L2xeScoxz6AbEo8rQ==", + "dev": true, + "license": "MIT" + }, "node_modules/to-regex-range": { "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "dev": true, "license": "MIT", "dependencies": { "is-number": "^7.0.0" }, - "engines": { - "node": ">=8.0" + "engines": { + "node": ">=8.0" + } + }, + "node_modules/to-vfile": { + "version": "8.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" } }, "node_modules/tough-cookie": { - "version": "4.1.4", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", - "integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.1.tgz", + "integrity": "sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==", "dev": true, "license": "BSD-3-Clause", "dependencies": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.2.0", - "url-parse": "^1.5.3" + "tldts": "^7.0.5" }, "engines": { - "node": ">=6" + "node": ">=16" } }, "node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", "dev": true, - "license": "MIT" + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } }, "node_modules/treeverse": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/treeverse/-/treeverse-3.0.0.tgz", - "integrity": "sha512-gcANaAnd2QDZFmHFEOF4k7uc1J/6a6z3DJMd/QwEyxLoKGiptJRwid582r7QIsFlFMIZ3SnxfS52S4hm2DHkuQ==", "inBundle": true, "license": "ISC", "engines": { @@ -14723,8 +16022,6 @@ }, "node_modules/trim-lines": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", - "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", "dev": true, "license": "MIT", "funding": { @@ -14734,8 +16031,6 @@ }, "node_modules/trim-newlines": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-3.0.1.tgz", - "integrity": "sha512-c1PTsA3tYrIsLGkJkzHF+w9F2EyxfXGo4UyJc4pFL++FMjnq0HJS69T3M7d//gKrFKwy429bouPescbjecU+Zw==", "dev": true, "license": "MIT", "engines": { @@ -14744,8 +16039,6 @@ }, "node_modules/trivial-deferred": { "version": "1.1.2", - "resolved": "https://registry.npmjs.org/trivial-deferred/-/trivial-deferred-1.1.2.tgz", - "integrity": "sha512-vDPiDBC3hyP6O4JrJYMImW3nl3c03Tsj9fEXc7Qc/XKa1O7gf5ZtFfIR/E0dun9SnDHdwjna1Z2rSzYgqpxh/g==", "dev": true, "license": "ISC", "engines": { @@ -14754,8 +16047,6 @@ }, "node_modules/trough": { "version": "2.2.0", - "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz", - "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==", "dev": true, "license": "MIT", "funding": { @@ -14765,8 +16056,6 @@ }, "node_modules/tsconfig-paths": { "version": "3.15.0", - "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz", - "integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==", "dev": true, "license": "MIT", "peer": true, @@ -14779,8 +16068,6 @@ }, "node_modules/tsconfig-paths/node_modules/json5": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", - "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", "dev": true, "license": "MIT", "peer": true, @@ -14793,8 +16080,6 @@ }, "node_modules/tsconfig-paths/node_modules/strip-bom": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", "dev": true, "license": "MIT", "peer": true, @@ -14803,18 +16088,32 @@ } }, "node_modules/tuf-js": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/tuf-js/-/tuf-js-2.2.1.tgz", - "integrity": "sha512-GwIJau9XaA8nLVbUXsN3IlFi7WmQ48gBUrl3FTkkL/XLu/POhBzfmX9hd33FNMX1qAsfl6ozO1iMmW9NC8YniA==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tuf-js/-/tuf-js-6.0.0.tgz", + "integrity": "sha512-zlJVOIO68hmgo1//X4ENEcTGfuOTAtDPi8PsTsG+FyxD85E/ww1ZnwBbWo/yCEExGpI+Kilg7Z3qCdHX2BoJTQ==", "inBundle": true, "license": "MIT", "dependencies": { - "@tufjs/models": "2.0.1", - "debug": "^4.3.4", - "make-fetch-happen": "^13.0.1" + "@gar/promise-retry": "^1.0.3", + "@tufjs/models": "5.0.0", + "debug": "^4.4.3" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/tuf-js/node_modules/@tufjs/models": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@tufjs/models/-/models-5.0.0.tgz", + "integrity": "sha512-U4mVcdFGOi6pt8n38LdWZp67Svn7ppnU1Pj8SGOVaBi1X4gm+G4ztQlLfkoJbKSHfjA6WeaiJp2A4V83AJF6nQ==", + "inBundle": true, + "license": "MIT", + "dependencies": { + "@tufjs/canonical-json": "2.0.0", + "minimatch": "^10.2.1" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/tunnel": { @@ -14829,8 +16128,6 @@ }, "node_modules/type-check": { "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", "dev": true, "license": "MIT", "peer": true, @@ -14843,8 +16140,6 @@ }, "node_modules/type-fest": { "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", "dev": true, "license": "(MIT OR CC0-1.0)", "peer": true, @@ -14856,34 +16151,30 @@ } }, "node_modules/typed-array-buffer": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.2.tgz", - "integrity": "sha512-gEymJYKZtKXzzBzM4jqa9w6Q1Jjm7x2d+sh19AdsD4wqnMPDYyvwpsIc2Q/835kHuo3BEQ7CjelGhfTsoBb2MQ==", + "version": "1.0.3", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.7", + "call-bound": "^1.0.3", "es-errors": "^1.3.0", - "is-typed-array": "^1.1.13" + "is-typed-array": "^1.1.14" }, "engines": { "node": ">= 0.4" } }, "node_modules/typed-array-byte-length": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.1.tgz", - "integrity": "sha512-3iMJ9q0ao7WE9tWcaYKIptkNBuOIcZCCT0d4MRvuuH88fEoEH62IuQe0OtraD3ebQEoTRk8XCBoknUNc1Y67pw==", + "version": "1.0.3", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.7", + "call-bind": "^1.0.8", "for-each": "^0.3.3", - "gopd": "^1.0.1", - "has-proto": "^1.0.3", - "is-typed-array": "^1.1.13" + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.14" }, "engines": { "node": ">= 0.4" @@ -14893,19 +16184,18 @@ } }, "node_modules/typed-array-byte-offset": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.2.tgz", - "integrity": "sha512-Ous0vodHa56FviZucS2E63zkgtgrACj7omjwd/8lTEMEPFFyjfixMZ1ZXenpgCFBBt4EC1J2XsyVS2gkG0eTFA==", + "version": "1.0.4", "dev": true, "license": "MIT", "peer": true, "dependencies": { "available-typed-arrays": "^1.0.7", - "call-bind": "^1.0.7", + "call-bind": "^1.0.8", "for-each": "^0.3.3", - "gopd": "^1.0.1", - "has-proto": "^1.0.3", - "is-typed-array": "^1.1.13" + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.15", + "reflect.getprototypeof": "^1.0.9" }, "engines": { "node": ">= 0.4" @@ -14915,9 +16205,7 @@ } }, "node_modules/typed-array-length": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.6.tgz", - "integrity": "sha512-/OxDN6OtAk5KBpGb28T+HZc2M+ADtvRxXrKKbUwtsLgdoxgX13hyy7ek6bFRl5+aBs2yZzB0c4CnQfAtVypW/g==", + "version": "1.0.7", "dev": true, "license": "MIT", "peer": true, @@ -14925,9 +16213,9 @@ "call-bind": "^1.0.7", "for-each": "^0.3.3", "gopd": "^1.0.1", - "has-proto": "^1.0.3", "is-typed-array": "^1.1.13", - "possible-typed-array-names": "^1.0.0" + "possible-typed-array-names": "^1.0.0", + "reflect.getprototypeof": "^1.0.6" }, "engines": { "node": ">= 0.4" @@ -14938,8 +16226,6 @@ }, "node_modules/typedarray-to-buffer": { "version": "3.1.5", - "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", - "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", "dev": true, "license": "MIT", "dependencies": { @@ -14947,9 +16233,9 @@ } }, "node_modules/typescript": { - "version": "5.4.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", - "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", "dev": true, "license": "Apache-2.0", "peer": true, @@ -14962,9 +16248,7 @@ } }, "node_modules/uglify-js": { - "version": "3.18.0", - "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.18.0.tgz", - "integrity": "sha512-SyVVbcNBCk0dzr9XL/R/ySrmYf0s372K6/hFklzgcp2lBFyXtw4I7BOdDjlLhE1aVqaI/SHWXWmYdlZxuyF38A==", + "version": "3.19.3", "dev": true, "license": "BSD-2-Clause", "optional": true, @@ -14976,134 +16260,75 @@ } }, "node_modules/unbox-primitive": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz", - "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==", + "version": "1.1.0", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "call-bind": "^1.0.2", + "call-bound": "^1.0.3", "has-bigints": "^1.0.2", - "has-symbols": "^1.0.3", - "which-boxed-primitive": "^1.0.2" + "has-symbols": "^1.1.0", + "which-boxed-primitive": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/underscore": { - "version": "1.12.1", - "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.12.1.tgz", - "integrity": "sha512-hEQt0+ZLDVUMhebKxL4x1BTtDY7bavVofhZ9KZ4aI26X9SRaE+Y3m83XUL1UP2jn8ynjndwCCpEHdUG+9pP1Tw==", - "dev": true, - "license": "MIT" - }, "node_modules/undici": { - "version": "6.19.2", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.19.2.tgz", - "integrity": "sha512-JfjKqIauur3Q6biAtHJ564e3bWa8VvT+7cSiOJHFbX4Erv6CLGDpg8z+Fmg/1OI/47RA+GI2QZaF48SSaLvyBA==", - "dev": true, + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.26.0.tgz", + "integrity": "sha512-4yqz8a3n5HmGTlsbADNtr/dJlhkh/55Rq798G6ibiULcXbDtaLpTl1pvdqcbFfeoj3iSi52lePFM7h9H21cw/A==", + "inBundle": true, "license": "MIT", "engines": { "node": ">=18.17" } }, "node_modules/undici-types": { - "version": "5.26.5", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", - "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/unicode-length": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/unicode-length/-/unicode-length-2.1.0.tgz", - "integrity": "sha512-4bV582zTV9Q02RXBxSUMiuN/KHo5w4aTojuKTNT96DIKps/SIawFp7cS5Mu25VuY1AioGXrmYyzKZUzh8OqoUw==", "dev": true, "license": "MIT", "dependencies": { "punycode": "^2.0.0" } }, - "node_modules/unicorn-magic": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.1.0.tgz", - "integrity": "sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/unified": { - "version": "10.1.2", - "resolved": "https://registry.npmjs.org/unified/-/unified-10.1.2.tgz", - "integrity": "sha512-pUSWAi/RAnVy1Pif2kAoeWNBa3JVrx0MId2LASj8G+7AiHWoKZNTomq6LG326T68U7/e263X6fTdcXIy7XnF7Q==", + "version": "11.0.5", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0", + "@types/unist": "^3.0.0", "bail": "^2.0.0", + "devlop": "^1.0.0", "extend": "^3.0.0", - "is-buffer": "^2.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", - "vfile": "^5.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unique-filename": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-3.0.0.tgz", - "integrity": "sha512-afXhuC55wkAmZ0P18QsVE6kp8JaxrEokN2HGIoIVv2ijHQd419H0+6EigAFcIzXeMIkcIkNBpB3L/DXB3cTS/g==", - "inBundle": true, - "license": "ISC", - "dependencies": { - "unique-slug": "^4.0.0" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/unique-slug": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-4.0.0.tgz", - "integrity": "sha512-WrcA6AyEfqDX5bWige/4NQfPZMtASNVxdmWR76WESYQVAACSgWcR6e9i0mofqqBxYFtL4oAxPIptY73/0YE1DQ==", - "inBundle": true, - "license": "ISC", - "dependencies": { - "imurmurhash": "^0.1.4" + "vfile": "^6.0.0" }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/unist-util-generated": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/unist-util-generated/-/unist-util-generated-2.0.1.tgz", - "integrity": "sha512-qF72kLmPxAw0oN2fwpWIqbXAVyEqUzDHMsbtPvOudIlUzXYFIeQIuxXQCRCFh22B7cixvU0MG7m3MW8FTq/S+A==", - "dev": true, - "license": "MIT", "funding": { "type": "opencollective", "url": "https://opencollective.com/unified" } }, "node_modules/unist-util-is": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-5.2.1.tgz", - "integrity": "sha512-u9njyyfEh43npf1M+yGKDGVPbY/JWEemg5nH05ncKPfi+kBbKBJoTdsogMu33uhytuLlv9y0O7GH7fEdwLdLQw==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", + "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0" + "@types/unist": "^3.0.0" }, "funding": { "type": "opencollective", @@ -15111,13 +16336,11 @@ } }, "node_modules/unist-util-position": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-4.0.4.tgz", - "integrity": "sha512-kUBE91efOWfIVBo8xzh/uZQ7p9ffYRtUbMRZBNFYwf0RK8koUMx6dGUfwylLOKmaT2cs4wSW96QoYUSXAyEtpg==", + "version": "5.0.0", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0" + "@types/unist": "^3.0.0" }, "funding": { "type": "opencollective", @@ -15125,13 +16348,11 @@ } }, "node_modules/unist-util-stringify-position": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-3.0.3.tgz", - "integrity": "sha512-k5GzIBZ/QatR8N5X2y+drfpWG8IDBzdnVj6OInRNWm1oXrzydiaAT2OQiA8DPRRZyAKb9b6I2a6PxYklZD0gKg==", + "version": "4.0.0", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0" + "@types/unist": "^3.0.0" }, "funding": { "type": "opencollective", @@ -15140,8 +16361,6 @@ }, "node_modules/unist-util-visit": { "version": "2.0.3", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-2.0.3.tgz", - "integrity": "sha512-iJ4/RczbJMkD0712mGktuGpm/U4By4FfDonL7N/9tATGIF4imikjOuagyMY53tnZq3NP6BcmlrHhEKAfGWjh7Q==", "dev": true, "license": "MIT", "dependencies": { @@ -15156,8 +16375,6 @@ }, "node_modules/unist-util-visit-parents": { "version": "3.1.1", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-3.1.1.tgz", - "integrity": "sha512-1KROIZWo6bcMrZEwiH2UrXDyalAa0uqzWCxCJj6lPOvTve2WkfgCytoDTPaMnodXh1WrXOq0haVYHj99ynJlsg==", "dev": true, "license": "MIT", "dependencies": { @@ -15169,10 +16386,15 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/unist-util-visit-parents/node_modules/@types/unist": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", + "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==", + "dev": true, + "license": "MIT" + }, "node_modules/unist-util-visit-parents/node_modules/unist-util-is": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-4.1.0.tgz", - "integrity": "sha512-ZOQSsnce92GrxSqlnEEseX0gi7GH9zTJZ0p9dtu87WRb/37mMPO2Ilx1s/t9vBHrFhbgweUwb+t7cIn5dxPhZg==", "dev": true, "license": "MIT", "funding": { @@ -15180,10 +16402,15 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/unist-util-visit/node_modules/@types/unist": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", + "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==", + "dev": true, + "license": "MIT" + }, "node_modules/unist-util-visit/node_modules/unist-util-is": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-4.1.0.tgz", - "integrity": "sha512-ZOQSsnce92GrxSqlnEEseX0gi7GH9zTJZ0p9dtu87WRb/37mMPO2Ilx1s/t9vBHrFhbgweUwb+t7cIn5dxPhZg==", "dev": true, "license": "MIT", "funding": { @@ -15192,26 +16419,14 @@ } }, "node_modules/universal-user-agent": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", - "integrity": "sha512-yCzhz6FN2wU1NiiQRogkTQszlQSlpWaw8SvVegAc+bDxbzHgh1vX8uIe8OYyMH6DwH+sdTJsgMl36+mSMdRJIQ==", + "version": "7.0.3", "dev": true, "license": "ISC" }, - "node_modules/universalify": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", - "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4.0.0" - } - }, "node_modules/update-browserslist-db": { - "version": "1.0.16", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.16.tgz", - "integrity": "sha512-KVbTxlBYlckhF5wgfyZXTWnMn7MMZjMu9XG8bPlliUOP9ThaF4QnhP8qrjrH7DRzHfSk0oQv1wToW+iA5GajEQ==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", "dev": true, "funding": [ { @@ -15229,8 +16444,8 @@ ], "license": "MIT", "dependencies": { - "escalade": "^3.1.2", - "picocolors": "^1.0.1" + "escalade": "^3.2.0", + "picocolors": "^1.1.1" }, "bin": { "update-browserslist-db": "cli.js" @@ -15241,65 +16456,27 @@ }, "node_modules/uri-js": { "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", "dev": true, "license": "BSD-2-Clause", "dependencies": { "punycode": "^2.1.0" } }, - "node_modules/url-parse": { - "version": "1.5.10", - "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", - "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "querystringify": "^2.1.1", - "requires-port": "^1.0.0" - } - }, "node_modules/util-deprecate": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "license": "MIT" }, "node_modules/uuid": { "version": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", "dev": true, "license": "MIT", "bin": { "uuid": "dist/bin/uuid" } }, - "node_modules/uvu": { - "version": "0.5.6", - "resolved": "https://registry.npmjs.org/uvu/-/uvu-0.5.6.tgz", - "integrity": "sha512-+g8ENReyr8YsOc6fv/NVJs2vFdHBnBNdfE49rshrTzDWOlUx4Gq7KOS2GD8eqhy2j+Ejq29+SbKH8yjkAqXqoA==", - "dev": true, - "license": "MIT", - "dependencies": { - "dequal": "^2.0.0", - "diff": "^5.0.0", - "kleur": "^4.0.3", - "sade": "^1.7.3" - }, - "bin": { - "uvu": "bin.js" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/validate-npm-package-license": { "version": "3.0.4", - "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", - "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", - "inBundle": true, + "dev": true, "license": "Apache-2.0", "dependencies": { "spdx-correct": "^3.0.0", @@ -15308,9 +16485,7 @@ }, "node_modules/validate-npm-package-license/node_modules/spdx-expression-parse": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", - "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", - "inBundle": true, + "dev": true, "license": "MIT", "dependencies": { "spdx-exceptions": "^2.1.0", @@ -15318,41 +16493,22 @@ } }, "node_modules/validate-npm-package-name": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-5.0.1.tgz", - "integrity": "sha512-OljLrQ9SQdOUqTaQxqL5dEfZWrXExyyWsozYlAWFawPVNuD83igl7uJD2RTkNMbniIYgt8l81eCJGIdQF7avLQ==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-8.0.0.tgz", + "integrity": "sha512-SCv6OOV6Xj2/3cXy3dGmADluJTNcL3o7hZAglNPTe+WYuEuvxgJzxPrSDLZhF+CwyQOubqgecjMmTJGMVLWjYQ==", "inBundle": true, "license": "ISC", "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/vfile": { - "version": "5.3.7", - "resolved": "https://registry.npmjs.org/vfile/-/vfile-5.3.7.tgz", - "integrity": "sha512-r7qlzkgErKjobAmyNIkkSpizsFPYiUPuJb5pNW1RB4JcYVZhs4lIbVqk8XPk033CV/1z8ss5pkax8SuhGpcG8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^2.0.0", - "is-buffer": "^2.0.0", - "unist-util-stringify-position": "^3.0.0", - "vfile-message": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/vfile-location": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/vfile-location/-/vfile-location-4.1.0.tgz", - "integrity": "sha512-YF23YMyASIIJXpktBa4vIGLJ5Gs88UB/XePgqPmTa7cDA+JeO3yclbpheQYCHjVHBn/yePzrXuygIL+xbvRYHw==", + "version": "6.0.3", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0", - "vfile": "^5.0.0" + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" }, "funding": { "type": "opencollective", @@ -15360,14 +16516,12 @@ } }, "node_modules/vfile-message": { - "version": "3.1.4", - "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-3.1.4.tgz", - "integrity": "sha512-fa0Z6P8HUrQN4BZaX05SIVXic+7kE3b05PWAtPuYP9QLHsLKYR7/AlLW3NtOrpXRLeawpDLMsVkmk5DG0NXgWw==", + "version": "4.0.3", "dev": true, "license": "MIT", "dependencies": { - "@types/unist": "^2.0.0", - "unist-util-stringify-position": "^3.0.0" + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" }, "funding": { "type": "opencollective", @@ -15376,8 +16530,6 @@ }, "node_modules/w3c-xmlserializer": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", - "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", "dev": true, "license": "MIT", "dependencies": { @@ -15388,33 +16540,27 @@ } }, "node_modules/walk-up-path": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/walk-up-path/-/walk-up-path-3.0.1.tgz", - "integrity": "sha512-9YlCL/ynK3CTlrSRrDxZvUauLzAswPCrsaCgilqFevUYpeEW0/3ScEjaa3kbW/T0ghhkEr7mv+fpjqn1Y1YuTA==", - "license": "ISC" - }, - "node_modules/web-namespaces": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/web-namespaces/-/web-namespaces-2.0.1.tgz", - "integrity": "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" + "version": "4.0.0", + "license": "ISC", + "engines": { + "node": "20 || >=22" } }, "node_modules/webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", "dev": true, - "license": "BSD-2-Clause" + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } }, "node_modules/whatwg-encoding": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", "dev": true, "license": "MIT", "dependencies": { @@ -15424,248 +16570,187 @@ "node": ">=18" } }, - "node_modules/whatwg-mimetype": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", - "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "node_modules/whatwg-encoding/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", "dev": true, "license": "MIT", "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, - "node_modules/which": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/which/-/which-4.0.0.tgz", - "integrity": "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg==", - "inBundle": true, - "license": "ISC", - "dependencies": { - "isexe": "^3.1.1" - }, - "bin": { - "node-which": "bin/which.js" + "safer-buffer": ">= 2.1.2 < 3.0.0" }, "engines": { - "node": "^16.13.0 || >=18.0.0" + "node": ">=0.10.0" } }, - "node_modules/which-boxed-primitive": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", - "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", "dev": true, "license": "MIT", - "peer": true, - "dependencies": { - "is-bigint": "^1.0.1", - "is-boolean-object": "^1.1.0", - "is-number-object": "^1.0.4", - "is-string": "^1.0.5", - "is-symbol": "^1.0.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "engines": { + "node": ">=18" } }, - "node_modules/which-module": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", - "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/which-typed-array": { - "version": "1.1.15", - "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.15.tgz", - "integrity": "sha512-oV0jmFtUky6CXfkqehVvBP/LSWJ2sy4vWMioiENyJLePrBO/yKyV9OyJySfAKosh+RYkIl5zJCNZ8/4JncrpdA==", + "node_modules/whatwg-url": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-15.1.0.tgz", + "integrity": "sha512-2ytDk0kiEj/yu90JOAp44PVPUkO9+jVhyf+SybKlRHSDlvOOZhdPIrr7xTH64l4WixO2cP+wQIcgujkGBPPz6g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { - "available-typed-arrays": "^1.0.7", - "call-bind": "^1.0.7", - "for-each": "^0.3.3", - "gopd": "^1.0.1", - "has-tostringtag": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.0" }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/which/node_modules/isexe": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.1.tgz", - "integrity": "sha512-LpB/54B+/2J5hqQ7imZHfdU31OlgQqx7ZicVlkm9kzg9/w8GKLEcFfJl/t7DCEDueOyBAD6zCCwTO6Fzs0NoEQ==", - "inBundle": true, - "license": "ISC", - "engines": { - "node": ">=16" - } - }, - "node_modules/word-wrap": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", - "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", - "dev": true, - "license": "MIT", "engines": { - "node": ">=0.10.0" + "node": ">=20" } }, - "node_modules/wordwrap": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", - "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/wrap-ansi": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", - "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "node_modules/which": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/which/-/which-7.0.0.tgz", + "integrity": "sha512-RancgH2dmbLdHl6LRhEqvklWMgl/Hdnun0Y90KhBOLkMefg8Qa7/Zel8Sm+8HEcP6DEjzsWzpkuBQEZok58isA==", "inBundle": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" + "isexe": "^4.0.0" }, - "engines": { - "node": ">=12" + "bin": { + "node-which": "bin/which.js" }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, - "node_modules/wrap-ansi-cjs": { - "name": "wrap-ansi", - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "inBundle": true, + "node_modules/which-boxed-primitive": { + "version": "1.1.1", + "dev": true, "license": "MIT", + "peer": true, "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" + "is-bigint": "^1.1.0", + "is-boolean-object": "^1.2.1", + "is-number-object": "^1.1.1", + "is-string": "^1.1.1", + "is-symbol": "^1.1.1" }, "engines": { - "node": ">=10" + "node": ">= 0.4" }, "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "inBundle": true, + "node_modules/which-builtin-type": { + "version": "1.2.1", + "dev": true, "license": "MIT", + "peer": true, "dependencies": { - "color-convert": "^2.0.1" + "call-bound": "^1.0.2", + "function.prototype.name": "^1.1.6", + "has-tostringtag": "^1.0.2", + "is-async-function": "^2.0.0", + "is-date-object": "^1.1.0", + "is-finalizationregistry": "^1.1.0", + "is-generator-function": "^1.0.10", + "is-regex": "^1.2.1", + "is-weakref": "^1.0.2", + "isarray": "^2.0.5", + "which-boxed-primitive": "^1.1.0", + "which-collection": "^1.0.2", + "which-typed-array": "^1.1.16" }, "engines": { - "node": ">=8" + "node": ">= 0.4" }, "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/wrap-ansi/node_modules/ansi-regex": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", - "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", - "inBundle": true, + "node_modules/which-collection": { + "version": "1.0.2", + "dev": true, "license": "MIT", + "peer": true, + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, "engines": { - "node": ">=12" + "node": ">= 0.4" }, "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/wrap-ansi/node_modules/emoji-regex": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", - "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", - "inBundle": true, - "license": "MIT" + "node_modules/which-module": { + "version": "2.0.1", + "dev": true, + "license": "ISC" }, - "node_modules/wrap-ansi/node_modules/string-width": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", - "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", - "inBundle": true, + "node_modules/which-typed-array": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.21.tgz", + "integrity": "sha512-zbRA8cVm6io/d5W8uIe2hblzN76/Wm3v/yiythQvr+dpBWeqhPSWIDNj4zOyHi4zKbMK6DN34Xsr9jPHJERAEw==", + "dev": true, "license": "MIT", + "peer": true, "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" }, "engines": { - "node": ">=12" + "node": ">= 0.4" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/wrap-ansi/node_modules/strip-ansi": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", - "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", - "inBundle": true, + "node_modules/word-wrap": { + "version": "1.2.5", + "dev": true, "license": "MIT", - "dependencies": { - "ansi-regex": "^6.0.1" - }, + "peer": true, "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" + "node": ">=0.10.0" } }, + "node_modules/wordwrap": { + "version": "1.0.0", + "dev": true, + "license": "MIT" + }, "node_modules/wrappy": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "dev": true, "license": "ISC" }, "node_modules/write-file-atomic": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-5.0.1.tgz", - "integrity": "sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==", - "inBundle": true, + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-7.0.1.tgz", + "integrity": "sha512-OTIk8iR8/aCRWBqvxrzxR0hgxWpnYBblY1S5hDWBQfk/VFmJwzmJgQFN3WsoUKHISv2eAwe+PpbUzyL1CKTLXg==", + "dev": true, "license": "ISC", "dependencies": { - "imurmurhash": "^0.1.4", "signal-exit": "^4.0.1" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/ws": { - "version": "8.17.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", - "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", "dev": true, "license": "MIT", "engines": { @@ -15686,8 +16771,6 @@ }, "node_modules/xml-name-validator": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", - "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", "dev": true, "license": "Apache-2.0", "engines": { @@ -15696,15 +16779,11 @@ }, "node_modules/xmlchars": { "version": "2.2.0", - "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", - "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", "dev": true, "license": "MIT" }, "node_modules/xpath": { "version": "0.0.34", - "resolved": "https://registry.npmjs.org/xpath/-/xpath-0.0.34.tgz", - "integrity": "sha512-FxF6+rkr1rNSQrhUNYrAFJpRXNzlDoMxeXN5qI84939ylEv3qqPFKa85Oxr6tDaJKqwW6KKyo2v26TSv3k6LeA==", "dev": true, "license": "MIT", "engines": { @@ -15713,8 +16792,6 @@ }, "node_modules/y18n": { "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", "dev": true, "license": "ISC", "engines": { @@ -15722,29 +16799,33 @@ } }, "node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", "inBundle": true, - "license": "ISC" + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } }, "node_modules/yaml": { - "version": "2.4.5", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.4.5.tgz", - "integrity": "sha512-aBx2bnqDzVOyNKfsysjA2ms5ZlnjSAW2eG3/L5G/CSujfjLJTJsEw1bGw8kCf04KodQWk1pxlGnZ56CRxiawmg==", + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", + "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", "dev": true, "license": "ISC", "bin": { "yaml": "bin.mjs" }, "engines": { - "node": ">= 14" + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" } }, "node_modules/yargs": { "version": "17.7.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", - "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", "dev": true, "license": "MIT", "dependencies": { @@ -15762,31 +16843,14 @@ }, "node_modules/yargs-parser": { "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", "dev": true, "license": "ISC", "engines": { "node": ">=12" } }, - "node_modules/yocto-queue": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.0.0.tgz", - "integrity": "sha512-9bnSc/HEW2uRy67wc+T8UwauLuPJVn28jb+GtJY16iiKWyvmYJRXVT4UamsAEGQfPohgr2q4Tq0sQbQlxTfi1g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/zwitch": { "version": "2.0.4", - "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", - "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", "dev": true, "license": "MIT", "funding": { @@ -15799,316 +16863,528 @@ "version": "1.0.1", "license": "ISC", "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", + "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-registry": "^1.0.0", - "@npmcli/promise-spawn": "^7.0.2", - "@npmcli/template-oss": "4.22.0", + "@npmcli/promise-spawn": "^10.0.0", + "@npmcli/template-oss": "5.1.1", "proxy": "^2.1.1", - "semver": "^7.5.4", + "rimraf": "^6.0.1", "tap": "^16.3.8", - "which": "^4.0.0" + "which": "^7.0.0" }, "engines": { - "node": "^18.17.0 || >=20.5.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "workspaces/arborist": { "name": "@npmcli/arborist", - "version": "7.5.4", + "version": "10.0.0-pre.1", "license": "ISC", "dependencies": { + "@gar/promise-retry": "^1.0.0", "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/fs": "^3.1.1", - "@npmcli/installed-package-contents": "^2.1.0", - "@npmcli/map-workspaces": "^3.0.2", - "@npmcli/metavuln-calculator": "^7.1.1", - "@npmcli/name-from-folder": "^2.0.0", - "@npmcli/node-gyp": "^3.0.0", - "@npmcli/package-json": "^5.1.0", - "@npmcli/query": "^3.1.0", - "@npmcli/redact": "^2.0.0", - "@npmcli/run-script": "^8.1.0", - "bin-links": "^4.0.4", - "cacache": "^18.0.3", - "common-ancestor-path": "^1.0.1", - "hosted-git-info": "^7.0.2", - "json-parse-even-better-errors": "^3.0.2", + "@npmcli/fs": "^6.0.0", + "@npmcli/installed-package-contents": "^5.0.0", + "@npmcli/map-workspaces": "^6.0.0", + "@npmcli/metavuln-calculator": "^10.0.0", + "@npmcli/name-from-folder": "^5.0.0", + "@npmcli/node-gyp": "^6.0.0", + "@npmcli/package-json": "^8.0.0", + "@npmcli/query": "^5.0.0", + "@npmcli/redact": "^5.0.0", + "@npmcli/run-script": "^11.0.0", + "bin-links": "^7.0.0", + "cacache": "^21.0.1", + "common-ancestor-path": "^2.0.0", + "diff": "^8.0.2", + "hosted-git-info": "^10.1.1", "json-stringify-nice": "^1.1.4", - "lru-cache": "^10.2.2", - "minimatch": "^9.0.4", - "nopt": "^7.2.1", - "npm-install-checks": "^6.2.0", - "npm-package-arg": "^11.0.2", - "npm-pick-manifest": "^9.0.1", - "npm-registry-fetch": "^17.0.1", - "pacote": "^18.0.6", - "parse-conflict-json": "^3.0.0", - "proc-log": "^4.2.0", - "proggy": "^2.0.0", + "lru-cache": "^11.2.1", + "minimatch": "^10.0.3", + "nopt": "^10.0.1", + "npm-install-checks": "^9.0.0", + "npm-package-arg": "^14.0.0", + "npm-pick-manifest": "^12.0.0", + "npm-registry-fetch": "^20.0.1", + "pacote": "^22.0.0", + "parse-conflict-json": "^6.0.0", + "proc-log": "^7.0.0", + "proggy": "^4.0.0", "promise-all-reject-late": "^1.0.0", "promise-call-limit": "^3.0.1", - "read-package-json-fast": "^3.0.2", "semver": "^7.3.7", - "ssri": "^10.0.6", + "ssri": "^14.0.0", "treeverse": "^3.0.0", - "walk-up-path": "^3.0.1" + "validate-npm-package-name": "^7.0.2", + "walk-up-path": "^4.0.0" }, "bin": { "arborist": "bin/index.js" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/mock-registry": "^1.0.0", + "@npmcli/template-oss": "5.1.1", "benchmark": "^2.1.4", - "minify-registry-metadata": "^3.0.0", - "nock": "^13.3.3", + "minify-registry-metadata": "^4.0.0", + "nock": "^14.0.0", "tap": "^16.3.8", "tar-stream": "^3.0.0", "tcompare": "^5.0.6" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "workspaces/arborist/node_modules/validate-npm-package-name": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-7.0.2.tgz", + "integrity": "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A==", + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" } }, "workspaces/config": { "name": "@npmcli/config", - "version": "8.3.4", + "version": "11.0.0-pre.1", "license": "ISC", "dependencies": { - "@npmcli/map-workspaces": "^3.0.2", - "@npmcli/package-json": "^5.1.1", + "@npmcli/map-workspaces": "^6.0.0", + "@npmcli/package-json": "^8.0.0", "ci-info": "^4.0.0", - "ini": "^4.1.2", - "nopt": "^7.2.1", - "proc-log": "^4.2.0", + "ini": "^7.0.0", + "nopt": "^10.0.1", + "proc-log": "^7.0.0", "semver": "^7.3.5", - "walk-up-path": "^3.0.1" + "walk-up-path": "^4.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", + "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-globals": "^1.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/template-oss": "5.1.1", "tap": "^16.3.8" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "workspaces/libnpmaccess": { - "version": "8.0.6", + "version": "11.0.0-pre.0", "license": "ISC", "dependencies": { - "npm-package-arg": "^11.0.2", - "npm-registry-fetch": "^17.0.1" + "npm-package-arg": "^14.0.0", + "npm-registry-fetch": "^20.0.1" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", + "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-registry": "^1.0.0", - "@npmcli/template-oss": "4.22.0", - "nock": "^13.3.3", + "@npmcli/template-oss": "5.1.1", "tap": "^16.3.8" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "workspaces/libnpmdiff": { - "version": "6.1.4", + "version": "9.0.0-pre.0", "license": "ISC", "dependencies": { - "@npmcli/arborist": "^7.5.4", - "@npmcli/installed-package-contents": "^2.1.0", - "binary-extensions": "^2.3.0", - "diff": "^5.1.0", - "minimatch": "^9.0.4", - "npm-package-arg": "^11.0.2", - "pacote": "^18.0.6", - "tar": "^6.2.1" + "@npmcli/arborist": "^10.0.0-pre.1", + "@npmcli/installed-package-contents": "^5.0.0", + "binary-extensions": "^3.0.0", + "diff": "^8.0.2", + "minimatch": "^10.0.3", + "npm-package-arg": "^14.0.0", + "pacote": "^22.0.0", + "tar": "^7.5.1" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "tap": "^16.3.8" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "workspaces/libnpmexec": { - "version": "8.1.3", + "version": "11.0.0-pre.0", "license": "ISC", "dependencies": { - "@npmcli/arborist": "^7.5.4", - "@npmcli/run-script": "^8.1.0", + "@gar/promise-retry": "^1.0.0", + "@npmcli/arborist": "^10.0.0-pre.1", + "@npmcli/package-json": "^8.0.0", + "@npmcli/run-script": "^11.0.0", "ci-info": "^4.0.0", - "npm-package-arg": "^11.0.2", - "pacote": "^18.0.6", - "proc-log": "^4.2.0", - "read": "^3.0.1", - "read-package-json-fast": "^3.0.2", + "npm-package-arg": "^14.0.0", + "pacote": "^22.0.0", + "proc-log": "^7.0.0", + "read": "^6.0.0", "semver": "^7.3.7", - "walk-up-path": "^3.0.1" + "signal-exit": "^4.1.0", + "walk-up-path": "^4.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", + "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-registry": "^1.0.0", - "@npmcli/template-oss": "4.22.0", - "bin-links": "^4.0.4", + "@npmcli/template-oss": "5.1.1", + "bin-links": "^7.0.0", "chalk": "^5.2.0", "just-extend": "^6.2.0", "just-safe-set": "^4.2.1", "tap": "^16.3.8" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "workspaces/libnpmfund": { - "version": "5.0.12", - "license": "ISC", - "dependencies": { - "@npmcli/arborist": "^7.5.4" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.3.8" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "workspaces/libnpmhook": { - "version": "10.0.5", + "version": "8.0.0-pre.0", "license": "ISC", "dependencies": { - "aproba": "^2.0.0", - "npm-registry-fetch": "^17.0.1" + "@npmcli/arborist": "^10.0.0-pre.1" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "nock": "^13.3.3", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "tap": "^16.3.8" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "workspaces/libnpmorg": { - "version": "6.0.6", + "version": "9.0.0-pre.0", "license": "ISC", "dependencies": { "aproba": "^2.0.0", - "npm-registry-fetch": "^17.0.1" + "npm-registry-fetch": "^20.0.1" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "minipass": "^7.1.1", - "nock": "^13.3.3", + "nock": "^14.0.0", "tap": "^16.3.8" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "workspaces/libnpmpack": { - "version": "7.0.4", + "version": "10.0.0-pre.1", "license": "ISC", "dependencies": { - "@npmcli/arborist": "^7.5.4", - "@npmcli/run-script": "^8.1.0", - "npm-package-arg": "^11.0.2", - "pacote": "^18.0.6" + "@npmcli/arborist": "^10.0.0-pre.1", + "@npmcli/run-script": "^11.0.0", + "npm-package-arg": "^14.0.0", + "pacote": "^22.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "nock": "^13.3.3", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", + "nock": "^14.0.0", "spawk": "^1.7.1", "tap": "^16.3.8" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "workspaces/libnpmpublish": { - "version": "9.0.9", + "version": "12.0.0-pre.0", "license": "ISC", "dependencies": { + "@npmcli/package-json": "^8.0.0", "ci-info": "^4.0.0", - "normalize-package-data": "^6.0.1", - "npm-package-arg": "^11.0.2", - "npm-registry-fetch": "^17.0.1", - "proc-log": "^4.2.0", + "npm-package-arg": "^14.0.0", + "npm-registry-fetch": "^20.0.1", + "proc-log": "^7.0.0", "semver": "^7.3.7", - "sigstore": "^2.2.0", - "ssri": "^10.0.6" + "sigstore": "^5.0.0", + "ssri": "^14.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", + "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-globals": "^1.0.0", "@npmcli/mock-registry": "^1.0.0", - "@npmcli/template-oss": "4.22.0", - "nock": "^13.3.3", + "@npmcli/template-oss": "5.1.1", "tap": "^16.3.8" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/sigstore/-/sigstore-5.0.0.tgz", + "integrity": "sha512-hJqJfoG/e4qFQaauQL00c6J6FrHLBGKtkFvW3JbTSIEFOhLrSjdSM/gWd/yUOfYo/gsERehTXGC1VZWX+9X4Dg==", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^5.0.0", + "@sigstore/core": "^4.0.0", + "@sigstore/protobuf-specs": "^0.5.0", + "@sigstore/sign": "^5.0.0", + "@sigstore/tuf": "^5.0.0", + "@sigstore/verify": "^4.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/@npmcli/agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-5.0.1.tgz", + "integrity": "sha512-PsOUeQRpNOGH+Iks/YPY8AXtttvGVqNqKIo/Cp2LhI0jpeqW32JP14yYRym+OsTg+roH4Avw281YwHMp8X8L2Q==", + "license": "ISC", + "dependencies": { + "agent-base": "^9.0.0", + "http-proxy-agent": "^9.0.0", + "https-proxy-agent": "^9.0.0", + "lru-cache": "^11.2.1", + "socks-proxy-agent": "^10.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/@npmcli/fs": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-6.0.0.tgz", + "integrity": "sha512-AheOs4swKka/XLtht6xxJDPezlQ7K2IYQ9Y8lST4JLDjnralnWuMM9AE2CdVcgQJ5omrXhsRzM7F7aYmeZBvKQ==", + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/@npmcli/redact": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-5.0.0.tgz", + "integrity": "sha512-3zcN5Q3yEmeyxXBzqB6fXPQFzYa2ROsGFSr69W0ArXIAGJqxl/aFECOVPD2kbkYPm0U/EHxFKgclK3UA9WQg5A==", + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/@sigstore/bundle": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@sigstore/bundle/-/bundle-5.0.0.tgz", + "integrity": "sha512-wefjygudENbzbQMks1t5u34EP0fFoD0XvaEP7DOUP/sXKvogzEJYFw5E6pegGyp3onGWzVEYKVa3bNZWyTYX+A==", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.5.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/@sigstore/core": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sigstore/core/-/core-4.0.0.tgz", + "integrity": "sha512-uFGJpKiMCKXV+61jsxQ0ECfr0wjDP+8qnT6pgfsOXbIk0j/KPfBSp2Dks/YcNcT/S4e3P267JKPL6gAwygJRuw==", + "license": "Apache-2.0", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/@sigstore/sign": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@sigstore/sign/-/sign-5.0.0.tgz", + "integrity": "sha512-DSFivqz9/i5AkwZ5fq0YdjaJlc4o1WeS2Zffon0kqtChx0vy4W9NOjkEet9bF2vkzOufX72eVH8kZBIGtcBp1w==", + "license": "Apache-2.0", + "dependencies": { + "@gar/promise-retry": "^1.0.2", + "@sigstore/bundle": "^5.0.0", + "@sigstore/core": "^4.0.0", + "@sigstore/protobuf-specs": "^0.5.0", + "make-fetch-happen": "^16.0.0", + "proc-log": "^7.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/@sigstore/verify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sigstore/verify/-/verify-4.0.0.tgz", + "integrity": "sha512-yYQTYQkjkdp69M5f+XGOhX45RvgCwh0cz6r++hGRHi7G/NVPmIK7ISxY73fM5WVerIiYe/ZbVlMu47dDodBP6A==", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^5.0.0", + "@sigstore/core": "^4.0.0", + "@sigstore/protobuf-specs": "^0.5.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/agent-base": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz", + "integrity": "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==", + "license": "MIT", + "engines": { + "node": ">= 20" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/cacache": { + "version": "21.0.1", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-21.0.1.tgz", + "integrity": "sha512-pTwz/uj3Jyp6WXdJ6fWhR+7LVxVs6RyroQSn7KJwHsSxXuyGSp0pcMVcwSwTpCFq1X2YG8QBe0W+vN+cr0SwzA==", + "license": "ISC", + "dependencies": { + "@npmcli/fs": "^6.0.0", + "fs-minipass": "^3.0.0", + "glob": "^13.0.0", + "lru-cache": "^11.1.0", + "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": "^14.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/http-proxy-agent": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-9.1.0.tgz", + "integrity": "sha512-2NxoveTT58mjYT4n3RPTEfCZGLMbidoO8XEieXfpSYxu+PQJ1qpx4ypwH6N+uF9twBPIvRRgvkvW5HUTYWENig==", + "license": "MIT", + "dependencies": { + "agent-base": "9.0.0", + "debug": "^4.3.4", + "proxy-agent-negotiate": "1.1.0" + }, + "engines": { + "node": ">= 20" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/https-proxy-agent": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz", + "integrity": "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==", + "license": "MIT", + "dependencies": { + "agent-base": "9.0.0", + "debug": "^4.3.4", + "proxy-agent-negotiate": "1.1.0" + }, + "engines": { + "node": ">= 20" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/make-fetch-happen": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-16.0.1.tgz", + "integrity": "sha512-uUv1yxHzaKVVEPfcFeGSNov/Cehjv08ovlY8ImTljgL7Q+SiA0dAYLQ6SYVa2kkKqNj4Y3aZEI7xv2teadie0A==", + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@npmcli/agent": "^5.0.0", + "@npmcli/redact": "^5.0.0", + "cacache": "^21.0.0", + "http-cache-semantics": "^4.1.1", + "minipass": "^7.0.2", + "minipass-fetch": "^6.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^1.0.0", + "proc-log": "^7.0.0", + "ssri": "^14.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/minipass-fetch": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-6.0.0.tgz", + "integrity": "sha512-AWI8bKapGmgx/J0E6IGYSKj8TiHebZkmKWSs8raPSw8KXwgEAJ+Bw3+LSdXHR6T/RHKAWCOYk2MiLrYluaUU6w==", + "license": "MIT", + "dependencies": { + "minipass": "^7.0.3", + "minipass-sized": "^2.0.0", + "minizlib": "^3.0.1" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "optionalDependencies": { + "iconv-lite": "^0.7.2" + } + }, + "workspaces/libnpmpublish/node_modules/sigstore/node_modules/socks-proxy-agent": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-10.1.0.tgz", + "integrity": "sha512-WlMj/67cEJ6MDI1OcsnjuYKDNDoyPCCYZ249kuuXPiMDw9F8PXkVaQ7YWu3siTydfQ/4BEZcvGzu+aYvz7dDCQ==", + "license": "MIT", + "dependencies": { + "agent-base": "9.0.0", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 20" } }, "workspaces/libnpmsearch": { - "version": "7.0.6", + "version": "10.0.0-pre.0", "license": "ISC", "dependencies": { - "npm-registry-fetch": "^17.0.1" + "npm-registry-fetch": "^20.0.1" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "nock": "^13.3.3", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", + "nock": "^14.0.0", "tap": "^16.3.8" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "workspaces/libnpmteam": { - "version": "6.0.5", + "version": "9.0.0-pre.0", "license": "ISC", "dependencies": { "aproba": "^2.0.0", - "npm-registry-fetch": "^17.0.1" + "npm-registry-fetch": "^20.0.1" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "nock": "^13.3.3", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", + "nock": "^14.0.0", "tap": "^16.3.8" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "workspaces/libnpmversion": { - "version": "6.0.3", + "version": "9.0.0-pre.1", "license": "ISC", "dependencies": { - "@npmcli/git": "^5.0.7", - "@npmcli/run-script": "^8.1.0", - "json-parse-even-better-errors": "^3.0.2", - "proc-log": "^4.2.0", + "@npmcli/git": "^8.0.0", + "@npmcli/run-script": "^11.0.0", + "json-parse-even-better-errors": "^6.0.0", + "proc-log": "^7.0.0", "semver": "^7.3.7" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "require-inject": "^1.4.4", "tap": "^16.3.8" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } } } diff --git a/package.json b/package.json index 02e2de7f2d692..223f70c0d4393 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "version": "10.8.2", + "version": "12.0.0-pre.1", "name": "npm", "description": "a package manager for JavaScript", "workspaces": [ @@ -32,10 +32,6 @@ "bugs": { "url": "https://github.com/npm/cli/issues" }, - "directories": { - "doc": "./doc", - "man": "./man" - }, "main": "./index.js", "bin": { "npm": "bin/npm-cli.js", @@ -52,80 +48,82 @@ }, "dependencies": { "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/arborist": "^7.5.4", - "@npmcli/config": "^8.3.4", - "@npmcli/fs": "^3.1.1", - "@npmcli/map-workspaces": "^3.0.6", - "@npmcli/package-json": "^5.2.0", - "@npmcli/promise-spawn": "^7.0.2", - "@npmcli/redact": "^2.0.1", - "@npmcli/run-script": "^8.1.0", - "@sigstore/tuf": "^2.3.4", - "abbrev": "^2.0.0", + "@npmcli/arborist": "^10.0.0-pre.1", + "@npmcli/config": "^11.0.0-pre.1", + "@npmcli/fs": "^6.0.0", + "@npmcli/git": "^8.0.0", + "@npmcli/map-workspaces": "^6.0.0", + "@npmcli/metavuln-calculator": "^10.0.0", + "@npmcli/package-json": "^8.0.0", + "@npmcli/promise-spawn": "^10.0.0", + "@npmcli/redact": "^5.0.0", + "@npmcli/run-script": "^11.0.0", + "@sigstore/tuf": "^5.0.0", + "abbrev": "^5.0.0", "archy": "~1.0.0", - "cacache": "^18.0.3", - "chalk": "^5.3.0", - "ci-info": "^4.0.0", - "cli-columns": "^4.0.0", + "bin-links": "^7.0.0", + "cacache": "^21.0.1", + "chalk": "^5.6.2", + "ci-info": "^4.4.0", + "diff": "^8.0.2", "fastest-levenshtein": "^1.0.16", "fs-minipass": "^3.0.3", - "glob": "^10.4.2", + "glob": "^13.0.6", "graceful-fs": "^4.2.11", - "hosted-git-info": "^7.0.2", - "ini": "^4.1.3", - "init-package-json": "^6.0.3", - "is-cidr": "^5.1.0", - "json-parse-even-better-errors": "^3.0.2", - "libnpmaccess": "^8.0.6", - "libnpmdiff": "^6.1.4", - "libnpmexec": "^8.1.3", - "libnpmfund": "^5.0.12", - "libnpmhook": "^10.0.5", - "libnpmorg": "^6.0.6", - "libnpmpack": "^7.0.4", - "libnpmpublish": "^9.0.9", - "libnpmsearch": "^7.0.6", - "libnpmteam": "^6.0.5", - "libnpmversion": "^6.0.3", - "make-fetch-happen": "^13.0.1", - "minimatch": "^9.0.5", - "minipass": "^7.1.1", + "hosted-git-info": "^10.1.1", + "ini": "^7.0.0", + "init-package-json": "^9.0.0", + "is-cidr": "^7.0.0", + "json-parse-even-better-errors": "^6.0.0", + "libnpmaccess": "^11.0.0-pre.0", + "libnpmdiff": "^9.0.0-pre.0", + "libnpmexec": "^11.0.0-pre.0", + "libnpmfund": "^8.0.0-pre.0", + "libnpmorg": "^9.0.0-pre.0", + "libnpmpack": "^10.0.0-pre.1", + "libnpmpublish": "^12.0.0-pre.0", + "libnpmsearch": "^10.0.0-pre.0", + "libnpmteam": "^9.0.0-pre.0", + "libnpmversion": "^9.0.0-pre.1", + "make-fetch-happen": "^16.0.1", + "minimatch": "^10.2.5", + "minipass": "^7.1.3", "minipass-pipeline": "^1.2.4", "ms": "^2.1.2", - "node-gyp": "^10.1.0", - "nopt": "^7.2.1", - "normalize-package-data": "^6.0.2", - "npm-audit-report": "^5.0.0", - "npm-install-checks": "^6.3.0", - "npm-package-arg": "^11.0.2", - "npm-pick-manifest": "^9.1.0", - "npm-profile": "^10.0.0", - "npm-registry-fetch": "^17.1.0", - "npm-user-validate": "^2.0.1", - "p-map": "^4.0.0", - "pacote": "^18.0.6", - "parse-conflict-json": "^3.0.1", - "proc-log": "^4.2.0", + "node-gyp": "^13.0.0", + "nopt": "^10.0.1", + "npm-audit-report": "^8.0.0", + "npm-install-checks": "^9.0.0", + "npm-package-arg": "^14.0.0", + "npm-pick-manifest": "^12.0.0", + "npm-profile": "^13.0.1", + "npm-registry-fetch": "^20.0.1", + "npm-user-validate": "^5.0.0", + "p-map": "^7.0.4", + "pacote": "^22.0.0", + "parse-conflict-json": "^6.0.0", + "proc-log": "^7.0.0", "qrcode-terminal": "^0.12.0", - "read": "^3.0.1", - "semver": "^7.6.2", + "read": "^6.0.0", + "semver": "^7.8.4", "spdx-expression-parse": "^4.0.0", - "ssri": "^10.0.6", - "supports-color": "^9.4.0", - "tar": "^6.2.1", + "ssri": "^14.0.0", + "supports-color": "^10.2.2", + "tar": "^7.5.16", "text-table": "~0.2.0", - "tiny-relative-date": "^1.3.0", + "tiny-relative-date": "^2.0.2", "treeverse": "^3.0.0", - "validate-npm-package-name": "^5.0.1", - "which": "^4.0.0", - "write-file-atomic": "^5.0.1" + "validate-npm-package-name": "^8.0.0", + "which": "^7.0.0" }, "bundleDependencies": [ "@isaacs/string-locale-compare", "@npmcli/arborist", "@npmcli/config", "@npmcli/fs", + "@npmcli/git", "@npmcli/map-workspaces", + "@npmcli/metavuln-calculator", "@npmcli/package-json", "@npmcli/promise-spawn", "@npmcli/redact", @@ -133,10 +131,11 @@ "@sigstore/tuf", "abbrev", "archy", + "bin-links", "cacache", "chalk", "ci-info", - "cli-columns", + "diff", "fastest-levenshtein", "fs-minipass", "glob", @@ -150,7 +149,6 @@ "libnpmdiff", "libnpmexec", "libnpmfund", - "libnpmhook", "libnpmorg", "libnpmpack", "libnpmpublish", @@ -164,7 +162,6 @@ "ms", "node-gyp", "nopt", - "normalize-package-data", "npm-audit-report", "npm-install-checks", "npm-package-arg", @@ -187,28 +184,29 @@ "tiny-relative-date", "treeverse", "validate-npm-package-name", - "which", - "write-file-atomic" + "which" ], "devDependencies": { "@npmcli/docs": "^1.0.0", - "@npmcli/eslint-config": "^4.0.2", - "@npmcli/git": "^5.0.8", + "@npmcli/eslint-config": "^5.1.0", + "@npmcli/installed-package-contents": "^5.0.0", "@npmcli/mock-globals": "^1.0.0", "@npmcli/mock-registry": "^1.0.0", - "@npmcli/template-oss": "4.22.0", - "@tufjs/repo-mock": "^2.0.0", + "@npmcli/name-from-folder": "^5.0.0", + "@npmcli/node-gyp": "^6.0.0", + "@npmcli/template-oss": "5.1.1", + "@tufjs/repo-mock": "^5.0.0", "ajv": "^8.12.0", - "ajv-formats": "^2.1.1", + "ajv-formats": "^3.0.1", "ajv-formats-draft2019": "^1.6.1", "cli-table3": "^0.6.4", - "diff": "^5.2.0", - "nock": "^13.4.0", - "npm-packlist": "^8.0.2", - "remark": "^14.0.2", - "remark-gfm": "^3.0.1", - "remark-github": "^11.2.4", - "rimraf": "^5.0.5", + "diff": "^8.0.4", + "nock": "^14.0.0", + "npm-packlist": "^11.3.0", + "remark": "^15.0.1", + "remark-gfm": "^4.0.1", + "remark-github": "^12.0.0", + "rimraf": "^6.0.1", "spawk": "^1.7.1", "tap": "^16.3.9" }, @@ -218,22 +216,27 @@ "licenses": "npx licensee --production --errors-only", "test": "tap", "test:nocolor": "CI=true tap -Rclassic", - "test-all": "node . run test -ws -iwr --if-present", + "test-all": "node . run test --workspaces --include-workspace-root --if-present", "snap": "tap", "prepack": "node . run build -w docs", "posttest": "node . run lint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "node . run lint -- --fix", - "lint-all": "node . run lint -ws -iwr --if-present", + "lint": "node . run eslint", + "lintfix": "node . run eslint -- --fix", + "lint-all": "node . run lint --workspaces --include-workspace-root --if-present", "resetdeps": "node scripts/resetdeps.js", "rp-pull-request": "node scripts/update-authors.js", "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "test-env": [ "LC_ALL=sk" ], + "node-arg": [ + "--require", + "./scripts/disable-agent-for-tests.js" + ], "timeout": 600, "nyc-arg": [ "--exclude", @@ -253,11 +256,12 @@ }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "content": "./scripts/template-oss/root.js" + "version": "5.1.1", + "content": "./scripts/template-oss/root.js", + "updateNpm": false }, "license": "Artistic-2.0", "engines": { - "node": "^18.17.0 || >=20.5.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } } diff --git a/release-please-config.json b/release-please-config.json index 40a03db783638..04aa98d06c5c7 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -46,7 +46,6 @@ "workspaces/libnpmdiff": {}, "workspaces/libnpmexec": {}, "workspaces/libnpmfund": {}, - "workspaces/libnpmhook": {}, "workspaces/libnpmorg": {}, "workspaces/libnpmpack": {}, "workspaces/libnpmpublish": {}, @@ -54,7 +53,7 @@ "workspaces/libnpmteam": {}, "workspaces/libnpmversion": {} }, - "prerelease": false, + "prerelease": true, "group-pull-request-title-pattern": "chore: release ${version}", "pull-request-title-pattern": "chore: release${component} ${version}", "prerelease-type": "pre" diff --git a/scripts/backport.js b/scripts/backport.js new file mode 100644 index 0000000000000..4eaf6acacc8cc --- /dev/null +++ b/scripts/backport.js @@ -0,0 +1,153 @@ +const { execFileSync } = require('node:child_process') + +module.exports = async ({ github, context, core }) => { + const pr = context.payload.pull_request + const sha = process.env.MERGE_COMMIT_SHA + const { owner, repo } = context.repo + + // For 'labeled' events, only process the newly added label. + // For 'closed' (merged) events, process all backport labels on the PR. + const labels = context.payload.action === 'labeled' + ? [context.payload.label.name].filter(n => n.startsWith('backport:')) + : pr.labels.map(l => l.name).filter(n => n.startsWith('backport:')) + + if (!labels.length) { + core.info('No backport labels found, nothing to do') + return + } + + const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim() + + // Build cherry-pick args based on merge strategy: + // - Merge commit (2 parents): cherry-pick -m 1 + // - Squash (1 parent, single commit): cherry-pick that commit + // - Rebase (1 parent, N commits rebased onto base): cherry-pick the full range to preserve all conventional commits + const cherryPickArgs = await (async () => { + const parentCount = git('cat-file', '-p', sha) + .split('\n') + .filter(l => l.startsWith('parent ')).length + + if (parentCount > 1) { + core.info('Detected merge commit') + return ['-x', '-m', '1', sha] + } + + if (pr.commits > 1) { + // Could be squash or rebase. Rebase preserves commit subjects, squash does not. + const { data: prCommits } = await github.rest.pulls.listCommits({ + owner, repo, pull_number: pr.number, per_page: 100, + }) + const prSubjects = prCommits.map(c => c.commit.message.split('\n')[0]) + try { + const branchSubjects = git('log', '--format=%s', '--reverse', `${sha}~${prCommits.length}..${sha}`) + .split('\n') + if ( + branchSubjects.length === prSubjects.length && + branchSubjects.every((s, i) => s === prSubjects[i]) + ) { + core.info(`Detected rebase merge with ${prCommits.length} commits`) + return ['-x', `${sha}~${prCommits.length}..${sha}`] + } + } catch { + // Fall through to squash + } + core.info('Detected squash merge') + } + + return ['-x', sha] + })() + + const startRef = git('rev-parse', 'HEAD') + const results = [] + + for (const label of labels) { + const version = label.replace('backport:', '') + const target = `release/${version}` + const branch = `backport/${version}/${pr.number}` + + try { + // Target branch is available locally from fetch-depth: 0 + try { + git('rev-parse', '--verify', `refs/remotes/origin/${target}`) + } catch { + throw new Error(`Target branch \`${target}\` does not exist`) + } + + // Backport branch requires ls-remote since a parallel run may have created it after our checkout + try { + git('ls-remote', '--exit-code', 'origin', `refs/heads/${branch}`) + core.info(`Branch ${branch} already exists, skipping`) + continue + } catch { + // Expected — branch doesn't exist yet + } + + git('checkout', '-b', branch, `origin/${target}`) + git('cherry-pick', ...cherryPickArgs) + git('push', 'origin', branch) + + const { data: backportPr } = await github.rest.pulls.create({ + owner, + repo, + title: pr.title, + body: `Backport of #${pr.number} to \`${target}\`.`, + head: branch, + base: target, + }) + + // Trigger CI on the backport branch. Events from GITHUB_TOKEN don't trigger workflows, but workflow_dispatch is an explicit exception to that rule. + await github.rest.actions.createWorkflowDispatch({ + owner, repo, workflow_id: 'ci.yml', ref: branch, + }) + + results.push(`🎉 Backport to \`${target}\` created: #${backportPr.number}`) + core.info(`Created backport PR #${backportPr.number} for ${target}`) + } catch (error) { + core.error(`Backport to ${target} failed: ${error.message}`) + + results.push([ + `⚠️ Backport to \`${target}\` failed.`, + '', + 'This usually means the cherry-pick had conflicts. Please create a manual backport:', + '', + '```sh', + `git fetch origin ${target}`, + `git checkout -b ${branch} origin/${target}`, + `git cherry-pick ${cherryPickArgs.join(' ')}`, + '# resolve any conflicts, then:', + `git push origin ${branch}`, + '```', + '', + '
Error details', + '', + '```', + error.message, + '```', + '', + '
', + ].join('\n')) + } finally { + try { + git('cherry-pick', '--abort') + } catch { /* noop */ } + git('checkout', '-f', startRef) + try { + git('branch', '-D', branch) + } catch { /* noop */ } + } + } + + if (results.length) { + await github.rest.issues.createComment({ + owner, + repo, + issue_number: pr.number, + body: results.join('\n\n---\n\n'), + }) + } + + const failures = results.filter(r => r.startsWith('⚠️')).length + if (failures) { + core.setFailed(`${failures} backport(s) failed`) + } +} diff --git a/scripts/bundle-and-gitignore-deps.js b/scripts/bundle-and-gitignore-deps.js index 404162595e0e9..55938106158e9 100644 --- a/scripts/bundle-and-gitignore-deps.js +++ b/scripts/bundle-and-gitignore-deps.js @@ -214,7 +214,7 @@ const main = async () => { // Get all files within node_modules and remove the node_modules/ portion of // the path for processing since this list will go inside a gitignore at the // root of the node_modules dir. It also removes workspaces since those are - // symlinks and should not be commited into source control. + // symlinks and should not be committed into source control. const files = allFiles .filter(f => f.startsWith('node_modules/')) .map(f => f.replace(/^node_modules\//, '')) diff --git a/scripts/create-node-pr.js b/scripts/create-node-pr.js index 0a8bdd35162c0..c75647ffd0669 100644 --- a/scripts/create-node-pr.js +++ b/scripts/create-node-pr.js @@ -93,14 +93,14 @@ const getPrBody = async ({ releases, closePrs }) => { const { remark } = await import('remark') const { default: remarkGfm } = await import('remark-gfm') - const { default: remarkGithub } = await import('remark-github') + const { default: remarkGithub, defaultBuildUrl } = await import('remark-github') return remark() .use(remarkGfm) .use(remarkGithub, { repository: 'npm/cli', - // dont link mentions, but anything else make the link an explicit referance to npm/cli - buildUrl: (values, buildUrl) => values.type === 'mention' ? false : buildUrl(values), + // don't link mentions, but anything else make the link an explicit reference to npm/cli + buildUrl: (values) => values.type === 'mention' ? false : defaultBuildUrl(values), }) .process(prBody) .then(v => String(v)) @@ -197,7 +197,7 @@ const main = async (spec, branch = 'main', opts) => withTempDir(CWD, async (tmpD // get a list of all versions changelogs to add to the body of the PR // do this before we checkout our branch and make any changes const npmReleases = await Promise.all(newNpmVersions.map(async (v) => { - // dont include prereleases unless we are updating to a prerlease since we + // don't include prereleases unless we are updating to a prerelease since we // manually put all prerelease notes into the first stable major version if (v.prerelease.length && !npmVersion.prerelease.length) { return null diff --git a/scripts/dependency-graph.js b/scripts/dependency-graph.js index 4d80f5207d8c1..da9b04c14ae23 100644 --- a/scripts/dependency-graph.js +++ b/scripts/dependency-graph.js @@ -11,10 +11,36 @@ const { run, CWD, pkg, fs, EOL } = require('./util.js') // npx -p @npmcli/stafftools gh repos --json | json -a name | sort > scripts/npm-cli-repos.txt const repos = readFileSync(join(CWD, 'scripts', 'npm-cli-repos.txt'), 'utf-8').trim().split(os.EOL) +// Packages with known circular dependencies. This is typically something with arborist as a dependency which is also in arborist's dev dependencies. Not a problem if they're workspaces so we ignore repeats +const circular = new Set(['@npmcli/mock-registry']) + +// TODO Set.intersection/difference was added in node 22.11.0, once we're above that line we can use the builtin +// https://node.green/#ES2025-features-Set-methods-Set-prototype-intersection-- +function intersection (set1, set2) { + const result = new Set() + for (const item of set1) { + if (set2.has(item)) { + result.add(item) + } + } + return result +} + +function difference (set1, set2) { + const result = new Set() + for (const item of set1) { + if (!set2.has(item)) { + result.add(item) + } + } + return result +} + // these have a different package name than the repo name, and are ours. const aliases = { - semver: 'node-semver', abbrev: 'abbrev-js', + semver: 'node-semver', + which: 'node-which', } // These are entries in npm-cli-repos.txt that correlate to namespaced repos. @@ -29,6 +55,7 @@ const namespaced = [ 'git', 'installed-package-contents', 'lint', + 'mock-registry', 'map-workspaces', 'metavuln-calculator', 'move-file', @@ -91,6 +118,8 @@ const main = async function () { const [annotationsAll] = walk(tree, false) const out = [ + '', + '', '# npm dependencies', '', '## `github.com/npm/` only', @@ -114,6 +143,10 @@ const main = async function () { ` - ${hierarchyOurs.reverse().join(`${EOL} - `)}`, ] + fs.writeFile(join(CWD, 'DEPENDENCIES.json'), + JSON.stringify(hierarchyOurs.map(v => v.split(', ')), null, 2) + ) + return fs.writeFile(join(CWD, 'DEPENDENCIES.md'), out.join(EOL)) } @@ -136,7 +169,11 @@ const walk = function (tree, onlyOurs) { log.silly(dep, '::', [...dependedBy[dep]].join(', ')) log.silly('-'.repeat(80)) - if (!dependedBy[dep].size) { + // things that depend on us that are at the same level + const both = intersection(allDeps, dependedBy[dep]) + // ... minus the known circular dependencies + const neither = difference(both, circular) + if (!dependedBy[dep].size || !neither.size) { level.push(dep) foundDeps.add(dep) } @@ -173,9 +210,7 @@ const iterate = function (node, dependedBy, annotations, onlyOurs) { dependedBy[node.packageName] = new Set() } for (const [name, edge] of node.edgesOut) { - if ( - (!onlyOurs || isOurs(name)) && !node.dev - ) { + if ((!onlyOurs || isOurs(name)) && !node.dev) { if (!dependedBy[node.packageName].has(edge.name)) { dependedBy[node.packageName].add(edge.name) annotations.push(` ${stripName(node.packageName)}-->${escapeName(edge.name)};`) diff --git a/scripts/disable-agent-for-tests.js b/scripts/disable-agent-for-tests.js new file mode 100644 index 0000000000000..6645edd982163 --- /dev/null +++ b/scripts/disable-agent-for-tests.js @@ -0,0 +1,29 @@ +'use strict' + +// nock (v14+, built on @mswjs/interceptors) can only intercept requests made +// through the default global agent, not the custom agents @npmcli/agent +// returns. This preload (loaded via tap's node-arg --require, before any test +// code) hooks the module loader so that every copy of @npmcli/agent has its +// getAgent forced to return false as it is required. Routing requests through +// the default agent lets nock intercept them. There can be multiple nested +// copies of @npmcli/agent in the tree (e.g. under sigstore), so patching at +// load time covers them all regardless of nesting. +// +// When a proxy is configured the real implementation is used so that proxy +// validation (e.g. rejecting unsupported protocols) still happens. +const Module = require('node:module') + +const originalLoad = Module._load +Module._load = function (request, ...args) { + const loaded = originalLoad.call(this, request, ...args) + if (request === '@npmcli/agent' && loaded && typeof loaded.getAgent === 'function') { + const realGetAgent = loaded.getAgent + loaded.getAgent = (url, options) => { + if (options.proxy) { + return realGetAgent(url, options) + } + return false + } + } + return loaded +} diff --git a/scripts/npm-cli-repos.txt b/scripts/npm-cli-repos.txt index e69d02c7ec9bd..1d2b57e1252e4 100644 --- a/scripts/npm-cli-repos.txt +++ b/scripts/npm-cli-repos.txt @@ -1,18 +1,12 @@ abbrev-js agent -are-we-there-yet -benchmarks bin-links cacache cli cmd-shim -create-oss -disparity-colors documentation eslint-config fs -fs-minipass -gauge git hosted-git-info ignore-walk @@ -43,7 +37,6 @@ npm-pick-manifest npm-profile npm-registry-fetch npm-user-validate -npmlog package-json pacote parse-conflict-json @@ -54,15 +47,15 @@ promzard query read read-cmd-shim -read-package-json read-package-json-fast +redact rfcs run-script ssri stafftools statusboard -tap-nock template-oss +types unique-filename unique-slug validate-npm-package-name diff --git a/scripts/publish.js b/scripts/publish.js index a28bfd849120c..1d6e13e7f8eda 100644 --- a/scripts/publish.js +++ b/scripts/publish.js @@ -3,7 +3,8 @@ const { log } = require('proc-log') const pacote = require('pacote') const { read } = require('read') const Table = require('cli-table3') -const { run, git, npm, pkg: cli, spawn } = require('./util.js') +const { run, git, npm, pkgPath: cliPath, pkg: cli, spawn } = require('./util.js') +const fs = require('fs').promises const resetdeps = () => npm('run', 'resetdeps') @@ -49,22 +50,40 @@ const versionNotExists = async ({ name, version }) => { const getPublishes = async ({ force }) => { const publishPackages = [] - for (const { pkg } of await cli.mapWorkspaces({ public: true })) { + for (const { pkg, pkgPath } of await cli.mapWorkspaces({ public: true })) { + const updatePkg = async (cb) => { + const data = JSON.parse(await fs.readFile(pkgPath, 'utf8')) + const result = cb(data) + await fs.writeFile(pkgPath, JSON.stringify(result, null, 2)) + return result + } + if (force || await versionNotExists(pkg)) { publishPackages.push({ - workspace: true, + workspace: `--workspace=${pkg.name}`, name: pkg.name, version: pkg.version, + dependencies: pkg.dependencies, + devDependencies: pkg.devDependencies, tag: await getWorkspaceTag(pkg), + updatePkg, }) } } if (force || await versionNotExists(cli)) { publishPackages.push({ + workspace: '', name: cli.name, version: cli.version, tag: `next-${semver.major(cli.version)}`, + dependencies: cli.dependencies, + devDependencies: cli.devDependencies, + updatePkg: async (cb) => { + const result = cb(cli) + await fs.writeFile(cliPath, JSON.stringify(result, null, 2)) + return result + }, }) } @@ -72,9 +91,10 @@ const getPublishes = async ({ force }) => { } const main = async (opts) => { - const { isLocal, smokePublish, packDestination } = opts - const isPack = !!packDestination - const publishes = await getPublishes({ force: isPack }) + const { test, otp, dryRun, smokePublish, packDestination } = opts + + const hasPackDest = !!packDestination + const publishes = await getPublishes({ force: smokePublish }) if (!publishes.length) { throw new Error( @@ -88,13 +108,15 @@ const main = async (opts) => { table.push([publish.name, publish.version, publish.tag]) } + const preformOperations = hasPackDest ? ['publish', 'pack'] : ['publish'] + const confirmMessage = [ - `Ready to ${isPack ? 'pack' : 'publish'} the following packages:`, + `Ready to ${preformOperations.join(',')} the following packages:`, table.toString(), - isPack ? null : 'Ok to proceed? ', + smokePublish ? null : 'Ok to proceed? ', ].filter(Boolean).join('\n') - if (isPack) { + if (smokePublish) { log.info(confirmMessage) } else { const confirm = await read({ prompt: confirmMessage, default: 'y' }) @@ -109,7 +131,7 @@ const main = async (opts) => { await npm('rm', '--global', '--force', 'npm') await npm('link', '--force', '--ignore-scripts') - if (opts.test) { + if (test) { await npm('run', 'lint-all', '--ignore-scripts') await npm('run', 'postlint', '--ignore-scripts') await npm('run', 'test-all', '--ignore-scripts') @@ -117,28 +139,63 @@ const main = async (opts) => { await npm('prune', '--omit=dev', '--no-save', '--no-audit', '--no-fund') await npm('install', '-w', 'docs', '--ignore-scripts', '--no-audit', '--no-fund') - if (isLocal && smokePublish) { + + if (smokePublish) { log.info(`Skipping git dirty check due to local smoke publish test being run`) } else { await git.dirty() } + let count = -1 + + if (smokePublish) { + // when we have a smoke test run we'd want to bump the version or else npm will throw an error even with dry-run + // this is the equivalent of running `npm version prerelease`, but ensuring all internally used workflows are bumped + for (const publish of publishes) { + const { version } = await publish.updatePkg((pkg) => ({ ...pkg, version: `${pkg.version}-smoke.0` })) + for (const ipublish of publishes) { + if (ipublish.dependencies?.[publish.name]) { + await ipublish.updatePkg((pkg) => ({ + ...pkg, + dependencies: { + ...pkg.dependencies, + [publish.name]: version, + }, + })) + } + if (ipublish.devDependencies?.[publish.name]) { + await ipublish.updatePkg((pkg) => ({ + ...pkg, + devDependencies: { + ...pkg.devDependencies, + [publish.name]: version, + }, + })) + } + } + } + await npm('install') + } + for (const publish of publishes) { + log.info(`Publishing ${publish.name}@${publish.version} to ${publish.tag} ${count++}/${publishes.length}`) const workspace = publish.workspace && `--workspace=${publish.name}` const publishPkg = (...args) => npm('publish', workspace, `--tag=${publish.tag}`, ...args) - if (isPack) { + + if (hasPackDest) { await npm( 'pack', workspace, - opts.packDestination && `--pack-destination=${opts.packDestination}` + packDestination && `--pack-destination=${packDestination}` ) - if (smokePublish) { - await publishPkg('--dry-run') - } + } + + if (smokePublish) { + await publishPkg('--dry-run', '--ignore-scripts') } else { await publishPkg( - opts.dryRun && '--dry-run', - opts.otp && `--otp=${opts.otp === 'op' ? await op() : opts.otp}` + dryRun && '--dry-run', + otp && `--otp=${otp === 'op' ? await op() : otp}` ) } } diff --git a/scripts/smoke-publish-test.sh b/scripts/smoke-publish-test.sh deleted file mode 100755 index 1d08a0adf2bc8..0000000000000 --- a/scripts/smoke-publish-test.sh +++ /dev/null @@ -1,92 +0,0 @@ - #!/usr/bin/env bash - -set -eo pipefail - -IS_LOCAL="false" -IS_CI="true" - -if [ -z "$CI" ]; then - echo "Running locally will overwrite your globally installed npm." - GITHUB_SHA=$(git rev-parse HEAD) - RUNNER_TEMP=$(mktemp -d) - IS_LOCAL="true" - IS_CI="false" -fi - -if [ -z "$GITHUB_SHA" ]; then - echo "Error: GITHUB_SHA is required" - exit 1 -fi - -if [ -z "$RUNNER_TEMP" ]; then - echo "Error: RUNNER_TEMP is required" - exit 1 -fi - -ORIGINAL_GLOBAL_NPM_VERSION=$(npm --version) -if [ ${#ORIGINAL_GLOBAL_NPM_VERSION} -gt 40 ]; then - echo "Error: Global npm version already contains a git SHA ${ORIGINAL_GLOBAL_NPM_VERSION}" - exit 1 -fi - -ORIGINAL_LOCAL_NPM_VERSION=$(node . --version) -if [ ${#ORIGINAL_LOCAL_NPM_VERSION} -gt 40 ]; then - echo "Error: Local npm version already contains a git SHA ${ORIGINAL_LOCAL_NPM_VERSION}" - exit 1 -fi -NPM_VERSION="$ORIGINAL_LOCAL_NPM_VERSION-$GITHUB_SHA.0" - -# Only cleanup locally -if [ "$IS_LOCAL" == "true" ]; then - function cleanup { - npm pkg set version=$ORIGINAL_LOCAL_NPM_VERSION - node scripts/resetdeps.js - if [ "$(git rev-parse HEAD)" != "$GITHUB_SHA" ]; then - echo "===================================" - echo "===================================" - echo "HEAD is on a different commit." - echo "===================================" - echo "===================================" - fi - if [ "$(npm --version)" == "$NPM_VERSION" ]; then - echo "===================================" - echo "===================================" - echo "Global npm version has changed to $NPM_VERSION" - echo "Run the following to change it back" - echo "npm install npm@$ORIGINAL_GLOBAL_NPM_VERSION -g" - echo "===================================" - echo "===================================" - fi - } - trap cleanup EXIT -fi - -# Version the local source of npm with the current git sha and -# and pack and install it globally the same way we would if we -# were publishing it to the registry. The only difference is in the -# publish.js script which will only pack and not publish -node . version $NPM_VERSION --ignore-scripts --git-tag-version="$IS_CI" -node scripts/publish.js --pack-destination=$RUNNER_TEMP --smoke-publish=true --is-local="$IS_LOCAL" -NPM_TARBALL="$RUNNER_TEMP/npm-$NPM_VERSION.tgz" -node . install --global $NPM_TARBALL - -# Only run the tests if we are sure we have the right version -# otherwise the tests being run are pointless -NPM_GLOBAL_VERSION="$(npm --version)" -if [ "$NPM_GLOBAL_VERSION" != "$NPM_VERSION" ]; then - echo "global npm is not the correct version for smoke-publish" - echo "found: $NPM_GLOBAL_VERSION, expected: $NPM_VERSION" - exit 1 -fi - -# Install dev deps only for smoke tests so they can be run -node . install -w smoke-tests --ignore-scripts --no-audit --no-fund -# Run smoke tests with env vars so it uses the globally installed tarball we -# just packed/installed. The tacked on args at the end are only used for -# debugging locally when we want to pass args to the smoke-tests to limit the -# files being run or grep a test, etc. Also now set CI=true so we get more -# debug output in our tap tests -CI="true" SMOKE_PUBLISH_TARBALL="$NPM_TARBALL" npm test \ - -w smoke-tests \ - --ignore-scripts \ - -- "$@" diff --git a/scripts/smoke-tests.js b/scripts/smoke-tests.js new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/scripts/smoke-tests.sh b/scripts/smoke-tests.sh new file mode 100755 index 0000000000000..0acda09c26b38 --- /dev/null +++ b/scripts/smoke-tests.sh @@ -0,0 +1,92 @@ + #!/usr/bin/env bash + +set -eo pipefail + +IS_LOCAL="false" +IS_CI="true" + +if [ -z "$CI" ]; then + echo "Running locally will overwrite your globally installed npm." + GITHUB_SHA=$(git rev-parse HEAD) + RUNNER_TEMP=$(mktemp -d) + IS_LOCAL="true" + IS_CI="false" +fi + +if [ -z "$GITHUB_SHA" ]; then + echo "Error: GITHUB_SHA is required" + exit 1 +fi + +if [ -z "$RUNNER_TEMP" ]; then + echo "Error: RUNNER_TEMP is required" + exit 1 +fi + +ORIGINAL_GLOBAL_NPM_VERSION=$(npm --version) +if [ ${#ORIGINAL_GLOBAL_NPM_VERSION} -gt 40 ]; then + echo "Error: Global npm version already contains a git SHA ${ORIGINAL_GLOBAL_NPM_VERSION}" + exit 1 +fi + +ORIGINAL_LOCAL_NPM_VERSION=$(node . --version) +if [ ${#ORIGINAL_LOCAL_NPM_VERSION} -gt 40 ]; then + echo "Error: Local npm version already contains a git SHA ${ORIGINAL_LOCAL_NPM_VERSION}" + exit 1 +fi +NPM_VERSION="$ORIGINAL_LOCAL_NPM_VERSION-$GITHUB_SHA.0" + +# Only cleanup locally +if [ "$IS_LOCAL" == "true" ]; then + function cleanup { + npm pkg set version=$ORIGINAL_LOCAL_NPM_VERSION + node scripts/resetdeps.js + if [ "$(git rev-parse HEAD)" != "$GITHUB_SHA" ]; then + echo "===================================" + echo "===================================" + echo "HEAD is on a different commit." + echo "===================================" + echo "===================================" + fi + if [ "$(npm --version)" == "$NPM_VERSION" ]; then + echo "===================================" + echo "===================================" + echo "Global npm version has changed to $NPM_VERSION" + echo "Run the following to change it back" + echo "npm install npm@$ORIGINAL_GLOBAL_NPM_VERSION -g" + echo "===================================" + echo "===================================" + fi + } + trap cleanup EXIT +fi + +# Version the local source of npm with the current git sha and +# and pack and install it globally the same way we would if we +# were publishing it to the registry. The only difference is in the +# publish.js script which will only pack and not publish +node . version $NPM_VERSION --ignore-scripts --git-tag-version="$IS_CI" +node . pack . --pack-destination "$RUNNER_TEMP" +NPM_TARBALL="$RUNNER_TEMP/npm-$NPM_VERSION.tgz" +node . install --global $NPM_TARBALL + +# Only run the tests if we are sure we have the right version +# otherwise the tests being run are pointless +NPM_GLOBAL_VERSION="$(npm --version)" +if [ "$NPM_GLOBAL_VERSION" != "$NPM_VERSION" ]; then + echo "global npm is not the correct version for smoke-publish" + echo "found: $NPM_GLOBAL_VERSION, expected: $NPM_VERSION" + exit 1 +fi + +# Install dev deps only for smoke tests so they can be run +node . install -w smoke-tests --ignore-scripts --no-audit --no-fund +# Run smoke tests with env vars so it uses the globally installed tarball we +# just packed/installed. The tacked on args at the end are only used for +# debugging locally when we want to pass args to the smoke-tests to limit the +# files being run or grep a test, etc. Also now set CI=true so we get more +# debug output in our tap tests +CI="true" SMOKE_PUBLISH_TARBALL="$NPM_TARBALL" npm test \ + -w smoke-tests \ + --ignore-scripts \ + -- "$@" diff --git a/scripts/template-oss/CODEOWNERS.hbs b/scripts/template-oss/CODEOWNERS.hbs new file mode 100644 index 0000000000000..5f01583d13b69 --- /dev/null +++ b/scripts/template-oss/CODEOWNERS.hbs @@ -0,0 +1 @@ +* @npm/cli-team @npm/cli-triage diff --git a/scripts/template-oss/_job-release-integration-yml.hbs b/scripts/template-oss/_job-release-integration-yml.hbs index 4898733c57e4c..7d0ef9c1fa089 100644 --- a/scripts/template-oss/_job-release-integration-yml.hbs +++ b/scripts/template-oss/_job-release-integration-yml.hbs @@ -2,8 +2,8 @@ strategy: fail-fast: false matrix: nodeVersion: - - 18 - - 20 + - 22 + - 23 - nightly uses: ./.github/workflows/node-integration.yml with: diff --git a/scripts/template-oss/branch-specific-config.js b/scripts/template-oss/branch-specific-config.js index 9dfbedd7d2a05..3a2d749783525 100644 --- a/scripts/template-oss/branch-specific-config.js +++ b/scripts/template-oss/branch-specific-config.js @@ -1,5 +1,5 @@ // Leave this empty to use the default ciVersions from template-oss // This file is kept here to make it easier to apply template-oss // changes to other branches which might have different ciVersions -// or other conifg options +// or other config options module.exports = {} diff --git a/scripts/template-oss/ci-release-yml.hbs b/scripts/template-oss/ci-release-yml.hbs index 8ff869812a331..6ec27f1b2e9d2 100644 --- a/scripts/template-oss/ci-release-yml.hbs +++ b/scripts/template-oss/ci-release-yml.hbs @@ -1,23 +1,45 @@ -{{> ciReleaseYml }} +{{> ciReleaseYml }} - smoke-publish: - # This cant be tested on Windows because our node_modules directory - # checks in symlinks which are not supported there. This should be - # fixed somehow, because this means some forms of local development - # are likely broken on Windows as well. - {{> jobMatrixYml - jobName="Smoke Publish" - jobCheckout=(obj ref="${{ inputs.ref }}") - jobCreateCheck=(obj sha="${{ inputs.check-sha }}") - windowsCI=false - macCI=false - }} - - name: Smoke Publish - run: ./scripts/smoke-publish-test.sh - - name: Conclude Check - uses: LouisBrunner/checks-action@v1.6.0 - if: steps.create-check.outputs.check-id && always() - with: - token: $\{{ secrets.GITHUB_TOKEN }} - conclusion: $\{{ job.status }} - check_id: $\{{ steps.create-check.outputs.check-id }} + smoke-tests: + # This cant be tested on Windows because our node_modules directory + # checks in symlinks which are not supported there. This should be + # fixed somehow, because this means some forms of local development + # are likely broken on Windows as well. + {{> jobMatrixYml + jobName="Smoke Tests" + jobCheckout=(obj ref="${{ inputs.ref }}") + jobCreateCheck=(obj sha="${{ inputs.check-sha }}") + windowsCI=false + macCI=false + }} + - name: Smoke Tests + run: ./scripts/smoke-tests.sh + - name: Conclude Check + uses: LouisBrunner/checks-action@v1.6.0 + if: steps.create-check.outputs.check-id && always() + with: + token: $\{{ secrets.GITHUB_TOKEN }} + conclusion: $\{{ job.status }} + check_id: $\{{ steps.create-check.outputs.check-id }} + + publish-dryrun: + # This cant be tested on Windows because our node_modules directory + # checks in symlinks which are not supported there. This should be + # fixed somehow, because this means some forms of local development + # are likely broken on Windows as well. + {{> jobMatrixYml + jobName="Publish Dry-Run" + jobCheckout=(obj ref="${{ inputs.ref }}") + jobCreateCheck=(obj sha="${{ inputs.check-sha }}") + windowsCI=false + macCI=false + }} + - name: Publish Dry-Run + run: node ./scripts/publish.js --pack-destination=$RUNNER_TEMP --smoke-publish=true + - name: Conclude Check + uses: LouisBrunner/checks-action@v1.6.0 + if: steps.create-check.outputs.check-id && always() + with: + token: $\{{ secrets.GITHUB_TOKEN }} + conclusion: $\{{ job.status }} + check_id: $\{{ steps.create-check.outputs.check-id }} \ No newline at end of file diff --git a/scripts/template-oss/ci-yml.hbs b/scripts/template-oss/ci-yml.hbs index bdd4e3b5ccab5..386a3716deadd 100644 --- a/scripts/template-oss/ci-yml.hbs +++ b/scripts/template-oss/ci-yml.hbs @@ -5,12 +5,49 @@ - name: Check Licenses run: {{rootNpmPath}} run licenses - smoke-tests: - {{> jobYml jobName="Smoke Tests" }} - - name: Run Smoke Tests - run: {{rootNpmPath}} test -w smoke-tests --ignore-scripts - - name: Check Git Status - run: node scripts/git-dirty.js + smoke-tests: + # This cant be tested on Windows because our node_modules directory + # checks in symlinks which are not supported there. This should be + # fixed somehow, because this means some forms of local development + # are likely broken on Windows as well. + {{> jobYml + jobName="Smoke Tests" + jobCheckout=(obj ref="${{ inputs.ref }}") + jobCreateCheck=(obj sha="${{ inputs.check-sha }}") + windowsCI=false + macCI=false + }} + - name: Smoke Tests + run: ./scripts/smoke-tests.sh + - name: Conclude Check + uses: LouisBrunner/checks-action@v1.6.0 + if: steps.create-check.outputs.check-id && always() + with: + token: $\{{ secrets.GITHUB_TOKEN }} + conclusion: $\{{ job.status }} + check_id: $\{{ steps.create-check.outputs.check-id }} + + publish-dryrun: + # This cant be tested on Windows because our node_modules directory + # checks in symlinks which are not supported there. This should be + # fixed somehow, because this means some forms of local development + # are likely broken on Windows as well. + {{> jobYml + jobName="Publish Dry-Run" + jobCheckout=(obj ref="${{ inputs.ref }}") + jobCreateCheck=(obj sha="${{ inputs.check-sha }}") + windowsCI=false + macCI=false + }} + - name: Publish Dry-Run + run: node ./scripts/publish.js --pack-destination=$RUNNER_TEMP --smoke-publish=true + - name: Conclude Check + uses: LouisBrunner/checks-action@v1.6.0 + if: steps.create-check.outputs.check-id && always() + with: + token: $\{{ secrets.GITHUB_TOKEN }} + conclusion: $\{{ job.status }} + check_id: $\{{ steps.create-check.outputs.check-id }} windows-shims: name: Windows Shims Tests diff --git a/scripts/template-oss/create-node-pr-yml.hbs b/scripts/template-oss/create-node-pr-yml.hbs index 80279c02220e8..04d217eb9dc8e 100644 --- a/scripts/template-oss/create-node-pr-yml.hbs +++ b/scripts/template-oss/create-node-pr-yml.hbs @@ -14,6 +14,9 @@ on: dryRun: description: "Setting this to anything will run all the steps except opening the PR" +permissions: + contents: write + jobs: create-pull-request: {{> jobYml jobName="Create Node PR" jobCheckout=(obj fetch-depth=0) }} diff --git a/scripts/template-oss/index.js b/scripts/template-oss/index.js index 0f214723f558c..ab4d034d1d8f4 100644 --- a/scripts/template-oss/index.js +++ b/scripts/template-oss/index.js @@ -4,4 +4,5 @@ module.exports = { // This is needed while workspaces and npm have different engines. // TODO: make npm and its workspaces always use the same engines and delete this. npm: 'npm', + updateNpm: false, } diff --git a/scripts/template-oss/node-integration-yml.hbs b/scripts/template-oss/node-integration-yml.hbs index 4632aae9aa98e..9b4391d3991f2 100644 --- a/scripts/template-oss/node-integration-yml.hbs +++ b/scripts/template-oss/node-integration-yml.hbs @@ -78,7 +78,7 @@ jobs: echo "::group::extracting source from $nodeUrl" mkdir -p "$sourceDir" - curl -sSL "$nodeUrl" | tar xz -C "$sourceDir" --strip=1 + curl -sSL "$nodeUrl" | tar xz -C "$sourceDir" --strip=1 echo "::endgroup::" echo "::group::cloning npm" @@ -135,7 +135,7 @@ jobs: echo "build=$targetFile" >> $GITHUB_OUTPUT echo "::endgroup::" - name: upload artifacts - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: nodejs-$\{{ steps.build-nodejs.outputs.nodeVersion }} path: | @@ -154,7 +154,7 @@ jobs: with: override_cache_key: nodejs-$\{{ inputs.nodeVersion }} - name: download artifacts - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: nodejs-$\{{ needs.build-nodejs.outputs.nodeVersion }} - name: test nodejs @@ -171,7 +171,7 @@ jobs: - build-nodejs steps: - name: download artifacts - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: nodejs-$\{{ needs.build-nodejs.outputs.nodeVersion }} path: $\{{ runner.temp }} @@ -359,7 +359,7 @@ jobs: include: $\{{ fromJson(needs.generate-matrix.outputs.matrix) }} steps: - name: download artifacts - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: nodejs-$\{{ needs.build-nodejs.outputs.nodeVersion }} path: $\{{ runner.temp }} diff --git a/scripts/template-oss/package-json.hbs b/scripts/template-oss/package-json.hbs index a70a944b171a1..26070f88647ec 100644 --- a/scripts/template-oss/package-json.hbs +++ b/scripts/template-oss/package-json.hbs @@ -3,12 +3,12 @@ "node": {{! Set the CLI and private workspaces to the same version }} {{~#if isRoot~}} - "^18.17.0 || >=20.5.0" + "^22.22.2 || ^24.15.0 || >=26.0.0" {{~else~}}{{~#if isPrivate~}} - "^18.17.0 || >=20.5.0" + "^22.22.2 || ^24.15.0 || >=26.0.0" {{~else~}} {{! All public workspaces get this version }} - "^16.14.0 || >=18.0.0" + "^22.22.2 || ^24.15.0 || >=26.0.0" {{~/if~}}{{~/if~}} } } diff --git a/scripts/template-oss/release-please-config-json.hbs b/scripts/template-oss/release-please-config-json.hbs index d3b59ea7227cd..55cf73669690a 100644 --- a/scripts/template-oss/release-please-config-json.hbs +++ b/scripts/template-oss/release-please-config-json.hbs @@ -1,4 +1,5 @@ { + "prerelease-type": "pre", "packages": { "{{ pkgPath }}": { {{#if isRoot}} diff --git a/scripts/template-oss/root.js b/scripts/template-oss/root.js index fb2d964a3f993..3771c2b09078f 100644 --- a/scripts/template-oss/root.js +++ b/scripts/template-oss/root.js @@ -16,6 +16,7 @@ module.exports = { }, rootRepo: { add: { + '.github/CODEOWNERS': 'CODEOWNERS.hbs', '.github/ISSUE_TEMPLATE/bug.yml': false, '.github/ISSUE_TEMPLATE/config.yml': false, '.github/dependabot.yml': false, @@ -60,6 +61,7 @@ module.exports = { '/node_modules/', '/index.js', '/DEPENDENCIES.md', + '/DEPENDENCIES.json', '/CONTRIBUTING.md', '/configure', '/AUTHORS', diff --git a/scripts/util.js b/scripts/util.js index f6f9cbc9300ba..838bac5a6bd3f 100644 --- a/scripts/util.js +++ b/scripts/util.js @@ -12,17 +12,19 @@ const mapWorkspaces = require('@npmcli/map-workspaces') const EOL = '\n' const CWD = resolve(__dirname, '..') +const rootPkgPath = join(CWD, 'package.json') const pkg = require(join(CWD, 'package.json')) pkg.mapWorkspaces = async ({ public = false } = {}) => { const ws = [] for (const [name, path] of await mapWorkspaces({ pkg })) { - const pkgJson = require(join(path, 'package.json')) + const pkgPath = join(path, 'package.json') + const pkgJson = require(pkgPath) if (public && pkgJson.private) { continue } - ws.push({ name, path, pkg: pkgJson }) + ws.push({ name, path, pkgPath, pkg: pkgJson }) } return ws } @@ -205,6 +207,7 @@ const run = async (main, { redact } = {}) => { module.exports = { CWD, pkg, + pkgPath: rootPkgPath, run, fs, spawn, diff --git a/smoke-tests/.gitignore b/smoke-tests/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/smoke-tests/.gitignore +++ b/smoke-tests/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/smoke-tests/package.json b/smoke-tests/package.json index 6c5d61e635b2d..03cd9d2528e6d 100644 --- a/smoke-tests/package.json +++ b/smoke-tests/package.json @@ -4,13 +4,14 @@ "version": "1.0.1", "private": true, "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", "test": "tap", - "posttest": "npm run lint" + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", @@ -18,20 +19,20 @@ "directory": "smoke-tests" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", + "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-registry": "^1.0.0", - "@npmcli/promise-spawn": "^7.0.2", - "@npmcli/template-oss": "4.22.0", + "@npmcli/promise-spawn": "^10.0.0", + "@npmcli/template-oss": "5.1.1", "proxy": "^2.1.1", - "semver": "^7.5.4", + "rimraf": "^6.0.1", "tap": "^16.3.8", - "which": "^4.0.0" + "which": "^7.0.0" }, "author": "GitHub Inc.", "license": "ISC", "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../scripts/template-oss/index.js" }, "tap": { @@ -49,6 +50,6 @@ "lib/" ], "engines": { - "node": "^18.17.0 || >=20.5.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } } diff --git a/smoke-tests/tap-snapshots/test/index.js.test.cjs b/smoke-tests/tap-snapshots/test/index.js.test.cjs index 69c9ceab87fd0..fae7823fc47ee 100644 --- a/smoke-tests/tap-snapshots/test/index.js.test.cjs +++ b/smoke-tests/tap-snapshots/test/index.js.test.cjs @@ -21,16 +21,16 @@ npm help npm more involved overview All 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, hook, 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, uninstall, unpublish, unstar, update, version, - view, whoami + access, approve-scripts, audit, bugs, cache, ci, + completion, config, dedupe, deny-scripts, 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, patch, ping, pkg, prefix, + profile, prune, publish, query, rebuild, repo, restart, + root, run, sbom, search, set, stage, start, stop, team, + test, token, trust, undeprecate, uninstall, unpublish, + update, version, view, whoami Specify configs in the ini-formatted file: {NPM}/{TESTDIR}/home/.npmrc @@ -45,7 +45,7 @@ npm {NPM} exports[`test/index.js TAP basic npm ci > should throw mismatch deps in lock file error 1`] = ` npm error code EUSAGE npm error -npm error \`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. +npm error \`npm ci\` can only install packages when your package.json and package-lock.json are in sync. Please update your lock file with \`npm install\` before continuing. npm error npm error Invalid: lock file's abbrev@1.0.4 does not satisfy abbrev@1.1.1 npm error @@ -58,10 +58,84 @@ npm error Options: npm error [--install-strategy ] [--legacy-bundling] npm error [--global-style] [--omit [--omit ...]] npm error [--include [--include ...]] -npm error [--strict-peer-deps] [--foreground-scripts] [--ignore-scripts] [--no-audit] +npm error [--strict-peer-deps] [--foreground-scripts] [--ignore-scripts] +npm error [--allow-directory ] [--allow-file ] +npm error [--allow-git ] [--allow-remote ] +npm error [--allow-scripts [--allow-scripts ...]] +npm error [--strict-allow-scripts] [--dangerously-allow-all-scripts] [--no-audit] npm error [--no-bin-links] [--no-fund] [--dry-run] npm error [-w|--workspace [-w|--workspace ...]] -npm error [-ws|--workspaces] [--include-workspace-root] [--install-links] +npm error [--workspaces] [--include-workspace-root] [--install-links] +npm error +npm error --install-strategy +npm error Sets the strategy for installing packages in node_modules. +npm error +npm error --legacy-bundling +npm error Instead of hoisting package installs in \`node_modules\`, install packages +npm error +npm error --global-style +npm error Only install direct dependencies in the top level \`node_modules\`, +npm error +npm error --omit +npm error Dependency types to omit from the installation tree on disk. +npm error +npm error --include +npm error Option that allows for defining which types of dependencies to install. +npm error +npm error --strict-peer-deps +npm error If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_ +npm error +npm error --foreground-scripts +npm error Run all build scripts (ie, \`preinstall\`, \`install\`, and +npm error +npm error --ignore-scripts +npm error If true, npm does not run scripts specified in package.json files. +npm error +npm error --allow-directory +npm error Limits the ability for npm to install dependencies from directories. +npm error +npm error --allow-file +npm error Limits the ability for npm to install dependencies from tarball files. +npm error +npm error --allow-git +npm error Limits the ability for npm to fetch dependencies from git references. +npm error +npm error --allow-remote +npm error Limits the ability for npm to fetch dependencies from urls. +npm error +npm error --allow-scripts +npm error Comma-separated list of packages whose install-time lifecycle scripts +npm error +npm error --strict-allow-scripts +npm error If \`true\`, turn the install-script policy from a warning into a hard +npm error +npm error --dangerously-allow-all-scripts +npm error If \`true\`, bypass the \`allowScripts\` policy entirely and run every +npm error +npm error --audit +npm error When "true" submit audit reports alongside the current npm command to the +npm error +npm error --bin-links +npm error Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package +npm error +npm error --fund +npm error When "true" displays the message at the end of each \`npm install\` +npm error +npm error --dry-run +npm error Indicates that you don't want npm to make any changes and that it should +npm error +npm error -w|--workspace +npm error Enable running a command in the context of the configured workspaces of the +npm error +npm error --workspaces +npm error Set to true to run the command in the context of **all** configured +npm error +npm error --include-workspace-root +npm error Include the workspace root when workspaces are enabled for a command. +npm error +npm error --install-links +npm error When set file: protocol dependencies will be packed and installed as +npm error npm error npm error aliases: clean-install, ic, install-clean, isntall-clean npm error @@ -110,14 +184,13 @@ Wrote to {NPM}/{TESTDIR}/project/package.json: { "name": "project", "version": "1.0.0", + "description": "", "main": "index.js", "scripts": { "test": "echo /"Error: no test specified/" && exit 1" }, "keywords": [], - "author": "", - "license": "ISC", - "description": "" + "type": "commonjs" } ` @@ -133,7 +206,6 @@ Object { "devDependencies": Object { "promise-all-reject-late": "^5.0.0", }, - "license": "ISC", "name": "project", "version": "1.0.0", }, @@ -157,7 +229,6 @@ Object { exports[`test/index.js TAP basic npm install dev dep > should have expected dev dep added package.json result 1`] = ` Object { - "author": "", "dependencies": Object { "abbrev": "^1.0.4", }, @@ -166,12 +237,12 @@ Object { "promise-all-reject-late": "^5.0.0", }, "keywords": Array [], - "license": "ISC", "main": "index.js", "name": "project", "scripts": Object { "test": "echo /"Error: no test specified/" && exit 1", }, + "type": "commonjs", "version": "1.0.0", } ` @@ -196,7 +267,6 @@ Object { "dependencies": Object { "abbrev": "^1.0.4", }, - "license": "ISC", "name": "project", "version": "1.0.0", }, @@ -212,18 +282,17 @@ Object { exports[`test/index.js TAP basic npm install prodDep@version > should have expected package.json result 1`] = ` Object { - "author": "", "dependencies": Object { "abbrev": "^1.0.4", }, "description": "", "keywords": Array [], - "license": "ISC", "main": "index.js", "name": "project", "scripts": Object { "test": "echo /"Error: no test specified/" && exit 1", }, + "type": "commonjs", "version": "1.0.0", } ` @@ -241,32 +310,29 @@ abbrev 1.0.4 1.1.1 1.1.1 node_modules/abbrev project exports[`test/index.js TAP basic npm pkg > should have expected npm pkg delete modified package.json result 1`] = ` Object { - "author": "", "dependencies": Object { "abbrev": "^1.0.4", }, "description": "", "keywords": Array [], - "license": "ISC", "main": "index.js", "name": "project", "scripts": Object { "hello": "echo Hello", "test": "echo /"Error: no test specified/" && exit 1", }, + "type": "commonjs", "version": "1.0.0", } ` exports[`test/index.js TAP basic npm pkg > should have expected npm pkg set modified package.json result 1`] = ` Object { - "author": "", "dependencies": Object { "abbrev": "^1.0.4", }, "description": "", "keywords": Array [], - "license": "ISC", "main": "index.js", "name": "project", "scripts": Object { @@ -278,6 +344,7 @@ Object { "LC_ALL=sk", ], }, + "type": "commonjs", "version": "1.0.0", } ` @@ -287,7 +354,7 @@ exports[`test/index.js TAP basic npm pkg > should have expected pkg delete outpu ` exports[`test/index.js TAP basic npm pkg > should have expected pkg get output 1`] = ` -"ISC" + ` exports[`test/index.js TAP basic npm pkg > should have expected pkg set output 1`] = ` @@ -295,32 +362,22 @@ exports[`test/index.js TAP basic npm pkg > should have expected pkg set output 1 ` exports[`test/index.js TAP basic npm pkg > should print package.json contents 1`] = ` -{ - "name": "project", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo /"Error: no test specified/" && exit 1", - "hello": "echo Hello" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", - "dependencies": { - "abbrev": "^1.0.4" - }, - "tap": { - "test-env": [ - "LC_ALL=sk" - ] - } +name = 'project' +version = '1.0.0' +description = '' +main = 'index.js' +scripts = { + test: 'echo "Error: no test specified" && exit 1', + hello: 'echo Hello' } +keywords = [] +type = 'commonjs' +dependencies = { abbrev: '^1.0.4' } +tap = { 'test-env': [ 'LC_ALL=sk' ] } ` exports[`test/index.js TAP basic npm pkg set scripts > should have expected script added package.json result 1`] = ` Object { - "author": "", "dependencies": Object { "abbrev": "^1.0.4", }, @@ -329,13 +386,13 @@ Object { "promise-all-reject-late": "^5.0.0", }, "keywords": Array [], - "license": "ISC", "main": "index.js", "name": "project", "scripts": Object { "hello": "echo Hello", "test": "echo /"Error: no test specified/" && exit 1", }, + "type": "commonjs", "version": "1.0.0", } ` @@ -348,10 +405,7 @@ exports[`test/index.js TAP basic npm prefix > should have expected prefix output {NPM}/{TESTDIR}/project ` -exports[`test/index.js TAP basic npm run-script > should have expected run-script output 1`] = ` -> project@1.0.0 hello -> echo Hello - +exports[`test/index.js TAP basic npm run > should have expected run output 1`] = ` Hello ` @@ -364,7 +418,6 @@ Object { "dependencies": Object { "abbrev": "^1.0.4", }, - "license": "ISC", "name": "project", "version": "1.0.0", }, @@ -380,19 +433,18 @@ Object { exports[`test/index.js TAP basic npm uninstall > should have expected uninstall package.json result 1`] = ` Object { - "author": "", "dependencies": Object { "abbrev": "^1.0.4", }, "description": "", "keywords": Array [], - "license": "ISC", "main": "index.js", "name": "project", "scripts": Object { "hello": "echo Hello", "test": "echo /"Error: no test specified/" && exit 1", }, + "type": "commonjs", "version": "1.0.0", } ` @@ -413,7 +465,6 @@ Object { "devDependencies": Object { "promise-all-reject-late": "^5.0.0", }, - "license": "ISC", "name": "project", "version": "1.0.0", }, @@ -437,7 +488,6 @@ Object { exports[`test/index.js TAP basic npm update dep > should have expected update package.json result 1`] = ` Object { - "author": "", "dependencies": Object { "abbrev": "^1.0.4", }, @@ -446,13 +496,13 @@ Object { "promise-all-reject-late": "^5.0.0", }, "keywords": Array [], - "license": "ISC", "main": "index.js", "name": "project", "scripts": Object { "hello": "echo Hello", "test": "echo /"Error: no test specified/" && exit 1", }, + "type": "commonjs", "version": "1.0.0", } ` diff --git a/smoke-tests/test/fixtures/setup.js b/smoke-tests/test/fixtures/setup.js index 18492d0d52f8f..2d0c54c984243 100644 --- a/smoke-tests/test/fixtures/setup.js +++ b/smoke-tests/test/fixtures/setup.js @@ -73,7 +73,9 @@ const getCleanPaths = async () => { }) } -module.exports = async (t, { testdir = {}, debug, mockRegistry = true, useProxy = false } = {}) => { +module.exports = async (t, { + testdir = {}, debug, mockRegistry = true, strictRegistryNock = true, useProxy = false, +} = {}) => { const debugLog = debug || CI ? (...a) => t.comment(...a) : () => {} debugLog({ SMOKE_PUBLISH_TARBALL, CI }) @@ -103,7 +105,7 @@ module.exports = async (t, { testdir = {}, debug, mockRegistry = true, useProxy tap: t, registry: MOCK_REGISTRY, debug, - strict: true, + strict: strictRegistryNock, }) const proxyEnv = {} diff --git a/smoke-tests/test/index.js b/smoke-tests/test/index.js index 48ab12ea98e53..0daf28ae9bf6c 100644 --- a/smoke-tests/test/index.js +++ b/smoke-tests/test/index.js @@ -182,10 +182,10 @@ t.test('basic', async t => { ) }) - await t.test('npm run-script', async t => { - const cmdRes = await npm('run', 'hello') + await t.test('npm run', async t => { + const cmdRes = await npm('run-script', 'hello') - t.matchSnapshot(cmdRes.stdout, 'should have expected run-script output') + t.matchSnapshot(cmdRes.stdout, 'should have expected run output') }) await t.test('npm prefix', async t => { diff --git a/smoke-tests/test/large-install.js b/smoke-tests/test/large-install.js index 460205c673182..7b2cfae93de0a 100644 --- a/smoke-tests/test/large-install.js +++ b/smoke-tests/test/large-install.js @@ -29,9 +29,7 @@ const runTest = async (t, { lowMemory } = {}) => { // should be investigated. t.test('large install', async t => { const { stdout } = await runTest(t) - // As a bonus this test asserts that this package-lock always - // installs the same number of packages. - t.match(stdout, `added 126${process.platform === 'linux' ? 4 : 5} packages in`) + t.match(stdout, /added \d+ packages/) }) t.test('large install, no lock and low memory', async t => { diff --git a/smoke-tests/test/npm-replace-global.js b/smoke-tests/test/npm-replace-global.js index 3514549aa40cd..c53beb10875af 100644 --- a/smoke-tests/test/npm-replace-global.js +++ b/smoke-tests/test/npm-replace-global.js @@ -103,6 +103,7 @@ t.test('publish and replace global self', async t => { getPaths, paths: { globalBin, globalNodeModules, cache }, } = await setupNpmGlobal(t, { + strictRegistryNock: false, testdir: { home: { '.npmrc': `//${setup.MOCK_REGISTRY.host}/:_authToken = test-token`, @@ -143,7 +144,7 @@ t.test('publish and replace global self', async t => { } return false }).reply(201, {}) - await npmLocal('publish', { proxy: true, force: true }) + await npmLocal('publish', '--tag=smoke-test', { proxy: true, force: true }) t.comment(JSON.stringify(publishedPackument, null, 2)) diff --git a/smoke-tests/test/pack-json-output.js b/smoke-tests/test/pack-json-output.js index 59a8e2cded66f..3457ada56f626 100644 --- a/smoke-tests/test/pack-json-output.js +++ b/smoke-tests/test/pack-json-output.js @@ -7,6 +7,6 @@ t.test('pack --json returns only json on stdout', async t => { const { stderr, stdout } = await npmLocal('pack', '--json', { force: true }) - t.match(stderr, /> npm@.* prepack\n/, 'stderr has banner') + t.match(stderr, /npm notice run npm@.* prepack\n/, 'stderr has banner') t.ok(JSON.parse(stdout), 'stdout can be parsed as json') }) diff --git a/tap-snapshots/test/lib/cli/exit-handler.js.test.cjs b/tap-snapshots/test/lib/cli/exit-handler.js.test.cjs index fd68eea57795b..29865aadf56ed 100644 --- a/tap-snapshots/test/lib/cli/exit-handler.js.test.cjs +++ b/tap-snapshots/test/lib/cli/exit-handler.js.test.cjs @@ -6,7 +6,6 @@ */ 'use strict' exports[`test/lib/cli/exit-handler.js TAP handles unknown error with logs and debug file > debug file contents 1`] = ` -XX timing npm:load:whichnode Completed in {TIME}ms XX silly config load:file:{CWD}/npmrc XX silly config load:file:{CWD}/prefix/.npmrc XX silly config load:file:{CWD}/home/.npmrc @@ -36,7 +35,6 @@ XX error A complete log of this run can be found in: {CWD}/cache/_logs/{DATE}-de ` exports[`test/lib/cli/exit-handler.js TAP handles unknown error with logs and debug file > logs 1`] = ` -timing npm:load:whichnode Completed in {TIME}ms silly config load:file:{CWD}/npmrc silly config load:file:{CWD}/prefix/.npmrc silly config load:file:{CWD}/home/.npmrc diff --git a/tap-snapshots/test/lib/cli/update-notifier.js.test.cjs b/tap-snapshots/test/lib/cli/update-notifier.js.test.cjs index 244d5216340f8..8736ee4623cd4 100644 --- a/tap-snapshots/test/lib/cli/update-notifier.js.test.cjs +++ b/tap-snapshots/test/lib/cli/update-notifier.js.test.cjs @@ -5,6 +5,14 @@ * Make sure to inspect the output below. Do not ignore changes! */ 'use strict' +exports[`test/lib/cli/update-notifier.js TAP notification situation with engine compatibility > must match snapshot 1`] = ` + +New minor version of npm available! 123.420.70 -> 123.421.60 +Changelog: https://github.com/npm/cli/releases/tag/v123.421.60 +To update run: npm install -g npm@123.421.60 + +` + exports[`test/lib/cli/update-notifier.js TAP notification situations 122.420.69 - color=always > must match snapshot 1`] = ` New major version of npm available! 122.420.69 -> 123.420.69 diff --git a/tap-snapshots/test/lib/commands/audit.js.test.cjs b/tap-snapshots/test/lib/commands/audit.js.test.cjs index 21c22b26c12e6..3a4cec0d6cead 100644 --- a/tap-snapshots/test/lib/commands/audit.js.test.cjs +++ b/tap-snapshots/test/lib/commands/audit.js.test.cjs @@ -305,6 +305,7 @@ audited 1 package in xxx 1 package has a verified registry signature 1 package has a verified attestation +(use --json --include-attestations to view attestation details) ` exports[`test/lib/commands/audit.js TAP audit signatures with valid signatures > must match snapshot 1`] = ` @@ -331,21 +332,6 @@ audited 2 packages in xxx 2 packages have verified registry signatures ` -exports[`test/lib/commands/audit.js TAP fallback audit > must match snapshot 1`] = ` -# npm audit report - -test-dep-a 1.0.0 -Severity: high -Test advisory 100 - https://github.com/advisories/GHSA-100 -fix available via \`npm audit fix\` -node_modules/test-dep-a - -1 high severity vulnerability - -To address all issues, run: - npm audit fix -` - exports[`test/lib/commands/audit.js TAP json audit > must match snapshot 1`] = ` { "auditReportVersion": 2, diff --git a/tap-snapshots/test/lib/commands/cache.js.test.cjs b/tap-snapshots/test/lib/commands/cache.js.test.cjs index 1cd699453478e..d5ce43922f024 100644 --- a/tap-snapshots/test/lib/commands/cache.js.test.cjs +++ b/tap-snapshots/test/lib/commands/cache.js.test.cjs @@ -41,6 +41,82 @@ make-fetch-happen:request-cache:https://registry.npmjs.org/foo make-fetch-happen:request-cache:https://registry.npmjs.org/foo/-/foo-1.2.3-beta.tgz ` +exports[`test/lib/commands/cache.js TAP cache npx info: valid and invalid entry > shows invalid package info 1`] = ` +invalid npx cache entry with key deadbeef +location: {CWD}/cache/_npx/deadbeef + +invalid npx cache entry with key badc0de +location: {CWD}/cache/_npx/badc0de +` + +exports[`test/lib/commands/cache.js TAP cache npx info: valid and invalid entry > shows valid package info 1`] = ` +invalid npx cache entry with key deadbeef +location: {CWD}/cache/_npx/deadbeef +` + +exports[`test/lib/commands/cache.js TAP cache npx info: valid entry with _npx directory package > shows valid package info with _npx directory package 1`] = ` +valid npx cache entry with key valid123 +location: {CWD}/cache/_npx/valid123 +packages: +- /path/to/valid-package +` + +exports[`test/lib/commands/cache.js TAP cache npx info: valid entry with _npx packages > shows valid package info with _npx packages 1`] = ` +valid npx cache entry with key valid123 +location: {CWD}/cache/_npx/valid123 +packages: +- valid-package@1.0.0 (valid-package@1.0.0) +` + +exports[`test/lib/commands/cache.js TAP cache npx info: valid entry with a link dependency > shows link dependency realpath (child.isLink branch) 1`] = ` +valid npx cache entry with key link123 +location: {CWD}/cache/_npx/link123 +packages: (unknown) +dependencies: +- {CWD}/cache/_npx/some-other-loc +` + +exports[`test/lib/commands/cache.js TAP cache npx info: valid entry with dependencies > shows valid package info with dependencies 1`] = ` +valid npx cache entry with key valid456 +location: {CWD}/cache/_npx/valid456 +packages: (unknown) +dependencies: +- dep-package@1.0.0 +` + +exports[`test/lib/commands/cache.js TAP cache npx ls: empty cache > logs message for empty npx cache 1`] = ` +npx cache does not exist +` + +exports[`test/lib/commands/cache.js TAP cache npx ls: entry with unknown package > lists entry with unknown package 1`] = ` +unknown123: (unknown) +` + +exports[`test/lib/commands/cache.js TAP cache npx ls: some entries > lists one valid and one invalid entry 1`] = ` +abc123: fake-npx-package@1.0.0 +z9y8x7: (empty/invalid) +` + +exports[`test/lib/commands/cache.js TAP cache npx rm: remove single entry > logs removing single npx cache entry 1`] = ` +Removing npx key at {CWD}/cache/_npx/123removeme +Removing npx key at {CWD}/cache/_npx/123removeme +` + +exports[`test/lib/commands/cache.js TAP cache npx rm: removing all with --force works > logs removing everything 1`] = ` +Removing npx key at {CWD}/cache/_npx/remove-all-yes-force +` + +exports[`test/lib/commands/cache.js TAP cache npx rm: removing all without --force fails > logs usage error when removing all without --force 1`] = ` + +` + +exports[`test/lib/commands/cache.js TAP cache npx rm: removing more than 1, less than all entries > logs removing 2 of 3 entries 1`] = ` +Removing npx key at {CWD}/cache/_npx/123removeme +Removing npx key at {CWD}/cache/_npx/456removeme +Removing npx key at {CWD}/cache/_npx/123removeme +Removing npx key at {CWD}/cache/_npx/456removeme +` + exports[`test/lib/commands/cache.js TAP cache rm > logs deleting single entry 1`] = ` Deleted: make-fetch-happen:request-cache:https://registry.npmjs.org/test-package/-/test-package-1.0.0.tgz ` diff --git a/tap-snapshots/test/lib/commands/completion.js.test.cjs b/tap-snapshots/test/lib/commands/completion.js.test.cjs index a538e3c068863..c2d4abc9d4c97 100644 --- a/tap-snapshots/test/lib/commands/completion.js.test.cjs +++ b/tap-snapshots/test/lib/commands/completion.js.test.cjs @@ -6,18 +6,17 @@ */ 'use strict' exports[`test/lib/commands/completion.js TAP completion --no- flags > flags 1`] = ` -Array [ - String( - --no-version - --no-versions - ), -] +Array [] ` exports[`test/lib/commands/completion.js TAP completion commands with no completion > no results 1`] = ` Array [] ` +exports[`test/lib/commands/completion.js TAP completion completion after custom definition flag requiring value > custom definition non-Boolean flag handled 1`] = ` +Array [] +` + exports[`test/lib/commands/completion.js TAP completion completion cannot complete options that take a value in mid-command > does not try to complete option arguments in the middle of a command 1`] = ` Array [] ` @@ -38,134 +37,16 @@ exports[`test/lib/commands/completion.js TAP completion completion of invalid co Array [] ` +exports[`test/lib/commands/completion.js TAP completion completion with double-dash escape in command line > double-dash escape handled 1`] = ` +Array [] +` + +exports[`test/lib/commands/completion.js TAP completion completion with non-flag word > non-flag word completion 1`] = ` +Array [] +` + exports[`test/lib/commands/completion.js TAP completion double dashes escape from flag completion > full command list 1`] = ` -Array [ - String( - 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 - hook - 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 - uninstall - unpublish - unstar - update - version - view - whoami - author - home - issues - info - show - find - add - unlink - remove - rm - r - un - rb - list - ln - create - i - it - cit - up - c - s - se - tst - t - ddp - v - run - clean-install - clean-install-test - x - why - la - verison - ic - innit - in - ins - inst - insta - instal - isnt - isnta - isntal - isntall - install-clean - isntall-clean - hlep - dist-tags - upgrade - udpate - rum - sit - urn - ogr - add-user - ), -] +Array [] ` exports[`test/lib/commands/completion.js TAP completion filtered subcommands > filtered subcommands 1`] = ` @@ -173,26 +54,17 @@ Array [] ` exports[`test/lib/commands/completion.js TAP completion flags > flags 1`] = ` -Array [ - String( - --version - --versions - --viewer - --verbose - --v - ), -] +Array [] ` exports[`test/lib/commands/completion.js TAP completion multiple command names > multiple command names 1`] = ` Array [ String( access - adduser + approve-scripts audit author add - add-user ), ] ` @@ -215,6 +87,76 @@ Array [ ] ` +exports[`test/lib/commands/completion.js TAP completion trust filtered subcommands > trust filtered subcommands 1`] = ` +Array [ + String( + github + gitlab + ), +] +` + +exports[`test/lib/commands/completion.js TAP completion trust github flags > trust github flags with custom definitions 1`] = ` +Array [ + String( + --file + --repository + --repo + --environment + --env + --allow-publish + --allow-stage-publish + --allow-staged-publish + --dry-run + --json + --registry + --yes + --no-allow-publish + --no-allow-stage-publish + --no-allow-staged-publish + --no-dry-run + --no-json + --no-yes + ), +] +` + +exports[`test/lib/commands/completion.js TAP completion trust gitlab flags > trust gitlab flags with custom definitions 1`] = ` +Array [ + String( + --file + --project + --environment + --env + --allow-publish + --allow-stage-publish + --allow-staged-publish + --dry-run + --json + --registry + --yes + --no-allow-publish + --no-allow-stage-publish + --no-allow-staged-publish + --no-dry-run + --no-json + --no-yes + ), +] +` + +exports[`test/lib/commands/completion.js TAP completion trust subcommands > trust subcommands 1`] = ` +Array [ + String( + github + gitlab + circleci + list + revoke + ), +] +` + exports[`test/lib/commands/completion.js TAP windows without bash > no output 1`] = ` Array [] ` diff --git a/tap-snapshots/test/lib/commands/config.js.test.cjs b/tap-snapshots/test/lib/commands/config.js.test.cjs index 0d62bacd45fa1..f65b081395088 100644 --- a/tap-snapshots/test/lib/commands/config.js.test.cjs +++ b/tap-snapshots/test/lib/commands/config.js.test.cjs @@ -10,12 +10,19 @@ exports[`test/lib/commands/config.js TAP config list --json > output matches sna "cache": "{CACHE}", "color": {COLOR}, "json": true, - "projectloaded": "yes", - "userloaded": "yes", - "globalloaded": "yes", + "tag": "from-project", + "init-author-name": "from-user", + "init-license": "from-global", "access": null, "all": false, "allow-same-version": false, + "allow-directory": "all", + "allow-file": "all", + "allow-git": "none", + "allow-remote": "none", + "allow-scripts": [ + "" + ], "also": null, "audit": true, "audit-level": null, @@ -23,6 +30,7 @@ exports[`test/lib/commands/config.js TAP config list --json > output matches sna "before": null, "bin-links": true, "browser": null, + "bypass-2fa": false, "ca": null, "cache-max": null, "cache-min": 0, @@ -32,6 +40,7 @@ exports[`test/lib/commands/config.js TAP config list --json > output matches sna "cidr": null, "commit-hooks": true, "cpu": null, + "dangerously-allow-all-scripts": false, "depth": null, "description": true, "dev": false, @@ -48,6 +57,8 @@ exports[`test/lib/commands/config.js TAP config list --json > output matches sna "engine-strict": false, "expect-result-count": null, "expect-results": null, + "expires": null, + "extension-file": null, "fetch-retries": 2, "fetch-retry-factor": 10, "fetch-retry-maxtimeout": 60000, @@ -61,24 +72,27 @@ exports[`test/lib/commands/config.js TAP config list --json > output matches sna "git-tag-version": true, "global": false, "globalconfig": "{CWD}/global/etc/npmrc", + "global-ignore-file": "{CWD}/global/etc/npmignore", "global-style": false, "heading": "npm", "https-proxy": null, "if-present": false, + "ignore-extension": false, "ignore-scripts": false, "include": [], "include-staged": false, "include-workspace-root": false, + "include-attestations": false, "init-author-email": "", - "init-author-name": "", "init-author-url": "", - "init-license": "ISC", "init-module": "{CWD}/home/.npm-init.js", + "init-type": "commonjs", "init-version": "1.0.0", + "init-private": false, "init.author.email": "", "init.author.name": "", "init.author.url": "", - "init.license": "ISC", + "init.license": "", "init.module": "{CWD}/home/.npm-init.js", "init.version": "1.0.0", "install-links": false, @@ -95,8 +109,12 @@ exports[`test/lib/commands/config.js TAP config list --json > output matches sna "logs-dir": null, "logs-max": 10, "long": false, + "name": null, "maxsockets": 15, "message": "%s", + "min-release-age": null, + "min-release-age-exclude": [], + "node-gyp": "{CWD}/node_modules/node-gyp/bin/node-gyp.js", "node-options": null, "noproxy": [ "" @@ -105,6 +123,7 @@ exports[`test/lib/commands/config.js TAP config list --json > output matches sna "omit": [], "omit-lockfile-registry-resolved": false, "only": null, + "orgs": null, "optional": null, "os": null, "otp": null, @@ -112,7 +131,16 @@ exports[`test/lib/commands/config.js TAP config list --json > output matches sna "package-lock": true, "package-lock-only": false, "pack-destination": ".", + "packages": [], + "patches-dir": "patches", + "allow-unused-patches": false, + "ignore-patch-failures": false, + "edit-dir": null, + "ignore-existing": false, + "keep-edit-dir": false, "parseable": false, + "allow-scripts-pending": false, + "allow-scripts-pin": true, "prefer-dedupe": false, "prefer-offline": false, "prefer-online": false, @@ -138,20 +166,25 @@ exports[`test/lib/commands/config.js TAP config list --json > output matches sna "sbom-format": null, "sbom-type": "library", "scope": "", + "scopes": null, + "packages-all": false, + "packages-and-scopes-permission": null, + "orgs-permission": null, + "token-description": null, "script-shell": null, "searchexclude": "", "searchlimit": 20, "searchopts": "", "searchstaleness": 900, "shell": "{SHELL}", - "shrinkwrap": true, "sign-git-commit": false, "sign-git-tag": false, "strict-peer-deps": false, + "strict-allow-scripts": false, "strict-ssl": true, - "tag": "latest", "tag-version-prefix": "v", "timing": false, + "to": null, "umask": 0, "unicode": false, "update-notifier": true, @@ -176,7 +209,15 @@ exports[`test/lib/commands/config.js TAP config list --long > output matches sna _auth = (protected) access = null all = false +allow-directory = "all" +allow-file = "all" +allow-git = "none" +allow-remote = "none" allow-same-version = false +allow-scripts = [""] +allow-scripts-pending = false +allow-scripts-pin = true +allow-unused-patches = false also = null audit = true audit-level = null @@ -184,6 +225,7 @@ auth-type = "web" before = null bin-links = true browser = null +bypass-2fa = false ca = null ; cache = "{CACHE}" ; overridden by cli cache-max = null @@ -195,6 +237,7 @@ cidr = null ; color = {COLOR} commit-hooks = true cpu = null +dangerously-allow-all-scripts = false depth = null description = true dev = false @@ -207,10 +250,13 @@ diff-src-prefix = "a/" diff-text = false diff-unified = 3 dry-run = false +edit-dir = null editor = "{EDITOR}" engine-strict = false expect-result-count = null expect-results = null +expires = null +extension-file = null fetch-retries = 2 fetch-retry-factor = 10 fetch-retry-maxtimeout = 60000 @@ -223,30 +269,38 @@ fund = true git = "git" git-tag-version = true global = false +global-ignore-file = "{CWD}/global/etc/npmignore" global-style = false globalconfig = "{CWD}/global/etc/npmrc" heading = "npm" https-proxy = null if-present = false +ignore-existing = false +ignore-extension = false +ignore-patch-failures = false ignore-scripts = false include = [] +include-attestations = false include-staged = false include-workspace-root = false init-author-email = "" -init-author-name = "" +; init-author-name = "" ; overridden by user init-author-url = "" -init-license = "ISC" +; init-license = "" ; overridden by global init-module = "{CWD}/home/.npm-init.js" +init-private = false +init-type = "commonjs" init-version = "1.0.0" init.author.email = "" init.author.name = "" init.author.url = "" -init.license = "ISC" +init.license = "" init.module = "{CWD}/home/.npm-init.js" init.version = "1.0.0" install-links = false install-strategy = "hoisted" json = false +keep-edit-dir = false key = null legacy-bundling = false legacy-peer-deps = false @@ -261,6 +315,10 @@ logs-max = 10 ; long = false ; overridden by cli maxsockets = 15 message = "%s" +min-release-age = null +min-release-age-exclude = [] +name = null +node-gyp = "{CWD}/node_modules/node-gyp/bin/node-gyp.js" node-options = null noproxy = [""] npm-version = "{NPM-VERSION}" @@ -269,13 +327,20 @@ omit = [] omit-lockfile-registry-resolved = false only = null optional = null +orgs = null +orgs-permission = null os = null otp = null pack-destination = "." package = [] package-lock = true package-lock-only = false +packages = [] +packages-all = false +packages-and-scopes-permission = null parseable = false +password = (protected) +patches-dir = "patches" prefer-dedupe = false prefer-offline = false prefer-online = false @@ -301,20 +366,23 @@ save-prod = false sbom-format = null sbom-type = "library" scope = "" +scopes = null script-shell = null searchexclude = "" searchlimit = 20 searchopts = "" searchstaleness = 900 shell = "{SHELL}" -shrinkwrap = true sign-git-commit = false sign-git-tag = false +strict-allow-scripts = false strict-peer-deps = false strict-ssl = true -tag = "latest" +; tag = "latest" ; overridden by project tag-version-prefix = "v" timing = false +to = null +token-description = null umask = 0 unicode = false update-notifier = true @@ -332,15 +400,15 @@ yes = null ; "global" config from {CWD}/global/etc/npmrc -globalloaded = "yes" +init-license = "from-global" ; "user" config from {CWD}/home/.npmrc -userloaded = "yes" +init-author-name = "from-user" ; "project" config from {CWD}/prefix/.npmrc -projectloaded = "yes" +tag = "from-project" ; "cli" config from command line options @@ -352,19 +420,17 @@ long = true exports[`test/lib/commands/config.js TAP config list > output matches snapshot 1`] = ` ; "global" config from {CWD}/global/etc/npmrc -globalloaded = "yes" +init-license = "from-global" ; "user" config from {CWD}/home/.npmrc _auth = (protected) //nerfdart:_auth = (protected) -//nerfdart:auth = (protected) -auth = (protected) -userloaded = "yes" +init-author-name = "from-user" ; "project" config from {CWD}/prefix/.npmrc -projectloaded = "yes" +tag = "from-project" ; "cli" config from command line options @@ -413,6 +479,13 @@ color = {COLOR} ; "publishConfig" from {CWD}/prefix/package.json ; This set of config values will be used at publish-time. -_authToken = (protected) +//some.registry:_authToken = (protected) +other = "not defined" registry = "https://some.registry" ` + +exports[`test/lib/commands/config.js TAP config list with publishConfig local > warns about unknown config 1`] = ` +Array [ + "Unknown publishConfig config /"other/". This will stop working in the next major version of npm. See \`npm help npmrc\` for supported config options.", +] +` diff --git a/tap-snapshots/test/lib/commands/diff.js.test.cjs b/tap-snapshots/test/lib/commands/diff.js.test.cjs index e87086d7d9b8f..0eb91154b2417 100644 --- a/tap-snapshots/test/lib/commands/diff.js.test.cjs +++ b/tap-snapshots/test/lib/commands/diff.js.test.cjs @@ -62,11 +62,13 @@ package.json ` exports[`test/lib/commands/diff.js TAP various options using diff option > must match snapshot 1`] = ` -diff --git a/index.js b/index.js +diff --git bar/index.js foo/index.js index v2.0.0..v3.0.0 100644 ---- a/index.js -+++ b/index.js -@@ -18,7 +18,7 @@ +--- bar/index.js ++++ foo/index.js +@@ -16,11 +16,11 @@ + 15 + 16 17 18 19 @@ -75,10 +77,12 @@ index v2.0.0..v3.0.0 100644 21 22 23 -diff --git a/package.json b/package.json + 24 + 25 +diff --git bar/package.json foo/package.json index v2.0.0..v3.0.0 100644 ---- a/package.json -+++ b/package.json +--- bar/package.json ++++ foo/package.json @@ -1,4 +1,4 @@ { "name": "bar", diff --git a/tap-snapshots/test/lib/commands/doctor.js.test.cjs b/tap-snapshots/test/lib/commands/doctor.js.test.cjs index 0f5b9520516f2..134e2290b5e99 100644 --- a/tap-snapshots/test/lib/commands/doctor.js.test.cjs +++ b/tap-snapshots/test/lib/commands/doctor.js.test.cjs @@ -1166,7 +1166,7 @@ Object { exports[`test/lib/commands/doctor.js TAP ping 404 > ping 404 1`] = ` Connecting to the registry Not ok -404 404 Not Found - GET https://registry.npmjs.org/-/ping?write=true +404 404 Not Found - GET https://registry.npmjs.org/-/ping Checking npm version Ok current: v1.0.0, latest: v1.0.0 @@ -1226,7 +1226,7 @@ Object { exports[`test/lib/commands/doctor.js TAP ping 404 in color > ping 404 in color 1`] = ` Connecting to the registry Not ok -404 404 Not Found - GET https://registry.npmjs.org/-/ping?write=true +404 404 Not Found - GET https://registry.npmjs.org/-/ping Checking npm version Ok current: v1.0.0, latest: v1.0.0 @@ -1286,7 +1286,7 @@ Object { exports[`test/lib/commands/doctor.js TAP ping exception with code > ping failure 1`] = ` Connecting to the registry Not ok -request to https://registry.npmjs.org/-/ping?write=true failed, reason: Test Error +request to https://registry.npmjs.org/-/ping failed, reason: Test Error Checking npm version Ok current: v1.0.0, latest: v1.0.0 @@ -1346,7 +1346,7 @@ Object { exports[`test/lib/commands/doctor.js TAP ping exception without code > ping failure 1`] = ` Connecting to the registry Not ok -request to https://registry.npmjs.org/-/ping?write=true failed, reason: Test Error +request to https://registry.npmjs.org/-/ping failed, reason: Test Error Checking npm version Ok current: v1.0.0, latest: v1.0.0 diff --git a/tap-snapshots/test/lib/commands/init.js.test.cjs b/tap-snapshots/test/lib/commands/init.js.test.cjs index eae04d77d2e82..d8c31b95d9d7d 100644 --- a/tap-snapshots/test/lib/commands/init.js.test.cjs +++ b/tap-snapshots/test/lib/commands/init.js.test.cjs @@ -9,17 +9,14 @@ exports[`test/lib/commands/init.js TAP displays output > displays helper info 1` 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. +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. +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. ` exports[`test/lib/commands/init.js TAP workspaces no args -- yes > should print helper info 1`] = ` - added 1 package in {TIME} ` diff --git a/tap-snapshots/test/lib/commands/install.js.test.cjs b/tap-snapshots/test/lib/commands/install.js.test.cjs new file mode 100644 index 0000000000000..9070c6299f03d --- /dev/null +++ b/tap-snapshots/test/lib/commands/install.js.test.cjs @@ -0,0 +1,309 @@ +/* IMPORTANT + * This snapshot file is auto-generated, but designed for humans. + * It should be checked into source control and tracked carefully. + * Re-generate by setting TAP_SNAPSHOT=1 and running tests. + * Make sure to inspect the output below. Do not ignore changes! + */ +'use strict' +exports[`test/lib/commands/install.js TAP devEngines should not utilize engines in root if devEngines is provided > must match snapshot 1`] = ` +silly config load:file:{CWD}/npmrc +silly config load:file:{CWD}/prefix/.npmrc +silly config load:file:{CWD}/home/.npmrc +silly config load:file:{CWD}/global/etc/npmrc +verbose title npm +verbose argv "--fetch-retries" "0" "--cache" "{CWD}/cache" "--loglevel" "silly" "--color" "false" +verbose logfile logs-max:10 dir:{CWD}/cache/_logs/{DATE}- +verbose logfile {CWD}/cache/_logs/{DATE}-debug-0.log +silly logfile done cleaning log files +warn EBADDEVENGINES The developer of this package has specified the following through devEngines +warn EBADDEVENGINES Invalid devEngines.runtime +warn EBADDEVENGINES Invalid semver version "0.0.1" does not match "v1337.0.0" for "runtime" +warn EBADDEVENGINES { +warn EBADDEVENGINES current: { name: 'node', version: 'v1337.0.0' }, +warn EBADDEVENGINES required: { name: 'node', version: '0.0.1', onFail: 'warn' } +warn EBADDEVENGINES } +silly packumentCache heap:{heap} maxSize:{maxSize} maxEntrySize:{maxEntrySize} +silly idealTree buildDeps +silly reify moves {} +silly audit report null + +up to date, audited 1 package in {TIME} +found 0 vulnerabilities +` + +exports[`test/lib/commands/install.js TAP devEngines should show devEngines doesnt break engines > must match snapshot 1`] = ` +silly config load:file:{CWD}/npmrc +silly config load:file:{CWD}/home/.npmrc +silly config load:file:{CWD}/global/etc/npmrc +verbose title npm +verbose argv "--fetch-retries" "0" "--cache" "{CWD}/cache" "--loglevel" "silly" "--color" "false" "--global" "true" +verbose logfile logs-max:10 dir:{CWD}/cache/_logs/{DATE}- +verbose logfile {CWD}/cache/_logs/{DATE}-debug-0.log +silly logfile done cleaning log files +silly packumentCache heap:{heap} maxSize:{maxSize} maxEntrySize:{maxEntrySize} +silly idealTree buildDeps +silly placeDep ROOT alpha@ OK for: want: file:../../prefix/alpha +warn EBADENGINE Unsupported engine { +warn EBADENGINE package: undefined, +warn EBADENGINE required: { node: '1.0.0' }, +warn EBADENGINE current: { node: 'v1337.0.0', npm: '42.0.0' } +warn EBADENGINE } +warn EBADENGINE Unsupported engine { +warn EBADENGINE package: undefined, +warn EBADENGINE required: { node: '1.0.0' }, +warn EBADENGINE current: { node: 'v1337.0.0', npm: '42.0.0' } +warn EBADENGINE } +silly reify moves {} +silly ADD node_modules/alpha + +added 1 package in {TIME} +` + +exports[`test/lib/commands/install.js TAP devEngines should show devEngines has no effect on dev package install > must match snapshot 1`] = ` +silly config load:file:{CWD}/npmrc +silly config load:file:{CWD}/prefix/.npmrc +silly config load:file:{CWD}/home/.npmrc +silly config load:file:{CWD}/global/etc/npmrc +verbose title npm +verbose argv "--fetch-retries" "0" "--cache" "{CWD}/cache" "--loglevel" "silly" "--color" "false" "--save-dev" "true" +verbose logfile logs-max:10 dir:{CWD}/cache/_logs/{DATE}- +verbose logfile {CWD}/cache/_logs/{DATE}-debug-0.log +silly logfile done cleaning log files +silly packumentCache heap:{heap} maxSize:{maxSize} maxEntrySize:{maxEntrySize} +silly idealTree buildDeps +silly placeDep ROOT alpha@ OK for: want: file:alpha +silly reify moves {} +silly audit bulk request {} +silly audit report null +silly ADD node_modules/alpha + +added 1 package, and audited 3 packages in {TIME} +found 0 vulnerabilities +` + +exports[`test/lib/commands/install.js TAP devEngines should show devEngines has no effect on global package install > must match snapshot 1`] = ` +silly config load:file:{CWD}/npmrc +silly config load:file:{CWD}/home/.npmrc +silly config load:file:{CWD}/global/etc/npmrc +verbose title npm +verbose argv "--fetch-retries" "0" "--cache" "{CWD}/cache" "--loglevel" "silly" "--color" "false" "--global" "true" +verbose logfile logs-max:10 dir:{CWD}/cache/_logs/{DATE}- +verbose logfile {CWD}/cache/_logs/{DATE}-debug-0.log +silly logfile done cleaning log files +silly packumentCache heap:{heap} maxSize:{maxSize} maxEntrySize:{maxEntrySize} +silly idealTree buildDeps +silly placeDep ROOT alpha@ OK for: want: file:../../prefix +silly reify moves {} +silly ADD node_modules/alpha + +added 1 package in {TIME} +` + +exports[`test/lib/commands/install.js TAP devEngines should show devEngines has no effect on package install > must match snapshot 1`] = ` +silly config load:file:{CWD}/npmrc +silly config load:file:{CWD}/prefix/.npmrc +silly config load:file:{CWD}/home/.npmrc +silly config load:file:{CWD}/global/etc/npmrc +verbose title npm +verbose argv "--fetch-retries" "0" "--cache" "{CWD}/cache" "--loglevel" "silly" "--color" "false" +verbose logfile logs-max:10 dir:{CWD}/cache/_logs/{DATE}- +verbose logfile {CWD}/cache/_logs/{DATE}-debug-0.log +silly logfile done cleaning log files +silly packumentCache heap:{heap} maxSize:{maxSize} maxEntrySize:{maxEntrySize} +silly idealTree buildDeps +silly placeDep ROOT alpha@ OK for: want: file:alpha +silly reify moves {} +silly audit bulk request {} +silly audit report null +silly ADD node_modules/alpha + +added 1 package, and audited 3 packages in {TIME} +found 0 vulnerabilities +` + +exports[`test/lib/commands/install.js TAP devEngines should utilize devEngines 2x error case > must match snapshot 1`] = ` +silly config load:file:{CWD}/npmrc +silly config load:file:{CWD}/prefix/.npmrc +silly config load:file:{CWD}/home/.npmrc +silly config load:file:{CWD}/global/etc/npmrc +verbose title npm +verbose argv "--fetch-retries" "0" "--cache" "{CWD}/cache" "--loglevel" "silly" "--color" "false" +verbose logfile logs-max:10 dir:{CWD}/cache/_logs/{DATE}- +verbose logfile {CWD}/cache/_logs/{DATE}-debug-0.log +silly logfile done cleaning log files +verbose stack Error: The developer of this package has specified the following through devEngines +verbose stack Invalid devEngines.runtime +verbose stack Invalid name "nondescript" does not match "node" for "runtime" +verbose stack at Install.checkDevEngines ({CWD}/lib/base-cmd.js:249:27) +verbose stack at MockNpm.execCommandClass ({CWD}/lib/npm.js:294:7) +verbose stack at MockNpm.exec ({CWD}/lib/npm.js:194:9) +error code EBADDEVENGINES +error EBADDEVENGINES The developer of this package has specified the following through devEngines +error EBADDEVENGINES Invalid devEngines.runtime +error EBADDEVENGINES Invalid name "nondescript" does not match "node" for "runtime" +error EBADDEVENGINES { +error EBADDEVENGINES current: { name: 'node', version: 'v1337.0.0' }, +error EBADDEVENGINES required: { name: 'nondescript', onFail: 'error' } +error EBADDEVENGINES } +` + +exports[`test/lib/commands/install.js TAP devEngines should utilize devEngines 2x warning case > must match snapshot 1`] = ` +silly config load:file:{CWD}/npmrc +silly config load:file:{CWD}/prefix/.npmrc +silly config load:file:{CWD}/home/.npmrc +silly config load:file:{CWD}/global/etc/npmrc +verbose title npm +verbose argv "--fetch-retries" "0" "--cache" "{CWD}/cache" "--loglevel" "silly" "--color" "false" +verbose logfile logs-max:10 dir:{CWD}/cache/_logs/{DATE}- +verbose logfile {CWD}/cache/_logs/{DATE}-debug-0.log +silly logfile done cleaning log files +warn EBADDEVENGINES The developer of this package has specified the following through devEngines +warn EBADDEVENGINES Invalid devEngines.runtime +warn EBADDEVENGINES Invalid name "nondescript" does not match "node" for "runtime" +warn EBADDEVENGINES { +warn EBADDEVENGINES current: { name: 'node', version: 'v1337.0.0' }, +warn EBADDEVENGINES required: { name: 'nondescript', onFail: 'warn' } +warn EBADDEVENGINES } +warn EBADDEVENGINES Invalid devEngines.cpu +warn EBADDEVENGINES Invalid name "risv" does not match "x86" for "cpu" +warn EBADDEVENGINES { +warn EBADDEVENGINES current: { name: 'x86' }, +warn EBADDEVENGINES required: { name: 'risv', onFail: 'warn' } +warn EBADDEVENGINES } +silly packumentCache heap:{heap} maxSize:{maxSize} maxEntrySize:{maxEntrySize} +silly idealTree buildDeps +silly reify moves {} +silly audit report null + +up to date, audited 1 package in {TIME} +found 0 vulnerabilities +` + +exports[`test/lib/commands/install.js TAP devEngines should utilize devEngines failure and warning case > must match snapshot 1`] = ` +silly config load:file:{CWD}/npmrc +silly config load:file:{CWD}/prefix/.npmrc +silly config load:file:{CWD}/home/.npmrc +silly config load:file:{CWD}/global/etc/npmrc +verbose title npm +verbose argv "--fetch-retries" "0" "--cache" "{CWD}/cache" "--loglevel" "silly" "--color" "false" +verbose logfile logs-max:10 dir:{CWD}/cache/_logs/{DATE}- +verbose logfile {CWD}/cache/_logs/{DATE}-debug-0.log +silly logfile done cleaning log files +warn EBADDEVENGINES The developer of this package has specified the following through devEngines +warn EBADDEVENGINES Invalid devEngines.cpu +warn EBADDEVENGINES Invalid name "risv" does not match "x86" for "cpu" +warn EBADDEVENGINES { +warn EBADDEVENGINES current: { name: 'x86' }, +warn EBADDEVENGINES required: { name: 'risv', onFail: 'warn' } +warn EBADDEVENGINES } +verbose stack Error: The developer of this package has specified the following through devEngines +verbose stack Invalid devEngines.runtime +verbose stack Invalid name "nondescript" does not match "node" for "runtime" +verbose stack at Install.checkDevEngines ({CWD}/lib/base-cmd.js:249:27) +verbose stack at MockNpm.execCommandClass ({CWD}/lib/npm.js:294:7) +verbose stack at MockNpm.exec ({CWD}/lib/npm.js:194:9) +error code EBADDEVENGINES +error EBADDEVENGINES The developer of this package has specified the following through devEngines +error EBADDEVENGINES Invalid devEngines.runtime +error EBADDEVENGINES Invalid name "nondescript" does not match "node" for "runtime" +error EBADDEVENGINES { +error EBADDEVENGINES current: { name: 'node', version: 'v1337.0.0' }, +error EBADDEVENGINES required: { name: 'nondescript' } +error EBADDEVENGINES } +` + +exports[`test/lib/commands/install.js TAP devEngines should utilize devEngines failure case > must match snapshot 1`] = ` +silly config load:file:{CWD}/npmrc +silly config load:file:{CWD}/prefix/.npmrc +silly config load:file:{CWD}/home/.npmrc +silly config load:file:{CWD}/global/etc/npmrc +verbose title npm +verbose argv "--fetch-retries" "0" "--cache" "{CWD}/cache" "--loglevel" "silly" "--color" "false" +verbose logfile logs-max:10 dir:{CWD}/cache/_logs/{DATE}- +verbose logfile {CWD}/cache/_logs/{DATE}-debug-0.log +silly logfile done cleaning log files +verbose stack Error: The developer of this package has specified the following through devEngines +verbose stack Invalid devEngines.runtime +verbose stack Invalid name "nondescript" does not match "node" for "runtime" +verbose stack at Install.checkDevEngines ({CWD}/lib/base-cmd.js:249:27) +verbose stack at MockNpm.execCommandClass ({CWD}/lib/npm.js:294:7) +verbose stack at MockNpm.exec ({CWD}/lib/npm.js:194:9) +error code EBADDEVENGINES +error EBADDEVENGINES The developer of this package has specified the following through devEngines +error EBADDEVENGINES Invalid devEngines.runtime +error EBADDEVENGINES Invalid name "nondescript" does not match "node" for "runtime" +error EBADDEVENGINES { +error EBADDEVENGINES current: { name: 'node', version: 'v1337.0.0' }, +error EBADDEVENGINES required: { name: 'nondescript' } +error EBADDEVENGINES } +` + +exports[`test/lib/commands/install.js TAP devEngines should utilize devEngines failure force case > must match snapshot 1`] = ` +silly config load:file:{CWD}/npmrc +silly config load:file:{CWD}/prefix/.npmrc +silly config load:file:{CWD}/home/.npmrc +silly config load:file:{CWD}/global/etc/npmrc +verbose title npm +verbose argv "--fetch-retries" "0" "--cache" "{CWD}/cache" "--loglevel" "silly" "--color" "false" "--force" "true" +verbose logfile logs-max:10 dir:{CWD}/cache/_logs/{DATE}- +verbose logfile {CWD}/cache/_logs/{DATE}-debug-0.log +warn using --force Recommended protections disabled. +silly logfile done cleaning log files +warn EBADDEVENGINES The developer of this package has specified the following through devEngines +warn EBADDEVENGINES Invalid devEngines.runtime +warn EBADDEVENGINES Invalid name "nondescript" does not match "node" for "runtime" +warn EBADDEVENGINES { +warn EBADDEVENGINES current: { name: 'node', version: 'v1337.0.0' }, +warn EBADDEVENGINES required: { name: 'nondescript' } +warn EBADDEVENGINES } +silly packumentCache heap:{heap} maxSize:{maxSize} maxEntrySize:{maxEntrySize} +silly idealTree buildDeps +silly reify moves {} +silly audit report null + +up to date, audited 1 package in {TIME} +found 0 vulnerabilities +` + +exports[`test/lib/commands/install.js TAP devEngines should utilize devEngines success case > must match snapshot 1`] = ` +silly config load:file:{CWD}/npmrc +silly config load:file:{CWD}/prefix/.npmrc +silly config load:file:{CWD}/home/.npmrc +silly config load:file:{CWD}/global/etc/npmrc +verbose title npm +verbose argv "--fetch-retries" "0" "--cache" "{CWD}/cache" "--loglevel" "silly" "--color" "false" +verbose logfile logs-max:10 dir:{CWD}/cache/_logs/{DATE}- +verbose logfile {CWD}/cache/_logs/{DATE}-debug-0.log +silly logfile done cleaning log files +silly packumentCache heap:{heap} maxSize:{maxSize} maxEntrySize:{maxEntrySize} +silly idealTree buildDeps +silly reify moves {} +silly audit report null + +up to date, audited 1 package in {TIME} +found 0 vulnerabilities +` + +exports[`test/lib/commands/install.js TAP devEngines should utilize engines in root if devEngines is not provided > must match snapshot 1`] = ` +silly config load:file:{CWD}/npmrc +silly config load:file:{CWD}/prefix/.npmrc +silly config load:file:{CWD}/home/.npmrc +silly config load:file:{CWD}/global/etc/npmrc +verbose title npm +verbose argv "--fetch-retries" "0" "--cache" "{CWD}/cache" "--loglevel" "silly" "--color" "false" +verbose logfile logs-max:10 dir:{CWD}/cache/_logs/{DATE}- +verbose logfile {CWD}/cache/_logs/{DATE}-debug-0.log +silly logfile done cleaning log files +silly packumentCache heap:{heap} maxSize:{maxSize} maxEntrySize:{maxEntrySize} +silly idealTree buildDeps +warn EBADENGINE Unsupported engine { +warn EBADENGINE package: undefined, +warn EBADENGINE required: { node: '0.0.1' }, +warn EBADENGINE current: { node: 'v1337.0.0', npm: '42.0.0' } +warn EBADENGINE } +silly reify moves {} +silly audit report null + +up to date, audited 1 package in {TIME} +found 0 vulnerabilities +` diff --git a/tap-snapshots/test/lib/commands/ls.js.test.cjs b/tap-snapshots/test/lib/commands/ls.js.test.cjs index 86394b702f19a..5ceb233215fc4 100644 --- a/tap-snapshots/test/lib/commands/ls.js.test.cjs +++ b/tap-snapshots/test/lib/commands/ls.js.test.cjs @@ -9,7 +9,9 @@ exports[`test/lib/commands/ls.js TAP ignore missing optional deps --json > ls -- Array [ "invalid: optional-wrong@3.2.1 {CWD}/prefix/node_modules/optional-wrong", "missing: peer-missing@1, required by test-npm-ls-ignore-missing-optional@1.2.3", + "extraneous: peer-optional-ok@1.2.3 {CWD}/prefix/node_modules/peer-optional-ok", "invalid: peer-optional-wrong@3.2.1 {CWD}/prefix/node_modules/peer-optional-wrong", + "extraneous: peer-optional-wrong@3.2.1 {CWD}/prefix/node_modules/peer-optional-wrong", "invalid: peer-wrong@3.2.1 {CWD}/prefix/node_modules/peer-wrong", "missing: prod-missing@1, required by test-npm-ls-ignore-missing-optional@1.2.3", "invalid: prod-wrong@3.2.1 {CWD}/prefix/node_modules/prod-wrong", @@ -36,8 +38,8 @@ test-npm-ls-ignore-missing-optional@1.2.3 {CWD}/prefix +-- UNMET DEPENDENCY peer-missing@1 +-- peer-ok@1.2.3 +-- UNMET OPTIONAL DEPENDENCY peer-optional-missing@1 -+-- peer-optional-ok@1.2.3 -+-- peer-optional-wrong@3.2.1 invalid: "1" from the root project ++-- peer-optional-ok@1.2.3 extraneous ++-- peer-optional-wrong@3.2.1 invalid: "1" from the root project extraneous +-- peer-wrong@3.2.1 invalid: "1" from the root project +-- UNMET DEPENDENCY prod-missing@1 +-- prod-ok@1.2.3 @@ -248,7 +250,7 @@ exports[`test/lib/commands/ls.js TAP ls --parseable no args > should output pars {CWD}/prefix/node_modules/dog ` -exports[`test/lib/commands/ls.js TAP ls --parseable overridden dep > should contain overridden outout 1`] = ` +exports[`test/lib/commands/ls.js TAP ls --parseable overridden dep > should contain overridden output 1`] = ` {CWD}/prefix:test-overridden@1.0.0 {CWD}/prefix/node_modules/foo:foo@1.0.0 {CWD}/prefix/node_modules/bar:bar@1.0.0:OVERRIDDEN @@ -288,11 +290,11 @@ exports[`test/lib/commands/ls.js TAP ls --parseable using aliases > should outpu {CWD}/prefix/node_modules/a ` -exports[`test/lib/commands/ls.js TAP ls --parseable with filter arg > should output parseable contaning only occurrences of filtered by package 1`] = ` +exports[`test/lib/commands/ls.js TAP ls --parseable with filter arg > should output parseable containing only occurrences of filtered by package 1`] = ` {CWD}/prefix/node_modules/chai ` -exports[`test/lib/commands/ls.js TAP ls --parseable with filter arg nested dep > should output parseable contaning only occurrences of filtered package 1`] = ` +exports[`test/lib/commands/ls.js TAP ls --parseable with filter arg nested dep > should output parseable containing only occurrences of filtered package 1`] = ` {CWD}/prefix/node_modules/dog ` @@ -300,7 +302,7 @@ exports[`test/lib/commands/ls.js TAP ls --parseable with missing filter arg > sh ` -exports[`test/lib/commands/ls.js TAP ls --parseable with multiple filter args > should output parseable contaning only occurrences of multiple filtered packages and their ancestors 1`] = ` +exports[`test/lib/commands/ls.js TAP ls --parseable with multiple filter args > should output parseable containing only occurrences of multiple filtered packages and their ancestors 1`] = ` {CWD}/prefix/node_modules/chai {CWD}/prefix/node_modules/dog ` @@ -313,6 +315,12 @@ test-npm-ls@1.0.0 {CWD}/prefix \`-- dog@2.0.0 ` +exports[`test/lib/commands/ls.js TAP ls .npm-extension dep > human output annotates the transformed node 1`] = ` +test-npm-extension@1.0.0 {CWD}/prefix +\`-- foo@1.0.0 .npm-extension: dependencies.bar + \`-- bar@1.0.0 +` + exports[`test/lib/commands/ls.js TAP ls broken resolved field > should NOT print git refs in output tree 1`] = ` npm-broken-resolved-field-test@1.0.0 {CWD}/prefix \`-- a@1.0.1 @@ -453,7 +461,7 @@ workspaces-tree@1.0.0 {CWD}/prefix \`-- bar@1.0.0 ` -exports[`test/lib/commands/ls.js TAP ls loading a tree containing workspaces should inlude root and specified workspace > output 1`] = ` +exports[`test/lib/commands/ls.js TAP ls loading a tree containing workspaces should include root and specified workspace > output 1`] = ` workspaces-tree@1.0.0 {CWD}/prefix +-- d@1.0.0 -> ./d | \`-- foo@1.1.1 @@ -541,19 +549,25 @@ test-npm-ls@1.0.0 {CWD}/prefix \`-- dog@1.0.0 ` -exports[`test/lib/commands/ls.js TAP ls overridden dep > should contain overridden outout 1`] = ` +exports[`test/lib/commands/ls.js TAP ls overridden dep > should contain overridden output 1`] = ` test-overridden@1.0.0 {CWD}/prefix \`-- foo@1.0.0 \`-- bar@1.0.0 overridden ` -exports[`test/lib/commands/ls.js TAP ls overridden dep w/ color > should contain overridden outout 1`] = ` +exports[`test/lib/commands/ls.js TAP ls overridden dep w/ color > should contain overridden output 1`] = ` test-overridden@1.0.0 {CWD}/prefix \`-- foo@1.0.0  \`-- bar@1.0.0 overridden  ` +exports[`test/lib/commands/ls.js TAP ls packageExtensions dep > human output annotates the extended node 1`] = ` +test-package-extensions@1.0.0 {CWD}/prefix +\`-- foo@1.0.0 packageExtensions: dependencies.bar + \`-- bar@1.0.0 +` + exports[`test/lib/commands/ls.js TAP ls print deduped symlinks > should output tree containing linked deps 1`] = ` print-deduped-symlinks@1.0.0 {CWD}/prefix +-- a@1.0.0 @@ -563,7 +577,7 @@ print-deduped-symlinks@1.0.0 {CWD}/prefix exports[`test/lib/commands/ls.js TAP ls resolved points to git ref > should output tree containing git refs 1`] = ` test-npm-ls@1.0.0 {CWD}/prefix -\`-- abbrev@1.1.1 (git+ssh://git@github.com/isaacs/abbrev-js.git#b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c) +\`-- abbrev@1.1.1 (git+https://github.com/isaacs/abbrev-js.git#b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c) ` exports[`test/lib/commands/ls.js TAP ls unmet optional dep > should output tree with empty entry for missing optional deps 1`] = ` @@ -609,18 +623,18 @@ dedupe-entries@1.0.0 {CWD}/prefix \`-- @npmcli/c@1.0.0 ` -exports[`test/lib/commands/ls.js TAP ls with dot filter arg > should output tree contaning only occurrences of filtered by package and colored output 1`] = ` +exports[`test/lib/commands/ls.js TAP ls with dot filter arg > should output tree containing only occurrences of filtered by package and colored output 1`] = ` test-npm-ls@1.0.0 {CWD}/prefix \`-- (empty) ` -exports[`test/lib/commands/ls.js TAP ls with filter arg > should output tree contaning only occurrences of filtered by package and colored output 1`] = ` +exports[`test/lib/commands/ls.js TAP ls with filter arg > should output tree containing only occurrences of filtered by package and colored output 1`] = ` test-npm-ls@1.0.0 {CWD}/prefix \`-- chai@1.0.0  ` -exports[`test/lib/commands/ls.js TAP ls with filter arg nested dep > should output tree contaning only occurrences of filtered package and its ancestors 1`] = ` +exports[`test/lib/commands/ls.js TAP ls with filter arg nested dep > should output tree containing only occurrences of filtered package and its ancestors 1`] = ` test-npm-ls@1.0.0 {CWD}/prefix \`-- foo@1.0.0 \`-- dog@1.0.0 @@ -631,7 +645,7 @@ test-npm-ls@1.0.0 {CWD}/prefix \`-- (empty) ` -exports[`test/lib/commands/ls.js TAP ls with multiple filter args > should output tree contaning only occurrences of multiple filtered packages and their ancestors 1`] = ` +exports[`test/lib/commands/ls.js TAP ls with multiple filter args > should output tree containing only occurrences of multiple filtered packages and their ancestors 1`] = ` test-npm-ls@1.0.0 {CWD}/prefix +-- chai@1.0.0 \`-- foo@1.0.0 diff --git a/tap-snapshots/test/lib/commands/outdated.js.test.cjs b/tap-snapshots/test/lib/commands/outdated.js.test.cjs index d15bbfc815e17..8eac2cc92dd4f 100644 --- a/tap-snapshots/test/lib/commands/outdated.js.test.cjs +++ b/tap-snapshots/test/lib/commands/outdated.js.test.cjs @@ -15,6 +15,37 @@ Package Current Wanted Latest Location Depended by cat:dog@^1.0.0 1.0.0 1.0.1 2.0.0 node_modules/cat prefix ` +exports[`test/lib/commands/outdated.js TAP dependent location --long --json > should display dependent location when using --long and --json 1`] = ` +{ + "dog": [ + { + "current": "1.0.0", + "wanted": "1.0.1", + "latest": "2.0.0", + "dependent": "a", + "location": "{CWD}/prefix/node_modules/dog", + "type": "dependencies", + "dependedByLocation": "a" + }, + { + "current": "1.0.0", + "wanted": "1.0.1", + "latest": "2.0.0", + "dependent": "a", + "location": "{CWD}/prefix/node_modules/dog", + "type": "dependencies", + "dependedByLocation": "nest/a" + } + ] +} +` + +exports[`test/lib/commands/outdated.js TAP dependent location --long > should display dependent location when using --long 1`] = ` +Package Current Wanted Latest Location Depended by Package Type Homepage Depended By Location +dog 1.0.0 1.0.1 2.0.0 node_modules/dog a@1.0.0 dependencies a +dog 1.0.0 1.0.1 2.0.0 node_modules/dog a@npm:nest-a@1.0.0 dependencies nest/a +` + exports[`test/lib/commands/outdated.js TAP should display outdated deps outdated --all > must match snapshot 1`] = ` Package Current Wanted Latest Location Depended by cat 1.0.0 1.0.1 1.0.1 node_modules/cat prefix @@ -31,7 +62,8 @@ exports[`test/lib/commands/outdated.js TAP should display outdated deps outdated "latest": "1.0.1", "dependent": "prefix", "location": "{CWD}/prefix/node_modules/cat", - "type": "dependencies" + "type": "dependencies", + "dependedByLocation": "" }, "chai": { "current": "1.0.0", @@ -39,7 +71,8 @@ exports[`test/lib/commands/outdated.js TAP should display outdated deps outdated "latest": "1.0.1", "dependent": "prefix", "location": "{CWD}/prefix/node_modules/chai", - "type": "peerDependencies" + "type": "peerDependencies", + "dependedByLocation": "" }, "dog": { "current": "1.0.1", @@ -47,13 +80,15 @@ exports[`test/lib/commands/outdated.js TAP should display outdated deps outdated "latest": "2.0.0", "dependent": "prefix", "location": "{CWD}/prefix/node_modules/dog", - "type": "dependencies" + "type": "dependencies", + "dependedByLocation": "" }, "theta": { "wanted": "1.0.1", "latest": "1.0.1", "dependent": "prefix", - "type": "dependencies" + "type": "dependencies", + "dependedByLocation": "" } } ` @@ -90,7 +125,7 @@ exports[`test/lib/commands/outdated.js TAP should display outdated deps outdated ` exports[`test/lib/commands/outdated.js TAP should display outdated deps outdated --long > must match snapshot 1`] = ` -Package Current Wanted Latest Location Depended by Package Type Homepage +Package Current Wanted Latest Location Depended by Package Type Homepage Depended By Location cat 1.0.0 1.0.1 1.0.1 node_modules/cat prefix dependencies chai 1.0.0 1.0.1 1.0.1 node_modules/chai prefix peerDependencies dog 1.0.1 1.0.1 2.0.0 node_modules/dog prefix dependencies @@ -120,10 +155,10 @@ exports[`test/lib/commands/outdated.js TAP should display outdated deps outdated ` exports[`test/lib/commands/outdated.js TAP should display outdated deps outdated --parseable --long > must match snapshot 1`] = ` -{CWD}/prefix/node_modules/cat:cat@1.0.1:cat@1.0.0:cat@1.0.1:prefix:dependencies: -{CWD}/prefix/node_modules/chai:chai@1.0.1:chai@1.0.0:chai@1.0.1:prefix:peerDependencies: -{CWD}/prefix/node_modules/dog:dog@1.0.1:dog@1.0.1:dog@2.0.0:prefix:dependencies: -:theta@1.0.1:MISSING:theta@1.0.1:prefix:dependencies: +{CWD}/prefix/node_modules/cat:cat@1.0.1:cat@1.0.0:cat@1.0.1:prefix:dependencies:: +{CWD}/prefix/node_modules/chai:chai@1.0.1:chai@1.0.0:chai@1.0.1:prefix:peerDependencies:: +{CWD}/prefix/node_modules/dog:dog@1.0.1:dog@1.0.1:dog@2.0.0:prefix:dependencies:: +:theta@1.0.1:MISSING:theta@1.0.1:prefix:dependencies:: ` exports[`test/lib/commands/outdated.js TAP should display outdated deps outdated --parseable > must match snapshot 1`] = ` @@ -254,7 +289,7 @@ exports[`test/lib/commands/outdated.js TAP workspaces should display ws outdated :theta@1.0.1:MISSING:theta@1.0.1:e ` -exports[`test/lib/commands/outdated.js TAP workspaces should highlight ws in dependend by section > output 1`] = ` +exports[`test/lib/commands/outdated.js TAP workspaces should highlight ws in depended by section > output 1`] = ` Package Current Wanted Latest Location Depended by cat 1.0.0 1.0.1 1.0.1 node_modules/cat a@1.0.0 dog 1.0.1 1.0.1 2.0.0 node_modules/dog prefix diff --git a/tap-snapshots/test/lib/commands/pack.js.test.cjs b/tap-snapshots/test/lib/commands/pack.js.test.cjs index 9ec24b3816261..3afb19a16b920 100644 --- a/tap-snapshots/test/lib/commands/pack.js.test.cjs +++ b/tap-snapshots/test/lib/commands/pack.js.test.cjs @@ -41,6 +41,10 @@ Array [ exports[`test/lib/commands/pack.js TAP foreground-scripts defaults to true > logs pack contents 1`] = ` Array [ + "run test-fg-scripts@0.0.0 prepack", + "run echo prepack!", + "run test-fg-scripts@0.0.0 postpack", + "run echo postpack!", "package: test-fg-scripts@0.0.0", "Tarball Contents", "110B package.json", @@ -62,8 +66,8 @@ Array [] exports[`test/lib/commands/pack.js TAP should log output as valid json > outputs as json 1`] = ` Array [ - Array [ - Object { + Object { + "test-package": Object { "bundled": Array [], "entryCount": 1, "filename": "test-package-1.0.0.tgz", @@ -82,18 +86,21 @@ Array [ "unpackedSize": 41, "version": "1.0.0", }, - ], + }, ] ` exports[`test/lib/commands/pack.js TAP should log scoped package output as valid json > logs pack contents 1`] = ` -Array [] +Array [ + "run @myscope/test-package@1.0.0 prepack", + "run echo prepack!", +] ` exports[`test/lib/commands/pack.js TAP should log scoped package output as valid json > outputs as json 1`] = ` Array [ - Array [ - Object { + Object { + "@myscope/test-package": Object { "bundled": Array [], "entryCount": 1, "filename": "myscope-test-package-1.0.0.tgz", @@ -112,18 +119,7 @@ Array [ "unpackedSize": 88, "version": "1.0.0", }, - ], -] -` - -exports[`test/lib/commands/pack.js TAP should log scoped package output as valid json > stderr has banners 1`] = ` -Array [ - String( - - > @myscope/test-package@1.0.0 prepack - > echo prepack! - - ), + }, ] ` diff --git a/tap-snapshots/test/lib/commands/pkg.js.test.cjs b/tap-snapshots/test/lib/commands/pkg.js.test.cjs new file mode 100644 index 0000000000000..9e31b675ec20d --- /dev/null +++ b/tap-snapshots/test/lib/commands/pkg.js.test.cjs @@ -0,0 +1,220 @@ +/* IMPORTANT + * This snapshot file is auto-generated, but designed for humans. + * It should be checked into source control and tracked carefully. + * Re-generate by setting TAP_SNAPSHOT=1 and running tests. + * Make sure to inspect the output below. Do not ignore changes! + */ +'use strict' +exports[`test/lib/commands/pkg.js TAP delete delete multiple field > should delete multiple fields from package.json 1`] = ` +Object { + "name": "foo", +} +` + +exports[`test/lib/commands/pkg.js TAP delete delete nested field > should delete nested fields from package.json 1`] = ` +Object { + "info": Object { + "foo": Object { + "bar": Array [ + Object {}, + ], + }, + }, + "name": "foo", + "version": "1.0.0", +} +` + +exports[`test/lib/commands/pkg.js TAP delete delete single field > should delete single field from package.json 1`] = ` +Object { + "name": "foo", +} +` + +exports[`test/lib/commands/pkg.js TAP fix > fixes package.json issues 1`] = ` +Object { + "name": "foo", + "version": "1.1.1", +} +` + +exports[`test/lib/commands/pkg.js TAP get array field > should print retrieved array field 1`] = ` +[ 'index.js', 'cli.js' ] +` + +exports[`test/lib/commands/pkg.js TAP get array item > should print retrieved array field 1`] = ` +index.js +` + +exports[`test/lib/commands/pkg.js TAP get get array nested items notation > should print json result containing matching results 1`] = ` +contributors[0].name = 'Ruy' +contributors[1].name = 'Gar' +` + +exports[`test/lib/commands/pkg.js TAP get json no args > should print package.json content 1`] = ` +{ + "name": "foo", + "version": "1.1.1" +} +` + +exports[`test/lib/commands/pkg.js TAP get json with args > should print package.json content 1`] = ` +{ + "name": "foo" +} +` + +exports[`test/lib/commands/pkg.js TAP get multiple arg > should print retrieved package.json fields 1`] = ` +name = 'foo' +version = '1.1.1' +` + +exports[`test/lib/commands/pkg.js TAP get multiple arg with empty value > should print retrieved package.json field regardless of empty value 1`] = ` +name = 'foo' +author = '' +` + +exports[`test/lib/commands/pkg.js TAP get multiple arg with only one arg existing > should print retrieved package.json field 1`] = ` +name = 'foo' +` + +exports[`test/lib/commands/pkg.js TAP get nested arg > node test.js 1`] = ` +node test.js +` + +exports[`test/lib/commands/pkg.js TAP get no args > should print package.json content 1`] = ` +name = 'foo' +version = '1.1.1' +` + +exports[`test/lib/commands/pkg.js TAP get non string > should print retrieved package.json field 1`] = ` +{ '@npmcli/test': '*' } +` + +exports[`test/lib/commands/pkg.js TAP get single arg > should print retrieved package.json field 1`] = ` +1.1.1 +` + +exports[`test/lib/commands/pkg.js TAP set push to array syntax > should append to arrays using empty bracket syntax 1`] = ` +Object { + "keywords": Array [ + "foo", + "bar", + "baz", + ], + "name": "foo", + "version": "1.1.1", +} +` + +exports[`test/lib/commands/pkg.js TAP set set --json > should add fields to package.json 1`] = ` +Object { + "description": "awesome", + "foo": Object { + "bar": Object { + "baz": "BAZ", + }, + }, + "name": "foo", + "private": true, + "tap": Object { + "timeout": 60, + }, + "version": "1.1.1", + "workspaces": Array [ + "packages/*", + ], +} +` + +exports[`test/lib/commands/pkg.js TAP set set = separate value > should add single field to package.json 1`] = ` +Object { + "name": "foo", + "tap": Object { + "test-env": Array [ + "LC_ALL=sk", + ], + }, + "version": "1.1.1", +} +` + +exports[`test/lib/commands/pkg.js TAP set set multiple fields > should add single field to package.json 1`] = ` +Object { + "bin": Object { + "foo": "foo.js", + }, + "name": "foo", + "scripts": Object { + "test": "node test.js", + }, + "version": "1.1.1", +} +` + +exports[`test/lib/commands/pkg.js TAP set set single field > should add single field to package.json 1`] = ` +Object { + "description": "Awesome stuff", + "name": "foo", + "version": "1.1.1", +} +` + +exports[`test/lib/commands/pkg.js TAP single workspace multiple args > should only return info for one workspace 1`] = ` +a name = 'a' +a version = '1.0.0' +` + +exports[`test/lib/commands/pkg.js TAP single workspace single arg > should only return info for one workspace 1`] = ` +a 1.0.0 +` + +exports[`test/lib/commands/pkg.js TAP workspaces get > should return expected result for configured workspaces 1`] = ` +a name = 'a' +a version = '1.0.0' +b name = 'b' +b version = '1.2.3' +` + +exports[`test/lib/commands/pkg.js TAP workspaces get json > should return expected json result for configured workspaces 1`] = ` +{ + "a": { + "name": "a", + "version": "1.0.0" + }, + "b": { + "name": "b", + "version": "1.2.3" + } +} +` + +exports[`test/lib/commands/pkg.js TAP workspaces set > should add field to workspace a 1`] = ` +Object { + "funding": "http://example.com", + "name": "a", + "version": "1.0.0", +} +` + +exports[`test/lib/commands/pkg.js TAP workspaces set > should add field to workspace b 1`] = ` +Object { + "funding": "http://example.com", + "name": "b", + "version": "1.2.3", +} +` + +exports[`test/lib/commands/pkg.js TAP workspaces set > should delete version field from workspace a 1`] = ` +Object { + "funding": "http://example.com", + "name": "a", +} +` + +exports[`test/lib/commands/pkg.js TAP workspaces set > should delete version field from workspace b 1`] = ` +Object { + "funding": "http://example.com", + "name": "b", +} +` diff --git a/tap-snapshots/test/lib/commands/profile.js.test.cjs b/tap-snapshots/test/lib/commands/profile.js.test.cjs index 1fbb09de29f3c..255bd3abc4e51 100644 --- a/tap-snapshots/test/lib/commands/profile.js.test.cjs +++ b/tap-snapshots/test/lib/commands/profile.js.test.cjs @@ -40,8 +40,6 @@ created 2015-02-26T01:26:37.384Z updated 2020-08-12T16:19:35.326Z fullname Foo Bar homepage https://github.com -freenode foobar -twitter https://twitter.com/npmjs github https://github.com/npm ` @@ -51,8 +49,6 @@ email: foo@github.com (verified) two-factor auth: auth-and-writes fullname: Foo Bar homepage: https://github.com -freenode: foobar -twitter: https://twitter.com/npmjs github: https://github.com/npm created: 2015-02-26T01:26:37.384Z updated: 2020-08-12T16:19:35.326Z @@ -64,8 +60,6 @@ email: foo@github.com (verified) two-factor auth: disabled fullname: Foo Bar homepage: https://github.com -freenode: foobar -twitter: https://twitter.com/npmjs github: https://github.com/npm created: 2015-02-26T01:26:37.384Z updated: 2020-08-12T16:19:35.326Z @@ -77,8 +71,6 @@ email: foo@github.com (verified) two-factor auth: auth-and-writes fullname: Foo Bar homepage: https://github.com -freenode: foobar -twitter: https://twitter.com/npmjs github: https://github.com/npm created: 2015-02-26T01:26:37.384Z updated: 2020-08-12T16:19:35.326Z @@ -91,8 +83,6 @@ email: foo@github.com(unverified) two-factor auth: auth-and-writes fullname: Foo Bar homepage: https://github.com -freenode: foobar -twitter: https://twitter.com/npmjs github: https://github.com/npm created: 2015-02-26T01:26:37.384Z updated: 2020-08-12T16:19:35.326Z diff --git a/tap-snapshots/test/lib/commands/publish.js.test.cjs b/tap-snapshots/test/lib/commands/publish.js.test.cjs index bad7355fb9076..d037582500b62 100644 --- a/tap-snapshots/test/lib/commands/publish.js.test.cjs +++ b/tap-snapshots/test/lib/commands/publish.js.test.cjs @@ -6,7 +6,7 @@ */ 'use strict' exports[`test/lib/commands/publish.js TAP _auth config default registry > new package version 1`] = ` -+ test-package@1.0.0 ++ @npmcli/test-package@1.0.0 ` exports[`test/lib/commands/publish.js TAP bare _auth and registry config > new package version 1`] = ` @@ -15,15 +15,15 @@ exports[`test/lib/commands/publish.js TAP bare _auth and registry config > new p exports[`test/lib/commands/publish.js TAP dry-run > must match snapshot 1`] = ` Array [ - "package: test-package@1.0.0", + "package: @npmcli/test-package@1.0.0", "Tarball Contents", - "87B package.json", + "95B package.json", "Tarball Details", - "name: test-package", + "name: @npmcli/test-package", "version: 1.0.0", - "filename: test-package-1.0.0.tgz", + "filename: npmcli-test-package-1.0.0.tgz", "package size: {size}", - "unpacked size: 87 B", + "unpacked size: 95 B", "shasum: {sha}", "integrity: {integrity} "total files: 1", @@ -51,6 +51,10 @@ Array [ exports[`test/lib/commands/publish.js TAP foreground-scripts defaults to true > must match snapshot 1`] = ` Array [ + "run test-fg-scripts@0.0.0 prepack", + "run echo prepack!", + "run test-fg-scripts@0.0.0 postpack", + "run echo postpack!", "package: test-fg-scripts@0.0.0", "Tarball Contents", "110B package.json", @@ -76,7 +80,7 @@ exports[`test/lib/commands/publish.js TAP has token auth for scope configured re ` exports[`test/lib/commands/publish.js TAP ignore-scripts > new package version 1`] = ` -+ test-package@1.0.0 ++ @npmcli/test-package@1.0.0 ` exports[`test/lib/commands/publish.js TAP json > must match snapshot 1`] = ` @@ -87,23 +91,25 @@ Array [ exports[`test/lib/commands/publish.js TAP json > new package json 1`] = ` { - "id": "test-package@1.0.0", - "name": "test-package", - "version": "1.0.0", - "size": "{size}", - "unpackedSize": 87, - "shasum": "{sha}", - "integrity": "{integrity}", - "filename": "test-package-1.0.0.tgz", - "files": [ - { - "path": "package.json", - "size": "{size}", - "mode": 420 - } - ], - "entryCount": 1, - "bundled": [] + "@npmcli/test-package": { + "id": "@npmcli/test-package@1.0.0", + "name": "@npmcli/test-package", + "version": "1.0.0", + "size": "{size}", + "unpackedSize": 95, + "shasum": "{sha}", + "integrity": "{integrity}", + "filename": "npmcli-test-package-1.0.0.tgz", + "files": [ + { + "path": "package.json", + "size": "{size}", + "mode": 420 + } + ], + "entryCount": 1, + "bundled": [] + } } ` @@ -121,10 +127,6 @@ Object { "url": "https://github.com/npm/cli/issues", }, "description": "a package manager for JavaScript", - "directories": Object { - "doc": "./doc", - "man": "./man", - }, "exports": Object { ".": Array [ Object { @@ -151,93 +153,6 @@ Object { ], "license": "Artistic-2.0", "main": "./index.js", - "man": Array [ - "man/man1/npm-access.1", - "man/man1/npm-adduser.1", - "man/man1/npm-audit.1", - "man/man1/npm-bugs.1", - "man/man1/npm-cache.1", - "man/man1/npm-ci.1", - "man/man1/npm-completion.1", - "man/man1/npm-config.1", - "man/man1/npm-dedupe.1", - "man/man1/npm-deprecate.1", - "man/man1/npm-diff.1", - "man/man1/npm-dist-tag.1", - "man/man1/npm-docs.1", - "man/man1/npm-doctor.1", - "man/man1/npm-edit.1", - "man/man1/npm-exec.1", - "man/man1/npm-explain.1", - "man/man1/npm-explore.1", - "man/man1/npm-find-dupes.1", - "man/man1/npm-fund.1", - "man/man1/npm-help-search.1", - "man/man1/npm-help.1", - "man/man1/npm-hook.1", - "man/man1/npm-init.1", - "man/man1/npm-install-ci-test.1", - "man/man1/npm-install-test.1", - "man/man1/npm-install.1", - "man/man1/npm-link.1", - "man/man1/npm-login.1", - "man/man1/npm-logout.1", - "man/man1/npm-ls.1", - "man/man1/npm-org.1", - "man/man1/npm-outdated.1", - "man/man1/npm-owner.1", - "man/man1/npm-pack.1", - "man/man1/npm-ping.1", - "man/man1/npm-pkg.1", - "man/man1/npm-prefix.1", - "man/man1/npm-profile.1", - "man/man1/npm-prune.1", - "man/man1/npm-publish.1", - "man/man1/npm-query.1", - "man/man1/npm-rebuild.1", - "man/man1/npm-repo.1", - "man/man1/npm-restart.1", - "man/man1/npm-root.1", - "man/man1/npm-run-script.1", - "man/man1/npm-sbom.1", - "man/man1/npm-search.1", - "man/man1/npm-shrinkwrap.1", - "man/man1/npm-star.1", - "man/man1/npm-stars.1", - "man/man1/npm-start.1", - "man/man1/npm-stop.1", - "man/man1/npm-team.1", - "man/man1/npm-test.1", - "man/man1/npm-token.1", - "man/man1/npm-uninstall.1", - "man/man1/npm-unpublish.1", - "man/man1/npm-unstar.1", - "man/man1/npm-update.1", - "man/man1/npm-version.1", - "man/man1/npm-view.1", - "man/man1/npm-whoami.1", - "man/man1/npm.1", - "man/man1/npx.1", - "man/man5/folders.5", - "man/man5/install.5", - "man/man5/npm-global.5", - "man/man5/npm-json.5", - "man/man5/npm-shrinkwrap-json.5", - "man/man5/npmrc.5", - "man/man5/package-json.5", - "man/man5/package-lock-json.5", - "man/man7/config.7", - "man/man7/dependency-selectors.7", - "man/man7/developers.7", - "man/man7/logging.7", - "man/man7/orgs.7", - "man/man7/package-spec.7", - "man/man7/registry.7", - "man/man7/removal.7", - "man/man7/scope.7", - "man/man7/scripts.7", - "man/man7/workspaces.7", - ], "name": "npm", "readmeFilename": "README.md", "repository": Object { @@ -249,17 +164,39 @@ Object { ` exports[`test/lib/commands/publish.js TAP no auth dry-run > must match snapshot 1`] = ` -+ test-package@1.0.0 ++ @npmcli/test-package@1.0.0 ` exports[`test/lib/commands/publish.js TAP no auth dry-run > warns about auth being needed 1`] = ` Array [ - "This command requires you to be logged in to https://registry.npmjs.org/ (dry-run)", + "publish This command requires you to be logged in to https://registry.npmjs.org/ (dry-run)", ] ` exports[`test/lib/commands/publish.js TAP prioritize CLI flags over publishConfig > new package version 1`] = ` -+ test-package@1.0.0 ++ @npmcli/test-package@1.0.0 +` + +exports[`test/lib/commands/publish.js TAP private access > must match snapshot 1`] = ` +Array [ + "package: @npm/test-package@1.0.0", + "Tarball Contents", + "55B package.json", + "Tarball Details", + "name: @npm/test-package", + "version: 1.0.0", + "filename: npm-test-package-1.0.0.tgz", + "package size: {size}", + "unpacked size: 55 B", + "shasum: {sha}", + "integrity: {integrity} + "total files: 1", + "Publishing to https://registry.npmjs.org/ with tag latest and restricted access", +] +` + +exports[`test/lib/commands/publish.js TAP private access > new package version 1`] = ` ++ @npm/test-package@1.0.0 ` exports[`test/lib/commands/publish.js TAP public access > must match snapshot 1`] = ` @@ -285,11 +222,11 @@ exports[`test/lib/commands/publish.js TAP public access > new package version 1` ` exports[`test/lib/commands/publish.js TAP re-loads publishConfig.registry if added during script process > new package version 1`] = ` -+ test-package@1.0.0 ++ @npmcli/test-package@1.0.0 ` exports[`test/lib/commands/publish.js TAP respects publishConfig.registry, runs appropriate scripts > new package version 1`] = ` - ++ @npmcli/test-package@1.0.0 ` exports[`test/lib/commands/publish.js TAP restricted access > must match snapshot 1`] = ` @@ -393,6 +330,10 @@ exports[`test/lib/commands/publish.js TAP workspaces all workspaces - some marke + workspace-a@1.2.3-a ` +exports[`test/lib/commands/publish.js TAP workspaces different package spec > publish different package spec 1`] = ` ++ pkg@1.2.3 +` + exports[`test/lib/commands/publish.js TAP workspaces json > all workspaces in json 1`] = ` { "workspace-a": { diff --git a/tap-snapshots/test/lib/commands/query.js.test.cjs b/tap-snapshots/test/lib/commands/query.js.test.cjs index b41b875f8ea94..65d625b18b029 100644 --- a/tap-snapshots/test/lib/commands/query.js.test.cjs +++ b/tap-snapshots/test/lib/commands/query.js.test.cjs @@ -124,6 +124,10 @@ exports[`test/lib/commands/query.js TAP missing > should return missing node 1`] ] ` +exports[`test/lib/commands/query.js TAP package-lock-only missing workspace in tree > should return empty array for missing workspace 1`] = ` +[] +` + exports[`test/lib/commands/query.js TAP package-lock-only with package lock > should return valid response with only lock info 1`] = ` [ { @@ -172,6 +176,48 @@ exports[`test/lib/commands/query.js TAP package-lock-only with package lock > sh ] ` +exports[`test/lib/commands/query.js TAP package-lock-only with package lock and workspace > should return workspace object with package-lock-only 1`] = ` +[ + { + "name": "root", + "workspaces": [ + "packages/*" + ], + "pkgid": "root@", + "location": "", + "path": "{CWD}/prefix", + "realpath": "{CWD}/prefix", + "resolved": null, + "from": [], + "to": [ + "node_modules/a" + ], + "dev": false, + "inBundle": false, + "deduped": false, + "overridden": false, + "queryContext": {} + }, + { + "name": "a", + "version": "1.0.0", + "_id": "a@1.0.0", + "pkgid": "a@1.0.0", + "location": "packages/a", + "path": "{CWD}/prefix/packages/a", + "realpath": "{CWD}/prefix/packages/a", + "resolved": null, + "from": [], + "to": [], + "dev": false, + "inBundle": false, + "deduped": false, + "overridden": false, + "queryContext": {} + } +] +` + exports[`test/lib/commands/query.js TAP recursive tree > should return everything in the tree, accounting for recursion 1`] = ` [ { diff --git a/tap-snapshots/test/lib/commands/run.js.test.cjs b/tap-snapshots/test/lib/commands/run.js.test.cjs new file mode 100644 index 0000000000000..367415db8fe07 --- /dev/null +++ b/tap-snapshots/test/lib/commands/run.js.test.cjs @@ -0,0 +1,274 @@ +/* IMPORTANT + * This snapshot file is auto-generated, but designed for humans. + * It should be checked into source control and tracked carefully. + * Re-generate by setting TAP_SNAPSHOT=1 and running tests. + * Make sure to inspect the output below. Do not ignore changes! + */ +'use strict' +exports[`test/lib/commands/run.js TAP list scripts no args > basic report 1`] = ` +Lifecycle scripts included in x@1.2.3: + test + exit 2 + start + node server.js + stop + node kill-server.js +available via \`npm run\`: + preenv + echo before the env + postenv + echo after the env +` + +exports[`test/lib/commands/run.js TAP list scripts parseable > must match snapshot 1`] = ` +test:exit 2 +start:node server.js +stop:node kill-server.js +preenv:echo before the env +postenv:echo after the env +` + +exports[`test/lib/commands/run.js TAP list scripts warn json > json report 1`] = ` +{ + "test": "exit 2", + "start": "node server.js", + "stop": "node kill-server.js", + "preenv": "echo before the env", + "postenv": "echo after the env" +} +` + +exports[`test/lib/commands/run.js TAP list scripts, only commands > must match snapshot 1`] = ` +Lifecycle scripts included in x@1.2.3: + preversion + echo doing the version dance +` + +exports[`test/lib/commands/run.js TAP list scripts, only non-commands > must match snapshot 1`] = ` +Scripts available in x@1.2.3 via \`npm run\`: + glorp + echo doing the glerp glop +` + +exports[`test/lib/commands/run.js TAP workspaces failed workspace run with succeeded runs > should log error msgs for each workspace script 1`] = ` +Lifecycle script \`glorp\` failed with error: +code ERR +workspace a@1.0.0 +location {CWD}/prefix/packages/a +ERR +` + +exports[`test/lib/commands/run.js TAP workspaces list all scripts --json > must match snapshot 1`] = ` +{ + "a": { + "glorp": "echo a doing the glerp glop" + }, + "b": { + "glorp": "echo b doing the glerp glop" + }, + "c": { + "test": "exit 0", + "posttest": "echo posttest", + "lorem": "echo c lorem" + }, + "d": { + "test": "exit 0", + "posttest": "echo posttest" + }, + "e": { + "test": "exit 0", + "start": "echo start something" + }, + "noscripts": {} +} +` + +exports[`test/lib/commands/run.js TAP workspaces list all scripts --parseable > must match snapshot 1`] = ` +a:glorp:echo a doing the glerp glop +b:glorp:echo b doing the glerp glop +c:test:exit 0 +c:posttest:echo posttest +c:lorem:echo c lorem +d:test:exit 0 +d:posttest:echo posttest +e:test:exit 0 +e:start:echo start something +` + +exports[`test/lib/commands/run.js TAP workspaces list all scripts > must match snapshot 1`] = ` +Scripts available in a@1.0.0 via \`npm run\`: + glorp + echo a doing the glerp glop + +Scripts available in b@2.0.0 via \`npm run\`: + glorp + echo b doing the glerp glop + +Lifecycle scripts included in c@1.0.0: + test + exit 0 + posttest + echo posttest +available via \`npm run\`: + lorem + echo c lorem + +Lifecycle scripts included in d@1.0.0: + test + exit 0 + posttest + echo posttest + +Lifecycle scripts included in e: + test + exit 0 + start + echo start something +` + +exports[`test/lib/commands/run.js TAP workspaces list all scripts with colors > must match snapshot 1`] = ` +Scripts available in a@1.0.0 via \`npm run\`: + glorp + echo a doing the glerp glop + +Scripts available in b@2.0.0 via \`npm run\`: + glorp + echo b doing the glerp glop + +Lifecycle scripts included in c@1.0.0: + test + exit 0 + posttest + echo posttest +available via \`npm run\`: + lorem + echo c lorem + +Lifecycle scripts included in d@1.0.0: + test + exit 0 + posttest + echo posttest + +Lifecycle scripts included in e: + test + exit 0 + start + echo start something +` + +exports[`test/lib/commands/run.js TAP workspaces list regular scripts, filtered by name > must match snapshot 1`] = ` +Scripts available in a@1.0.0 via \`npm run\`: + glorp + echo a doing the glerp glop + +Scripts available in b@2.0.0 via \`npm run\`: + glorp + echo b doing the glerp glop +` + +exports[`test/lib/commands/run.js TAP workspaces list regular scripts, filtered by parent folder > must match snapshot 1`] = ` +Scripts available in a@1.0.0 via \`npm run\`: + glorp + echo a doing the glerp glop + +Scripts available in b@2.0.0 via \`npm run\`: + glorp + echo b doing the glerp glop + +Lifecycle scripts included in c@1.0.0: + test + exit 0 + posttest + echo posttest +available via \`npm run\`: + lorem + echo c lorem + +Lifecycle scripts included in d@1.0.0: + test + exit 0 + posttest + echo posttest + +Lifecycle scripts included in e: + test + exit 0 + start + echo start something +` + +exports[`test/lib/commands/run.js TAP workspaces list regular scripts, filtered by path > must match snapshot 1`] = ` +Scripts available in a@1.0.0 via \`npm run\`: + glorp + echo a doing the glerp glop +` + +exports[`test/lib/commands/run.js TAP workspaces missing scripts in all workspaces > should log error msgs for each workspace script 1`] = ` +Lifecycle script \`missing-script\` failed with error: +workspace a@1.0.0 +location {CWD}/prefix/packages/a +Missing script: "missing-script" +npm error +To see a list of scripts, run: + npm run --workspace=a@1.0.0 +Lifecycle script \`missing-script\` failed with error: +workspace b@2.0.0 +location {CWD}/prefix/packages/b +Missing script: "missing-script" +npm error +To see a list of scripts, run: + npm run --workspace=b@2.0.0 +Lifecycle script \`missing-script\` failed with error: +workspace c@1.0.0 +location {CWD}/prefix/packages/c +Missing script: "missing-script" +npm error +To see a list of scripts, run: + npm run --workspace=c@1.0.0 +Lifecycle script \`missing-script\` failed with error: +workspace d@1.0.0 +location {CWD}/prefix/packages/d +Missing script: "missing-script" +npm error +To see a list of scripts, run: + npm run --workspace=d@1.0.0 +Lifecycle script \`missing-script\` failed with error: +workspace e +location {CWD}/prefix/packages/e +Missing script: "missing-script" +npm error +To see a list of scripts, run: + npm run --workspace=e +Lifecycle script \`missing-script\` failed with error: +workspace noscripts@1.0.0 +location {CWD}/prefix/packages/noscripts +Missing script: "missing-script" +npm error +To see a list of scripts, run: + npm run --workspace=noscripts@1.0.0 +` + +exports[`test/lib/commands/run.js TAP workspaces missing scripts in some workspaces > should log error msgs for each workspace script 1`] = ` +Lifecycle script \`test\` failed with error: +workspace a@1.0.0 +location {CWD}/prefix/packages/a +Missing script: "test" +npm error +To see a list of scripts, run: + npm run --workspace=a@1.0.0 +Lifecycle script \`test\` failed with error: +workspace b@2.0.0 +location {CWD}/prefix/packages/b +Missing script: "test" +npm error +To see a list of scripts, run: + npm run --workspace=b@2.0.0 +` + +exports[`test/lib/commands/run.js TAP workspaces single failed workspace run > should log error msgs for each workspace script 1`] = ` +Lifecycle script \`test\` failed with error: +workspace c@1.0.0 +location {CWD}/prefix/packages/c +err +` diff --git a/tap-snapshots/test/lib/commands/sbom.js.test.cjs b/tap-snapshots/test/lib/commands/sbom.js.test.cjs index 826cf074e6038..2643ac44ce7a1 100644 --- a/tap-snapshots/test/lib/commands/sbom.js.test.cjs +++ b/tap-snapshots/test/lib/commands/sbom.js.test.cjs @@ -11,7 +11,7 @@ exports[`test/lib/commands/sbom.js TAP sbom --omit dev > must match snapshot 1`] "dataLicense": "CC0-1.0", "SPDXID": "SPDXRef-DOCUMENT", "name": "test-npm-sbom@1.0.0", - "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-00000000-0000-0000-0000-000000000000", + "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-12345678-90ab-cdef-1234-567890abcdef", "creationInfo": { "created": "2020-01-01T00:00:00.000Z", "creators": [ @@ -101,7 +101,7 @@ exports[`test/lib/commands/sbom.js TAP sbom --omit optional > must match snapsho "dataLicense": "CC0-1.0", "SPDXID": "SPDXRef-DOCUMENT", "name": "test-npm-sbom@1.0.0", - "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-00000000-0000-0000-0000-000000000000", + "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-12345678-90ab-cdef-1234-567890abcdef", "creationInfo": { "created": "2020-01-01T00:00:00.000Z", "creators": [ @@ -169,7 +169,7 @@ exports[`test/lib/commands/sbom.js TAP sbom --omit peer > must match snapshot 1` "dataLicense": "CC0-1.0", "SPDXID": "SPDXRef-DOCUMENT", "name": "test-npm-sbom@1.0.0", - "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-00000000-0000-0000-0000-000000000000", + "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-12345678-90ab-cdef-1234-567890abcdef", "creationInfo": { "created": "2020-01-01T00:00:00.000Z", "creators": [ @@ -236,7 +236,7 @@ exports[`test/lib/commands/sbom.js TAP sbom basic sbom - cyclonedx > must match "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", "bomFormat": "CycloneDX", "specVersion": "1.5", - "serialNumber": "urn:uuid:00000000-0000-0000-0000-000000000000", + "serialNumber": "urn:uuid:12345678-90ab-cdef-1234-567890abcdef", "version": 1, "metadata": { "timestamp": "2020-01-01T00:00:00.000Z", @@ -255,16 +255,11 @@ exports[`test/lib/commands/sbom.js TAP sbom basic sbom - cyclonedx > must match "component": { "bom-ref": "test-npm-sbom@1.0.0", "type": "application", - "name": "prefix", + "name": "test-npm-sbom", "version": "1.0.0", "scope": "required", "purl": "pkg:npm/test-npm-sbom@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [] } }, @@ -276,12 +271,7 @@ exports[`test/lib/commands/sbom.js TAP sbom basic sbom - cyclonedx > must match "version": "1.0.0", "scope": "required", "purl": "pkg:npm/chai@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "node_modules/chai" - } - ], + "properties": [], "externalReferences": [] }, { @@ -291,12 +281,7 @@ exports[`test/lib/commands/sbom.js TAP sbom basic sbom - cyclonedx > must match "version": "1.0.0", "scope": "required", "purl": "pkg:npm/foo@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "node_modules/foo" - } - ], + "properties": [], "externalReferences": [] }, { @@ -306,12 +291,7 @@ exports[`test/lib/commands/sbom.js TAP sbom basic sbom - cyclonedx > must match "version": "1.0.0", "scope": "required", "purl": "pkg:npm/dog@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "node_modules/foo/node_modules/dog" - } - ], + "properties": [], "externalReferences": [] } ], @@ -347,7 +327,7 @@ exports[`test/lib/commands/sbom.js TAP sbom basic sbom - spdx > must match snaps "dataLicense": "CC0-1.0", "SPDXID": "SPDXRef-DOCUMENT", "name": "test-npm-sbom@1.0.0", - "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-00000000-0000-0000-0000-000000000000", + "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-12345678-90ab-cdef-1234-567890abcdef", "creationInfo": { "created": "2020-01-01T00:00:00.000Z", "creators": [ @@ -453,13 +433,259 @@ exports[`test/lib/commands/sbom.js TAP sbom basic sbom - spdx > must match snaps } ` +exports[`test/lib/commands/sbom.js TAP sbom duplicate deps - cyclonedx > must match snapshot 1`] = ` +{ + "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "serialNumber": "urn:uuid:12345678-90ab-cdef-1234-567890abcdef", + "version": 1, + "metadata": { + "timestamp": "2020-01-01T00:00:00.000Z", + "lifecycles": [ + { + "phase": "build" + } + ], + "tools": [ + { + "vendor": "npm", + "name": "cli", + "version": "10.0.0" + } + ], + "component": { + "bom-ref": "test-npm-sbom@1.0.0", + "type": "library", + "name": "test-npm-sbom", + "version": "1.0.0", + "scope": "required", + "purl": "pkg:npm/test-npm-sbom@1.0.0", + "properties": [], + "externalReferences": [] + } + }, + "components": [ + { + "bom-ref": "bar@1.0.0", + "type": "library", + "name": "bar", + "version": "1.0.0", + "scope": "required", + "purl": "pkg:npm/bar@1.0.0", + "properties": [], + "externalReferences": [] + }, + { + "bom-ref": "chai@1.0.0", + "type": "library", + "name": "chai", + "version": "1.0.0", + "scope": "required", + "purl": "pkg:npm/chai@1.0.0", + "properties": [], + "externalReferences": [] + }, + { + "bom-ref": "chai@2.0.0", + "type": "library", + "name": "chai", + "version": "2.0.0", + "scope": "required", + "purl": "pkg:npm/chai@2.0.0", + "properties": [], + "externalReferences": [] + }, + { + "bom-ref": "foo@1.0.0", + "type": "library", + "name": "foo", + "version": "1.0.0", + "scope": "required", + "purl": "pkg:npm/foo@1.0.0", + "properties": [], + "externalReferences": [] + } + ], + "dependencies": [ + { + "ref": "test-npm-sbom@1.0.0", + "dependsOn": [ + "foo@1.0.0", + "bar@1.0.0", + "chai@2.0.0" + ] + }, + { + "ref": "bar@1.0.0", + "dependsOn": [ + "chai@1.0.0" + ] + }, + { + "ref": "chai@1.0.0", + "dependsOn": [] + }, + { + "ref": "chai@2.0.0", + "dependsOn": [] + }, + { + "ref": "foo@1.0.0", + "dependsOn": [ + "chai@1.0.0" + ] + } + ] +} +` + +exports[`test/lib/commands/sbom.js TAP sbom duplicate deps - spdx > must match snapshot 1`] = ` +{ + "spdxVersion": "SPDX-2.3", + "dataLicense": "CC0-1.0", + "SPDXID": "SPDXRef-DOCUMENT", + "name": "test-npm-sbom@1.0.0", + "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-12345678-90ab-cdef-1234-567890abcdef", + "creationInfo": { + "created": "2020-01-01T00:00:00.000Z", + "creators": [ + "Tool: npm/cli-10.0.0" + ] + }, + "documentDescribes": [ + "SPDXRef-Package-test-npm-sbom-1.0.0" + ], + "packages": [ + { + "name": "test-npm-sbom", + "SPDXID": "SPDXRef-Package-test-npm-sbom-1.0.0", + "versionInfo": "1.0.0", + "packageFileName": "", + "primaryPackagePurpose": "LIBRARY", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "NOASSERTION", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/test-npm-sbom@1.0.0" + } + ] + }, + { + "name": "bar", + "SPDXID": "SPDXRef-Package-bar-1.0.0", + "versionInfo": "1.0.0", + "packageFileName": "node_modules/bar", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "NOASSERTION", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/bar@1.0.0" + } + ] + }, + { + "name": "chai", + "SPDXID": "SPDXRef-Package-chai-1.0.0", + "versionInfo": "1.0.0", + "packageFileName": "node_modules/bar/node_modules/chai", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "NOASSERTION", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/chai@1.0.0" + } + ] + }, + { + "name": "chai", + "SPDXID": "SPDXRef-Package-chai-2.0.0", + "versionInfo": "2.0.0", + "packageFileName": "node_modules/chai", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "NOASSERTION", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/chai@2.0.0" + } + ] + }, + { + "name": "foo", + "SPDXID": "SPDXRef-Package-foo-1.0.0", + "versionInfo": "1.0.0", + "packageFileName": "node_modules/foo", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "NOASSERTION", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/foo@1.0.0" + } + ] + } + ], + "relationships": [ + { + "spdxElementId": "SPDXRef-DOCUMENT", + "relatedSpdxElement": "SPDXRef-Package-test-npm-sbom-1.0.0", + "relationshipType": "DESCRIBES" + }, + { + "spdxElementId": "SPDXRef-Package-foo-1.0.0", + "relatedSpdxElement": "SPDXRef-Package-test-npm-sbom-1.0.0", + "relationshipType": "DEPENDENCY_OF" + }, + { + "spdxElementId": "SPDXRef-Package-bar-1.0.0", + "relatedSpdxElement": "SPDXRef-Package-test-npm-sbom-1.0.0", + "relationshipType": "DEPENDENCY_OF" + }, + { + "spdxElementId": "SPDXRef-Package-chai-2.0.0", + "relatedSpdxElement": "SPDXRef-Package-test-npm-sbom-1.0.0", + "relationshipType": "DEPENDENCY_OF" + }, + { + "spdxElementId": "SPDXRef-Package-chai-1.0.0", + "relatedSpdxElement": "SPDXRef-Package-bar-1.0.0", + "relationshipType": "DEPENDENCY_OF" + }, + { + "spdxElementId": "SPDXRef-Package-chai-1.0.0", + "relatedSpdxElement": "SPDXRef-Package-foo-1.0.0", + "relationshipType": "DEPENDENCY_OF" + } + ] +} +` + exports[`test/lib/commands/sbom.js TAP sbom extraneous dep > must match snapshot 1`] = ` { "spdxVersion": "SPDX-2.3", "dataLicense": "CC0-1.0", "SPDXID": "SPDXRef-DOCUMENT", "name": "test-npm-ls@1.0.0", - "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-00000000-0000-0000-0000-000000000000", + "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-12345678-90ab-cdef-1234-567890abcdef", "creationInfo": { "created": "2020-01-01T00:00:00.000Z", "creators": [ @@ -565,13 +791,13 @@ exports[`test/lib/commands/sbom.js TAP sbom extraneous dep > must match snapshot } ` -exports[`test/lib/commands/sbom.js TAP sbom loading a tree containing workspaces should filter worksapces with --workspace > must match snapshot 1`] = ` +exports[`test/lib/commands/sbom.js TAP sbom loading a tree containing workspaces should filter workspaces with --workspace > must match snapshot 1`] = ` { "spdxVersion": "SPDX-2.3", "dataLicense": "CC0-1.0", "SPDXID": "SPDXRef-DOCUMENT", "name": "workspaces-tree@1.0.0", - "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-00000000-0000-0000-0000-000000000000", + "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-12345678-90ab-cdef-1234-567890abcdef", "creationInfo": { "created": "2020-01-01T00:00:00.000Z", "creators": [ @@ -754,7 +980,7 @@ exports[`test/lib/commands/sbom.js TAP sbom loading a tree containing workspaces "dataLicense": "CC0-1.0", "SPDXID": "SPDXRef-DOCUMENT", "name": "workspaces-tree@1.0.0", - "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-00000000-0000-0000-0000-000000000000", + "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-12345678-90ab-cdef-1234-567890abcdef", "creationInfo": { "created": "2020-01-01T00:00:00.000Z", "creators": [ @@ -844,7 +1070,7 @@ exports[`test/lib/commands/sbom.js TAP sbom loading a tree containing workspaces "dataLicense": "CC0-1.0", "SPDXID": "SPDXRef-DOCUMENT", "name": "workspaces-tree@1.0.0", - "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-00000000-0000-0000-0000-000000000000", + "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-12345678-90ab-cdef-1234-567890abcdef", "creationInfo": { "created": "2020-01-01T00:00:00.000Z", "creators": [ @@ -1115,7 +1341,7 @@ exports[`test/lib/commands/sbom.js TAP sbom loading a tree containing workspaces "dataLicense": "CC0-1.0", "SPDXID": "SPDXRef-DOCUMENT", "name": "workspaces-tree@1.0.0", - "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-00000000-0000-0000-0000-000000000000", + "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-12345678-90ab-cdef-1234-567890abcdef", "creationInfo": { "created": "2020-01-01T00:00:00.000Z", "creators": [ @@ -1187,7 +1413,7 @@ exports[`test/lib/commands/sbom.js TAP sbom lock file only > must match snapshot "dataLicense": "CC0-1.0", "SPDXID": "SPDXRef-DOCUMENT", "name": "test-npm-ls@1.0.0", - "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-00000000-0000-0000-0000-000000000000", + "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-12345678-90ab-cdef-1234-567890abcdef", "creationInfo": { "created": "2020-01-01T00:00:00.000Z", "creators": [ @@ -1299,7 +1525,7 @@ exports[`test/lib/commands/sbom.js TAP sbom missing (optional) dep > must match "dataLicense": "CC0-1.0", "SPDXID": "SPDXRef-DOCUMENT", "name": "test-npm-ls@1.0.0", - "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-00000000-0000-0000-0000-000000000000", + "documentNamespace": "http://spdx.org/spdxdocs/test-npm-sbom-1.0.0-12345678-90ab-cdef-1234-567890abcdef", "creationInfo": { "created": "2020-01-01T00:00:00.000Z", "creators": [ diff --git a/tap-snapshots/test/lib/commands/search.js.test.cjs b/tap-snapshots/test/lib/commands/search.js.test.cjs index 7645e60abb88b..f8dc5d94f4b21 100644 --- a/tap-snapshots/test/lib/commands/search.js.test.cjs +++ b/tap-snapshots/test/lib/commands/search.js.test.cjs @@ -45,12 +45,6 @@ npm Team management APIs Version 2.0.2 published 2020-11-03 by nlf Maintainers: nlf ruyadorno darcyclarke isaacs https://npm.im/libnpmteam -libnpmhook -programmatic API for managing npm registry hooks -Version 6.0.1 published 2020-11-03 by nlf -Maintainers: nlf ruyadorno darcyclarke isaacs -Keywords: npm hooks registry npm api -https://npm.im/libnpmhook libnpmpublish Programmatic API for the bits behind npm publish and unpublish Version 4.0.0 published 2020-11-03 by nlf @@ -124,12 +118,6 @@ npm Team management APIs Version 2.0.2 published 2020-11-03 by nlf Maintainers: nlf ruyadorno darcyclarke isaacs https://npm.im/libnpmteam -libnpmhook -programmatic API for managing npm registry hooks -Version 6.0.1 published 2020-11-03 by nlf -Maintainers: nlf ruyadorno darcyclarke isaacs -Keywords: npm hooks registry npm api -https://npm.im/libnpmhook libnpmpublish Programmatic API for the bits behind npm publish and unpublish Version 4.0.0 published 2020-11-03 by nlf @@ -171,7 +159,6 @@ libnpmaccess programmatic library for \`npm access\` commands 2020-11-03 4.0.1 l libnpmorg Programmatic api for \`npm org\` commands 2020-11-03 2.0.1 libnpm,npm,package manager,api,orgs,teams libnpmsearch Programmatic API for searching in npm and compatible registries. 2020-12-08 3.1.0 npm,search,api,libnpm libnpmteam npm Team management APIs 2020-11-03 2.0.2 -libnpmhook programmatic API for managing npm registry hooks 2020-11-03 6.0.1 npm,hooks,registry,npm api libnpmpublish Programmatic API for the bits behind npm publish and unpublish 2020-11-03 4.0.0 libnpmfund Programmatic API for npm fund 2020-12-08 1.0.2 npm,npmcli,libnpm,cli,git,fund,gitfund @npmcli/map-workspaces Retrieves a name:pathname Map for a given workspaces config 2020-09-30 1.0.1 npm,,bad map,npmcli,libnpm,cli,workspaces,map-workspaces @@ -235,12 +222,6 @@ npm Team management APIs Version 2.0.2 published 2020-11-03 by nlf Maintainers: nlf ruyadorno darcyclarke isaacs https://npm.im/libnpmteam -libnpmhook -programmatic API for managing npm registry hooks -Version 6.0.1 published 2020-11-03 by nlf -Maintainers: nlf ruyadorno darcyclarke isaacs -Keywords: npm hooks registry npm api -https://npm.im/libnpmhook libnpmpublish Programmatic API for the bits behind npm publish and unpublish Version 4.0.0 published 2020-11-03 by nlf @@ -318,12 +299,6 @@ npm Team management APIs Version 2.0.2 published 2020-11-03 by nlf Maintainers: nlf ruyadorno darcyclarke isaacs https://npm.im/libnpmteam -libnpmhook -programmatic API for managing npm registry hooks -Version 6.0.1 published 2020-11-03 by nlf -Maintainers: nlf ruyadorno darcyclarke isaacs -Keywords: npm hooks registry npm api -https://npm.im/libnpmhook libnpmpublish Programmatic API for the bits behind npm publish and unpublish Version 4.0.0 published 2020-11-03 by nlf @@ -392,12 +367,6 @@ npm Team management APIs Version 2.0.2 published 2020-11-03 by nlf Maintainers: nlf ruyadorno darcyclarke isaacs https://npm.im/libnpmteam -libnpmhook -programmatic API for managing npm registry hooks -Version 6.0.1 published 2020-11-03 by nlf -Maintainers: nlf ruyadorno darcyclarke isaacs -Keywords: npm hooks registry npm api -https://npm.im/libnpmhook libnpmpublish Programmatic API for the bits behind npm publish and unpublish Version 4.0.0 published 2020-11-03 by nlf @@ -466,12 +435,6 @@ npm Team management APIs Version 2.0.2 published 2020-11-03 by nlf Maintainers: nlf ruyadorno darcyclarke isaacs https://npm.im/libnpmteam -libnpmhook -programmatic API for managing npm registry hooks -Version 6.0.1 published 2020-11-03 by nlf -Maintainers: nlf ruyadorno darcyclarke isaacs -Keywords: npm hooks registry npm api -https://npm.im/libnpmhook libnpmpublish Programmatic API for the bits behind npm publish and unpublish Version 4.0.0 published 2020-11-03 by nlf @@ -772,51 +735,6 @@ Array [ "scope": "unscoped", "version": "2.0.2", }, - Object { - "author": Object { - "email": "kzm@sykosomatic.org", - "name": "Kat Marchán", - }, - "date": "2020-11-03T19:20:45.818Z", - "description": "programmatic API for managing npm registry hooks", - "keywords": Array [ - "npm", - "hooks", - "registry", - "npm api", - ], - "links": Object { - "bugs": "https://github.com/npm/libnpmhook/issues", - "homepage": "https://github.com/npm/libnpmhook#readme", - "npm": "https://www.npmjs.com/package/libnpmhook", - "repository": "https://github.com/npm/libnpmhook", - }, - "maintainers": Array [ - Object { - "email": "quitlahok@gmail.com", - "username": "nlf", - }, - Object { - "email": "ruyadorno@hotmail.com", - "username": "ruyadorno", - }, - Object { - "email": "darcy@darcyclarke.me", - "username": "darcyclarke", - }, - Object { - "email": "i@izs.me", - "username": "isaacs", - }, - ], - "name": "libnpmhook", - "publisher": Object { - "email": "quitlahok@gmail.com", - "username": "nlf", - }, - "scope": "unscoped", - "version": "6.0.1", - }, Object { "author": Object { "email": "support@npmjs.com", @@ -1014,6 +932,152 @@ Maintainers: lukekarrys https://npm.im/pkg-no-desc ` +exports[`test/lib/commands/search.js TAP search multiple terms --color > should have expected search results with color 1`] = ` +libnpm +Collection of programmatic APIs for the npm CLI +Version 3.0.1 published 2019-07-16 by isaacs +Maintainers: nlf ruyadorno darcyclarke isaacs +Keywords: npm api package manager lib +https://npm.im/libnpm +libnpmaccess +programmatic library for \`npm access\` commands +Version 4.0.1 published 2020-11-03 by nlf +Maintainers: nlf ruyadorno darcyclarke isaacs +Keywords: libnpmaccess +https://npm.im/libnpmaccess +@evocateur/libnpmaccess +programmatic library for \`npm access\` commands +Version 3.1.2 published 2019-07-16 by evocateur +Maintainers: evocateur +https://npm.im/@evocateur/libnpmaccess +@evocateur/libnpmpublish +Programmatic API for the bits behind npm publish and unpublish +Version 1.2.2 published 2019-07-16 by evocateur +Maintainers: evocateur +https://npm.im/@evocateur/libnpmpublish +libnpmorg +Programmatic api for \`npm org\` commands +Version 2.0.1 published 2020-11-03 by nlf +Maintainers: nlf ruyadorno darcyclarke isaacs +Keywords: libnpm npm package manager api orgs teams +https://npm.im/libnpmorg +libnpmsearch +Programmatic API for searching in npm and compatible registries. +Version 3.1.0 published 2020-12-08 by isaacs +Maintainers: nlf ruyadorno darcyclarke isaacs +Keywords: npm search api libnpm +https://npm.im/libnpmsearch +libnpmteam +npm Team management APIs +Version 2.0.2 published 2020-11-03 by nlf +Maintainers: nlf ruyadorno darcyclarke isaacs +https://npm.im/libnpmteam +libnpmpublish +Programmatic API for the bits behind npm publish and unpublish +Version 4.0.0 published 2020-11-03 by nlf +Maintainers: nlf ruyadorno darcyclarke isaacs +https://npm.im/libnpmpublish +libnpmfund +Programmatic API for npm fund +Version 1.0.2 published 2020-12-08 by isaacs +Maintainers: nlf ruyadorno darcyclarke isaacs +Keywords: npm npmcli libnpm cli git fund gitfund +https://npm.im/libnpmfund +@npmcli/map-workspaces +Retrieves a name:pathname Map for a given workspaces config +Version 1.0.1 published 2020-09-30 by ruyadorno +Maintainers: nlf ruyadorno darcyclarke isaacs +Keywords: npm bad map npmcli libnpm cli workspaces map-workspaces +https://npm.im/@npmcli/map-workspaces +libnpmversion +library to do the things that 'npm version' does +Version 1.0.7 published 2020-11-04 by isaacs +Maintainers: nlf ruyadorno darcyclarke isaacs +https://npm.im/libnpmversion +@types/libnpmsearch +TypeScript definitions for libnpmsearch +Version 2.0.1 published 2019-09-26 by types +Maintainers: types +https://npm.im/@types/libnpmsearch +pkg-no-desc +Version 1.0.0 published 2019-09-26 by lukekarrys +Maintainers: lukekarrys +https://npm.im/pkg-no-desc +` + +exports[`test/lib/commands/search.js TAP search multiple terms text > should have expected search results 1`] = ` +libnpm +Collection of programmatic APIs for the npm CLI +Version 3.0.1 published 2019-07-16 by isaacs +Maintainers: nlf ruyadorno darcyclarke isaacs +Keywords: npm api package manager lib +https://npm.im/libnpm +libnpmaccess +programmatic library for \`npm access\` commands +Version 4.0.1 published 2020-11-03 by nlf +Maintainers: nlf ruyadorno darcyclarke isaacs +Keywords: libnpmaccess +https://npm.im/libnpmaccess +@evocateur/libnpmaccess +programmatic library for \`npm access\` commands +Version 3.1.2 published 2019-07-16 by evocateur +Maintainers: evocateur +https://npm.im/@evocateur/libnpmaccess +@evocateur/libnpmpublish +Programmatic API for the bits behind npm publish and unpublish +Version 1.2.2 published 2019-07-16 by evocateur +Maintainers: evocateur +https://npm.im/@evocateur/libnpmpublish +libnpmorg +Programmatic api for \`npm org\` commands +Version 2.0.1 published 2020-11-03 by nlf +Maintainers: nlf ruyadorno darcyclarke isaacs +Keywords: libnpm npm package manager api orgs teams +https://npm.im/libnpmorg +libnpmsearch +Programmatic API for searching in npm and compatible registries. +Version 3.1.0 published 2020-12-08 by isaacs +Maintainers: nlf ruyadorno darcyclarke isaacs +Keywords: npm search api libnpm +https://npm.im/libnpmsearch +libnpmteam +npm Team management APIs +Version 2.0.2 published 2020-11-03 by nlf +Maintainers: nlf ruyadorno darcyclarke isaacs +https://npm.im/libnpmteam +libnpmpublish +Programmatic API for the bits behind npm publish and unpublish +Version 4.0.0 published 2020-11-03 by nlf +Maintainers: nlf ruyadorno darcyclarke isaacs +https://npm.im/libnpmpublish +libnpmfund +Programmatic API for npm fund +Version 1.0.2 published 2020-12-08 by isaacs +Maintainers: nlf ruyadorno darcyclarke isaacs +Keywords: npm npmcli libnpm cli git fund gitfund +https://npm.im/libnpmfund +@npmcli/map-workspaces +Retrieves a name:pathname Map for a given workspaces config +Version 1.0.1 published 2020-09-30 by ruyadorno +Maintainers: nlf ruyadorno darcyclarke isaacs +Keywords: npm bad map npmcli libnpm cli workspaces map-workspaces +https://npm.im/@npmcli/map-workspaces +libnpmversion +library to do the things that 'npm version' does +Version 1.0.7 published 2020-11-04 by isaacs +Maintainers: nlf ruyadorno darcyclarke isaacs +https://npm.im/libnpmversion +@types/libnpmsearch +TypeScript definitions for libnpmsearch +Version 2.0.1 published 2019-09-26 by types +Maintainers: types +https://npm.im/@types/libnpmsearch +pkg-no-desc +Version 1.0.0 published 2019-09-26 by lukekarrys +Maintainers: lukekarrys +https://npm.im/pkg-no-desc +` + exports[`test/lib/commands/search.js TAP search no publisher > should have filtered expected search results 1`] = ` custom-registry Version 1.0.0 published prehistoric by ??? diff --git a/tap-snapshots/test/lib/commands/shrinkwrap.js.test.cjs b/tap-snapshots/test/lib/commands/shrinkwrap.js.test.cjs deleted file mode 100644 index 96b41b117d19b..0000000000000 --- a/tap-snapshots/test/lib/commands/shrinkwrap.js.test.cjs +++ /dev/null @@ -1,435 +0,0 @@ -/* IMPORTANT - * This snapshot file is auto-generated, but designed for humans. - * It should be checked into source control and tracked carefully. - * Re-generate by setting TAP_SNAPSHOT=1 and running tests. - * Make sure to inspect the output below. Do not ignore changes! - */ -'use strict' -exports[`test/lib/commands/shrinkwrap.js TAP with hidden lockfile ancient > must match snapshot 1`] = ` -{ - "localPrefix": { - "node_modules": { - ".package-lock.json": { - "lockfileVersion": 1 - } - } - }, - "config": {}, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 1, - "requires": true - }, - "logs": [ - "created a lockfile as npm-shrinkwrap.json" - ], - "warn": [] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with hidden lockfile ancient upgrade > must match snapshot 1`] = ` -{ - "localPrefix": { - "node_modules": { - ".package-lock.json": { - "lockfileVersion": 1 - } - } - }, - "config": { - "lockfile-version": 3 - }, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 3, - "requires": true, - "packages": {} - }, - "logs": [ - "created a lockfile as npm-shrinkwrap.json with version 3" - ], - "warn": [ - "shrinkwrap Converting lock file (npm-shrinkwrap.json) from v1 -> v3" - ] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with hidden lockfile existing > must match snapshot 1`] = ` -{ - "localPrefix": { - "node_modules": { - ".package-lock.json": { - "lockfileVersion": 2 - } - } - }, - "config": {}, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 2, - "requires": true, - "packages": {} - }, - "logs": [ - "created a lockfile as npm-shrinkwrap.json" - ], - "warn": [] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with hidden lockfile existing downgrade > must match snapshot 1`] = ` -{ - "localPrefix": { - "node_modules": { - ".package-lock.json": { - "lockfileVersion": 2 - } - } - }, - "config": { - "lockfile-version": 1 - }, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 1, - "requires": true - }, - "logs": [ - "created a lockfile as npm-shrinkwrap.json with version 1" - ], - "warn": [ - "shrinkwrap Converting lock file (npm-shrinkwrap.json) from v2 -> v1" - ] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with hidden lockfile existing upgrade > must match snapshot 1`] = ` -{ - "localPrefix": { - "node_modules": { - ".package-lock.json": { - "lockfileVersion": 2 - } - } - }, - "config": { - "lockfile-version": 3 - }, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 3, - "requires": true, - "packages": {} - }, - "logs": [ - "created a lockfile as npm-shrinkwrap.json with version 3" - ], - "warn": [ - "shrinkwrap Converting lock file (npm-shrinkwrap.json) from v2 -> v3" - ] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with nothing ancient > must match snapshot 1`] = ` -{ - "localPrefix": {}, - "config": {}, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 3, - "requires": true, - "packages": {} - }, - "logs": [ - "created a lockfile as npm-shrinkwrap.json with version 3" - ], - "warn": [] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with nothing ancient upgrade > must match snapshot 1`] = ` -{ - "localPrefix": {}, - "config": { - "lockfile-version": 3 - }, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 3, - "requires": true, - "packages": {} - }, - "logs": [ - "created a lockfile as npm-shrinkwrap.json with version 3" - ], - "warn": [] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with npm-shrinkwrap.json ancient > must match snapshot 1`] = ` -{ - "localPrefix": { - "npm-shrinkwrap.json": { - "lockfileVersion": 1 - } - }, - "config": {}, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "prefix" - } - } - }, - "logs": [ - "npm-shrinkwrap.json updated to version 3" - ], - "warn": [ - "shrinkwrap Converting lock file (npm-shrinkwrap.json) from v1 -> v3" - ] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with npm-shrinkwrap.json ancient upgrade > must match snapshot 1`] = ` -{ - "localPrefix": { - "npm-shrinkwrap.json": { - "lockfileVersion": 1 - } - }, - "config": { - "lockfile-version": 3 - }, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "prefix" - } - } - }, - "logs": [ - "npm-shrinkwrap.json updated to version 3" - ], - "warn": [ - "shrinkwrap Converting lock file (npm-shrinkwrap.json) from v1 -> v3" - ] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with npm-shrinkwrap.json existing > must match snapshot 1`] = ` -{ - "localPrefix": { - "npm-shrinkwrap.json": { - "lockfileVersion": 2 - } - }, - "config": {}, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "prefix" - } - } - }, - "logs": [ - "npm-shrinkwrap.json up to date" - ], - "warn": [] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with npm-shrinkwrap.json existing downgrade > must match snapshot 1`] = ` -{ - "localPrefix": { - "npm-shrinkwrap.json": { - "lockfileVersion": 2 - } - }, - "config": { - "lockfile-version": 1 - }, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 1, - "requires": true - }, - "logs": [ - "npm-shrinkwrap.json updated to version 1" - ], - "warn": [ - "shrinkwrap Converting lock file (npm-shrinkwrap.json) from v2 -> v1" - ] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with npm-shrinkwrap.json existing upgrade > must match snapshot 1`] = ` -{ - "localPrefix": { - "npm-shrinkwrap.json": { - "lockfileVersion": 2 - } - }, - "config": { - "lockfile-version": 3 - }, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "prefix" - } - } - }, - "logs": [ - "npm-shrinkwrap.json updated to version 3" - ], - "warn": [ - "shrinkwrap Converting lock file (npm-shrinkwrap.json) from v2 -> v3" - ] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with package-lock.json ancient > must match snapshot 1`] = ` -{ - "localPrefix": { - "package-lock.json": { - "lockfileVersion": 1 - } - }, - "config": {}, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "prefix" - } - } - }, - "logs": [ - "package-lock.json has been renamed to npm-shrinkwrap.json and updated to version 3" - ], - "warn": [ - "shrinkwrap Converting lock file (npm-shrinkwrap.json) from v1 -> v3" - ] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with package-lock.json ancient upgrade > must match snapshot 1`] = ` -{ - "localPrefix": { - "package-lock.json": { - "lockfileVersion": 1 - } - }, - "config": { - "lockfile-version": 3 - }, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "prefix" - } - } - }, - "logs": [ - "package-lock.json has been renamed to npm-shrinkwrap.json and updated to version 3" - ], - "warn": [ - "shrinkwrap Converting lock file (npm-shrinkwrap.json) from v1 -> v3" - ] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with package-lock.json existing > must match snapshot 1`] = ` -{ - "localPrefix": { - "package-lock.json": { - "lockfileVersion": 2 - } - }, - "config": {}, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "prefix" - } - } - }, - "logs": [ - "package-lock.json has been renamed to npm-shrinkwrap.json" - ], - "warn": [] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with package-lock.json existing downgrade > must match snapshot 1`] = ` -{ - "localPrefix": { - "package-lock.json": { - "lockfileVersion": 2 - } - }, - "config": { - "lockfile-version": 1 - }, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 1, - "requires": true - }, - "logs": [ - "package-lock.json has been renamed to npm-shrinkwrap.json and updated to version 1" - ], - "warn": [ - "shrinkwrap Converting lock file (npm-shrinkwrap.json) from v2 -> v1" - ] -} -` - -exports[`test/lib/commands/shrinkwrap.js TAP with package-lock.json existing upgrade > must match snapshot 1`] = ` -{ - "localPrefix": { - "package-lock.json": { - "lockfileVersion": 2 - } - }, - "config": { - "lockfile-version": 3 - }, - "shrinkwrap": { - "name": "prefix", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "prefix" - } - } - }, - "logs": [ - "package-lock.json has been renamed to npm-shrinkwrap.json and updated to version 3" - ], - "warn": [ - "shrinkwrap Converting lock file (npm-shrinkwrap.json) from v2 -> v3" - ] -} -` diff --git a/tap-snapshots/test/lib/commands/view.js.test.cjs b/tap-snapshots/test/lib/commands/view.js.test.cjs index e6cd42d0d32a5..470d4138e90fd 100644 --- a/tap-snapshots/test/lib/commands/view.js.test.cjs +++ b/tap-snapshots/test/lib/commands/view.js.test.cjs @@ -5,6 +5,22 @@ * Make sure to inspect the output below. Do not ignore changes! */ 'use strict' +exports[`test/lib/commands/view.js TAP allow-git=root, package with multiple dist‑tags and no time > must match snapshot 1`] = ` + +gray@1.1.0 | Proprietary | deps: none | versions: 1 + +dist +.tarball: http://gray/1.1.0.tgz +.shasum: b + +dist-tags: +latest: 1.1.0 +stable: 1.1.0 +old: 1.0.0 +beta: 1.2.0-beta +alpha: 1.2.0-alpha +` + exports[`test/lib/commands/view.js TAP deprecated package with license, bugs, repository and other fields > must match snapshot 1`] = ` green@1.0.0 | ACME | deps: 2 | versions: 2 @@ -23,8 +39,7 @@ dist .unpackedSize: 1.0 GB dependencies: -red: 1.0.0 -yellow: 1.0.0 +red: 1.0.0, yellow: 1.0.0 maintainers: - claudia <c@yellow.com> @@ -52,8 +67,7 @@ dist .unpackedSize: 1.0 GB dependencies: -red: 1.0.0 -yellow: 1.0.0 +red: 1.0.0, yellow: 1.0.0 maintainers: - claudia <c@yellow.com> @@ -81,8 +95,7 @@ dist .unpackedSize: 1.0 GB dependencies: -red: 1.0.0 -yellow: 1.0.0 +red: 1.0.0, yellow: 1.0.0 maintainers: - claudia <c@yellow.com> @@ -102,6 +115,11 @@ dist dist-tags: latest: 1.0.0 +z: 1.0.0 +y: 1.0.0 +v1: 1.0.0 +prev: 1.0.0 +(...and 10 more.) published {TIME} ago ` @@ -116,6 +134,11 @@ dist dist-tags: latest: 1.0.0 +z: 1.0.0 +y: 1.0.0 +v1: 1.0.0 +prev: 1.0.0 +(...and 10 more.) published {TIME} ago ` @@ -130,6 +153,11 @@ dist dist-tags: latest: 1.0.0 +z: 1.0.0 +y: 1.0.0 +v1: 1.0.0 +prev: 1.0.0 +(...and 10 more.) published {TIME} ago ` @@ -213,30 +241,7 @@ dist .unpackedSize: 1 B dependencies: -0: 1.0.0 -10: 1.0.0 -11: 1.0.0 -12: 1.0.0 -13: 1.0.0 -14: 1.0.0 -15: 1.0.0 -16: 1.0.0 -17: 1.0.0 -18: 1.0.0 -19: 1.0.0 -1: 1.0.0 -20: 1.0.0 -21: 1.0.0 -22: 1.0.0 -23: 1.0.0 -2: 1.0.0 -3: 1.0.0 -4: 1.0.0 -5: 1.0.0 -6: 1.0.0 -7: 1.0.0 -8: 1.0.0 -9: 1.0.0 +0: 1.0.0, 1: 1.0.0, 2: 1.0.0, 3: 1.0.0, 4: 1.0.0, 5: 1.0.0, 6: 1.0.0, 7: 1.0.0, 8: 1.0.0, 9: 1.0.0, 10: 1.0.0, 11: 1.0.0, 12: 1.0.0, 13: 1.0.0, 14: 1.0.0, 15: 1.0.0, 16: 1.0.0, 17: 1.0.0, 18: 1.0.0, 19: 1.0.0, 20: 1.0.0, 21: 1.0.0, 22: 1.0.0, 23: 1.0.0 (...and 1 more.) dist-tags: @@ -269,6 +274,11 @@ dist dist-tags: latest: 1.0.0 +z: 1.0.0 +y: 1.0.0 +v1: 1.0.0 +prev: 1.0.0 +(...and 10 more.) published {TIME} ago ` @@ -283,6 +293,11 @@ dist dist-tags: latest: 1.0.0 +z: 1.0.0 +y: 1.0.0 +v1: 1.0.0 +prev: 1.0.0 +(...and 10 more.) published {TIME} ago @@ -296,27 +311,34 @@ dist dist-tags: latest: 1.0.0 +z: 1.0.0 +y: 1.0.0 +v1: 1.0.0 +prev: 1.0.0 +(...and 10 more.) -published over a year from now +published {TIME} ago ` exports[`test/lib/commands/view.js TAP package with single version full json > must match snapshot 1`] = ` -{ - "_id": "single-version", - "name": "single-version", - "dist-tags": { - "latest": "1.0.0" - }, - "versions": [ - "1.0.0" - ], - "version": "1.0.0", - "dist": { - "shasum": "123", - "tarball": "http://hm.single-version.com/1.0.0.tgz", - "fileCount": 1 +[ + { + "_id": "single-version", + "name": "single-version", + "dist-tags": { + "latest": "1.0.0" + }, + "versions": [ + "1.0.0" + ], + "version": "1.0.0", + "dist": { + "shasum": "123", + "tarball": "http://hm.single-version.com/1.0.0.tgz", + "fileCount": 1 + } } -} +] ` exports[`test/lib/commands/view.js TAP specific field names array field - 1 element > must match snapshot 1`] = ` @@ -381,8 +403,7 @@ dist .unpackedSize: 1.0 GB dependencies: -red: 1.0.0 -yellow: 1.0.0 +red: 1.0.0, yellow: 1.0.0 maintainers: - claudia <c@yellow.com> @@ -396,60 +417,62 @@ error 404 404 exports[`test/lib/commands/view.js TAP workspaces 404 workspaces json > must match snapshot 1`] = ` { - "green": { - "_id": "green", - "name": "green", - "dist-tags": { - "latest": "1.0.0" - }, - "maintainers": [ - { - "name": "claudia", - "email": "c@yellow.com", - "twitter": "cyellow" + "green": [ + { + "_id": "green", + "name": "green", + "dist-tags": { + "latest": "1.0.0" + }, + "maintainers": [ + { + "name": "claudia", + "email": "c@yellow.com", + "twitter": "cyellow" + }, + { + "name": "isaacs", + "email": "i@yellow.com", + "twitter": "iyellow" + } + ], + "keywords": [ + "colors", + "green", + "crayola" + ], + "versions": [ + "1.0.0", + "1.0.1" + ], + "version": "1.0.0", + "description": "green is a very important color", + "bugs": { + "url": "http://bugs.green.com" + }, + "deprecated": true, + "repository": { + "url": "http://repository.green.com" + }, + "license": { + "type": "ACME" }, - { - "name": "isaacs", - "email": "i@yellow.com", - "twitter": "iyellow" + "bin": { + "green": "bin/green.js" + }, + "dependencies": { + "red": "1.0.0", + "yellow": "1.0.0" + }, + "dist": { + "shasum": "123", + "tarball": "http://hm.green.com/1.0.0.tgz", + "integrity": "---", + "fileCount": 1, + "unpackedSize": 1000000000 } - ], - "keywords": [ - "colors", - "green", - "crayola" - ], - "versions": [ - "1.0.0", - "1.0.1" - ], - "version": "1.0.0", - "description": "green is a very important color", - "bugs": { - "url": "http://bugs.green.com" - }, - "deprecated": true, - "repository": { - "url": "http://repository.green.com" - }, - "license": { - "type": "ACME" - }, - "bin": { - "green": "bin/green.js" - }, - "dependencies": { - "red": "1.0.0", - "yellow": "1.0.0" - }, - "dist": { - "shasum": "123", - "tarball": "http://hm.green.com/1.0.0.tgz", - "integrity": "---", - "fileCount": 1, - "unpackedSize": 1000000000 } - }, + ], "error": { "missing-package": { "code": "E404", @@ -491,8 +514,7 @@ dist .unpackedSize: 1.0 GB dependencies: -red: 1.0.0 -yellow: 1.0.0 +red: 1.0.0, yellow: 1.0.0 maintainers: - claudia <c@yellow.com> @@ -512,80 +534,84 @@ error Unknown error exports[`test/lib/commands/view.js TAP workspaces all workspaces --json > must match snapshot 1`] = ` { - "green": { - "_id": "green", - "name": "green", - "dist-tags": { - "latest": "1.0.0" - }, - "maintainers": [ - { - "name": "claudia", - "email": "c@yellow.com", - "twitter": "cyellow" + "green": [ + { + "_id": "green", + "name": "green", + "dist-tags": { + "latest": "1.0.0" + }, + "maintainers": [ + { + "name": "claudia", + "email": "c@yellow.com", + "twitter": "cyellow" + }, + { + "name": "isaacs", + "email": "i@yellow.com", + "twitter": "iyellow" + } + ], + "keywords": [ + "colors", + "green", + "crayola" + ], + "versions": [ + "1.0.0", + "1.0.1" + ], + "version": "1.0.0", + "description": "green is a very important color", + "bugs": { + "url": "http://bugs.green.com" + }, + "deprecated": true, + "repository": { + "url": "http://repository.green.com" + }, + "license": { + "type": "ACME" }, - { - "name": "isaacs", - "email": "i@yellow.com", - "twitter": "iyellow" + "bin": { + "green": "bin/green.js" + }, + "dependencies": { + "red": "1.0.0", + "yellow": "1.0.0" + }, + "dist": { + "shasum": "123", + "tarball": "http://hm.green.com/1.0.0.tgz", + "integrity": "---", + "fileCount": 1, + "unpackedSize": 1000000000 } - ], - "keywords": [ - "colors", - "green", - "crayola" - ], - "versions": [ - "1.0.0", - "1.0.1" - ], - "version": "1.0.0", - "description": "green is a very important color", - "bugs": { - "url": "http://bugs.green.com" - }, - "deprecated": true, - "repository": { - "url": "http://repository.green.com" - }, - "license": { - "type": "ACME" - }, - "bin": { - "green": "bin/green.js" - }, - "dependencies": { - "red": "1.0.0", - "yellow": "1.0.0" - }, - "dist": { - "shasum": "123", - "tarball": "http://hm.green.com/1.0.0.tgz", - "integrity": "---", - "fileCount": 1, - "unpackedSize": 1000000000 } - }, - "orange": { - "name": "orange", - "dist-tags": { - "latest": "1.0.0" - }, - "versions": [ - "1.0.0", - "1.0.1" - ], - "version": "1.0.0", - "homepage": "http://hm.orange.com", - "license": {}, - "dist": { - "shasum": "123", - "tarball": "http://hm.orange.com/1.0.0.tgz", - "integrity": "---", - "fileCount": 1, - "unpackedSize": 1 + ], + "orange": [ + { + "name": "orange", + "dist-tags": { + "latest": "1.0.0" + }, + "versions": [ + "1.0.0", + "1.0.1" + ], + "version": "1.0.0", + "homepage": "http://hm.orange.com", + "license": {}, + "dist": { + "shasum": "123", + "tarball": "http://hm.orange.com/1.0.0.tgz", + "integrity": "---", + "fileCount": 1, + "unpackedSize": 1 + } } - } + ] } ` @@ -607,8 +633,7 @@ dist .unpackedSize: 1.0 GB dependencies: -red: 1.0.0 -yellow: 1.0.0 +red: 1.0.0, yellow: 1.0.0 maintainers: - claudia <c@yellow.com> @@ -641,8 +666,12 @@ orange: exports[`test/lib/commands/view.js TAP workspaces all workspaces single field --json > must match snapshot 1`] = ` { - "green": "green", - "orange": "orange" + "green": [ + "green" + ], + "orange": [ + "orange" + ] } ` @@ -671,8 +700,7 @@ dist .unpackedSize: 1.0 GB dependencies: -red: 1.0.0 -yellow: 1.0.0 +red: 1.0.0, yellow: 1.0.0 maintainers: - claudia <c@yellow.com> @@ -704,59 +732,61 @@ Array [ exports[`test/lib/commands/view.js TAP workspaces single workspace --json > must match snapshot 1`] = ` { - "green": { - "_id": "green", - "name": "green", - "dist-tags": { - "latest": "1.0.0" - }, - "maintainers": [ - { - "name": "claudia", - "email": "c@yellow.com", - "twitter": "cyellow" + "green": [ + { + "_id": "green", + "name": "green", + "dist-tags": { + "latest": "1.0.0" + }, + "maintainers": [ + { + "name": "claudia", + "email": "c@yellow.com", + "twitter": "cyellow" + }, + { + "name": "isaacs", + "email": "i@yellow.com", + "twitter": "iyellow" + } + ], + "keywords": [ + "colors", + "green", + "crayola" + ], + "versions": [ + "1.0.0", + "1.0.1" + ], + "version": "1.0.0", + "description": "green is a very important color", + "bugs": { + "url": "http://bugs.green.com" }, - { - "name": "isaacs", - "email": "i@yellow.com", - "twitter": "iyellow" + "deprecated": true, + "repository": { + "url": "http://repository.green.com" + }, + "license": { + "type": "ACME" + }, + "bin": { + "green": "bin/green.js" + }, + "dependencies": { + "red": "1.0.0", + "yellow": "1.0.0" + }, + "dist": { + "shasum": "123", + "tarball": "http://hm.green.com/1.0.0.tgz", + "integrity": "---", + "fileCount": 1, + "unpackedSize": 1000000000 } - ], - "keywords": [ - "colors", - "green", - "crayola" - ], - "versions": [ - "1.0.0", - "1.0.1" - ], - "version": "1.0.0", - "description": "green is a very important color", - "bugs": { - "url": "http://bugs.green.com" - }, - "deprecated": true, - "repository": { - "url": "http://repository.green.com" - }, - "license": { - "type": "ACME" - }, - "bin": { - "green": "bin/green.js" - }, - "dependencies": { - "red": "1.0.0", - "yellow": "1.0.0" - }, - "dist": { - "shasum": "123", - "tarball": "http://hm.green.com/1.0.0.tgz", - "integrity": "---", - "fileCount": 1, - "unpackedSize": 1000000000 } - } + ] } ` diff --git a/tap-snapshots/test/lib/docs.js.test.cjs b/tap-snapshots/test/lib/docs.js.test.cjs index d2b6673f38a67..c28955615d600 100644 --- a/tap-snapshots/test/lib/docs.js.test.cjs +++ b/tap-snapshots/test/lib/docs.js.test.cjs @@ -36,7 +36,6 @@ npm@{VERSION} {BASEDIR} exports[`test/lib/docs.js TAP command list > aliases 1`] = ` Object { "add": "install", - "add-user": "adduser", "author": "owner", "c": "config", "cit": "install-ci-test", @@ -73,20 +72,21 @@ Object { "rb": "rebuild", "remove": "uninstall", "rm": "uninstall", - "rum": "run-script", - "run": "run-script", + "rum": "run", + "run-script": "run", "s": "search", "se": "search", "show": "view", "sit": "install-ci-test", "t": "test", "tst": "test", + "u": "update", "udpate": "update", "un": "uninstall", "unlink": "uninstall", "up": "update", "upgrade": "update", - "urn": "run-script", + "urn": "run", "v": "view", "verison": "version", "why": "explain", @@ -97,7 +97,7 @@ Object { exports[`test/lib/docs.js TAP command list > commands 1`] = ` Array [ "access", - "adduser", + "approve-scripts", "audit", "bugs", "cache", @@ -105,6 +105,7 @@ Array [ "completion", "config", "dedupe", + "deny-scripts", "deprecate", "diff", "dist-tag", @@ -119,7 +120,6 @@ Array [ "get", "help", "help-search", - "hook", "init", "install", "install-ci-test", @@ -133,6 +133,7 @@ Array [ "outdated", "owner", "pack", + "patch", "ping", "pkg", "prefix", @@ -144,21 +145,20 @@ Array [ "repo", "restart", "root", - "run-script", + "run", "sbom", "search", "set", - "shrinkwrap", - "star", - "stars", + "stage", "start", "stop", "team", "test", "token", + "trust", + "undeprecate", "uninstall", "unpublish", - "unstar", "update", "version", "view", @@ -190,18 +190,20 @@ safer to use a registry-provided authentication bearer token stored in the * Default: 'public' for new packages, existing packages it will not change the current level -* Type: null, "restricted", or "public" +* Type: null, "restricted", "public", or "private" 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\`. +Unscoped packages cannot 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. +The value \`private\` is an alias for \`restricted\`. + #### \`all\` @@ -209,9 +211,95 @@ status\` would. * Default: false * Type: Boolean -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. +Show or act on all packages, not just the ones your project directly depends +on. For \`npm outdated\` and \`npm ls\` this lists every outdated or installed +package. For \`npm approve-scripts\` and \`npm deny-scripts\` it selects every +package with pending install scripts. + + + +#### \`allow-directory\` + +* Default: "all" +* Type: "all", "none", or "root" + +Limits the ability for npm to install dependencies from directories. That +is, dependencies that point to a directory instead of a version or semver +range. Please note that this could leave your tree incomplete and some +packages may not function as intended or designed. Changing this setting +will not remove dependencies that are already installed. + +\`all\` allows any directories to be installed. \`none\` prevents any +directories from being installed. \`root\` only allows directories defined in +your project's package.json to be installed. Also allows directory +dependencies to be used for other commands like \`npm view\` + + + +#### \`allow-file\` + +* Default: "all" +* Type: "all", "none", or "root" + +Limits the ability for npm to install dependencies from tarball files. That +is, dependencies that point to a local tarball file instead of a version or +semver range. Please note that this could leave your tree incomplete and +some packages may not function as intended or designed. Changing this +setting will not remove dependencies that are already installed. + +\`all\` allows any tarball file to be installed. \`none\` prevents any tarball +file from being installed. \`root\` only allows tarball files defined in your +project's package.json to be installed. Also allows tarball file +dependencies to be used for other commands like \`npm view\` + + + +#### \`allow-git\` + +* Default: "none" +* Type: "all", "none", or "root" + +Limits the ability for npm to fetch dependencies from git references. That +is, dependencies that point to a git repo instead of a version or semver +range. Please note that this could leave your tree incomplete and some +packages may not function as intended or designed. Changing this setting +will not remove dependencies that are already installed. + +As of npm 12 the default is \`none\`. Git dependencies run \`git\` against a +remote repo and may install configuration the project does not control. Opt +in explicitly per project (in \`.npmrc\`) or per command (on the CLI) when you +need git deps. + +\`all\` allows any git dependencies to be fetched and installed. \`none\` +prevents any git dependencies from being fetched and installed. \`root\` only +allows git dependencies defined in your project's package.json to be fetched +and installed. Also allows git dependencies to be fetched for other commands +like \`npm view\` + + + +#### \`allow-remote\` + +* Default: "none" +* Type: "all", "none", or "root" + +Limits the ability for npm to fetch dependencies from urls. That is, +dependencies that point to a tarball url instead of a version or semver +range. Please note that this could leave your tree incomplete and some +packages may not function as intended or designed. Changing this setting +will not remove dependencies that are already installed. + +As of npm 12 the default is \`none\`. Tarballs that share a hostname with the +configured registry (the typical case for the npm registry, GitHub Packages, +and most private registries) are still installed normally. If your registry +serves tarballs from a different host, set \`replace-registry-host\` or +override this setting. Opt in explicitly per project (in \`.npmrc\`) or per +command (on the CLI) when you intentionally install from a URL. + +\`all\` allows any url to be installed. \`none\` prevents any url from being +installed. \`root\` only allows urls defined in your project's package.json to +be installed. Also allows url dependencies to be used for other commands +like \`npm view\` @@ -225,6 +313,64 @@ to the same value as the current version. +#### \`allow-scripts\` + +* Default: "" +* Type: String (can be set multiple times) + +Comma-separated list of packages whose install-time lifecycle scripts +(\`preinstall\`, \`install\`, \`postinstall\`, and \`prepare\` for non-registry +dependencies) are allowed to run. + +This setting is intended for one-off and global contexts: \`npm exec\`, \`npx\`, +and \`npm install -g\`, where no project \`package.json\` is involved. For +team-wide policy in a project, use the \`allowScripts\` field in +\`package.json\` (which also supports explicit denials), or configure it in +\`.npmrc\`. Passing \`--allow-scripts\` on the command line during a +project-scoped \`npm install\`, \`ci\`, \`update\`, or \`rebuild\` is an error. + +Each name is matched against a dependency's resolved identity, not against +the package's self-reported name. \`--ignore-scripts\` and +\`--dangerously-allow-all-scripts\` both override this setting. + + + +#### \`allow-scripts-pending\` + +* Default: false +* Type: Boolean + +List packages with install scripts that are not yet covered by the +\`allowScripts\` policy, without modifying \`package.json\`. Only meaningful for +\`npm approve-scripts\`. + + + +#### \`allow-scripts-pin\` + +* Default: true +* Type: Boolean + +Write pinned (\`pkg@version\`) entries when approving install scripts. Set to +\`false\` to write name-only entries that allow any version. Has no effect on +\`npm deny-scripts\`, which always writes name-only entries regardless of this +setting. + + + +#### \`allow-unused-patches\` + +* Default: false +* Type: Boolean + +Install even when a registered patch in \`patchedDependencies\` matches no +installed package. Does not silence patch apply failures. + +This flag is only honored when passed on the command line; it is ignored in +\`.npmrc\` and environment variables, and rejected by \`npm ci\`. + + + #### \`audit\` * Default: true @@ -263,15 +409,28 @@ config is given, this value will always be set to \`legacy\`. * Type: null or Date 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. +versions that were available **on or before** the given date are installed. +If there are no versions available for the current set of 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\`. +If \`before\` and \`min-release-age\` are both set in the same source, \`before\` +wins (an explicit absolute date overrides a relative window). Across +sources, the standard precedence applies (cli > env > project > user > +global), so a higher-priority source can always relax or override a +lower-priority one. + +As with \`min-release-age\`, when this cutoff blocks a fix that \`npm audit +fix\` would install, npm keeps the vulnerable version, warns, and exits with +a non-zero code. + +Packages whose names match \`min-release-age-exclude\` are exempt from this +filter. + #### \`bin-links\` @@ -290,7 +449,7 @@ systems. #### \`browser\` -* Default: OS X: \`"open"\`, Windows: \`"start"\`, Others: \`"xdg-open"\` +* Default: macOS: \`"open"\`, Windows: \`"start"\`, Others: \`"xdg-open"\` * Type: null, Boolean, or String The browser that is called by npm commands to open websites. @@ -302,6 +461,17 @@ Set to \`true\` to use default system URL opener. +#### \`bypass-2fa\` + +* Default: false +* Type: Boolean + +When creating a Granular Access Token with \`npm token create\`, setting this +to true will allow the token to bypass two-factor authentication. This is +useful for automation and CI/CD workflows. + + + #### \`ca\` * Default: null @@ -403,9 +573,21 @@ are same as \`cpu\` field of package.json, which comes from \`process.arch\`. +#### \`dangerously-allow-all-scripts\` + +* Default: false +* Type: Boolean + +If \`true\`, bypass the \`allowScripts\` policy entirely and run every +dependency install script regardless of whether it was approved or denied. +Intended as a migration escape hatch only; its use is strongly discouraged. +\`--ignore-scripts\` still takes precedence over this setting. + + + #### \`depth\` -* Default: \`Infinity\` if \`--all\` is set, otherwise \`1\` +* Default: \`Infinity\` if \`--all\` is set; otherwise, \`0\` * Type: null or Number The depth to go when recursing packages for \`npm ls\`. @@ -514,6 +696,16 @@ Note: This is NOT honored by other network related commands, eg \`dist-tags\`, +#### \`edit-dir\` + +* Default: null +* Type: null or Path + +Override the temporary directory used by \`npm patch add\` to prepare a +package for editing. + + + #### \`editor\` * Default: The EDITOR or VISUAL environment variables, or @@ -544,7 +736,7 @@ This can be overridden by setting the \`--force\` flag. Tells to expect a specific number of results from the command. -This config can not be used with: \`expect-results\` +This config cannot be used with: \`expect-results\` #### \`expect-results\` @@ -554,7 +746,31 @@ This config can not be used with: \`expect-results\` Tells npm whether or not to expect results from the command. Can be either true (expect some results) or false (expect no results). -This config can not be used with: \`expect-result-count\` +This config cannot be used with: \`expect-result-count\` + +#### \`expires\` + +* Default: null +* Type: null or Number + +When creating a Granular Access Token with \`npm token create\`, this sets the +expiration in days. If not specified, the server will determine the default +expiration. + + + +#### \`extension-file\` + +* Default: null +* Type: null or Path + +Path to a project-local npm extension file to load instead of discovering +\`.npm-extension.mjs\` / \`.npm-extension.cjs\` at the project root. Must +resolve inside the project root and use a \`.mjs\` or \`.cjs\` extension. Only +honored from project config or the command line, never from user, global, or +builtin config. + + #### \`fetch-retries\` @@ -655,8 +871,7 @@ but can be useful for debugging. * Default: true * Type: Boolean -Format \`package-lock.json\` or \`npm-shrinkwrap.json\` as a human readable -file. +Format \`package-lock.json\` as a human readable file. @@ -707,6 +922,25 @@ folder instead of the current working directory. See +#### \`global-ignore-file\` + +* Default: The global --prefix setting plus 'etc/npmignore'. For example, + '/usr/local/etc/npmignore' +* Type: Path + +An additional ignore file applied during \`npm pack\` and \`npm publish\`, owned +by the current user rather than the package. Patterns follow the same syntax +as a package's local \`.npmignore\` file. Useful for keeping editor metadata +(such as \`.idea/\` or \`*.iml\`) and scratch directories out of every package +you publish, without adding them to each package's own ignore rules. + +The global rules apply in addition to a package's local \`.npmignore\`. When a +package uses a \`files\` field in its \`package.json\`, an entry in \`files\` that +contradicts a global rule (i.e., explicitly includes a path the global rule +would exclude) still wins. + + + #### \`globalconfig\` * Default: The global --prefix setting plus 'etc/npmrc'. For example, @@ -743,15 +977,50 @@ library. * Default: false * Type: Boolean -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 +If true, npm will not exit with an error code when \`run\` 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. This value is not exported to the environment for child processes. +#### \`ignore-existing\` + +* Default: false +* Type: Boolean + +With \`npm patch add\`, discard a previous unfinished edit directory and start +fresh. + + + +#### \`ignore-extension\` + +* Default: false +* Type: Boolean + +If true, npm does not import or execute a root \`.npm-extension.mjs\` / +\`.npm-extension.cjs\` file (or one selected via \`extension-file\`). +\`ignore-scripts\` implies \`ignore-extension\`, since both disable root-owned +install-time code. + + + +#### \`ignore-patch-failures\` + +* Default: false +* Type: Boolean + +Install even when a registered patch fails to apply, with a warning per +failure. Intended for incident response only. + +This flag is only honored when passed on the command line; it is ignored in +\`.npmrc\` and environment variables, and rejected by \`npm ci\`. + + + #### \`ignore-scripts\` * Default: false @@ -760,9 +1029,12 @@ This value is not exported to the environment for child processes. 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. +\`npm start\`, \`npm stop\`, \`npm restart\`, \`npm test\`, and \`npm run\` will still +run their intended script if \`ignore-scripts\` is set, but they will *not* +run any pre- or post-scripts. + +Setting \`ignore-scripts\` also disables \`.npm-extension\` execution, as if +\`ignore-extension\` were set. @@ -780,6 +1052,18 @@ the order in which omit/include are specified on the command-line. +#### \`include-attestations\` + +* Default: false +* Type: Boolean + +When used with \`npm audit signatures --json\`, includes the full sigstore +attestation bundles in the JSON output for each verified package. The +bundles contain DSSE envelopes, verification material, and transparency log +entries. + + + #### \`include-staged\` * Default: false @@ -835,10 +1119,11 @@ homepage. #### \`init-license\` -* Default: "ISC" +* Default: "" * Type: String -The value \`npm init\` should use by default for the package license. +The value \`npm init\` should use by default for the package license. If not +set, the license field will be omitted from new packages. @@ -854,6 +1139,25 @@ more information, or [npm init](/commands/npm-init). +#### \`init-private\` + +* Default: false +* Type: Boolean + +The value \`npm init\` should use by default for the package's private flag. + + + +#### \`init-type\` + +* Default: "commonjs" +* Type: String + +The value that \`npm init\` should use by default for the package.json type +field. + + + #### \`init-version\` * Default: "1.0.0" @@ -903,6 +1207,16 @@ Not supported by all npm commands. +#### \`keep-edit-dir\` + +* Default: false +* Type: Boolean + +With \`npm patch commit\`, do not remove the edit directory after committing +the patch. + + + #### \`legacy-peer-deps\` * Default: false @@ -973,12 +1287,12 @@ instead of the current working directory. See #### \`lockfile-version\` -* Default: Version 3 if no lockfile, auto-converting v1 lockfiles to v3, - otherwise maintain current lockfile version. +* Default: Version 3 if no lockfile, auto-converting v1 lockfiles to v3; + otherwise, maintain current lockfile version. * Type: null, 1, 2, 3, "1", "2", or "3" -Set the lockfile format version to be used in package-lock.json and -npm-shrinkwrap-json files. Possible options are: +Set the lockfile format version to be used in package-lock.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 @@ -1062,6 +1376,85 @@ Any "%s" in the message will be replaced with the version number. +#### \`min-release-age\` + +* Default: null +* Type: null or Number + +If set, npm will build the npm tree such that only versions that were +available more than the given number of days ago will be installed. If there +are no versions available for the current set of dependencies, the command +will error. + +This flag is a complement to \`before\`, which accepts an exact date instead +of a relative number of days. The two may coexist (e.g. \`min-release-age\` in +your \`.npmrc\` is preserved when npm internally spawns a sub-process with +\`--before\` while preparing a \`git:\` or \`github:\` dependency); when both +apply, \`before\` wins within a single source and across sources the standard +precedence rules apply. + +When this window stops \`npm audit fix\` from installing a patched version +(because the fix was published too recently), npm keeps the package at its +vulnerable version, warns that the fix was blocked, and exits with a +non-zero code. To install the fix, add the package to +\`min-release-age-exclude\`, or relax \`min-release-age\` or \`before\`. + +Packages whose names match \`min-release-age-exclude\` are exempt from this +filter. + +This value is not exported to the environment for child processes. + +#### \`min-release-age-exclude\` + +* Default: +* Type: String (can be set multiple times) + +A list of package names or \`minimatch\` glob patterns that are exempt from +the \`min-release-age\` (and \`before\`) filter. A matching package can always +resolve to its newest version, even when a release-age window is set. + +For example, to apply a release-age window to third-party dependencies while +letting internally maintained packages update immediately: + +\`\`\` +min-release-age=7 +min-release-age-exclude[]=@myorg/* +min-release-age-exclude[]=my-internal-pkg +\`\`\` + +Only the named package is exempt; its own dependencies still follow the +release-age policy unless they also match a pattern. Patterns match against +the package name, so \`@myorg/*\` matches \`@myorg/shared-utils\`. + +Excluding a package does not change which registry it is fetched from. You +should own your private scope on the public registry so that nobody else can +publish a package with the same name. + +This value is not exported to the environment for child processes. + +#### \`name\` + +* Default: null +* Type: null or String + +When creating a Granular Access Token with \`npm token create\`, this sets the +name/description for the token. + + + +#### \`node-gyp\` + +* Default: The path to the node-gyp bin that ships with npm +* Type: Path + +This is the location of the "node-gyp" bin. By default it uses one that +ships with npm itself. + +You can use this config to specify your own "node-gyp" to run when it is +required to build a package. + + + #### \`node-options\` * Default: null @@ -1097,14 +1490,13 @@ allow the CLI to fill in missing cache data, see \`--prefer-offline\`. #### \`omit\` * Default: 'dev' if the \`NODE_ENV\` environment variable is set to - 'production', otherwise empty. + 'production'; otherwise, empty. * Type: "dev", "optional", or "peer" (can be set multiple times) 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. +\`package-lock.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. @@ -1126,6 +1518,27 @@ time. +#### \`orgs\` + +* Default: null +* Type: null or String (can be set multiple times) + +When creating a Granular Access Token with \`npm token create\`, this limits +the token access to specific organizations. + + + +#### \`orgs-permission\` + +* Default: null +* Type: null, "read-only", "read-write", or "no-access" + +When creating a Granular Access Token with \`npm token create\`, sets the +permission level for organizations. Options are "read-only", "read-write", +or "no-access". + + + #### \`os\` * Default: null @@ -1193,6 +1606,37 @@ For \`list\` this means the output will be based on the tree described by the +#### \`packages\` + +* Default: +* Type: null or String (can be set multiple times) + +When creating a Granular Access Token with \`npm token create\`, this limits +the token access to specific packages. + + + +#### \`packages-all\` + +* Default: false +* Type: Boolean + +When creating a Granular Access Token with \`npm token create\`, grants the +token access to all packages instead of limiting to specific packages. + + + +#### \`packages-and-scopes-permission\` + +* Default: null +* Type: null, "read-only", "read-write", or "no-access" + +When creating a Granular Access Token with \`npm token create\`, sets the +permission level for packages and scopes. Options are "read-only", +"read-write", or "no-access". + + + #### \`parseable\` * Default: false @@ -1203,6 +1647,26 @@ Output parseable results from commands that write to standard output. For +#### \`password\` + +* Default: null +* Type: null or String + +Password for authentication. Can be provided via command line when creating +tokens, though it's generally safer to be prompted for it. + + + +#### \`patches-dir\` + +* Default: "patches" +* Type: String + +The directory, relative to the project root, where \`npm patch commit\` writes +patch files for \`patchedDependencies\`. + + + #### \`prefer-dedupe\` * Default: false @@ -1258,7 +1722,8 @@ a semver. Like the \`rc\` in \`1.2.0-rc.8\`. #### \`progress\` -* Default: \`true\` unless running in a known CI system +* Default: \`true\` when not in CI and both stderr and stdout are TTYs and not + in a dumb terminal * Type: Boolean When set to \`true\`, npm will display a progress bar during time intensive @@ -1276,7 +1741,7 @@ Set to \`false\` to suppress the progress bar. When publishing from a supported cloud CI/CD system, the package will be publicly linked to where it was built and published from. -This config can not be used with: \`provenance-file\` +This config cannot be used with: \`provenance-file\` #### \`provenance-file\` @@ -1285,7 +1750,7 @@ This config can not be used with: \`provenance-file\` When publishing, the provenance bundle at the given path will be used. -This config can not be used with: \`provenance\` +This config cannot be used with: \`provenance\` #### \`proxy\` @@ -1377,7 +1842,7 @@ Ignored if \`--save-peer\` is set, since peerDependencies cannot be bundled. Save installed packages to a package.json file as \`devDependencies\`. - +This config cannot be used with: \`save-optional\`, \`save-peer\`, \`save-prod\` #### \`save-exact\` @@ -1396,7 +1861,7 @@ rather than using npm's default semver range operator. Save installed packages to a package.json file as \`optionalDependencies\`. - +This config cannot be used with: \`save-dev\`, \`save-peer\`, \`save-prod\` #### \`save-peer\` @@ -1405,7 +1870,7 @@ Save installed packages to a package.json file as \`optionalDependencies\`. Save installed packages to a package.json file as \`peerDependencies\` - +This config cannot be used with: \`save-dev\`, \`save-optional\`, \`save-prod\` #### \`save-prefix\` @@ -1434,7 +1899,7 @@ 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. - +This config cannot be used with: \`save-dev\`, \`save-optional\`, \`save-peer\` #### \`sbom-format\` @@ -1487,6 +1952,17 @@ npm init --scope=@foo --yes +#### \`scopes\` + +* Default: null +* Type: null or String (can be set multiple times) + +When creating a Granular Access Token with \`npm token create\`, this limits +the token access to specific scopes. Provide a scope name (with or without @ +prefix). + + + #### \`script-shell\` * Default: '/bin/sh' on POSIX systems, 'cmd.exe' on Windows @@ -1571,6 +2047,23 @@ this to work properly. +#### \`strict-allow-scripts\` + +* Default: false +* Type: Boolean + +If \`true\`, turn the install-script policy from a warning into a hard error: +any dependency with install scripts that is not covered by \`allowScripts\` +will fail the install instead of being blocked with a warning. + +Dependencies explicitly denied with \`false\` in \`allowScripts\` are always +silently skipped; this setting only affects unreviewed entries (packages +with install scripts that are neither approved nor denied). +\`--ignore-scripts\` and \`--dangerously-allow-all-scripts\` both override this +setting. + + + #### \`strict-peer-deps\` * Default: false @@ -1654,6 +2147,26 @@ while still writing the timing file, use \`--silent\`. +#### \`to\` + +* Default: null +* Type: null or String + +Used by \`npm patch update\` to set the version to rebase a patch onto when it +cannot be read from \`package-lock.json\` — for example an exact-version +selector, or a version that has not been installed yet. + + + +#### \`token-description\` + +* Default: null +* Type: null or String + +Description text for the token when using \`npm token create\`. + + + #### \`umask\` * Default: 0 @@ -1950,7 +2463,7 @@ Alias for \`--init-author-url\` #### \`init.license\` -* Default: "ISC" +* Default: "" * Type: String * DEPRECATED: Use \`--init-license\` instead. @@ -2045,16 +2558,6 @@ Alias for --include=optional or --omit=optional Alias for \`--omit=dev\` - -#### \`shrinkwrap\` - -* Default: true -* Type: Boolean -* DEPRECATED: Use the --package-lock setting instead. - -Alias for --package-lock - - ` exports[`test/lib/docs.js TAP config > all keys 1`] = ` @@ -2063,6 +2566,11 @@ Array [ "access", "all", "allow-same-version", + "allow-directory", + "allow-file", + "allow-git", + "allow-remote", + "allow-scripts", "also", "audit", "audit-level", @@ -2070,6 +2578,7 @@ Array [ "before", "bin-links", "browser", + "bypass-2fa", "ca", "cache", "cache-max", @@ -2081,6 +2590,7 @@ Array [ "color", "commit-hooks", "cpu", + "dangerously-allow-all-scripts", "depth", "description", "dev", @@ -2097,6 +2607,8 @@ Array [ "engine-strict", "expect-result-count", "expect-results", + "expires", + "extension-file", "fetch-retries", "fetch-retry-factor", "fetch-retry-maxtimeout", @@ -2110,20 +2622,25 @@ Array [ "git-tag-version", "global", "globalconfig", + "global-ignore-file", "global-style", "heading", "https-proxy", "if-present", + "ignore-extension", "ignore-scripts", "include", "include-staged", "include-workspace-root", + "include-attestations", "init-author-email", "init-author-name", "init-author-url", "init-license", "init-module", + "init-type", "init-version", + "init-private", "init.author.email", "init.author.name", "init.author.url", @@ -2145,14 +2662,19 @@ Array [ "logs-dir", "logs-max", "long", + "name", "maxsockets", "message", + "min-release-age", + "min-release-age-exclude", + "node-gyp", "node-options", "noproxy", "offline", "omit", "omit-lockfile-registry-resolved", "only", + "orgs", "optional", "os", "otp", @@ -2160,7 +2682,16 @@ Array [ "package-lock", "package-lock-only", "pack-destination", + "packages", + "patches-dir", + "allow-unused-patches", + "ignore-patch-failures", + "edit-dir", + "ignore-existing", + "keep-edit-dir", "parseable", + "allow-scripts-pending", + "allow-scripts-pin", "prefer-dedupe", "prefer-offline", "prefer-online", @@ -2186,20 +2717,27 @@ Array [ "sbom-format", "sbom-type", "scope", + "scopes", + "packages-all", + "packages-and-scopes-permission", + "orgs-permission", + "password", + "token-description", "script-shell", "searchexclude", "searchlimit", "searchopts", "searchstaleness", "shell", - "shrinkwrap", "sign-git-commit", "sign-git-tag", "strict-peer-deps", + "strict-allow-scripts", "strict-ssl", "tag", "tag-version-prefix", "timing", + "to", "umask", "unicode", "update-notifier", @@ -2223,6 +2761,11 @@ Array [ "access", "all", "allow-same-version", + "allow-directory", + "allow-file", + "allow-git", + "allow-remote", + "allow-scripts", "also", "audit", "audit-level", @@ -2230,6 +2773,7 @@ Array [ "before", "bin-links", "browser", + "bypass-2fa", "ca", "cache", "cache-max", @@ -2241,6 +2785,7 @@ Array [ "color", "commit-hooks", "cpu", + "dangerously-allow-all-scripts", "depth", "description", "dev", @@ -2255,6 +2800,8 @@ Array [ "dry-run", "editor", "engine-strict", + "expires", + "extension-file", "fetch-retries", "fetch-retry-factor", "fetch-retry-maxtimeout", @@ -2268,14 +2815,18 @@ Array [ "git-tag-version", "global", "globalconfig", + "global-ignore-file", "global-style", "heading", "https-proxy", "if-present", + "ignore-extension", "ignore-scripts", "include", "include-staged", "include-workspace-root", + "include-attestations", + "init-private", "install-links", "install-strategy", "json", @@ -2287,13 +2838,18 @@ Array [ "location", "lockfile-version", "loglevel", + "name", "maxsockets", "message", + "min-release-age", + "min-release-age-exclude", + "node-gyp", "noproxy", "offline", "omit", "omit-lockfile-registry-resolved", "only", + "orgs", "optional", "os", "otp", @@ -2301,7 +2857,11 @@ Array [ "package-lock", "package-lock-only", "pack-destination", + "packages", + "patches-dir", "parseable", + "allow-scripts-pending", + "allow-scripts-pin", "prefer-dedupe", "prefer-offline", "prefer-online", @@ -2326,16 +2886,22 @@ Array [ "sbom-format", "sbom-type", "scope", + "scopes", + "packages-all", + "packages-and-scopes-permission", + "orgs-permission", + "password", + "token-description", "script-shell", "searchexclude", "searchlimit", "searchopts", "searchstaleness", "shell", - "shrinkwrap", "sign-git-commit", "sign-git-tag", "strict-peer-deps", + "strict-allow-scripts", "strict-ssl", "tag", "tag-version-prefix", @@ -2357,6 +2923,7 @@ Array [ "init-author-url", "init-license", "init-module", + "init-type", "init-version", "init.author.email", "init.author.name", @@ -2369,8 +2936,14 @@ Array [ "logs-max", "long", "node-options", + "allow-unused-patches", + "ignore-patch-failures", + "edit-dir", + "ignore-existing", + "keep-edit-dir", "prefix", "timing", + "to", "update-notifier", "usage", "userconfig", @@ -2387,13 +2960,21 @@ Object { "_auth": null, "access": null, "all": false, + "allowDirectory": "all", + "allowFile": "all", + "allowGit": "none", + "allowRemote": "none", "allowSameVersion": false, + "allowScripts": Array [], + "allowScriptsPending": false, + "allowScriptsPin": true, "audit": true, "auditLevel": null, "authType": "web", "before": null, "binLinks": true, "browser": null, + "bypass-2fa": false, "ca": null, "cache": "{CWD}/cache/_cacache", "call": "", @@ -2402,6 +2983,7 @@ Object { "color": false, "commitHooks": true, "cpu": null, + "dangerouslyAllowAllScripts": false, "defaultTag": "latest", "depth": null, "diff": Array [], @@ -2415,6 +2997,8 @@ Object { "dryRun": false, "editor": "{EDITOR}", "engineStrict": false, + "expires": null, + "extensionFile": null, "force": false, "foregroundScripts": false, "formatPackageLock": true, @@ -2423,12 +3007,16 @@ Object { "gitTagVersion": true, "global": false, "globalconfig": "{CWD}/global/etc/npmrc", + "globalIgnoreFile": "{CWD}/global/etc/npmignore", "heading": "npm", "httpsProxy": null, "ifPresent": false, + "ignoreExtension": false, "ignoreScripts": false, + "includeAttestations": false, "includeStaged": false, "includeWorkspaceRoot": false, + "initPrivate": false, "installLinks": false, "installStrategy": "hoisted", "json": false, @@ -2441,7 +3029,10 @@ Object { "logColor": false, "maxSockets": 15, "message": "%s", + "minReleaseAgeExclude": Array [], + "name": null, "nodeBin": "{NODE}", + "nodeGyp": "{CWD}/node_modules/node-gyp/bin/node-gyp.js", "nodeVersion": "2.2.2", "noProxy": "", "npmBin": "{CWD}/other/bin/npm-cli.js", @@ -2451,13 +3042,20 @@ Object { "offline": false, "omit": Array [], "omitLockfileRegistryResolved": false, + "orgs": null, + "orgsPermission": null, "os": null, "otp": null, "package": Array [], "packageLock": true, "packageLockOnly": false, + "packages": Array [], + "packagesAll": false, + "packagesAndScopesPermission": null, "packDestination": ".", "parseable": false, + "password": null, + "patchesDir": "patches", "preferDedupe": false, "preferOffline": false, "preferOnline": false, @@ -2483,6 +3081,7 @@ Object { "sbomFormat": null, "sbomType": "library", "scope": "", + "scopes": null, "scriptShell": undefined, "search": Object { "description": true, @@ -2495,10 +3094,12 @@ Object { "signGitCommit": false, "signGitTag": false, "silent": false, + "strictAllowScripts": false, "strictPeerDeps": false, "strictSSL": true, "tagVersionPrefix": "v", "timeout": 300000, + "tokenDescription": null, "tufCache": "{CWD}/cache/_tuf", "umask": 0, "unicode": false, @@ -2566,6 +3167,16 @@ npm access revoke [] Options: [--json] [--otp ] [--registry ] + --json + Whether or not to output JSON data, rather than the normal output. + + --otp + This is a one-time password from a two-factor authenticator. It's needed + + --registry + The base URL of the npm registry. + + Run "npm help access" for more info \`\`\`bash @@ -2585,30 +3196,44 @@ Note: This command is unaware of workspaces. #### \`registry\` ` -exports[`test/lib/docs.js TAP usage adduser > must match snapshot 1`] = ` -Add a registry user account +exports[`test/lib/docs.js TAP usage approve-scripts > must match snapshot 1`] = ` +Approve install scripts for specific dependencies Usage: -npm adduser +npm approve-scripts [ ...] +npm approve-scripts --all +npm approve-scripts --allow-scripts-pending Options: -[--registry ] [--scope <@scope>] [--auth-type ] +[-a|--all] [--allow-scripts-pending] [--no-allow-scripts-pin] [--json] -alias: add-user + -a|--all + Show or act on all packages, not just the ones your project directly -Run "npm help adduser" for more info + --allow-scripts-pending + List packages with install scripts that are not yet covered by the -\`\`\`bash -npm adduser + --allow-scripts-pin + Write pinned (\`pkg@version\`) entries when approving install scripts. -alias: add-user + --json + Whether or not to output JSON data, rather than the normal output. + + +Run "npm help approve-scripts" for more info + +\`\`\`bash +npm approve-scripts [ ...] +npm approve-scripts --all +npm approve-scripts --allow-scripts-pending \`\`\` Note: This command is unaware of workspaces. -#### \`registry\` -#### \`scope\` -#### \`auth-type\` +#### \`all\` +#### \`allow-scripts-pending\` +#### \`allow-scripts-pin\` +#### \`json\` ` exports[`test/lib/docs.js TAP usage audit > must match snapshot 1`] = ` @@ -2622,9 +3247,55 @@ Options: [--json] [--package-lock-only] [--no-package-lock] [--omit [--omit ...]] [--include [--include ...]] -[--foreground-scripts] [--ignore-scripts] +[--foreground-scripts] [--ignore-scripts] [--include-attestations] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + --audit-level + The minimum level of vulnerability for \`npm audit\` to exit with + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + -f|--force + Removes various protections against unfortunate side effects, common + + --json + Whether or not to output JSON data, rather than the normal output. + + --package-lock-only + If set to true, the current operation will only use the \`package-lock.json\`, + + --package-lock + If set to false, then ignore \`package-lock.json\` files when installing. + + --omit + Dependency types to omit from the installation tree on disk. + + --include + Option that allows for defining which types of dependencies to install. + + --foreground-scripts + Run all build scripts (ie, \`preinstall\`, \`install\`, and + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --include-attestations + When used with \`npm audit signatures --json\`, includes the full + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + Run "npm help audit" for more info @@ -2642,6 +3313,7 @@ npm audit [fix|signatures] #### \`include\` #### \`foreground-scripts\` #### \`ignore-scripts\` +#### \`include-attestations\` #### \`workspace\` #### \`workspaces\` #### \`include-workspace-root\` @@ -2657,7 +3329,23 @@ npm bugs [ [ ...]] Options: [--no-browser|--browser ] [--registry ] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] +[--workspaces] [--include-workspace-root] + + --browser + The browser that is called by npm commands to open websites. + + --registry + The base URL of the npm registry. + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + alias: issues @@ -2677,17 +3365,24 @@ alias: issues ` exports[`test/lib/docs.js TAP usage cache > must match snapshot 1`] = ` -Manipulates packages cache +Manipulates packages and npx cache Usage: npm cache add npm cache clean [] npm cache ls [@] npm cache verify +npm cache npx ls +npm cache npx rm [...] +npm cache npx info ... Options: [--cache ] + --cache + The location of npm's cache directory. + + Run "npm help cache" for more info \`\`\`bash @@ -2695,6 +3390,9 @@ npm cache add npm cache clean [] npm cache ls [@] npm cache verify +npm cache npx ls +npm cache npx rm [...] +npm cache npx info ... \`\`\` Note: This command is unaware of workspaces. @@ -2712,10 +3410,84 @@ Options: [--install-strategy ] [--legacy-bundling] [--global-style] [--omit [--omit ...]] [--include [--include ...]] -[--strict-peer-deps] [--foreground-scripts] [--ignore-scripts] [--no-audit] +[--strict-peer-deps] [--foreground-scripts] [--ignore-scripts] +[--allow-directory ] [--allow-file ] +[--allow-git ] [--allow-remote ] +[--allow-scripts [--allow-scripts ...]] +[--strict-allow-scripts] [--dangerously-allow-all-scripts] [--no-audit] [--no-bin-links] [--no-fund] [--dry-run] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + --install-strategy + Sets the strategy for installing packages in node_modules. + + --legacy-bundling + Instead of hoisting package installs in \`node_modules\`, install packages + + --global-style + Only install direct dependencies in the top level \`node_modules\`, + + --omit + Dependency types to omit from the installation tree on disk. + + --include + Option that allows for defining which types of dependencies to install. + + --strict-peer-deps + If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_ + + --foreground-scripts + Run all build scripts (ie, \`preinstall\`, \`install\`, and + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --allow-directory + Limits the ability for npm to install dependencies from directories. + + --allow-file + Limits the ability for npm to install dependencies from tarball files. + + --allow-git + Limits the ability for npm to fetch dependencies from git references. + + --allow-remote + Limits the ability for npm to fetch dependencies from urls. + + --allow-scripts + Comma-separated list of packages whose install-time lifecycle scripts + + --strict-allow-scripts + If \`true\`, turn the install-script policy from a warning into a hard + + --dangerously-allow-all-scripts + If \`true\`, bypass the \`allowScripts\` policy entirely and run every + + --audit + When "true" submit audit reports alongside the current npm command to the + + --bin-links + Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package + + --fund + When "true" displays the message at the end of each \`npm install\` + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + aliases: clean-install, ic, install-clean, isntall-clean @@ -2735,6 +3507,13 @@ aliases: clean-install, ic, install-clean, isntall-clean #### \`strict-peer-deps\` #### \`foreground-scripts\` #### \`ignore-scripts\` +#### \`allow-directory\` +#### \`allow-file\` +#### \`allow-git\` +#### \`allow-remote\` +#### \`allow-scripts\` +#### \`strict-allow-scripts\` +#### \`dangerously-allow-all-scripts\` #### \`audit\` #### \`bin-links\` #### \`fund\` @@ -2751,6 +3530,9 @@ Tab Completion for npm Usage: npm completion +Options: + + Run "npm help completion" for more info \`\`\`bash @@ -2777,6 +3559,22 @@ Options: [--json] [-g|--global] [--editor ] [-L|--location ] [-l|--long] + --json + Whether or not to output JSON data, rather than the normal output. + + -g|--global + Operates in "global" mode, so that packages are installed into the + + --editor + The command to run for \`npm edit\` and \`npm config edit\`. + + -L|--location + When passed to \`npm config\` this refers to which config file to use. + + -l|--long + Show extended information in \`ls\`, \`search\`, and \`help-search\`. + + alias: c Run "npm help config" for more info @@ -2812,9 +3610,73 @@ Options: [--global-style] [--strict-peer-deps] [--no-package-lock] [--omit [--omit ...]] [--include [--include ...]] -[--ignore-scripts] [--no-audit] [--no-bin-links] [--no-fund] [--dry-run] +[--ignore-scripts] [--allow-directory ] +[--allow-file ] [--allow-git ] +[--allow-remote ] [--no-audit] [--no-bin-links] [--no-fund] +[--dry-run] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + --install-strategy + Sets the strategy for installing packages in node_modules. + + --legacy-bundling + Instead of hoisting package installs in \`node_modules\`, install packages + + --global-style + Only install direct dependencies in the top level \`node_modules\`, + + --strict-peer-deps + If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_ + + --package-lock + If set to false, then ignore \`package-lock.json\` files when installing. + + --omit + Dependency types to omit from the installation tree on disk. + + --include + Option that allows for defining which types of dependencies to install. + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --allow-directory + Limits the ability for npm to install dependencies from directories. + + --allow-file + Limits the ability for npm to install dependencies from tarball files. + + --allow-git + Limits the ability for npm to fetch dependencies from git references. + + --allow-remote + Limits the ability for npm to fetch dependencies from urls. + + --audit + When "true" submit audit reports alongside the current npm command to the + + --bin-links + Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package + + --fund + When "true" displays the message at the end of each \`npm install\` + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + alias: ddp @@ -2834,6 +3696,10 @@ alias: ddp #### \`omit\` #### \`include\` #### \`ignore-scripts\` +#### \`allow-directory\` +#### \`allow-file\` +#### \`allow-git\` +#### \`allow-remote\` #### \`audit\` #### \`bin-links\` #### \`fund\` @@ -2844,6 +3710,44 @@ alias: ddp #### \`install-links\` ` +exports[`test/lib/docs.js TAP usage deny-scripts > must match snapshot 1`] = ` +Deny install scripts for specific dependencies + +Usage: +npm deny-scripts [ ...] +npm deny-scripts --all + +Options: +[-a|--all] [--allow-scripts-pending] [--no-allow-scripts-pin] [--json] + + -a|--all + Show or act on all packages, not just the ones your project directly + + --allow-scripts-pending + List packages with install scripts that are not yet covered by the + + --allow-scripts-pin + Write pinned (\`pkg@version\`) entries when approving install scripts. + + --json + Whether or not to output JSON data, rather than the normal output. + + +Run "npm help deny-scripts" for more info + +\`\`\`bash +npm deny-scripts [ ...] +npm deny-scripts --all +\`\`\` + +Note: This command is unaware of workspaces. + +#### \`all\` +#### \`allow-scripts-pending\` +#### \`allow-scripts-pin\` +#### \`json\` +` + exports[`test/lib/docs.js TAP usage deprecate > must match snapshot 1`] = ` Deprecate a version of a package @@ -2851,7 +3755,17 @@ Usage: npm deprecate Options: -[--registry ] [--otp ] +[--registry ] [--otp ] [--dry-run] + + --registry + The base URL of the npm registry. + + --otp + This is a one-time password from a two-factor authenticator. It's needed + + --dry-run + Indicates that you don't want npm to make any changes and that it should + Run "npm help deprecate" for more info @@ -2863,6 +3777,7 @@ Note: This command is unaware of workspaces. #### \`registry\` #### \`otp\` +#### \`dry-run\` ` exports[`test/lib/docs.js TAP usage diff > must match snapshot 1`] = ` @@ -2877,7 +3792,47 @@ Options: [--diff-src-prefix ] [--diff-dst-prefix ] [--diff-text] [-g|--global] [--tag ] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] +[--workspaces] [--include-workspace-root] + + --diff + Define arguments to compare in \`npm diff\`. + + --diff-name-only + Prints only filenames when using \`npm diff\`. + + --diff-unified + The number of lines of context to print in \`npm diff\`. + + --diff-ignore-all-space + Ignore whitespace when comparing lines in \`npm diff\`. + + --diff-no-prefix + Do not show any source or destination prefix in \`npm diff\` output. + + --diff-src-prefix + Source prefix to be used in \`npm diff\` output. + + --diff-dst-prefix + Destination prefix to be used in \`npm diff\` output. + + --diff-text + Treat all files as text in \`npm diff\`. + + -g|--global + Operates in "global" mode, so that packages are installed into the + + --tag + If you ask npm to install a package and don't tell it a specific version, + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + Run "npm help diff" for more info @@ -2910,7 +3865,17 @@ npm dist-tag ls [] Options: [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] +[--workspaces] [--include-workspace-root] + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + alias: dist-tags @@ -2938,7 +3903,23 @@ npm docs [ [ ...]] Options: [--no-browser|--browser ] [--registry ] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] +[--workspaces] [--include-workspace-root] + + --browser + The browser that is called by npm commands to open websites. + + --registry + The base URL of the npm registry. + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + alias: home @@ -2966,6 +3947,10 @@ npm doctor [connection] [registry] [versions] [environment] [permissions] [cache Options: [--registry ] + --registry + The base URL of the npm registry. + + Run "npm help doctor" for more info \`\`\`bash @@ -2986,6 +3971,10 @@ npm edit [/...] Options: [--editor ] + --editor + The command to run for \`npm edit\` and \`npm config edit\`. + + Run "npm help edit" for more info \`\`\`bash @@ -3009,7 +3998,34 @@ npm exec --package=foo -c ' [args...]' Options: [--package [--package ...]] [-c|--call ] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] +[--workspaces] [--include-workspace-root] +[--allow-scripts [--allow-scripts ...]] +[--strict-allow-scripts] [--dangerously-allow-all-scripts] + + --package + The package or packages to install for [\`npm exec\`](/commands/npm-exec) + + -c|--call + Optional companion option for \`npm exec\`, \`npx\` that allows for + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --allow-scripts + Comma-separated list of packages whose install-time lifecycle scripts + + --strict-allow-scripts + If \`true\`, turn the install-script policy from a warning into a hard + + --dangerously-allow-all-scripts + If \`true\`, bypass the \`allowScripts\` policy entirely and run every + alias: x @@ -3029,6 +4045,9 @@ alias: x #### \`workspace\` #### \`workspaces\` #### \`include-workspace-root\` +#### \`allow-scripts\` +#### \`strict-allow-scripts\` +#### \`dangerously-allow-all-scripts\` ` exports[`test/lib/docs.js TAP usage explain > must match snapshot 1`] = ` @@ -3040,6 +4059,13 @@ npm explain Options: [--json] [-w|--workspace [-w|--workspace ...]] + --json + Whether or not to output JSON data, rather than the normal output. + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + alias: why Run "npm help explain" for more info @@ -3063,6 +4089,10 @@ npm explore [ -- ] Options: [--shell ] + --shell + The shell to run for the \`npm explore\` command. + + Run "npm help explore" for more info \`\`\`bash @@ -3087,7 +4117,53 @@ Options: [--include [--include ...]] [--ignore-scripts] [--no-audit] [--no-bin-links] [--no-fund] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + --install-strategy + Sets the strategy for installing packages in node_modules. + + --legacy-bundling + Instead of hoisting package installs in \`node_modules\`, install packages + + --global-style + Only install direct dependencies in the top level \`node_modules\`, + + --strict-peer-deps + If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_ + + --package-lock + If set to false, then ignore \`package-lock.json\` files when installing. + + --omit + Dependency types to omit from the installation tree on disk. + + --include + Option that allows for defining which types of dependencies to install. + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --audit + When "true" submit audit reports alongside the current npm command to the + + --bin-links + Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package + + --fund + When "true" displays the message at the end of each \`npm install\` + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + Run "npm help find-dupes" for more info @@ -3123,6 +4199,22 @@ Options: [-w|--workspace [-w|--workspace ...]] [--which ] + --json + Whether or not to output JSON data, rather than the normal output. + + --browser + The browser that is called by npm commands to open websites. + + --unicode + When set to true, npm uses unicode characters in the tree output. When + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --which + If there are multiple funding sources, which 1-indexed source URL to open. + + Run "npm help fund" for more info \`\`\`bash @@ -3145,6 +4237,10 @@ npm get [ ...] (See \`npm config\`) Options: [-l|--long] + -l|--long + Show extended information in \`ls\`, \`search\`, and \`help-search\`. + + Run "npm help get" for more info \`\`\`bash @@ -3165,6 +4261,10 @@ npm help [] Options: [--viewer ] + --viewer + The program to use to view help content. + + alias: hlep Run "npm help help" for more info @@ -3189,6 +4289,10 @@ npm help-search Options: [-l|--long] + -l|--long + Show extended information in \`ls\`, \`search\`, and \`help-search\`. + + Run "npm help help-search" for more info \`\`\`bash @@ -3200,53 +4304,69 @@ Note: This command is unaware of workspaces. #### \`long\` ` -exports[`test/lib/docs.js TAP usage hook > must match snapshot 1`] = ` -Manage registry hooks +exports[`test/lib/docs.js TAP usage init > must match snapshot 1`] = ` +Create a package.json file Usage: -npm hook add [--type=] -npm hook ls [pkg] -npm hook rm -npm hook update +npm init (same as \`npx create-\`) +npm init <@scope> (same as \`npx <@scope>/create\`) Options: -[--registry ] [--otp ] +[--init-author-name ] [--init-author-url ] [--init-license ] +[--init-module ] [--init-type ] [--init-version ] +[--init-private] [-y|--yes] [-f|--force] [--scope <@scope>] +[-w|--workspace [-w|--workspace ...]] +[--workspaces] [--no-workspaces-update] [--include-workspace-root] -Run "npm help hook" for more info + --init-author-name + The value \`npm init\` should use by default for the package author's name. -\`\`\`bash -npm hook add [--type=] -npm hook ls [pkg] -npm hook rm -npm hook update -\`\`\` + --init-author-url + The value \`npm init\` should use by default for the package author's homepage. -Note: This command is unaware of workspaces. + --init-license + The value \`npm init\` should use by default for the package license. -#### \`registry\` -#### \`otp\` -` + --init-module + A module that will be loaded by the \`npm init\` command. See the -exports[`test/lib/docs.js TAP usage init > must match snapshot 1`] = ` -Create a package.json file + --init-type + The value that \`npm init\` should use by default for the package.json type field. -Usage: -npm init (same as \`npx \`) -npm init <@scope> (same as \`npx <@scope>/create\`) + --init-version + The value that \`npm init\` should use by default for the package + + --init-private + The value \`npm init\` should use by default for the package's private flag. + + -y|--yes + Automatically answer "yes" to any prompts that npm might print on + + -f|--force + Removes various protections against unfortunate side effects, common + + --scope + Associate an operation with a scope for a scoped registry. + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --workspaces-update + If set to true, the npm cli will run an update after operations that may + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. -Options: -[--init-author-name ] [--init-author-url ] [--init-license ] -[--init-module ] [--init-version ] [-y|--yes] [-f|--force] -[--scope <@scope>] -[-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--no-workspaces-update] [--include-workspace-root] aliases: create, innit Run "npm help init" for more info \`\`\`bash -npm init (same as \`npx \`) +npm init (same as \`npx create-\`) npm init <@scope> (same as \`npx <@scope>/create\`) aliases: create, innit @@ -3256,7 +4376,9 @@ aliases: create, innit #### \`init-author-url\` #### \`init-license\` #### \`init-module\` +#### \`init-type\` #### \`init-version\` +#### \`init-private\` #### \`yes\` #### \`force\` #### \`scope\` @@ -3279,36 +4401,159 @@ Options: [--global-style] [--omit [--omit ...]] [--include [--include ...]] [--strict-peer-deps] [--prefer-dedupe] [--no-package-lock] [--package-lock-only] -[--foreground-scripts] [--ignore-scripts] [--no-audit] [--no-bin-links] -[--no-fund] [--dry-run] [--cpu ] [--os ] [--libc ] +[--foreground-scripts] [--ignore-scripts] [--allow-directory ] +[--allow-file ] [--allow-git ] +[--allow-remote ] +[--allow-scripts [--allow-scripts ...]] +[--strict-allow-scripts] [--dangerously-allow-all-scripts] [--no-audit] +[--before ] [--min-release-age ] +[--min-release-age-exclude [--min-release-age-exclude ...]] +[--no-bin-links] [--no-fund] [--dry-run] [--cpu ] [--os ] +[--libc ] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] -aliases: add, i, in, ins, inst, insta, instal, isnt, isnta, isntal, isntall + -S|--save + Save installed packages to a \`package.json\` file as dependencies. -Run "npm help install" for more info + -E|--save-exact + Dependencies saved to package.json will be configured with an exact -\`\`\`bash -npm install [ ...] + -g|--global + Operates in "global" mode, so that packages are installed into the -aliases: add, i, in, ins, inst, insta, instal, isnt, isnta, isntal, isntall -\`\`\` + --install-strategy + Sets the strategy for installing packages in node_modules. -#### \`save\` -#### \`save-exact\` -#### \`global\` -#### \`install-strategy\` -#### \`legacy-bundling\` -#### \`global-style\` -#### \`omit\` -#### \`include\` -#### \`strict-peer-deps\` -#### \`prefer-dedupe\` -#### \`package-lock\` -#### \`package-lock-only\` + --legacy-bundling + Instead of hoisting package installs in \`node_modules\`, install packages + + --global-style + Only install direct dependencies in the top level \`node_modules\`, + + --omit + Dependency types to omit from the installation tree on disk. + + --include + Option that allows for defining which types of dependencies to install. + + --strict-peer-deps + If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_ + + --prefer-dedupe + Prefer to deduplicate packages if possible, rather than + + --package-lock + If set to false, then ignore \`package-lock.json\` files when installing. + + --package-lock-only + If set to true, the current operation will only use the \`package-lock.json\`, + + --foreground-scripts + Run all build scripts (ie, \`preinstall\`, \`install\`, and + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --allow-directory + Limits the ability for npm to install dependencies from directories. + + --allow-file + Limits the ability for npm to install dependencies from tarball files. + + --allow-git + Limits the ability for npm to fetch dependencies from git references. + + --allow-remote + Limits the ability for npm to fetch dependencies from urls. + + --allow-scripts + Comma-separated list of packages whose install-time lifecycle scripts + + --strict-allow-scripts + If \`true\`, turn the install-script policy from a warning into a hard + + --dangerously-allow-all-scripts + If \`true\`, bypass the \`allowScripts\` policy entirely and run every + + --audit + When "true" submit audit reports alongside the current npm command to the + + --before + If passed to \`npm install\`, will rebuild the npm tree such that only + + --min-release-age + If set, npm will build the npm tree such that only versions that were + + --min-release-age-exclude + A list of package names or \`minimatch\` glob patterns that are exempt + + --bin-links + Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package + + --fund + When "true" displays the message at the end of each \`npm install\` + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + --cpu + Override CPU architecture of native modules to install. + + --os + Override OS of native modules to install. + + --libc + Override libc of native modules to install. + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + + +aliases: add, i, in, ins, inst, insta, instal, isnt, isnta, isntal, isntall + +Run "npm help install" for more info + +\`\`\`bash +npm install [ ...] + +aliases: add, i, in, ins, inst, insta, instal, isnt, isnta, isntal, isntall +\`\`\` + +#### \`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\` +#### \`allow-directory\` +#### \`allow-file\` +#### \`allow-git\` +#### \`allow-remote\` +#### \`allow-scripts\` +#### \`strict-allow-scripts\` +#### \`dangerously-allow-all-scripts\` #### \`audit\` +#### \`before\` +#### \`min-release-age\` +#### \`min-release-age-exclude\` #### \`bin-links\` #### \`fund\` #### \`dry-run\` @@ -3331,10 +4576,84 @@ Options: [--install-strategy ] [--legacy-bundling] [--global-style] [--omit [--omit ...]] [--include [--include ...]] -[--strict-peer-deps] [--foreground-scripts] [--ignore-scripts] [--no-audit] +[--strict-peer-deps] [--foreground-scripts] [--ignore-scripts] +[--allow-directory ] [--allow-file ] +[--allow-git ] [--allow-remote ] +[--allow-scripts [--allow-scripts ...]] +[--strict-allow-scripts] [--dangerously-allow-all-scripts] [--no-audit] [--no-bin-links] [--no-fund] [--dry-run] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + --install-strategy + Sets the strategy for installing packages in node_modules. + + --legacy-bundling + Instead of hoisting package installs in \`node_modules\`, install packages + + --global-style + Only install direct dependencies in the top level \`node_modules\`, + + --omit + Dependency types to omit from the installation tree on disk. + + --include + Option that allows for defining which types of dependencies to install. + + --strict-peer-deps + If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_ + + --foreground-scripts + Run all build scripts (ie, \`preinstall\`, \`install\`, and + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --allow-directory + Limits the ability for npm to install dependencies from directories. + + --allow-file + Limits the ability for npm to install dependencies from tarball files. + + --allow-git + Limits the ability for npm to fetch dependencies from git references. + + --allow-remote + Limits the ability for npm to fetch dependencies from urls. + + --allow-scripts + Comma-separated list of packages whose install-time lifecycle scripts + + --strict-allow-scripts + If \`true\`, turn the install-script policy from a warning into a hard + + --dangerously-allow-all-scripts + If \`true\`, bypass the \`allowScripts\` policy entirely and run every + + --audit + When "true" submit audit reports alongside the current npm command to the + + --bin-links + Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package + + --fund + When "true" displays the message at the end of each \`npm install\` + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + aliases: cit, clean-install-test, sit @@ -3354,6 +4673,13 @@ aliases: cit, clean-install-test, sit #### \`strict-peer-deps\` #### \`foreground-scripts\` #### \`ignore-scripts\` +#### \`allow-directory\` +#### \`allow-file\` +#### \`allow-git\` +#### \`allow-remote\` +#### \`allow-scripts\` +#### \`strict-allow-scripts\` +#### \`dangerously-allow-all-scripts\` #### \`audit\` #### \`bin-links\` #### \`fund\` @@ -3377,10 +4703,123 @@ Options: [--global-style] [--omit [--omit ...]] [--include [--include ...]] [--strict-peer-deps] [--prefer-dedupe] [--no-package-lock] [--package-lock-only] -[--foreground-scripts] [--ignore-scripts] [--no-audit] [--no-bin-links] -[--no-fund] [--dry-run] [--cpu ] [--os ] [--libc ] +[--foreground-scripts] [--ignore-scripts] [--allow-directory ] +[--allow-file ] [--allow-git ] +[--allow-remote ] +[--allow-scripts [--allow-scripts ...]] +[--strict-allow-scripts] [--dangerously-allow-all-scripts] [--no-audit] +[--before ] [--min-release-age ] +[--min-release-age-exclude [--min-release-age-exclude ...]] +[--no-bin-links] [--no-fund] [--dry-run] [--cpu ] [--os ] +[--libc ] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + -S|--save + Save installed packages to a \`package.json\` file as dependencies. + + -E|--save-exact + Dependencies saved to package.json will be configured with an exact + + -g|--global + Operates in "global" mode, so that packages are installed into the + + --install-strategy + Sets the strategy for installing packages in node_modules. + + --legacy-bundling + Instead of hoisting package installs in \`node_modules\`, install packages + + --global-style + Only install direct dependencies in the top level \`node_modules\`, + + --omit + Dependency types to omit from the installation tree on disk. + + --include + Option that allows for defining which types of dependencies to install. + + --strict-peer-deps + If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_ + + --prefer-dedupe + Prefer to deduplicate packages if possible, rather than + + --package-lock + If set to false, then ignore \`package-lock.json\` files when installing. + + --package-lock-only + If set to true, the current operation will only use the \`package-lock.json\`, + + --foreground-scripts + Run all build scripts (ie, \`preinstall\`, \`install\`, and + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --allow-directory + Limits the ability for npm to install dependencies from directories. + + --allow-file + Limits the ability for npm to install dependencies from tarball files. + + --allow-git + Limits the ability for npm to fetch dependencies from git references. + + --allow-remote + Limits the ability for npm to fetch dependencies from urls. + + --allow-scripts + Comma-separated list of packages whose install-time lifecycle scripts + + --strict-allow-scripts + If \`true\`, turn the install-script policy from a warning into a hard + + --dangerously-allow-all-scripts + If \`true\`, bypass the \`allowScripts\` policy entirely and run every + + --audit + When "true" submit audit reports alongside the current npm command to the + + --before + If passed to \`npm install\`, will rebuild the npm tree such that only + + --min-release-age + If set, npm will build the npm tree such that only versions that were + + --min-release-age-exclude + A list of package names or \`minimatch\` glob patterns that are exempt + + --bin-links + Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package + + --fund + When "true" displays the message at the end of each \`npm install\` + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + --cpu + Override CPU architecture of native modules to install. + + --os + Override OS of native modules to install. + + --libc + Override libc of native modules to install. + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + alias: it @@ -3406,7 +4845,17 @@ alias: it #### \`package-lock-only\` #### \`foreground-scripts\` #### \`ignore-scripts\` +#### \`allow-directory\` +#### \`allow-file\` +#### \`allow-git\` +#### \`allow-remote\` +#### \`allow-scripts\` +#### \`strict-allow-scripts\` +#### \`dangerously-allow-all-scripts\` #### \`audit\` +#### \`before\` +#### \`min-release-age\` +#### \`min-release-age-exclude\` #### \`bin-links\` #### \`fund\` #### \`dry-run\` @@ -3432,9 +4881,82 @@ Options: [--global-style] [--strict-peer-deps] [--no-package-lock] [--omit [--omit ...]] [--include [--include ...]] -[--ignore-scripts] [--no-audit] [--no-bin-links] [--no-fund] [--dry-run] +[--ignore-scripts] [--allow-directory ] +[--allow-file ] [--allow-git ] +[--allow-remote ] [--no-audit] [--no-bin-links] [--no-fund] +[--dry-run] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + -S|--save + Save installed packages to a \`package.json\` file as dependencies. + + -E|--save-exact + Dependencies saved to package.json will be configured with an exact + + -g|--global + Operates in "global" mode, so that packages are installed into the + + --install-strategy + Sets the strategy for installing packages in node_modules. + + --legacy-bundling + Instead of hoisting package installs in \`node_modules\`, install packages + + --global-style + Only install direct dependencies in the top level \`node_modules\`, + + --strict-peer-deps + If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_ + + --package-lock + If set to false, then ignore \`package-lock.json\` files when installing. + + --omit + Dependency types to omit from the installation tree on disk. + + --include + Option that allows for defining which types of dependencies to install. + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --allow-directory + Limits the ability for npm to install dependencies from directories. + + --allow-file + Limits the ability for npm to install dependencies from tarball files. + + --allow-git + Limits the ability for npm to fetch dependencies from git references. + + --allow-remote + Limits the ability for npm to fetch dependencies from urls. + + --audit + When "true" submit audit reports alongside the current npm command to the + + --bin-links + Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package + + --fund + When "true" displays the message at the end of each \`npm install\` + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + alias: ln @@ -3457,6 +4979,10 @@ alias: ln #### \`omit\` #### \`include\` #### \`ignore-scripts\` +#### \`allow-directory\` +#### \`allow-file\` +#### \`allow-git\` +#### \`allow-remote\` #### \`audit\` #### \`bin-links\` #### \`fund\` @@ -3479,7 +5005,53 @@ Options: [--include [--include ...]] [--link] [--package-lock-only] [--unicode] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + -a|--all + Show or act on all packages, not just the ones your project directly + + --json + Whether or not to output JSON data, rather than the normal output. + + -l|--long + Show extended information in \`ls\`, \`search\`, and \`help-search\`. + + -p|--parseable + Output parseable results from commands that write to standard output. For + + -g|--global + Operates in "global" mode, so that packages are installed into the + + --depth + The depth to go when recursing packages for \`npm ls\`. + + --omit + Dependency types to omit from the installation tree on disk. + + --include + Option that allows for defining which types of dependencies to install. + + --link + Used with \`npm ls\`, limiting output to only those packages that are + + --package-lock-only + If set to true, the current operation will only use the \`package-lock.json\`, + + --unicode + When set to true, npm uses unicode characters in the tree output. When + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + alias: la @@ -3517,6 +5089,16 @@ npm login Options: [--registry ] [--scope <@scope>] [--auth-type ] + --registry + The base URL of the npm registry. + + --scope + Associate an operation with a scope for a scoped registry. + + --auth-type + What authentication strategy to use with \`login\`. + + Run "npm help login" for more info \`\`\`bash @@ -3539,6 +5121,13 @@ npm logout Options: [--registry ] [--scope <@scope>] + --registry + The base URL of the npm registry. + + --scope + Associate an operation with a scope for a scoped registry. + + Run "npm help logout" for more info \`\`\`bash @@ -3563,7 +5152,53 @@ Options: [--include [--include ...]] [--link] [--package-lock-only] [--unicode] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + -a|--all + Show or act on all packages, not just the ones your project directly + + --json + Whether or not to output JSON data, rather than the normal output. + + -l|--long + Show extended information in \`ls\`, \`search\`, and \`help-search\`. + + -p|--parseable + Output parseable results from commands that write to standard output. For + + -g|--global + Operates in "global" mode, so that packages are installed into the + + --depth + The depth to go when recursing packages for \`npm ls\`. + + --omit + Dependency types to omit from the installation tree on disk. + + --include + Option that allows for defining which types of dependencies to install. + + --link + Used with \`npm ls\`, limiting output to only those packages that are + + --package-lock-only + If set to true, the current operation will only use the \`package-lock.json\`, + + --unicode + When set to true, npm uses unicode characters in the tree output. When + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + alias: list @@ -3624,6 +5259,19 @@ npm org ls orgname [] Options: [--registry ] [--otp ] [--json] [-p|--parseable] + --registry + The base URL of the npm registry. + + --otp + This is a one-time password from a two-factor authenticator. It's needed + + --json + Whether or not to output JSON data, rather than the normal output. + + -p|--parseable + Output parseable results from commands that write to standard output. For + + alias: ogr Run "npm help org" for more info @@ -3653,6 +5301,36 @@ npm outdated [ ...] Options: [-a|--all] [--json] [-l|--long] [-p|--parseable] [-g|--global] [-w|--workspace [-w|--workspace ...]] +[--before ] [--min-release-age ] +[--min-release-age-exclude [--min-release-age-exclude ...]] + + -a|--all + Show or act on all packages, not just the ones your project directly + + --json + Whether or not to output JSON data, rather than the normal output. + + -l|--long + Show extended information in \`ls\`, \`search\`, and \`help-search\`. + + -p|--parseable + Output parseable results from commands that write to standard output. For + + -g|--global + Operates in "global" mode, so that packages are installed into the + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --before + If passed to \`npm install\`, will rebuild the npm tree such that only + + --min-release-age + If set, npm will build the npm tree such that only versions that were + + --min-release-age-exclude + A list of package names or \`minimatch\` glob patterns that are exempt + Run "npm help outdated" for more info @@ -3666,6 +5344,9 @@ npm outdated [ ...] #### \`parseable\` #### \`global\` #### \`workspace\` +#### \`before\` +#### \`min-release-age\` +#### \`min-release-age-exclude\` ` exports[`test/lib/docs.js TAP usage owner > must match snapshot 1`] = ` @@ -3679,7 +5360,20 @@ npm owner ls Options: [--registry ] [--otp ] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] +[--workspaces] + + --registry + The base URL of the npm registry. + + --otp + This is a one-time password from a two-factor authenticator. It's needed + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + alias: author @@ -3708,7 +5402,29 @@ npm pack Options: [--dry-run] [--json] [--pack-destination ] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] +[--workspaces] [--include-workspace-root] [--ignore-scripts] + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + --json + Whether or not to output JSON data, rather than the normal output. + + --pack-destination + Directory in which \`npm pack\` will save tarballs. + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + Run "npm help pack" for more info @@ -3722,6 +5438,71 @@ npm pack #### \`workspace\` #### \`workspaces\` #### \`include-workspace-root\` +#### \`ignore-scripts\` +` + +exports[`test/lib/docs.js TAP usage patch > must match snapshot 1`] = ` +Apply local patches to installed dependencies + +Usage: +npm patch [@] +npm patch add [@] [--edit-dir ] [--ignore-existing] +npm patch commit [--patches-dir ] [--keep-edit-dir] +npm patch update [@] [--to ] [--patches-dir ] +npm patch ls +npm patch rm [@] + +Options: +[--patches-dir ] [--allow-unused-patches] [--ignore-patch-failures] +[--edit-dir ] [--ignore-existing] [--keep-edit-dir] [--to ] +[--registry ] + + --patches-dir + The directory, relative to the project root, where \`npm patch commit\` + + --allow-unused-patches + Install even when a registered patch in \`patchedDependencies\` matches no + + --ignore-patch-failures + Install even when a registered patch fails to apply, with a warning per + + --edit-dir + Override the temporary directory used by \`npm patch add\` to prepare a + + --ignore-existing + With \`npm patch add\`, discard a previous unfinished edit directory and + + --keep-edit-dir + With \`npm patch commit\`, do not remove the edit directory after + + --to + Used by \`npm patch update\` to set the version to rebase a patch onto + + --registry + The base URL of the npm registry. + + +Run "npm help patch" for more info + +\`\`\`bash +npm patch [@] +npm patch add [@] [--edit-dir ] [--ignore-existing] +npm patch commit [--patches-dir ] [--keep-edit-dir] +npm patch update [@] [--to ] [--patches-dir ] +npm patch ls +npm patch rm [@] +\`\`\` + +Note: This command is unaware of workspaces. + +#### \`patches-dir\` +#### \`allow-unused-patches\` +#### \`ignore-patch-failures\` +#### \`edit-dir\` +#### \`ignore-existing\` +#### \`keep-edit-dir\` +#### \`to\` +#### \`registry\` ` exports[`test/lib/docs.js TAP usage ping > must match snapshot 1`] = ` @@ -3733,6 +5514,10 @@ npm ping Options: [--registry ] + --registry + The base URL of the npm registry. + + Run "npm help ping" for more info \`\`\`bash @@ -3758,7 +5543,20 @@ npm pkg fix Options: [-f|--force] [--json] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] +[--workspaces] + + -f|--force + Removes various protections against unfortunate side effects, common + + --json + Whether or not to output JSON data, rather than the normal output. + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + Run "npm help pkg" for more info @@ -3781,15 +5579,19 @@ exports[`test/lib/docs.js TAP usage prefix > must match snapshot 1`] = ` Display prefix Usage: -npm prefix [-g] +npm prefix Options: [-g|--global] + -g|--global + Operates in "global" mode, so that packages are installed into the + + Run "npm help prefix" for more info \`\`\`bash -npm prefix [-g] +npm prefix \`\`\` Note: This command is unaware of workspaces. @@ -3809,6 +5611,19 @@ npm profile set Options: [--registry ] [--json] [-p|--parseable] [--otp ] + --registry + The base URL of the npm registry. + + --json + Whether or not to output JSON data, rather than the normal output. + + -p|--parseable + Output parseable results from commands that write to standard output. For + + --otp + This is a one-time password from a two-factor authenticator. It's needed + + Run "npm help profile" for more info \`\`\`bash @@ -3837,7 +5652,38 @@ Options: [--include [--include ...]] [--dry-run] [--json] [--foreground-scripts] [--ignore-scripts] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + --omit + Dependency types to omit from the installation tree on disk. + + --include + Option that allows for defining which types of dependencies to install. + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + --json + Whether or not to output JSON data, rather than the normal output. + + --foreground-scripts + Run all build scripts (ie, \`preinstall\`, \`install\`, and + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + Run "npm help prune" for more info @@ -3864,10 +5710,34 @@ Usage: npm publish Options: -[--tag ] [--access ] [--dry-run] [--otp ] +[--tag ] [--access ] [--dry-run] [--otp ] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] -[--provenance|--provenance-file ] +[--workspaces] [--include-workspace-root] [--provenance|--provenance-file ] + + --tag + If you ask npm to install a package and don't tell it a specific version, + + --access + If you do not want your scoped package to be publicly viewable (and + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + --otp + This is a one-time password from a two-factor authenticator. It's needed + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --provenance + When publishing from a supported cloud CI/CD system, the package will be + Run "npm help publish" for more info @@ -3895,8 +5765,38 @@ npm query Options: [-g|--global] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--package-lock-only] -[--expect-results|--expect-result-count ] +[--workspaces] [--include-workspace-root] [--package-lock-only] +[--expect-results|--expect-result-count ] [--before ] +[--min-release-age ] +[--min-release-age-exclude [--min-release-age-exclude ...]] + + -g|--global + Operates in "global" mode, so that packages are installed into the + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --package-lock-only + If set to true, the current operation will only use the \`package-lock.json\`, + + --expect-results + Tells npm whether or not to expect results from the command. + + --before + If passed to \`npm install\`, will rebuild the npm tree such that only + + --min-release-age + If set, npm will build the npm tree such that only versions that were + + --min-release-age-exclude + A list of package names or \`minimatch\` glob patterns that are exempt + Run "npm help query" for more info @@ -3911,6 +5811,9 @@ npm query #### \`package-lock-only\` #### \`expect-results\` #### \`expect-result-count\` +#### \`before\` +#### \`min-release-age\` +#### \`min-release-age-exclude\` ` exports[`test/lib/docs.js TAP usage rebuild > must match snapshot 1`] = ` @@ -3921,8 +5824,44 @@ npm rebuild [] ...] Options: [-g|--global] [--no-bin-links] [--foreground-scripts] [--ignore-scripts] +[--allow-scripts [--allow-scripts ...]] +[--strict-allow-scripts] [--dangerously-allow-all-scripts] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + -g|--global + Operates in "global" mode, so that packages are installed into the + + --bin-links + Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package + + --foreground-scripts + Run all build scripts (ie, \`preinstall\`, \`install\`, and + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --allow-scripts + Comma-separated list of packages whose install-time lifecycle scripts + + --strict-allow-scripts + If \`true\`, turn the install-script policy from a warning into a hard + + --dangerously-allow-all-scripts + If \`true\`, bypass the \`allowScripts\` policy entirely and run every + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + alias: rb @@ -3938,6 +5877,9 @@ alias: rb #### \`bin-links\` #### \`foreground-scripts\` #### \`ignore-scripts\` +#### \`allow-scripts\` +#### \`strict-allow-scripts\` +#### \`dangerously-allow-all-scripts\` #### \`workspace\` #### \`workspaces\` #### \`include-workspace-root\` @@ -3953,7 +5895,23 @@ npm repo [ [ ...]] Options: [--no-browser|--browser ] [--registry ] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] +[--workspaces] [--include-workspace-root] + + --browser + The browser that is called by npm commands to open websites. + + --registry + The base URL of the npm registry. + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + Run "npm help repo" for more info @@ -3977,6 +5935,13 @@ npm restart [-- ] Options: [--ignore-scripts] [--script-shell ] + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --script-shell + The shell to use for scripts run with the \`npm exec\`, + + Run "npm help restart" for more info \`\`\`bash @@ -3996,6 +5961,10 @@ npm root Options: [-g|--global] + -g|--global + Operates in "global" mode, so that packages are installed into the + + Run "npm help root" for more info \`\`\`bash @@ -4007,25 +5976,47 @@ Note: This command is unaware of workspaces. #### \`global\` ` -exports[`test/lib/docs.js TAP usage run-script > must match snapshot 1`] = ` +exports[`test/lib/docs.js TAP usage run > must match snapshot 1`] = ` Run arbitrary package scripts Usage: -npm run-script [-- ] +npm run [-- ] Options: [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--if-present] [--ignore-scripts] +[--workspaces] [--include-workspace-root] [--if-present] [--ignore-scripts] [--foreground-scripts] [--script-shell ] -aliases: run, rum, urn + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --if-present + If true, npm will not exit with an error code when \`run\` is + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --foreground-scripts + Run all build scripts (ie, \`preinstall\`, \`install\`, and + + --script-shell + The shell to use for scripts run with the \`npm exec\`, -Run "npm help run-script" for more info + +aliases: run-script, rum, urn + +Run "npm help run" for more info \`\`\`bash -npm run-script [-- ] +npm run [-- ] -aliases: run, rum, urn +aliases: run-script, rum, urn \`\`\` #### \`workspace\` @@ -4048,7 +6039,26 @@ Options: [--package-lock-only] [--sbom-format ] [--sbom-type ] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] +[--workspaces] + + --omit + Dependency types to omit from the installation tree on disk. + + --package-lock-only + If set to true, the current operation will only use the \`package-lock.json\`, + + --sbom-format + SBOM format to use when generating SBOMs. + + --sbom-type + The type of package described by the generated SBOM. For SPDX, this is the + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + Run "npm help sbom" for more info @@ -4076,6 +6086,40 @@ Options: [--searchexclude ] [--registry ] [--prefer-online] [--prefer-offline] [--offline] + --json + Whether or not to output JSON data, rather than the normal output. + + --color + If false, never shows colors. If \`"always"\` then always shows colors. + + -p|--parseable + Output parseable results from commands that write to standard output. For + + --description + Show the description in \`npm search\` + + --searchlimit + Number of items to limit search results to. Will not apply at all to + + --searchopts + Space-separated options that are always passed to search. + + --searchexclude + Space-separated options that limit the results from search. + + --registry + The base URL of the npm registry. + + --prefer-online + If true, staleness checks for cached data will be forced, making the CLI + + --prefer-offline + If true, staleness checks for cached data will be bypassed, but missing + + --offline + Force offline mode: no network requests will be done during install. To allow + + aliases: find, s, se Run "npm help search" for more info @@ -4110,6 +6154,13 @@ npm set = [= ...] (See \`npm config\`) Options: [-g|--global] [-L|--location ] + -g|--global + Operates in "global" mode, so that packages are installed into the + + -L|--location + When passed to \`npm config\` this refers to which config file to use. + + Run "npm help set" for more info \`\`\`bash @@ -4122,63 +6173,59 @@ Note: This command is unaware of workspaces. #### \`location\` ` -exports[`test/lib/docs.js TAP usage shrinkwrap > must match snapshot 1`] = ` -Lock down dependency versions for publication +exports[`test/lib/docs.js TAP usage stage > must match snapshot 1`] = ` +Stage packages for publishing, deferring proof-of-presence (2FA) to a later point in time Usage: -npm shrinkwrap - -Run "npm help shrinkwrap" for more info - -\`\`\`bash -npm shrinkwrap -\`\`\` - -Note: This command is unaware of workspaces. - -NO PARAMS -` - -exports[`test/lib/docs.js TAP usage star > must match snapshot 1`] = ` -Mark your favorite packages - -Usage: -npm star [...] - -Options: -[--registry ] [--unicode] [--otp ] +npm stage +npm stage publish +npm stage list [] +npm stage view +npm stage approve +npm stage reject +npm stage download -Run "npm help star" for more info +Subcommands: + publish + Stage a package for publishing, deferring proof-of-presence (2FA) to a later point in time -\`\`\`bash -npm star [...] -\`\`\` + list + List all staged package versions -Note: This command is unaware of workspaces. + view + View details of a specific staged package -#### \`registry\` -#### \`unicode\` -#### \`otp\` -` + approve + Approve a staged package, publishing it to the npm registry -exports[`test/lib/docs.js TAP usage stars > must match snapshot 1`] = ` -View packages marked as favorites + reject + Reject a staged package, removing it from the registry -Usage: -npm stars [] + download + Download the tarball of a staged package for inspection -Options: -[--registry ] +Run "npm stage --help" for more info on a subcommand. -Run "npm help stars" for more info +Run "npm help stage" for more info \`\`\`bash -npm stars [] +npm stage \`\`\` Note: This command is unaware of workspaces. -#### \`registry\` +#### Synopsis +#### Flags +#### Synopsis +#### Flags +#### Synopsis +#### Flags +#### Synopsis +#### Flags +#### Synopsis +#### Flags +#### Synopsis +#### Flags ` exports[`test/lib/docs.js TAP usage start > must match snapshot 1`] = ` @@ -4190,6 +6237,13 @@ npm start [-- ] Options: [--ignore-scripts] [--script-shell ] + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --script-shell + The shell to use for scripts run with the \`npm exec\`, + + Run "npm help start" for more info \`\`\`bash @@ -4209,6 +6263,13 @@ npm stop [-- ] Options: [--ignore-scripts] [--script-shell ] + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --script-shell + The shell to use for scripts run with the \`npm exec\`, + + Run "npm help stop" for more info \`\`\`bash @@ -4232,6 +6293,19 @@ npm team ls | Options: [--registry ] [--otp ] [-p|--parseable] [--json] + --registry + The base URL of the npm registry. + + --otp + This is a one-time password from a two-factor authenticator. It's needed + + -p|--parseable + Output parseable results from commands that write to standard output. For + + --json + Whether or not to output JSON data, rather than the normal output. + + Run "npm help team" for more info \`\`\`bash @@ -4259,6 +6333,13 @@ npm test [-- ] Options: [--ignore-scripts] [--script-shell ] + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --script-shell + The shell to use for scripts run with the \`npm exec\`, + + aliases: tst, t Run "npm help test" for more info @@ -4279,26 +6360,164 @@ Manage your authentication tokens Usage: npm token list npm token revoke -npm token create [--read-only] [--cidr=list] +npm token create Options: -[--read-only] [--cidr [--cidr ...]] [--registry ] -[--otp ] +[--name ] [--token-description ] [--expires ] +[--packages [--packages ...]] [--packages-all] +[--scopes [--scopes ...]] [--orgs [--orgs ...]] +[--packages-and-scopes-permission ] +[--orgs-permission ] +[--cidr [--cidr ...]] [--bypass-2fa] [--password ] +[--registry ] [--otp ] [--read-only] + + --name + When creating a Granular Access Token with \`npm token create\`, + + --token-description + Description text for the token when using \`npm token create\`. + + --expires + When creating a Granular Access Token with \`npm token create\`, + + --packages + When creating a Granular Access Token with \`npm token create\`, + + --packages-all + When creating a Granular Access Token with \`npm token create\`, + + --scopes + When creating a Granular Access Token with \`npm token create\`, + + --orgs + When creating a Granular Access Token with \`npm token create\`, + + --packages-and-scopes-permission + When creating a Granular Access Token with \`npm token create\`, + + --orgs-permission + When creating a Granular Access Token with \`npm token create\`, + + --cidr + This is a list of CIDR address to be used when configuring limited access + + --bypass-2fa + When creating a Granular Access Token with \`npm token create\`, + + --password + Password for authentication. Can be provided via command line when + + --registry + The base URL of the npm registry. + + --otp + This is a one-time password from a two-factor authenticator. It's needed + + --read-only + This is used to mark a token as unable to publish when configuring + Run "npm help token" for more info \`\`\`bash npm token list npm token revoke -npm token create [--read-only] [--cidr=list] +npm token create \`\`\` Note: This command is unaware of workspaces. -#### \`read-only\` +#### \`name\` +#### \`token-description\` +#### \`expires\` +#### \`packages\` +#### \`packages-all\` +#### \`scopes\` +#### \`orgs\` +#### \`packages-and-scopes-permission\` +#### \`orgs-permission\` #### \`cidr\` +#### \`bypass-2fa\` +#### \`password\` #### \`registry\` #### \`otp\` +#### \`read-only\` +` + +exports[`test/lib/docs.js TAP usage trust > must match snapshot 1`] = ` +Create a trusted relationship between a package and a OIDC provider + +Usage: +npm trust github [package] --file [--repo|--repository] [--env|--environment] [--allow-publish] [--allow-stage-publish] [-y|--yes] +npm trust gitlab [package] --file [--project|--repo|--repository] [--env|--environment] [--allow-publish] [--allow-stage-publish] [-y|--yes] +npm trust circleci [package] --org-id --project-id --pipeline-definition-id --vcs-origin [--context-id ...] [--allow-publish] [--allow-stage-publish] [-y|--yes] +npm trust list [package] +npm trust revoke [package] --id= + +Subcommands: + github + Create a trusted relationship between a package and GitHub Actions + + gitlab + Create a trusted relationship between a package and GitLab CI/CD + + circleci + Create a trusted relationship between a package and CircleCI + + list + List trusted relationships for a package + + revoke + Revoke a trusted relationship for a package + +Run "npm trust --help" for more info on a subcommand. + +Run "npm help trust" for more info + +Note: This command is unaware of workspaces. + +#### Synopsis +#### Flags +#### Synopsis +#### Flags +#### Synopsis +#### Flags +#### Synopsis +#### Flags +#### Synopsis +#### Flags +` + +exports[`test/lib/docs.js TAP usage undeprecate > must match snapshot 1`] = ` +Undeprecate a version of a package + +Usage: +npm undeprecate + +Options: +[--registry ] [--otp ] [--dry-run] + + --registry + The base URL of the npm registry. + + --otp + This is a one-time password from a two-factor authenticator. It's needed + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + +Run "npm help undeprecate" for more info + +\`\`\`bash +npm undeprecate +\`\`\` + +Note: This command is unaware of workspaces. + +#### \`registry\` +#### \`otp\` +#### \`dry-run\` ` exports[`test/lib/docs.js TAP usage uninstall > must match snapshot 1`] = ` @@ -4311,7 +6530,26 @@ Options: [-S|--save|--no-save|--save-prod|--save-dev|--save-optional|--save-peer|--save-bundle] [-g|--global] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + -S|--save + Save installed packages to a \`package.json\` file as dependencies. + + -g|--global + Operates in "global" mode, so that packages are installed into the + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + aliases: unlink, remove, rm, r, un @@ -4340,7 +6578,20 @@ npm unpublish [] Options: [--dry-run] [-f|--force] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] +[--workspaces] + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + -f|--force + Removes various protections against unfortunate side effects, common + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + Run "npm help unpublish" for more info @@ -4354,28 +6605,6 @@ npm unpublish [] #### \`workspaces\` ` -exports[`test/lib/docs.js TAP usage unstar > must match snapshot 1`] = ` -Remove an item from your favorite packages - -Usage: -npm unstar [...] - -Options: -[--registry ] [--unicode] [--otp ] - -Run "npm help unstar" for more info - -\`\`\`bash -npm unstar [...] -\`\`\` - -Note: This command is unaware of workspaces. - -#### \`registry\` -#### \`unicode\` -#### \`otp\` -` - exports[`test/lib/docs.js TAP usage update > must match snapshot 1`] = ` Update packages @@ -4389,18 +6618,99 @@ Options: [--omit [--omit ...]] [--include [--include ...]] [--strict-peer-deps] [--no-package-lock] [--foreground-scripts] -[--ignore-scripts] [--no-audit] [--no-bin-links] [--no-fund] [--dry-run] +[--ignore-scripts] +[--allow-scripts [--allow-scripts ...]] +[--strict-allow-scripts] [--dangerously-allow-all-scripts] [--no-audit] +[--before ] [--min-release-age ] +[--min-release-age-exclude [--min-release-age-exclude ...]] +[--no-bin-links] [--no-fund] [--dry-run] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] [--install-links] +[--workspaces] [--include-workspace-root] [--install-links] + + -S|--save + Save installed packages to a \`package.json\` file as dependencies. + + -g|--global + Operates in "global" mode, so that packages are installed into the + + --install-strategy + Sets the strategy for installing packages in node_modules. + + --legacy-bundling + Instead of hoisting package installs in \`node_modules\`, install packages + + --global-style + Only install direct dependencies in the top level \`node_modules\`, + + --omit + Dependency types to omit from the installation tree on disk. + + --include + Option that allows for defining which types of dependencies to install. + + --strict-peer-deps + If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_ + + --package-lock + If set to false, then ignore \`package-lock.json\` files when installing. + + --foreground-scripts + Run all build scripts (ie, \`preinstall\`, \`install\`, and + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + + --allow-scripts + Comma-separated list of packages whose install-time lifecycle scripts + + --strict-allow-scripts + If \`true\`, turn the install-script policy from a warning into a hard + + --dangerously-allow-all-scripts + If \`true\`, bypass the \`allowScripts\` policy entirely and run every + + --audit + When "true" submit audit reports alongside the current npm command to the + + --before + If passed to \`npm install\`, will rebuild the npm tree such that only + + --min-release-age + If set, npm will build the npm tree such that only versions that were + + --min-release-age-exclude + A list of package names or \`minimatch\` glob patterns that are exempt + + --bin-links + Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package -aliases: up, upgrade, udpate + --fund + When "true" displays the message at the end of each \`npm install\` + + --dry-run + Indicates that you don't want npm to make any changes and that it should + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --install-links + When set file: protocol dependencies will be packed and installed as + + +aliases: u, up, upgrade, udpate Run "npm help update" for more info \`\`\`bash npm update [...] -aliases: up, upgrade, udpate +aliases: u, up, upgrade, udpate \`\`\` #### \`save\` @@ -4414,7 +6724,13 @@ aliases: up, upgrade, udpate #### \`package-lock\` #### \`foreground-scripts\` #### \`ignore-scripts\` +#### \`allow-scripts\` +#### \`strict-allow-scripts\` +#### \`dangerously-allow-all-scripts\` #### \`audit\` +#### \`before\` +#### \`min-release-age\` +#### \`min-release-age-exclude\` #### \`bin-links\` #### \`fund\` #### \`dry-run\` @@ -4433,8 +6749,47 @@ npm version [ | major | minor | patch | premajor | preminor | prepat Options: [--allow-same-version] [--no-commit-hooks] [--no-git-tag-version] [--json] [--preid prerelease-id] [--sign-git-tag] +[-S|--save|--no-save|--save-prod|--save-dev|--save-optional|--save-peer|--save-bundle] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--no-workspaces-update] [--include-workspace-root] +[--workspaces] [--no-workspaces-update] [--include-workspace-root] +[--ignore-scripts] + + --allow-same-version + Prevents throwing an error when \`npm version\` is used to set the new + + --commit-hooks + Run git commit hooks when using the \`npm version\` command. + + --git-tag-version + Tag the commit when using the \`npm version\` command. Setting this to + + --json + Whether or not to output JSON data, rather than the normal output. + + --preid + The "prerelease identifier" to use as a prefix for the "prerelease" part + + --sign-git-tag + If set to true, then the \`npm version\` command will tag the version + + -S|--save + Save installed packages to a \`package.json\` file as dependencies. + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --workspaces-update + If set to true, the npm cli will run an update after operations that may + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + + --ignore-scripts + If true, npm does not run scripts specified in package.json files. + alias: verison @@ -4452,10 +6807,12 @@ alias: verison #### \`json\` #### \`preid\` #### \`sign-git-tag\` +#### \`save\` #### \`workspace\` #### \`workspaces\` #### \`workspaces-update\` #### \`include-workspace-root\` +#### \`ignore-scripts\` ` exports[`test/lib/docs.js TAP usage view > must match snapshot 1`] = ` @@ -4466,7 +6823,20 @@ npm view [] [[.subfield]...] Options: [--json] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] +[--workspaces] [--include-workspace-root] + + --json + Whether or not to output JSON data, rather than the normal output. + + -w|--workspace + Enable running a command in the context of the configured workspaces of the + + --workspaces + Set to true to run the command in the context of **all** configured + + --include-workspace-root + Include the workspace root when workspaces are enabled for a command. + aliases: info, show, v @@ -4493,6 +6863,10 @@ npm whoami Options: [--registry ] + --registry + The base URL of the npm registry. + + Run "npm help whoami" for more info \`\`\`bash diff --git a/tap-snapshots/test/lib/npm.js.test.cjs b/tap-snapshots/test/lib/npm.js.test.cjs index 32ab47ef06b18..8066c41184f09 100644 --- a/tap-snapshots/test/lib/npm.js.test.cjs +++ b/tap-snapshots/test/lib/npm.js.test.cjs @@ -31,16 +31,16 @@ npm help npm more involved overview All 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, hook, 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, uninstall, unpublish, unstar, update, version, - view, whoami + access, approve-scripts, audit, bugs, cache, ci, + completion, config, dedupe, deny-scripts, 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, patch, ping, pkg, prefix, + profile, prune, publish, query, rebuild, repo, restart, + root, run, sbom, search, set, stage, start, stop, team, + test, token, trust, undeprecate, uninstall, unpublish, + update, version, view, whoami Specify configs in the ini-formatted file: {USERCONFIG} @@ -68,31 +68,33 @@ npm help npm more involved overview All commands: - access, adduser, - audit, bugs, cache, ci, + access, + approve-scripts, audit, + bugs, cache, ci, completion, config, - dedupe, deprecate, diff, + dedupe, deny-scripts, + deprecate, diff, dist-tag, docs, doctor, edit, exec, explain, explore, find-dupes, fund, get, help, - help-search, hook, init, + 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, + patch, ping, pkg, + prefix, profile, prune, + publish, query, rebuild, + repo, restart, root, + run, sbom, search, set, + stage, start, stop, + team, test, token, + trust, undeprecate, uninstall, unpublish, - unstar, update, version, - view, whoami + update, version, view, + whoami Specify configs in the ini-formatted file: {USERCONFIG} @@ -120,31 +122,33 @@ npm help npm more involved overview All commands: - access, adduser, - audit, bugs, cache, ci, + access, + approve-scripts, audit, + bugs, cache, ci, completion, config, - dedupe, deprecate, diff, + dedupe, deny-scripts, + deprecate, diff, dist-tag, docs, doctor, edit, exec, explain, explore, find-dupes, fund, get, help, - help-search, hook, init, + 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, + patch, ping, pkg, + prefix, profile, prune, + publish, query, rebuild, + repo, restart, root, + run, sbom, search, set, + stage, start, stop, + team, test, token, + trust, undeprecate, uninstall, unpublish, - unstar, update, version, - view, whoami + update, version, view, + whoami Specify configs in the ini-formatted file: {USERCONFIG} @@ -172,16 +176,16 @@ npm help npm more involved overview All 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, hook, 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, uninstall, unpublish, unstar, update, version, - view, whoami + access, approve-scripts, audit, bugs, cache, ci, + completion, config, dedupe, deny-scripts, 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, patch, ping, pkg, prefix, + profile, prune, publish, query, rebuild, repo, restart, + root, run, sbom, search, set, stage, start, stop, team, + test, token, trust, undeprecate, uninstall, unpublish, + update, version, view, whoami Specify configs in the ini-formatted file: {USERCONFIG} @@ -209,31 +213,33 @@ npm help npm more involved overview All commands: - access, adduser, - audit, bugs, cache, ci, + access, + approve-scripts, audit, + bugs, cache, ci, completion, config, - dedupe, deprecate, diff, + dedupe, deny-scripts, + deprecate, diff, dist-tag, docs, doctor, edit, exec, explain, explore, find-dupes, fund, get, help, - help-search, hook, init, + 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, + patch, ping, pkg, + prefix, profile, prune, + publish, query, rebuild, + repo, restart, root, + run, sbom, search, set, + stage, start, stop, + team, test, token, + trust, undeprecate, uninstall, unpublish, - unstar, update, version, - view, whoami + update, version, view, + whoami Specify configs in the ini-formatted file: {USERCONFIG} @@ -261,31 +267,33 @@ npm help npm more involved overview All commands: - access, adduser, - audit, bugs, cache, ci, + access, + approve-scripts, audit, + bugs, cache, ci, completion, config, - dedupe, deprecate, diff, + dedupe, deny-scripts, + deprecate, diff, dist-tag, docs, doctor, edit, exec, explain, explore, find-dupes, fund, get, help, - help-search, hook, init, + 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, + patch, ping, pkg, + prefix, profile, prune, + publish, query, rebuild, + repo, restart, root, + run, sbom, search, set, + stage, start, stop, + team, test, token, + trust, undeprecate, uninstall, unpublish, - unstar, update, version, - view, whoami + update, version, view, + whoami Specify configs in the ini-formatted file: {USERCONFIG} @@ -313,30 +321,31 @@ npm help npm more involved overview All commands: - access, adduser, audit, + access, + approve-scripts, audit, bugs, cache, ci, completion, config, - dedupe, deprecate, diff, + dedupe, deny-scripts, + deprecate, diff, dist-tag, docs, doctor, edit, exec, explain, explore, find-dupes, fund, get, help, - help-search, hook, init, + help-search, init, install, install-ci-test, install-test, link, ll, login, logout, ls, org, outdated, owner, pack, - ping, pkg, prefix, + patch, ping, pkg, prefix, profile, prune, publish, query, rebuild, repo, - restart, root, - run-script, sbom, search, - set, shrinkwrap, star, - stars, start, stop, team, - test, token, uninstall, - unpublish, unstar, - update, version, view, - whoami + restart, root, run, sbom, + search, set, stage, + start, stop, team, test, + token, trust, + undeprecate, uninstall, + unpublish, update, + version, view, whoami Specify configs in the ini-formatted file: {USERCONFIG} @@ -364,16 +373,16 @@ npm help npm more involved overview All 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, hook, 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, uninstall, unpublish, unstar, update, version, - view, whoami + access, approve-scripts, audit, bugs, cache, ci, + completion, config, dedupe, deny-scripts, 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, patch, ping, pkg, prefix, + profile, prune, publish, query, rebuild, repo, restart, + root, run, sbom, search, set, stage, start, stop, team, + test, token, trust, undeprecate, uninstall, unpublish, + update, version, view, whoami Specify configs in the ini-formatted file: {USERCONFIG} @@ -401,16 +410,16 @@ npm help npm more involved overview All 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, hook, 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, uninstall, unpublish, unstar, update, version, - view, whoami + access, approve-scripts, audit, bugs, cache, ci, + completion, config, dedupe, deny-scripts, 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, patch, ping, pkg, prefix, + profile, prune, publish, query, rebuild, repo, restart, + root, run, sbom, search, set, stage, start, stop, team, + test, token, trust, undeprecate, uninstall, unpublish, + update, version, view, whoami Specify configs in the ini-formatted file: {USERCONFIG} @@ -438,16 +447,16 @@ npm help npm more involved overview All 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, hook, 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, uninstall, unpublish, unstar, update, version, - view, whoami + access, approve-scripts, audit, bugs, cache, ci, + completion, config, dedupe, deny-scripts, 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, patch, ping, pkg, prefix, + profile, prune, publish, query, rebuild, repo, restart, + root, run, sbom, search, set, stage, start, stop, team, + test, token, trust, undeprecate, uninstall, unpublish, + update, version, view, whoami Specify configs in the ini-formatted file: {USERCONFIG} diff --git a/tap-snapshots/test/lib/utils/error-message.js.test.cjs b/tap-snapshots/test/lib/utils/error-message.js.test.cjs index 4cfd91fd278cd..a63412c96ea4a 100644 --- a/tap-snapshots/test/lib/utils/error-message.js.test.cjs +++ b/tap-snapshots/test/lib/utils/error-message.js.test.cjs @@ -15,7 +15,7 @@ Object { Array [ "404", "", - "'http://evil:***@npmjs.org/not-found' is not in this registry.", + "The requested resource 'http://evil:***@npmjs.org/not-found' could not be found or you do not have permission to access it.", ], Array [ "404", @@ -58,7 +58,7 @@ Object { Array [ "404", "", - "'node_modules' is not in this registry.", + "The requested resource 'node_modules' could not be found or you do not have permission to access it.", ], Array [ "404", @@ -67,7 +67,7 @@ Object { ], Array [ "404", - " 1. node_modules is a blacklisted name", + " 1. node_modules is not a valid package name", ], Array [ "404", @@ -101,7 +101,7 @@ Object { Array [ "404", "", - "'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' is not in this registry.", + "The requested resource 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' could not be found or you do not have permission to access it.", ], Array [ "404", @@ -156,7 +156,7 @@ Object { Array [ "404", "", - "'yolo' is not in this registry.", + "The requested resource 'yolo' could not be found or you do not have permission to access it.", ], Array [ "404", @@ -222,7 +222,7 @@ Object { String( Not compatible with your version of node/npm: some@package Required: undefined - Actual: {"npm":"123.456.789-npm","node":"123.456.789-node"} + Actual: {"node":"123.456.789-node","npm":"123.456.789-npm"} ), ], ], @@ -370,9 +370,7 @@ Object { The operation was rejected by your operating system. 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. + 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. ), ], ], @@ -403,9 +401,7 @@ Object { The operation was rejected by your operating system. 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. + 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. ), ], ], @@ -436,9 +432,7 @@ Object { The operation was rejected by your operating system. 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. + 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. ), ], ], @@ -469,9 +463,7 @@ Object { The operation was rejected by your operating system. 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. + 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. ), ], ], @@ -502,9 +494,7 @@ Object { The operation was rejected by your operating system. 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. + 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. ), ], ], @@ -538,8 +528,7 @@ Object { "", String( - Your cache folder contains root-owned files, due to a bug in - previous versions of npm which has since been addressed. + 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 867:5309 "{CWD}/cache" @@ -567,8 +556,7 @@ Object { "", String( - Your cache folder contains root-owned files, due to a bug in - previous versions of npm which has since been addressed. + 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 867:5309 "{CWD}/cache" @@ -596,8 +584,7 @@ Object { "", String( - Your cache folder contains root-owned files, due to a bug in - previous versions of npm which has since been addressed. + 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 867:5309 "{CWD}/cache" @@ -625,12 +612,9 @@ Object { String( The operation was rejected by your operating system. - 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's possible that the file was already in use (by a text editor or antivirus), or that you lack permissions to access it. - 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. + 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. ), ], ], @@ -659,12 +643,9 @@ Object { String( The operation was rejected by your operating system. - 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's possible that the file was already in use (by a text editor or antivirus), or that you lack permissions to access it. - 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. + 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. ), ], ], @@ -693,12 +674,9 @@ Object { String( The operation was rejected by your operating system. - 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's possible that the file was already in use (by a text editor or antivirus), or that you lack permissions to access it. - 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. + 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. ), ], ], @@ -727,12 +705,9 @@ Object { String( The operation was rejected by your operating system. - 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's possible that the file was already in use (by a text editor or antivirus), or that you lack permissions to access it. - 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. + 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. ), ], ], @@ -761,12 +736,9 @@ Object { String( The operation was rejected by your operating system. - 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's possible that the file was already in use (by a text editor or antivirus), or that you lack permissions to access it. - 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. + 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. ), ], ], @@ -800,12 +772,9 @@ Object { String( The operation was rejected by your operating system. - 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's possible that the file was already in use (by a text editor or antivirus), or that you lack permissions to access it. - 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. + 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. ), ], ], @@ -839,12 +808,9 @@ Object { String( The operation was rejected by your operating system. - 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's possible that the file was already in use (by a text editor or antivirus), or that you lack permissions to access it. - 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. + 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. ), ], ], @@ -878,12 +844,9 @@ Object { String( The operation was rejected by your operating system. - 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's possible that the file was already in use (by a text editor or antivirus), or that you lack permissions to access it. - 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. + 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. ), ], ], @@ -980,8 +943,7 @@ Object { "", String( 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. + If you already provided a one-time password then it is likely that you either typoed it, or it timed out. Please try again. ), ], ], @@ -1001,8 +963,7 @@ Object { "", String( 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. + If you already provided a one-time password then it is likely that you either typoed it, or it timed out. Please try again. ), ], ], @@ -1015,20 +976,55 @@ Object { } ` +exports[`test/lib/utils/error-message.js TAP eotp/e401 one-time pass webauth challenge > must match snapshot 1`] = ` +Object { + "detail": Array [ + Array [ + "", + "Open this URL in your browser to authenticate:", + ], + Array [ + "", + " https://registry.npmjs.org/-/auth/login/abc123", + ], + Array [ + "", + "", + ], + Array [ + "", + "After authenticating, your token can be retrieved from:", + ], + Array [ + "", + " https://registry.npmjs.org/-/auth/done/abc123", + ], + ], + "json": Object { + "authUrl": "https://registry.npmjs.org/-/auth/login/abc123", + "doneUrl": "https://registry.npmjs.org/-/auth/done/abc123", + }, + "summary": Array [ + Array [ + "", + "This operation requires a one-time password.", + ], + ], +} +` + exports[`test/lib/utils/error-message.js TAP eotp/e401 www-authenticate challenges Basic realm=by, charset="UTF-8", challenge="your friends" > must match snapshot 1`] = ` Object { "detail": Array [ Array [ "", String( - 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. + 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: + 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 ), ], @@ -1134,8 +1130,7 @@ Object { 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' + If you are behind a proxy, please make sure that the 'proxy' config is set properly. See: 'npm help config' ), ], ], @@ -1157,8 +1152,7 @@ Object { 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' + If you are behind a proxy, please make sure that the 'proxy' config is set properly. See: 'npm help config' ), ], ], @@ -1180,8 +1174,7 @@ Object { 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' + If you are behind a proxy, please make sure that the 'proxy' config is set properly. See: 'npm help config' ), ], ], @@ -1202,7 +1195,7 @@ Object { String( Not compatible with your version of node/npm: some@package Required: undefined - Actual: {"npm":"123.456.789-npm","node":"123.456.789-node"} + Actual: {"node":"123.456.789-node","npm":"123.456.789-npm"} ), ], ], @@ -1244,10 +1237,7 @@ Object { "detail": Array [ Array [ "rofs", - String( - Often virtualized file systems, or other file systems - that don't support symlinks, give this error. - ), + "Often virtualized file systems, or other file systems that don't support symlinks, give this error.", ], ], "summary": Array [ @@ -1287,7 +1277,7 @@ Object { "typeerror", String( This is an error with npm itself. Please report this error at: - https://github.com/npm/cli/issues + https://github.com/npm/cli/issues ), ], ], @@ -1307,7 +1297,7 @@ Object { "typeerror", String( This is an error with npm itself. Please report this error at: - https://github.com/npm/cli/issues + https://github.com/npm/cli/issues ), ], ], @@ -1327,7 +1317,7 @@ Object { "typeerror", String( This is an error with npm itself. Please report this error at: - https://github.com/npm/cli/issues + https://github.com/npm/cli/issues ), ], ], @@ -1368,7 +1358,7 @@ Object { "typeerror", String( This is an error with npm itself. Please report this error at: - https://github.com/npm/cli/issues + https://github.com/npm/cli/issues ), ], ], @@ -1386,10 +1376,7 @@ Object { "detail": Array [ Array [ "notarget", - String( - In most cases you or one of your dependencies are requesting - a package version that doesn't exist. - ), + "In most cases you or one of your dependencies are requesting a package version that doesn't exist.", ], ], "summary": Array [ @@ -1406,11 +1393,7 @@ Object { "detail": Array [ Array [ "403", - String( - 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. - ), + "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.", ], ], "summary": Array [ @@ -1431,8 +1414,7 @@ Object { 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' + If you are behind a proxy, please make sure that the 'proxy' config is set properly. See: 'npm help config' ), ], ], @@ -1452,8 +1434,7 @@ Object { "", String( - If you are behind a proxy, please make sure that the - 'proxy' config is set properly. See: 'npm help config' + If you are behind a proxy, please make sure that the 'proxy' config is set properly. See: 'npm help config' ), ], ], @@ -1526,10 +1507,7 @@ Object { "detail": Array [ Array [ "git", - String( - Refusing to remove it. Update manually, - or move it out of the way first. - ), + "Refusing to remove it. Update manually, or move it out of the way first.", ], ], "summary": Array [ @@ -1575,7 +1553,7 @@ Object { "detail": Array [ Array [ "need auth", - "You need to authorize this machine using \`npm adduser\`", + "You need to authorize this machine using \`npm login\`", ], ], "summary": Array [ @@ -1596,8 +1574,7 @@ Object { 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' + If you are behind a proxy, please make sure that the 'proxy' config is set properly. See: 'npm help config' ), ], ], @@ -1610,7 +1587,7 @@ Object { } ` -exports[`test/lib/utils/error-message.js TAP replace message/stack sensistive info > must match snapshot 1`] = ` +exports[`test/lib/utils/error-message.js TAP replace message/stack sensitive info > must match snapshot 1`] = ` Object { "detail": Array [], "summary": Array [ diff --git a/tap-snapshots/test/lib/utils/explain-dep.js.test.cjs b/tap-snapshots/test/lib/utils/explain-dep.js.test.cjs index 34620d5c749bc..3fbe92562f879 100644 --- a/tap-snapshots/test/lib/utils/explain-dep.js.test.cjs +++ b/tap-snapshots/test/lib/utils/explain-dep.js.test.cjs @@ -5,6 +5,28 @@ * Make sure to inspect the output below. Do not ignore changes! */ 'use strict' +exports[`test/lib/utils/explain-dep.js TAP basic > circular dependency does not recurse infinitely 1`] = ` +cycle-a@1.0.0 +node_modules/cycle-a + cycle-a@"1.x" from cycle-b@2.0.0 + node_modules/cycle-b + cycle-b@"2.x" from cycle-a@1.0.0 + node_modules/cycle-a + cycle-a@"1.x" from cycle-b@2.0.0 + node_modules/cycle-b +` + +exports[`test/lib/utils/explain-dep.js TAP basic > circular dependency from other side 1`] = ` +cycle-b@2.0.0 +node_modules/cycle-b + cycle-b@"2.x" from cycle-a@1.0.0 + node_modules/cycle-a + cycle-a@"1.x" from cycle-b@2.0.0 + node_modules/cycle-b + cycle-b@"2.x" from cycle-a@1.0.0 + node_modules/cycle-a +` + exports[`test/lib/utils/explain-dep.js TAP basic > ellipses test one 1`] = ` manydep@1.0.0 manydep@"1.0.0" from prod-dep@1.2.3 @@ -21,6 +43,11 @@ manydep@1.0.0 6 more (optdep, extra-neos, deep-dev, peer, the root project, a package with a pretty long name) ` +exports[`test/lib/utils/explain-dep.js TAP basic > explainEdge without seen parameter 1`] = ` +some-dep@"1.x" from parent-pkg@2.0.0 +node_modules/parent-pkg +` + exports[`test/lib/utils/explain-dep.js TAP basic bundled > explain color deep 1`] = ` bundle-of-joy@1.0.0 bundled node_modules/bundle-of-joy @@ -134,6 +161,30 @@ exports[`test/lib/utils/explain-dep.js TAP basic manyDeps > print nocolor 1`] = manydep@1.0.0 ` +exports[`test/lib/utils/explain-dep.js TAP basic npmExtension > explain color deep 1`] = ` +bar@1.2.3 +node_modules/bar + bar@"^1.0.0" from foo@1.0.0 + node_modules/foo (changed by .npm-extension transformManifest dependencies.bar) +` + +exports[`test/lib/utils/explain-dep.js TAP basic npmExtension > explain nocolor shallow 1`] = ` +bar@1.2.3 +node_modules/bar + bar@"^1.0.0" from foo@1.0.0 + node_modules/foo (changed by .npm-extension transformManifest dependencies.bar) +` + +exports[`test/lib/utils/explain-dep.js TAP basic npmExtension > print color 1`] = ` +bar@1.2.3 +node_modules/bar +` + +exports[`test/lib/utils/explain-dep.js TAP basic npmExtension > print nocolor 1`] = ` +bar@1.2.3 +node_modules/bar +` + exports[`test/lib/utils/explain-dep.js TAP basic optional > explain color deep 1`] = ` optdep@1.0.0 optional node_modules/optdep @@ -178,6 +229,30 @@ overridden-root@1.0.0 overridden node_modules/overridden-root ` +exports[`test/lib/utils/explain-dep.js TAP basic packageExtensions > explain color deep 1`] = ` +bar@1.2.3 +node_modules/bar + bar@"^1.0.0" from foo@1.0.0 + node_modules/foo (added by packageExtensions["foo@1"].dependencies.bar) +` + +exports[`test/lib/utils/explain-dep.js TAP basic packageExtensions > explain nocolor shallow 1`] = ` +bar@1.2.3 +node_modules/bar + bar@"^1.0.0" from foo@1.0.0 + node_modules/foo (added by packageExtensions["foo@1"].dependencies.bar) +` + +exports[`test/lib/utils/explain-dep.js TAP basic packageExtensions > print color 1`] = ` +bar@1.2.3 +node_modules/bar +` + +exports[`test/lib/utils/explain-dep.js TAP basic packageExtensions > print nocolor 1`] = ` +bar@1.2.3 +node_modules/bar +` + exports[`test/lib/utils/explain-dep.js TAP basic peer > explain color deep 1`] = ` peer@1.0.0 peer node_modules/peer diff --git a/tap-snapshots/test/lib/utils/explain-eresolve.js.test.cjs b/tap-snapshots/test/lib/utils/explain-eresolve.js.test.cjs index 5190ead244697..ac3f8607cc6c8 100644 --- a/tap-snapshots/test/lib/utils/explain-eresolve.js.test.cjs +++ b/tap-snapshots/test/lib/utils/explain-eresolve.js.test.cjs @@ -42,9 +42,7 @@ peer @isaacs/testing-peer-dep-conflict-chain-d@"1" from @isaacs/testing-peer-dep node_modules/@isaacs/testing-peer-dep-conflict-chain-c @isaacs/testing-peer-dep-conflict-chain-c@"1" from the root project -Fix the upstream dependency conflict, or retry -this command with --force or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic chain-conflict > report with color 1`] = ` @@ -58,9 +56,7 @@ Could not resolve dependency: node_modules/@isaacs/testing-peer-dep-conflict-chain-c @isaacs/testing-peer-dep-conflict-chain-c@"1" from the root project -Fix the upstream dependency conflict, or retry -this command with --force or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic chain-conflict > report with no color 1`] = ` @@ -74,9 +70,7 @@ peer @isaacs/testing-peer-dep-conflict-chain-d@"1" from @isaacs/testing-peer-dep node_modules/@isaacs/testing-peer-dep-conflict-chain-c @isaacs/testing-peer-dep-conflict-chain-c@"1" from the root project -Fix the upstream dependency conflict, or retry -this command with --force or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic cycleNested > explain with color, depth of 2 1`] = ` @@ -136,9 +130,7 @@ node_modules/@isaacs/peer-dep-cycle-c node_modules/@isaacs/peer-dep-cycle-a @isaacs/peer-dep-cycle-a@"1.x" from the root project -Fix the upstream dependency conflict, or retry -this command with --no-strict-peer-deps, --force, or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --no-strict-peer-deps, --force, or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic cycleNested > report with color 1`] = ` @@ -159,9 +151,7 @@ Conflicting peer dependency: @isaacs/peer-dep-cycle-c@1.0.0 node_modules/@isaacs/peer-dep-cycle-a @isaacs/peer-dep-cycle-a@"1.x" from the root project -Fix the upstream dependency conflict, or retry -this command with --no-strict-peer-deps, --force, or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --no-strict-peer-deps, --force, or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic cycleNested > report with no color 1`] = ` @@ -182,9 +172,7 @@ node_modules/@isaacs/peer-dep-cycle-c node_modules/@isaacs/peer-dep-cycle-a @isaacs/peer-dep-cycle-a@"1.x" from the root project -Fix the upstream dependency conflict, or retry -this command with --no-strict-peer-deps, --force, or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --no-strict-peer-deps, --force, or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic eslint-plugin case > explain with color, depth of 2 1`] = ` @@ -256,9 +244,7 @@ node_modules/eslint node_modules/eslint-plugin-eslint-plugin dev eslint-plugin-eslint-plugin@"^3.1.0" from the root project -Fix the upstream dependency conflict, or retry -this command with --force or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic eslint-plugin case > report with color 1`] = ` @@ -280,9 +266,7 @@ Conflicting peer dependency: eslint@7.31.0 node_modules/eslint-plugin-eslint-plugin dev eslint-plugin-eslint-plugin@"^3.1.0" from the root project -Fix the upstream dependency conflict, or retry -this command with --force or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic eslint-plugin case > report with no color 1`] = ` @@ -304,9 +288,7 @@ node_modules/eslint node_modules/eslint-plugin-eslint-plugin dev eslint-plugin-eslint-plugin@"^3.1.0" from the root project -Fix the upstream dependency conflict, or retry -this command with --force or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic gatsby > explain with color, depth of 2 1`] = ` @@ -374,9 +356,7 @@ node_modules/ink-box node_modules/gatsby gatsby@"" from the root project -Fix the upstream dependency conflict, or retry -this command with --no-strict-peer-deps, --force, or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --no-strict-peer-deps, --force, or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic gatsby > report with color 1`] = ` @@ -401,9 +381,7 @@ Could not resolve dependency: gatsby-cli@"^2.12.107" from gatsby@2.24.74 node_modules/gatsby -Fix the upstream dependency conflict, or retry -this command with --no-strict-peer-deps, --force, or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --no-strict-peer-deps, --force, or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic gatsby > report with no color 1`] = ` @@ -428,9 +406,7 @@ node_modules/ink-box gatsby-cli@"^2.12.107" from gatsby@2.24.74 node_modules/gatsby -Fix the upstream dependency conflict, or retry -this command with --no-strict-peer-deps, --force, or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --no-strict-peer-deps, --force, or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic no current node, but has current edge > explain with color, depth of 2 1`] = ` @@ -464,9 +440,7 @@ peer eslint@"^6.0.0" from eslint-plugin-jsdoc@22.2.0 node_modules/eslint-plugin-jsdoc dev eslint-plugin-jsdoc@"^22.1.0" from the root project -Fix the upstream dependency conflict, or retry -this command with --force or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic no current node, but has current edge > report with color 1`] = ` @@ -478,9 +452,7 @@ Could not resolve dependency: node_modules/eslint-plugin-jsdoc dev eslint-plugin-jsdoc@"^22.1.0" from the root project -Fix the upstream dependency conflict, or retry -this command with --force or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic no current node, but has current edge > report with no color 1`] = ` @@ -492,9 +464,7 @@ peer eslint@"^6.0.0" from eslint-plugin-jsdoc@22.2.0 node_modules/eslint-plugin-jsdoc dev eslint-plugin-jsdoc@"^22.1.0" from the root project -Fix the upstream dependency conflict, or retry -this command with --force or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic no current node, no current edge, idk > explain with color, depth of 2 1`] = ` @@ -534,9 +504,7 @@ peer eslint@"^6.0.0" from eslint-plugin-jsdoc@22.2.0 node_modules/eslint-plugin-jsdoc dev eslint-plugin-jsdoc@"^22.1.0" from the root project -Fix the upstream dependency conflict, or retry -this command with --force or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic no current node, no current edge, idk > report with color 1`] = ` @@ -550,9 +518,7 @@ Could not resolve dependency: node_modules/eslint-plugin-jsdoc dev eslint-plugin-jsdoc@"^22.1.0" from the root project -Fix the upstream dependency conflict, or retry -this command with --force or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic no current node, no current edge, idk > report with no color 1`] = ` @@ -566,9 +532,7 @@ peer eslint@"^6.0.0" from eslint-plugin-jsdoc@22.2.0 node_modules/eslint-plugin-jsdoc dev eslint-plugin-jsdoc@"^22.1.0" from the root project -Fix the upstream dependency conflict, or retry -this command with --force or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic withShrinkwrap > explain with color, depth of 2 1`] = ` @@ -613,9 +577,7 @@ node_modules/@isaacs/peer-dep-cycle-b node_modules/@isaacs/peer-dep-cycle-a @isaacs/peer-dep-cycle-a@"1.x" from the root project -Fix the upstream dependency conflict, or retry -this command with --no-strict-peer-deps, --force, or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --no-strict-peer-deps, --force, or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic withShrinkwrap > report with color 1`] = ` @@ -631,9 +593,7 @@ Could not resolve dependency: node_modules/@isaacs/peer-dep-cycle-a @isaacs/peer-dep-cycle-a@"1.x" from the root project -Fix the upstream dependency conflict, or retry -this command with --no-strict-peer-deps, --force, or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --no-strict-peer-deps, --force, or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` exports[`test/lib/utils/explain-eresolve.js TAP basic withShrinkwrap > report with no color 1`] = ` @@ -649,7 +609,5 @@ node_modules/@isaacs/peer-dep-cycle-b node_modules/@isaacs/peer-dep-cycle-a @isaacs/peer-dep-cycle-a@"1.x" from the root project -Fix the upstream dependency conflict, or retry -this command with --no-strict-peer-deps, --force, or --legacy-peer-deps -to accept an incorrect (and potentially broken) dependency resolution. +Fix the upstream dependency conflict, or retry this command with --no-strict-peer-deps, --force, or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution. ` diff --git a/tap-snapshots/test/lib/utils/open-url.js.test.cjs b/tap-snapshots/test/lib/utils/open-url.js.test.cjs index fa256ba131447..5154579f0df59 100644 --- a/tap-snapshots/test/lib/utils/open-url.js.test.cjs +++ b/tap-snapshots/test/lib/utils/open-url.js.test.cjs @@ -22,10 +22,9 @@ npm home: https://www.npmjs.com ` -exports[`test/lib/utils/open-url.js TAP open url prompt does not error when opener can not find command > Outputs extra Browser unavailable message and url 1`] = ` +exports[`test/lib/utils/open-url.js TAP open url prompt does not error when opener cannot find command > Outputs extra Browser unavailable message and url 1`] = ` npm home: https://www.npmjs.com - Browser unavailable. Please open the URL manually: https://www.npmjs.com ` diff --git a/tap-snapshots/test/lib/utils/reify-output.js.test.cjs b/tap-snapshots/test/lib/utils/reify-output.js.test.cjs index d653d4c1fadc0..40d4cd221ca02 100644 --- a/tap-snapshots/test/lib/utils/reify-output.js.test.cjs +++ b/tap-snapshots/test/lib/utils/reify-output.js.test.cjs @@ -22,11 +22,14 @@ up to date in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":0,"changed":0,"audited":0,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 0, - "changed": 0, "audited": 0, - "funding": 0 + "change": [], + "changed": 0, + "funding": 0, + "remove": [], + "removed": 0 } ` @@ -39,11 +42,14 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":0,"changed":0,"audited":1,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 0, - "changed": 0, "audited": 1, + "change": [], + "changed": 0, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -68,11 +74,14 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":0,"changed":0,"audited":2,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 0, - "changed": 0, "audited": 2, + "change": [], + "changed": 0, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -83,11 +92,14 @@ exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added" exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":0,"changed":0,"audited":2,"json":true} 2`] = ` { + "add": [], "added": 0, - "removed": 0, - "changed": 0, "audited": 2, + "change": [], + "changed": 0, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": {}, "metadata": { @@ -106,11 +118,27 @@ changed 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":0,"changed":1,"audited":0,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 0, - "changed": 1, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, + "funding": 0, + "remove": [], + "removed": 0 } ` @@ -123,11 +151,27 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":0,"changed":1,"audited":1,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 0, - "changed": 1, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -145,11 +189,27 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":0,"changed":1,"audited":2,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 0, - "changed": 1, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -165,11 +225,39 @@ changed 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":0,"changed":2,"audited":0,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 0, - "changed": 2, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, + "funding": 0, + "remove": [], + "removed": 0 } ` @@ -182,11 +270,39 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":0,"changed":2,"audited":1,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 0, - "changed": 2, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -204,11 +320,39 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":0,"changed":2,"audited":2,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 0, - "changed": 2, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -224,11 +368,20 @@ removed 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":1,"changed":0,"audited":0,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 1, - "changed": 0, "audited": 0, - "funding": 0 + "change": [], + "changed": 0, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1 } ` @@ -241,11 +394,20 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":1,"changed":0,"audited":1,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 1, - "changed": 0, "audited": 1, + "change": [], + "changed": 0, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -263,11 +425,20 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":1,"changed":0,"audited":2,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 1, - "changed": 0, "audited": 2, + "change": [], + "changed": 0, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -283,11 +454,33 @@ removed 1 package, and changed 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":1,"changed":1,"audited":0,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 1, - "changed": 1, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1 } ` @@ -300,11 +493,33 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":1,"changed":1,"audited":1,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 1, - "changed": 1, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -322,11 +537,33 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":1,"changed":1,"audited":2,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 1, - "changed": 1, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -342,11 +579,45 @@ removed 1 package, and changed 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":1,"changed":2,"audited":0,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 1, - "changed": 2, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1 } ` @@ -359,11 +630,45 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":1,"changed":2,"audited":1,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 1, - "changed": 2, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -381,11 +686,45 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":1,"changed":2,"audited":2,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 1, - "changed": 2, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -401,11 +740,25 @@ removed 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":2,"changed":0,"audited":0,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 2, - "changed": 0, "audited": 0, - "funding": 0 + "change": [], + "changed": 0, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2 } ` @@ -418,11 +771,25 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":2,"changed":0,"audited":1,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 2, - "changed": 0, "audited": 1, + "change": [], + "changed": 0, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -440,11 +807,25 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":2,"changed":0,"audited":2,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 2, - "changed": 0, "audited": 2, + "change": [], + "changed": 0, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -460,11 +841,38 @@ removed 2 packages, and changed 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":2,"changed":1,"audited":0,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 2, - "changed": 1, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2 } ` @@ -477,11 +885,38 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":2,"changed":1,"audited":1,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 2, - "changed": 1, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -499,11 +934,38 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":2,"changed":1,"audited":2,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 2, - "changed": 1, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -519,11 +981,50 @@ removed 2 packages, and changed 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":2,"changed":2,"audited":0,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 2, - "changed": 2, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2 } ` @@ -536,11 +1037,50 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":2,"changed":2,"audited":1,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 2, - "changed": 2, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -558,11 +1098,50 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":0,"removed":2,"changed":2,"audited":2,"json":true} 1`] = ` { + "add": [], "added": 0, - "removed": 2, - "changed": 2, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -578,11 +1157,20 @@ added 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":0,"changed":0,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 0, - "changed": 0, "audited": 0, - "funding": 0 + "change": [], + "changed": 0, + "funding": 0, + "remove": [], + "removed": 0 } ` @@ -595,11 +1183,20 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":0,"changed":0,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 0, - "changed": 0, "audited": 1, + "change": [], + "changed": 0, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -617,11 +1214,20 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":0,"changed":0,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 0, - "changed": 0, "audited": 2, + "change": [], + "changed": 0, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -637,11 +1243,33 @@ added 1 package, and changed 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":0,"changed":1,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 0, - "changed": 1, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, + "funding": 0, + "remove": [], + "removed": 0 } ` @@ -654,11 +1282,33 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":0,"changed":1,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 0, - "changed": 1, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -676,11 +1326,33 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":0,"changed":1,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 0, - "changed": 1, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -696,11 +1368,45 @@ added 1 package, and changed 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":0,"changed":2,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 0, - "changed": 2, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, + "funding": 0, + "remove": [], + "removed": 0 } ` @@ -713,11 +1419,45 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":0,"changed":2,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 0, - "changed": 2, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -735,11 +1475,45 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":0,"changed":2,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 0, - "changed": 2, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -755,11 +1529,26 @@ added 1 package, and removed 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":1,"changed":0,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 1, - "changed": 0, "audited": 0, - "funding": 0 + "change": [], + "changed": 0, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1 } ` @@ -772,11 +1561,26 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":1,"changed":0,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 1, - "changed": 0, "audited": 1, + "change": [], + "changed": 0, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -794,11 +1598,26 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":1,"changed":0,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 1, - "changed": 0, "audited": 2, + "change": [], + "changed": 0, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -814,11 +1633,39 @@ added 1 package, removed 1 package, and changed 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":1,"changed":1,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 1, - "changed": 1, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1 } ` @@ -831,11 +1678,39 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":1,"changed":1,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 1, - "changed": 1, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -853,11 +1728,39 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":1,"changed":1,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 1, - "changed": 1, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -873,11 +1776,51 @@ added 1 package, removed 1 package, and changed 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":1,"changed":2,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 1, - "changed": 2, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1 } ` @@ -890,11 +1833,51 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":1,"changed":2,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 1, - "changed": 2, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -912,11 +1895,51 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":1,"changed":2,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 1, - "changed": 2, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -932,11 +1955,31 @@ added 1 package, and removed 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":2,"changed":0,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 2, - "changed": 0, "audited": 0, - "funding": 0 + "change": [], + "changed": 0, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2 } ` @@ -949,11 +1992,31 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":2,"changed":0,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 2, - "changed": 0, "audited": 1, + "change": [], + "changed": 0, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -971,11 +2034,31 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":2,"changed":0,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 2, - "changed": 0, "audited": 2, + "change": [], + "changed": 0, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -991,11 +2074,44 @@ added 1 package, removed 2 packages, and changed 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":2,"changed":1,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 2, - "changed": 1, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2 } ` @@ -1008,11 +2124,44 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":2,"changed":1,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 2, - "changed": 1, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -1030,11 +2179,44 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":2,"changed":1,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 2, - "changed": 1, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -1050,11 +2232,56 @@ added 1 package, removed 2 packages, and changed 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":2,"changed":2,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 2, - "changed": 2, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2 } ` @@ -1067,11 +2294,56 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":2,"changed":2,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 2, - "changed": 2, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -1089,11 +2361,56 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":1,"removed":2,"changed":2,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 1, - "removed": 2, - "changed": 2, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -1109,11 +2426,25 @@ added 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":0,"changed":0,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 0, - "changed": 0, "audited": 0, - "funding": 0 + "change": [], + "changed": 0, + "funding": 0, + "remove": [], + "removed": 0 } ` @@ -1126,11 +2457,25 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":0,"changed":0,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 0, - "changed": 0, "audited": 1, + "change": [], + "changed": 0, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -1148,11 +2493,25 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":0,"changed":0,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 0, - "changed": 0, "audited": 2, + "change": [], + "changed": 0, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -1168,11 +2527,38 @@ added 2 packages, and changed 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":0,"changed":1,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 0, - "changed": 1, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, + "funding": 0, + "remove": [], + "removed": 0 } ` @@ -1185,11 +2571,38 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":0,"changed":1,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 0, - "changed": 1, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -1207,11 +2620,38 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":0,"changed":1,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 0, - "changed": 1, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -1227,11 +2667,50 @@ added 2 packages, and changed 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":0,"changed":2,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 0, - "changed": 2, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, + "funding": 0, + "remove": [], + "removed": 0 } ` @@ -1244,11 +2723,50 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":0,"changed":2,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 0, - "changed": 2, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -1266,11 +2784,50 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":0,"changed":2,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 0, - "changed": 2, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [], + "removed": 0, "audit": { "vulnerabilities": { "total": 0 @@ -1286,11 +2843,31 @@ added 2 packages, and removed 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":1,"changed":0,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 1, - "changed": 0, "audited": 0, - "funding": 0 + "change": [], + "changed": 0, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1 } ` @@ -1303,11 +2880,31 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":1,"changed":0,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 1, - "changed": 0, "audited": 1, + "change": [], + "changed": 0, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -1325,11 +2922,31 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":1,"changed":0,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 1, - "changed": 0, "audited": 2, + "change": [], + "changed": 0, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -1345,11 +2962,44 @@ added 2 packages, removed 1 package, and changed 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":1,"changed":1,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 1, - "changed": 1, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1 } ` @@ -1362,11 +3012,44 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":1,"changed":1,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 1, - "changed": 1, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -1384,11 +3067,44 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":1,"changed":1,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 1, - "changed": 1, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -1404,11 +3120,56 @@ added 2 packages, removed 1 package, and changed 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":1,"changed":2,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 1, - "changed": 2, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1 } ` @@ -1421,11 +3182,56 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":1,"changed":2,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 1, - "changed": 2, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -1443,11 +3249,56 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":1,"changed":2,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 1, - "changed": 2, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 1, "audit": { "vulnerabilities": { "total": 0 @@ -1463,11 +3314,36 @@ added 2 packages, and removed 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":2,"changed":0,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 2, - "changed": 0, "audited": 0, - "funding": 0 + "change": [], + "changed": 0, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2 } ` @@ -1480,11 +3356,36 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":2,"changed":0,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 2, - "changed": 0, "audited": 1, + "change": [], + "changed": 0, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -1502,11 +3403,36 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":2,"changed":0,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 2, - "changed": 0, "audited": 2, + "change": [], + "changed": 0, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -1522,11 +3448,49 @@ added 2 packages, removed 2 packages, and changed 1 package in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":2,"changed":1,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 2, - "changed": 1, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2 } ` @@ -1539,11 +3503,49 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":2,"changed":1,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 2, - "changed": 1, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -1561,11 +3563,49 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":2,"changed":1,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 2, - "changed": 1, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 1, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -1581,11 +3621,61 @@ added 2 packages, removed 2 packages, and changed 2 packages in {TIME} exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":2,"changed":2,"audited":0,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 2, - "changed": 2, "audited": 0, - "funding": 0 + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, + "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2 } ` @@ -1598,11 +3688,61 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":2,"changed":2,"audited":1,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 2, - "changed": 2, "audited": 1, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 @@ -1620,11 +3760,61 @@ found 0 vulnerabilities exports[`test/lib/utils/reify-output.js TAP packages changed message > {"added":2,"removed":2,"changed":2,"audited":2,"json":true} 1`] = ` { + "add": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], "added": 2, - "removed": 2, - "changed": 2, "audited": 2, + "change": [ + { + "from": { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/a/1" + }, + "to": { + "name": "@npmcli/pkg1", + "version": "1.1.1", + "path": "test/i/1" + } + }, + { + "from": { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/a/0" + }, + "to": { + "name": "@npmcli/pkg0", + "version": "1.1.0", + "path": "test/i/0" + } + } + ], + "changed": 2, "funding": 0, + "remove": [ + { + "name": "@npmcli/pkg1", + "version": "1.0.1", + "path": "test/1" + }, + { + "name": "@npmcli/pkg0", + "version": "1.0.0", + "path": "test/0" + } + ], + "removed": 2, "audit": { "vulnerabilities": { "total": 0 diff --git a/tap-snapshots/test/lib/utils/sbom-cyclonedx.js.test.cjs b/tap-snapshots/test/lib/utils/sbom-cyclonedx.js.test.cjs index 7a8d79017f36a..124478bc82993 100644 --- a/tap-snapshots/test/lib/utils/sbom-cyclonedx.js.test.cjs +++ b/tap-snapshots/test/lib/utils/sbom-cyclonedx.js.test.cjs @@ -34,12 +34,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP node - with deps > must match snap "scope": "required", "author": "Author", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [] } }, @@ -51,12 +46,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP node - with deps > must match snap "version": "0.0.1", "scope": "required", "purl": "pkg:npm/dep1@0.0.1", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "node_modules/dep1" - } - ], + "properties": [], "externalReferences": [] }, { @@ -66,12 +56,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP node - with deps > must match snap "version": "0.0.2", "scope": "required", "purl": "pkg:npm/dep2@0.0.2", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "node_modules/dep2" - } - ], + "properties": [], "externalReferences": [] } ], @@ -97,6 +82,126 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP node - with deps > must match snap } ` +exports[`test/lib/utils/sbom-cyclonedx.js TAP node - with duplicate deps > must match snapshot 1`] = ` +{ + "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "serialNumber": "urn:uuid:00000000-0000-0000-0000-000000000000", + "version": 1, + "metadata": { + "timestamp": "2020-01-01T00:00:00.000Z", + "lifecycles": [ + { + "phase": "build" + } + ], + "tools": [ + { + "vendor": "npm", + "name": "cli", + "version": "10.0.0 " + } + ], + "component": { + "bom-ref": "root@1.0.0", + "type": "library", + "name": "root", + "version": "1.0.0", + "scope": "required", + "author": "Author", + "purl": "pkg:npm/root@1.0.0", + "properties": [], + "externalReferences": [] + } + }, + "components": [ + { + "bom-ref": "dep1@0.0.1", + "type": "library", + "name": "dep1", + "version": "0.0.1", + "scope": "required", + "purl": "pkg:npm/dep1@0.0.1", + "properties": [], + "externalReferences": [] + } + ], + "dependencies": [ + { + "ref": "root@1.0.0", + "dependsOn": [ + "dep1@0.0.1" + ] + }, + { + "ref": "dep1@0.0.1", + "dependsOn": [] + } + ] +} +` + +exports[`test/lib/utils/sbom-cyclonedx.js TAP node - with duplicate edges to same dep > must match snapshot 1`] = ` +{ + "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "serialNumber": "urn:uuid:00000000-0000-0000-0000-000000000000", + "version": 1, + "metadata": { + "timestamp": "2020-01-01T00:00:00.000Z", + "lifecycles": [ + { + "phase": "build" + } + ], + "tools": [ + { + "vendor": "npm", + "name": "cli", + "version": "10.0.0 " + } + ], + "component": { + "bom-ref": "root@1.0.0", + "type": "library", + "name": "root", + "version": "1.0.0", + "scope": "required", + "author": "Author", + "purl": "pkg:npm/root@1.0.0", + "properties": [], + "externalReferences": [] + } + }, + "components": [ + { + "bom-ref": "dep1@0.0.1", + "type": "library", + "name": "dep1", + "version": "0.0.1", + "scope": "required", + "purl": "pkg:npm/dep1@0.0.1", + "properties": [], + "externalReferences": [] + } + ], + "dependencies": [ + { + "ref": "root@1.0.0", + "dependsOn": [ + "dep1@0.0.1" + ] + }, + { + "ref": "dep1@0.0.1", + "dependsOn": [] + } + ] +} +` + exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - application package type > must match snapshot 1`] = ` { "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", @@ -126,12 +231,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - application package "scope": "required", "author": "Author", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [] } }, @@ -175,10 +275,6 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - bundled > must match "author": "Author", "purl": "pkg:npm/root@1.0.0", "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - }, { "name": "cdx:npm:package:bundled", "value": "true" @@ -227,10 +323,6 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - development > must m "author": "Author", "purl": "pkg:npm/root@1.0.0", "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - }, { "name": "cdx:npm:package:development", "value": "true" @@ -279,10 +371,6 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - extraneous > must ma "author": "Author", "purl": "pkg:npm/root@1.0.0", "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - }, { "name": "cdx:npm:package:extraneous", "value": "true" @@ -330,12 +418,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - from git url > must "scope": "required", "author": "Author", "purl": "pkg:npm/root@1.0.0?vcs_url=https://github.com/foo/bar#1234", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [ { "type": "distribution", @@ -382,12 +465,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - no package info > mu "version": "1.0.0", "scope": "required", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [] } }, @@ -430,12 +508,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - optional > must matc "scope": "optional", "author": "Author", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [] } }, @@ -478,12 +551,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - package lock only > "scope": "required", "author": "Author", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [] } }, @@ -527,10 +595,6 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - private > must match "author": "Author", "purl": "pkg:npm/root@1.0.0", "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - }, { "name": "cdx:npm:package:private", "value": "true" @@ -578,12 +642,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with author object > "scope": "required", "author": "Arthur", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [] } }, @@ -627,12 +686,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with description > m "author": "Author", "description": "Package description", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [] } }, @@ -675,12 +729,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with distribution ur "scope": "required", "author": "Author", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [ { "type": "distribution", @@ -728,12 +777,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with homepage > must "scope": "required", "author": "Author", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [ { "type": "website", @@ -781,12 +825,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with integrity > mus "scope": "required", "author": "Author", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [], "hashes": [ { @@ -835,12 +874,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with issue tracker > "scope": "required", "author": "Author", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [ { "type": "issue-tracker", @@ -859,7 +893,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with issue tracker > } ` -exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with license expression > must match snapshot 1`] = ` +exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with legacy licenses array (multiple) > must match snapshot 1`] = ` { "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", "bomFormat": "CycloneDX", @@ -888,16 +922,61 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with license express "scope": "required", "author": "Author", "purl": "pkg:npm/root@1.0.0", - "properties": [ + "properties": [], + "externalReferences": [], + "licenses": [ { - "name": "cdx:npm:package:path", - "value": "" + "expression": "MIT OR Apache-2.0" } - ], + ] + } + }, + "components": [], + "dependencies": [ + { + "ref": "root@1.0.0", + "dependsOn": [] + } + ] +} +` + +exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with legacy licenses array (single) > must match snapshot 1`] = ` +{ + "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "serialNumber": "urn:uuid:00000000-0000-0000-0000-000000000000", + "version": 1, + "metadata": { + "timestamp": "2020-01-01T00:00:00.000Z", + "lifecycles": [ + { + "phase": "build" + } + ], + "tools": [ + { + "vendor": "npm", + "name": "cli", + "version": "10.0.0 " + } + ], + "component": { + "bom-ref": "root@1.0.0", + "type": "library", + "name": "root", + "version": "1.0.0", + "scope": "required", + "author": "Author", + "purl": "pkg:npm/root@1.0.0", + "properties": [], "externalReferences": [], "licenses": [ { - "expression": "(MIT OR Apache-2.0)" + "license": { + "id": "MIT" + } } ] } @@ -912,7 +991,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with license express } ` -exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with license object > must match snapshot 1`] = ` +exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with legacy licenses array (string entries) > must match snapshot 1`] = ` { "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", "bomFormat": "CycloneDX", @@ -941,12 +1020,105 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with license object "scope": "required", "author": "Author", "purl": "pkg:npm/root@1.0.0", - "properties": [ + "properties": [], + "externalReferences": [], + "licenses": [ { - "name": "cdx:npm:package:path", - "value": "" + "license": { + "id": "MIT" + } } - ], + ] + } + }, + "components": [], + "dependencies": [ + { + "ref": "root@1.0.0", + "dependsOn": [] + } + ] +} +` + +exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with license expression > must match snapshot 1`] = ` +{ + "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "serialNumber": "urn:uuid:00000000-0000-0000-0000-000000000000", + "version": 1, + "metadata": { + "timestamp": "2020-01-01T00:00:00.000Z", + "lifecycles": [ + { + "phase": "build" + } + ], + "tools": [ + { + "vendor": "npm", + "name": "cli", + "version": "10.0.0 " + } + ], + "component": { + "bom-ref": "root@1.0.0", + "type": "library", + "name": "root", + "version": "1.0.0", + "scope": "required", + "author": "Author", + "purl": "pkg:npm/root@1.0.0", + "properties": [], + "externalReferences": [], + "licenses": [ + { + "expression": "(MIT OR Apache-2.0)" + } + ] + } + }, + "components": [], + "dependencies": [ + { + "ref": "root@1.0.0", + "dependsOn": [] + } + ] +} +` + +exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with license object > must match snapshot 1`] = ` +{ + "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "serialNumber": "urn:uuid:00000000-0000-0000-0000-000000000000", + "version": 1, + "metadata": { + "timestamp": "2020-01-01T00:00:00.000Z", + "lifecycles": [ + { + "phase": "build" + } + ], + "tools": [ + { + "vendor": "npm", + "name": "cli", + "version": "10.0.0 " + } + ], + "component": { + "bom-ref": "root@1.0.0", + "type": "library", + "name": "root", + "version": "1.0.0", + "scope": "required", + "author": "Author", + "purl": "pkg:npm/root@1.0.0", + "properties": [], "externalReferences": [], "licenses": [ { @@ -996,12 +1168,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with repository url "scope": "required", "author": "Author", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [ { "type": "vcs", @@ -1049,12 +1216,7 @@ exports[`test/lib/utils/sbom-cyclonedx.js TAP single node - with single license "scope": "required", "author": "Author", "purl": "pkg:npm/root@1.0.0", - "properties": [ - { - "name": "cdx:npm:package:path", - "value": "" - } - ], + "properties": [], "externalReferences": [], "licenses": [ { diff --git a/tap-snapshots/test/lib/utils/sbom-spdx.js.test.cjs b/tap-snapshots/test/lib/utils/sbom-spdx.js.test.cjs index b887e13ca7dc0..6adb6d26de143 100644 --- a/tap-snapshots/test/lib/utils/sbom-spdx.js.test.cjs +++ b/tap-snapshots/test/lib/utils/sbom-spdx.js.test.cjs @@ -182,6 +182,162 @@ exports[`test/lib/utils/sbom-spdx.js TAP node - with deps > must match snapshot } ` +exports[`test/lib/utils/sbom-spdx.js TAP node - with duplicate deps > must match snapshot 1`] = ` +{ + "spdxVersion": "SPDX-2.3", + "dataLicense": "CC0-1.0", + "SPDXID": "SPDXRef-DOCUMENT", + "name": "root@1.0.0", + "documentNamespace": "docns", + "creationInfo": { + "created": "2020-01-01T00:00:00.000Z", + "creators": [ + "Tool: npm/cli-10.0.0 " + ] + }, + "documentDescribes": [ + "SPDXRef-Package-root-1.0.0" + ], + "packages": [ + { + "name": "root", + "SPDXID": "SPDXRef-Package-root-1.0.0", + "versionInfo": "1.0.0", + "packageFileName": "", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "NOASSERTION", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/root@1.0.0" + } + ] + }, + { + "name": "dep1", + "SPDXID": "SPDXRef-Package-dep1-0.0.1", + "versionInfo": "0.0.1", + "packageFileName": "node_modules/dep1", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "NOASSERTION", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/dep1@0.0.1" + } + ] + }, + { + "name": "dep2", + "SPDXID": "SPDXRef-Package-dep2-0.0.2", + "versionInfo": "0.0.2", + "packageFileName": "node_modules/dep2", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "NOASSERTION", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/dep2@0.0.2" + } + ] + } + ], + "relationships": [ + { + "spdxElementId": "SPDXRef-DOCUMENT", + "relatedSpdxElement": "SPDXRef-Package-root-1.0.0", + "relationshipType": "DESCRIBES" + }, + { + "spdxElementId": "SPDXRef-Package-dep1-0.0.1", + "relatedSpdxElement": "SPDXRef-Package-root-1.0.0", + "relationshipType": "DEPENDENCY_OF" + }, + { + "spdxElementId": "SPDXRef-Package-dep2-0.0.2", + "relatedSpdxElement": "SPDXRef-Package-root-1.0.0", + "relationshipType": "DEPENDENCY_OF" + } + ] +} +` + +exports[`test/lib/utils/sbom-spdx.js TAP node - with duplicate edges to same dep > must match snapshot 1`] = ` +{ + "spdxVersion": "SPDX-2.3", + "dataLicense": "CC0-1.0", + "SPDXID": "SPDXRef-DOCUMENT", + "name": "root@1.0.0", + "documentNamespace": "docns", + "creationInfo": { + "created": "2020-01-01T00:00:00.000Z", + "creators": [ + "Tool: npm/cli-10.0.0 " + ] + }, + "documentDescribes": [ + "SPDXRef-Package-root-1.0.0" + ], + "packages": [ + { + "name": "root", + "SPDXID": "SPDXRef-Package-root-1.0.0", + "versionInfo": "1.0.0", + "packageFileName": "", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "NOASSERTION", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/root@1.0.0" + } + ] + }, + { + "name": "dep1", + "SPDXID": "SPDXRef-Package-dep1-0.0.1", + "versionInfo": "0.0.1", + "packageFileName": "node_modules/dep1", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "NOASSERTION", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/dep1@0.0.1" + } + ] + } + ], + "relationships": [ + { + "spdxElementId": "SPDXRef-DOCUMENT", + "relatedSpdxElement": "SPDXRef-Package-root-1.0.0", + "relationshipType": "DESCRIBES" + }, + { + "spdxElementId": "SPDXRef-Package-dep1-0.0.1", + "relatedSpdxElement": "SPDXRef-Package-root-1.0.0", + "relationshipType": "DEPENDENCY_OF" + } + ] +} +` + exports[`test/lib/utils/sbom-spdx.js TAP single node - application package type > must match snapshot 1`] = ` { "spdxVersion": "SPDX-2.3", @@ -505,6 +661,141 @@ exports[`test/lib/utils/sbom-spdx.js TAP single node - with integrity > must mat } ` +exports[`test/lib/utils/sbom-spdx.js TAP single node - with legacy licenses array (multiple) > must match snapshot 1`] = ` +{ + "spdxVersion": "SPDX-2.3", + "dataLicense": "CC0-1.0", + "SPDXID": "SPDXRef-DOCUMENT", + "name": "root@1.0.0", + "documentNamespace": "docns", + "creationInfo": { + "created": "2020-01-01T00:00:00.000Z", + "creators": [ + "Tool: npm/cli-10.0.0 " + ] + }, + "documentDescribes": [ + "SPDXRef-Package-root-1.0.0" + ], + "packages": [ + { + "name": "root", + "SPDXID": "SPDXRef-Package-root-1.0.0", + "versionInfo": "1.0.0", + "packageFileName": "", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "MIT OR Apache-2.0", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/root@1.0.0" + } + ] + } + ], + "relationships": [ + { + "spdxElementId": "SPDXRef-DOCUMENT", + "relatedSpdxElement": "SPDXRef-Package-root-1.0.0", + "relationshipType": "DESCRIBES" + } + ] +} +` + +exports[`test/lib/utils/sbom-spdx.js TAP single node - with legacy licenses array (single) > must match snapshot 1`] = ` +{ + "spdxVersion": "SPDX-2.3", + "dataLicense": "CC0-1.0", + "SPDXID": "SPDXRef-DOCUMENT", + "name": "root@1.0.0", + "documentNamespace": "docns", + "creationInfo": { + "created": "2020-01-01T00:00:00.000Z", + "creators": [ + "Tool: npm/cli-10.0.0 " + ] + }, + "documentDescribes": [ + "SPDXRef-Package-root-1.0.0" + ], + "packages": [ + { + "name": "root", + "SPDXID": "SPDXRef-Package-root-1.0.0", + "versionInfo": "1.0.0", + "packageFileName": "", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "MIT", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/root@1.0.0" + } + ] + } + ], + "relationships": [ + { + "spdxElementId": "SPDXRef-DOCUMENT", + "relatedSpdxElement": "SPDXRef-Package-root-1.0.0", + "relationshipType": "DESCRIBES" + } + ] +} +` + +exports[`test/lib/utils/sbom-spdx.js TAP single node - with legacy licenses array (string entries) > must match snapshot 1`] = ` +{ + "spdxVersion": "SPDX-2.3", + "dataLicense": "CC0-1.0", + "SPDXID": "SPDXRef-DOCUMENT", + "name": "root@1.0.0", + "documentNamespace": "docns", + "creationInfo": { + "created": "2020-01-01T00:00:00.000Z", + "creators": [ + "Tool: npm/cli-10.0.0 " + ] + }, + "documentDescribes": [ + "SPDXRef-Package-root-1.0.0" + ], + "packages": [ + { + "name": "root", + "SPDXID": "SPDXRef-Package-root-1.0.0", + "versionInfo": "1.0.0", + "packageFileName": "", + "downloadLocation": "NOASSERTION", + "filesAnalyzed": false, + "homepage": "NOASSERTION", + "licenseDeclared": "MIT", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:npm/root@1.0.0" + } + ] + } + ], + "relationships": [ + { + "spdxElementId": "SPDXRef-DOCUMENT", + "relatedSpdxElement": "SPDXRef-Package-root-1.0.0", + "relationshipType": "DESCRIBES" + } + ] +} +` + exports[`test/lib/utils/sbom-spdx.js TAP single node - with license expression > must match snapshot 1`] = ` { "spdxVersion": "SPDX-2.3", diff --git a/tap-snapshots/test/lib/utils/validate-lockfile.js.test.cjs b/tap-snapshots/test/lib/utils/validate-lockfile.js.test.cjs index 98a51267b1f4e..5335beb359996 100644 --- a/tap-snapshots/test/lib/utils/validate-lockfile.js.test.cjs +++ b/tap-snapshots/test/lib/utils/validate-lockfile.js.test.cjs @@ -19,6 +19,20 @@ exports[`test/lib/utils/validate-lockfile.js TAP identical inventory for both id Array [] ` +exports[`test/lib/utils/validate-lockfile.js TAP lock file records a patch package.json no longer declares > should report a stray lock file patch 1`] = ` +Array [ + "Invalid: lock file records a patch for foo@1.0.0 that package.json no longer declares", +] +` + +exports[`test/lib/utils/validate-lockfile.js TAP mismatching patch integrity or path > should error on integrity drift, path drift, and a newly added patch 1`] = ` +Array [ + "Invalid: patch for foo@1.0.0 does not match the patch recorded in the lock file", + "Invalid: patch for bar@2.0.0 does not match the patch recorded in the lock file", + "Invalid: package.json declares a patch for baz@3.0.0 that the lock file does not record (it may have been skipped with --ignore-patch-failures). Fix the patch and reinstall, or remove its patchedDependencies entry", +] +` + exports[`test/lib/utils/validate-lockfile.js TAP mismatching versions on inventory > should have errors for each mismatching version 1`] = ` Array [ "Invalid: lock file's foo@1.0.0 does not satisfy foo@2.0.0", diff --git a/test/bin/windows-shims.js b/test/bin/windows-shims.js index 8fbee609a0fab..d785fbe7b1c55 100644 --- a/test/bin/windows-shims.js +++ b/test/bin/windows-shims.js @@ -20,6 +20,9 @@ const BIN = join(ROOT, 'bin') const SHIMS = readNonJsFiles(BIN) const NODE_GYP = readNonJsFiles(join(BIN, 'node-gyp-bin')) const SHIM_EXTS = [...new Set(Object.keys(SHIMS).map(p => extname(p)))] +const PACKAGE_NAME = 'test' +const PACKAGE_VERSION = '1.0.0' +const SCRIPT_NAME = 'args.js' t.test('shim contents', t => { // these scripts should be kept in sync so this tests the contents of each @@ -99,6 +102,18 @@ t.test('run shims', t => { }, }, }, + // test script returning all command line arguments + [SCRIPT_NAME]: `#!/usr/bin/env node\n\nprocess.argv.slice(2).forEach((arg) => console.log(arg))`, + // package.json for the test script + 'package.json': ` + { + "name": "${PACKAGE_NAME}", + "version": "${PACKAGE_VERSION}", + "scripts": { + "test": "node ${SCRIPT_NAME}" + }, + "bin": "${SCRIPT_NAME}" + }`, }) // The removal of this fixture causes this test to fail when done with @@ -112,6 +127,12 @@ t.test('run shims', t => { // only cygwin *requires* the -l, but the others are ok with it args.unshift('-l') } + if (cmd.toLowerCase().endsWith('powershell.exe') || cmd.toLowerCase().endsWith('pwsh.exe')) { + // pwsh *requires* the -Command, Windows PowerShell defaults to it + args.unshift('-Command') + // powershell requires escaping double-quotes for this test + args = args.map(elem => elem.replaceAll('"', '\\"')) + } const result = spawnSync(`"${cmd}"`, args, { // don't hit the registry for the update check env: { PATH: path, npm_config_update_notifier: 'false' }, @@ -162,6 +183,7 @@ t.test('run shims', t => { const shells = Object.entries({ cmd: 'cmd', + powershell: 'powershell', pwsh: 'pwsh', git: join(ProgramFiles, 'Git', 'bin', 'bash.exe'), 'user git': join(ProgramFiles, 'Git', 'usr', 'bin', 'bash.exe'), @@ -216,7 +238,7 @@ t.test('run shims', t => { } }) - const matchCmd = (t, cmd, bin, match) => { + const matchCmd = (t, cmd, bin, match, params, expected) => { const args = [] const opts = {} @@ -227,6 +249,7 @@ t.test('run shims', t => { case 'bash.exe': args.push(bin) break + case 'powershell.exe': case 'pwsh.exe': args.push(`${bin}.ps1`) break @@ -234,18 +257,38 @@ t.test('run shims', t => { throw new Error('unknown shell') } - const isNpm = bin === 'npm' - const result = spawnPath(cmd, [...args, isNpm ? 'help' : '--version'], opts) + const result = spawnPath(cmd, [...args, ...params], opts) + + // run-script@11 emits its run banners as notice logs on stderr, e.g. + // "npm notice run test@1.0.0 test". Strip them so we can assert on the + // script's actual output. + if (result.stderr) { + result.stderr = result.stderr.toString() + .split('\n') + .filter(line => !line.startsWith('npm notice run')) + .join('\n') + .trim() + } t.match(result, { status: 0, signal: null, stderr: '', - stdout: isNpm ? `npm@${version} ${ROOT}` : version, + stdout: expected, ...match, - }, `${cmd} ${bin}`) + }, `${cmd} ${bin} ${params[0]}`) } + // Array with command line parameters and expected output + const tests = [ + { bin: 'npm', params: ['help'], expected: `npm@${version} ${ROOT}` }, + { bin: 'npx', params: ['--version'], expected: version }, + { bin: 'npm', params: ['test'], expected: '' }, + { bin: 'npm', params: [`test -- hello -p1 world -p2 "hello world" --q1=hello world --q2="hello world"`], expected: `hello\n-p1\nworld\n-p2\nhello world\n--q1=hello\nworld\n--q2=hello world` }, + { bin: 'npm', params: ['test -- a=1,b=2,c=3'], expected: `a=1,b=2,c=3` }, + { bin: 'npx', params: ['. -- a=1,b=2,c=3'], expected: `a=1,b=2,c=3` }, + ] + // ensure that all tests are either run or skipped t.plan(shells.length) @@ -259,9 +302,17 @@ t.test('run shims', t => { } return t.end() } - t.plan(2) - matchCmd(t, cmd, 'npm', match) - matchCmd(t, cmd, 'npx', match) + t.plan(tests.length) + for (const { bin, params, expected } of tests) { + if (name === 'cygwin bash' && ( + (bin === 'npm' && params[0].startsWith('test')) || + (bin === 'npx' && params[0].startsWith('.')) + )) { + t.skip("`cygwin bash` doesn't respect option `{ cwd: path }` when calling `spawnSync`") + } else { + matchCmd(t, cmd, bin, match, params, expected) + } + } }) } }) diff --git a/test/fixtures/clean-snapshot.js b/test/fixtures/clean-snapshot.js index bcbf699cb81fc..3439400b576ae 100644 --- a/test/fixtures/clean-snapshot.js +++ b/test/fixtures/clean-snapshot.js @@ -42,12 +42,18 @@ const cleanZlib = str => str .replace(/"integrity": ".*",/g, '"integrity": "{integrity}",') .replace(/"size": [0-9]*,/g, '"size": "{size}",') +const cleanPackumentCache = str => str + .replace(/heap:[0-9]*/g, 'heap:{heap}') + .replace(/maxSize:[0-9]*/g, 'maxSize:{maxSize}') + .replace(/maxEntrySize:[0-9]*/g, 'maxEntrySize:{maxEntrySize}') + module.exports = { cleanCwd, cleanDate, cleanNewlines, cleanTime, cleanZlib, + cleanPackumentCache, normalizePath, pathRegex, } diff --git a/test/fixtures/git-test.tgz b/test/fixtures/git-test.tgz new file mode 100644 index 0000000000000..c06592708c2a0 Binary files /dev/null and b/test/fixtures/git-test.tgz differ diff --git a/test/fixtures/libnpmsearch-stream-result.js b/test/fixtures/libnpmsearch-stream-result.js index 872a7940340d4..db1c0fae5752b 100644 --- a/test/fixtures/libnpmsearch-stream-result.js +++ b/test/fixtures/libnpmsearch-stream-result.js @@ -140,28 +140,6 @@ module.exports = [ { username: 'isaacs', email: 'i@izs.me' }, ], }, - { - name: 'libnpmhook', - scope: 'unscoped', - version: '6.0.1', - description: 'programmatic API for managing npm registry hooks', - keywords: ['npm', 'hooks', 'registry', 'npm api'], - date: '2020-11-03T19:20:45.818Z', - links: { - npm: 'https://www.npmjs.com/package/libnpmhook', - homepage: 'https://github.com/npm/libnpmhook#readme', - repository: 'https://github.com/npm/libnpmhook', - bugs: 'https://github.com/npm/libnpmhook/issues', - }, - author: { name: 'Kat Marchán', email: 'kzm@sykosomatic.org' }, - publisher: { username: 'nlf', email: 'quitlahok@gmail.com' }, - maintainers: [ - { username: 'nlf', email: 'quitlahok@gmail.com' }, - { username: 'ruyadorno', email: 'ruyadorno@hotmail.com' }, - { username: 'darcyclarke', email: 'darcy@darcyclarke.me' }, - { username: 'isaacs', email: 'i@izs.me' }, - ], - }, { name: 'libnpmpublish', scope: 'unscoped', diff --git a/test/fixtures/mock-npm.js b/test/fixtures/mock-npm.js index 9e9113972d6a3..0b29fc934d84c 100644 --- a/test/fixtures/mock-npm.js +++ b/test/fixtures/mock-npm.js @@ -83,6 +83,16 @@ const getMockNpm = async (t, { mocks, init, load, npm: npmOpts }) => { await Promise.all(this.unrefPromises) return res } + + async exec (cmd, args = this.argv) { + // In tests, when exec is called with args, update config.argv to include them + // This mimics production where config.argv contains the full command line + if (args && args !== this.argv) { + // Build full argv: ['node', 'npm', cmd, ...args] + this.config.argv = [process.argv[0], process.argv[1], cmd, ...args] + } + return super.exec(cmd, args) + } } const npm = init ? new MockNpm() : null @@ -107,6 +117,7 @@ const setupMockNpm = async (t, { exec = null, // optionally exec the command before returning // test dirs prefixDir = {}, + prefixOverride = null, // sets global and local prefix to this, the same as the `--prefix` flag homeDir = {}, cacheDir = {}, globalPrefixDir = { node_modules: {} }, @@ -170,9 +181,9 @@ const setupMockNpm = async (t, { const dirs = { testdir: dir, - prefix: path.join(dir, 'prefix'), + prefix: prefixOverride ?? path.join(dir, 'prefix'), cache: path.join(dir, 'cache'), - globalPrefix: path.join(dir, 'global'), + globalPrefix: prefixOverride ?? path.join(dir, 'global'), home: path.join(dir, 'home'), other: path.join(dir, 'other'), } @@ -292,12 +303,26 @@ const setupMockNpm = async (t, { const loadNpmWithRegistry = async (t, opts) => { const mock = await setupMockNpm(t, opts) + return { + ...mock, + ...loadRegistry(t, mock, opts), + ...loadFsAssertions(t, mock), + } +} + +const loadRegistry = (t, mock, opts) => { const registry = new MockRegistry({ tap: t, - registry: mock.npm.config.get('registry'), - strict: true, + registry: opts.registry ?? mock.npm.config.get('registry'), + authorization: opts.authorization, + basic: opts.basic, + debug: opts.debugRegistry ?? false, + strict: opts.strictRegistryNock ?? true, }) + return { registry } +} +const loadFsAssertions = (t, mock) => { const fileShouldExist = (filePath) => { t.equal( fsSync.existsSync(path.join(mock.npm.prefix, filePath)), true, `${filePath} should exist` @@ -352,7 +377,7 @@ const loadNpmWithRegistry = async (t, opts) => { packageDirty, } - return { registry, assert, ...mock } + return { assert } } /** breaks down a spec "abbrev@1.1.1" into different parts for mocking */ diff --git a/test/fixtures/mock-oidc.js b/test/fixtures/mock-oidc.js new file mode 100644 index 0000000000000..d15d52c1b819f --- /dev/null +++ b/test/fixtures/mock-oidc.js @@ -0,0 +1,184 @@ +const ciInfo = require('ci-info') +const nock = require('nock') +const mockGlobals = require('@npmcli/mock-globals') +const { loadNpmWithRegistry } = require('./mock-npm') +const { mockProvenance } = require('@npmcli/mock-registry/lib/provenance') + +// this is an effort to not add a dependency to the cli just for testing +function makeJwt (payload) { + const header = { alg: 'none', typ: 'JWT' } + const headerB64 = Buffer.from(JSON.stringify(header)).toString('base64') + const payloadB64 = Buffer.from(JSON.stringify(payload)).toString('base64') + // empty signature section + return `${headerB64}.${payloadB64}.` +} + +function gitlabIdToken ({ visibility = 'public' } = { visibility: 'public' }) { + const now = Math.floor(Date.now() / 1000) + const payload = { + project_visibility: visibility, + iat: now, + exp: now + 3600, // 1 hour expiration + } + return makeJwt(payload) +} + +function githubIdToken ({ visibility = 'public' } = { visibility: 'public' }) { + const now = Math.floor(Date.now() / 1000) + const payload = { + repository_visibility: visibility, + iat: now, + exp: now + 3600, // 1 hour expiration + } + return makeJwt(payload) +} + +function circleciIdToken () { + const now = Math.floor(Date.now() / 1000) + const payload = { + 'oidc.circleci.com/org-id': 'c9035eb6-6eb2-4c85-8a81-d9ee6a1fa8c2', + 'oidc.circleci.com/project-id': 'ecc458d2-fbdc-4d9a-93c4-ac065ed3c3ca', + 'oidc.circleci.com/vcs-origin': 'github.com/npm/trust-publish-test', + iat: now, + exp: now + 3600, // 1 hour expiration + } + return makeJwt(payload) +} + +const mockOidc = async (t, { + oidcOptions = {}, + packageName = '@npmcli/test-package', + config = {}, + packageJson = {}, + load = {}, + mockGithubOidcOptions = false, + mockOidcTokenExchangeOptions = false, + publishOptions = {}, + provenance = false, + oidcVisibilityOptions = false, +}) => { + const github = oidcOptions.github ?? false + const gitlab = oidcOptions.gitlab ?? false + const circleci = oidcOptions.circleci ?? false + + const ACTIONS_ID_TOKEN_REQUEST_URL = oidcOptions.ACTIONS_ID_TOKEN_REQUEST_URL ?? 'https://github.com/actions/id-token' + const ACTIONS_ID_TOKEN_REQUEST_TOKEN = oidcOptions.ACTIONS_ID_TOKEN_REQUEST_TOKEN ?? 'ACTIONS_ID_TOKEN_REQUEST_TOKEN' + + mockGlobals(t, { + process: { + env: { + ACTIONS_ID_TOKEN_REQUEST_TOKEN: ACTIONS_ID_TOKEN_REQUEST_TOKEN, + ACTIONS_ID_TOKEN_REQUEST_URL: ACTIONS_ID_TOKEN_REQUEST_URL, + CI: github || gitlab || circleci ? 'true' : undefined, + ...(github ? { GITHUB_ACTIONS: 'true' } : {}), + ...(gitlab ? { GITLAB_CI: 'true' } : {}), + ...(circleci ? { CIRCLECI: 'true' } : {}), + ...(oidcOptions.NPM_ID_TOKEN ? { NPM_ID_TOKEN: oidcOptions.NPM_ID_TOKEN } : {}), + /* eslint-disable-next-line max-len */ + ...(oidcOptions.SIGSTORE_ID_TOKEN ? { SIGSTORE_ID_TOKEN: oidcOptions.SIGSTORE_ID_TOKEN } : {}), + }, + }, + }) + + const GITHUB_ACTIONS = ciInfo.GITHUB_ACTIONS + const GITLAB = ciInfo.GITLAB + const CIRCLE = ciInfo.CIRCLE + delete ciInfo.GITHUB_ACTIONS + delete ciInfo.GITLAB + delete ciInfo.CIRCLE + if (github) { + ciInfo.GITHUB_ACTIONS = 'true' + } + if (gitlab) { + ciInfo.GITLAB = 'true' + } + if (circleci) { + ciInfo.CIRCLE = 'true' + } + t.teardown(() => { + ciInfo.GITHUB_ACTIONS = GITHUB_ACTIONS + ciInfo.GITLAB = GITLAB + ciInfo.CIRCLE = CIRCLE + }) + + const { npm, registry, joinedOutput, logs } = await loadNpmWithRegistry(t, { + config: { + loglevel: 'silly', + ...config, + }, + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + ...packageJson, + }, null, 2), + }, + ...load, + }) + + if (mockGithubOidcOptions) { + const { idToken, audience, statusCode = 200 } = mockGithubOidcOptions + const url = new URL(ACTIONS_ID_TOKEN_REQUEST_URL) + nock(url.origin) + .get(url.pathname) + .query({ audience }) + .matchHeader('authorization', `Bearer ${ACTIONS_ID_TOKEN_REQUEST_TOKEN}`) + .matchHeader('accept', 'application/json') + .reply(statusCode, statusCode !== 500 ? { value: idToken } : { message: 'Internal Server Error' }) + } + + if (mockOidcTokenExchangeOptions) { + registry.mockOidcTokenExchange({ + packageName, + ...mockOidcTokenExchangeOptions, + }) + } + + if (oidcVisibilityOptions) { + registry.getVisibility({ spec: packageName, visibility: oidcVisibilityOptions }) + } + + registry.publish(packageName, publishOptions) + + /** + * this will nock / mock all the successful requirements for provenance and + * assumes when a test has "provenance true" that these calls are expected + */ + if (provenance) { + registry.getVisibility({ spec: packageName, visibility: { public: true } }) + mockProvenance(t, { + oidcURL: ACTIONS_ID_TOKEN_REQUEST_URL, + requestToken: ACTIONS_ID_TOKEN_REQUEST_TOKEN, + workflowPath: '.github/workflows/publish.yml', + repository: 'github/foo', + serverUrl: 'https://github.com', + ref: 'refs/tags/pkg@1.0.0', + sha: 'deadbeef', + runID: '123456', + runAttempt: '1', + runnerEnv: 'github-hosted', + }) + } + + return { npm, joinedOutput, logs, ACTIONS_ID_TOKEN_REQUEST_URL } +} + +const oidcPublishTest = (opts) => { + return async (t) => { + const { logsContain } = opts + const { npm, joinedOutput, logs } = await mockOidc(t, opts) + await npm.exec('publish', []) + logsContain?.forEach(item => { + t.ok(logs.includes(item), `Expected log to include: ${item}`) + }) + t.match(joinedOutput(), '+ @npmcli/test-package@1.0.0') + } +} + +module.exports = { + circleciIdToken, + gitlabIdToken, + githubIdToken, + mockOidc, + oidcPublishTest, +} diff --git a/test/fixtures/sigstore/keyless-sigstore-attestations.json b/test/fixtures/sigstore/keyless-sigstore-attestations.json new file mode 100644 index 0000000000000..f2fcb660554b9 --- /dev/null +++ b/test/fixtures/sigstore/keyless-sigstore-attestations.json @@ -0,0 +1,54 @@ +{ + "attestations": [ + { + "predicateType": "https://slsa.dev/provenance/v0.2", + "bundle": { + "mediaType": "application/vnd.dev.sigstore.bundle+json;version=0.1", + "verificationMaterial": { + "x509CertificateChain": { + "certificates": [ + { + "rawBytes": "MIIDmzCCAyGgAwIBAgIUce0wM1Ev1pqBXH9W1BbvEg9RopYwCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcNMjMwMjA5MTc1NjAwWhcNMjMwMjA5MTgwNjAwWjAAMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0SgHPgKy+HgMtXdqkkgY6Ji1v7wc+lxnnatY73cbKFwQzw+/x8288IwIz6y54dtznSXnjbzNMdNS0Q2rfMsMcaOCAkAwggI8MA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQUVVMaFO5X4Xzc/tiJCfm0WXa75QIwHwYDVR0jBBgwFoAU39Ppz1YkEZb5qNjpKFWixi4YZD8wZAYDVR0RAQH/BFowWIZWaHR0cHM6Ly9naXRodWIuY29tL3NpZ3N0b3JlL3NpZ3N0b3JlLWpzLy5naXRodWIvd29ya2Zsb3dzL3B1Ymxpc2gueW1sQHJlZnMvdGFncy92MS4wLjAwOQYKKwYBBAGDvzABAQQraHR0cHM6Ly90b2tlbi5hY3Rpb25zLmdpdGh1YnVzZXJjb250ZW50LmNvbTAVBgorBgEEAYO/MAECBAdyZWxlYXNlMDYGCisGAQQBg78wAQMEKDA2NTI4OTk3YzNjOGFiOWY4NjRmYWQ5YTM2NTg0NDZhY2E3ZmQ4NmQwFQYKKwYBBAGDvzABBAQHcHVibGlzaDAiBgorBgEEAYO/MAEFBBRzaWdzdG9yZS9zaWdzdG9yZS1qczAeBgorBgEEAYO/MAEGBBByZWZzL3RhZ3MvdjEuMC4wMIGJBgorBgEEAdZ5AgQCBHsEeQB3AHUA3T0wasbHETJjGR4cmWc3AqJKXrjePK3/h4pygC8p7o4AAAGGN1HpGQAABAMARjBEAiB/E0+AFpKimPxI/TQDXeCa06+wtpwvLhyPrbHOQYu74gIgB/9fdZD+uHvUBHyptxaGoBxdJfUKEYx9nhaZw2LeZuwwCgYIKoZIzj0EAwMDaAAwZQIxAPW070C7IM0RrAU5rMpP25TFH/rfKvbvqRNnUoPfvIlA9q7Abe8BHIl97pTmf/5vJgIwbZ4myRXGWjB0LUyzplC2GX0kklVGYeqRM5xxsxAK0zwd/U7KjoFIlp/gkyLyiMHH" + }, + { + "rawBytes": "MIICGjCCAaGgAwIBAgIUALnViVfnU0brJasmRkHrn/UnfaQwCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMjA0MTMyMDA2MTVaFw0zMTEwMDUxMzU2NThaMDcxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEeMBwGA1UEAxMVc2lnc3RvcmUtaW50ZXJtZWRpYXRlMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8RVS/ysH+NOvuDZyPIZtilgUF9NlarYpAd9HP1vBBH1U5CV77LSS7s0ZiH4nE7Hv7ptS6LvvR/STk798LVgMzLlJ4HeIfF3tHSaexLcYpSASr1kS0N/RgBJz/9jWCiXno3sweTAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU39Ppz1YkEZb5qNjpKFWixi4YZD8wHwYDVR0jBBgwFoAUWMAeX5FFpWapesyQoZMi0CrFxfowCgYIKoZIzj0EAwMDZwAwZAIwPCsQK4DYiZYDPIaDi5HFKnfxXx6ASSVmERfsynYBiX2X6SJRnZU84/9DZdnFvvxmAjBOt6QpBlc4J/0DxvkTCqpclvziL6BCCPnjdlIB3Pu3BxsPmygUY7Ii2zbdCdliiow=" + }, + { + "rawBytes": "MIIB9zCCAXygAwIBAgIUALZNAPFdxHPwjeDloDwyYChAO/4wCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMTEwMDcxMzU2NTlaFw0zMTEwMDUxMzU2NThaMCoxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjERMA8GA1UEAxMIc2lnc3RvcmUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT7XeFT4rb3PQGwS4IajtLk3/OlnpgangaBclYpsYBr5i+4ynB07ceb3LP0OIOZdxexX69c5iVuyJRQ+Hz05yi+UF3uBWAlHpiS5sh0+H2GHE7SXrk1EC5m1Tr19L9gg92jYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRYwB5fkUWlZql6zJChkyLQKsXF+jAfBgNVHSMEGDAWgBRYwB5fkUWlZql6zJChkyLQKsXF+jAKBggqhkjOPQQDAwNpADBmAjEAj1nHeXZp+13NWBNa+EDsDP8G1WWg1tCMWP/WHPqpaVo0jhsweNFZgSs0eE7wYI4qAjEA2WB9ot98sIkoF3vZYdd3/VtWB5b9TNMea7Ix/stJ5TfcLLeABLE4BNJOsQ4vnBHJ" + } + ] + }, + "tlogEntries": [ + { + "logIndex": "12988397", + "logId": { + "keyId": "wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0=" + }, + "kindVersion": { + "kind": "intoto", + "version": "0.0.2" + }, + "integratedTime": "1675965360", + "inclusionPromise": { + "signedEntryTimestamp": "MEUCID8bfktgHysxMJAIXz6CqqKHGAYPp/X6FZrS9SDtKdbcAiEAg+0zUFNPJKEVX6m33aCU+CRBgWkDNOC8oE4jHoco4kw=" + }, + "inclusionProof": null, + "canonicalizedBody": "eyJhcGlWZXJzaW9uIjoiMC4wLjIiLCJraW5kIjoiaW50b3RvIiwic3BlYyI6eyJjb250ZW50Ijp7ImVudmVsb3BlIjp7InBheWxvYWRUeXBlIjoiYXBwbGljYXRpb24vdm5kLmluLXRvdG8ranNvbiIsInNpZ25hdHVyZXMiOlt7InB1YmxpY0tleSI6IkxTMHRMUzFDUlVkSlRpQkRSVkpVU1VaSlEwRlVSUzB0TFMwdENrMUpTVVJ0ZWtORFFYbEhaMEYzU1VKQlowbFZZMlV3ZDAweFJYWXhjSEZDV0VnNVZ6RkNZblpGWnpsU2IzQlpkME5uV1VsTGIxcEplbW93UlVGM1RYY0tUbnBGVmsxQ1RVZEJNVlZGUTJoTlRXTXliRzVqTTFKMlkyMVZkVnBIVmpKTlVqUjNTRUZaUkZaUlVVUkZlRlo2WVZka2VtUkhPWGxhVXpGd1ltNVNiQXBqYlRGc1drZHNhR1JIVlhkSWFHTk9UV3BOZDAxcVFUVk5WR014VG1wQmQxZG9ZMDVOYWsxM1RXcEJOVTFVWjNkT2FrRjNWMnBCUVUxR2EzZEZkMWxJQ2t0dldrbDZhakJEUVZGWlNVdHZXa2w2YWpCRVFWRmpSRkZuUVVVd1UyZElVR2RMZVN0SVowMTBXR1J4YTJ0bldUWkthVEYyTjNkaksyeDRibTVoZEZrS056TmpZa3RHZDFGNmR5c3ZlRGd5T0RoSmQwbDZObmsxTkdSMGVtNVRXRzVxWW5wT1RXUk9VekJSTW5KbVRYTk5ZMkZQUTBGclFYZG5aMGs0VFVFMFJ3cEJNVlZrUkhkRlFpOTNVVVZCZDBsSVowUkJWRUpuVGxaSVUxVkZSRVJCUzBKblozSkNaMFZHUWxGalJFRjZRV1JDWjA1V1NGRTBSVVpuVVZWV1ZrMWhDa1pQTlZnMFdIcGpMM1JwU2tObWJUQlhXR0UzTlZGSmQwaDNXVVJXVWpCcVFrSm5kMFp2UVZVek9WQndlakZaYTBWYVlqVnhUbXB3UzBaWGFYaHBORmtLV2tRNGQxcEJXVVJXVWpCU1FWRklMMEpHYjNkWFNWcFhZVWhTTUdOSVRUWk1lVGx1WVZoU2IyUlhTWFZaTWpsMFRETk9jRm96VGpCaU0wcHNURE5PY0FwYU0wNHdZak5LYkV4WGNIcE1lVFZ1WVZoU2IyUlhTWFprTWpsNVlUSmFjMkl6WkhwTU0wSXhXVzE0Y0dNeVozVmxWekZ6VVVoS2JGcHVUWFprUjBadUNtTjVPVEpOVXpSM1RHcEJkMDlSV1V0TGQxbENRa0ZIUkhaNlFVSkJVVkZ5WVVoU01HTklUVFpNZVRrd1lqSjBiR0pwTldoWk0xSndZakkxZWt4dFpIQUtaRWRvTVZsdVZucGFXRXBxWWpJMU1GcFhOVEJNYlU1MllsUkJWa0puYjNKQ1owVkZRVmxQTDAxQlJVTkNRV1I1V2xkNGJGbFlUbXhOUkZsSFEybHpSd3BCVVZGQ1p6YzRkMEZSVFVWTFJFRXlUbFJKTkU5VWF6TlplazVxVDBkR2FVOVhXVFJPYWxKdFdWZFJOVmxVVFRKT1ZHY3dUa1JhYUZreVJUTmFiVkUwQ2s1dFVYZEdVVmxMUzNkWlFrSkJSMFIyZWtGQ1FrRlJTR05JVm1saVIyeDZZVVJCYVVKbmIzSkNaMFZGUVZsUEwwMUJSVVpDUWxKNllWZGtlbVJIT1hrS1dsTTVlbUZYWkhwa1J6bDVXbE14Y1dONlFXVkNaMjl5UW1kRlJVRlpUeTlOUVVWSFFrSkNlVnBYV25wTU0xSm9Xak5OZG1ScVJYVk5RelIzVFVsSFNncENaMjl5UW1kRlJVRmtXalZCWjFGRFFraHpSV1ZSUWpOQlNGVkJNMVF3ZDJGellraEZWRXBxUjFJMFkyMVhZek5CY1VwTFdISnFaVkJMTXk5b05IQjVDbWRET0hBM2J6UkJRVUZIUjA0eFNIQkhVVUZCUWtGTlFWSnFRa1ZCYVVJdlJUQXJRVVp3UzJsdFVIaEpMMVJSUkZobFEyRXdOaXQzZEhCM2RreG9lVkFLY21KSVQxRlpkVGMwWjBsblFpODVabVJhUkN0MVNIWlZRa2g1Y0hSNFlVZHZRbmhrU21aVlMwVlplRGx1YUdGYWR6Sk1aVnAxZDNkRFoxbEpTMjlhU1FwNmFqQkZRWGROUkdGQlFYZGFVVWw0UVZCWE1EY3dRemRKVFRCU2NrRlZOWEpOY0ZBeU5WUkdTQzl5Wmt0MlluWnhVazV1Vlc5UVpuWkpiRUU1Y1RkQkNtSmxPRUpJU1d3NU4zQlViV1l2TlhaS1owbDNZbG8wYlhsU1dFZFhha0l3VEZWNWVuQnNRekpIV0RCcmEyeFdSMWxsY1ZKTk5YaDRjM2hCU3pCNmQyUUtMMVUzUzJwdlJrbHNjQzluYTNsTWVXbE5TRWdLTFMwdExTMUZUa1FnUTBWU1ZFbEdTVU5CVkVVdExTMHRMUW89Iiwic2lnIjoiVFVWWlEwbFJSREV3YTBGdU0yeERMekZ5U25aWVFuUlRSR05yWW5GclMwVnRlak0yT1dkUVJFdGlOR3hITkhwTlMxRkphRUZRTVN0U2FHSk5ZMEZUYzJaWWFIaHdXRXRPUTBGcVNtSXJNMEYyTTBKeU9UVmxTMFEzVmt3dlFrVkMifV19LCJoYXNoIjp7ImFsZ29yaXRobSI6InNoYTI1NiIsInZhbHVlIjoiNjI2OWQzNzQ2MzI0MjM5YzEzOGJkZTMzMDEzMTVlY2FkNmI4ZGM5YzcwY2RlYTBhODEyYjYzYTUzOGJmYzdlYyJ9LCJwYXlsb2FkSGFzaCI6eyJhbGdvcml0aG0iOiJzaGEyNTYiLCJ2YWx1ZSI6Ijg0NWU5MTRlYmJhZTBkNmZmY2FlMmFmYjc3YzdkZWY0NzkzMDVjOWVlMzExMDE0MDJmZTQ3NWU2ZDIzZjExYzkifX19fQ==" + } + ], + "timestampVerificationData": null + }, + "dsseEnvelope": { + "payload": "eyJfdHlwZSI6Imh0dHBzOi8vaW4tdG90by5pby9TdGF0ZW1lbnQvdjAuMSIsInN1YmplY3QiOlt7Im5hbWUiOiJwa2c6bnBtL3NpZ3N0b3JlQDEuMC4wIiwiZGlnZXN0Ijp7InNoYTUxMiI6IjdiZWE5ZjZlN2ZmMzdmNWZhYjBiMzZiZjA2MTIwMGZmZjAzMDk5ZmQyZmQ2OTZiOTFkMDRiYzVlNGYyMjVlYjlmZDZlMGNhZGNhZDU0YmE5ODBmNDNmYjM1MmE5OWU4ODEwYjRlMGFiZWI1YzBlZjJjZjkxMDhjZDFmMjU4YjM2In19XSwicHJlZGljYXRlVHlwZSI6Imh0dHBzOi8vc2xzYS5kZXYvcHJvdmVuYW5jZS92MC4yIiwicHJlZGljYXRlIjp7ImJ1aWxkVHlwZSI6Imh0dHBzOi8vZ2l0aHViLmNvbS9ucG0vY2xpL2doYUB2MCIsImJ1aWxkZXIiOnsiaWQiOiJodHRwczovL2dpdGh1Yi5jb20vbnBtL2NsaUA5LjQuMiJ9LCJpbnZvY2F0aW9uIjp7ImNvbmZpZ1NvdXJjZSI6eyJ1cmkiOiJnaXQraHR0cHM6Ly9naXRodWIuY29tL3NpZ3N0b3JlL3NpZ3N0b3JlLWpzQHJlZnMvdGFncy92MS4wLjAiLCJkaWdlc3QiOnsic2hhMSI6IjA2NTI4OTk3YzNjOGFiOWY4NjRmYWQ5YTM2NTg0NDZhY2E3ZmQ4NmQifSwiZW50cnlQb2ludCI6InNpZ3N0b3JlL3NpZ3N0b3JlLWpzLy5naXRodWIvd29ya2Zsb3dzL3B1Ymxpc2gueW1sQHJlZnMvdGFncy92MS4wLjAifSwicGFyYW1ldGVycyI6e30sImVudmlyb25tZW50Ijp7IkdJVEhVQl9BQ1RPUl9JRCI6IjM5ODAyNyIsIkdJVEhVQl9FVkVOVF9OQU1FIjoicmVsZWFzZSIsIkdJVEhVQl9SRUYiOiJyZWZzL3RhZ3MvdjEuMC4wIiwiR0lUSFVCX1JFRl9UWVBFIjoidGFnIiwiR0lUSFVCX1JFUE9TSVRPUlkiOiJzaWdzdG9yZS9zaWdzdG9yZS1qcyIsIkdJVEhVQl9SRVBPU0lUT1JZX0lEIjoiNDk1NTc0NTU1IiwiR0lUSFVCX1JFUE9TSVRPUllfT1dORVJfSUQiOiI3MTA5NjM1MyIsIkdJVEhVQl9SVU5fQVRURU1QVCI6IjEiLCJHSVRIVUJfUlVOX0lEIjoiNDEzNzAyODgxNiIsIkdJVEhVQl9SVU5fTlVNQkVSIjoiOSIsIkdJVEhVQl9TSEEiOiIwNjUyODk5N2MzYzhhYjlmODY0ZmFkOWEzNjU4NDQ2YWNhN2ZkODZkIiwiR0lUSFVCX1dPUktGTE9XX1JFRiI6InNpZ3N0b3JlL3NpZ3N0b3JlLWpzLy5naXRodWIvd29ya2Zsb3dzL3B1Ymxpc2gueW1sQHJlZnMvdGFncy92MS4wLjAiLCJHSVRIVUJfV09SS0ZMT1dfU0hBIjoiMDY1Mjg5OTdjM2M4YWI5Zjg2NGZhZDlhMzY1ODQ0NmFjYTdmZDg2ZCJ9fSwibWV0YWRhdGEiOnsiYnVpbGRJbnZvY2F0aW9uSWQiOiI0MTM3MDI4ODE2LTEiLCJjb21wbGV0ZW5lc3MiOnsicGFyYW1ldGVycyI6ZmFsc2UsImVudmlyb25tZW50IjpmYWxzZSwibWF0ZXJpYWxzIjpmYWxzZX0sInJlcHJvZHVjaWJsZSI6ZmFsc2V9LCJtYXRlcmlhbHMiOlt7InVyaSI6ImdpdCtodHRwczovL2dpdGh1Yi5jb20vc2lnc3RvcmUvc2lnc3RvcmUtanMiLCJkaWdlc3QiOnsic2hhMSI6IjA2NTI4OTk3YzNjOGFiOWY4NjRmYWQ5YTM2NTg0NDZhY2E3ZmQ4NmQifX1dfX0=", + "payloadType": "application/vnd.in-toto+json", + "signatures": [ + { + "sig": "MEYCIQD10kAn3lC/1rJvXBtSDckbqkKEmz369gPDKb4lG4zMKQIhAP1+RhbMcASsfXhxpXKNCAjJb+3Av3Br95eKD7VL/BEB", + "keyid": "" + } + ] + } + } + } + ] +} diff --git a/test/lib/base-cmd.js b/test/lib/base-cmd.js new file mode 100644 index 0000000000000..58573f9594cd4 --- /dev/null +++ b/test/lib/base-cmd.js @@ -0,0 +1,861 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../fixtures/mock-npm') +const BaseCommand = require('../../lib/base-cmd.js') +const Definition = require('@npmcli/config/lib/definitions/definition.js') + +t.test('flags() method with command definitions', async t => { + const { npm } = await loadMockNpm(t, { + config: { + mountain: 'kilimanjaro', + }, + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static params = ['mountain'] + + static definitions = [ + new Definition('mountain', { + type: String, + default: 'everest', + description: 'Your favorite mountain', + usage: '--mountain=', + }), + ] + + async exec () { + return this.flags() + } + } + + const command = new TestCommand(npm) + const [flags] = await command.exec() + + t.ok(flags, 'flags() returns an object') + t.equal(flags.mountain, 'kilimanjaro', 'includes config value when set') +}) + +t.test('flags() method with default values', async t => { + const { npm } = await loadMockNpm(t) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static params = ['mountain'] + + static definitions = [ + new Definition('mountain', { + type: String, + default: 'everest', + description: 'Your favorite mountain', + usage: '--mountain=', + }), + ] + + async exec () { + return this.flags() + } + } + + const command = new TestCommand(npm) + const [flags] = await command.exec() + + t.equal(flags.mountain, 'everest', 'uses default value when not set') +}) + +t.test('flags() method filters unknown options', async t => { + const { npm } = await loadMockNpm(t, { + // npm.config.argv would have both known and unknown flags parsed + config: { + mountain: 'denali', + }, + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static params = ['mountain'] + + static definitions = [ + new Definition('mountain', { + type: String, + default: 'everest', + description: 'Your favorite mountain', + usage: '--mountain=', + }), + ] + + async exec () { + return this.flags() + } + } + + const command = new TestCommand(npm) + const [flags] = await command.exec() + + t.equal(flags.mountain, 'denali', 'includes known flag') + t.notOk(flags.bug, 'filters out unknown flags') + t.same(Object.keys(flags), ['mountain'], 'only includes defined keys') +}) + +t.test('flags() method with no definitions', async t => { + const { npm } = await loadMockNpm(t) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + + async exec () { + return this.flags() + } + } + + const command = new TestCommand(npm) + const [flags] = await command.exec() + + t.same(flags, {}, 'returns empty object when no definitions') +}) + +t.test('flags() throws error for unknown flags', async t => { + const { npm } = await loadMockNpm(t, { + npm: { argv: ['test-command', '--unknown-flag'] }, + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static params = ['mountain'] + + static definitions = [ + new Definition('mountain', { + type: String, + default: 'everest', + description: 'Your favorite mountain', + usage: '--mountain=', + }), + ] + + async exec () { + return this.flags() + } + } + + const command = new TestCommand(npm) + await t.rejects( + command.exec(), + { + code: 'EUNKNOWNCONFIG', + message: /Unknown cli config:[\s\S]*--unknown-flag/, + }, + 'throws EUNKNOWNCONFIG for unknown flag' + ) +}) + +t.test('flags() maps alias to main key', async t => { + const { npm } = await loadMockNpm(t) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static params = ['mountain'] + + static definitions = [ + new Definition('mountain', { + type: String, + default: 'everest', + description: 'Your favorite mountain', + usage: '--mountain=', + alias: ['peak'], + }), + ] + + async exec () { + return this.flags() + } + } + + // Use the alias --peak instead of --mountain + npm.config.argv = ['node', 'npm', 'test-command', '--peak=denali'] + + const command = new TestCommand(npm) + const [flags] = await command.exec() + + t.equal(flags.mountain, 'denali', 'alias value is mapped to main key') + t.notOk('peak' in flags, 'alias key is not present in flags') +}) + +t.test('flags() throws error when both main key and alias are provided', async t => { + const { npm } = await loadMockNpm(t) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static params = ['mountain'] + + static definitions = [ + new Definition('mountain', { + type: String, + default: 'everest', + description: 'Your favorite mountain', + usage: '--mountain=', + alias: ['peak'], + }), + ] + + async exec () { + return this.flags() + } + } + + // Provide both --mountain and --peak (its alias) + npm.config.argv = ['node', 'npm', 'test-command', '--mountain=everest', '--peak=denali'] + + const command = new TestCommand(npm) + await t.rejects( + command.exec(), + { message: /Please provide only one of --mountain or --peak/ }, + 'throws error when main key and alias are both provided' + ) +}) + +t.test('getUsage() with no params and no definitions', async t => { + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command description' + static usage = [''] + } + + const usage = TestCommand.describeUsage + + t.ok(usage.includes('Test command description'), 'includes description') + t.ok(usage.includes('npm test-command'), 'includes usage line') + t.notOk(usage.includes('Options:'), 'does not include Options section') +}) + +t.test('getUsage() with both params and definitions', async t => { + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command description' + static params = ['mountain', 'river'] + + static definitions = [ + new Definition('mountain', { + type: String, + default: 'everest', + description: 'Your favorite mountain', + usage: '--mountain=', + }), + new Definition('river', { + type: String, + default: 'nile', + description: 'Your favorite river', + usage: '--river=', + }), + ] + } + + const usage = TestCommand.describeUsage + + t.ok(usage.includes('Test command description'), 'includes description') + t.ok(usage.includes('Options:'), 'includes Options section') + t.ok(usage.includes('--mountain'), 'includes mountain flag') + t.ok(usage.includes('--river'), 'includes river flag') +}) + +t.test('getUsage() with subcommand without description', async t => { + class SubCommandWithDesc extends BaseCommand { + static name = 'with-desc' + static description = 'Subcommand with description' + } + + class SubCommandNoDesc extends BaseCommand { + static name = 'no-desc' + // No description + } + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command description' + static subcommands = { + 'with-desc': SubCommandWithDesc, + 'no-desc': SubCommandNoDesc, + } + } + + const usage = TestCommand.describeUsage + + t.ok(usage.includes('Subcommands:'), 'includes Subcommands section') + t.ok(usage.includes('with-desc'), 'includes subcommand with description') + t.ok(usage.includes('Subcommand with description'), 'includes the description text') + t.ok(usage.includes('no-desc'), 'includes subcommand without description') +}) + +t.test('getUsage() with definition without description', async t => { + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command description' + static params = ['mountain', 'river'] + + static definitions = [ + new Definition('mountain', { + type: String, + default: 'everest', + description: 'Your favorite mountain', + usage: '--mountain=', + }), + new Definition('river', { + type: String, + default: 'nile', + description: '', // Empty description + usage: '--river=', + }), + ] + } + + const usage = TestCommand.describeUsage + + t.ok(usage.includes('Options:'), 'includes Options section') + t.ok(usage.includes('--mountain'), 'includes mountain flag in options') + t.ok(usage.includes('Your favorite mountain'), 'includes mountain description') + t.ok(usage.includes('[--river=]'), 'includes river in usage line') + t.notOk(usage.includes(' --river'), 'does not include river flag description section') +}) + +t.test('flags() handles definition with multiple aliases', async t => { + const { npm } = await loadMockNpm(t) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + + static definitions = [ + new Definition('mountain', { + type: String, + default: 'everest', + description: 'Your favorite mountain', + usage: '--mountain=', + alias: ['peak', 'summit'], // Multiple aliases + }), + ] + + async exec () { + return this.flags() + } + } + + // Use the second alias --summit + npm.config.argv = ['node', 'npm', 'test-command', '--summit=denali'] + + const command = new TestCommand(npm) + const [flags] = await command.exec() + + t.equal(flags.mountain, 'denali', 'second alias value is mapped to main key') + t.notOk('summit' in flags, 'alias key is not present in flags') + t.notOk('peak' in flags, 'other alias key is not present in flags') +}) + +t.test('flags() handles definition with short as array', async t => { + const { npm } = await loadMockNpm(t) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + + static definitions = [ + new Definition('mountain', { + type: String, + default: 'everest', + description: 'Your favorite mountain', + usage: '--mountain=', + short: ['m', 'M'], // Short as array + }), + ] + + async exec () { + return this.flags() + } + } + + // Use the short flag -m + npm.config.argv = ['node', 'npm', 'test-command', '-m', 'denali'] + + const command = new TestCommand(npm) + const [flags] = await command.exec() + + t.equal(flags.mountain, 'denali', 'short flag value is parsed correctly') +}) + +t.test('flags() returns defaults when argv is empty', async t => { + const { npm } = await loadMockNpm(t) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + + static definitions = [ + new Definition('mountain', { + type: String, + default: 'everest', + description: 'Your favorite mountain', + usage: '--mountain=', + }), + ] + + async exec () { + return this.flags() + } + } + + // Set argv to empty array + npm.config.argv = [] + + const command = new TestCommand(npm) + const [flags, remains] = await command.exec() + + t.equal(flags.mountain, 'everest', 'returns default value when argv is empty') + t.same(remains, [], 'remains is empty array') +}) + +t.test('flags() throws error for multiple unknown flags with pluralization', async t => { + const { npm } = await loadMockNpm(t, { + npm: { argv: ['test-command', '--unknown-one', '--unknown-two'] }, + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + + static definitions = [ + new Definition('mountain', { + type: String, + default: 'everest', + description: 'Your favorite mountain', + usage: '--mountain=', + }), + ] + + async exec () { + return this.flags() + } + } + + // Provide multiple unknown flags + npm.config.argv = ['node', 'npm', 'test-command', '--unknown-one', '--unknown-two'] + + const command = new TestCommand(npm) + await t.rejects( + command.exec(), + { + code: 'EUNKNOWNCONFIG', + message: /Unknown cli configs:[\s\S]*--unknown-one[\s\S]*--unknown-two/, + }, + 'throws EUNKNOWNCONFIG with pluralized "configs" for multiple unknown flags' + ) +}) + +t.test('base exec() method returns undefined', async t => { + const { npm } = await loadMockNpm(t) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + // Intentionally not overriding exec() to test the base implementation + } + + const command = new TestCommand(npm) + const result = await command.exec() + + t.equal(result, undefined, 'base exec() returns undefined') +}) + +t.test('flags() removes unknown positional warning when value is consumed by command definition', async t => { + // Pass raw argv to loadMockNpm so warnings are generated during config.load() + // The global config sees --id as unknown (boolean), so "abc123" becomes a positional + // and queues a warning. But command-specific definitions should consume it. + const { npm, logs } = await loadMockNpm(t, { + argv: ['--id', 'abc123'], + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static params = ['id'] + + static definitions = [ + new Definition('id', { + type: String, + default: null, + description: 'An identifier', + usage: '--id=', + }), + ] + + async exec () { + return this.flags() + } + } + + // Set up argv for command execution (mock-npm prepends the command) + npm.config.argv = ['node', 'npm', 'test-command', '--id', 'abc123'] + + const command = new TestCommand(npm) + const [flags, remains] = await command.exec() + + // The flag should be properly parsed + t.equal(flags.id, 'abc123', 'id flag is properly parsed') + t.same(remains, [], 'no remaining positionals') + + // Check that no warning about "abc123" being parsed as positional was logged + const warningLogs = logs.warn + const positionalWarnings = warningLogs.filter(msg => + msg.includes('abc123') && msg.includes('parsed as a normal command line argument') + ) + t.equal(positionalWarnings.length, 0, 'no warning about abc123 being a positional') +}) + +t.test('flags() keeps unknown positional warning when multiple values follow unknown flag', async t => { + // Pass raw argv to loadMockNpm so warnings are generated during config.load() + // Both "abc123" and "def456" are seen as positionals by global config because --id is unknown + // nopt only warns about "abc123" (the immediate next value after unknown flag) + // Command definition consumes "abc123" for --id, "def456" remains as true positional + const { npm, logs } = await loadMockNpm(t, { + argv: ['--id', 'abc123', 'def456'], + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static params = ['id'] + + static definitions = [ + new Definition('id', { + type: String, + default: null, + description: 'An identifier', + usage: '--id=', + }), + ] + + async exec () { + return this.flags() + } + } + + // Set up argv for command execution + npm.config.argv = ['node', 'npm', 'test-command', '--id', 'abc123', 'def456'] + + const command = new TestCommand(npm) + const [flags, remains] = await command.exec() + + // The flag should be properly parsed + t.equal(flags.id, 'abc123', 'id flag is properly parsed') + t.same(remains, ['def456'], 'def456 remains as positional') + + // Check that warning about "abc123" was removed (consumed by --id) + const warningLogs = logs.warn + const abc123Warnings = warningLogs.filter(msg => + msg.includes('abc123') && msg.includes('parsed as a normal command line argument') + ) + t.equal(abc123Warnings.length, 0, 'no warning about abc123 (consumed by --id)') +}) + +t.test('flags() does not remove unknown positional warning when value is in remains', async t => { + // This tests the else branch where remainsSet.has(unknownPos) is true + // When a value is a true positional (in remains), we should NOT remove its warning + // The warning should be logged (not suppressed) + const { npm, logs } = await loadMockNpm(t, { + argv: ['truepositional'], + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static params = ['id'] + + static definitions = [ + new Definition('id', { + type: String, + default: null, + description: 'An identifier', + usage: '--id=', + }), + ] + + async exec () { + return this.flags() + } + } + + // Manually queue a warning for a value that will be in remains + npm.config.queueWarning('unknown:truepositional', 'config', 'truepositional was parsed as positional') + + // Set up argv for command execution with the value as a true positional + npm.config.argv = ['node', 'npm', 'test-command', 'truepositional'] + + const command = new TestCommand(npm) + const [flags, remains] = await command.exec() + + // The positional should remain + t.same(remains, ['truepositional'], 'truepositional is in remains') + t.equal(flags.id, null, 'id flag uses default') + + // Check that the warning WAS logged (not removed before logWarnings()) + // Because the value is in remains, it's a true positional and should warn + const warningLogs = logs.warn + const positionalWarnings = warningLogs.filter(msg => + msg.includes('truepositional') && msg.includes('parsed as positional') + ) + t.equal(positionalWarnings.length, 1, 'warning for truepositional was logged') +}) + +t.test('flags() throws error for extra positional arguments beyond expected count', async t => { + // When a command specifies static positionals = N, extra positionals should throw an error + const { npm } = await loadMockNpm(t, { + argv: ['pkg1', 'extra1', 'extra2'], + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static positionals = 1 // expects only 1 positional + static params = ['id'] + + static definitions = [ + new Definition('id', { + type: String, + default: null, + description: 'An identifier', + usage: '--id=', + }), + ] + + async exec () { + return this.flags() + } + } + + // Set up argv for command execution with multiple positionals + npm.config.argv = ['node', 'npm', 'test-command', 'pkg1', 'extra1', 'extra2'] + + const command = new TestCommand(npm) + + // Should throw error for extra positional + await t.rejects( + command.exec(), + { message: 'Unknown positional arguments: extra1, extra2' }, + 'throws error for extra positionals' + ) +}) + +t.test('flags() does not throw when positionals is null (unlimited)', async t => { + // When static positionals is null, any number of positionals is allowed without error + const { npm } = await loadMockNpm(t, { + argv: ['pkg1', 'extra1', 'extra2'], + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static positionals = null // unlimited/unchecked + static params = ['id'] + + static definitions = [ + new Definition('id', { + type: String, + default: null, + description: 'An identifier', + usage: '--id=', + }), + ] + + async exec () { + return this.flags() + } + } + + // Set up argv for command execution with multiple positionals + npm.config.argv = ['node', 'npm', 'test-command', 'pkg1', 'extra1', 'extra2'] + + const command = new TestCommand(npm) + const [flags, remains] = await command.exec() + + // All positionals should remain - no error thrown + t.same(remains, ['pkg1', 'extra1', 'extra2'], 'all positionals are in remains') + t.equal(flags.id, null, 'id flag uses default') +}) + +t.test('validateCli throws aggregated error for unknown file configs', async t => { + const { npm } = await loadMockNpm(t, { + homeDir: { + '.npmrc': [ + 'bogus-user-key=yes', + '@scope:bogus-scoped=no', + ].join('\n'), + }, + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + } + + const command = new TestCommand(npm) + await t.rejects( + (async () => command.validateCli())(), + { + code: 'EUNKNOWNCONFIG', + message: /Unknown npm configuration keys:[\s\S]*bogus-user-key[\s\S]*bogus-scoped[\s\S]*npm help npmrc/, + }, + 'throws EUNKNOWNCONFIG aggregating plain and scoped keys' + ) +}) + +t.test('validateCli uses singular "key" when only one unknown file config', async t => { + const { npm } = await loadMockNpm(t, { + homeDir: { + '.npmrc': 'only-one-bad-key=yes', + }, + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + } + + const command = new TestCommand(npm) + await t.rejects( + (async () => command.validateCli())(), + { + code: 'EUNKNOWNCONFIG', + message: /Unknown npm configuration key:\n/, + }, + 'singular phrasing when only one unknown key' + ) +}) + +t.test('validateCli bypasses checks when skipConfigValidation is set', async t => { + const { npm } = await loadMockNpm(t, { + homeDir: { + '.npmrc': 'bogus-user-key=yes', + }, + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static skipConfigValidation = true + } + + const command = new TestCommand(npm) + t.doesNotThrow(() => command.validateCli(), 'skipConfigValidation bypasses unknown-file-config check') +}) + +t.test('validateCli combines cli and file unknowns into a single error', async t => { + const { npm } = await loadMockNpm(t, { + homeDir: { + '.npmrc': 'bogus-user-key=yes', + }, + npm: { argv: ['test-command', '--unknown-cli'] }, + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + async exec () { + return this.flags() + } + } + + const command = new TestCommand(npm) + let err + try { + command.validateCli() + t.fail('expected throw') + } catch (e) { + err = e + } + t.equal(err.code, 'EUNKNOWNCONFIG') + t.match(err.message, /Unknown cli config:[\s\S]*--unknown-cli/, + 'message contains the cli section') + t.match(err.message, /Unknown npm configuration key:[\s\S]*bogus-user-key/, + 'message contains the file section') + t.match(err.unknownConfigs, [ + { where: 'cli', key: 'unknown-cli' }, + { where: 'user', key: 'bogus-user-key' }, + ], 'structured payload contains both cli and file entries') +}) + +t.test('validateCli does not throw on unknown env (npm_config_*) configs', async t => { + // Env unknowns warn but never error — they are excluded from getUnknownConfigs() by default. + // This test locks in the carve-out at the validateCli boundary so the env→warn behavior cannot silently flip if the filter changes. + const { npm } = await loadMockNpm(t, { + globals: { + 'process.env.npm_config_bogus_env': 'yes', + }, + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + } + + const command = new TestCommand(npm) + t.doesNotThrow(() => command.validateCli(), + 'unknown env-set config does not throw at validateCli') + // sanity: the unknown was in fact seen by Config, just filtered from getUnknownConfigs() + t.ok( + npm.config.getUnknownConfigs('env').some(u => u.key === 'bogus-env'), + 'env unknown is still tracked internally' + ) +}) + +t.test('flags() throws with scoped (nerfdart) display for unknown cli config', async t => { + const { npm } = await loadMockNpm(t, { + argv: ['--@scope:bogus=yes'], + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + + async exec () { + return this.flags() + } + } + + npm.config.argv = ['node', 'npm', 'test-command', '--@scope:bogus=yes'] + const command = new TestCommand(npm) + await t.rejects( + command.exec(), + { + code: 'EUNKNOWNCONFIG', + message: /Unknown cli config:[\s\S]*--bogus \(@scope:bogus\)/, + }, + 'scoped display form uses baseKey (key) layout, throws EUNKNOWNCONFIG' + ) +}) + +t.test('flags() throws singular "argument" for a single extra positional', async t => { + const { npm } = await loadMockNpm(t, { + argv: ['pkg1', 'extra1'], + }) + + class TestCommand extends BaseCommand { + static name = 'test-command' + static description = 'Test command' + static positionals = 1 + + async exec () { + return this.flags() + } + } + + npm.config.argv = ['node', 'npm', 'test-command', 'pkg1', 'extra1'] + const command = new TestCommand(npm) + await t.rejects( + command.exec(), + { message: 'Unknown positional argument: extra1' }, + 'singular phrasing when only one extra positional' + ) +}) diff --git a/test/lib/cli/entry.js b/test/lib/cli/entry.js index 900e3ab794317..369927dace0f2 100644 --- a/test/lib/cli/entry.js +++ b/test/lib/cli/entry.js @@ -35,16 +35,16 @@ const cliMock = async (t, opts) => { } } -t.test('print the version, and treat npm_g as npm -g', async t => { +t.test('print the version ', async t => { const { logs, cli, Npm, outputs, exitHandlerCalled } = await cliMock(t, { - globals: { 'process.argv': ['node', 'npm_g', 'root'] }, + globals: { 'process.argv': ['node', 'npm', 'root'] }, }) await cli(process) - t.strictSame(process.argv, ['node', 'npm', '-g', 'root'], 'system process.argv was rewritten') + t.strictSame(process.argv, ['node', 'npm', 'root'], 'system process.argv was rewritten') t.strictSame(logs.verbose.byTitle('cli'), ['cli node npm']) t.strictSame(logs.verbose.byTitle('title'), ['title npm root']) - t.match(logs.verbose.byTitle('argv'), ['argv "--global" "root"']) + t.match(logs.verbose.byTitle('argv'), ['argv "root"']) t.strictSame(logs.info, [`using npm@${Npm.version}`, `using node@${process.version}`]) t.equal(outputs.length, 1) t.match(outputs[0], dirname(process.cwd())) diff --git a/test/lib/cli/exit-handler.js b/test/lib/cli/exit-handler.js index 939c9617aff56..0deae15428ff5 100644 --- a/test/lib/cli/exit-handler.js +++ b/test/lib/cli/exit-handler.js @@ -46,7 +46,6 @@ t.cleanSnapshot = (path) => cleanDate(cleanCwd(path)) mockGlobals(t, { process: Object.assign(new EventEmitter(), { // these are process properties that are needed in the running code and tests - // eslint-disable-next-line max-len ...pick(process, 'version', 'execPath', 'stdout', 'stderr', 'stdin', 'cwd', 'chdir', 'env', 'umask'), pid: 123456, argv: ['/node', ...process.argv.slice(1)], @@ -126,7 +125,7 @@ const mockExitHandler = async (t, { ...errors, ], npm, - // Make it async to make testing ergonomics a little easier so we dont need + // Make it async to make testing ergonomics a little easier so we don't need // to t.plan() every test to make sure we get process.exit called. exitHandler: (argErr) => new Promise(res => { process.once('exit', res) @@ -297,6 +296,35 @@ t.test('merges output buffers errors with --json', async (t) => { ) }) +t.test('json output includes authUrl and doneUrl for webauth EOTP errors', async (t) => { + const { exitHandler, outputs } = await mockExitHandler(t, { + config: { json: true }, + error: Object.assign(new Error('one-time pass required'), { + code: 'EOTP', + body: { + authUrl: 'https://registry.npmjs.org/-/auth/login/abc123', + doneUrl: 'https://registry.npmjs.org/-/auth/done/abc123', + }, + }), + }) + + await exitHandler() + + t.equal(process.exitCode, 1) + const jsonOutput = JSON.parse(outputs[0]) + t.same(jsonOutput.error, { + code: 'EOTP', + summary: 'This operation requires a one-time password.', + detail: 'Open this URL in your browser to authenticate:\n' + + ' https://registry.npmjs.org/-/auth/login/abc123\n' + + '\n' + + 'After authenticating, your token can be retrieved from:\n' + + ' https://registry.npmjs.org/-/auth/done/abc123', + authUrl: 'https://registry.npmjs.org/-/auth/login/abc123', + doneUrl: 'https://registry.npmjs.org/-/auth/done/abc123', + }) +}) + t.test('output buffer without json', async (t) => { const { exitHandler, outputs, logs } = await mockExitHandler(t, { error: err('Error: EBADTHING Something happened'), diff --git a/test/lib/cli/update-notifier.js b/test/lib/cli/update-notifier.js index 929e088bd4fa5..023a44294622e 100644 --- a/test/lib/cli/update-notifier.js +++ b/test/lib/cli/update-notifier.js @@ -2,21 +2,59 @@ const t = require('tap') const { basename } = require('node:path') const tmock = require('../../fixtures/tmock') const mockNpm = require('../../fixtures/mock-npm') +const MockRegistry = require('@npmcli/mock-registry') +const mockGlobals = require('@npmcli/mock-globals') const CURRENT_VERSION = '123.420.69' const CURRENT_MAJOR = '122.420.69' const CURRENT_MINOR = '123.419.69' const CURRENT_PATCH = '123.420.68' const NEXT_VERSION = '123.421.70' +const NEXT_VERSION_ENGINE_COMPATIBLE = '123.421.60' +const NEXT_VERSION_ENGINE_COMPATIBLE_MINOR = `123.420.70` +const NEXT_VERSION_ENGINE_COMPATIBLE_PATCH = `123.421.58` const NEXT_MINOR = '123.420.70' const NEXT_PATCH = '123.421.69' const CURRENT_BETA = '124.0.0-beta.99999' const HAVE_BETA = '124.0.0-beta.0' +const packumentResponse = { + _id: 'npm', + name: 'npm', + 'dist-tags': { + latest: CURRENT_VERSION, + }, + access: 'public', + versions: { + [CURRENT_VERSION]: { version: CURRENT_VERSION, engines: { node: '>1' } }, + [CURRENT_MAJOR]: { version: CURRENT_MAJOR, engines: { node: '>1' } }, + [CURRENT_MINOR]: { version: CURRENT_MINOR, engines: { node: '>1' } }, + [CURRENT_PATCH]: { version: CURRENT_PATCH, engines: { node: '>1' } }, + [NEXT_VERSION]: { version: NEXT_VERSION, engines: { node: '>1' } }, + [NEXT_MINOR]: { version: NEXT_MINOR, engines: { node: '>1' } }, + [NEXT_PATCH]: { version: NEXT_PATCH, engines: { node: '>1' } }, + [CURRENT_BETA]: { version: CURRENT_BETA, engines: { node: '>1' } }, + [HAVE_BETA]: { version: HAVE_BETA, engines: { node: '>1' } }, + [NEXT_VERSION_ENGINE_COMPATIBLE]: { + version: NEXT_VERSION_ENGINE_COMPATIBLE, + engines: { node: '<=1' }, + }, + [NEXT_VERSION_ENGINE_COMPATIBLE_MINOR]: { + version: NEXT_VERSION_ENGINE_COMPATIBLE_MINOR, + engines: { node: '<=1' }, + }, + [NEXT_VERSION_ENGINE_COMPATIBLE_PATCH]: { + version: NEXT_VERSION_ENGINE_COMPATIBLE_PATCH, + engines: { node: '<=1' }, + }, + }, +} + const runUpdateNotifier = async (t, { STAT_ERROR, WRITE_ERROR, PACOTE_ERROR, + PACOTE_MOCK_REQ_COUNT = 1, STAT_MTIME = 0, mocks: _mocks = {}, command = 'help', @@ -30,7 +68,7 @@ const runUpdateNotifier = async (t, { ...require('node:fs/promises'), stat: async (path) => { if (basename(path) !== '_update-notifier-last-checked') { - t.fail('no stat allowed for non upate notifier files') + t.fail('no stat allowed for non update notifier files') } if (STAT_ERROR) { throw STAT_ERROR @@ -43,7 +81,7 @@ const runUpdateNotifier = async (t, { t.fail('no write file content allowed') } if (basename(path) !== '_update-notifier-last-checked') { - t.fail('no writefile allowed for non upate notifier files') + t.fail('no writefile allowed for non update notifier files') } if (WRITE_ERROR) { throw WRITE_ERROR @@ -51,24 +89,7 @@ const runUpdateNotifier = async (t, { }, } - const MANIFEST_REQUEST = [] - const mockPacote = { - manifest: async (spec) => { - if (!spec.match(/^npm@/)) { - t.fail('no pacote manifest allowed for non npm packages') - } - MANIFEST_REQUEST.push(spec) - if (PACOTE_ERROR) { - throw PACOTE_ERROR - } - const manifestV = spec === 'npm@latest' ? CURRENT_VERSION - : /-/.test(spec) ? CURRENT_BETA : NEXT_VERSION - return { version: manifestV } - }, - } - const mocks = { - pacote: mockPacote, 'node:fs/promises': mockFs, '{ROOT}/package.json': { version }, 'ci-info': { isCI: false, name: null }, @@ -83,6 +104,15 @@ const runUpdateNotifier = async (t, { prefixDir, argv, }) + const registry = new MockRegistry({ + tap: t, + registry: mock.npm.config.get('registry'), + }) + + if (PACOTE_MOCK_REQ_COUNT > 0) { + registry.nock.get('/npm').times(PACOTE_MOCK_REQ_COUNT).reply(200, packumentResponse) + } + const updateNotifier = tmock(t, '{LIB}/cli/update-notifier.js', mocks) const result = await updateNotifier(mock.npm) @@ -90,29 +120,28 @@ const runUpdateNotifier = async (t, { return { wroteFile, result, - MANIFEST_REQUEST, } } t.test('duration has elapsed, no updates', async t => { - const { wroteFile, result, MANIFEST_REQUEST } = await runUpdateNotifier(t) + const { wroteFile, result } = await runUpdateNotifier(t) t.equal(wroteFile, true) t.not(result) - t.equal(MANIFEST_REQUEST.length, 1) }) t.test('situations in which we do not notify', t => { t.test('nothing to do if notifier disabled', async t => { - const { wroteFile, result, MANIFEST_REQUEST } = await runUpdateNotifier(t, { + const { wroteFile, result } = await runUpdateNotifier(t, { + PACOTE_MOCK_REQ_COUNT: 0, 'update-notifier': false, }) t.equal(wroteFile, false) t.equal(result, null) - t.strictSame(MANIFEST_REQUEST, [], 'no requests for manifests') }) t.test('do not suggest update if already updating', async t => { - const { wroteFile, result, MANIFEST_REQUEST } = await runUpdateNotifier(t, { + const { wroteFile, result } = await runUpdateNotifier(t, { + PACOTE_MOCK_REQ_COUNT: 0, command: 'install', prefixDir: { 'package.json': `{"name":"${t.testName}"}` }, argv: ['npm'], @@ -120,11 +149,11 @@ t.test('situations in which we do not notify', t => { }) t.equal(wroteFile, false) t.equal(result, null) - t.strictSame(MANIFEST_REQUEST, [], 'no requests for manifests') }) t.test('do not suggest update if already updating with spec', async t => { - const { wroteFile, result, MANIFEST_REQUEST } = await runUpdateNotifier(t, { + const { wroteFile, result } = await runUpdateNotifier(t, { + PACOTE_MOCK_REQ_COUNT: 0, command: 'install', prefixDir: { 'package.json': `{"name":"${t.testName}"}` }, argv: ['npm@latest'], @@ -132,75 +161,68 @@ t.test('situations in which we do not notify', t => { }) t.equal(wroteFile, false) t.equal(result, null) - t.strictSame(MANIFEST_REQUEST, [], 'no requests for manifests') }) t.test('do not update if same as latest', async t => { - const { wroteFile, result, MANIFEST_REQUEST } = await runUpdateNotifier(t) + const { wroteFile, result } = await runUpdateNotifier(t) t.equal(wroteFile, true) t.equal(result, null) - t.strictSame(MANIFEST_REQUEST, ['npm@latest'], 'requested latest version') }) t.test('check if stat errors (here for coverage)', async t => { const STAT_ERROR = new Error('blorg') - const { wroteFile, result, MANIFEST_REQUEST } = await runUpdateNotifier(t, { STAT_ERROR }) + const { wroteFile, result } = await runUpdateNotifier(t, { STAT_ERROR }) t.equal(wroteFile, true) t.equal(result, null) - t.strictSame(MANIFEST_REQUEST, ['npm@latest'], 'requested latest version') }) t.test('ok if write errors (here for coverage)', async t => { const WRITE_ERROR = new Error('grolb') - const { wroteFile, result, MANIFEST_REQUEST } = await runUpdateNotifier(t, { WRITE_ERROR }) + const { wroteFile, result } = await runUpdateNotifier(t, { WRITE_ERROR }) t.equal(wroteFile, true) t.equal(result, null) - t.strictSame(MANIFEST_REQUEST, ['npm@latest'], 'requested latest version') }) t.test('ignore pacote failures (here for coverage)', async t => { const PACOTE_ERROR = new Error('pah-KO-tchay') - const { wroteFile, result, MANIFEST_REQUEST } = await runUpdateNotifier(t, { PACOTE_ERROR }) + const { wroteFile, result } = await runUpdateNotifier(t, { + PACOTE_ERROR, PACOTE_MOCK_REQ_COUNT: 0, + }) t.equal(result, null) t.equal(wroteFile, true) - t.strictSame(MANIFEST_REQUEST, ['npm@latest'], 'requested latest version') }) t.test('do not update if newer than latest, but same as next', async t => { const { wroteFile, result, - MANIFEST_REQUEST, } = await runUpdateNotifier(t, { version: NEXT_VERSION }) t.equal(result, null) t.equal(wroteFile, true) - const reqs = ['npm@latest', `npm@^${NEXT_VERSION}`] - t.strictSame(MANIFEST_REQUEST, reqs, 'requested latest and next versions') }) t.test('do not update if on the latest beta', async t => { const { wroteFile, result, - MANIFEST_REQUEST, } = await runUpdateNotifier(t, { version: CURRENT_BETA }) t.equal(result, null) t.equal(wroteFile, true) - const reqs = [`npm@^${CURRENT_BETA}`] - t.strictSame(MANIFEST_REQUEST, reqs, 'requested latest and next versions') }) t.test('do not update in CI', async t => { - const { wroteFile, result, MANIFEST_REQUEST } = await runUpdateNotifier(t, { mocks: { + const { wroteFile, result } = await runUpdateNotifier(t, { mocks: { 'ci-info': { isCI: true, name: 'something' }, - } }) + }, + PACOTE_MOCK_REQ_COUNT: 0 }) t.equal(wroteFile, false) t.equal(result, null) - t.strictSame(MANIFEST_REQUEST, [], 'no requests for manifests') }) t.test('only check weekly for GA releases', async t => { // One week (plus five minutes to account for test environment fuzziness) const STAT_MTIME = Date.now() - 1000 * 60 * 60 * 24 * 7 + 1000 * 60 * 5 - const { wroteFile, result, MANIFEST_REQUEST } = await runUpdateNotifier(t, { STAT_MTIME }) + const { wroteFile, result } = await runUpdateNotifier(t, { + STAT_MTIME, + PACOTE_MOCK_REQ_COUNT: 0, + }) t.equal(wroteFile, false, 'duration was not reset') t.equal(result, null) - t.strictSame(MANIFEST_REQUEST, [], 'no requests for manifests') }) t.test('only check daily for betas', async t => { @@ -209,37 +231,48 @@ t.test('situations in which we do not notify', t => { const { wroteFile, result, - MANIFEST_REQUEST, - } = await runUpdateNotifier(t, { STAT_MTIME, version: HAVE_BETA }) + } = await runUpdateNotifier(t, { STAT_MTIME, version: HAVE_BETA, PACOTE_MOCK_REQ_COUNT: 0 }) t.equal(wroteFile, false, 'duration was not reset') t.equal(result, null) - t.strictSame(MANIFEST_REQUEST, [], 'no requests for manifests') }) t.end() }) +t.test('notification situation with engine compatibility', async t => { + // no version which are greater than node 1.0.0 should be selected. + mockGlobals(t, { 'process.version': 'v1.0.0' }, { replace: true }) + + const { + wroteFile, + result, + } = await runUpdateNotifier(t, { + version: NEXT_VERSION_ENGINE_COMPATIBLE_MINOR, + PACOTE_MOCK_REQ_COUNT: 1 }) + + t.matchSnapshot(result) + t.equal(wroteFile, true) +}) + t.test('notification situations', async t => { const cases = { - [HAVE_BETA]: [`^{V}`], - [NEXT_PATCH]: [`latest`, `^{V}`], - [NEXT_MINOR]: [`latest`, `^{V}`], - [CURRENT_PATCH]: ['latest'], - [CURRENT_MINOR]: ['latest'], - [CURRENT_MAJOR]: ['latest'], + [HAVE_BETA]: 1, + [NEXT_PATCH]: 2, + [NEXT_MINOR]: 2, + [CURRENT_PATCH]: 1, + [CURRENT_MINOR]: 1, + [CURRENT_MAJOR]: 1, } - for (const [version, reqs] of Object.entries(cases)) { + for (const [version, requestCount] of Object.entries(cases)) { for (const color of [false, 'always']) { await t.test(`${version} - color=${color}`, async t => { const { wroteFile, result, - MANIFEST_REQUEST, - } = await runUpdateNotifier(t, { version, color }) + } = await runUpdateNotifier(t, { version, color, PACOTE_MOCK_REQ_COUNT: requestCount }) t.matchSnapshot(result) t.equal(wroteFile, true) - t.strictSame(MANIFEST_REQUEST, reqs.map(r => `npm@${r.replace('{V}', version)}`)) }) } } diff --git a/test/lib/cli/validate-engines.js b/test/lib/cli/validate-engines.js index 1c0b59700a773..980b508f02d97 100644 --- a/test/lib/cli/validate-engines.js +++ b/test/lib/cli/validate-engines.js @@ -23,7 +23,6 @@ t.test('validate engines', async t => { node: 'v4.5.6', npm: 'v1.2.3', engines: '>=0', - /* eslint-disable-next-line max-len */ unsupportedMessage: 'npm v1.2.3 does not support Node.js v4.5.6. This version of npm supports the following node versions: `>=0`. You can find the latest version at https://nodejs.org/.', }) diff --git a/test/lib/commands/adduser.js b/test/lib/commands/adduser.js deleted file mode 100644 index c69d996f91486..0000000000000 --- a/test/lib/commands/adduser.js +++ /dev/null @@ -1,181 +0,0 @@ -const t = require('tap') -const fs = require('node:fs') -const path = require('node:path') -const ini = require('ini') - -const { load: loadMockNpm } = require('../../fixtures/mock-npm.js') -const mockGlobals = require('@npmcli/mock-globals') -const MockRegistry = require('@npmcli/mock-registry') -const stream = require('node:stream') - -const mockAddUser = async (t, { stdin: stdinLines, registry: registryUrl, ...options } = {}) => { - if (stdinLines) { - const stdin = new stream.PassThrough() - for (const l of stdinLines) { - stdin.write(l + '\n') - } - mockGlobals(t, { - 'process.stdin': stdin, - 'process.stdout': new stream.PassThrough(), // to quiet readline - }, { replace: true }) - } - const mock = await loadMockNpm(t, { - ...options, - command: 'adduser', - }) - const registry = new MockRegistry({ - tap: t, - registry: registryUrl ?? mock.npm.config.get('registry'), - }) - return { - registry, - rc: () => ini.parse(fs.readFileSync(path.join(mock.home, '.npmrc'), 'utf8')), - ...mock, - } -} - -t.test('usage', async t => { - const { adduser } = await loadMockNpm(t, { command: 'adduser' }) - t.match(adduser.usage, 'adduser', 'usage has command name in it') -}) - -t.test('legacy', async t => { - t.test('simple adduser', async t => { - const { npm, rc, registry, adduser } = await mockAddUser(t, { - stdin: ['test-user', 'test-password', 'test-email@npmjs.org'], - config: { 'auth-type': 'legacy' }, - homeDir: { - '.npmrc': [ - '//registry.npmjs.org/:_authToken=user', - '//registry.npmjs.org/:always-auth=user', - '//registry.npmjs.org/:email=test-email-old@npmjs.org', - ].join('\n'), - }, - }) - registry.couchadduser({ - username: 'test-user', - password: 'test-password', - email: 'test-email@npmjs.org', - token: 'npm_test-token', - }) - await adduser.exec([]) - t.same(npm.config.get('email'), 'test-email-old@npmjs.org') - t.same(npm.config.get('//registry.npmjs.org/:_authToken'), 'npm_test-token') - t.same(rc(), { - '//registry.npmjs.org/:_authToken': 'npm_test-token', - email: 'test-email-old@npmjs.org', - }, 'should only have token and un-nerfed old email') - }) - - t.test('scoped adduser', async t => { - const { npm, rc, registry, adduser } = await mockAddUser(t, { - stdin: ['test-user', 'test-password', 'test-email@npmjs.org'], - config: { - 'auth-type': 'legacy', - scope: '@myscope', - }, - }) - registry.couchadduser({ - username: 'test-user', - password: 'test-password', - email: 'test-email@npmjs.org', - token: 'npm_test-token', - }) - await adduser.exec([]) - t.same(npm.config.get('//registry.npmjs.org/:_authToken'), 'npm_test-token') - t.same(npm.config.get('@myscope:registry'), 'https://registry.npmjs.org/') - t.same(rc(), { - '//registry.npmjs.org/:_authToken': 'npm_test-token', - '@myscope:registry': 'https://registry.npmjs.org/', - }, 'should only have token and scope:registry') - }) - - t.test('scoped adduser with valid scoped registry config', async t => { - const { npm, rc, registry, adduser } = await mockAddUser(t, { - stdin: ['test-user', 'test-password', 'test-email@npmjs.org'], - registry: 'https://diff-registry.npmjs.org', - homeDir: { - '.npmrc': '@myscope:registry=https://diff-registry.npmjs.org', - }, - config: { - 'auth-type': 'legacy', - scope: '@myscope', - }, - }) - registry.couchadduser({ - username: 'test-user', - password: 'test-password', - email: 'test-email@npmjs.org', - token: 'npm_test-token', - }) - await adduser.exec([]) - t.same(npm.config.get('//diff-registry.npmjs.org/:_authToken'), 'npm_test-token') - t.same(npm.config.get('@myscope:registry'), 'https://diff-registry.npmjs.org') - t.same(rc(), { - '@myscope:registry': 'https://diff-registry.npmjs.org', - '//diff-registry.npmjs.org/:_authToken': 'npm_test-token', - }, 'should only have token and scope:registry') - }) - - t.test('save config failure', async t => { - const { registry, adduser } = await mockAddUser(t, { - stdin: ['test-user', 'test-password', 'test-email@npmjs.org'], - config: { 'auth-type': 'legacy' }, - homeDir: { - '.npmrc': {}, - }, - }) - registry.couchadduser({ - username: 'test-user', - password: 'test-password', - email: 'test-email@npmjs.org', - token: 'npm_test-token', - }) - await t.rejects(adduser.exec([])) - }) - t.end() -}) - -t.test('web', t => { - t.test('basic adduser', async t => { - const { npm, rc, registry, adduser } = await mockAddUser(t, { - config: { 'auth-type': 'web' }, - }) - registry.webadduser({ token: 'npm_test-token' }) - await adduser.exec([]) - t.same(npm.config.get('//registry.npmjs.org/:_authToken'), 'npm_test-token') - t.same(rc(), { - '//registry.npmjs.org/:_authToken': 'npm_test-token', - }) - }) - - t.test('server error', async t => { - const { adduser, registry } = await mockAddUser(t, { - config: { 'auth-type': 'web' }, - }) - registry.nock.post(registry.fullPath('/-/v1/login')) - .reply(503, {}) - await t.rejects( - adduser.exec([]), - { message: /503/ } - ) - }) - - t.test('fallback', async t => { - const { npm, registry, adduser } = await mockAddUser(t, { - stdin: ['test-user', 'test-password', 'test-email@npmjs.org'], - config: { 'auth-type': 'web' }, - }) - registry.nock.post(registry.fullPath('/-/v1/login')) - .reply(404, {}) - registry.couchadduser({ - username: 'test-user', - password: 'test-password', - email: 'test-email@npmjs.org', - token: 'npm_test-token', - }) - await adduser.exec([]) - t.same(npm.config.get('//registry.npmjs.org/:_authToken'), 'npm_test-token') - }) - t.end() -}) diff --git a/test/lib/commands/approve-scripts.js b/test/lib/commands/approve-scripts.js new file mode 100644 index 0000000000000..7033db1acd97c --- /dev/null +++ b/test/lib/commands/approve-scripts.js @@ -0,0 +1,811 @@ +const t = require('tap') +const fs = require('node:fs') +const { resolve } = require('node:path') +const _mockNpm = require('../../fixtures/mock-npm') + +const mockNpm = async (t, opts = {}) => { + return _mockNpm(t, opts) +} + +const setupProject = ({ allowScripts, withScripts = ['canvas'] } = {}) => { + const pkg = { + name: 'host', + version: '1.0.0', + dependencies: Object.fromEntries(withScripts.map((n) => [n, '*'])), + } + if (allowScripts !== undefined) { + pkg.allowScripts = allowScripts + } + + const lockPackages = { '': pkg } + const nodeModules = {} + for (const name of withScripts) { + const tarUrl = `https://registry.npmjs.org/${name}/-/${name}-1.0.0.tgz` + nodeModules[name] = { + 'package.json': JSON.stringify({ + name, + version: '1.0.0', + scripts: { install: 'echo install' }, + }), + } + lockPackages[`node_modules/${name}`] = { + version: '1.0.0', + resolved: tarUrl, + hasInstallScript: true, + } + } + + return { + 'package.json': JSON.stringify(pkg, null, 2), + 'package-lock.json': JSON.stringify({ + name: pkg.name, + version: pkg.version, + lockfileVersion: 3, + requires: true, + packages: lockPackages, + }), + node_modules: nodeModules, + } +} + +t.test('approve-scripts --pending lists unreviewed packages', async t => { + const { npm, joinedOutput } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas', 'sharp'] }), + config: { 'allow-scripts-pending': true }, + }) + await npm.exec('approve-scripts', []) + const out = joinedOutput() + t.match(out, /2 packages have install scripts blocked because they are not covered by allowScripts/) + t.match(out, /canvas@1\.0\.0/) + t.match(out, /sharp@1\.0\.0/) +}) + +t.test('approve-scripts --pending lists unreviewed packages even with ignore-scripts set', async t => { + const { npm, joinedOutput } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas', 'sharp'] }), + config: { 'allow-scripts-pending': true, 'ignore-scripts': true }, + }) + await npm.exec('approve-scripts', []) + const out = joinedOutput() + t.match(out, /2 packages have install scripts blocked because they are not covered by allowScripts/) + t.match(out, /canvas@1\.0\.0/) + t.match(out, /sharp@1\.0\.0/) +}) + +t.test('approve-scripts --pending with no unreviewed says so', async t => { + const { npm, joinedOutput } = await mockNpm(t, { + prefixDir: setupProject({ + allowScripts: { canvas: true }, + withScripts: ['canvas'], + }), + config: { 'allow-scripts-pending': true }, + }) + await npm.exec('approve-scripts', []) + t.match(joinedOutput(), /No packages with unreviewed install scripts/) +}) + +t.test('approve-scripts writes pinned entry by default', async t => { + const { npm, prefix } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + }) + await npm.exec('approve-scripts', ['canvas']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'canvas@1.0.0': true }) +}) + +t.test('approve-scripts --no-pin writes name-only entry', async t => { + const { npm, prefix } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + config: { 'allow-scripts-pin': false }, + }) + await npm.exec('approve-scripts', ['canvas']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { canvas: true }) +}) + +t.test('approve-scripts --all approves every unreviewed package', async t => { + const { npm, prefix } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas', 'sharp'] }), + config: { all: true }, + }) + await npm.exec('approve-scripts', []) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { + 'canvas@1.0.0': true, + 'sharp@1.0.0': true, + }) +}) + +t.test('approve-scripts errors on unknown package', async t => { + const { npm } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + }) + await t.rejects( + npm.exec('approve-scripts', ['not-installed']), + { code: 'ENOMATCH' } + ) +}) + +t.test('approve-scripts approves a package whose name contains dots', async t => { + const { npm, prefix } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['cordova.plugins.diagnostic'] }), + }) + await npm.exec('approve-scripts', ['cordova.plugins.diagnostic']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'cordova.plugins.diagnostic@1.0.0': true }) +}) + +t.test('approve-scripts approves a dotted name with a version specifier', async t => { + const { npm, prefix } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['cordova.plugins.diagnostic'] }), + }) + await npm.exec('approve-scripts', ['cordova.plugins.diagnostic@1.0.0']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'cordova.plugins.diagnostic@1.0.0': true }) +}) + +t.test('approve-scripts <@scope/pkg@version> approves a scoped name with a version', async t => { + const { npm, prefix } = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + dependencies: { '@scope/pkg': '*' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'host', version: '1.0.0', dependencies: { '@scope/pkg': '*' } }, + 'node_modules/@scope/pkg': { + version: '2.0.0', + resolved: 'https://registry.npmjs.org/@scope/pkg/-/pkg-2.0.0.tgz', + hasInstallScript: true, + }, + }, + }), + node_modules: { + '@scope': { + pkg: { + 'package.json': JSON.stringify({ + name: '@scope/pkg', + version: '2.0.0', + scripts: { install: 'echo install' }, + }), + }, + }, + }, + }, + }) + await npm.exec('approve-scripts', ['@scope/pkg@2.0.0']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { '@scope/pkg@2.0.0': true }) +}) + +t.test('approve-scripts errors when no installed version matches', async t => { + const { npm } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + }) + await t.rejects( + npm.exec('approve-scripts', ['canvas@9.9.9']), + { code: 'ENOMATCH' } + ) +}) + +t.test('approve-scripts reports only the unmatched args and writes nothing', async t => { + const { npm, prefix } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + }) + const err = await npm.exec('approve-scripts', ['canvas', 'not-installed']) + .then(() => null, e => e) + t.equal(err.code, 'ENOMATCH') + t.match(err.message, /not-installed/) + t.notMatch(err.message, /canvas/) + // Nothing is written when any arg fails to match. + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.notOk(pkg.allowScripts) +}) + +t.test('approve-scripts matches every installed version', async t => { + const { npm, prefix } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + }) + // A tag carries no version to filter on, so it behaves like a bare name. + await npm.exec('approve-scripts', ['canvas@latest']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'canvas@1.0.0': true }) +}) + +t.test('approve-scripts errors on an unparseable spec', async t => { + const { npm } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + }) + // npm-package-arg throws on this; the raw string is used as the name and + // matches nothing. + await t.rejects( + npm.exec('approve-scripts', ['foo@@bar']), + { code: 'ENOMATCH' } + ) +}) + +t.test('approve-scripts errors on a spec with no package name', async t => { + const { npm } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + }) + // A path spec parses but carries no name, so it matches no registry dep. + await t.rejects( + npm.exec('approve-scripts', ['./local-pkg']), + { code: 'ENOMATCH' } + ) +}) + +t.test('approve-scripts respects existing deny entry', async t => { + const { npm, prefix, logs } = await mockNpm(t, { + prefixDir: setupProject({ + withScripts: ['canvas'], + allowScripts: { canvas: false }, + }), + }) + await npm.exec('approve-scripts', ['canvas']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + // Deny wins; unchanged. + t.strictSame(pkg.allowScripts, { canvas: false }) + t.match(logs.warn.byTitle('approve-scripts'), [/canvas is denied/]) +}) + +t.test('approve-scripts requires positional args, --all, or --pending', async t => { + const { npm } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + }) + await t.rejects(npm.exec('approve-scripts', []), { code: 'EUSAGE' }) +}) + +t.test('approve-scripts --pending cannot be combined with positional', async t => { + const { npm } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + config: { 'allow-scripts-pending': true }, + }) + await t.rejects(npm.exec('approve-scripts', ['canvas']), { code: 'EUSAGE' }) +}) + +t.test('approve-scripts fails on global', async t => { + const { npm } = await mockNpm(t, { + config: { global: true }, + }) + await t.rejects(npm.exec('approve-scripts', ['canvas']), { code: 'EGLOBAL' }) +}) + +t.test('approve-scripts --json outputs structured summary', async t => { + const { npm, joinedOutput } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + config: { json: true }, + }) + await npm.exec('approve-scripts', ['canvas']) + const parsed = JSON.parse(joinedOutput()) + t.match(parsed, { + allowScripts: [{ name: 'canvas', changes: [{ key: 'canvas@1.0.0', change: 'added' }] }], + }) +}) + +t.test('approve-scripts --pending --json lists unreviewed packages as JSON', async t => { + const { npm, joinedOutput } = await mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas', 'sharp'] }), + config: { 'allow-scripts-pending': true, json: true }, + }) + await npm.exec('approve-scripts', []) + const parsed = JSON.parse(joinedOutput()) + const byName = Object.fromEntries(parsed.allowScripts.map((e) => [e.name, e.changes])) + t.strictSame(byName, { + canvas: [{ key: 'canvas@1.0.0', change: 'pending' }], + sharp: [{ key: 'sharp@1.0.0', change: 'pending' }], + }) +}) + +t.test('approve-scripts --pending --json with no unreviewed emits empty list', async t => { + const { npm, joinedOutput } = await mockNpm(t, { + prefixDir: setupProject({ + allowScripts: { canvas: true }, + withScripts: ['canvas'], + }), + config: { 'allow-scripts-pending': true, json: true }, + }) + await npm.exec('approve-scripts', []) + t.strictSame(JSON.parse(joinedOutput()), { allowScripts: [] }) +}) + +t.test('approve-scripts --all --json with no unreviewed emits empty list', async t => { + const { npm, joinedOutput } = await _mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'host', version: '1.0.0' }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { '': { name: 'host', version: '1.0.0' } }, + }), + node_modules: {}, + }, + config: { all: true, json: true }, + }) + await npm.exec('approve-scripts', []) + t.strictSame(JSON.parse(joinedOutput()), { allowScripts: [] }) +}) + +t.test('approve-scripts --all with no unreviewed packages prints message', async t => { + const { npm, joinedOutput } = await _mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'host', version: '1.0.0' }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { '': { name: 'host', version: '1.0.0' } }, + }), + node_modules: {}, + }, + config: { all: true }, + }) + await npm.exec('approve-scripts', []) + t.match(joinedOutput(), /No packages with unreviewed install scripts/) +}) + +t.test('approve-scripts on a package already at the right pin is no-op', async t => { + const { npm, prefix, joinedOutput } = await _mockNpm(t, { + prefixDir: setupProject({ + withScripts: ['canvas'], + allowScripts: { 'canvas@1.0.0': true }, + }), + }) + await npm.exec('approve-scripts', ['canvas']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'canvas@1.0.0': true }) + t.match(joinedOutput(), /Nothing to approve/) +}) + +t.test('approve-scripts --pending with single package uses singular wording', async t => { + const { npm, joinedOutput } = await _mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + config: { 'allow-scripts-pending': true }, + }) + await npm.exec('approve-scripts', []) + t.match(joinedOutput(), /1 package has install scripts/) +}) + +t.test('approve-scripts --pending lists package with no version', async t => { + // Use a fixture where the lockfile records a synthetic node without a version + const { npm } = await _mockNpm(t, { + prefixDir: setupProject({ withScripts: ['canvas'] }), + config: { 'allow-scripts-pending': true }, + }) + await npm.exec('approve-scripts', []) + // Just exercising; no assertion needed for additional coverage. + t.pass() +}) + +const twoVersionFixture = { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + dependencies: { 'top-of-tree': '*' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'host', version: '1.0.0', dependencies: { 'top-of-tree': '*' } }, + 'node_modules/lodash': { + version: '4.17.21', + resolved: 'https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz', + hasInstallScript: true, + }, + 'node_modules/top-of-tree': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/top-of-tree/-/top-of-tree-1.0.0.tgz', + dependencies: { lodash: '3.10.1' }, + }, + 'node_modules/top-of-tree/node_modules/lodash': { + version: '3.10.1', + resolved: 'https://registry.npmjs.org/lodash/-/lodash-3.10.1.tgz', + hasInstallScript: true, + }, + }, + }), + node_modules: { + lodash: { + 'package.json': JSON.stringify({ + name: 'lodash', + version: '4.17.21', + scripts: { install: 'echo install' }, + }), + }, + 'top-of-tree': { + 'package.json': JSON.stringify({ name: 'top-of-tree', version: '1.0.0' }), + node_modules: { + lodash: { + 'package.json': JSON.stringify({ + name: 'lodash', + version: '3.10.1', + scripts: { install: 'echo install' }, + }), + }, + }, + }, + }, +} + +t.test('approve-scripts --pending --json groups multiple versions under one name', async t => { + // Two versions of lodash are unreviewed; pendingSummary must collapse + // them into a single `lodash` entry (hits the `groups.has(display)` + // truthy branch on the second node). + const { npm, joinedOutput } = await _mockNpm(t, { + prefixDir: twoVersionFixture, + config: { 'allow-scripts-pending': true, json: true }, + }) + await npm.exec('approve-scripts', []) + const parsed = JSON.parse(joinedOutput()) + t.strictSame(parsed.allowScripts.map((e) => e.name), ['lodash']) + t.strictSame(parsed.allowScripts[0].changes.map((c) => c.key).sort(), [ + 'lodash@3.10.1', + 'lodash@4.17.21', + ]) + t.ok(parsed.allowScripts[0].changes.every((c) => c.change === 'pending')) +}) + +t.test('approve-scripts groups multiple installed versions of the same package', async t => { + // Two versions of lodash exist in the tree; both have install scripts. + // groupByPackage should put them in the same group (hits the + // `if (!groups[key])` falsy branch on the second node). + const { npm, prefix } = await _mockNpm(t, { + prefixDir: twoVersionFixture, + }) + await npm.exec('approve-scripts', ['lodash']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + // Both versions get pinned. + t.strictSame(pkg.allowScripts, { + 'lodash@3.10.1': true, + 'lodash@4.17.21': true, + }) +}) + +t.test('approve-scripts pins only the matching installed version', async t => { + const { npm, prefix } = await _mockNpm(t, { + prefixDir: twoVersionFixture, + }) + await npm.exec('approve-scripts', ['lodash@4.17.21']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'lodash@4.17.21': true }) +}) + +t.test('approve-scripts pins only versions satisfying the range', async t => { + const { npm, prefix } = await _mockNpm(t, { + prefixDir: twoVersionFixture, + }) + await npm.exec('approve-scripts', ['lodash@^4']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'lodash@4.17.21': true }) +}) + +t.test('approve-scripts --pending handles node with no version', async t => { + // Exercise the ternary's falsy branch in runPending: `node.version ? '@'... : ''` + // when the node has no version field. + const mockSync = await _mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'host', version: '1.0.0' }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { '': { name: 'host', version: '1.0.0' } }, + }), + node_modules: {}, + }, + config: { 'allow-scripts-pending': true }, + mocks: { + // Make the walker return a synthetic node with no version + '{LIB}/utils/check-allow-scripts.js': async () => [{ + node: { packageName: 'no-version-pkg', name: 'no-version-pkg', version: undefined }, + scripts: { install: 'do-stuff' }, + }], + }, + }) + await mockSync.npm.exec('approve-scripts', []) + // Output should mention the package without an @version suffix. + t.match(mockSync.joinedOutput(), / no-version-pkg \(install: do-stuff\)/) +}) + +t.test('approve-scripts --pending --json handles node with no version', async t => { + // Exercise pendingSummary's `version ? ... : display` falsy branch: the + // key is the bare name when the node has no version field. + const { npm, joinedOutput } = await _mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'host', version: '1.0.0' }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { '': { name: 'host', version: '1.0.0' } }, + }), + node_modules: {}, + }, + config: { 'allow-scripts-pending': true, json: true }, + mocks: { + '{LIB}/utils/check-allow-scripts.js': async () => [{ + node: { packageName: 'no-version-pkg', name: 'no-version-pkg', version: undefined }, + scripts: { install: 'do-stuff' }, + }], + }, + }) + await npm.exec('approve-scripts', []) + t.strictSame(JSON.parse(joinedOutput()), { + allowScripts: [ + { name: 'no-version-pkg', changes: [{ key: 'no-version-pkg', change: 'pending' }] }, + ], + }) +}) + +t.test('forbidden semver range in package.json#allowScripts is dropped with a warning', async t => { + // End-to-end: project declares a caret range in allowScripts. The + // resolver must drop the entry, emit a warning, and the matching node + // must remain unreviewed (listed by --pending). + const mock = await _mockNpm(t, { + prefixDir: setupProject({ + withScripts: ['canvas'], + // ^0.33.0 is a forbidden range per RFC. + allowScripts: { 'canvas@^0.33.0': true }, + }), + config: { 'allow-scripts-pending': true }, + }) + await mock.npm.exec('approve-scripts', []) + + const warnings = mock.logs.warn.byTitle('allow-scripts') + t.ok( + warnings.some(m => /semver ranges/.test(m) && /canvas@\^0\.33\.0/.test(m)), + 'resolver emits warning about forbidden range' + ) + // canvas was installed with version 1.0.0 (setupProject default) and + // the forbidden allowlist entry was dropped, so canvas appears in the + // pending list. + t.match(mock.joinedOutput(), /canvas@1\.0\.0/) +}) + +t.test('approve-scripts --pending lists packages that only have binding.gyp', async t => { + // End-to-end: a package with no preinstall/install/postinstall but a + // binding.gyp on disk gets a synthetic `node-gyp rebuild` install + // script. The runtime isNodeGypPackage check must see it and surface + // the package in --pending output. + const mock = await _mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + dependencies: { 'native-pkg': '*' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'host', version: '1.0.0', dependencies: { 'native-pkg': '*' } }, + 'node_modules/native-pkg': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/native-pkg/-/native-pkg-1.0.0.tgz', + // No hasInstallScript — the synthetic node-gyp injection is + // what we want this test to exercise. + }, + }, + }), + node_modules: { + 'native-pkg': { + 'package.json': JSON.stringify({ name: 'native-pkg', version: '1.0.0' }), + // The file that triggers isNodeGypPackage to return true. + 'binding.gyp': '{}', + }, + }, + }, + config: { 'allow-scripts-pending': true }, + }) + await mock.npm.exec('approve-scripts', []) + + const out = mock.joinedOutput() + t.match(out, /native-pkg@1\.0\.0/, 'binding.gyp-only package appears in --pending') + t.match(out, /install: node-gyp rebuild/, 'synthetic node-gyp install is named') +}) + +t.test('approve-scripts --all never approves bundled deps', async t => { + // Bundled deps never run their install scripts and cannot be + // allowlisted. They never reach the unreviewed list, so --all must not + // write a key derived from the bundled tarball's self-claimed identity. + const { npm, logs, prefix } = await _mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + dependencies: { 'parent-pkg': '*' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'host', version: '1.0.0', dependencies: { 'parent-pkg': '*' } }, + 'node_modules/parent-pkg': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/parent-pkg/-/parent-pkg-1.0.0.tgz', + hasInstallScript: true, + }, + 'node_modules/parent-pkg/node_modules/inner': { + version: '1.0.0', + inBundle: true, + hasInstallScript: true, + }, + }, + }), + node_modules: { + 'parent-pkg': { + 'package.json': JSON.stringify({ + name: 'parent-pkg', + version: '1.0.0', + scripts: { install: 'echo install' }, + bundleDependencies: ['inner'], + }), + node_modules: { + inner: { + 'package.json': JSON.stringify({ + name: 'inner', + version: '1.0.0', + scripts: { install: 'echo bundled-install' }, + }), + }, + }, + }, + }, + }, + config: { all: true }, + }) + await npm.exec('approve-scripts', []) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + // parent-pkg is approvable. inner is bundled and must be excluded. + t.equal(pkg.allowScripts['parent-pkg@1.0.0'], true, + 'non-bundled parent gets approved') + t.notOk(Object.keys(pkg.allowScripts).some(k => k.startsWith('inner')), + 'bundled inner is not approved') + t.strictSame(logs.warn.byTitle('approve-scripts'), [], + 'no warning; bundled deps are excluded upstream') +}) + +t.test('approve-scripts positional is ignored', async t => { + // Same protection on the positional path: a user typing a bundled + // package name must not get a policy entry written. + const { npm } = await _mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + dependencies: { 'parent-pkg': '*' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'host', version: '1.0.0', dependencies: { 'parent-pkg': '*' } }, + 'node_modules/parent-pkg': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/parent-pkg/-/parent-pkg-1.0.0.tgz', + hasInstallScript: true, + }, + 'node_modules/parent-pkg/node_modules/inner': { + version: '1.0.0', + inBundle: true, + hasInstallScript: true, + }, + }, + }), + node_modules: { + 'parent-pkg': { + 'package.json': JSON.stringify({ + name: 'parent-pkg', + version: '1.0.0', + scripts: { install: 'echo install' }, + bundleDependencies: ['inner'], + }), + node_modules: { + inner: { + 'package.json': JSON.stringify({ + name: 'inner', + version: '1.0.0', + scripts: { install: 'echo bundled' }, + }), + }, + }, + }, + }, + }, + }) + await t.rejects( + npm.exec('approve-scripts', ['inner']), + { code: 'ENOMATCH' }, + 'typing the bundled package name does not match any approvable node' + ) +}) + +t.test('approve-scripts --all with only bundled deps has nothing to review', async t => { + const { npm, logs, joinedOutput, prefix } = await _mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + dependencies: { 'parent-pkg': '*' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'host', version: '1.0.0', dependencies: { 'parent-pkg': '*' } }, + 'node_modules/parent-pkg': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/parent-pkg/-/parent-pkg-1.0.0.tgz', + // parent-pkg has NO install scripts; only the bundled child does. + }, + 'node_modules/parent-pkg/node_modules/only-bundled': { + version: '1.0.0', + inBundle: true, + hasInstallScript: true, + }, + }, + }), + node_modules: { + 'parent-pkg': { + 'package.json': JSON.stringify({ + name: 'parent-pkg', + version: '1.0.0', + bundleDependencies: ['only-bundled'], + }), + node_modules: { + 'only-bundled': { + 'package.json': JSON.stringify({ + name: 'only-bundled', + version: '1.0.0', + scripts: { install: 'echo evil' }, + }), + }, + }, + }, + }, + }, + config: { all: true }, + }) + await npm.exec('approve-scripts', []) + t.match(joinedOutput(), /No packages with unreviewed install scripts/) + t.strictSame(logs.warn.byTitle('approve-scripts'), [], + 'no warning; bundled deps are excluded upstream') + // Ensure no policy entry was written. + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.notOk(pkg.allowScripts, 'no allowScripts written') +}) diff --git a/test/lib/commands/audit.js b/test/lib/commands/audit.js index 4b239116188ca..196888c9b675e 100644 --- a/test/lib/commands/audit.js +++ b/test/lib/commands/audit.js @@ -7,6 +7,13 @@ const { default: tufmock } = require('@tufjs/repo-mock') const { load: loadMockNpm } = require('../../fixtures/mock-npm') const MockRegistry = require('@npmcli/mock-registry') +// pacote bundles its own copy of sigstore, which may be nested rather than +// hoisted. Resolve sigstore relative to pacote so test mocks replace the copy +// pacote actually requires. +const pacoteSigstore = require.resolve('sigstore', { + paths: [path.dirname(require.resolve('pacote'))], +}) + const gunzip = zlib.gunzipSync const gzip = zlib.gzipSync @@ -90,54 +97,6 @@ t.test('normal audit', async t => { t.matchSnapshot(joinedOutput()) }) -t.test('fallback audit ', async t => { - const { npm, joinedOutput } = await loadMockNpm(t, { - prefixDir: tree, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), - }) - const manifest = registry.manifest({ - name: 'test-dep-a', - packuments: [{ version: '1.0.0' }, { version: '1.0.1' }], - }) - await registry.package({ manifest }) - const advisory = registry.advisory({ - id: 100, - module_name: 'test-dep-a', - vulnerable_versions: '<1.0.1', - findings: [{ version: '1.0.0', paths: ['test-dep-a'] }], - }) - registry.nock - .post('/-/npm/v1/security/advisories/bulk').reply(404) - .post('/-/npm/v1/security/audits/quick', body => { - const unzipped = JSON.parse(gunzip(Buffer.from(body, 'hex'))) - return t.match(unzipped, { - name: 'test-dep', - version: '1.0.0', - requires: { 'test-dep-a': '*' }, - dependencies: { 'test-dep-a': { version: '1.0.0' } }, - }) - }).reply(200, { - actions: [], - muted: [], - advisories: { - 100: advisory, - }, - metadata: { - vulnerabilities: { info: 0, low: 0, moderate: 0, high: 1, critical: 0 }, - dependencies: 1, - devDependencies: 0, - optionalDependencies: 0, - totalDependencies: 1, - }, - }) - await npm.exec('audit', []) - t.ok(process.exitCode, 'would have exited uncleanly') - t.matchSnapshot(joinedOutput()) -}) - t.test('json audit', async t => { const { npm, joinedOutput } = await loadMockNpm(t, { prefixDir: tree, @@ -211,6 +170,86 @@ t.test('audit fix - bulk endpoint', async t => { ) }) +t.test('audit fix exits non-zero when min-release-age blocks a fix', async t => { + const { npm, logs } = await loadMockNpm(t, { + prefixDir: tree, + config: { 'min-release-age': 30 }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + }) + const manifest = registry.manifest({ + name: 'test-dep-a', + packuments: [{ version: '1.0.0' }, { version: '1.0.1' }], + }) + // 1.0.0 is old enough to install; the fix 1.0.1 was published too recently. + manifest.time['1.0.0'] = '2020-01-01T00:00:00.000Z' + manifest.time['1.0.1'] = new Date().toISOString() + await registry.package({ + manifest, + tarballs: { + '1.0.0': path.join(npm.prefix, 'test-dep-a-vuln'), + }, + times: 2, + }) + const advisory = registry.advisory({ id: 100, vulnerable_versions: '<1.0.1' }) + registry.nock.post('/-/npm/v1/security/advisories/bulk', body => { + const unzipped = JSON.parse(gunzip(Buffer.from(body, 'hex'))) + return t.same(unzipped, { 'test-dep-a': ['1.0.0'] }) + }) + .reply(200, { 'test-dep-a': [advisory] }) + .post('/-/npm/v1/security/advisories/bulk', body => { + const unzipped = JSON.parse(gunzip(Buffer.from(body, 'hex'))) + return t.same(unzipped, { 'test-dep-a': ['1.0.0'] }) + }) + .reply(200, { 'test-dep-a': [advisory] }) + + await npm.exec('audit', ['fix']) + + t.equal(process.exitCode, 1, 'exits non-zero because the fix was blocked') + t.ok( + logs.warn.some(w => + /left at a vulnerable version because a fix is newer than the release-age cutoff/.test(w)), + 'warns that the fix was blocked by min-release-age' + ) + const lock = JSON.parse(fs.readFileSync(path.join(npm.prefix, 'package-lock.json'), 'utf8')) + t.equal(lock.packages['node_modules/test-dep-a'].version, '1.0.0', + 'test-dep-a was left at the vulnerable version') +}) + +t.test('json audit reports fixBlockedByReleaseAge when a fix is too new', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: tree, + config: { + json: true, + 'min-release-age': 30, + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + }) + const manifest = registry.manifest({ + name: 'test-dep-a', + packuments: [{ version: '1.0.0' }, { version: '1.0.1' }], + }) + manifest.time['1.0.0'] = '2020-01-01T00:00:00.000Z' + manifest.time['1.0.1'] = new Date().toISOString() + await registry.package({ manifest }) + const advisory = registry.advisory({ id: 100, vulnerable_versions: '<1.0.1' }) + const bulkBody = gzip(JSON.stringify({ 'test-dep-a': ['1.0.0'] })) + registry.nock.post('/-/npm/v1/security/advisories/bulk', bulkBody) + .reply(200, { + 'test-dep-a': [advisory], + }) + + await npm.exec('audit', []) + const report = JSON.parse(joinedOutput()) + t.match(report.vulnerabilities['test-dep-a'].fixBlockedByReleaseAge, { version: '1.0.1' }, + 'json output flags the fix that min-release-age blocked') +}) + t.test('audit fix no package lock', async t => { const { npm } = await loadMockNpm(t, { config: { @@ -873,12 +912,9 @@ t.test('audit signatures', async t => { packuments: [{ version: '1.0.0', dist: { - // eslint-disable-next-line max-len integrity: 'sha512-e+qfbn/zf1+rCza/BhIA//Awmf0v1pa5HQS8Xk8iXrn9bgytytVLqYD0P7NSqZ6IELTgq+tcDvLPkQjNHyWLNg==', tarball: 'https://registry.npmjs.org/sigstore/-/sigstore-1.0.0.tgz', - // eslint-disable-next-line max-len attestations: { url: 'https://registry.npmjs.org/-/npm/v1/attestations/sigstore@1.0.0', provenance: { predicateType: 'https://slsa.dev/provenance/v0.2' } }, - // eslint-disable-next-line max-len signatures: [{ keyid: 'SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA', sig: 'MEQCIBlpcHT68iWOpx8pJr3WUzD1EqQ7tb0CmY36ebbceR6IAiAVGRaxrFoyh0/5B7H1o4VFhfsHw9F8G+AxOZQq87q+lg==' }], }, }], @@ -892,12 +928,9 @@ t.test('audit signatures', async t => { packuments: [{ version: '1.0.0', dist: { - // eslint-disable-next-line max-len integrity: 'sha512-1dxsQwESDzACJjTdYHQ4wJ1f/of7jALWKfJEHSBWUQB/5UTJUx9SW6GHXp4mZ1KvdBRJCpGjssoPFGi4hvw8/A==', tarball: 'https://registry.npmjs.org/tuf-js/-/tuf-js-1.0.0.tgz', - // eslint-disable-next-line max-len attestations: { url: 'https://registry.npmjs.org/-/npm/v1/attestations/tuf-js@1.0.0', provenance: { predicateType: 'https://slsa.dev/provenance/v0.2' } }, - // eslint-disable-next-line max-len signatures: [{ keyid: 'SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA', sig: 'MEYCIQDgGQeY2QLkLuoO9YxOqFZ+a6zYuaZpXhc77kUfdCUXDQIhAJp/vV+9Xg1bfM5YlTvKIH9agUEOu5T76+tQaHY2vZyO' }], }, }], @@ -960,6 +993,26 @@ t.test('audit signatures', async t => { t.matchSnapshot(joinedOutput()) }) + t.test('with min-release-age set verifies installed versions', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: installWithValidSigs, + config: { + 'min-release-age': 99999, + }, + }) + const registry = new MockRegistry({ tap: t, registry: npm.config.get('registry') }) + await manifestWithValidSigs({ registry }) + mockTUF({ npm, target: TUF_VALID_KEYS_TARGET }) + + // min-release-age flattens into a `before` cutoff that previously leaked + // into the exact-version manifest lookup, producing a spurious ETARGET on + // already-installed versions. See npm/cli#9277. + await npm.exec('audit', ['signatures']) + + t.notOk(process.exitCode, 'should exit successfully') + t.match(joinedOutput(), /audited 1 package/) + }) + t.test('with valid signatures using alias', async t => { const { npm, joinedOutput } = await loadMockNpm(t, { prefixDir: installWithAlias, @@ -994,7 +1047,7 @@ t.test('audit signatures', async t => { }) t.test('with key fallback to legacy API', async t => { - const { npm, joinedOutput } = await loadMockNpm(t, { + const { logs, npm, joinedOutput } = await loadMockNpm(t, { prefixDir: installWithValidSigs, }) const registry = new MockRegistry({ tap: t, registry: npm.config.get('registry') }) @@ -1006,6 +1059,7 @@ t.test('audit signatures', async t => { t.notOk(process.exitCode, 'should exit successfully') t.match(joinedOutput(), /audited 1 package/) + t.match(logs.warn, ['Fetching verification keys using TUF failed. Fetching directly from https://registry.npmjs.org/.']) t.matchSnapshot(joinedOutput()) }) @@ -1886,7 +1940,7 @@ t.test('audit signatures', async t => { prefixDir: installWithValidAttestations, mocks: { pacote: t.mock('pacote', { - sigstore: { verify: async () => true }, + [pacoteSigstore]: { verify: async () => true }, }), }, }) @@ -1903,15 +1957,146 @@ t.test('audit signatures', async t => { t.notOk(process.exitCode, 'should exit successfully') t.match(joinedOutput(), /1 package has a verified attestation/) + t.match(joinedOutput(), /use --json --include-attestations to view attestation details/) t.matchSnapshot(joinedOutput()) }) + t.test('with valid attestations and --include-attestations (human-readable)', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: installWithValidAttestations, + config: { + 'include-attestations': true, + }, + mocks: { + pacote: t.mock('pacote', { + [pacoteSigstore]: { verify: async () => true }, + }), + }, + }) + const registry = new MockRegistry({ tap: t, registry: npm.config.get('registry') }) + await manifestWithValidAttestations({ registry }) + const fixture = fs.readFileSync( + path.resolve(__dirname, '../../fixtures/sigstore/valid-sigstore-attestations.json'), + 'utf8' + ) + registry.nock.get('/-/npm/v1/attestations/sigstore@1.0.0').reply(200, fixture) + mockTUF({ npm, target: TUF_VALID_KEYS_TARGET }) + + await npm.exec('audit', ['signatures']) + + t.notOk(process.exitCode, 'should exit successfully') + t.match(joinedOutput(), /1 package has a verified attestation/) + t.notMatch(joinedOutput(), /use --json --include-attestations to view attestation details/) + }) + + t.test('with valid attestations --json --include-attestations', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: installWithValidAttestations, + config: { + json: true, + 'include-attestations': true, + }, + mocks: { + pacote: t.mock('pacote', { + [pacoteSigstore]: { verify: async () => true }, + }), + }, + }) + const registry = new MockRegistry({ tap: t, registry: npm.config.get('registry') }) + await manifestWithValidAttestations({ registry }) + const fixture = fs.readFileSync( + path.resolve(__dirname, '../../fixtures/sigstore/valid-sigstore-attestations.json'), + 'utf8' + ) + registry.nock.get('/-/npm/v1/attestations/sigstore@1.0.0').reply(200, fixture) + mockTUF({ npm, target: TUF_VALID_KEYS_TARGET }) + + await npm.exec('audit', ['signatures']) + + t.notOk(process.exitCode, 'should exit successfully') + const jsonOutput = JSON.parse(joinedOutput()) + t.ok(jsonOutput.verified, 'should include verified array') + t.equal(jsonOutput.verified.length, 1, 'should have one verified package') + t.equal(jsonOutput.verified[0].name, 'sigstore', 'should have correct package name') + t.equal(jsonOutput.verified[0].version, '1.0.0', 'should have correct version') + t.ok(jsonOutput.verified[0].attestations, 'should include attestations') + }) + + t.test('with valid attestations --json without --include-attestations', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: installWithValidAttestations, + config: { + json: true, + }, + mocks: { + pacote: t.mock('pacote', { + [pacoteSigstore]: { verify: async () => true }, + }), + }, + }) + const registry = new MockRegistry({ tap: t, registry: npm.config.get('registry') }) + await manifestWithValidAttestations({ registry }) + const fixture = fs.readFileSync( + path.resolve(__dirname, '../../fixtures/sigstore/valid-sigstore-attestations.json'), + 'utf8' + ) + registry.nock.get('/-/npm/v1/attestations/sigstore@1.0.0').reply(200, fixture) + mockTUF({ npm, target: TUF_VALID_KEYS_TARGET }) + + await npm.exec('audit', ['signatures']) + + t.notOk(process.exitCode, 'should exit successfully') + const jsonOutput = JSON.parse(joinedOutput()) + t.notOk(jsonOutput.verified, 'should not include verified array') + }) + + t.test('with keyless attestations and no registry keys', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: installWithValidAttestations, + mocks: { + pacote: t.mock('pacote', { + [pacoteSigstore]: { verify: async () => true }, + }), + }, + }) + const registry = new MockRegistry({ tap: t, registry: npm.config.get('registry') }) + const manifest = registry.manifest({ + name: 'sigstore', + packuments: [{ + version: '1.0.0', + dist: { + integrity: 'sha512-e+qfbn/zf1+rCza/BhIA//Awmf0v1pa5HQS8Xk8iXrn9bgytytVLqYD' + + '0P7NSqZ6IELTgq+tcDvLPkQjNHyWLNg==', + tarball: 'https://registry.npmjs.org/sigstore/-/sigstore-1.0.0.tgz', + attestations: { + url: 'https://registry.npmjs.org/-/npm/v1/attestations/sigstore@1.0.0', + provenance: { predicateType: 'https://slsa.dev/provenance/v0.2' }, + }, + }, + }], + }) + await registry.package({ manifest }) + const fixture = fs.readFileSync( + path.resolve(__dirname, '../../fixtures/sigstore/keyless-sigstore-attestations.json'), + 'utf8' + ) + registry.nock.get('/-/npm/v1/attestations/sigstore@1.0.0').reply(200, JSON.parse(fixture)) + // TUF returns no keys and the keys endpoint returns 404 + mockTUF({ npm, target: TUF_TARGET_NOT_FOUND }) + registry.nock.get('/-/npm/v1/keys').reply(404) + + await npm.exec('audit', ['signatures']) + + t.notOk(process.exitCode, 'should exit successfully') + t.match(joinedOutput(), /1 package has a verified attestation/) + }) + t.test('with multiple valid attestations', async t => { const { npm, joinedOutput } = await loadMockNpm(t, { prefixDir: installWithMultipleValidAttestations, mocks: { pacote: t.mock('pacote', { - sigstore: { verify: async () => true }, + [pacoteSigstore]: { verify: async () => true }, }), }, }) @@ -1941,7 +2126,7 @@ t.test('audit signatures', async t => { prefixDir: installWithValidAttestations, mocks: { pacote: t.mock('pacote', { - sigstore: { + [pacoteSigstore]: { verify: async () => { throw new Error(`artifact signature verification failed`) }, @@ -1976,7 +2161,7 @@ t.test('audit signatures', async t => { }, mocks: { pacote: t.mock('pacote', { - sigstore: { + [pacoteSigstore]: { verify: async () => { throw new Error(`artifact signature verification failed`) }, @@ -2005,7 +2190,7 @@ t.test('audit signatures', async t => { prefixDir: installWithMultipleValidAttestations, mocks: { pacote: t.mock('pacote', { - sigstore: { + [pacoteSigstore]: { verify: async () => { throw new Error(`artifact signature verification failed`) }, @@ -2160,3 +2345,31 @@ t.test('audit signatures', async t => { }) }) }) + +t.test('audit fix threads allowScripts policy through to arborist', async t => { + let capturedOpts + const FakeArborist = function (opts) { + capturedOpts = opts + this.options = opts + this.actualTree = { inventory: new Map() } + this.auditReport = {} + } + FakeArborist.prototype.audit = async () => {} + + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + allowScripts: { canvas: true }, + }), + }, + mocks: { + '@npmcli/arborist': FakeArborist, + '{LIB}/utils/reify-finish.js': async () => {}, + }, + }) + await npm.exec('audit', ['fix']) + t.strictSame(capturedOpts.allowScripts, { canvas: true }, + 'opts.allowScripts populated from package.json') +}) diff --git a/test/lib/commands/cache.js b/test/lib/commands/cache.js index 538a8c761a2d1..dc4b0388f9df8 100644 --- a/test/lib/commands/cache.js +++ b/test/lib/commands/cache.js @@ -5,11 +5,26 @@ const MockRegistry = require('@npmcli/mock-registry') const cacache = require('cacache') const fs = require('node:fs') const path = require('node:path') +const { cleanCwd } = require('../../fixtures/clean-snapshot.js') const pkg = 'test-package' +const createNpxCacheEntry = (npxCacheDir, hash, pkgJson, lockJson) => { + fs.mkdirSync(path.join(npxCacheDir, hash)) + fs.writeFileSync( + path.join(npxCacheDir, hash, 'package.json'), + JSON.stringify(pkgJson) + ) + if (lockJson) { + fs.writeFileSync( + path.join(npxCacheDir, hash, 'package-lock.json'), + JSON.stringify(lockJson) + ) + } +} + t.cleanSnapshot = str => { - return str + return cleanCwd(str) .replace(/Finished in [0-9.s]+/g, 'Finished in xxxs') .replace(/Cache verified and compressed (.*)/, 'Cache verified and compressed ({PATH})') } @@ -78,9 +93,7 @@ t.test('cache add single pkg', async t => { }) await npm.exec('cache', ['add', pkg]) t.equal(joinedOutput(), '') - // eslint-disable-next-line max-len t.resolves(cacache.get(cache, 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package/-/test-package-1.0.0.tgz')) - // eslint-disable-next-line max-len t.resolves(cacache.get(cache, 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package')) }) @@ -113,20 +126,15 @@ t.test('cache add multiple pkgs', async t => { }) await npm.exec('cache', ['add', pkg, pkg2]) t.equal(joinedOutput(), '') - // eslint-disable-next-line max-len t.resolves(cacache.get(cache, 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package/-/test-package-1.0.0.tgz')) - // eslint-disable-next-line max-len t.resolves(cacache.get(cache, 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package')) - // eslint-disable-next-line max-len t.resolves(cacache.get(cache, 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package-two/-/test-package-two-1.0.0.tgz')) - // eslint-disable-next-line max-len t.resolves(cacache.get(cache, 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package-two')) }) t.test('cache ls', async t => { const keys = [ 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package', - // eslint-disable-next-line max-len 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package/-/test-package-1.0.0.tgz', ] const { npm, joinedOutput } = await loadMockNpm(t) @@ -204,10 +212,8 @@ t.test('cache ls tagged', async t => { t.test('cache ls scoped and scoped slash', async t => { const keys = [ - // eslint-disable-next-line max-len 'make-fetch-happen:request-cache:https://registry.npmjs.org/@fritzy/staydown/-/@fritzy/staydown-3.1.1.tgz', 'make-fetch-happen:request-cache:https://registry.npmjs.org/@fritzy%2fstaydown', - // eslint-disable-next-line max-len 'make-fetch-happen:request-cache:https://registry.npmjs.org/@gar/npm-expansion/-/@gar/npm-expansion-2.1.0.tgz', 'make-fetch-happen:request-cache:https://registry.npmjs.org/@gar%2fnpm-expansion', ] @@ -248,16 +254,11 @@ t.test('cache ls missing packument version not an object', async t => { t.test('cache rm', async t => { const { npm, joinedOutput } = await loadMockNpm(t) const cache = path.join(npm.cache, '_cacache') - // eslint-disable-next-line max-len await cacache.put(cache, 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package', '{}') - // eslint-disable-next-line max-len await cacache.put(cache, 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package/-/test-package-1.0.0.tgz', 'test data') - // eslint-disable-next-line max-len await npm.exec('cache', ['rm', 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package/-/test-package-1.0.0.tgz']) t.matchSnapshot(joinedOutput(), 'logs deleting single entry') - // eslint-disable-next-line max-len t.resolves(cacache.get(cache, 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package')) - // eslint-disable-next-line max-len t.rejects(cacache.get(cache, 'make-fetch-happen:request-cache:https://registry.npmjs.org/test-package/-/test-package-1.0.0.tgz')) }) @@ -324,3 +325,393 @@ t.test('cache completion', async t => { testComp(['npm', 'cache', 'verify'], []), ]) }) + +t.test('cache npx ls: empty cache', async t => { + const { npm, joinedOutput } = await loadMockNpm(t) + await npm.exec('cache', ['npx', 'ls']) + t.matchSnapshot(joinedOutput(), 'logs message for empty npx cache') +}) + +t.test('cache npx ls: some entries', async t => { + const { npm, joinedOutput } = await loadMockNpm(t) + const npxCacheDir = path.join(npm.flatOptions.npxCache || path.join(npm.cache, '..', '_npx')) + fs.mkdirSync(npxCacheDir, { recursive: true }) + + // Make two fake entries: one valid, one invalid + const hash1 = 'abc123' + const hash2 = 'z9y8x7' + fs.mkdirSync(path.join(npxCacheDir, hash1)) + fs.writeFileSync( + path.join(npxCacheDir, hash1, 'package.json'), + JSON.stringify({ + name: 'fake-npx-package', + version: '1.0.0', + _npx: { packages: ['fake-npx-package@1.0.0'] }, + }) + ) + // invalid (missing or broken package.json) directory + fs.mkdirSync(path.join(npxCacheDir, hash2)) + + await npm.exec('cache', ['npx', 'ls']) + t.matchSnapshot(joinedOutput(), 'lists one valid and one invalid entry') +}) + +t.test('cache npx info: valid and invalid entry', async t => { + const { npm, joinedOutput } = await loadMockNpm(t) + const npxCacheDir = path.join(npm.flatOptions.npxCache || path.join(npm.cache, '..', '_npx')) + fs.mkdirSync(npxCacheDir, { recursive: true }) + + const goodHash = 'deadbeef' + fs.mkdirSync(path.join(npxCacheDir, goodHash)) + fs.writeFileSync( + path.join(npxCacheDir, goodHash, 'package.json'), + JSON.stringify({ + name: 'good-npx-package', + version: '2.0.0', + dependencies: { + rimraf: '^3.0.0', + }, + _npx: { packages: ['good-npx-package@2.0.0'] }, + }) + ) + + const badHash = 'badc0de' + fs.mkdirSync(path.join(npxCacheDir, badHash)) + + await npm.exec('cache', ['npx', 'info', goodHash]) + t.matchSnapshot(joinedOutput(), 'shows valid package info') + + await npm.exec('cache', ['npx', 'info', badHash]) + t.matchSnapshot(joinedOutput(), 'shows invalid package info') +}) + +t.test('cache npx rm: remove single entry', async t => { + const { npm, joinedOutput } = await loadMockNpm(t) + const npxCacheDir = path.join(npm.flatOptions.npxCache || path.join(npm.cache, '..', '_npx')) + fs.mkdirSync(npxCacheDir, { recursive: true }) + + const removableHash = '123removeme' + fs.mkdirSync(path.join(npxCacheDir, removableHash)) + fs.writeFileSync( + path.join(npxCacheDir, removableHash, 'package.json'), + JSON.stringify({ name: 'removable-package', _npx: { packages: ['removable-package@1.0.0'] } }) + ) + + npm.config.set('dry-run', true) + await npm.exec('cache', ['npx', 'rm', removableHash]) + t.ok(fs.existsSync(path.join(npxCacheDir, removableHash)), 'entry folder remains') + npm.config.set('dry-run', false) + + await npm.exec('cache', ['npx', 'rm', removableHash]) + t.matchSnapshot(joinedOutput(), 'logs removing single npx cache entry') + t.notOk(fs.existsSync(path.join(npxCacheDir, removableHash)), 'entry folder removed') +}) + +t.test('cache npx rm: removing all without --force fails', async t => { + const { npm, joinedOutput } = await loadMockNpm(t) + const npxCacheDir = path.join(npm.flatOptions.npxCache || path.join(npm.cache, '..', '_npx')) + fs.mkdirSync(npxCacheDir, { recursive: true }) + + const testHash = 'remove-all-no-force' + fs.mkdirSync(path.join(npxCacheDir, testHash)) + fs.writeFileSync( + path.join(npxCacheDir, testHash, 'package.json'), + JSON.stringify({ name: 'no-force-pkg', _npx: { packages: ['no-force-pkg@1.0.0'] } }) + ) + + await t.rejects( + npm.exec('cache', ['npx', 'rm']), + /Please use --force to remove entire npx cache/, + 'fails without --force' + ) + t.matchSnapshot(joinedOutput(), 'logs usage error when removing all without --force') + + t.ok(fs.existsSync(path.join(npxCacheDir, testHash)), 'folder still exists') +}) + +t.test('cache npx rm: removing all with --force works', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { force: true }, + }) + const npxCacheDir = path.join(npm.flatOptions.npxCache || path.join(npm.cache, '..', '_npx')) + fs.mkdirSync(npxCacheDir, { recursive: true }) + + const testHash = 'remove-all-yes-force' + fs.mkdirSync(path.join(npxCacheDir, testHash)) + fs.writeFileSync( + path.join(npxCacheDir, testHash, 'package.json'), + JSON.stringify({ name: 'yes-force-pkg', _npx: { packages: ['yes-force-pkg@1.0.0'] } }) + ) + + npm.config.set('dry-run', true) + await npm.exec('cache', ['npx', 'rm']) + t.ok(fs.existsSync(npxCacheDir), 'npx cache directory remains') + npm.config.set('dry-run', false) + + await npm.exec('cache', ['npx', 'rm']) + + t.matchSnapshot(joinedOutput(), 'logs removing everything') + t.notOk(fs.existsSync(npxCacheDir), 'npx cache directory removed') +}) + +t.test('cache npx rm: removing more than 1, less than all entries', async t => { + const { npm, joinedOutput } = await loadMockNpm(t) + const npxCacheDir = path.join(npm.flatOptions.npxCache || path.join(npm.cache, '..', '_npx')) + fs.mkdirSync(npxCacheDir, { recursive: true }) + + // Removable folder + const removableHash = '123removeme' + fs.mkdirSync(path.join(npxCacheDir, removableHash)) + fs.writeFileSync( + path.join(npxCacheDir, removableHash, 'package.json'), + JSON.stringify({ name: 'removable-package', _npx: { packages: ['removable-package@1.0.0'] } }) + ) + + // Another Removable folder + const anotherRemovableHash = '456removeme' + fs.mkdirSync(path.join(npxCacheDir, anotherRemovableHash)) + fs.writeFileSync( + path.join(npxCacheDir, anotherRemovableHash, 'package.json'), + JSON.stringify({ name: 'another-removable-package', _npx: { packages: ['another-removable-package@1.0.0'] } }) + ) + + // Another folder that should remain + const keepHash = '999keep' + fs.mkdirSync(path.join(npxCacheDir, keepHash)) + fs.writeFileSync( + path.join(npxCacheDir, keepHash, 'package.json'), + JSON.stringify({ name: 'keep-package', _npx: { packages: ['keep-package@1.0.0'] } }) + ) + + npm.config.set('dry-run', true) + await npm.exec('cache', ['npx', 'rm', removableHash, anotherRemovableHash]) + t.ok(fs.existsSync(path.join(npxCacheDir, removableHash)), 'entry folder remains') + t.ok(fs.existsSync(path.join(npxCacheDir, anotherRemovableHash)), 'entry folder remains') + t.ok(fs.existsSync(path.join(npxCacheDir, keepHash)), 'entry folder remains') + npm.config.set('dry-run', false) + + await npm.exec('cache', ['npx', 'rm', removableHash, anotherRemovableHash]) + t.matchSnapshot(joinedOutput(), 'logs removing 2 of 3 entries') + + t.notOk(fs.existsSync(path.join(npxCacheDir, removableHash)), 'removed folder no longer exists') + t.notOk(fs.existsSync(path.join(npxCacheDir, anotherRemovableHash)), 'the other folder no longer exists') + t.ok(fs.existsSync(path.join(npxCacheDir, keepHash)), 'the other folder remains') +}) + +t.test('cache npx should throw usage error', async t => { + const { npm } = await loadMockNpm(t) + await t.rejects( + npm.exec('cache', ['npx', 'badcommand']), + { code: 'EUSAGE' }, + 'should throw usage error' + ) +}) + +t.test('cache npx should throw usage error for invalid key', async t => { + const { npm } = await loadMockNpm(t) + const npxCacheDir = path.join(npm.flatOptions.npxCache || path.join(npm.cache, '..', '_npx')) + fs.mkdirSync(npxCacheDir, { recursive: true }) + + const key = 'badkey' + await t.rejects( + npm.exec('cache', ['npx', 'rm', key]), + { code: 'EUSAGE' }, + `Invalid npx key ${key}` + ) +}) + +t.test('cache npx ls: entry with unknown package', async t => { + const { npm, joinedOutput } = await loadMockNpm(t) + const npxCacheDir = path.join(npm.flatOptions.npxCache || path.join(npm.cache, '..', '_npx')) + fs.mkdirSync(npxCacheDir, { recursive: true }) + + // Create an entry without the _npx property + const unknownHash = 'unknown123' + fs.mkdirSync(path.join(npxCacheDir, unknownHash)) + fs.writeFileSync( + path.join(npxCacheDir, unknownHash, 'package.json'), + JSON.stringify({ + name: 'unknown-package', + version: '1.0.0', + }) + ) + + await npm.exec('cache', ['npx', 'ls']) + t.matchSnapshot(joinedOutput(), 'lists entry with unknown package') +}) + +t.test('cache npx info: should throw usage error when no keys are provided', async t => { + const { npm } = await loadMockNpm(t) + await t.rejects( + npm.exec('cache', ['npx', 'info']), + { code: 'EUSAGE' }, + 'should throw usage error when no keys are provided' + ) +}) + +t.test('cache npx info: valid entry with _npx packages', async t => { + const { npm, joinedOutput } = await loadMockNpm(t) + const npxCacheDir = path.join(npm.flatOptions.npxCache || path.join(npm.cache, '..', '_npx')) + fs.mkdirSync(npxCacheDir, { recursive: true }) + + const validHash = 'valid123' + createNpxCacheEntry(npxCacheDir, validHash, { + name: 'valid-package', + version: '1.0.0', + _npx: { packages: ['valid-package@1.0.0'] }, + }, { + name: 'valid-package', + version: '1.0.0', + dependencies: { + 'valid-package': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/valid-package/-/valid-package-1.0.0.tgz', + integrity: 'sha512-...', + }, + }, + }) + + const nodeModulesDir = path.join(npxCacheDir, validHash, 'node_modules') + fs.mkdirSync(nodeModulesDir, { recursive: true }) + fs.mkdirSync(path.join(nodeModulesDir, 'valid-package')) + fs.writeFileSync( + path.join(nodeModulesDir, 'valid-package', 'package.json'), + JSON.stringify({ + name: 'valid-package', + version: '1.0.0', + }) + ) + + await npm.exec('cache', ['npx', 'info', validHash]) + t.matchSnapshot(joinedOutput(), 'shows valid package info with _npx packages') +}) + +t.test('cache npx info: valid entry with dependencies', async t => { + const { npm, joinedOutput } = await loadMockNpm(t) + const npxCacheDir = path.join(npm.flatOptions.npxCache || path.join(npm.cache, '..', '_npx')) + fs.mkdirSync(npxCacheDir, { recursive: true }) + + const validHash = 'valid456' + createNpxCacheEntry(npxCacheDir, validHash, { + name: 'valid-package', + version: '1.0.0', + dependencies: { + 'dep-package': '1.0.0', + }, + }, { + name: 'valid-package', + version: '1.0.0', + dependencies: { + 'dep-package': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/dep-package/-/dep-package-1.0.0.tgz', + integrity: 'sha512-...', + }, + }, + }) + + const nodeModulesDir = path.join(npxCacheDir, validHash, 'node_modules') + fs.mkdirSync(nodeModulesDir, { recursive: true }) + fs.mkdirSync(path.join(nodeModulesDir, 'dep-package')) + fs.writeFileSync( + path.join(nodeModulesDir, 'dep-package', 'package.json'), + JSON.stringify({ + name: 'dep-package', + version: '1.0.0', + }) + ) + + await npm.exec('cache', ['npx', 'info', validHash]) + t.matchSnapshot(joinedOutput(), 'shows valid package info with dependencies') +}) + +t.test('cache npx info: valid entry with _npx directory package', async t => { + const { npm, joinedOutput } = await loadMockNpm(t) + const npxCacheDir = path.join(npm.flatOptions.npxCache || path.join(npm.cache, '..', '_npx')) + fs.mkdirSync(npxCacheDir, { recursive: true }) + + const validHash = 'valid123' + createNpxCacheEntry(npxCacheDir, validHash, { + name: 'valid-package', + version: '1.0.0', + _npx: { packages: ['/path/to/valid-package'] }, + }, { + name: 'valid-package', + version: '1.0.0', + dependencies: { + 'valid-package': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/valid-package/-/valid-package-1.0.0.tgz', + integrity: 'sha512-...', + }, + }, + }) + + const nodeModulesDir = path.join(npxCacheDir, validHash, 'node_modules') + fs.mkdirSync(nodeModulesDir, { recursive: true }) + fs.mkdirSync(path.join(nodeModulesDir, 'valid-package')) + fs.writeFileSync( + path.join(nodeModulesDir, 'valid-package', 'package.json'), + JSON.stringify({ + name: 'valid-package', + version: '1.0.0', + }) + ) + + await npm.exec('cache', ['npx', 'info', validHash]) + t.matchSnapshot(joinedOutput(), 'shows valid package info with _npx directory package') +}) + +t.test('cache npx info: valid entry with a link dependency', async t => { + const { npm, joinedOutput } = await loadMockNpm(t) + const npxCacheDir = path.join( + npm.flatOptions.npxCache || path.join(npm.cache, '..', '_npx') + ) + fs.mkdirSync(npxCacheDir, { recursive: true }) + + const validHash = 'link123' + const pkgDir = path.join(npxCacheDir, validHash) + fs.mkdirSync(pkgDir) + + fs.writeFileSync( + path.join(pkgDir, 'package.json'), + JSON.stringify({ + name: 'link-package', + version: '1.0.0', + dependencies: { + 'linked-dep': 'file:./some-other-loc', + }, + }) + ) + + fs.writeFileSync( + path.join(pkgDir, 'package-lock.json'), + JSON.stringify({ + name: 'link-package', + version: '1.0.0', + dependencies: { + 'linked-dep': { + version: 'file:../some-other-loc', + }, + }, + }) + ) + + const nodeModulesDir = path.join(pkgDir, 'node_modules') + fs.mkdirSync(nodeModulesDir, { recursive: true }) + + const linkTarget = path.join(pkgDir, 'some-other-loc') + fs.mkdirSync(linkTarget) + fs.writeFileSync( + path.join(linkTarget, 'package.json'), + JSON.stringify({ name: 'linked-dep', version: '1.0.0' }) + ) + + fs.symlinkSync('../some-other-loc', path.join(nodeModulesDir, 'linked-dep')) + await npm.exec('cache', ['npx', 'info', validHash]) + + t.matchSnapshot( + joinedOutput(), + 'shows link dependency realpath (child.isLink branch)' + ) +}) diff --git a/test/lib/commands/ci.js b/test/lib/commands/ci.js index 8dc0f1d3cc149..a90ca4b0cffe6 100644 --- a/test/lib/commands/ci.js +++ b/test/lib/commands/ci.js @@ -122,6 +122,41 @@ t.test('reifies, audits, removes node_modules on repeat run', async t => { t.equal(fs.existsSync(nmAbbrev), true, 'installs abbrev') }) +t.test('fails when packageExtensions are out of sync with the lock file', async t => { + const { npm } = await loadMockNpm(t, { + config: { audit: false }, + prefixDir: { + abbrev, + // packageExtensions present in package.json but the lock file records no hash + 'package.json': JSON.stringify({ ...packageJson, packageExtensions: {} }), + 'package-lock.json': JSON.stringify(packageLock), + }, + }) + await t.rejects( + npm.exec('ci', []), + /packageExtensions state from lock file/, + 'ci refuses to install with stale packageExtensions state' + ) +}) + +t.test('fails when both .npm-extension files are present', async t => { + const { npm } = await loadMockNpm(t, { + config: { audit: false }, + prefixDir: { + abbrev, + 'package.json': JSON.stringify(packageJson), + 'package-lock.json': JSON.stringify(packageLock), + '.npm-extension.mjs': 'export function transformManifest (p) { return p }\n', + '.npm-extension.cjs': 'module.exports = { transformManifest (p) { return p } }\n', + }, + }) + await t.rejects( + npm.exec('ci', []), + /keep only one/, + 'ci surfaces the ambiguous extension file error' + ) +}) + t.test('--no-audit and --ignore-scripts', async t => { const { npm, joinedOutput, registry } = await loadMockNpm(t, { config: { @@ -150,6 +185,37 @@ t.test('--no-audit and --ignore-scripts', async t => { t.match(joinedOutput(), 'added 1 package in', 'would fail if install script ran') }) +t.test('allow-remote=none blocks same-host tarball outside registry path', async t => { + const token = 'test-path-token' + const registryUrl = 'https://registry.example.com/npm/' + const evilTarball = 'https://registry.example.com/evil/abbrev-1.0.0.tgz' + const lock = JSON.parse(JSON.stringify(packageLock)) + lock.packages['node_modules/abbrev'].resolved = evilTarball + lock.dependencies.abbrev.resolved = evilTarball + + const { npm } = await loadMockNpm(t, { + config: { + audit: false, + 'allow-remote': 'none', + registry: registryUrl, + [`//registry.example.com/npm/:_authToken`]: token, + }, + prefixDir: { + abbrev, + 'package.json': JSON.stringify(packageJson), + 'package-lock.json': JSON.stringify(lock), + }, + }) + + await t.rejects( + npm.exec('ci', []), + { code: 'EALLOWREMOTE' }, + 'sibling-path tarball is blocked by allow-remote=none' + ) + const nmAbbrev = path.join(npm.prefix, 'node_modules', 'abbrev') + t.equal(fs.existsSync(nmAbbrev), false, 'does not install tarball outside configured registry path') +}) + t.test('lifecycle scripts', async t => { const scripts = [] const { npm, registry } = await loadMockNpm(t, { @@ -182,7 +248,116 @@ t.test('lifecycle scripts', async t => { ], 'runs appropriate scripts, in order') }) -t.test('should throw if package-lock.json or npm-shrinkwrap missing', async t => { +// Regression test: `npm ci` must run root `preinstall` before reify populates node_modules, matching `npm install` behavior. +t.test('preinstall runs before reify for npm ci', async t => { + const events = [] + const { npm, registry } = await loadMockNpm(t, { + prefixDir: { + abbrev: abbrev, + 'package.json': JSON.stringify({ + ...packageJson, + scripts: { + preinstall: 'echo preinstall', + postinstall: 'echo postinstall', + }, + }), + 'package-lock.json': JSON.stringify(packageLock), + }, + mocks: { + '@npmcli/run-script': async (opts) => { + if (opts.path === npm.prefix) { + const abbrevPkg = path.join(npm.prefix, 'node_modules', 'abbrev', 'package.json') + events.push({ event: opts.event, depInstalled: fs.existsSync(abbrevPkg) }) + } + }, + }, + }) + const manifest = registry.manifest({ name: 'abbrev' }) + await registry.tarball({ + manifest: manifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'abbrev'), + }) + registry.nock.post('/-/npm/v1/security/advisories/bulk').reply(200, {}) + await npm.exec('ci', []) + + const pre = events.find(e => e.event === 'preinstall') + const post = events.find(e => e.event === 'postinstall') + t.ok(pre, 'preinstall ran') + t.ok(post, 'postinstall ran') + t.equal(pre.depInstalled, false, 'preinstall runs before dependencies are installed') + t.equal(post.depInstalled, true, 'postinstall runs after dependencies are installed') +}) + +// Regression test: --ignore-scripts must suppress the new pre-reify `preinstall` path in `npm ci`, matching the symmetric guarantee in `npm install`. +t.test('--ignore-scripts skips preinstall entirely for npm ci', async t => { + const events = [] + const { npm, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + abbrev: abbrev, + 'package.json': JSON.stringify({ + ...packageJson, + scripts: { + preinstall: 'echo preinstall', + postinstall: 'echo postinstall', + }, + }), + 'package-lock.json': JSON.stringify(packageLock), + }, + mocks: { + '@npmcli/run-script': async (opts) => { + if (opts.path === npm.prefix) { + events.push(opts.event) + } + }, + }, + }) + const manifest = registry.manifest({ name: 'abbrev' }) + await registry.tarball({ + manifest: manifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'abbrev'), + }) + await npm.exec('ci', []) + t.strictSame(events, [], 'no root lifecycle scripts run when --ignore-scripts is set') +}) + +// Regression test: symmetric to the install-side guarantee — a failing root `preinstall` must short-circuit before reify runs in `npm ci`, so dependencies never reach disk on failure. +t.test('a failing preinstall prevents reify for npm ci', async t => { + const events = [] + const { npm } = await loadMockNpm(t, { + prefixDir: { + abbrev: abbrev, + 'package.json': JSON.stringify({ + ...packageJson, + scripts: { + preinstall: 'exit 1', + postinstall: 'echo postinstall', + }, + }), + 'package-lock.json': JSON.stringify(packageLock), + }, + mocks: { + '@npmcli/run-script': async (opts) => { + if (opts.path === npm.prefix) { + events.push(opts.event) + if (opts.event === 'preinstall') { + throw Object.assign(new Error('preinstall failed'), { code: 'ELIFECYCLE' }) + } + } + }, + }, + }) + + await t.rejects(npm.exec('ci', []), /preinstall failed/, 'ci rejects when preinstall fails') + t.strictSame(events, ['preinstall'], 'only preinstall ran; no post-reify scripts') + t.equal( + fs.existsSync(path.join(npm.prefix, 'node_modules', 'abbrev', 'package.json')), + false, + 'no dependency reached disk after preinstall failure' + ) +}) + +t.test('should throw if package-lock.json is missing', async t => { const { npm } = await loadMockNpm(t, { prefixDir: { 'package.json': JSON.stringify(packageJson), @@ -203,6 +378,17 @@ t.test('should throw ECIGLOBAL', async t => { await t.rejects(npm.exec('ci', []), { code: 'ECIGLOBAL' }) }) +t.test('rejects the patch relax flags', async t => { + for (const flag of ['allow-unused-patches', 'ignore-patch-failures']) { + t.test(flag, async t => { + const { npm } = await loadMockNpm(t, { + config: { [flag]: true }, + }) + await t.rejects(npm.exec('ci', []), { code: 'ECIPATCHFLAG' }) + }) + } +}) + t.test('should throw error when ideal inventory mismatches virtual', async t => { const { npm, registry } = await loadMockNpm(t, { prefixDir: { @@ -308,3 +494,142 @@ t.test('should use --workspace flag', async t => { assert.packageMissing('node_modules/abbrev@1.1.0') assert.packageInstalled('node_modules/lodash@1.1.1') }) + +// Issue #8726 - npm ci fails because npm install produces an out-of-sync lockfile +// https://github.com/npm/cli/issues/8726 +// +// Root cause: an optional peerDependency at an exact version causes buildIdealTree() to resolve a different version than what's in the lockfile. +// +// Pattern (mirrors real-world addons-linter / htmlhint / node-fetch scenario): +// - scanner@1.0.0 has optional peerDep: fetcher@1.0.0 (exact version) +// - hint@1.0.0 has regular dep: fetcher@^1.0.0 (semver range) +// - npm install resolves fetcher to 1.1.0 (latest matching ^1.0.0) +// - npm ci's buildIdealTree sees fetcher@1.1.0 doesn't satisfy the exact peerDep "1.0.0", treats it as a problem edge, resolves fetcher to 1.0.0 +// - validateLockfile: lockfile has 1.1.0, ideal tree has 1.0.0 → MISMATCH + +t.test('issue-8726: npm ci with optional peerDep causing lockfile version mismatch', async t => { + // Pre-built lockfile locks fetcher@1.1.0 (what npm install would pick). + // scanner has optional peerDep fetcher@1.0.0 (exact version). + // buildIdealTree should respect the lockfile version, but the bug causes it to resolve fetcher to 1.0.0, failing validateLockfile. + const { npm, registry } = await loadMockNpm(t, { + config: { audit: false, 'ignore-scripts': true }, + strictRegistryNock: false, + prefixDir: { + 'linter-tarball': { + 'package.json': JSON.stringify({ + name: 'linter', + version: '1.0.0', + dependencies: { scanner: '1.0.0' }, + }), + }, + 'scanner-tarball': { + 'package.json': JSON.stringify({ + name: 'scanner', + version: '1.0.0', + peerDependencies: { fetcher: '1.0.0' }, + peerDependenciesMeta: { fetcher: { optional: true } }, + }), + }, + 'hint-tarball': { + 'package.json': JSON.stringify({ + name: 'hint', + version: '1.0.0', + dependencies: { fetcher: '^1.0.0' }, + }), + }, + 'fetcher-1.0.0-tarball': { + 'package.json': JSON.stringify({ name: 'fetcher', version: '1.0.0' }), + }, + 'fetcher-1.1.0-tarball': { + 'package.json': JSON.stringify({ name: 'fetcher', version: '1.1.0' }), + }, + 'package.json': JSON.stringify({ + name: 'test-package', + version: '1.0.0', + devDependencies: { + linter: '1.0.0', + hint: '1.0.0', + }, + }), + 'package-lock.json': JSON.stringify({ + name: 'test-package', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { + name: 'test-package', + version: '1.0.0', + devDependencies: { linter: '1.0.0', hint: '1.0.0' }, + }, + 'node_modules/linter': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/linter/-/linter-1.0.0.tgz', + dev: true, + dependencies: { scanner: '1.0.0' }, + }, + 'node_modules/scanner': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/scanner/-/scanner-1.0.0.tgz', + dev: true, + peerDependencies: { fetcher: '1.0.0' }, + peerDependenciesMeta: { fetcher: { optional: true } }, + }, + 'node_modules/hint': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/hint/-/hint-1.0.0.tgz', + dev: true, + dependencies: { fetcher: '^1.0.0' }, + }, + 'node_modules/fetcher': { + version: '1.1.0', + resolved: 'https://registry.npmjs.org/fetcher/-/fetcher-1.1.0.tgz', + dev: true, + }, + }, + }), + }, + }) + + // With the fix, buildIdealTree no longer treats the invalid peerOptional edge as a problem, so npm ci proceeds to reification and needs tarballs. + const linterManifest = registry.manifest({ name: 'linter' }) + await registry.tarball({ + manifest: linterManifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'linter-tarball'), + }) + + const scannerManifest = registry.manifest({ name: 'scanner' }) + await registry.tarball({ + manifest: scannerManifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'scanner-tarball'), + }) + + const hintManifest = registry.manifest({ name: 'hint' }) + await registry.tarball({ + manifest: hintManifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'hint-tarball'), + }) + + const fetcherManifest = registry.manifest({ + name: 'fetcher', + versions: ['1.0.0', '1.1.0'], + }) + await registry.tarball({ + manifest: fetcherManifest.versions['1.1.0'], + tarball: path.join(npm.prefix, 'fetcher-1.1.0-tarball'), + }) + + // npm ci should succeed - the lockfile is valid and the fix ensures the peerOptional edge doesn't cause a version mismatch. + await npm.exec('ci', []) + + const installedFetcher = JSON.parse( + fs.readFileSync( + path.join(npm.prefix, 'node_modules', 'fetcher', 'package.json'), 'utf8' + ) + ) + t.equal( + installedFetcher.version, + '1.1.0', + 'installed the locked fetcher version, not the peer dep version' + ) +}) diff --git a/test/lib/commands/completion.js b/test/lib/commands/completion.js index e9ed95929fc34..1f07f651296db 100644 --- a/test/lib/commands/completion.js +++ b/test/lib/commands/completion.js @@ -152,10 +152,10 @@ t.test('completion', async t => { }) t.test('commands with no completion', async t => { - const { outputs, completion } = await loadMockCompletionComp(t, 2, 'npm adduser ') + const { outputs, completion } = await loadMockCompletionComp(t, 2, 'npm whoami ') - // quotes around adduser are to ensure coverage when unescaping commands - await completion.exec(['npm', "'adduser'", '']) + // quotes around whoami are to ensure coverage when unescaping commands + await completion.exec(['npm', "'whoami'", '']) t.matchSnapshot(outputs, 'no results') }) @@ -186,6 +186,141 @@ t.test('completion', async t => { await completion.exec(['npm', '--registry', 'install']) t.matchSnapshot(outputs, 'does not try to complete option arguments in the middle of a command') }) + + // Test custom definition flag that requires a value (non-Boolean) + t.test('completion after custom definition flag requiring value', async t => { + const { outputs, completion } = await loadMockCompletionComp(t, 4, 'npm trust github --file value') + + await completion.exec(['npm', 'trust', 'github', '--file', 'value']) + t.matchSnapshot(outputs, 'custom definition non-Boolean flag handled') + }) + + t.test('trust subcommands', async t => { + const { outputs, completion } = await loadMockCompletionComp(t, 2, 'npm trust ') + + await completion.exec(['npm', 'trust', '']) + t.matchSnapshot(outputs, 'trust subcommands') + }) + + t.test('trust filtered subcommands', async t => { + const { outputs, completion } = await loadMockCompletionComp(t, 2, 'npm trust g') + + await completion.exec(['npm', 'trust', 'g']) + t.matchSnapshot(outputs, 'trust filtered subcommands') + }) + + t.test('trust github flags', async t => { + const { outputs, completion } = await loadMockCompletionComp(t, 3, 'npm trust github --re') + + await completion.exec(['npm', 'trust', 'github', '--re']) + t.matchSnapshot(outputs, 'trust github flags with custom definitions') + }) + + t.test('trust gitlab flags', async t => { + const { outputs, completion } = await loadMockCompletionComp(t, 3, 'npm trust gitlab --pro') + + await completion.exec(['npm', 'trust', 'gitlab', '--pro']) + t.matchSnapshot(outputs, 'trust gitlab flags with custom definitions') + }) + + // Test to ensure custom definition aliases are recognized + t.test('custom definition with alias', async t => { + const { completion } = await loadMockCompletionComp(t, 3, 'npm trust github --repo') + await completion.exec(['npm', 'trust', 'github', '--repo']) + t.pass('custom alias handled') + }) + + // Test to ensure the code handles undefined word gracefully + t.test('completion with undefined current word', async t => { + const { completion } = await loadMockCompletion(t, { + globals: { + 'process.env.COMP_CWORD': '3', + 'process.env.COMP_LINE': 'npm trust github ', + 'process.env.COMP_POINT': '19', + }, + }) + await completion.exec(['npm', 'trust', 'github']) + t.pass('undefined word handled') + }) + + // Test custom definition Boolean type checking (covers isFlag with custom defs) + t.test('completion after Boolean flag from custom definitions', async t => { + const { completion } = await loadMockCompletionComp(t, 4, 'npm trust github --yes ') + await completion.exec(['npm', 'trust', 'github', '--yes', '']) + t.pass('Boolean custom definition handled') + }) + + // Test custom definition non-Boolean type (requires value) + t.test('completion after non-Boolean custom definition flag', async t => { + const { completion } = await loadMockCompletionComp(t, 4, 'npm trust github --file ') + await completion.exec(['npm', 'trust', 'github', '--file', '']) + t.pass('non-Boolean custom definition handled') + }) + + // Test to trigger isFlag with custom definition alias + t.test('completion after custom definition flag with alias', async t => { + const { completion } = await loadMockCompletionComp(t, 4, 'npm trust github --repo ') + await completion.exec(['npm', 'trust', 'github', '--repo', '']) + t.pass('custom definition alias handled in isFlag') + }) + + // Test to cover shorthand fallback in isFlag (line 345) + t.test('completion with unknown flag', async t => { + const { completion } = await loadMockCompletionComp(t, 3, 'npm install --unknown ') + await completion.exec(['npm', 'install', '--unknown', '']) + t.pass('unknown flag handled via shorthand fallback') + }) + + // Test to cover line 110 - cursor in middle of word + t.test('completion with cursor in middle of word', async t => { + const { completion } = await loadMockCompletion(t, { + globals: { + 'process.env.COMP_CWORD': '1', + 'process.env.COMP_LINE': 'npm install', + 'process.env.COMP_POINT': '7', // cursor after "npm ins" + }, + }) + await completion.exec(['npm', 'ins']) + t.pass('cursor in middle of word handled') + }) + + // Test to cover line 110 - with escaped/quoted word + t.test('completion with escaped word', async t => { + const { completion } = await loadMockCompletion(t, { + globals: { + 'process.env.COMP_CWORD': '1', + 'process.env.COMP_LINE': 'npm inst', + 'process.env.COMP_POINT': '8', // cursor after "npm inst" + }, + }) + await completion.exec(['npm', 'install']) // args has full word but COMP_LINE is partial + t.pass('escaped word handled') + }) + + // Test to cover line 261 - command with definitions (not subcommand) + t.test('completion for command with definitions', async t => { + const { completion } = await loadMockCompletionComp(t, 2, 'npm completion --') + await completion.exec(['npm', 'completion', '--']) + t.pass('command with definitions handled') + }) + + // Test to cover line 141 - false branch where '--' IS in partialWords + t.test('completion with double-dash escape in command line', async t => { + // This tests the false branch at line 141 where partialWords contains '--' + // The '--' escape prevents flag completion + // COMP_CWORD should point to the word AFTER '--' + const { outputs, completion } = await loadMockCompletionComp(t, 3, 'npm install -- pkg') + await completion.exec(['npm', 'install', '--', 'pkg']) + t.matchSnapshot(outputs, 'double-dash escape handled') + }) + + // Test to cover line 142 - false branch where word doesn't start with '-' + t.test('completion with non-flag word', async t => { + // Inside the outer if (no '--' in partialWords) but word doesn't start with '-' + const { outputs, completion } = await loadMockCompletionComp(t, 2, 'npm install pack') + await completion.exec(['npm', 'install', 'pack']) + t.matchSnapshot(outputs, 'non-flag word completion') + }) }) t.test('windows without bash', async t => { diff --git a/test/lib/commands/config.js b/test/lib/commands/config.js index 849f832554aab..1ab9bbae67bd1 100644 --- a/test/lib/commands/config.js +++ b/test/lib/commands/config.js @@ -72,19 +72,17 @@ t.test('config ignores workspaces', async t => { t.test('config list', async t => { const { npm, joinedOutput } = await loadMockNpm(t, { prefixDir: { - '.npmrc': 'projectloaded=yes', + '.npmrc': 'tag=from-project', }, globalPrefixDir: { etc: { - npmrc: 'globalloaded=yes', + npmrc: 'init-license=from-global', }, }, homeDir: { '.npmrc': [ - 'userloaded=yes', - 'auth=bad', + 'init-author-name=from-user', '_auth=bad', - '//nerfdart:auth=bad', '//nerfdart:_auth=bad', ].join('\n'), }, @@ -94,25 +92,68 @@ t.test('config list', async t => { const output = joinedOutput() - t.match(output, 'projectloaded = "yes"') - t.match(output, 'globalloaded = "yes"') - t.match(output, 'userloaded = "yes"') + t.match(output, 'tag = "from-project"') + t.match(output, 'init-license = "from-global"') + t.match(output, 'init-author-name = "from-user"') t.matchSnapshot(output, 'output matches snapshot') }) +t.test('config list with proxy environment variables', async t => { + const originalHTTP = process.env.HTTP_PROXY + const originalHTTPS = process.env.HTTPS_PROXY + const originalNO = process.env.NO_PROXY + + t.teardown(() => { + if (originalHTTP !== undefined) { + process.env.HTTP_PROXY = originalHTTP + } else { + delete process.env.HTTP_PROXY + } + if (originalHTTPS !== undefined) { + process.env.HTTPS_PROXY = originalHTTPS + } else { + delete process.env.HTTPS_PROXY + } + if (originalNO !== undefined) { + process.env.NO_PROXY = originalNO + } else { + delete process.env.NO_PROXY + } + }) + + process.env.HTTP_PROXY = 'http://proxy.example.com:8080' + process.env.HTTPS_PROXY = 'https://secure-proxy.example.com:8443' + process.env.NO_PROXY = 'localhost,127.0.0.1' + + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + '.npmrc': 'tag=value', + }, + }) + + await npm.exec('config', ['list']) + + const output = joinedOutput() + + t.match(output, 'HTTP_PROXY = "http://proxy.example.com:8080"') + t.match(output, 'HTTPS_PROXY = "https://secure-proxy.example.com:8443"') + t.match(output, 'NO_PROXY = "localhost,127.0.0.1"') + t.match(output, 'environment-related config') +}) + t.test('config list --long', async t => { const { npm, joinedOutput } = await loadMockNpm(t, { prefixDir: { - '.npmrc': 'projectloaded=yes', + '.npmrc': 'tag=from-project', }, globalPrefixDir: { etc: { - npmrc: 'globalloaded=yes', + npmrc: 'init-license=from-global', }, }, homeDir: { - '.npmrc': 'userloaded=yes', + '.npmrc': 'init-author-name=from-user', }, config: { long: true, @@ -123,9 +164,9 @@ t.test('config list --long', async t => { const output = joinedOutput() - t.match(output, 'projectloaded = "yes"') - t.match(output, 'globalloaded = "yes"') - t.match(output, 'userloaded = "yes"') + t.match(output, 'tag = "from-project"') + t.match(output, 'init-license = "from-global"') + t.match(output, 'init-author-name = "from-user"') t.matchSnapshot(output, 'output matches snapshot') }) @@ -133,15 +174,15 @@ t.test('config list --long', async t => { t.test('config list --json', async t => { const { npm, joinedOutput } = await loadMockNpm(t, { prefixDir: { - '.npmrc': 'projectloaded=yes', + '.npmrc': 'tag=from-project', }, globalPrefixDir: { etc: { - npmrc: 'globalloaded=yes', + npmrc: 'init-license=from-global', }, }, homeDir: { - '.npmrc': 'userloaded=yes', + '.npmrc': 'init-author-name=from-user', }, config: { json: true, @@ -152,9 +193,9 @@ t.test('config list --json', async t => { const output = joinedOutput() - t.match(output, '"projectloaded": "yes",') - t.match(output, '"globalloaded": "yes",') - t.match(output, '"userloaded": "yes",') + t.match(output, '"tag": "from-project"') + t.match(output, '"init-license": "from-global"') + t.match(output, '"init-author-name": "from-user"') t.matchSnapshot(output, 'output matches snapshot') }) @@ -164,8 +205,9 @@ t.test('config list with publishConfig', async t => { prefixDir: { 'package.json': JSON.stringify({ publishConfig: { + other: 'not defined', registry: 'https://some.registry', - _authToken: 'mytoken', + '//some.registry:_authToken': 'mytoken', }, }), }, @@ -173,7 +215,7 @@ t.test('config list with publishConfig', async t => { }) t.test('local', async t => { - const { npm, joinedOutput } = await loadMockNpmWithPublishConfig(t) + const { npm, logs, joinedOutput } = await loadMockNpmWithPublishConfig(t) await npm.exec('config', ['list']) @@ -182,6 +224,7 @@ t.test('config list with publishConfig', async t => { t.match(output, 'registry = "https://some.registry"') t.matchSnapshot(output, 'output matches snapshot') + t.matchSnapshot(logs.warn, 'warns about unknown config') }) t.test('global', async t => { @@ -223,7 +266,7 @@ t.test('config delete single key', async t => { await npm.exec('config', ['delete', 'access']) - t.equal(npm.config.get('access'), null, 'acces should be defaulted') + t.equal(npm.config.get('access'), null, 'access should be defaulted') const contents = await fs.readFile(join(home, '.npmrc'), { encoding: 'utf8' }) const rc = ini.parse(contents) @@ -292,19 +335,11 @@ t.test('config delete key --global', async t => { t.test('config set invalid option', async t => { const { npm } = await loadMockNpm(t) await t.rejects( - npm.exec('config', ['set', 'nonexistantconfigoption', 'something']), + npm.exec('config', ['set', 'nonexistentconfigoption', 'something']), /not a valid npm option/ ) }) -t.test('config set deprecated option', async t => { - const { npm } = await loadMockNpm(t) - await t.rejects( - npm.exec('config', ['set', 'shrinkwrap', 'true']), - /deprecated/ - ) -}) - t.test('config set nerf-darted option', async t => { const { npm } = await loadMockNpm(t) await npm.exec('config', ['set', '//npm.pkg.github.com/:_authToken', '0xdeadbeef']) @@ -315,7 +350,7 @@ t.test('config set nerf-darted option', async t => { ) }) -t.test('config set scoped optoin', async t => { +t.test('config set scoped option', async t => { const { npm } = await loadMockNpm(t) await npm.exec('config', ['set', '@npm:registry', 'https://registry.npmjs.org']) t.equal( @@ -532,11 +567,14 @@ t.test('config edit', async t => { homeDir: { '.npmrc': 'foo=bar\nbar=baz', }, - config: { - editor: EDITOR, - }, + npm: { argv: ['config', 'edit', '--editor=' + EDITOR] }, }) + const inputEvents = [] + const inputListener = (level) => inputEvents.push(level) + process.on('input', inputListener) + t.teardown(() => process.off('input', inputListener)) + await npm.exec('config', ['edit']) t.ok(editor.called, 'editor was spawned') @@ -545,6 +583,7 @@ t.test('config edit', async t => { [join(home, '.npmrc')], 'editor opened the user config file' ) + t.same(inputEvents.slice(0, 2), ['start', 'end'], 'progress paused and resumed around editor') const contents = await fs.readFile(join(home, '.npmrc'), { encoding: 'utf8' }) t.ok(contents.includes('foo=bar'), 'kept foo') @@ -600,6 +639,7 @@ t.test('config fix', (t) => { homeDir: { '.npmrc': '_authtoken=thisisinvalid\n_auth=beef', }, + npm: { argv: ['config', 'fix'] }, }) const registry = `//registry.npmjs.org/` @@ -643,6 +683,7 @@ t.test('config fix', (t) => { config: { location: 'user', }, + npm: { argv: ['config', 'fix', '--location=user'] }, }) const registry = `//registry.npmjs.org/` diff --git a/test/lib/commands/dedupe.js b/test/lib/commands/dedupe.js index c94b0b8228cea..22e3f0e2063ea 100644 --- a/test/lib/commands/dedupe.js +++ b/test/lib/commands/dedupe.js @@ -94,3 +94,30 @@ t.test('dedupe', async (t) => { fs.existsSync(path.join(npm.prefix, 'node_modules', 'test-dep-b', 'node_modules', 'test-sub')), 'test-dep-b/test-sub was removed') }) + +t.test('dedupe threads allowScripts policy through to arborist', async t => { + let capturedOpts + const FakeArborist = function (opts) { + capturedOpts = opts + this.options = opts + this.actualTree = { inventory: new Map() } + } + FakeArborist.prototype.dedupe = async () => {} + + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + allowScripts: { canvas: true }, + }), + }, + mocks: { + '@npmcli/arborist': FakeArborist, + '{LIB}/utils/reify-finish.js': async () => {}, + }, + }) + await npm.exec('dedupe', []) + t.strictSame(capturedOpts.allowScripts, { canvas: true }, + 'opts.allowScripts populated from package.json') +}) diff --git a/test/lib/commands/deny-scripts.js b/test/lib/commands/deny-scripts.js new file mode 100644 index 0000000000000..358b71d7da7bd --- /dev/null +++ b/test/lib/commands/deny-scripts.js @@ -0,0 +1,192 @@ +const t = require('tap') +const fs = require('node:fs') +const { resolve } = require('node:path') +const _mockNpm = require('../../fixtures/mock-npm') + +const setupProject = ({ allowScripts, withScripts = ['core-js'] } = {}) => { + const pkg = { + name: 'host', + version: '1.0.0', + dependencies: Object.fromEntries(withScripts.map((n) => [n, '*'])), + } + if (allowScripts !== undefined) { + pkg.allowScripts = allowScripts + } + const lockPackages = { '': pkg } + const nodeModules = {} + for (const name of withScripts) { + nodeModules[name] = { + 'package.json': JSON.stringify({ + name, + version: '1.0.0', + scripts: { install: 'echo install' }, + }), + } + lockPackages[`node_modules/${name}`] = { + version: '1.0.0', + resolved: `https://registry.npmjs.org/${name}/-/${name}-1.0.0.tgz`, + hasInstallScript: true, + } + } + return { + 'package.json': JSON.stringify(pkg, null, 2), + 'package-lock.json': JSON.stringify({ + name: pkg.name, + version: pkg.version, + lockfileVersion: 3, + requires: true, + packages: lockPackages, + }), + node_modules: nodeModules, + } +} + +t.test('deny-scripts writes name-only false entry', async t => { + const { npm, prefix } = await _mockNpm(t, { + prefixDir: setupProject({ withScripts: ['core-js'] }), + }) + await npm.exec('deny-scripts', ['core-js']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'core-js': false }) +}) + +t.test('deny-scripts ignores --pin and always writes name-only', async t => { + const { npm, prefix } = await _mockNpm(t, { + prefixDir: setupProject({ withScripts: ['core-js'] }), + config: { 'allow-scripts-pin': true }, + }) + await npm.exec('deny-scripts', ['core-js']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'core-js': false }) +}) + +t.test('deny-scripts replaces existing pinned allow', async t => { + const { npm, prefix } = await _mockNpm(t, { + prefixDir: setupProject({ + withScripts: ['core-js'], + allowScripts: { 'core-js@1.0.0': true }, + }), + }) + await npm.exec('deny-scripts', ['core-js']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'core-js': false }) +}) + +t.test('deny-scripts --pending is rejected', async t => { + const { npm } = await _mockNpm(t, { + prefixDir: setupProject({ withScripts: ['core-js'] }), + config: { 'allow-scripts-pending': true }, + }) + await t.rejects(npm.exec('deny-scripts', []), { code: 'EUSAGE' }) +}) + +t.test('deny-scripts --all denies every unreviewed package', async t => { + const { npm, prefix } = await _mockNpm(t, { + prefixDir: setupProject({ withScripts: ['core-js', 'telemetry'] }), + config: { all: true }, + }) + await npm.exec('deny-scripts', []) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'core-js': false, telemetry: false }) +}) + +t.test('deny-scripts errors on unknown package', async t => { + const { npm } = await _mockNpm(t, { + prefixDir: setupProject({ withScripts: ['core-js'] }), + }) + await t.rejects( + npm.exec('deny-scripts', ['not-installed']), + { code: 'ENOMATCH' } + ) +}) + +t.test('deny-scripts denies a dotted name with a version specifier', async t => { + const { npm, prefix } = await _mockNpm(t, { + prefixDir: setupProject({ withScripts: ['cordova.plugins.diagnostic'] }), + }) + await npm.exec('deny-scripts', ['cordova.plugins.diagnostic@1.0.0']) + + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'cordova.plugins.diagnostic': false }) +}) + +t.test('deny-scripts requires positional args or --all', async t => { + const { npm } = await _mockNpm(t, { + prefixDir: setupProject({ withScripts: ['core-js'] }), + }) + await t.rejects(npm.exec('deny-scripts', []), { code: 'EUSAGE' }) +}) + +t.test('deny-scripts --all with no unreviewed packages prints message', async t => { + const { npm, joinedOutput } = await _mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'host', version: '1.0.0' }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { '': { name: 'host', version: '1.0.0' } }, + }), + node_modules: {}, + }, + config: { all: true }, + }) + await npm.exec('deny-scripts', []) + t.match(joinedOutput(), /No packages with unreviewed install scripts/) +}) + +t.test('deny-scripts --all --json with no unreviewed emits empty list', async t => { + const { npm, joinedOutput } = await _mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'host', version: '1.0.0' }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { '': { name: 'host', version: '1.0.0' } }, + }), + node_modules: {}, + }, + config: { all: true, json: true }, + }) + await npm.exec('deny-scripts', []) + t.strictSame(JSON.parse(joinedOutput()), { allowScripts: [] }) +}) + +t.test('deny-scripts fails on global', async t => { + const { npm } = await _mockNpm(t, { + config: { global: true }, + }) + await t.rejects(npm.exec('deny-scripts', ['canvas']), { code: 'EGLOBAL' }) +}) + +t.test('deny-scripts on a package already denied is no-op', async t => { + const { npm, joinedOutput, prefix } = await _mockNpm(t, { + prefixDir: setupProject({ + withScripts: ['core-js'], + allowScripts: { 'core-js': false }, + }), + }) + await npm.exec('deny-scripts', ['core-js']) + const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')) + t.strictSame(pkg.allowScripts, { 'core-js': false }) + t.match(joinedOutput(), /Nothing to deny/) +}) + +t.test('deny-scripts --json outputs structured summary', async t => { + const { npm, joinedOutput } = await _mockNpm(t, { + prefixDir: setupProject({ withScripts: ['core-js'] }), + config: { json: true }, + }) + await npm.exec('deny-scripts', ['core-js']) + const parsed = JSON.parse(joinedOutput()) + t.match(parsed, { + allowScripts: [{ name: 'core-js', changes: [{ key: 'core-js', change: 'added' }] }], + }) +}) diff --git a/test/lib/commands/deprecate.js b/test/lib/commands/deprecate.js index 09aaeacfe8563..eda51bfef2895 100644 --- a/test/lib/commands/deprecate.js +++ b/test/lib/commands/deprecate.js @@ -129,7 +129,7 @@ t.test('deprecates given range', async t => { }) t.test('deprecates all versions when no range is specified', async t => { - const { npm, joinedOutput } = await loadMockNpm(t, { config: { ...auth } }) + const { npm, logs, joinedOutput } = await loadMockNpm(t, { config: { ...auth } }) const registry = new MockRegistry({ tap: t, registry: npm.config.get('registry'), @@ -151,6 +151,37 @@ t.test('deprecates all versions when no range is specified', async t => { }).reply(200, {}) await npm.exec('deprecate', ['foo', message]) + t.match(logs.notice, [ + `deprecating foo@1.0.0 with message "${message}"`, + `deprecating foo@1.0.1 with message "${message}"`, + `deprecating foo@1.0.1-pre with message "${message}"`, + ]) + t.match(joinedOutput(), '') +}) + +t.test('dry-run', async t => { + const { npm, logs, joinedOutput } = await loadMockNpm(t, { config: { + 'dry-run': true, + ...auth, + } }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + const manifest = registry.manifest({ + name: 'foo', + versions, + }) + await registry.package({ manifest, query: { write: true } }) + const message = 'test deprecation message' + + await npm.exec('deprecate', ['foo', message]) + t.match(logs.notice, [ + `deprecating foo@1.0.0 with message "${message}"`, + `deprecating foo@1.0.1 with message "${message}"`, + `deprecating foo@1.0.1-pre with message "${message}"`, + ]) t.match(joinedOutput(), '') }) diff --git a/test/lib/commands/diff.js b/test/lib/commands/diff.js index 3d55cd7879b7a..0e30ac9b71cec 100644 --- a/test/lib/commands/diff.js +++ b/test/lib/commands/diff.js @@ -943,11 +943,11 @@ t.test('various options', async t => { t.test('using diff option', async t => { const { output } = await mockOptions(t, { - 'diff-context': 5, - 'diff-ignore-whitespace': true, + 'diff-unified': 5, + 'diff-ignore-all-space': true, 'diff-no-prefix': false, - 'diff-drc-prefix': 'foo/', - 'diff-fst-prefix': 'bar/', + 'diff-dst-prefix': 'foo/', + 'diff-src-prefix': 'bar/', 'diff-text': true, }) diff --git a/test/lib/commands/doctor.js b/test/lib/commands/doctor.js index 0c58a09e20c57..659b465a25a60 100644 --- a/test/lib/commands/doctor.js +++ b/test/lib/commands/doctor.js @@ -89,7 +89,7 @@ t.test('all clear', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -108,7 +108,7 @@ t.test('all clear in color', async t => { }, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -127,7 +127,7 @@ t.test('silent success', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -146,7 +146,7 @@ t.test('silent errors', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(404, '{}') + .get('/-/ping').reply(404, '{}') await t.rejects(npm.exec('doctor', ['ping']), { message: /Check logs/, }) @@ -161,7 +161,7 @@ t.test('ping 404', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(404, '{}') + .get('/-/ping').reply(404, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -182,7 +182,7 @@ t.test('ping 404 in color', async t => { }, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(404, '{}') + .get('/-/ping').reply(404, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -198,7 +198,7 @@ t.test('ping exception with code', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').replyWithError({ message: 'Test Error', code: 'TEST' }) + .get('/-/ping').replyWithError(Object.assign(new Error('Test Error'), { code: 'TEST' })) .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -214,7 +214,7 @@ t.test('ping exception without code', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').replyWithError({ message: 'Test Error', code: false }) + .get('/-/ping').replyWithError(Object.assign(new Error('Test Error'), { code: false })) .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -230,7 +230,7 @@ t.test('npm out of date', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest('2.0.0')) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -255,7 +255,7 @@ t.test('node out of date - lts', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -280,7 +280,7 @@ t.test('node out of date - current', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -297,7 +297,7 @@ t.test('non-default registry', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -318,7 +318,7 @@ t.test('missing git', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -344,7 +344,7 @@ t.test('windows skips permissions checks', async t => { globalPrefixDir: {}, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -361,7 +361,7 @@ t.test('missing global directories', async t => { globalPrefixDir: {}, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -377,7 +377,7 @@ t.test('missing local node_modules', async t => { globalPrefixDir: dirs.globalPrefixDir, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -406,7 +406,7 @@ t.test('incorrect owner', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -430,7 +430,7 @@ t.test('incorrect permissions', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -458,7 +458,7 @@ t.test('error reading directory', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -481,7 +481,7 @@ t.test('cacache badContent', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -504,7 +504,7 @@ t.test('cacache reclaimedCount', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -527,7 +527,7 @@ t.test('cacache missingContent', async t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') .get('/npm').reply(200, npmManifest(npm.version)) tnock(t, 'https://nodejs.org') .get('/dist/index.json').reply(200, nodeVersions) @@ -558,7 +558,7 @@ t.test('discrete checks', t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') await npm.exec('doctor', ['ping']) t.matchSnapshot(joinedOutput(), 'output') t.matchSnapshot({ info: logs.info, warn: logs.warn, error: logs.error }, 'logs') @@ -586,7 +586,7 @@ t.test('discrete checks', t => { ...dirs, }) tnock(t, npm.config.get('registry')) - .get('/-/ping?write=true').reply(200, '{}') + .get('/-/ping').reply(200, '{}') await npm.exec('doctor', ['registry']) t.matchSnapshot(joinedOutput(), 'output') t.matchSnapshot({ info: logs.info, warn: logs.warn, error: logs.error }, 'logs') diff --git a/test/lib/commands/edit.js b/test/lib/commands/edit.js index ae6826f7f98ad..167b77a674ce1 100644 --- a/test/lib/commands/edit.js +++ b/test/lib/commands/edit.js @@ -3,11 +3,30 @@ const path = require('node:path') const tspawk = require('../../fixtures/tspawk') const { load: loadMockNpm } = require('../../fixtures/mock-npm') +t.test('completion', async t => { + const { edit } = await loadMockNpm(t, { + command: 'edit', + prefixDir: { + node_modules: { + foo: {}, + bar: {}, + }, + }, + }) + const res = await edit.completion({ conf: { argv: { remain: ['npm', 'edit'] } } }) + t.match(res, ['bar', 'foo']) +}) + const spawk = tspawk(t) const npmConfig = { config: { 'ignore-scripts': false, + // Phase 2 gates dependency install scripts by default. `npm edit` + // rebuilds the edited package via `npm rebuild`, which honors the + // allowScripts gate, so opt every script in for these tests to exercise + // the editor -> rebuild -> install-script flow. + 'dangerously-allow-all-scripts': true, editor: 'testeditor', 'script-shell': process.platform === 'win32' ? process.env.COMSPEC : 'sh', }, @@ -44,8 +63,14 @@ t.test('npm edit', async t => { : ['-c', 'testinstall'] spawk.spawn(scriptShell, scriptArgs, { cwd: semverPath }) + const inputEvents = [] + const inputListener = (level) => inputEvents.push(level) + process.on('input', inputListener) + t.teardown(() => process.off('input', inputListener)) + await npm.exec('edit', ['semver']) t.match(joinedOutput(), 'rebuilt dependencies successfully') + t.same(inputEvents.slice(0, 2), ['start', 'end'], 'progress paused and resumed around editor') }) t.test('rebuild failure', async t => { diff --git a/test/lib/commands/exec.js b/test/lib/commands/exec.js index c2977a2f577cb..30d8c2c046c37 100644 --- a/test/lib/commands/exec.js +++ b/test/lib/commands/exec.js @@ -254,3 +254,118 @@ t.test('npx --no-install @npmcli/npx-test', async t => { ) } }) + +t.test('packs from git spec', async t => { + const spec = 'test/test#111111aaaaaaaabbbbbbbbccccccdddddddeeeee' + const pkgPath = path.resolve(__dirname, '../../fixtures/git-test.tgz') + + const srv = MockRegistry.tnock(t, 'https://codeload.github.com') + srv.get('/test/test/tar.gz/111111aaaaaaaabbbbbbbbccccccdddddddeeeee') + .times(2) + .reply(200, await fs.readFile(pkgPath)) + + const { npm } = await loadMockNpm(t, { + config: { + audit: false, + yes: true, + 'allow-git': 'all', + }, + }) + try { + await npm.exec('exec', [spec]) + const exists = await fs.stat(path.join(npm.prefix, 'npm-exec-test-success')) + t.ok(exists.isFile(), 'bin ran, creating file') + } catch (err) { + t.fail(err, 'should not throw') + } +}) + +t.test('can run packages with keywords', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: '@npmcli/npx-package-test', + bin: { select: 'index.js' }, + }), + 'index.js': `#!/usr/bin/env node + require('fs').writeFileSync('npm-exec-test-success', (process.argv.length).toString())`, + }, + }) + + try { + await npm.exec('exec', ['select']) + + const testFilePath = path.join(npm.prefix, 'npm-exec-test-success') + const exists = await fs.stat(testFilePath) + t.ok(exists.isFile(), 'bin ran, creating file') + const noExtraArgumentCount = await fs.readFile(testFilePath, 'utf8') + t.equal(+noExtraArgumentCount, 2, 'should have no extra arguments') + } catch (err) { + t.fail(err, 'should not throw') + } +}) + +t.test('exec threads allowScripts policy from .npmrc through to libexec', async t => { + let capturedOpts + const fakeLibexec = async (opts) => { + capturedOpts = opts + } + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'host', version: '1.0.0' }), + '.npmrc': 'allow-scripts = canvas', + }, + mocks: { + libnpmexec: fakeLibexec, + }, + }) + await npm.exec('exec', ['some-pkg']) + t.strictSame(capturedOpts.allowScripts, { canvas: true }, + 'allowScripts populated from .npmrc layer') +}) + +t.test('exec ignores project package.json#allowScripts (RFC: .npmrc-only)', async t => { + // Per RFC line 299, exec/npx consults only user/global .npmrc. Project + // package.json policy must NOT influence npx behaviour, even when the + // user is running npx inside a project that has its own allowScripts. + let capturedOpts + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + allowScripts: { sharp: true }, + }), + }, + mocks: { + libnpmexec: async (opts) => { + capturedOpts = opts + }, + }, + }) + await npm.exec('exec', ['some-pkg']) + // package.json policy is skipped; no other layer has policy; result is null. + t.equal(capturedOpts.allowScripts, null) +}) + +t.test('exec reads .npmrc policy even when project package.json has a different policy', async t => { + // .npmrc-tier policy wins because package.json is skipped entirely. + let capturedOpts + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + allowScripts: { sharp: true }, + }), + '.npmrc': 'allow-scripts = canvas', + }, + mocks: { + libnpmexec: async (opts) => { + capturedOpts = opts + }, + }, + }) + await npm.exec('exec', ['some-pkg']) + t.strictSame(capturedOpts.allowScripts, { canvas: true }) +}) diff --git a/test/lib/commands/explain.js b/test/lib/commands/explain.js index b55371c8b7e5c..d702019e9202a 100644 --- a/test/lib/commands/explain.js +++ b/test/lib/commands/explain.js @@ -2,6 +2,22 @@ const t = require('tap') const { resolve } = require('node:path') const mockNpm = require('../../fixtures/mock-npm.js') +t.test('completion', async t => { + const { explain } = await mockNpm(t, { + command: 'explain', + prefixDir: { + node_modules: { + foo: { + 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }), + }, + }, + 'package.json': JSON.stringify({ name: 'project', version: '1.0.0' }), + }, + }) + const res = await explain.completion({ conf: { argv: { remain: ['npm', 'explain'] } } }) + t.type(res, Array) +}) + const mockExplain = async (t, opts) => { const mock = await mockNpm(t, { command: 'explain', diff --git a/test/lib/commands/explore.js b/test/lib/commands/explore.js index 6988dca90fbfb..b40de9817bff6 100644 --- a/test/lib/commands/explore.js +++ b/test/lib/commands/explore.js @@ -2,6 +2,20 @@ const t = require('tap') const mockNpm = require('../../fixtures/mock-npm') const { cleanCwd } = require('../../fixtures/clean-snapshot') +t.test('completion', async t => { + const { explore } = await mockNpm(t, { + command: 'explore', + prefixDir: { + node_modules: { + foo: {}, + bar: {}, + }, + }, + }) + const res = await explore.completion({ conf: { argv: { remain: ['npm', 'explore'] } } }) + t.match(res, ['bar', 'foo']) +}) + const mockExplore = async (t, exec, { PJ_ERROR = null, RUN_SCRIPT_ERROR = null, diff --git a/test/lib/commands/fund.js b/test/lib/commands/fund.js index 277190e7a1a48..95521fb6da650 100644 --- a/test/lib/commands/fund.js +++ b/test/lib/commands/fund.js @@ -1,6 +1,22 @@ const t = require('tap') const mockNpm = require('../../fixtures/mock-npm') +t.test('completion', async t => { + const { fund } = await mockNpm(t, { + command: 'fund', + prefixDir: { + node_modules: { + foo: { + 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }), + }, + }, + 'package.json': JSON.stringify({ name: 'project', version: '1.0.0' }), + }, + }) + const res = await fund.completion({ conf: { argv: { remain: ['npm', 'fund'] } } }) + t.type(res, Array) +}) + const version = '1.0.0' const funding = { diff --git a/test/lib/commands/get.js b/test/lib/commands/get.js index dec634f835172..6a1db69628217 100644 --- a/test/lib/commands/get.js +++ b/test/lib/commands/get.js @@ -1,6 +1,12 @@ const t = require('tap') const { load: loadMockNpm } = require('../../fixtures/mock-npm') +t.test('completion', async t => { + const { get } = await loadMockNpm(t, { command: 'get' }) + const res = await get.completion({ conf: { argv: { remain: ['npm', 'get'] } } }) + t.type(res, Array) +}) + t.test('should retrieve values from config', async t => { const name = 'editor' const value = 'vigor' diff --git a/test/lib/commands/help-search.js b/test/lib/commands/help-search.js index 354fb0291eb2f..c7f5c444ecb8c 100644 --- a/test/lib/commands/help-search.js +++ b/test/lib/commands/help-search.js @@ -1,14 +1,13 @@ const t = require('tap') const { load: loadMockNpm } = require('../../fixtures/mock-npm.js') -/* eslint-disable max-len */ const docsFixtures = { dir1: { 'npm-exec.md': 'the exec command\nhelp has multiple lines of exec help\none of them references exec', }, dir2: { 'npm-something.md': 'another\ncommand you run\nthat\nreferences exec\nand has multiple lines\nwith no matches\nthat will be ignored\nand another line\nthat does have exec as well', - 'npm-run-script.md': 'the scripted run-script command runs scripts\nand has lines\nsome of which dont match the string run\nor script\nscript', + 'npm-run.md': 'the scripted run command runs scripts\nand has lines\nsome of which dont match the string run\nor script\nscript', 'npm-install.md': 'does a thing in a script\nif a thing does not exist in a thing you run\nto install it and run it maybe in a script', }, dir3: { @@ -19,7 +18,6 @@ const docsFixtures = { 'npm-extra-useless.md': 'exec\nexec\nexec', }, } -/* eslint-enable max-len */ const execHelpSearch = async (t, exec = [], opts) => { const { npm, ...rest } = await loadMockNpm(t, { diff --git a/test/lib/commands/help.js b/test/lib/commands/help.js index 3fda9fb6e07fd..77d05d7b5048c 100644 --- a/test/lib/commands/help.js +++ b/test/lib/commands/help.js @@ -30,7 +30,7 @@ const genManPages = (obj) => { const mockHelp = async (t, { man = { 5: ['npmrc', 'install', 'package-json'], - 1: ['whoami', 'install', 'star', 'unstar', 'uninstall', 'unpublish'].map(p => `npm-${p}`), + 1: ['whoami', 'install', 'uninstall', 'unpublish'].map(p => `npm-${p}`), 7: ['disputes', 'config'], }, browser = false, @@ -153,9 +153,9 @@ t.test('npm help package.json redirects to package-json', async t => { t.match(spawnArgs[0], /package-json\.5$/) }) -t.test('npm help ?(un)star', async t => { +t.test('npm help ?(un)publish with woman', async t => { const { getArgs } = await mockHelp(t, { - exec: ['?(un)star'], + exec: ['?(un)publish'], woman: true, }) @@ -163,7 +163,7 @@ t.test('npm help ?(un)star', async t => { t.equal(spawnBin, 'emacsclient', 'maps woman to emacs correctly') t.equal(spawnArgs.length, 2) t.match(spawnArgs[1], /^\(woman-find-file '/) - t.match(spawnArgs[1], /npm-star.1'\)$/) + t.match(spawnArgs[1], /npm-unpublish.1'\)$/) }) t.test('npm help un*', async t => { diff --git a/test/lib/commands/hook.js b/test/lib/commands/hook.js deleted file mode 100644 index 003dae647a35a..0000000000000 --- a/test/lib/commands/hook.js +++ /dev/null @@ -1,640 +0,0 @@ -const t = require('tap') -const mockNpm = require('../../fixtures/mock-npm') - -const mockHook = async (t, { hookResponse, ...npmOpts } = {}) => { - const now = Date.now() - - let hookArgs = null - - const pkgTypes = { - semver: 'package', - '@npmcli': 'scope', - npm: 'owner', - } - - const libnpmhook = { - add: async (pkg, uri, secret, opts) => { - hookArgs = { pkg, uri, secret, opts } - return { id: 1, name: pkg, type: pkgTypes[pkg], endpoint: uri } - }, - ls: async opts => { - hookArgs = opts - let id = 0 - if (hookResponse) { - return hookResponse - } - - return Object.keys(pkgTypes).map(name => ({ - id: ++id, - name, - type: pkgTypes[name], - endpoint: 'https://google.com', - last_delivery: id % 2 === 0 ? now : undefined, - response_code: 200, - })) - }, - rm: async (id, opts) => { - hookArgs = { id, opts } - const pkg = Object.keys(pkgTypes)[0] - return { - id: 1, - name: pkg, - type: pkgTypes[pkg], - endpoint: 'https://google.com', - } - }, - update: async (id, uri, secret, opts) => { - hookArgs = { id, uri, secret, opts } - const pkg = Object.keys(pkgTypes)[0] - return { id, name: pkg, type: pkgTypes[pkg], endpoint: uri } - }, - } - - const mock = await mockNpm(t, { - ...npmOpts, - command: 'hook', - mocks: { - libnpmhook, - ...npmOpts.mocks, - }, - }) - - return { - ...mock, - now, - hookArgs: () => hookArgs, - } -} - -t.test('npm hook no args', async t => { - const { hook } = await mockHook(t) - await t.rejects(hook.exec([]), hook.usage, 'throws usage with no arguments') -}) - -t.test('npm hook add', async t => { - const { npm, hook, outputs, hookArgs } = await mockHook(t) - await hook.exec(['add', 'semver', 'https://google.com', 'some-secret']) - - t.match( - hookArgs(), - { - pkg: 'semver', - uri: 'https://google.com', - secret: 'some-secret', - opts: npm.flatOptions, - }, - 'provided the correct arguments to libnpmhook' - ) - t.strictSame(outputs[0], '+ semver -> https://google.com', 'prints the correct output') -}) - -t.test('npm hook add - correct owner hook output', async t => { - const { npm, hook, outputs, hookArgs } = await mockHook(t) - await hook.exec(['add', '~npm', 'https://google.com', 'some-secret']) - - t.match( - hookArgs(), - { - pkg: '~npm', - uri: 'https://google.com', - secret: 'some-secret', - opts: npm.flatOptions, - }, - 'provided the correct arguments to libnpmhook' - ) - t.strictSame(outputs[0], '+ ~npm -> https://google.com', 'prints the correct output') -}) - -t.test('npm hook add - correct scope hook output', async t => { - const { npm, hook, outputs, hookArgs } = await mockHook(t) - await hook.exec(['add', '@npmcli', 'https://google.com', 'some-secret']) - - t.match( - hookArgs(), - { - pkg: '@npmcli', - uri: 'https://google.com', - secret: 'some-secret', - opts: npm.flatOptions, - }, - 'provided the correct arguments to libnpmhook' - ) - t.strictSame(outputs[0], '+ @npmcli -> https://google.com', 'prints the correct output') -}) - -t.test('npm hook add - unicode output', async t => { - const config = { - unicode: true, - } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['add', 'semver', 'https://google.com', 'some-secret']) - - t.match( - hookArgs(), - { - pkg: 'semver', - uri: 'https://google.com', - secret: 'some-secret', - opts: npm.flatOptions, - }, - 'provided the correct arguments to libnpmhook' - ) - t.strictSame(outputs[0], '+ semver ➜ https://google.com', 'prints the correct output') -}) - -t.test('npm hook add - json output', async t => { - const config = { - json: true, - } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['add', '@npmcli', 'https://google.com', 'some-secret']) - - t.match( - hookArgs(), - { - pkg: '@npmcli', - uri: 'https://google.com', - secret: 'some-secret', - opts: npm.flatOptions, - }, - 'provided the correct arguments to libnpmhook' - ) - t.strictSame( - JSON.parse(outputs[0]), - { - id: 1, - name: '@npmcli', - endpoint: 'https://google.com', - type: 'scope', - }, - 'prints the correct json output' - ) -}) - -t.test('npm hook add - parseable output', async t => { - const config = { - parseable: true, - } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['add', '@npmcli', 'https://google.com', 'some-secret']) - - t.match( - hookArgs(), - { - pkg: '@npmcli', - uri: 'https://google.com', - secret: 'some-secret', - opts: npm.flatOptions, - }, - 'provided the correct arguments to libnpmhook' - ) - - t.strictSame( - outputs[0].split(/\t/), - ['id', 'name', 'type', 'endpoint'], - 'prints the correct parseable output headers' - ) - t.strictSame( - outputs[1].split(/\t/), - ['1', '@npmcli', 'scope', 'https://google.com'], - 'prints the correct parseable values' - ) -}) - -t.test('npm hook add - silent output', async t => { - const config = { loglevel: 'silent' } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['add', '@npmcli', 'https://google.com', 'some-secret']) - - t.match( - hookArgs(), - { - pkg: '@npmcli', - uri: 'https://google.com', - secret: 'some-secret', - opts: npm.flatOptions, - }, - 'provided the correct arguments to libnpmhook' - ) - t.strictSame(outputs, [], 'printed no output') -}) - -t.test('npm hook ls', async t => { - const { npm, hook, outputs, hookArgs } = await mockHook(t) - await hook.exec(['ls']) - - t.match( - hookArgs(), - { - ...npm.flatOptions, - package: undefined, - }, - 'received the correct arguments' - ) - t.strictSame(outputs, [ - 'You have 3 hooks configured.', - 'Hook 1: semver', - 'Endpoint: https://google.com', - 'Never triggered\n', - 'Hook 2: @npmcli', - 'Endpoint: https://google.com', - 'Triggered just now, response code was "200"\n', - 'Hook 3: ~npm', - 'Endpoint: https://google.com', - 'Never triggered\n', - ]) -}) - -t.test('npm hook ls, no results', async t => { - const hookResponse = [] - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - hookResponse, - }) - - await hook.exec(['ls']) - - t.match( - hookArgs(), - { - ...npm.flatOptions, - package: undefined, - }, - 'received the correct arguments' - ) - t.strictSame(outputs, [`You don't have any hooks configured yet.`]) -}) - -t.test('npm hook ls, single result', async t => { - const hookResponse = [ - { - id: 1, - name: 'semver', - type: 'package', - endpoint: 'https://google.com', - }, - ] - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - hookResponse, - }) - - await hook.exec(['ls']) - - t.match( - hookArgs(), - { - ...npm.flatOptions, - package: undefined, - }, - 'received the correct arguments' - ) - t.strictSame(outputs, [ - 'You have 1 hook configured.', - 'Hook 1: semver', - 'Endpoint: https://google.com', - 'Never triggered\n', - ]) -}) - -t.test('npm hook ls - json output', async t => { - const config = { - json: true, - } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['ls']) - - t.match( - hookArgs(), - { - ...npm.flatOptions, - package: undefined, - }, - 'received the correct arguments' - ) - const out = JSON.parse(outputs[0]) - t.match( - out, - [ - { - id: 1, - name: 'semver', - type: 'package', - endpoint: 'https://google.com', - }, - { - id: 2, - name: 'npmcli', - type: 'scope', - endpoint: 'https://google.com', - }, - { - id: 3, - name: 'npm', - type: 'owner', - endpoint: 'https://google.com', - }, - ], - 'prints the correct output' - ) -}) - -t.test('npm hook ls - parseable output', async t => { - const config = { - parseable: true, - } - const { npm, hook, outputs, hookArgs, now } = await mockHook(t, { - config, - }) - - await hook.exec(['ls']) - - t.match( - hookArgs(), - { - ...npm.flatOptions, - package: undefined, - }, - 'received the correct arguments' - ) - t.strictSame( - outputs.map(line => line.split(/\t/)), - [ - ['id', 'name', 'type', 'endpoint', 'last_delivery', 'response_code'], - ['1', 'semver', 'package', 'https://google.com', '', '200'], - ['2', '@npmcli', 'scope', 'https://google.com', `${now}`, '200'], - ['3', 'npm', 'owner', 'https://google.com', '', '200'], - ], - 'prints the correct result' - ) -}) - -t.test('npm hook ls - silent output', async t => { - const config = { loglevel: 'silent' } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['ls']) - - t.match( - hookArgs(), - { - ...npm.flatOptions, - package: undefined, - }, - 'received the correct arguments' - ) - t.strictSame(outputs, [], 'printed no output') -}) - -t.test('npm hook rm', async t => { - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - }) - await hook.exec(['rm', '1']) - - t.match( - hookArgs(), - { - id: '1', - opts: npm.flatOptions, - }, - 'received the correct arguments' - ) - t.strictSame(outputs[0], '- semver X https://google.com', 'printed the correct output') -}) - -t.test('npm hook rm - unicode output', async t => { - const config = { - unicode: true, - } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['rm', '1']) - - t.match( - hookArgs(), - { - id: '1', - opts: npm.flatOptions, - }, - 'received the correct arguments' - ) - t.strictSame(outputs[0], '- semver ✘ https://google.com', 'printed the correct output') -}) - -t.test('npm hook rm - silent output', async t => { - const config = { loglevel: 'silent' } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['rm', '1']) - - t.match( - hookArgs(), - { - id: '1', - opts: npm.flatOptions, - }, - 'received the correct arguments' - ) - t.strictSame(outputs, [], 'printed no output') -}) - -t.test('npm hook rm - json output', async t => { - const config = { - json: true, - } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['rm', '1']) - - t.match( - hookArgs(), - { - id: '1', - opts: npm.flatOptions, - }, - 'received the correct arguments' - ) - t.strictSame( - JSON.parse(outputs[0]), - { - id: 1, - name: 'semver', - type: 'package', - endpoint: 'https://google.com', - }, - 'printed correct output' - ) -}) - -t.test('npm hook rm - parseable output', async t => { - const config = { - parseable: true, - } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['rm', '1']) - - t.match( - hookArgs(), - { - id: '1', - opts: npm.flatOptions, - }, - 'received the correct arguments' - ) - t.strictSame( - outputs.map(line => line.split(/\t/)), - [ - ['id', 'name', 'type', 'endpoint'], - ['1', 'semver', 'package', 'https://google.com'], - ], - 'printed correct output' - ) -}) - -t.test('npm hook update', async t => { - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - }) - await hook.exec(['update', '1', 'https://google.com', 'some-secret']) - - t.match( - hookArgs(), - { - id: '1', - uri: 'https://google.com', - secret: 'some-secret', - opts: npm.flatOptions, - }, - 'received the correct arguments' - ) - t.strictSame(outputs[0], '+ semver -> https://google.com', 'printed the correct output') -}) - -t.test('npm hook update - unicode', async t => { - const config = { - unicode: true, - } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['update', '1', 'https://google.com', 'some-secret']) - - t.match( - hookArgs(), - { - id: '1', - uri: 'https://google.com', - secret: 'some-secret', - opts: npm.flatOptions, - }, - 'received the correct arguments' - ) - t.strictSame(outputs[0], '+ semver ➜ https://google.com', 'printed the correct output') -}) - -t.test('npm hook update - json output', async t => { - const config = { - json: true, - } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['update', '1', 'https://google.com', 'some-secret']) - - t.match( - hookArgs(), - { - id: '1', - uri: 'https://google.com', - secret: 'some-secret', - opts: npm.flatOptions, - }, - 'received the correct arguments' - ) - t.strictSame( - JSON.parse(outputs[0]), - { - id: '1', - name: 'semver', - type: 'package', - endpoint: 'https://google.com', - }, - 'printed the correct output' - ) -}) - -t.test('npm hook update - parseable output', async t => { - const config = { - parseable: true, - } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['update', '1', 'https://google.com', 'some-secret']) - - t.match( - hookArgs(), - { - id: '1', - uri: 'https://google.com', - secret: 'some-secret', - opts: npm.flatOptions, - }, - 'received the correct arguments' - ) - t.strictSame( - outputs.map(line => line.split(/\t/)), - [ - ['id', 'name', 'type', 'endpoint'], - ['1', 'semver', 'package', 'https://google.com'], - ], - 'printed the correct output' - ) -}) - -t.test('npm hook update - silent output', async t => { - const config = { loglevel: 'silent' } - const { npm, hook, outputs, hookArgs } = await mockHook(t, { - config, - }) - - await hook.exec(['update', '1', 'https://google.com', 'some-secret']) - - t.match( - hookArgs(), - { - id: '1', - uri: 'https://google.com', - secret: 'some-secret', - opts: npm.flatOptions, - }, - 'received the correct arguments' - ) - t.strictSame(outputs, [], 'printed no output') -}) diff --git a/test/lib/commands/init.js b/test/lib/commands/init.js index 1e45347429258..7e79098a55848 100644 --- a/test/lib/commands/init.js +++ b/test/lib/commands/init.js @@ -16,7 +16,7 @@ const mockNpm = async (t, { noLog, libnpmexec, initPackageJson, ...opts } = {}) }, globals: { // init-package-json prints directly to console.log - // this avoids poluting test output with those logs + // this avoids polluting test output with those logs ...(noLog ? { 'console.log': () => {} } : {}), }, }) @@ -43,7 +43,7 @@ t.test('classic npm init -y', async t => { const pkg = require(resolve(prefix, 'package.json')) t.equal(pkg.version, '1.0.0') - t.equal(pkg.license, 'ISC') + t.equal(pkg.license, undefined, 'license is omitted by default') }) t.test('classic interactive npm init', async t => { @@ -273,7 +273,7 @@ t.test('workspaces', async t => { const pkg = require(resolve(prefix, 'a/package.json')) t.equal(pkg.name, 'a') t.equal(pkg.version, '1.0.0') - t.equal(pkg.license, 'ISC') + t.equal(pkg.license, undefined, 'license is omitted by default') t.matchSnapshot(joinedOutput(), 'should print helper info') @@ -306,7 +306,7 @@ t.test('workspaces', async t => { const pkg = require(resolve(prefix, 'packages/a/package.json')) t.equal(pkg.name, 'a') t.equal(pkg.version, '2.0.0') - t.equal(pkg.license, 'ISC') + t.equal(pkg.license, undefined, 'license is omitted by default') }) await t.test('fail parsing top-level package.json to set workspace', async t => { @@ -324,7 +324,7 @@ t.test('workspaces', async t => { ) }) - await t.test('missing top-level package.json when settting workspace', async t => { + await t.test('missing top-level package.json when setting workspace', async t => { const { npm, logs } = await mockNpm(t, { config: { workspace: 'a' }, }) @@ -338,7 +338,7 @@ t.test('workspaces', async t => { t.equal(logs.warn[0], 'init Missing package.json. Try with `--include-workspace-root`.') }) - await t.test('bad package.json when settting workspace', async t => { + await t.test('bad package.json when setting workspace', async t => { const { npm, logs } = await mockNpm(t, { prefixDir: { 'package.json': '{{{{', @@ -422,12 +422,12 @@ t.test('workspaces', async t => { const pkg = require(resolve(npm.localPrefix, 'package.json')) t.equal(pkg.version, '1.0.0') - t.equal(pkg.license, 'ISC') + t.equal(pkg.license, undefined, 'license is omitted by default') t.strictSame(pkg.workspaces, ['packages/a']) const ws = require(resolve(npm.localPrefix, 'packages/a/package.json')) t.equal(ws.version, '1.0.0') - t.equal(ws.license, 'ISC') + t.equal(ws.license, undefined, 'license is omitted by default') }) t.test('init pkg - installed workspace package', async t => { const { npm } = await mockNpm(t, { @@ -459,3 +459,125 @@ t.test('workspaces', async t => { t.ok(exists.isFile(), 'bin ran, creating file inside workspace') }) }) + +t.test('npm init with init-private config set', async t => { + const { npm, prefix } = await mockNpm(t, { + config: { yes: true, 'init-private': true }, + noLog: true, + }) + + await npm.exec('init', []) + + const pkg = require(resolve(prefix, 'package.json')) + t.equal(pkg.private, true, 'should set private to true when init-private is set') +}) + +t.test('npm init does not set private by default', async t => { + const { npm, prefix } = await mockNpm(t, { + config: { yes: true }, + noLog: true, + }) + + await npm.exec('init', []) + + const pkg = require(resolve(prefix, 'package.json')) + t.strictSame(pkg.private, undefined, 'should not set private by default') +}) + +t.test('user‑set init-private IS forwarded', async t => { + const { npm, prefix } = await mockNpm(t, { + config: { yes: true, 'init-private': true }, + noLog: true, + }) + + await npm.exec('init', []) + + const pkg = require(resolve(prefix, 'package.json')) + t.strictSame(pkg.private, true, 'should set private to true when init-private is set') +}) + +t.test('user‑set init-private IS forwarded when false', async t => { + const { npm, prefix } = await mockNpm(t, { + config: { yes: true, 'init-private': false }, + noLog: true, + }) + + await npm.exec('init', []) + + const pkg = require(resolve(prefix, 'package.json')) + t.strictSame(pkg.private, false, 'should set private to false when init-private is false') +}) + +t.test('No init-private is respected in workspaces', async t => { + const { npm, prefix } = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'top-level', + }), + }, + config: { workspace: 'a', yes: true }, + noLog: true, + }) + + await npm.exec('init', []) + + const pkg = require(resolve(prefix, 'a/package.json')) + t.strictSame(pkg.private, undefined, 'workspace package.json has no private field set') +}) + +t.test('init-private is respected in workspaces', async t => { + const { npm, prefix } = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'top-level', + }), + }, + config: { workspace: 'a', yes: true, 'init-private': true }, + noLog: true, + }) + + await npm.exec('init', []) + + const pkg = require(resolve(prefix, 'a/package.json')) + t.equal(pkg.private, true, 'workspace package.json has private field set') +}) + +t.test('create‑initializer path: init-private flag is forwarded via args', async t => { + const calls = [] + const libexecStub = async opts => calls.push(opts) + + const { npm } = await mockNpm(t, { + libnpmexec: libexecStub, + // user set the flag in their config + config: { yes: true, 'init-private': true }, + noLog: true, + }) + + await npm.exec('init', ['create-bar']) + + t.ok(calls[0].initPrivate, 'init-private included in options') + + // Also verify the test for when isDefault returns true + calls.length = 0 + npm.config.isDefault = () => true + + await npm.exec('init', ['create-bar']) + + t.equal(calls[0].initPrivate, undefined, 'init-private not included when using default') +}) + +t.test('create‑initializer path: false init-private is forwarded', async t => { + const calls = [] + const libexecStub = async opts => calls.push(opts) + + const { npm } = await mockNpm(t, { + libnpmexec: libexecStub, + // explicitly set to false + config: { yes: true, 'init-private': false }, + noLog: true, + }) + + await npm.exec('init', ['create-baz']) + + t.equal(calls[0].initPrivate, false, 'false init-private value is properly forwarded') +}) diff --git a/test/lib/commands/install.js b/test/lib/commands/install.js index 0273f3deec73e..3961b7f02e0c1 100644 --- a/test/lib/commands/install.js +++ b/test/lib/commands/install.js @@ -1,8 +1,17 @@ +const fs = require('node:fs') const tspawk = require('../../fixtures/tspawk') +const { + cleanCwd, + cleanTime, + cleanDate, + cleanPackumentCache, +} = require('../../fixtures/clean-snapshot.js') const path = require('node:path') const t = require('tap') +t.cleanSnapshot = (str) => cleanPackumentCache(cleanDate(cleanTime(cleanCwd(str)))) + const { loadNpmWithRegistry: loadMockNpm, workspaceMock, @@ -92,6 +101,118 @@ t.test('exec commands', async t => { t.strictSame(lifecycleScripts, runOrder, 'all script ran in the correct order') }) + // Regression test: root `preinstall` must run before any dependency is fetched/unpacked, while `install` and `postinstall` run after reify has populated node_modules. + await t.test('preinstall runs before reify, post-reify scripts run after', async t => { + const events = [] + const { npm, registry } = await loadMockNpm(t, { + config: { audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + ...packageJson, + scripts: { + preinstall: 'echo preinstall', + install: 'echo install', + postinstall: 'echo postinstall', + }, + }), + abbrev, + }, + mocks: { + '@npmcli/run-script': async (opts) => { + // Only record scripts targeted at the project root, not any that arborist may run for dependencies during reify. + if (opts.path === npm.prefix) { + const abbrevPkg = path.join(npm.prefix, 'node_modules', 'abbrev', 'package.json') + events.push({ event: opts.event, depInstalled: fs.existsSync(abbrevPkg) }) + } + }, + }, + }) + const manifest = registry.manifest({ name: 'abbrev' }) + await registry.package({ manifest }) + await registry.tarball({ + manifest: manifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'abbrev'), + }) + + await npm.exec('install') + + const pre = events.find(e => e.event === 'preinstall') + const post = events.find(e => e.event === 'postinstall') + t.ok(pre, 'preinstall ran') + t.ok(post, 'postinstall ran') + t.equal(pre.depInstalled, false, 'preinstall runs before dependencies are installed') + t.equal(post.depInstalled, true, 'postinstall runs after dependencies are installed') + }) + + await t.test('without args, --ignore-scripts skips preinstall entirely', async t => { + const events = [] + const { npm, registry } = await loadMockNpm(t, { + config: { audit: false, 'ignore-scripts': true }, + prefixDir: { + 'package.json': JSON.stringify({ + ...packageJson, + scripts: { + preinstall: 'echo preinstall', + postinstall: 'echo postinstall', + }, + }), + abbrev, + }, + mocks: { + '@npmcli/run-script': async (opts) => { + if (opts.path === npm.prefix) { + events.push(opts.event) + } + }, + }, + }) + const manifest = registry.manifest({ name: 'abbrev' }) + await registry.package({ manifest }) + await registry.tarball({ + manifest: manifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'abbrev'), + }) + + await npm.exec('install') + t.strictSame(events, [], 'no root lifecycle scripts run when --ignore-scripts is set') + }) + + // Regression test: a failing root `preinstall` must short-circuit before reify runs, so dependencies never reach disk on failure. This is the cleaner failure mode the PR was motivated by; future refactors that swallow the rejection and still call reify must fail here. + await t.test('a failing preinstall prevents reify', async t => { + const events = [] + const { npm } = await loadMockNpm(t, { + config: { audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + ...packageJson, + scripts: { + preinstall: 'exit 1', + postinstall: 'echo postinstall', + }, + }), + abbrev, + }, + mocks: { + '@npmcli/run-script': async (opts) => { + if (opts.path === npm.prefix) { + events.push(opts.event) + if (opts.event === 'preinstall') { + throw Object.assign(new Error('preinstall failed'), { code: 'ELIFECYCLE' }) + } + } + }, + }, + }) + + await t.rejects(npm.exec('install'), /preinstall failed/, 'install rejects when preinstall fails') + t.strictSame(events, ['preinstall'], 'only preinstall ran; no post-reify scripts') + t.equal( + fs.existsSync(path.join(npm.prefix, 'node_modules', 'abbrev', 'package.json')), + false, + 'no dependency reached disk after preinstall failure' + ) + }) + await t.test('should ignore scripts with --ignore-scripts', async t => { const { npm, registry } = await loadMockNpm(t, { config: { @@ -118,6 +239,25 @@ t.test('exec commands', async t => { await npm.exec('install') }) + await t.test('should not self-install package if prefix is the same as CWD', async t => { + let REIFY_CALLED_WITH = null + const { npm } = await loadMockNpm(t, { + mocks: { + '{LIB}/utils/reify-finish.js': async () => {}, + '@npmcli/run-script': () => {}, + '@npmcli/arborist': function () { + this.reify = (opts) => { + REIFY_CALLED_WITH = opts + } + }, + }, + prefixOverride: process.cwd(), + }) + + await npm.exec('install') + t.equal(REIFY_CALLED_WITH.add.length, 0, 'did not install current directory as a dependency') + }) + await t.test('should not install invalid global package name', async t => { const { npm } = await loadMockNpm(t, { config: { @@ -209,6 +349,196 @@ t.test('exec commands', async t => { await npm.exec('install', ['npm']) t.ok('No exceptions happen') }) + + t.test('allow-git=none', async t => { + const { npm } = await loadMockNpm(t, { + config: { + 'allow-git': 'none', + audit: false, + }, + }) + await t.rejects( + npm.exec('install', ['npm/npm']), + { + code: 'EALLOWGIT', + message: 'Fetching packages of type "git" have been disabled', + package: 'github:npm/npm', + } + ) + }) + + t.test('allow-git default rejects git deps', async t => { + const { npm } = await loadMockNpm(t, { + config: { audit: false }, + }) + await t.rejects( + npm.exec('install', ['npm/npm']), + { + code: 'EALLOWGIT', + package: 'github:npm/npm', + }, + 'no explicit allow-git config still blocks git installs' + ) + }) + + t.test('allow-git=root refuses non-root git dependency', async t => { + const { npm } = await loadMockNpm(t, { + config: { + 'allow-git': 'root', + audit: false, + }, + prefixDir: { + 'package.json': JSON.stringify({ name: '@npmcli/test-package', version: '1.0.0' }), + abbrev: { + 'package.json': JSON.stringify({ name: 'abbrev', version: '1.0.0', dependencies: { npm: 'npm/npm' } }), + }, + }, + }) + await t.rejects( + npm.exec('install', ['./abbrev']), + /Fetching non-root packages of type "git" have been disabled/ + ) + }) + + t.test('allow-directory=none blocks default symlink install', async t => { + const { npm } = await loadMockNpm(t, { + config: { + 'allow-directory': 'none', + audit: false, + }, + prefixDir: { + 'package.json': JSON.stringify({ + name: '@npmcli/test-package', + version: '1.0.0', + dependencies: { 'dir-dep': 'file:./dir-dep' }, + }), + 'dir-dep': { + 'package.json': JSON.stringify({ name: 'dir-dep', version: '1.0.0' }), + }, + }, + }) + await t.rejects( + npm.exec('install', []), + { + code: 'EALLOWDIRECTORY', + message: 'Fetching packages of type "directory" have been disabled', + } + ) + }) + + t.test('allow-directory=root permits top-level directory dependency', async t => { + const { npm } = await loadMockNpm(t, { + config: { + 'allow-directory': 'root', + audit: false, + }, + prefixDir: { + 'package.json': JSON.stringify({ + name: '@npmcli/test-package', + version: '1.0.0', + dependencies: { 'dir-dep': 'file:./dir-dep' }, + }), + 'dir-dep': { + 'package.json': JSON.stringify({ name: 'dir-dep', version: '1.0.0' }), + }, + }, + }) + await npm.exec('install', []) + const installedPkg = require(path.join(npm.prefix, 'node_modules', 'dir-dep', 'package.json')) + t.equal(installedPkg.name, 'dir-dep', 'dir-dep is installed and readable through node_modules') + }) + + t.test('allow-git=root soft-skips transitive optional git dependency', async t => { + const { npm } = await loadMockNpm(t, { + config: { + 'allow-git': 'root', + audit: false, + }, + prefixDir: { + 'package.json': JSON.stringify({ name: '@npmcli/test-package', version: '1.0.0' }), + abbrev: { + 'package.json': JSON.stringify({ + name: 'abbrev', + version: '1.0.0', + optionalDependencies: { npm: 'npm/npm' }, + }), + }, + }, + }) + await npm.exec('install', ['./abbrev']) + t.ok( + fs.existsSync(path.join(npm.prefix, 'node_modules', 'abbrev', 'package.json')), + 'abbrev (the legitimate parent) is installed' + ) + t.notOk( + fs.existsSync(path.join(npm.prefix, 'node_modules', 'npm')), + 'optional transitive git dep is silently skipped' + ) + }) + + t.test('allow-remote=none does not block registry tarballs', async t => { + const { npm, registry } = await loadMockNpm(t, { + config: { + 'allow-remote': 'none', + audit: false, + }, + prefixDir: { + 'package.json': JSON.stringify({ + ...packageJson, + dependencies: { abbrev: '^1.0.0' }, + }), + abbrev, + }, + }) + const manifest = registry.manifest({ name: 'abbrev' }) + await registry.package({ manifest }) + await registry.tarball({ + manifest: manifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'abbrev'), + }) + await npm.exec('install', []) + const installed = require(path.join(npm.prefix, 'node_modules', 'abbrev', 'package.json')) + t.equal(installed.name, 'abbrev', 'registry dep is installed despite allow-remote=none') + }) + + t.test('allow-remote=none still blocks a user-supplied remote URL', async t => { + const { npm } = await loadMockNpm(t, { + config: { + 'allow-remote': 'none', + audit: false, + }, + prefixDir: { + 'package.json': JSON.stringify({ + name: '@npmcli/test-package', + version: '1.0.0', + dependencies: { abbrev: 'https://registry.npmjs.org/abbrev/-/abbrev-2.0.0.tgz' }, + }), + }, + }) + await t.rejects( + npm.exec('install', []), + { code: 'EALLOWREMOTE' }, + 'user-supplied remote URL is still blocked' + ) + }) + + t.test('allow-remote default rejects a user-supplied remote URL', async t => { + const { npm } = await loadMockNpm(t, { + config: { audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + name: '@npmcli/test-package', + version: '1.0.0', + dependencies: { abbrev: 'https://registry.npmjs.org/abbrev/-/abbrev-2.0.0.tgz' }, + }), + }, + }) + await t.rejects( + npm.exec('install', []), + { code: 'EALLOWREMOTE' }, + 'no explicit allow-remote config still blocks user-supplied tarball URLs' + ) + }) }) t.test('completion', async t => { @@ -400,3 +730,581 @@ t.test('should show install keeps dirty --workspace flag', async t => { assert.packageDirty('node_modules/abbrev@1.1.0') assert.packageInstalled('node_modules/lodash@1.1.1') }) + +t.test('devEngines', async t => { + const mockArguments = { + globals: { + 'process.platform': 'linux', + 'process.arch': 'x86', + 'process.version': 'v1337.0.0', + }, + mocks: { + '{ROOT}/package.json': { version: '42.0.0' }, + }, + } + + t.test('should utilize devEngines success case', async t => { + const { npm, joinedFullOutput } = await loadMockNpm(t, { + ...mockArguments, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'test-package', + version: '1.0.0', + devEngines: { + runtime: { + name: 'node', + }, + }, + }), + }, + }) + await npm.exec('install', []) + const output = joinedFullOutput() + t.matchSnapshot(output) + t.ok(!output.includes('EBADDEVENGINES')) + }) + + t.test('should utilize devEngines failure case', async t => { + const { npm, joinedFullOutput } = await loadMockNpm(t, { + ...mockArguments, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'test-package', + version: '1.0.0', + devEngines: { + runtime: { + name: 'nondescript', + }, + }, + }), + }, + }) + await t.rejects( + npm.exec('install', []) + ) + const output = joinedFullOutput() + t.matchSnapshot(output) + t.ok(output.includes('error EBADDEVENGINES')) + }) + + t.test('should utilize devEngines failure force case', async t => { + const { npm, joinedFullOutput } = await loadMockNpm(t, { + ...mockArguments, + config: { + force: true, + }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'test-package', + version: '1.0.0', + devEngines: { + runtime: { + name: 'nondescript', + }, + }, + }), + }, + }) + await npm.exec('install', []) + const output = joinedFullOutput() + t.matchSnapshot(output) + t.ok(output.includes('warn EBADDEVENGINES')) + }) + + t.test('should utilize devEngines 2x warning case', async t => { + const { npm, joinedFullOutput } = await loadMockNpm(t, { + ...mockArguments, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'test-package', + version: '1.0.0', + devEngines: { + runtime: { + name: 'nondescript', + onFail: 'warn', + }, + cpu: { + name: 'risv', + onFail: 'warn', + }, + }, + }), + }, + }) + await npm.exec('install', []) + const output = joinedFullOutput() + t.matchSnapshot(output) + t.ok(output.includes('warn EBADDEVENGINES')) + }) + + t.test('should utilize devEngines 2x error case', async t => { + const { npm, joinedFullOutput } = await loadMockNpm(t, { + ...mockArguments, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'test-package', + version: '1.0.0', + devEngines: { + runtime: { + name: 'nondescript', + onFail: 'error', + }, + cpu: { + name: 'risv', + onFail: 'error', + }, + }, + }), + }, + }) + await t.rejects( + npm.exec('install', []) + ) + const output = joinedFullOutput() + t.matchSnapshot(output) + t.ok(output.includes('error EBADDEVENGINES')) + }) + + t.test('should utilize devEngines failure and warning case', async t => { + const { npm, joinedFullOutput } = await loadMockNpm(t, { + ...mockArguments, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'test-package', + version: '1.0.0', + devEngines: { + runtime: { + name: 'nondescript', + }, + cpu: { + name: 'risv', + onFail: 'warn', + }, + }, + }), + }, + }) + await t.rejects( + npm.exec('install', []) + ) + const output = joinedFullOutput() + t.matchSnapshot(output) + t.ok(output.includes('EBADDEVENGINES')) + }) + + t.test('should show devEngines has no effect on package install', async t => { + const { npm, joinedFullOutput } = await loadMockNpm(t, { + ...mockArguments, + prefixDir: { + alpha: { + 'package.json': JSON.stringify({ + name: 'alpha', + devEngines: { runtime: { name: 'node', version: '1.0.0' } }, + }), + 'index.js': 'console.log("this is alpha index")', + }, + 'package.json': JSON.stringify({ + name: 'project', + }), + }, + }) + await npm.exec('install', ['./alpha']) + const output = joinedFullOutput() + t.matchSnapshot(output) + t.ok(!output.includes('EBADDEVENGINES')) + }) + + t.test('should show devEngines has no effect on dev package install', async t => { + const { npm, joinedFullOutput } = await loadMockNpm(t, { + ...mockArguments, + prefixDir: { + alpha: { + 'package.json': JSON.stringify({ + name: 'alpha', + devEngines: { runtime: { name: 'node', version: '1.0.0' } }, + }), + 'index.js': 'console.log("this is alpha index")', + }, + 'package.json': JSON.stringify({ + name: 'project', + }), + }, + config: { + 'save-dev': true, + }, + }) + await npm.exec('install', ['./alpha']) + const output = joinedFullOutput() + t.matchSnapshot(output) + t.ok(!output.includes('EBADDEVENGINES')) + }) + + t.test('should show devEngines doesnt break engines', async t => { + const { npm, joinedFullOutput } = await loadMockNpm(t, { + ...mockArguments, + prefixDir: { + alpha: { + 'package.json': JSON.stringify({ + name: 'alpha', + devEngines: { runtime: { name: 'node', version: '1.0.0' } }, + engines: { node: '1.0.0' }, + }), + 'index.js': 'console.log("this is alpha index")', + }, + 'package.json': JSON.stringify({ + name: 'project', + }), + }, + config: { global: true }, + }) + await npm.exec('install', ['./alpha']) + const output = joinedFullOutput() + t.matchSnapshot(output) + t.ok(output.includes('warn EBADENGINE')) + }) + + t.test('should not utilize engines in root if devEngines is provided', async t => { + const { npm, joinedFullOutput } = await loadMockNpm(t, { + ...mockArguments, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'alpha', + engines: { + node: '0.0.1', + }, + devEngines: { + runtime: { + name: 'node', + version: '0.0.1', + onFail: 'warn', + }, + }, + }), + 'index.js': 'console.log("this is alpha index")', + }, + }) + await npm.exec('install') + const output = joinedFullOutput() + t.matchSnapshot(output) + t.ok(!output.includes('EBADENGINE')) + t.ok(output.includes('warn EBADDEVENGINES')) + }) + + t.test('should utilize engines in root if devEngines is not provided', async t => { + const { npm, joinedFullOutput } = await loadMockNpm(t, { + ...mockArguments, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'alpha', + engines: { + node: '0.0.1', + }, + }), + 'index.js': 'console.log("this is alpha index")', + }, + }) + await npm.exec('install') + const output = joinedFullOutput() + t.matchSnapshot(output) + t.ok(output.includes('EBADENGINE')) + t.ok(!output.includes('EBADDEVENGINES')) + }) + + t.test('should show devEngines has no effect on global package install', async t => { + const { npm, joinedFullOutput } = await loadMockNpm(t, { + ...mockArguments, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'alpha', + bin: { + alpha: 'index.js', + }, + devEngines: { + runtime: { + name: 'node', + version: '0.0.1', + }, + }, + }), + 'index.js': 'console.log("this is alpha index")', + }, + config: { + global: true, + }, + }) + await npm.exec('install', ['.']) + const output = joinedFullOutput() + t.matchSnapshot(output) + t.ok(!output.includes('EBADENGINE')) + t.ok(!output.includes('EBADDEVENGINES')) + }) +}) + +// Issue #8726 - npm install should re-resolve to satisfy peerOptional constraints +// https://github.com/npm/cli/issues/8726 +// +// When a lockfile has fetcher@1.1.0 but a peerOptional wants fetcher@1.0.0 (exact), npm install (save: true) should re-resolve fetcher to 1.0.0 to satisfy both the regular dep range (^1.0.0) and the exact peerOptional constraint. +t.test('issue-8726: npm install re-resolves to satisfy peerOptional constraint', async t => { + const { npm, registry } = await loadMockNpm(t, { + config: { audit: false, 'ignore-scripts': true }, + prefixDir: { + 'linter-tarball': { + 'package.json': JSON.stringify({ + name: 'linter', + version: '1.0.0', + dependencies: { scanner: '1.0.0' }, + }), + }, + 'scanner-tarball': { + 'package.json': JSON.stringify({ + name: 'scanner', + version: '1.0.0', + peerDependencies: { fetcher: '1.0.0' }, + peerDependenciesMeta: { fetcher: { optional: true } }, + }), + }, + 'hint-tarball': { + 'package.json': JSON.stringify({ + name: 'hint', + version: '1.0.0', + dependencies: { fetcher: '^1.0.0' }, + }), + }, + 'fetcher-1.0.0-tarball': { + 'package.json': JSON.stringify({ name: 'fetcher', version: '1.0.0' }), + }, + 'fetcher-1.1.0-tarball': { + 'package.json': JSON.stringify({ name: 'fetcher', version: '1.1.0' }), + }, + 'package.json': JSON.stringify({ + name: 'test-package', + version: '1.0.0', + devDependencies: { + linter: '1.0.0', + hint: '1.0.0', + }, + }), + 'package-lock.json': JSON.stringify({ + name: 'test-package', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { + name: 'test-package', + version: '1.0.0', + devDependencies: { linter: '1.0.0', hint: '1.0.0' }, + }, + 'node_modules/linter': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/linter/-/linter-1.0.0.tgz', + dev: true, + dependencies: { scanner: '1.0.0' }, + }, + 'node_modules/scanner': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/scanner/-/scanner-1.0.0.tgz', + dev: true, + peerDependencies: { fetcher: '1.0.0' }, + peerDependenciesMeta: { fetcher: { optional: true } }, + }, + 'node_modules/hint': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/hint/-/hint-1.0.0.tgz', + dev: true, + dependencies: { fetcher: '^1.0.0' }, + }, + 'node_modules/fetcher': { + version: '1.1.0', + resolved: 'https://registry.npmjs.org/fetcher/-/fetcher-1.1.0.tgz', + dev: true, + }, + }, + }), + }, + }) + + // Only set up mocks that npm install actually needs: tarballs for all installed packages (linter, scanner, hint, fetcher@1.0.0) and the fetcher packument (needed for re-resolution via #problemEdges). + // Packuments for linter/scanner/hint are NOT needed (already in lockfile). + // Fetcher@1.1.0 tarball is NOT needed (gets replaced by 1.0.0). + const linterManifest = registry.manifest({ name: 'linter' }) + await registry.tarball({ + manifest: linterManifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'linter-tarball'), + }) + + const scannerManifest = registry.manifest({ name: 'scanner' }) + await registry.tarball({ + manifest: scannerManifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'scanner-tarball'), + }) + + const hintManifest = registry.manifest({ name: 'hint' }) + await registry.tarball({ + manifest: hintManifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'hint-tarball'), + }) + + const fetcherManifest = registry.manifest({ + name: 'fetcher', + versions: ['1.0.0', '1.1.0'], + }) + await registry.package({ manifest: fetcherManifest }) + await registry.tarball({ + manifest: fetcherManifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'fetcher-1.0.0-tarball'), + }) + + await npm.exec('install', []) + + // Read the updated lockfile and verify fetcher was re-resolved to 1.0.0 + const lockfile = JSON.parse( + fs.readFileSync(path.join(npm.prefix, 'package-lock.json'), 'utf8') + ) + t.equal( + lockfile.packages['node_modules/fetcher'].version, + '1.0.0', + 'lockfile updated fetcher to satisfy peerOptional constraint' + ) + + // Also verify the installed package + const installedFetcher = JSON.parse( + fs.readFileSync( + path.join(npm.prefix, 'node_modules', 'fetcher', 'package.json'), 'utf8' + ) + ) + t.equal( + installedFetcher.version, + '1.0.0', + 'installed fetcher version satisfies peerOptional constraint' + ) +}) + +// Issue #8726 - fresh npm install (no lockfile) should pick a version that satisfies both the regular dep range AND the exact peerOptional constraint, even when the peerOptional holder is processed BEFORE the dep is placed. +// https://github.com/npm/cli/issues/8726 +// +// This test uses package names that reproduce the real-world alphabetical ordering from the original issue (addons-linter < htmlhint), which causes addons-scanner to be processed from the queue BEFORE htmlhint places node-fetcher. +// At that point the peerOptional edge has no destination (MISSING, valid for peerOptional). +// Later, htmlhint places node-fetcher@1.1.0 and the edge becomes INVALID. +// The fix re-queues addons-scanner so #problemEdges can trigger re-resolution of node-fetcher to 1.0.0. +// +// Dependency graph: +// root -> addons-linter@1.0.0 -> addons-scanner@1.0.0 -> PEER_OPTIONAL node-fetcher@1.0.0 +// root -> htmlhint@1.0.0 -> node-fetcher@^1.0.0 +// +// Processing order (alphabetical): addons-linter, then addons-scanner (dep of addons-linter), THEN htmlhint (which places node-fetcher@1.1.0) +t.test('issue-8726: fresh install re-queues scanner when dep placed later', async t => { + const { npm, registry } = await loadMockNpm(t, { + config: { audit: false, 'ignore-scripts': true }, + prefixDir: { + 'addons-linter-tarball': { + 'package.json': JSON.stringify({ + name: 'addons-linter', + version: '1.0.0', + dependencies: { 'addons-scanner': '1.0.0' }, + }), + }, + 'addons-scanner-tarball': { + 'package.json': JSON.stringify({ + name: 'addons-scanner', + version: '1.0.0', + peerDependencies: { 'node-fetcher': '1.0.0' }, + peerDependenciesMeta: { 'node-fetcher': { optional: true } }, + }), + }, + 'htmlhint-tarball': { + 'package.json': JSON.stringify({ + name: 'htmlhint', + version: '1.0.0', + dependencies: { 'node-fetcher': '^1.0.0' }, + }), + }, + 'node-fetcher-1.0.0-tarball': { + 'package.json': JSON.stringify({ name: 'node-fetcher', version: '1.0.0' }), + }, + 'node-fetcher-1.1.0-tarball': { + 'package.json': JSON.stringify({ name: 'node-fetcher', version: '1.1.0' }), + }, + 'package.json': JSON.stringify({ + name: 'test-package', + version: '1.0.0', + devDependencies: { + 'addons-linter': '1.0.0', + htmlhint: '1.0.0', + }, + }), + // NO package-lock.json — this is a fresh install + }, + }) + + // Fresh install needs packuments for all packages + const linterManifest = registry.manifest({ + name: 'addons-linter', + packuments: [{ version: '1.0.0', dependencies: { 'addons-scanner': '1.0.0' } }], + }) + await registry.package({ manifest: linterManifest }) + await registry.tarball({ + manifest: linterManifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'addons-linter-tarball'), + }) + + const scannerManifest = registry.manifest({ + name: 'addons-scanner', + packuments: [{ + version: '1.0.0', + peerDependencies: { 'node-fetcher': '1.0.0' }, + peerDependenciesMeta: { 'node-fetcher': { optional: true } }, + }], + }) + await registry.package({ manifest: scannerManifest }) + await registry.tarball({ + manifest: scannerManifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'addons-scanner-tarball'), + }) + + const hintManifest = registry.manifest({ + name: 'htmlhint', + packuments: [{ version: '1.0.0', dependencies: { 'node-fetcher': '^1.0.0' } }], + }) + await registry.package({ manifest: hintManifest }) + await registry.tarball({ + manifest: hintManifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'htmlhint-tarball'), + }) + + const fetcherManifest = registry.manifest({ + name: 'node-fetcher', + packuments: [{ version: '1.0.0' }, { version: '1.1.0' }], + }) + // Packument is fetched twice: once when htmlhint resolves node-fetcher@^1.0.0 (picking 1.1.0), and again when addons-scanner is re-queued and re-resolves node-fetcher (picking 1.0.0 to satisfy the exact peerOptional spec). + await registry.package({ manifest: fetcherManifest, times: 2 }) + await registry.tarball({ + manifest: fetcherManifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'node-fetcher-1.0.0-tarball'), + }) + // node-fetcher@1.1.0 tarball is NOT needed: it's replaced by 1.0.0 during tree building (before reification), so it's never downloaded. + + await npm.exec('install', []) + + // Verify the lockfile has node-fetcher@1.0.0 + const lockfile = JSON.parse( + fs.readFileSync(path.join(npm.prefix, 'package-lock.json'), 'utf8') + ) + t.equal( + lockfile.packages['node_modules/node-fetcher'].version, + '1.0.0', + 'fresh install picks node-fetcher@1.0.0 satisfying peerOptional constraint' + ) + + // Also verify the installed package + const installedFetcher = JSON.parse( + fs.readFileSync( + path.join(npm.prefix, 'node_modules', 'node-fetcher', 'package.json'), 'utf8' + ) + ) + t.equal( + installedFetcher.version, + '1.0.0', + 'installed node-fetcher version satisfies peerOptional constraint' + ) +}) diff --git a/test/lib/commands/link.js b/test/lib/commands/link.js index 184f7d6420339..7fe72865fc52f 100644 --- a/test/lib/commands/link.js +++ b/test/lib/commands/link.js @@ -289,6 +289,44 @@ t.test('link global linked pkg to local workspace using args', async t => { t.matchSnapshot(await printLinks(), 'should create a local symlink to global pkg') }) +t.test('link --workspace --save targets the workspace manifest, not the root', async t => { + const { link, prefix } = await mockLink(t, { + globalPrefixDir: { + node_modules: { + a: { + 'package.json': JSON.stringify({ + name: 'a', + version: '1.0.0', + }), + }, + }, + }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'my-project', + version: '1.0.0', + workspaces: ['packages/*'], + }), + packages: { + x: { + 'package.json': JSON.stringify({ + name: 'x', + version: '1.0.0', + }), + }, + }, + }, + config: { workspace: 'x', save: true }, + }) + + await link.exec(['a']) + + const root = JSON.parse(fs.readFileSync(join(prefix, 'package.json'), 'utf8')) + const ws = JSON.parse(fs.readFileSync(join(prefix, 'packages', 'x', 'package.json'), 'utf8')) + t.notOk(root.dependencies, 'root manifest should not get the dependency') + t.match(ws.dependencies, { a: /^file:/ }, 'workspace manifest should get the file: dependency') +}) + t.test('link pkg already in global space', async t => { const { npm, link, printLinks, prefix } = await mockLink(t, { globalPrefixDir: { @@ -523,3 +561,34 @@ t.test('test linked installed as symlinks', async t => { t.matchSnapshot(await printLinks(), 'linked package should not be installed') }) + +t.test('link threads allowScripts policy through to arborist', async t => { + const capturedOpts = [] + const FakeArborist = function (opts) { + capturedOpts.push(opts) + this.options = opts + this.actualTree = { inventory: new Map() } + } + FakeArborist.prototype.loadActual = async () => ({ isLink: false, children: new Map() }) + FakeArborist.prototype.reify = async () => {} + + const mock = await mockNpm(t, { + command: 'link', + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + allowScripts: { canvas: true }, + }), + }, + mocks: { + '@npmcli/arborist': FakeArborist, + '{LIB}/utils/reify-finish.js': async () => {}, + }, + }) + await mock.npm.exec('link', ['canvas']) + // the local Arborist is the last one constructed in linkInstall + const localOpts = capturedOpts[capturedOpts.length - 1] + t.strictSame(localOpts.allowScripts, { canvas: true }, + 'local arborist opts.allowScripts populated from package.json') +}) diff --git a/test/lib/commands/login.js b/test/lib/commands/login.js index a55637f9e00e2..623bc5845708f 100644 --- a/test/lib/commands/login.js +++ b/test/lib/commands/login.js @@ -49,7 +49,6 @@ t.test('legacy', t => { homeDir: { '.npmrc': [ '//registry.npmjs.org/:_authToken=user', - '//registry.npmjs.org/:always-auth=user', '//registry.npmjs.org/:email=test-email-old@npmjs.org', ].join('\n'), }, @@ -63,8 +62,8 @@ t.test('legacy', t => { t.same(npm.config.get('//registry.npmjs.org/:_authToken'), 'npm_test-token') t.same(rc(), { '//registry.npmjs.org/:_authToken': 'npm_test-token', - email: 'test-email-old@npmjs.org', - }, 'should only have token and un-nerfed old email') + '//registry.npmjs.org/:email': 'test-email-old@npmjs.org', + }, 'should only have token and nerfed email') }) t.test('scoped login default registry', async t => { @@ -119,7 +118,7 @@ t.test('legacy', t => { t.test('web', t => { t.test('basic login', async t => { - const { npm, registry, login, rc } = await mockLogin(t, { + const { outputs, npm, registry, login, rc } = await mockLogin(t, { config: { 'auth-type': 'web' }, }) registry.weblogin({ token: 'npm_test-token' }) @@ -128,6 +127,20 @@ t.test('web', t => { t.same(rc(), { '//registry.npmjs.org/:_authToken': 'npm_test-token', }) + t.match(outputs[0], '/npm-cli-test/login/cli/00000000-0000-0000-0000-000000000000') + }) + t.test('proxy registry whose doneUrl points at the canonical registry', async t => { + // Regression for npm/cli#8875: a proxy/mirror returns a doneUrl on registry.npmjs.org. + // npm must poll the configured proxy where the session lives, not the canonical registry. + const proxy = 'https://proxy.registry.example/' + const { npm, registry, login, rc } = await mockLogin(t, { + registry: proxy, + config: { 'auth-type': 'web', registry: proxy }, + }) + registry.weblogin({ token: 'npm_proxy-token', doneRegistry: 'https://registry.npmjs.org' }) + await login.exec([]) + t.same(npm.config.get('//proxy.registry.example/:_authToken'), 'npm_proxy-token') + t.match(rc(), { '//proxy.registry.example/:_authToken': 'npm_proxy-token' }) }) t.test('server error', async t => { const { registry, login } = await mockLogin(t, { diff --git a/test/lib/commands/logout.js b/test/lib/commands/logout.js index 840c92274bad0..b18b84ca48325 100644 --- a/test/lib/commands/logout.js +++ b/test/lib/commands/logout.js @@ -9,7 +9,7 @@ t.test('token logout - user config', async t => { homeDir: { '.npmrc': [ '//registry.npmjs.org/:_authToken=@foo/', - 'other-config=true', + 'fund=true', ].join('\n'), }, }) @@ -23,7 +23,7 @@ t.test('token logout - user config', async t => { 'should log message with correct registry' ) const userRc = await fs.readFile(join(home, '.npmrc'), 'utf-8') - t.equal(userRc.trim(), 'other-config=true') + t.equal(userRc.trim(), 'fund=true') }) t.test('token scoped logout - user config', async t => { @@ -60,7 +60,7 @@ t.test('user/pass logout - user config', async t => { '.npmrc': [ '//registry.npmjs.org/:username=foo', '//registry.npmjs.org/:_password=bar', - 'other-config=true', + 'fund=true', ].join('\n'), }, }) @@ -73,7 +73,7 @@ t.test('user/pass logout - user config', async t => { ) const userRc = await fs.readFile(join(home, '.npmrc'), 'utf-8') - t.equal(userRc.trim(), 'other-config=true') + t.equal(userRc.trim(), 'fund=true') }) t.test('missing credentials', async t => { @@ -95,7 +95,7 @@ t.test('ignore invalid scoped registry config', async t => { homeDir: { '.npmrc': [ '//registry.npmjs.org/:_authToken=@foo/', - 'other-config=true', + 'fund=true', ].join('\n'), }, @@ -111,7 +111,7 @@ t.test('ignore invalid scoped registry config', async t => { 'should log message with correct registry' ) const userRc = await fs.readFile(join(home, '.npmrc'), 'utf-8') - t.equal(userRc.trim(), 'other-config=true') + t.equal(userRc.trim(), 'fund=true') }) t.test('token logout - project config', async t => { @@ -119,13 +119,13 @@ t.test('token logout - project config', async t => { homeDir: { '.npmrc': [ '//registry.npmjs.org/:_authToken=@foo/', - 'other-config=true', + 'fund=true', ].join('\n'), }, prefixDir: { '.npmrc': [ '//registry.npmjs.org/:_authToken=@bar/', - 'other-config=true', + 'fund=true', ].join('\n'), }, }) @@ -142,7 +142,7 @@ t.test('token logout - project config', async t => { const userRc = await fs.readFile(join(home, '.npmrc'), 'utf-8') t.equal(userRc.trim(), [ '//registry.npmjs.org/:_authToken=@foo/', - 'other-config=true', + 'fund=true', ].join('\n'), 'leaves user config alone') t.equal( logs.verbose.byTitle('logout')[0], @@ -150,5 +150,5 @@ t.test('token logout - project config', async t => { 'should log message with correct registry' ) const projectRc = await fs.readFile(join(prefix, '.npmrc'), 'utf-8') - t.equal(projectRc.trim(), 'other-config=true', 'removes project config') + t.equal(projectRc.trim(), 'fund=true', 'removes project config') }) diff --git a/test/lib/commands/ls.js b/test/lib/commands/ls.js index 2147b3f036d72..577c2e7835e2a 100644 --- a/test/lib/commands/ls.js +++ b/test/lib/commands/ls.js @@ -263,7 +263,7 @@ t.test('ls', async t => { await ls.exec([]) - t.matchSnapshot(cleanCwd(result()), 'should contain overridden outout') + t.matchSnapshot(cleanCwd(result()), 'should contain overridden output') }) t.test('overridden dep w/ color', async t => { @@ -305,7 +305,93 @@ t.test('ls', async t => { }) await ls.exec([]) - t.matchSnapshot(cleanCwd(result()), 'should contain overridden outout') + t.matchSnapshot(cleanCwd(result()), 'should contain overridden output') + }) + + const packageExtensionsPrefix = { + 'package.json': JSON.stringify({ + name: 'test-package-extensions', + version: '1.0.0', + dependencies: { foo: '^1.0.0' }, + packageExtensions: { 'foo@1': { dependencies: { bar: '^1.0.0' } } }, + }), + node_modules: { + '.package-lock.json': JSON.stringify({ + packages: { + 'node_modules/foo': { + version: '1.0.0', + dependencies: { bar: '^1.0.0' }, + packageExtensionsApplied: { selector: 'foo@1', dependencies: ['bar'] }, + }, + 'node_modules/bar': { version: '1.0.0' }, + }, + }), + foo: { + 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0', dependencies: { bar: '^1.0.0' } }), + }, + bar: { 'package.json': JSON.stringify({ name: 'bar', version: '1.0.0' }) }, + }, + } + + t.test('packageExtensions dep', async t => { + const { npm, result, ls } = await mockLs(t, { config: {}, prefixDir: packageExtensionsPrefix }) + touchHiddenPackageLock(npm.prefix) + await ls.exec([]) + t.matchSnapshot(cleanCwd(result()), 'human output annotates the extended node') + }) + + t.test('packageExtensions dep --json', async t => { + const { npm, result, ls } = await mockLs(t, { + config: { json: true }, + prefixDir: packageExtensionsPrefix, + }) + touchHiddenPackageLock(npm.prefix) + await ls.exec([]) + const applied = JSON.parse(result()).dependencies.foo.packageExtensionsApplied + t.match(applied, { selector: 'foo@1', dependencies: ['bar'] }, 'json output includes provenance') + }) + + const npmExtensionPrefix = { + 'package.json': JSON.stringify({ + name: 'test-npm-extension', + version: '1.0.0', + dependencies: { foo: '^1.0.0' }, + }), + node_modules: { + '.package-lock.json': JSON.stringify({ + packages: { + 'node_modules/foo': { + version: '1.0.0', + dependencies: { bar: '^1.0.0' }, + npmExtensionApplied: { extensionPoint: 'transformManifest', dependencies: ['bar'] }, + }, + 'node_modules/bar': { version: '1.0.0' }, + }, + }), + foo: { + 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0', dependencies: { bar: '^1.0.0' } }), + }, + bar: { 'package.json': JSON.stringify({ name: 'bar', version: '1.0.0' }) }, + }, + } + + t.test('.npm-extension dep', async t => { + const { npm, result, ls } = await mockLs(t, { config: {}, prefixDir: npmExtensionPrefix }) + touchHiddenPackageLock(npm.prefix) + await ls.exec([]) + t.matchSnapshot(cleanCwd(result()), 'human output annotates the transformed node') + }) + + t.test('.npm-extension dep --json', async t => { + const { npm, result, ls } = await mockLs(t, { + config: { json: true }, + prefixDir: npmExtensionPrefix, + }) + touchHiddenPackageLock(npm.prefix) + await ls.exec([]) + const applied = JSON.parse(result()).dependencies.foo.npmExtensionApplied + t.match(applied, { extensionPoint: 'transformManifest', dependencies: ['bar'] }, + 'json output includes provenance') }) t.test('with filter arg', async t => { @@ -329,7 +415,7 @@ t.test('ls', async t => { await ls.exec(['chai']) t.matchSnapshot( cleanCwd(result()), - 'should output tree contaning only occurrences of filtered by package and colored output' + 'should output tree containing only occurrences of filtered by package and colored output' ) }) @@ -355,7 +441,7 @@ t.test('ls', async t => { await ls.exec(['.']) t.matchSnapshot( cleanCwd(result()), - 'should output tree contaning only occurrences of filtered by package and colored output' + 'should output tree containing only occurrences of filtered by package and colored output' ) }) @@ -377,7 +463,7 @@ t.test('ls', async t => { await ls.exec(['dog']) t.matchSnapshot( cleanCwd(result()), - 'should output tree contaning only occurrences of filtered package and its ancestors' + 'should output tree containing only occurrences of filtered package and its ancestors' ) }) @@ -408,8 +494,7 @@ t.test('ls', async t => { await ls.exec(['dog@*', 'chai@1.0.0']) t.matchSnapshot( cleanCwd(result()), - /* eslint-disable-next-line max-len */ - 'should output tree contaning only occurrences of multiple filtered packages and their ancestors' + 'should output tree containing only occurrences of multiple filtered packages and their ancestors' ) }) @@ -1314,7 +1399,6 @@ t.test('ls', async t => { name: 'abbrev', version: '1.1.1', from: 'git+https://github.com/isaacs/abbrev-js.git', - /* eslint-disable-next-line max-len */ resolved: 'git+https://github.com/isaacs/abbrev-js.git#b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c', }, }, @@ -1325,7 +1409,6 @@ t.test('ls', async t => { version: '1.1.1', _id: 'abbrev@1.1.1', _from: 'git+https://github.com/isaacs/abbrev-js.git', - /* eslint-disable-next-line max-len */ _resolved: 'git+https://github.com/isaacs/abbrev-js.git#b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c', _requested: { type: 'git', @@ -1372,7 +1455,6 @@ t.test('ls', async t => { a: { version: '1.0.1', resolved: 'foo@dog://b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c', - /* eslint-disable-next-line max-len */ integrity: 'sha512-8AN9lNCcBt5Xeje7fMEEpp5K3rgcAzIpTtAjYb/YMUYu8SbIVF6wz0WqACDVKvpQOUcSfNHZQNLNmue0QSwXOQ==', }, }, @@ -1654,7 +1736,7 @@ t.test('ls', async t => { })) // filter out a single workspace and include root - t.test('should inlude root and specified workspace', t => mockWorkspaces(t, [], { + t.test('should include root and specified workspace', t => mockWorkspaces(t, [], { 'include-workspace-root': true, workspace: 'd', })) @@ -1827,7 +1909,7 @@ t.test('ls --parseable', async t => { }) await ls.exec([]) - t.matchSnapshot(cleanCwd(result()), 'should contain overridden outout') + t.matchSnapshot(cleanCwd(result()), 'should contain overridden output') }) t.test('with filter arg', async t => { @@ -1848,7 +1930,7 @@ t.test('ls --parseable', async t => { await ls.exec(['chai']) t.matchSnapshot( cleanCwd(result()), - 'should output parseable contaning only occurrences of filtered by package' + 'should output parseable containing only occurrences of filtered by package' ) }) @@ -1870,7 +1952,7 @@ t.test('ls --parseable', async t => { await ls.exec(['dog']) t.matchSnapshot( cleanCwd(result()), - 'should output parseable contaning only occurrences of filtered package' + 'should output parseable containing only occurrences of filtered package' ) }) @@ -1901,8 +1983,7 @@ t.test('ls --parseable', async t => { await ls.exec(['dog@*', 'chai@1.0.0']) t.matchSnapshot( cleanCwd(result()), - /* eslint-disable-next-line max-len */ - 'should output parseable contaning only occurrences of multiple filtered packages and their ancestors' + 'should output parseable containing only occurrences of multiple filtered packages and their ancestors' ) }) @@ -2465,7 +2546,6 @@ t.test('ls --parseable', async t => { 'node_modules/abbrev': { name: 'abbrev', version: '1.1.1', - /* eslint-disable-next-line max-len */ resolved: 'git+https://github.com/isaacs/abbrev-js.git#b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c', }, }, @@ -2476,7 +2556,6 @@ t.test('ls --parseable', async t => { version: '1.1.1', _id: 'abbrev@1.1.1', _from: 'git+https://github.com/isaacs/abbrev-js.git', - /* eslint-disable-next-line max-len */ _resolved: 'git+https://github.com/isaacs/abbrev-js.git#b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c', _requested: { type: 'git', @@ -2948,7 +3027,7 @@ t.test('ls --json', async t => { }, }, }, - 'should output json contaning only occurrences of filtered by package' + 'should output json containing only occurrences of filtered by package' ) t.not(process.exitCode, 1, 'should not exit with error code 1') }) @@ -2989,7 +3068,7 @@ t.test('ls --json', async t => { }, }, }, - 'should output json contaning only occurrences of filtered by package' + 'should output json containing only occurrences of filtered by package' ) t.notOk(jsonParse(result()).dependencies.chai) }) @@ -3043,8 +3122,7 @@ t.test('ls --json', async t => { }, }, }, - /* eslint-disable-next-line max-len */ - 'should output json contaning only occurrences of multiple filtered packages and their ancestors' + 'should output json containing only occurrences of multiple filtered packages and their ancestors' ) }) @@ -3489,9 +3567,7 @@ t.test('ls --json', async t => { 'node_modules/@isaacs/dedupe-tests-a': { name: '@isaacs/dedupe-tests-a', version: '1.0.1', - /* eslint-disable-next-line max-len */ resolved: 'https://registry.npmjs.org/@isaacs/dedupe-tests-a/-/dedupe-tests-a-1.0.1.tgz', - /* eslint-disable-next-line max-len */ integrity: 'sha512-8AN9lNCcBt5Xeje7fMEEpp5K3rgcAzIpTtAjYb/YMUYu8SbIVF6wz0WqACDVKvpQOUcSfNHZQNLNmue0QSwXOQ==', dependencies: { '@isaacs/dedupe-tests-b': '1', @@ -3500,26 +3576,20 @@ t.test('ls --json', async t => { 'node_modules/@isaacs/dedupe-tests-a/node_modules/@isaacs/dedupe-tests-b': { name: '@isaacs/dedupe-tests-b', version: '1.0.0', - /* eslint-disable-next-line max-len */ resolved: 'https://registry.npmjs.org/@isaacs/dedupe-tests-b/-/dedupe-tests-b-1.0.0.tgz', - /* eslint-disable-next-line max-len */ integrity: 'sha512-3nmvzIb8QL8OXODzipwoV3U8h9OQD9g9RwOPuSBQqjqSg9JZR1CCFOWNsDUtOfmwY8HFUJV9EAZ124uhqVxq+w==', }, 'node_modules/@isaacs/dedupe-tests-b': { name: '@isaacs/dedupe-tests-b', version: '2.0.0', - /* eslint-disable-next-line max-len */ resolved: 'https://registry.npmjs.org/@isaacs/dedupe-tests-b/-/dedupe-tests-b-2.0.0.tgz', - /* eslint-disable-next-line max-len */ integrity: 'sha512-KTYkpRv9EzlmCg4Gsm/jpclWmRYFCXow8GZKJXjK08sIZBlElTZEa5Bw/UQxIvEfcKmWXczSqItD49Kr8Ax4UA==', }, }, dependencies: { '@isaacs/dedupe-tests-a': { version: '1.0.1', - /* eslint-disable-next-line max-len */ resolved: 'https://registry.npmjs.org/@isaacs/dedupe-tests-a/-/dedupe-tests-a-1.0.1.tgz', - /* eslint-disable-next-line max-len */ integrity: 'sha512-8AN9lNCcBt5Xeje7fMEEpp5K3rgcAzIpTtAjYb/YMUYu8SbIVF6wz0WqACDVKvpQOUcSfNHZQNLNmue0QSwXOQ==', requires: { '@isaacs/dedupe-tests-b': '1', @@ -3527,18 +3597,14 @@ t.test('ls --json', async t => { dependencies: { '@isaacs/dedupe-tests-b': { version: '1.0.0', - /* eslint-disable-next-line max-len */ resolved: 'https://registry.npmjs.org/@isaacs/dedupe-tests-b/-/dedupe-tests-b-1.0.0.tgz', - /* eslint-disable-next-line max-len */ integrity: 'sha512-3nmvzIb8QL8OXODzipwoV3U8h9OQD9g9RwOPuSBQqjqSg9JZR1CCFOWNsDUtOfmwY8HFUJV9EAZ124uhqVxq+w==', }, }, }, '@isaacs/dedupe-tests-b': { version: '2.0.0', - /* eslint-disable-next-line max-len */ resolved: 'https://registry.npmjs.org/@isaacs/dedupe-tests-b/-/dedupe-tests-b-2.0.0.tgz', - /* eslint-disable-next-line max-len */ integrity: 'sha512-KTYkpRv9EzlmCg4Gsm/jpclWmRYFCXow8GZKJXjK08sIZBlElTZEa5Bw/UQxIvEfcKmWXczSqItD49Kr8Ax4UA==', }, }, @@ -3572,7 +3638,6 @@ t.test('ls --json', async t => { extraneous: true, overridden: false, problems: [ - /* eslint-disable-next-line max-len */ 'extraneous: @isaacs/dedupe-tests-b@ {CWD}/prefix/node_modules/@isaacs/dedupe-tests-a/node_modules/@isaacs/dedupe-tests-b', ], }, @@ -3586,7 +3651,6 @@ t.test('ls --json', async t => { }, }, problems: [ - /* eslint-disable-next-line max-len */ 'extraneous: @isaacs/dedupe-tests-b@ {CWD}/prefix/node_modules/@isaacs/dedupe-tests-a/node_modules/@isaacs/dedupe-tests-b', ], }, @@ -3860,7 +3924,7 @@ t.test('ls --json', async t => { await t.rejects( ls.exec([]), { code: 'EJSONPARSE', message: 'Failed to parse root package.json' }, - 'should have missin root package.json msg' + 'should have missing root package.json msg' ) t.same( jsonParse(result()), @@ -4212,7 +4276,6 @@ t.test('ls --json', async t => { version: '1.1.1', id: 'abbrev@1.1.1', from: 'git+https://github.com/isaacs/abbrev-js.git', - /* eslint-disable-next-line max-len */ resolved: 'git+https://github.com/isaacs/abbrev-js.git#b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c', }, }, @@ -4223,7 +4286,6 @@ t.test('ls --json', async t => { version: '1.1.1', _id: 'abbrev@1.1.1', _from: 'git+https://github.com/isaacs/abbrev-js.git', - /* eslint-disable-next-line max-len */ _resolved: 'git+https://github.com/isaacs/abbrev-js.git#b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c', _requested: { type: 'git', @@ -4249,8 +4311,7 @@ t.test('ls --json', async t => { abbrev: { version: '1.1.1', overridden: false, - /* eslint-disable-next-line max-len */ - resolved: 'git+ssh://git@github.com/isaacs/abbrev-js.git#b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c', + resolved: 'git+https://github.com/isaacs/abbrev-js.git#b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c', }, }, }, @@ -4689,7 +4750,7 @@ t.test('ls --package-lock-only', async t => { }, }, }, - 'should output json contaning only occurrences of filtered by package' + 'should output json containing only occurrences of filtered by package' ) t.notOk(process.exitCode, 'should not set exit code') }) @@ -4749,7 +4810,7 @@ t.test('ls --package-lock-only', async t => { }, }, }, - 'should output json contaning only occurrences of filtered by package' + 'should output json containing only occurrences of filtered by package' ) }) @@ -4813,8 +4874,7 @@ t.test('ls --package-lock-only', async t => { }, }, }, - /* eslint-disable-next-line max-len */ - 'should output json contaning only occurrences of multiple filtered packages and their ancestors' + 'should output json containing only occurrences of multiple filtered packages and their ancestors' ) }) @@ -5137,9 +5197,7 @@ t.test('ls --package-lock-only', async t => { 'node_modules/@isaacs/dedupe-tests-a': { name: '@isaacs/dedupe-tests-a', version: '1.0.1', - /* eslint-disable-next-line max-len */ resolved: 'https://registry.npmjs.org/@isaacs/dedupe-tests-a/-/dedupe-tests-a-1.0.1.tgz', - /* eslint-disable-next-line max-len */ integrity: 'sha512-8AN9lNCcBt5Xeje7fMEEpp5K3rgcAzIpTtAjYb/YMUYu8SbIVF6wz0WqACDVKvpQOUcSfNHZQNLNmue0QSwXOQ==', dependencies: { '@isaacs/dedupe-tests-b': '1', @@ -5148,26 +5206,20 @@ t.test('ls --package-lock-only', async t => { 'node_modules/@isaacs/dedupe-tests-a/node_modules/@isaacs/dedupe-tests-b': { name: '@isaacs/dedupe-tests-b', version: '1.0.0', - /* eslint-disable-next-line max-len */ resolved: 'https://registry.npmjs.org/@isaacs/dedupe-tests-b/-/dedupe-tests-b-1.0.0.tgz', - /* eslint-disable-next-line max-len */ integrity: 'sha512-3nmvzIb8QL8OXODzipwoV3U8h9OQD9g9RwOPuSBQqjqSg9JZR1CCFOWNsDUtOfmwY8HFUJV9EAZ124uhqVxq+w==', }, 'node_modules/@isaacs/dedupe-tests-b': { name: '@isaacs/dedupe-tests-b', version: '2.0.0', - /* eslint-disable-next-line max-len */ resolved: 'https://registry.npmjs.org/@isaacs/dedupe-tests-b/-/dedupe-tests-b-2.0.0.tgz', - /* eslint-disable-next-line max-len */ integrity: 'sha512-KTYkpRv9EzlmCg4Gsm/jpclWmRYFCXow8GZKJXjK08sIZBlElTZEa5Bw/UQxIvEfcKmWXczSqItD49Kr8Ax4UA==', }, }, dependencies: { '@isaacs/dedupe-tests-a': { version: '1.0.1', - /* eslint-disable-next-line max-len */ resolved: 'https://registry.npmjs.org/@isaacs/dedupe-tests-a/-/dedupe-tests-a-1.0.1.tgz', - /* eslint-disable-next-line max-len */ integrity: 'sha512-8AN9lNCcBt5Xeje7fMEEpp5K3rgcAzIpTtAjYb/YMUYu8SbIVF6wz0WqACDVKvpQOUcSfNHZQNLNmue0QSwXOQ==', requires: { '@isaacs/dedupe-tests-b': '1', @@ -5175,18 +5227,14 @@ t.test('ls --package-lock-only', async t => { dependencies: { '@isaacs/dedupe-tests-b': { version: '1.0.0', - /* eslint-disable-next-line max-len */ resolved: 'https://registry.npmjs.org/@isaacs/dedupe-tests-b/-/dedupe-tests-b-1.0.0.tgz', - /* eslint-disable-next-line max-len */ integrity: 'sha512-3nmvzIb8QL8OXODzipwoV3U8h9OQD9g9RwOPuSBQqjqSg9JZR1CCFOWNsDUtOfmwY8HFUJV9EAZ124uhqVxq+w==', }, }, }, '@isaacs/dedupe-tests-b': { version: '2.0.0', - /* eslint-disable-next-line max-len */ resolved: 'https://registry.npmjs.org/@isaacs/dedupe-tests-b/-/dedupe-tests-b-2.0.0.tgz', - /* eslint-disable-next-line max-len */ integrity: 'sha512-KTYkpRv9EzlmCg4Gsm/jpclWmRYFCXow8GZKJXjK08sIZBlElTZEa5Bw/UQxIvEfcKmWXczSqItD49Kr8Ax4UA==', }, }, @@ -5298,7 +5346,6 @@ t.test('ls --package-lock-only', async t => { requires: true, dependencies: { abbrev: { - /* eslint-disable-next-line max-len */ version: 'git+ssh://git@github.com/isaacs/abbrev-js.git#b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c', from: 'abbrev@git+https://github.com/isaacs/abbrev-js.git', }, @@ -5314,7 +5361,6 @@ t.test('ls --package-lock-only', async t => { version: '1.0.0', dependencies: { abbrev: { - /* eslint-disable-next-line max-len */ resolved: 'git+ssh://git@github.com/isaacs/abbrev-js.git#b8f3a2fc0c3bb8ffd8b0d0072cc6b5a3667e963c', overridden: false, }, @@ -5325,3 +5371,167 @@ t.test('ls --package-lock-only', async t => { }) }) }) + +t.test('completion', async t => { + const { ls } = await mockNpm(t, { + command: 'ls', + prefixDir: { + node_modules: { + foo: { + 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }), + }, + }, + 'package.json': JSON.stringify({ name: 'project', version: '1.0.0' }), + }, + }) + const res = await ls.completion({ conf: { argv: { remain: ['npm', 'ls'] } } }) + t.type(res, Array) +}) + +t.test('ls --install-strategy=linked', async t => { + t.test('should not report undeclared workspaces as UNMET DEPENDENCY', async t => { + const { result, ls } = await mockLs(t, { + config: { + 'install-strategy': 'linked', + }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'test-linked-ws', + version: '1.0.0', + workspaces: ['packages/*'], + dependencies: { 'workspace-a': '*' }, + }), + packages: { + 'workspace-a': { + 'package.json': JSON.stringify({ + name: 'workspace-a', + version: '1.0.0', + }), + }, + 'workspace-b': { + 'package.json': JSON.stringify({ + name: 'workspace-b', + version: '1.0.0', + }), + }, + }, + node_modules: { + 'workspace-a': t.fixture('symlink', '../packages/workspace-a'), + // workspace-b intentionally NOT linked (undeclared in dependencies) + }, + }, + }) + await ls.exec([]) + const output = cleanCwd(result()) + t.notMatch(output, /UNMET DEPENDENCY/, 'should not report undeclared workspace as UNMET DEPENDENCY') + t.match(output, /workspace-a/, 'should list declared workspace') + }) + + t.test('should not report devDeps of store packages as UNMET DEPENDENCY', async t => { + const { result, ls } = await mockLs(t, { + config: { + 'install-strategy': 'linked', + }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'test-linked-store', + version: '1.0.0', + dependencies: { nopt: '^1.0.0' }, + }), + node_modules: { + nopt: t.fixture('symlink', '.store/nopt@1.0.0/node_modules/nopt'), + '.store': { + 'nopt@1.0.0': { + node_modules: { + nopt: { + 'package.json': JSON.stringify({ + name: 'nopt', + version: '1.0.0', + devDependencies: { tap: '^16.0.0' }, + }), + }, + }, + }, + }, + }, + }, + }) + await ls.exec([]) + const output = cleanCwd(result()) + t.notMatch(output, /UNMET DEPENDENCY/, 'should not report devDeps of store packages') + t.match(output, /nopt/, 'should list the dependency') + }) + + t.test('should still report declared workspace as UNMET DEPENDENCY when missing', async t => { + const { ls } = await mockLs(t, { + config: { + 'install-strategy': 'linked', + }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'test-linked-ws-missing', + version: '1.0.0', + workspaces: ['packages/*'], + dependencies: { 'workspace-a': '*' }, + }), + packages: { + 'workspace-a': { + 'package.json': JSON.stringify({ + name: 'workspace-a', + version: '1.0.0', + }), + }, + }, + node_modules: { + // workspace-a is declared but its symlink is missing + }, + }, + }) + await t.rejects(ls.exec([]), { code: 'ELSPROBLEMS' }, + 'should report declared workspace as UNMET DEPENDENCY') + }) +}) + +t.test('patched dependency annotation', async t => { + const patchedLock = { + name: 'test-npm-ls', + version: '1.0.0', + lockfileVersion: 4, + requires: true, + packages: { + '': { name: 'test-npm-ls', version: '1.0.0', dependencies: { foo: '^1.0.0' } }, + 'node_modules/foo': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/foo/-/foo-1.0.0.tgz', + integrity: 'sha512-deadbeef', + patched: { path: 'patches/foo@1.0.0.patch', integrity: 'sha512-abc' }, + }, + }, + } + const prefixDir = { + 'package.json': JSON.stringify({ + name: 'test-npm-ls', + version: '1.0.0', + dependencies: { foo: '^1.0.0' }, + patchedDependencies: { 'foo@1.0.0': 'patches/foo@1.0.0.patch' }, + }), + node_modules: { + '.package-lock.json': JSON.stringify(patchedLock), + foo: { 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }) }, + }, + } + + t.test('human output annotates the patched dependency', async t => { + const { npm, result, ls } = await mockLs(t, { config: {}, prefixDir }) + touchHiddenPackageLock(npm.prefix) + await ls.exec([]) + t.match(result(), /foo@1\.0\.0 \[patched: patches\/foo@1\.0\.0\.patch\]/) + }) + + t.test('json output records the patch path', async t => { + const { npm, result, ls } = await mockLs(t, { config: { json: true }, prefixDir }) + touchHiddenPackageLock(npm.prefix) + await ls.exec([]) + t.equal(JSON.parse(result()).dependencies.foo.patched, 'patches/foo@1.0.0.patch') + }) +}) diff --git a/test/lib/commands/org.js b/test/lib/commands/org.js index 7a1538d9c69e4..ad82e79dc5cc3 100644 --- a/test/lib/commands/org.js +++ b/test/lib/commands/org.js @@ -424,7 +424,7 @@ t.test('npm org ls', async t => { org: 'orgname', opts: npm.flatOptions, }, - 'receieved the correct args' + 'received the correct args' ) t.strictSame(outputs, [ 'one - developer', @@ -450,7 +450,7 @@ t.test('npm org ls - user filter', async t => { org: 'orgname', opts: npm.flatOptions, }, - 'receieved the correct args' + 'received the correct args' ) t.strictSame(outputs, [ 'username - admin', @@ -473,7 +473,7 @@ t.test('npm org ls - user filter, missing user', async t => { org: 'orgname', opts: npm.flatOptions, }, - 'receieved the correct args' + 'received the correct args' ) t.strictSame(outputs, []) }) @@ -503,7 +503,7 @@ t.test('npm org ls - json output', async t => { org: 'orgname', opts: npm.flatOptions, }, - 'receieved the correct args' + 'received the correct args' ) t.strictSame(JSON.parse(outputs[0]), orgList, 'prints the correct output') }) @@ -528,7 +528,7 @@ t.test('npm org ls - parseable output', async t => { org: 'orgname', opts: npm.flatOptions, }, - 'receieved the correct args' + 'received the correct args' ) t.strictSame( outputs.map(line => line.split(/\t/)), @@ -562,7 +562,7 @@ t.test('npm org ls - silent output', async t => { org: 'orgname', opts: npm.flatOptions, }, - 'receieved the correct args' + 'received the correct args' ) t.strictSame(outputs, [], 'printed no output') }) diff --git a/test/lib/commands/outdated.js b/test/lib/commands/outdated.js index 34e60d911bff4..34b8ea75190fc 100644 --- a/test/lib/commands/outdated.js +++ b/test/lib/commands/outdated.js @@ -57,6 +57,24 @@ const packument = spec => { }, }, }, + timed: { + name: 'timed', + 'dist-tags': { + latest: '2.0.0', + }, + versions: { + '1.0.0': { + version: '1.0.0', + }, + '2.0.0': { + version: '2.0.0', + }, + }, + time: { + '1.0.0': '2020-01-01T00:00:00.000Z', + '2.0.0': '2020-06-01T00:00:00.000Z', + }, + }, } if (spec.name === 'eta') { @@ -582,7 +600,7 @@ t.test('workspaces', async t => { await t.test('should display all dependencies', t => mockWorkspaces(t, { all: true })) - await t.test('should highlight ws in dependend by section', t => + await t.test('should highlight ws in depended by section', t => mockWorkspaces(t, { color: 'always' })) await t.test('should display results filtered by ws', t => @@ -662,3 +680,126 @@ t.test('aliases with version range', async t => { ) t.equal(process.exitCode, 1) }) + +t.test('dependent location', async t => { + const testDir = { + 'package.json': JSON.stringify({ + name: 'similar-name', + version: '1.0.0', + workspaces: ['a', 'nest/a'], + }), + a: { + 'package.json': JSON.stringify({ + name: 'a', + version: '1.0.0', + dependencies: { + dog: '^1.0.0', + }, + }), + }, + nest: { + a: { + 'package.json': JSON.stringify({ + name: 'nest-a', + version: '1.0.0', + dependencies: { + dog: '^1.0.0', + }, + }), + }, + }, + node_modules: { + dog: { + 'package.json': JSON.stringify({ + name: 'dog', + version: '1.0.0', + }), + }, + a: t.fixture('symlink', '../a'), + 'nest-a': t.fixture('symlink', '../nest/a'), + }, + + } + t.test(`--long`, async t => { + const { outdated, joinedOutput } = await mockNpm(t, { + prefixDir: testDir, + config: { + long: true, + }, + }) + await outdated.exec([]) + t.matchSnapshot( + joinedOutput(), + 'should display dependent location when using --long' + ) + }) + + t.test('--long --json', async t => { + const { outdated, joinedOutput } = await mockNpm(t, { + prefixDir: testDir, + config: { + long: true, + json: true, + }, + }) + await outdated.exec([]) + t.matchSnapshot( + joinedOutput(), + 'should display dependent location when using --long and --json' + ) + }) +}) + +t.test('min-release-age-exclude', async t => { + const prefixDir = { + 'package.json': JSON.stringify({ + name: 'project', + version: '1.0.0', + dependencies: { + timed: '^1.0.0', + }, + }, null, 2), + node_modules: { + timed: { + 'package.json': JSON.stringify({ + name: 'timed', + version: '1.0.0', + }, null, 2), + }, + }, + } + + await t.test('before hides the newer version', async t => { + const { outdated, joinedOutput } = await mockNpm(t, { + prefixDir, + config: { before: new Date('2020-03-01') }, + }) + await outdated.exec([]) + t.notMatch(joinedOutput(), 'timed', 'newer version filtered out by before') + }) + + await t.test('exact-name exclude restores the newer version', async t => { + const { outdated, joinedOutput } = await mockNpm(t, { + prefixDir, + config: { + before: new Date('2020-03-01'), + 'min-release-age-exclude': ['timed'], + }, + }) + await outdated.exec([]) + t.match(joinedOutput(), 'timed', 'excluded package is reported as outdated') + t.match(joinedOutput(), '2.0.0', 'latest 2.0.0 is surfaced') + }) + + await t.test('glob exclude restores the newer version', async t => { + const { outdated, joinedOutput } = await mockNpm(t, { + prefixDir, + config: { + before: new Date('2020-03-01'), + 'min-release-age-exclude': ['tim*'], + }, + }) + await outdated.exec([]) + t.match(joinedOutput(), '2.0.0', 'glob-excluded package shows newer version') + }) +}) diff --git a/test/lib/commands/pack.js b/test/lib/commands/pack.js index 7e98b12704df9..121992bdfc887 100644 --- a/test/lib/commands/pack.js +++ b/test/lib/commands/pack.js @@ -72,7 +72,7 @@ t.test('should log output as valid json', async t => { }) t.test('should log scoped package output as valid json', async t => { - const { npm, outputs, outputErrors, logs } = await loadMockNpm(t, { + const { npm, outputs, logs } = await loadMockNpm(t, { prefixDir: { 'package.json': JSON.stringify({ name: '@myscope/test-package', @@ -90,7 +90,6 @@ t.test('should log scoped package output as valid json', async t => { await npm.exec('pack', []) const filename = 'myscope-test-package-1.0.0.tgz' t.matchSnapshot(outputs.map(JSON.parse), 'outputs as json') - t.matchSnapshot(outputErrors, 'stderr has banners') t.matchSnapshot(logs.notice, 'logs pack contents') t.ok(fs.statSync(path.resolve(npm.prefix, filename))) }) @@ -132,12 +131,8 @@ t.test('foreground-scripts defaults to true', async t => { const filename = 'test-fg-scripts-0.0.0.tgz' t.strictSame( outputs, - [ - '\n> test-fg-scripts@0.0.0 prepack\n> echo prepack!\n', - '\n> test-fg-scripts@0.0.0 postpack\n> echo postpack!\n', - filename, - ], - 'prepack and postpack log to stdout' + [filename], + 'tarball filename is the only stdout output' ) t.matchSnapshot(logs.notice, 'logs pack contents') t.throws(() => fs.statSync(path.resolve(npm.prefix, filename))) diff --git a/test/lib/commands/patch.js b/test/lib/commands/patch.js new file mode 100644 index 0000000000000..ac409bf2d175a --- /dev/null +++ b/test/lib/commands/patch.js @@ -0,0 +1,1328 @@ +const fs = require('node:fs') +const path = require('node:path') +const t = require('tap') +const Arborist = require('@npmcli/arborist') +const pacote = require('pacote') + +const { loadNpmWithRegistry: loadMockNpm } = require('../../fixtures/mock-npm') +const Patch = require('../../../lib/commands/patch.js') + +// Tiny dependency served by the mock registry so pacote can extract it. +const DEP_NAME = 'patch-me' +const DEP_VERSION = '1.0.0' +const DEP_SRC = 'module.exports = function () { return "original" }\n' + +// On-disk tarball contents for the dependency. +const depTarball = { + 'package.json': JSON.stringify({ name: DEP_NAME, version: DEP_VERSION }), + 'index.js': DEP_SRC, +} + +// Root project package.json depending on the patchable dep. +const rootPackageJson = { + name: 'root-project', + version: '1.0.0', + dependencies: { [DEP_NAME]: `^${DEP_VERSION}` }, +} + +// Lockfile pre-resolving the dep so installs/reifies are deterministic. +const rootPackageLock = { + name: 'root-project', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { + name: 'root-project', + version: '1.0.0', + dependencies: { [DEP_NAME]: `^${DEP_VERSION}` }, + }, + [`node_modules/${DEP_NAME}`]: { + version: DEP_VERSION, + resolved: `https://registry.npmjs.org/${DEP_NAME}/-/${DEP_NAME}-${DEP_VERSION}.tgz`, + }, + }, +} + +// Persist the manifest and tarball so the many extract and reify passes (add, commit baseline, reify, rm reify, install) all find a tarball without having to count requests precisely. +const setupDep = async (npm, registry) => { + const manifest = registry.manifest({ name: DEP_NAME, versions: [DEP_VERSION] }) + const dist = new URL(manifest.versions[DEP_VERSION].dist.tarball) + const tar = await pacote.tarball(path.join(npm.prefix, 'dep-tarball'), { Arborist }) + registry.nock.get(`/${DEP_NAME}`).reply(200, manifest).persist() + registry.nock.get(dist.pathname).reply(200, tar).persist() + return manifest +} + +const basePrefix = () => ({ + 'dep-tarball': depTarball, + 'package.json': JSON.stringify(rootPackageJson), + 'package-lock.json': JSON.stringify(rootPackageLock), +}) + +const readJson = file => JSON.parse(fs.readFileSync(file, 'utf8')) + +t.test('no args rejects with EUSAGE', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: basePrefix(), + }) + await t.rejects(npm.exec('patch', []), { code: 'EUSAGE' }, 'bare npm patch is a usage error') +}) + +t.test('add with no pkg rejects with EUSAGE', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: basePrefix(), + }) + await t.rejects(npm.exec('patch', ['add']), { code: 'EUSAGE' }) +}) + +t.test('add rejects non-registry spec with EPATCHNONREGISTRY', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: basePrefix(), + }) + await t.rejects( + npm.exec('patch', ['add', 'file:./dep-tarball']), + { code: 'EPATCHNONREGISTRY' }, + 'file: spec is rejected' + ) +}) + +t.test('add accepts an edgeless installed node (extraneous / linked store)', async t => { + // an installed-but-undeclared dep has no edges, so isRegistryDependency is false; + // it must not be misread as non-registry the way a linked store node or extraneous install would be + const { npm, joinedOutput, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: { + 'dep-tarball': depTarball, + 'package.json': JSON.stringify({ name: 'root-project', version: '1.0.0' }), + node_modules: { + [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: DEP_VERSION }) }, + }, + }, + }) + await setupDep(npm, registry) + await npm.exec('patch', ['add', DEP_NAME]) + t.match(joinedOutput(), /You can now edit the following directory: /, 'edgeless node is patchable') +}) + +t.test('full round-trip: install, add, edit, commit, ls, rm', async t => { + const { npm, joinedOutput, registry, outputs } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + + // install the dep so it is present on disk + await npm.exec('install', []) + const installedIndex = path.join(npm.prefix, 'node_modules', DEP_NAME, 'index.js') + t.equal(fs.readFileSync(installedIndex, 'utf8'), DEP_SRC, 'installed clean') + + // npm patch add prints the edit dir and commit hint + outputs.length = 0 + await npm.exec('patch', ['add', DEP_NAME]) + const addOut = joinedOutput() + t.match(addOut, /You can now edit the following directory: /, 'prints edit dir line') + t.match(addOut, /When done, run: npm patch commit /, 'prints commit hint line') + + const editDirMatch = addOut.match(/You can now edit the following directory: (.+)/) + const editDir = editDirMatch[1].trim() + t.ok(fs.existsSync(path.join(editDir, 'package.json')), 'extracted package.json to edit dir') + + // edit a file in the printed edit dir + const edited = 'module.exports = function () { return "patched" }\n' + fs.writeFileSync(path.join(editDir, 'index.js'), edited) + + // npm patch commit + outputs.length = 0 + await npm.exec('patch', ['commit', editDir]) + + // patches/@.patch exists + const patchFile = path.join(npm.prefix, 'patches', `${DEP_NAME}@${DEP_VERSION}.patch`) + t.ok(fs.existsSync(patchFile), 'patch file written under patches/') + t.match(fs.readFileSync(patchFile, 'utf8'), /patched/, 'patch file contains the edit') + + // package.json has the relative patchedDependencies entry + const pkg = readJson(path.join(npm.prefix, 'package.json')) + t.same( + pkg.patchedDependencies, + { [`${DEP_NAME}@${DEP_VERSION}`]: `patches/${DEP_NAME}@${DEP_VERSION}.patch` }, + 'patchedDependencies has the relative posix entry' + ) + + // package-lock.json: lockfileVersion 4 and packages[node_modules/].patched + const lock = readJson(path.join(npm.prefix, 'package-lock.json')) + t.equal(lock.lockfileVersion, 4, 'lockfile bumped to v4') + const lockNode = lock.packages[`node_modules/${DEP_NAME}`] + t.ok(lockNode.patched, 'lockfile node has patched block') + t.equal(lockNode.patched.path, `patches/${DEP_NAME}@${DEP_VERSION}.patch`, 'patched.path set') + t.match(lockNode.patched.integrity, /^sha512-/, 'patched.integrity is an SSRI') + + // the installed file on disk contains the edit + t.equal(fs.readFileSync(installedIndex, 'utf8'), edited, 'installed file is patched on disk') + + // edit dir removed by default + t.notOk(fs.existsSync(editDir), 'edit dir removed when keep-edit-dir not set') + + // npm patch ls lists the entry + outputs.length = 0 + await npm.exec('patch', ['ls']) + const lsOut = joinedOutput() + t.match(lsOut, new RegExp(`patches/${DEP_NAME}@${DEP_VERSION}\\.patch`), 'ls shows patch path') + t.match(lsOut, new RegExp(`${DEP_NAME}@${DEP_VERSION}`), 'ls shows selector') + t.match(lsOut, /\(1 node\)/, 'ls shows node count') + + // npm patch rm removes the entry from package.json and deletes the file + outputs.length = 0 + await npm.exec('patch', ['rm', DEP_NAME]) + const pkgAfter = readJson(path.join(npm.prefix, 'package.json')) + t.notOk(pkgAfter.patchedDependencies, 'patchedDependencies removed from package.json') + t.notOk(fs.existsSync(patchFile), 'patch file deleted') + + // rm clears the patch record from the lockfile and reverts the installed file + const lockAfter = readJson(path.join(npm.prefix, 'package-lock.json')) + t.notOk( + lockAfter.packages[`node_modules/${DEP_NAME}`].patched, + 'lockfile patched block removed' + ) + t.equal( + fs.readFileSync(installedIndex, 'utf8'), + DEP_SRC, + 'installed file reverted to original' + ) +}) + +t.test('bare form routes to add', async t => { + const { npm, joinedOutput, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + await npm.exec('install', []) + + // npm patch behaves like npm patch add + await npm.exec('patch', [DEP_NAME]) + t.match(joinedOutput(), /You can now edit the following directory: /, 'bare form extracts like add') +}) + +t.test('npm ci rejects patch path drift from the lockfile', async t => { + const { npm, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + await npm.exec('install', []) + + // commit a real patch so the lockfile records patched.path + const editDir = path.join(npm.prefix, 'edit') + await pacote.extract(`${DEP_NAME}@${DEP_VERSION}`, editDir, npm.flatOptions) + fs.writeFileSync(path.join(editDir, 'index.js'), 'module.exports = () => "patched"\n') + await npm.exec('patch', ['commit', editDir]) + + // move the patch file and repoint package.json without updating the lockfile + const pkgPath = path.join(npm.prefix, 'package.json') + const pkg = readJson(pkgPath) + const key = `${DEP_NAME}@${DEP_VERSION}` + const oldPath = path.join(npm.prefix, pkg.patchedDependencies[key]) + const newRel = 'patches/renamed.patch' + fs.renameSync(oldPath, path.join(npm.prefix, newRel)) + pkg.patchedDependencies[key] = newRel + fs.writeFileSync(pkgPath, JSON.stringify(pkg)) + + await t.rejects( + npm.exec('ci', []), + /package-lock\.json are in sync/, + 'npm ci refuses when the patch path diverges from the lockfile' + ) +}) + +t.test('rm with no registered patch rejects with EPATCHNOTFOUND', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: basePrefix(), + }) + await t.rejects( + npm.exec('patch', ['rm', DEP_NAME]), + { code: 'EPATCHNOTFOUND' }, + 'rm errors when nothing matches' + ) +}) + +t.test('ls with no patches prints nothing', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: basePrefix(), + }) + await npm.exec('patch', ['ls']) + t.equal(joinedOutput(), '', 'no output when no patchedDependencies') +}) + +t.test('ls with no package.json prints nothing', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: {}, + }) + await npm.exec('patch', ['ls']) + t.equal(joinedOutput(), '', 'no output and no crash without a package.json') +}) + +t.test('add with edit-dir config uses that directory', async t => { + const { npm, joinedOutput, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + await npm.exec('install', []) + + const customDir = path.join(npm.prefix, 'my-edit-dir') + npm.config.set('edit-dir', customDir) + await npm.exec('patch', ['add', DEP_NAME]) + t.match(joinedOutput(), new RegExp('my-edit-dir'), 'uses configured edit dir') + t.ok(fs.existsSync(path.join(customDir, 'package.json')), 'extracted into configured dir') +}) + +t.test('add: not-installed bare name rejects with EPATCHNOTINSTALLED', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ name: 'root-project', version: '1.0.0' }), + }, + }) + await t.rejects( + npm.exec('patch', ['add', DEP_NAME]), + { code: 'EPATCHNOTINSTALLED' }, + 'errors when no installed version and no explicit version' + ) +}) + +t.test('add: ambiguous when multiple versions installed', async t => { + // root-direct 1.0.0 plus two nested 2.0.0 copies, so the dedup guard and the root-dependant label are both exercised while listing the ambiguity + const nestedDep = v => ({ + node_modules: { [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: v }) } }, + }) + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root-project', + version: '1.0.0', + dependencies: { [DEP_NAME]: '1.0.0', b: '1.0.0', c: '1.0.0' }, + }), + node_modules: { + [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: '1.0.0' }) }, + b: { + 'package.json': JSON.stringify({ name: 'b', version: '1.0.0', dependencies: { [DEP_NAME]: '2.0.0' } }), + ...nestedDep('2.0.0'), + }, + c: { + 'package.json': JSON.stringify({ name: 'c', version: '1.0.0', dependencies: { [DEP_NAME]: '2.0.0' } }), + ...nestedDep('2.0.0'), + }, + }, + }, + }) + await t.rejects( + npm.exec('patch', ['add', DEP_NAME]), + { code: 'EPATCHAMBIGUOUS' }, + 'errors when multiple versions are installed for a bare name' + ) +}) + +t.test('add: an installed file: dependency is rejected as non-registry', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root-project', version: '1.0.0', dependencies: { [DEP_NAME]: 'file:./local' }, + }), + local: { 'package.json': JSON.stringify({ name: DEP_NAME, version: DEP_VERSION }) }, + node_modules: { + [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: DEP_VERSION }) }, + }, + }, + }) + await t.rejects( + npm.exec('patch', ['add', DEP_NAME]), + { code: 'EPATCHNONREGISTRY' }, + 'cannot patch a file: dependency that is already installed' + ) +}) + +t.test('add: a version installed as both registry and file: is rejected', async t => { + // one consumer pulls the registry copy, another pulls a file: copy of the same version; + // the file: edge must still cause a rejection even though a registry edge also exists + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root-project', + version: '1.0.0', + dependencies: { [DEP_NAME]: '1.0.0', b: '1.0.0' }, + }), + local: { 'package.json': JSON.stringify({ name: DEP_NAME, version: DEP_VERSION }) }, + node_modules: { + [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: DEP_VERSION }) }, + b: { + 'package.json': JSON.stringify({ + name: 'b', version: '1.0.0', dependencies: { [DEP_NAME]: 'file:../../local' }, + }), + node_modules: { + [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: DEP_VERSION }) }, + }, + }, + }, + }, + }) + await t.rejects( + npm.exec('patch', ['add', DEP_NAME]), + { code: 'EPATCHNONREGISTRY' }, + 'a version with any file: consumer cannot be patched' + ) +}) + +t.test('add: a range matching multiple installed versions is ambiguous', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root-project', + version: '1.0.0', + dependencies: { [DEP_NAME]: '1.0.0', b: '1.0.0' }, + }), + node_modules: { + [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: '1.0.0' }) }, + b: { + 'package.json': JSON.stringify({ name: 'b', version: '1.0.0', dependencies: { [DEP_NAME]: '2.0.0' } }), + node_modules: { [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: '2.0.0' }) } }, + }, + }, + }, + }) + await t.rejects( + npm.exec('patch', ['add', `${DEP_NAME}@>=1.0.0`]), + { code: 'EPATCHAMBIGUOUS' }, + 'a range matching two installed versions errors' + ) +}) + +t.test('add: explicit exact version is honored without install', async t => { + const { npm, joinedOutput, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + // no install; explicit exact version path returns { name, version } directly + await npm.exec('patch', ['add', `${DEP_NAME}@${DEP_VERSION}`]) + t.match(joinedOutput(), /You can now edit the following directory: /, 'extracts the exact version') +}) + +t.test('commit: no edit dir arg rejects with EUSAGE', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: basePrefix(), + }) + await t.rejects(npm.exec('patch', ['commit']), { code: 'EUSAGE' }) +}) + +t.test('commit: missing package.json in edit dir rejects with EPATCHNOEDITDIR', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { 'package.json': JSON.stringify(rootPackageJson), 'empty-dir': {} }, + }) + await t.rejects( + npm.exec('patch', ['commit', path.join(npm.prefix, 'empty-dir')]), + { code: 'EPATCHNOEDITDIR' } + ) +}) + +t.test('commit: no changes logs a warning and does not write a patch', async t => { + const { npm, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + await npm.exec('install', []) + + // add then commit without editing anything + await npm.exec('patch', ['add', DEP_NAME]) + // the edit dir is a tmp path; re-extract a fresh clean copy to a known dir + const editDir = path.join(npm.prefix, 'clean-edit') + await pacote.extract(`${DEP_NAME}@${DEP_VERSION}`, editDir, npm.flatOptions) + + await npm.exec('patch', ['commit', editDir]) + t.notOk( + fs.existsSync(path.join(npm.prefix, 'patches', `${DEP_NAME}@${DEP_VERSION}.patch`)), + 'no patch file written when there are no changes' + ) + const pkg = readJson(path.join(npm.prefix, 'package.json')) + t.notOk(pkg.patchedDependencies, 'no patchedDependencies added when nothing changed') +}) + +t.test('commit: only package.json changed warns and writes no patch', async t => { + const { npm, logs, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + await npm.exec('install', []) + + await npm.exec('patch', ['add', DEP_NAME]) + const editDir = path.join(npm.prefix, 'clean-edit') + await pacote.extract(`${DEP_NAME}@${DEP_VERSION}`, editDir, npm.flatOptions) + + // edit only package.json, which is excluded from patches + const pkgPath = path.join(editDir, 'package.json') + const edited = readJson(pkgPath) + edited.description = 'edited' + fs.writeFileSync(pkgPath, JSON.stringify(edited)) + + await npm.exec('patch', ['commit', editDir]) + t.notOk( + fs.existsSync(path.join(npm.prefix, 'patches', `${DEP_NAME}@${DEP_VERSION}.patch`)), + 'no patch file written when only package.json changed' + ) + t.match(logs.warn.join('\n'), /only package.json changed/, 'warns package.json is not patchable') +}) + +t.test('commit: package.json change alongside code is dropped with a warning', async t => { + const { npm, logs, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + await npm.exec('install', []) + + await npm.exec('patch', ['add', DEP_NAME]) + const editDir = path.join(npm.prefix, 'clean-edit') + await pacote.extract(`${DEP_NAME}@${DEP_VERSION}`, editDir, npm.flatOptions) + + // edit both package.json and a real file + const pkgPath = path.join(editDir, 'package.json') + const edited = readJson(pkgPath) + edited.description = 'edited' + fs.writeFileSync(pkgPath, JSON.stringify(edited)) + fs.writeFileSync(path.join(editDir, 'index.js'), 'module.exports = () => "patched"\n') + + await npm.exec('patch', ['commit', editDir]) + const patchPath = path.join(npm.prefix, 'patches', `${DEP_NAME}@${DEP_VERSION}.patch`) + t.ok(fs.existsSync(patchPath), 'patch written for the code change') + t.notMatch(fs.readFileSync(patchPath, 'utf8'), 'package.json', 'patch excludes package.json') + t.match( + logs.warn.join('\n'), + /changes to package.json are not included/, + 'warns the package.json edit was ignored' + ) +}) + +// Serve several versions of a package, each with its own index.js source. +const setupVersions = async (npm, registry, name, sources) => { + const versions = Object.keys(sources) + const manifest = registry.manifest({ name, versions }) + for (const version of versions) { + const dir = path.join(npm.prefix, `pkg-${name}-${version}`) + fs.mkdirSync(dir, { recursive: true }) + fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name, version })) + fs.writeFileSync(path.join(dir, 'index.js'), sources[version]) + const tar = await pacote.tarball(dir, { Arborist }) + const { pathname } = new URL(manifest.versions[version].dist.tarball) + registry.nock.get(pathname).reply(200, tar).persist() + } + registry.nock.get(`/${name}`).reply(200, manifest).persist() + return manifest +} + +const rootWith = dep => ({ + 'package.json': JSON.stringify({ + name: 'root-project', version: '1.0.0', dependencies: dep, + }), +}) + +const updatePrefix = patchedDependencies => ({ + 'package.json': JSON.stringify({ + name: 'root-project', version: '1.0.0', patchedDependencies, + }), +}) + +t.test('update --to rebases an exact patch onto a new version', async t => { + const name = 'upd-exact' + const { npm, joinedOutput, outputs, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: rootWith({ [name]: '^1.0.0' }), + }) + // v2 differs from v1 only on the last line; the patch edits the first line -> clean 3-way merge + await setupVersions(npm, registry, name, { '1.0.0': 'a\nb\nc\n', '2.0.0': 'a\nb\nCC\n' }) + await npm.exec('install', []) + + outputs.length = 0 + await npm.exec('patch', ['add', name]) + const editDir = joinedOutput().match(/directory: (.+)/)[1].trim() + fs.writeFileSync(path.join(editDir, 'index.js'), 'AA\nb\nc\n') + await npm.exec('patch', ['commit', editDir]) + + npm.config.set('to', '2.0.0') + await npm.exec('patch', ['update', name]) + + const pkg = readJson(path.join(npm.prefix, 'package.json')) + t.same(pkg.patchedDependencies, { [`${name}@2.0.0`]: `patches/${name}@2.0.0.patch` }, + 'selector renamed to the new version') + t.notOk(fs.existsSync(path.join(npm.prefix, 'patches', `${name}@1.0.0.patch`)), 'old patch file removed') + t.match(fs.readFileSync(path.join(npm.prefix, 'patches', `${name}@2.0.0.patch`), 'utf8'), /\+AA/, + 'rebased patch keeps the edit') +}) + +t.test('update --to warns when the target version is not installed', async t => { + const name = 'upd-uninstalled' + const { npm, joinedOutput, outputs, registry, logs } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: rootWith({ [name]: '1.0.0' }), + }) + await setupVersions(npm, registry, name, { '1.0.0': 'a\nb\nc\n', '2.0.0': 'a\nb\nCC\n' }) + await npm.exec('install', []) + + outputs.length = 0 + await npm.exec('patch', ['add', name]) + const editDir = joinedOutput().match(/directory: (.+)/)[1].trim() + fs.writeFileSync(path.join(editDir, 'index.js'), 'AA\nb\nc\n') + await npm.exec('patch', ['commit', editDir]) + + // dependency is pinned to 1.0.0, so rebasing onto 2.0.0 targets an uninstalled version + npm.config.set('to', '2.0.0') + await npm.exec('patch', ['update', name]) + + t.match(logs.warn.byTitle('patch'), + [new RegExp(`${name}@2\\.0\\.0 is not installed.*EPATCHUNUSED`)], + 'warns that the target version is not installed') +}) + +t.test('update --to is silent when the target version is installed', async t => { + const name = 'upd-installed' + const { npm, registry, logs } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: rootWith({ [name]: '^2.0.0' }), + }) + await setupVersions(npm, registry, name, { '1.0.0': 'x\n', '2.0.0': 'x\n' }) + // 2.0.0 is the installed version; hand-author a patch against 1.0.0 that adds a file (applies to any version) + await npm.exec('install', []) + fs.mkdirSync(path.join(npm.prefix, 'patches'), { recursive: true }) + fs.writeFileSync(path.join(npm.prefix, 'patches', `${name}@1.0.0.patch`), + '--- /dev/null\t\n+++ b/EXTRA.txt\t\n@@ -0,0 +1 @@\n+extra\n') + const pkg = readJson(path.join(npm.prefix, 'package.json')) + pkg.patchedDependencies = { [`${name}@1.0.0`]: `patches/${name}@1.0.0.patch` } + fs.writeFileSync(path.join(npm.prefix, 'package.json'), JSON.stringify(pkg)) + + // rebasing onto 2.0.0, which is installed, must not warn + npm.config.set('to', '2.0.0') + await npm.exec('patch', ['update', name]) + t.strictSame(logs.warn.byTitle('patch'), [], 'no warning when --to matches the installed version') +}) + +t.test('update auto-detects the new version and drops a fully-shadowed range', async t => { + const name = 'upd-range' + const { npm, joinedOutput, outputs, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: rootWith({ [name]: '1.0.0' }), + }) + await setupVersions(npm, registry, name, { '1.0.0': 'x\n', '1.1.0': 'x\n' }) + await npm.exec('install', []) + // a patch that adds a file applies to any version, so the dep can float + outputs.length = 0 + await npm.exec('patch', ['add', name]) + const editDir = joinedOutput().match(/directory: (.+)/)[1].trim() + fs.writeFileSync(path.join(editDir, 'EXTRA.txt'), 'extra\n') + await npm.exec('patch', ['commit', editDir]) + + // turn the exact selector into a range and float the lockfile to 1.1.0 + const pkg = readJson(path.join(npm.prefix, 'package.json')) + pkg.dependencies[name] = '^1.0.0' + pkg.patchedDependencies = { [`${name}@^1.0.0`]: pkg.patchedDependencies[`${name}@1.0.0`] } + fs.writeFileSync(path.join(npm.prefix, 'package.json'), JSON.stringify(pkg)) + // clear the resolved tree so a fresh install floats the range up to 1.1.0 + fs.rmSync(path.join(npm.prefix, 'package-lock.json')) + fs.rmSync(path.join(npm.prefix, 'node_modules'), { recursive: true, force: true }) + await npm.exec('install', []) + + await npm.exec('patch', ['update', name]) + t.same(readJson(path.join(npm.prefix, 'package.json')).patchedDependencies, + { [`${name}@1.1.0`]: `patches/${name}@1.1.0.patch` }, 'shadowed range dropped, new exact entry added') +}) + +t.test('update conflict leaves an edit dir; commit finalizes the rename', async t => { + const name = 'upd-conflict' + const { npm, joinedOutput, outputs, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: rootWith({ [name]: '^1.0.0' }), + }) + // v2 changes the same line the patch edits -> conflict + await setupVersions(npm, registry, name, { '1.0.0': 'a\nb\nc\n', '2.0.0': 'a\nBB\nc\n' }) + await npm.exec('install', []) + outputs.length = 0 + await npm.exec('patch', ['add', name]) + const addDir = joinedOutput().match(/directory: (.+)/)[1].trim() + fs.writeFileSync(path.join(addDir, 'index.js'), 'a\nMINE\nc\n') + await npm.exec('patch', ['commit', addDir]) + + npm.config.set('to', '2.0.0') + outputs.length = 0 + await npm.exec('patch', ['update', name]) + const editDir = joinedOutput().match(/Resolve the conflicts in: (.+)/)[1].trim() + t.ok(fs.existsSync(path.join(editDir, '.npm-patch-update.json')), 'cleanup marker written') + t.match(fs.readFileSync(path.join(editDir, 'index.js'), 'utf8'), /<<<<<<>>>>>>[^\n]*\n/, '$1') + fs.writeFileSync(path.join(editDir, 'index.js'), src) + await npm.exec('patch', ['commit', editDir]) + t.same(readJson(path.join(npm.prefix, 'package.json')).patchedDependencies, + { [`${name}@2.0.0`]: `patches/${name}@2.0.0.patch` }, 'renamed after the resolving commit') + t.notOk(fs.existsSync(path.join(npm.prefix, 'patches', `${name}@1.0.0.patch`)), 'old patch file removed') +}) + +t.test('a no-op resolving commit keeps the marker so a corrected retry still finalizes', async t => { + const name = 'upd-noop-retry' + const { npm, joinedOutput, outputs, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: rootWith({ [name]: '^1.0.0' }), + }) + await setupVersions(npm, registry, name, { '1.0.0': 'a\nb\nc\n', '2.0.0': 'a\nBB\nc\n' }) + await npm.exec('install', []) + outputs.length = 0 + await npm.exec('patch', ['add', name]) + const addDir = joinedOutput().match(/directory: (.+)/)[1].trim() + fs.writeFileSync(path.join(addDir, 'index.js'), 'a\nMINE\nc\n') + await npm.exec('patch', ['commit', addDir]) + + npm.config.set('to', '2.0.0') + outputs.length = 0 + await npm.exec('patch', ['update', name]) + const editDir = joinedOutput().match(/Resolve the conflicts in: (.+)/)[1].trim() + const markerPath = path.join(editDir, '.npm-patch-update.json') + t.ok(fs.existsSync(markerPath), 'marker written on conflict') + + // resolve to the new version verbatim (no net change) and commit: a no-op + let src = fs.readFileSync(path.join(editDir, 'index.js'), 'utf8') + src = src.replace(/<<<<<<<[^\n]*\n([\s\S]*?)=======\n[\s\S]*?>>>>>>>[^\n]*\n/, '$1') + fs.writeFileSync(path.join(editDir, 'index.js'), src) + await npm.exec('patch', ['commit', editDir]) + t.ok(fs.existsSync(markerPath), 'marker survives a no-op commit so the update context is not lost') + + // now resolve properly and commit again: must finalize the rename, not throw EPATCHUNUSED on the uninstalled 2.0.0 + fs.writeFileSync(path.join(editDir, 'index.js'), src.replace('BB', 'MINE')) + await npm.exec('patch', ['commit', editDir]) + t.same(readJson(path.join(npm.prefix, 'package.json')).patchedDependencies, + { [`${name}@2.0.0`]: `patches/${name}@2.0.0.patch` }, 'finalized: old selector dropped, new one added') +}) + +t.test('update conflict on a name-only selector forks and commits without EPATCHUNUSED', async t => { + const name = 'upd-rconflict' + const { npm, joinedOutput, outputs, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: rootWith({ [name]: '^1.0.0' }), + }) + await setupVersions(npm, registry, name, { '1.0.0': 'a\nb\nc\n', '2.0.0': 'a\nBB\nc\n' }) + await npm.exec('install', []) + outputs.length = 0 + await npm.exec('patch', ['add', name]) + const addDir = joinedOutput().match(/directory: (.+)/)[1].trim() + fs.writeFileSync(path.join(addDir, 'index.js'), 'a\nMINE\nc\n') + await npm.exec('patch', ['commit', addDir]) + // turn it into a name-only selector so the conflict path takes the fork (non-exact) branch + const pkg = readJson(path.join(npm.prefix, 'package.json')) + pkg.patchedDependencies = { [name]: pkg.patchedDependencies[`${name}@1.0.0`] } + fs.writeFileSync(path.join(npm.prefix, 'package.json'), JSON.stringify(pkg)) + + // --to 2.0.0 is not installed and conflicts; the fork must still leave a marker + npm.config.set('to', '2.0.0') + outputs.length = 0 + await npm.exec('patch', ['update', name]) + const editDir = joinedOutput().match(/Resolve the conflicts in: (.+)/)[1].trim() + t.same(readJson(path.join(editDir, '.npm-patch-update.json')), { name, removeKey: null }, + 'a fork still writes a marker, with removeKey null') + + // resolve and commit: must finalize metadata-only, not fail with EPATCHUNUSED on the uninstalled 2.0.0 + let src = fs.readFileSync(path.join(editDir, 'index.js'), 'utf8') + src = src.replace(/<<<<<<<[^\n]*\n[\s\S]*?=======\n([\s\S]*?)>>>>>>>[^\n]*\n/, '$1') + fs.writeFileSync(path.join(editDir, 'index.js'), src) + await npm.exec('patch', ['commit', editDir]) + + const after = readJson(path.join(npm.prefix, 'package.json')).patchedDependencies + t.ok(after[name], 'the name-only selector is kept') + t.ok(after[`${name}@2.0.0`], 'the new exact selector is added') +}) + +t.test('update: no registered patch rejects with EPATCHNOTFOUND', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { 'package.json': JSON.stringify({ name: 'r', version: '1.0.0' }) }, + }) + await t.rejects(npm.exec('patch', ['update', 'nope']), { code: 'EPATCHNOTFOUND' }) +}) + +t.test('update: an unknown explicit selector rejects with EPATCHNOTFOUND', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: updatePrefix({ 'foo@1.0.0': 'patches/foo@1.0.0.patch' }), + }) + await t.rejects(npm.exec('patch', ['update', 'foo@9.9.9']), { code: 'EPATCHNOTFOUND' }) +}) + +t.test('update: multiple entries for a bare name reject with EPATCHAMBIGUOUS', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: updatePrefix({ 'foo@1.0.0': 'patches/foo@1.0.0.patch', 'foo@2.0.0': 'patches/foo@2.0.0.patch' }), + }) + await t.rejects(npm.exec('patch', ['update', 'foo']), { code: 'EPATCHAMBIGUOUS' }) +}) + +t.test('update: an unparseable patch filename rejects with EPATCHBASE', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: updatePrefix({ 'foo@1.0.0': 'patches/custom.patch' }), + }) + await t.rejects(npm.exec('patch', ['update', 'foo@1.0.0']), { code: 'EPATCHBASE' }) +}) + +t.test('update: --to equal to the baseline rejects with EPATCHNOOP', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: updatePrefix({ 'foo@1.0.0': 'patches/foo@1.0.0.patch' }), + }) + npm.config.set('to', '1.0.0') + await t.rejects(npm.exec('patch', ['update', 'foo@1.0.0']), { code: 'EPATCHNOOP' }) +}) + +t.test('update: an invalid --to rejects with EPATCHBADTO', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: updatePrefix({ 'foo@1.0.0': 'patches/foo@1.0.0.patch' }), + }) + npm.config.set('to', 'not-a-version') + await t.rejects(npm.exec('patch', ['update', 'foo@1.0.0']), { code: 'EPATCHBADTO' }) +}) + +t.test('update: an existing target entry rejects with EPATCHEXISTS', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: updatePrefix({ 'foo@1.0.0': 'patches/foo@1.0.0.patch', 'foo@2.0.0': 'patches/foo@2.0.0.patch' }), + }) + npm.config.set('to', '2.0.0') + await t.rejects(npm.exec('patch', ['update', 'foo@1.0.0']), { code: 'EPATCHEXISTS' }) +}) + +t.test('update: a missing lockfile with no --to rejects with EPATCHSTALE', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: updatePrefix({ 'foo@^1.0.0': 'patches/foo@1.0.0.patch' }), + }) + await t.rejects(npm.exec('patch', ['update', 'foo']), + { code: 'EPATCHSTALE', message: /could not read the lockfile/ }) +}) + +t.test('update: wrong arg count rejects with EUSAGE', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { 'package.json': JSON.stringify({ name: 'r', version: '1.0.0' }) }, + }) + await t.rejects(npm.exec('patch', ['update']), { code: 'EUSAGE' }) +}) + +// install a single version of `name` and commit a patch, then hand-edit the selector to `selectorKey`. +const installAndPatch = async (t, name, { src = 'x\n', addFile, selectorKey } = {}) => { + const { npm, joinedOutput, outputs, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: rootWith({ [name]: '^1.0.0' }), + }) + await setupVersions(npm, registry, name, { '1.0.0': src }) + await npm.exec('install', []) + outputs.length = 0 + await npm.exec('patch', ['add', name]) + const editDir = joinedOutput().match(/directory: (.+)/)[1].trim() + if (addFile) { + fs.writeFileSync(path.join(editDir, addFile), 'extra\n') + } else { + fs.writeFileSync(path.join(editDir, 'index.js'), 'A\n') + } + await npm.exec('patch', ['commit', editDir]) + if (selectorKey) { + const pkg = readJson(path.join(npm.prefix, 'package.json')) + pkg.patchedDependencies = { [selectorKey]: pkg.patchedDependencies[`${name}@1.0.0`] } + fs.writeFileSync(path.join(npm.prefix, 'package.json'), JSON.stringify(pkg)) + } + return { npm, joinedOutput, outputs } +} + +t.test('update: exact selector with no --to is a no-op', async t => { + const { npm } = await installAndPatch(t, 'upd-noop') + await t.rejects(npm.exec('patch', ['update', 'upd-noop']), { code: 'EPATCHNOOP' }) +}) + +t.test('update: a name-only selector resolves the installed version', async t => { + const { npm } = await installAndPatch(t, 'upd-nameonly', { selectorKey: 'upd-nameonly' }) + // only 1.0.0 installed, so the name-only selector resolves to it -> no-op + await t.rejects(npm.exec('patch', ['update', 'upd-nameonly']), { code: 'EPATCHNOOP' }) +}) + +t.test('update: a range matching no installed version rejects with EPATCHSTALE', async t => { + const { npm } = await installAndPatch(t, 'upd-norange', { selectorKey: 'upd-norange@^5.0.0' }) + await t.rejects(npm.exec('patch', ['update', 'upd-norange']), + { code: 'EPATCHSTALE', message: /no installed version matches the patch selector "upd-norange@\^5.0.0"/ }) +}) + +t.test('update: a patch that no longer applies to its baseline rejects with EPATCHBASE', async t => { + const name = 'upd-drift' + const { npm, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: rootWith({ [name]: '^1.0.0' }), + }) + await setupVersions(npm, registry, name, { '1.0.0': 'real\n', '2.0.0': 'real2\n' }) + await npm.exec('install', []) + // a patch whose context does not exist in the baseline tarball cannot be re-applied during rebase + fs.mkdirSync(path.join(npm.prefix, 'patches'), { recursive: true }) + fs.writeFileSync(path.join(npm.prefix, 'patches', `${name}@1.0.0.patch`), + '--- a/index.js\t\n+++ b/index.js\t\n@@ -1,1 +1,1 @@\n-NOT-THE-REAL-LINE\n+changed\n') + const pkg = readJson(path.join(npm.prefix, 'package.json')) + pkg.patchedDependencies = { [`${name}@1.0.0`]: `patches/${name}@1.0.0.patch` } + fs.writeFileSync(path.join(npm.prefix, 'package.json'), JSON.stringify(pkg)) + npm.config.set('to', '2.0.0') + await t.rejects(npm.exec('patch', ['update', name]), { code: 'EPATCHBASE' }) +}) + +t.test('update: when the new version already contains the patch, reports EPATCHEMPTY', async t => { + const name = 'upd-empty' + const { npm, joinedOutput, outputs, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: rootWith({ [name]: '^1.0.0' }), + }) + // v2 already has the value the patch sets, so the rebase yields nothing + await setupVersions(npm, registry, name, { '1.0.0': 'old\n', '2.0.0': 'new\n' }) + await npm.exec('install', []) + outputs.length = 0 + await npm.exec('patch', ['add', name]) + const editDir = joinedOutput().match(/directory: (.+)/)[1].trim() + fs.writeFileSync(path.join(editDir, 'index.js'), 'new\n') + await npm.exec('patch', ['commit', editDir]) + npm.config.set('to', '2.0.0') + await t.rejects(npm.exec('patch', ['update', name]), { code: 'EPATCHEMPTY' }) +}) + +t.test('update: a patches-dir outside the project is rejected', async t => { + const name = 'upd-unsafe' + const { npm, joinedOutput, outputs, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: rootWith({ [name]: '^1.0.0' }), + }) + await setupVersions(npm, registry, name, { '1.0.0': 'a\nb\nc\n', '2.0.0': 'a\nb\nCC\n' }) + await npm.exec('install', []) + outputs.length = 0 + await npm.exec('patch', ['add', name]) + const editDir = joinedOutput().match(/directory: (.+)/)[1].trim() + fs.writeFileSync(path.join(editDir, 'index.js'), 'AA\nb\nc\n') + await npm.exec('patch', ['commit', editDir]) + npm.config.set('to', '2.0.0') + npm.config.set('patches-dir', '../outside') + await t.rejects(npm.exec('patch', ['update', name]), { code: 'EPATCHUNSAFE' }) +}) + +t.test('update --to keeps a range selector when the lockfile is unknown', async t => { + const name = 'upd-keep' + const { npm, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root-project', + version: '1.0.0', + dependencies: { [name]: '*' }, + patchedDependencies: { [`${name}@^1.0.0`]: `patches/${name}@1.0.0.patch` }, + }), + patches: { [`${name}@1.0.0.patch`]: '--- /dev/null\t\n+++ b/EXTRA.txt\t\n@@ -0,0 +1 @@\n+extra\n' }, + }, + }) + await setupVersions(npm, registry, name, { '1.0.0': 'x\n', '2.0.0': 'x\n' }) + // no install -> no lockfile -> installed versions unknown; --to drives the target + npm.config.set('to', '2.0.0') + await npm.exec('patch', ['update', name]) + t.same(readJson(path.join(npm.prefix, 'package.json')).patchedDependencies, { + [`${name}@^1.0.0`]: `patches/${name}@1.0.0.patch`, + [`${name}@2.0.0`]: `patches/${name}@2.0.0.patch`, + }, 'range kept, new exact entry added') +}) + +t.test('commit: a foreign update marker does not hijack a normal commit', async t => { + const name = 'upd-foreign' + const { npm, joinedOutput, outputs, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: rootWith({ [name]: '^1.0.0' }), + }) + await setupVersions(npm, registry, name, { '1.0.0': 'a\n' }) + await npm.exec('install', []) + outputs.length = 0 + await npm.exec('patch', ['add', name]) + const editDir = joinedOutput().match(/directory: (.+)/)[1].trim() + fs.writeFileSync(path.join(editDir, 'index.js'), 'patched\n') + // a valid marker naming a different package must be ignored, not acted on + fs.writeFileSync(path.join(editDir, '.npm-patch-update.json'), + JSON.stringify({ name: 'other-pkg', removeKey: 'other-pkg@9.9.9' })) + await npm.exec('patch', ['commit', editDir]) + + const pkg = readJson(path.join(npm.prefix, 'package.json')) + t.ok(pkg.patchedDependencies[`${name}@1.0.0`], 'normal commit recorded its own selector') + // a normal commit does a full reify, so node_modules is patched (not the metadata-only update path) + t.equal(fs.readFileSync(path.join(npm.prefix, 'node_modules', name, 'index.js'), 'utf8'), 'patched\n', + 'node_modules is patched despite the foreign marker') +}) + +t.test('commit: an invalid update marker rejects with EPATCHBADMARKER', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { 'package.json': JSON.stringify({ name: 'r', version: '1.0.0' }) }, + }) + const editDir = path.join(npm.prefix, 'ed') + fs.mkdirSync(editDir, { recursive: true }) + fs.writeFileSync(path.join(editDir, 'package.json'), JSON.stringify({ name: 'foo', version: '1.0.0' })) + fs.writeFileSync(path.join(editDir, '.npm-patch-update.json'), 'not json') + await t.rejects(npm.exec('patch', ['commit', editDir]), { code: 'EPATCHBADMARKER' }) +}) + +t.test('rm: no pkg arg rejects with EUSAGE', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: basePrefix(), + }) + await t.rejects(npm.exec('patch', ['rm']), { code: 'EUSAGE' }) +}) + +t.test('completion lists subcommands at the right depth', async t => { + t.same( + await Patch.completion({ conf: { argv: { remain: ['npm', 'patch'] } } }), + ['add', 'commit', 'update', 'ls', 'rm'] + ) + t.same(await Patch.completion({ conf: { argv: { remain: ['npm', 'patch', 'add', 'x'] } } }), []) +}) + +t.test('add: ignore-existing wipes a pre-existing edit dir', async t => { + const { npm, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + await npm.exec('install', []) + + const customDir = path.join(npm.prefix, 'reuse-edit') + fs.mkdirSync(customDir, { recursive: true }) + fs.writeFileSync(path.join(customDir, 'stale.txt'), 'old') + npm.config.set('edit-dir', customDir) + npm.config.set('ignore-existing', true) + await npm.exec('patch', ['add', DEP_NAME]) + t.notOk(fs.existsSync(path.join(customDir, 'stale.txt')), 'stale file removed') + t.ok(fs.existsSync(path.join(customDir, 'package.json')), 'fresh extract present') +}) + +t.test('add: range matching an installed version resolves to it', async t => { + const { npm, joinedOutput, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + await npm.exec('install', []) + await npm.exec('patch', ['add', `${DEP_NAME}@^${DEP_VERSION}`]) + t.match(joinedOutput(), /You can now edit the following directory: /, 'range matched the installed version') +}) + +t.test('add: range not installed resolves against the registry', async t => { + const { npm, joinedOutput, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: { + 'dep-tarball': { 'package.json': JSON.stringify({ name: DEP_NAME, version: '2.0.0' }), 'index.js': DEP_SRC }, + 'package.json': JSON.stringify({ name: 'root-project', version: '1.0.0' }), + }, + }) + const manifest = registry.manifest({ name: DEP_NAME, versions: ['2.0.0'] }) + const dist = new URL(manifest.versions['2.0.0'].dist.tarball) + const tar = await pacote.tarball(path.join(npm.prefix, 'dep-tarball'), { Arborist }) + registry.nock.get(`/${DEP_NAME}`).reply(200, manifest).persist() + registry.nock.get(dist.pathname).reply(200, tar).persist() + + await npm.exec('patch', ['add', `${DEP_NAME}@^2.0.0`]) + t.match(joinedOutput(), /You can now edit the following directory: /, 'resolved the range via the registry') +}) + +t.test('commit: a patches-dir outside the project is rejected', async t => { + const { npm, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false, 'patches-dir': '../outside' }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + await npm.exec('install', []) + + const editDir = path.join(npm.prefix, 'edit') + await pacote.extract(`${DEP_NAME}@${DEP_VERSION}`, editDir, npm.flatOptions) + fs.writeFileSync(path.join(editDir, 'index.js'), 'module.exports = () => "patched"\n') + await t.rejects( + npm.exec('patch', ['commit', editDir]), + { code: 'EPATCHUNSAFE' }, + 'commit refuses to write the patch outside the project root' + ) +}) + +t.test('commit: edit dir package.json missing version rejects', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + 'package.json': JSON.stringify(rootPackageJson), + 'bad-edit': { 'package.json': JSON.stringify({ name: 'no-version' }) }, + }, + }) + await t.rejects( + npm.exec('patch', ['commit', path.join(npm.prefix, 'bad-edit')]), + /missing name or version/ + ) +}) + +t.test('commit: keep-edit-dir leaves the edit directory in place', async t => { + const { npm, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false, 'keep-edit-dir': true }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + await npm.exec('install', []) + + const editDir = path.join(npm.prefix, 'kept-edit') + await pacote.extract(`${DEP_NAME}@${DEP_VERSION}`, editDir, npm.flatOptions) + fs.writeFileSync(path.join(editDir, 'index.js'), 'module.exports = () => "patched"\n') + await npm.exec('patch', ['commit', editDir]) + t.ok(fs.existsSync(editDir), 'edit dir kept when keep-edit-dir is set') +}) + +t.test('ls counts nodes for a range selector', async t => { + // offline fixture: ls reads the installed tree from disk, no registry needed + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + ...rootPackageJson, + patchedDependencies: { [`${DEP_NAME}@^1.0.0`]: `patches/${DEP_NAME}.patch` }, + }), + 'package-lock.json': JSON.stringify(rootPackageLock), + node_modules: { + [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: DEP_VERSION }) }, + }, + }, + }) + await npm.exec('patch', ['ls']) + t.match(joinedOutput(), /\(1 node\)/, 'range selector matches the installed version') +}) + +t.test('ls tolerates ambiguous overlapping range selectors', async t => { + // two overlapping non-subset ranges make matchSelector throw; ls must not crash + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root-project', + version: '1.0.0', + dependencies: { [DEP_NAME]: '1.5.0' }, + patchedDependencies: { + [`${DEP_NAME}@>=1.0.0 <2.0.0`]: 'patches/a.patch', + [`${DEP_NAME}@>=1.4.0 <3.0.0`]: 'patches/b.patch', + }, + }), + node_modules: { + [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: '1.5.0' }) }, + }, + }, + }) + await npm.exec('patch', ['ls']) + t.match(joinedOutput(), /\(error: ambiguous selectors\)/, 'ls surfaces the ambiguity') +}) + +t.test('ls flags only the conflicting range selectors, not an exact one', async t => { + // an exact selector for the same name must not be reported as ambiguous + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root-project', + version: '1.0.0', + dependencies: { [DEP_NAME]: '1.0.0', b: '1.0.0' }, + patchedDependencies: { + [`${DEP_NAME}@1.0.0`]: 'patches/exact.patch', + [`${DEP_NAME}@>=2.0.0 <4.0.0`]: 'patches/a.patch', + [`${DEP_NAME}@>=3.0.0 <5.0.0`]: 'patches/b.patch', + }, + }), + node_modules: { + [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: '1.0.0' }) }, + b: { + 'package.json': JSON.stringify({ name: 'b', version: '1.0.0', dependencies: { [DEP_NAME]: '3.5.0' } }), + node_modules: { [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: '3.5.0' }) } }, + }, + }, + }, + }) + await npm.exec('patch', ['ls']) + const out = joinedOutput() + t.match(out, new RegExp(`patches/exact\\.patch\\t${DEP_NAME}@1\\.0\\.0\\t\\(1 node\\)`), 'exact selector counts its node') + t.match(out, /patches\/a\.patch\t.*\(error: ambiguous selectors\)/, 'first overlapping range flagged') + t.match(out, /patches\/b\.patch\t.*\(error: ambiguous selectors\)/, 'second overlapping range flagged') +}) + +t.test('ls reports plural node counts for a name-only selector', async t => { + // offline fixture with two installed copies so the match count is plural + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root-project', + version: '1.0.0', + dependencies: { [DEP_NAME]: '1.0.0', b: '1.0.0' }, + patchedDependencies: { [DEP_NAME]: `patches/${DEP_NAME}.patch` }, + }), + node_modules: { + [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: '1.0.0' }) }, + b: { + 'package.json': JSON.stringify({ name: 'b', version: '1.0.0', dependencies: { [DEP_NAME]: '2.0.0' } }), + node_modules: { [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: '2.0.0' }) } }, + }, + }, + }, + }) + await npm.exec('patch', ['ls']) + t.match(joinedOutput(), /\(2 nodes\)/, 'name-only selector matches both installed copies') +}) + +t.test('rm refuses to delete a patch file outside the project root', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root-project', + version: '1.0.0', + patchedDependencies: { [`${DEP_NAME}@1.0.0`]: '../escape.patch' }, + }), + }, + }) + await t.rejects( + npm.exec('patch', ['rm', DEP_NAME]), + { code: 'EPATCHUNSAFE' }, + 'a crafted escaping patch path is not deleted' + ) +}) + +t.test('rm removes every selector for a bare name', async t => { + // offline: the dep is already installed and unpatched, so rm reifies without the registry + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { + 'package.json': JSON.stringify({ + ...rootPackageJson, + patchedDependencies: { + [`${DEP_NAME}@1.0.0`]: 'patches/one.patch', + [`${DEP_NAME}@2.0.0`]: 'patches/two.patch', + }, + }), + 'package-lock.json': JSON.stringify(rootPackageLock), + patches: { 'one.patch': '', 'two.patch': '' }, + node_modules: { + [DEP_NAME]: { 'package.json': JSON.stringify({ name: DEP_NAME, version: DEP_VERSION }) }, + }, + }, + }) + await npm.exec('patch', ['rm', DEP_NAME]) + t.match(joinedOutput(), /Removed patches:/, 'reports plural removal') + t.notOk(readJson(path.join(npm.prefix, 'package.json')).patchedDependencies, 'all selectors removed') +}) + +t.test('rm keeps a patch file still referenced by another selector', async t => { + const { npm, registry } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + strictRegistryNock: false, + prefixDir: basePrefix(), + }) + await setupDep(npm, registry) + await npm.exec('install', []) + + // create a real patch via the normal flow + await npm.exec('patch', ['add', DEP_NAME]) + const editDir = path.join(npm.prefix, 'edit') + await pacote.extract(`${DEP_NAME}@${DEP_VERSION}`, editDir, npm.flatOptions) + fs.writeFileSync(path.join(editDir, 'index.js'), 'module.exports = () => "patched"\n') + await npm.exec('patch', ['commit', editDir]) + + // add a second name-only selector pointing at the same patch file + const pkgPath = path.join(npm.prefix, 'package.json') + const pkg = readJson(pkgPath) + const patchPath = pkg.patchedDependencies[`${DEP_NAME}@${DEP_VERSION}`] + pkg.patchedDependencies[DEP_NAME] = patchPath + fs.writeFileSync(pkgPath, JSON.stringify(pkg)) + + // removing the exact selector leaves the name-only one, so the file stays + await npm.exec('patch', ['rm', `${DEP_NAME}@${DEP_VERSION}`]) + t.ok(fs.existsSync(path.join(npm.prefix, patchPath)), 'shared patch file retained') + const after = readJson(pkgPath) + t.ok(after.patchedDependencies[DEP_NAME], 'name-only selector kept') + t.notOk(after.patchedDependencies[`${DEP_NAME}@${DEP_VERSION}`], 'exact selector removed') +}) + +t.test('install honors --allow-unused-patches only from the cli', async t => { + // an empty project with a ghost patch entry triggers EPATCHUNUSED entirely offline + const prefixDir = { + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + patchedDependencies: { 'ghost@1.0.0': 'patches/ghost.patch' }, + }), + patches: { 'ghost.patch': '--- a/x\n+++ b/x\n' }, + } + + t.test('unused patch is a hard error by default', async t => { + const { npm } = await loadMockNpm(t, { config: { 'ignore-scripts': true, audit: false }, prefixDir }) + await t.rejects(npm.exec('install', []), { code: 'EPATCHUNUSED' }) + }) + + t.test('the cli flag suppresses the error', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false, 'allow-unused-patches': true }, + prefixDir, + }) + await t.resolves(npm.exec('install', [])) + }) + + t.test('the same flag in .npmrc is ignored', async t => { + const { npm } = await loadMockNpm(t, { + config: { 'ignore-scripts': true, audit: false }, + prefixDir: { ...prefixDir, '.npmrc': 'allow-unused-patches=true' }, + }) + await t.rejects(npm.exec('install', []), { code: 'EPATCHUNUSED' }) + }) +}) diff --git a/test/lib/commands/ping.js b/test/lib/commands/ping.js index 7f90ea394f9ae..aca1e730131df 100644 --- a/test/lib/commands/ping.js +++ b/test/lib/commands/ping.js @@ -1,6 +1,8 @@ const t = require('tap') const { load: loadMockNpm } = require('../../fixtures/mock-npm.js') const MockRegistry = require('@npmcli/mock-registry') +const cacache = require('cacache') +const path = require('node:path') t.test('no details', async t => { const { npm, logs, joinedOutput } = await loadMockNpm(t) @@ -74,3 +76,19 @@ t.test('invalid json', async t => { details: {}, }) }) +t.test('fail when registry is unreachable even if request is cached', async t => { + const { npm } = await loadMockNpm(t, { + config: { registry: 'https://ur.npmlocal.npmtest/' }, + cacheDir: { _cacache: {} }, + }) + const url = `${npm.config.get('registry')}-/ping` + const cache = path.join(npm.cache, '_cacache') + await cacache.put(cache, + `make-fetch-happen:request-cache:${url}`, + '{}', { metadata: { url } } + ) + t.rejects(npm.exec('ping', []), { + code: 'ENOTFOUND', + }, + 'throws ENOTFOUND error') +}) diff --git a/test/lib/commands/pkg.js b/test/lib/commands/pkg.js index 2306fe10db025..50288cc42366b 100644 --- a/test/lib/commands/pkg.js +++ b/test/lib/commands/pkg.js @@ -1,584 +1,510 @@ const { resolve } = require('node:path') const { readFileSync } = require('node:fs') const t = require('tap') -const _mockNpm = require('../../fixtures/mock-npm') +const { load: loadMockNpm } = require('../../fixtures/mock-npm') const { cleanCwd } = require('../../fixtures/clean-snapshot') t.cleanSnapshot = (str) => cleanCwd(str) -const mockNpm = async (t, { ...opts } = {}) => { - const res = await _mockNpm(t, { - ...opts, - command: 'pkg', - }) - - const readPackageJson = (dir = '') => - JSON.parse(readFileSync(resolve(res.prefix, dir, 'package.json'), 'utf8')) - - return { - ...res, - pkg: (...args) => res.npm.exec('pkg', args), - readPackageJson, - OUTPUT: () => res.joinedOutput(), - } -} +const readPackageJson = (prefix, dir = '') => + JSON.parse(readFileSync(resolve(prefix, dir, 'package.json'), 'utf8')) t.test('no args', async t => { - const { pkg } = await mockNpm(t) + const { npm } = await loadMockNpm(t) await t.rejects( - pkg(), + npm.exec('pkg'), { code: 'EUSAGE' }, 'should throw usage error' ) }) t.test('no global mode', async t => { - const { pkg } = await mockNpm(t, { - config: { global: true }, + const { npm } = await loadMockNpm(t, { + config: { + global: true, + }, }) await t.rejects( - pkg('get', 'foo'), + npm.exec('pkg'), { code: 'EPKGGLOBAL' }, 'should throw no global mode error' ) }) -t.test('get no args', async t => { - const { pkg, OUTPUT } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - version: '1.1.1', - }), - }, +t.test('get', t => { + t.test('no args', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.1.1', + }), + }, + }) + await npm.exec('pkg', ['get']) + + t.matchSnapshot( + joinedOutput(), + 'should print package.json content' + ) }) - await pkg('get') + t.test('single arg', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.1.1', + }), + }, + }) - t.strictSame( - JSON.parse(OUTPUT()), - { - name: 'foo', - version: '1.1.1', - }, - 'should print package.json content' - ) -}) + await npm.exec('pkg', ['get', 'version']) -t.test('get single arg', async t => { - const { pkg, OUTPUT } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - version: '1.1.1', - }), - }, + t.matchSnapshot( + joinedOutput(), + 'should print retrieved package.json field' + ) }) - await pkg('get', 'version') + t.test('non string', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.1.1', + dependencies: { + '@npmcli/test': '*', + }, + }), + }, + }) - t.strictSame( - JSON.parse(OUTPUT()), - '1.1.1', - 'should print retrieved package.json field' - ) -}) + await npm.exec('pkg', ['get', 'dependencies']) -t.test('get multiple arg', async t => { - const { pkg, OUTPUT } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - version: '1.1.1', - }), - }, + t.matchSnapshot( + joinedOutput(), + 'should print retrieved package.json field' + ) }) + t.test('multiple arg', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.1.1', + }), + }, + }) - await pkg('get', 'name', 'version') - - t.strictSame( - JSON.parse(OUTPUT()), - { - name: 'foo', - version: '1.1.1', - }, - 'should print retrieved package.json field' - ) -}) + await npm.exec('pkg', ['get', 'name', 'version']) -t.test('get multiple arg with empty value', async t => { - const { pkg, OUTPUT } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - author: '', - }), - }, + t.matchSnapshot( + joinedOutput(), + 'should print retrieved package.json fields' + ) }) - await pkg('get', 'name', 'author') + t.test('multiple arg with only one arg existing', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + }), + }, + }) - t.strictSame( - JSON.parse(OUTPUT()), - { - name: 'foo', - author: '', - }, - 'should print retrieved package.json field regardless of empty value' - ) -}) + await npm.exec('pkg', ['get', 'name', 'version', 'dependencies']) -t.test('get nested arg', async t => { - const { pkg, OUTPUT } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - version: '1.1.1', - scripts: { - test: 'node test.js', - }, - }), - }, + t.matchSnapshot( + joinedOutput(), + 'should print retrieved package.json field' + ) }) - await pkg('get', 'scripts.test') + t.test('multiple arg with empty value', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + author: '', + }), + }, + }) - t.strictSame( - JSON.parse(OUTPUT()), - 'node test.js', - 'should print retrieved nested field' - ) -}) + await npm.exec('pkg', ['get', 'name', 'author']) -t.test('get array field', async t => { - const files = [ - 'index.js', - 'cli.js', - ] - const { pkg, OUTPUT } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - version: '1.1.1', - files, - }), - }, + t.matchSnapshot( + joinedOutput(), + 'should print retrieved package.json field regardless of empty value' + ) }) - await pkg('get', 'files') + t.test('nested arg', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.1.1', + scripts: { + test: 'node test.js', + }, + }), + }, + }) - t.strictSame( - JSON.parse(OUTPUT()), - files, - 'should print retrieved array field' - ) -}) + await npm.exec('pkg', ['get', 'scripts.test']) -t.test('get array item', async t => { - const files = [ - 'index.js', - 'cli.js', - ] - const { pkg, OUTPUT } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - version: '1.1.1', - files, - }), - }, + t.matchSnapshot( + joinedOutput(), + 'node test.js', + 'should print retrieved nested field' + ) }) - await pkg('get', 'files[0]') + t.test('array field', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.1.1', + files: [ + 'index.js', + 'cli.js', + ], + }), + }, + }) - t.strictSame( - JSON.parse(OUTPUT()), - 'index.js', - 'should print retrieved array field' - ) -}) + await npm.exec('pkg', ['get', 'files']) -t.test('get array nested items notation', async t => { - const contributors = [ - { - name: 'Ruy', - url: 'http://example.com/ruy', - }, - { - name: 'Gar', - url: 'http://example.com/gar', - }, - ] - const { pkg, OUTPUT } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - version: '1.1.1', - contributors, - }), - }, + t.matchSnapshot( + joinedOutput(), + 'should print retrieved array field' + ) }) - await pkg('get', 'contributors.name') - t.strictSame( - JSON.parse(OUTPUT()), - { - 'contributors[0].name': 'Ruy', - 'contributors[1].name': 'Gar', - }, - 'should print json result containing matching results' - ) -}) + t.test('array item', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.1.1', + files: [ + 'index.js', + 'cli.js', + ], + }), + }, + }) -t.test('set no args', async t => { - const { pkg } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ name: 'foo' }), - }, - }) - await t.rejects( - pkg('set'), - { code: 'EUSAGE' }, - 'should throw an error if no args' - ) -}) + await npm.exec('pkg', ['get', 'files[0]']) -t.test('set missing value', async t => { - const { pkg } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ name: 'foo' }), - }, + t.matchSnapshot( + joinedOutput(), + 'should print retrieved array field' + ) }) - await t.rejects( - pkg('set', 'key='), - { code: 'EUSAGE' }, - 'should throw an error if missing value' - ) -}) -t.test('set missing key', async t => { - const { pkg } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ name: 'foo' }), - }, - }) - await t.rejects( - pkg('set', '=value'), - { code: 'EUSAGE' }, - 'should throw an error if missing key' - ) -}) + t.test('json no args', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.1.1', + }), + }, + config: { + json: true, + }, + }) + await npm.exec('pkg', ['get']) -t.test('set single field', async t => { - const json = { - name: 'foo', - version: '1.1.1', - } - const { pkg, readPackageJson } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify(json), - }, + t.matchSnapshot( + joinedOutput(), + 'should print package.json content' + ) }) - await pkg('set', 'description=Awesome stuff') - t.strictSame( - readPackageJson(), - { - ...json, - description: 'Awesome stuff', - }, - 'should add single field to package.json' - ) -}) + t.test('json with args', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.1.1', + }), + }, + config: { + json: true, + }, + }) + await npm.exec('pkg', ['get', 'name']) -t.test('push to array syntax', async t => { - const json = { - name: 'foo', - version: '1.1.1', - keywords: [ - 'foo', - ], - } - const { pkg, readPackageJson } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify(json), - }, + t.matchSnapshot( + joinedOutput(), + 'should print package.json content' + ) }) - await pkg('set', 'keywords[]=bar', 'keywords[]=baz') - t.strictSame( - readPackageJson(), - { - ...json, - keywords: [ - 'foo', - 'bar', - 'baz', - ], - }, - 'should append to arrays using empty bracket syntax' - ) -}) + t.test('get array nested items notation', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.1.1', + contributors: [ + { + name: 'Ruy', + url: 'http://example.com/ruy', + }, + { + name: 'Gar', + url: 'http://example.com/gar', + }, + ], + }), + }, + }) -t.test('set multiple fields', async t => { - const json = { - name: 'foo', - version: '1.1.1', - } - const { pkg, readPackageJson } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify(json), - }, + await npm.exec('pkg', ['get', 'contributors.name']) + t.matchSnapshot( + joinedOutput(), + 'should print json result containing matching results' + ) }) - - await pkg('set', 'bin.foo=foo.js', 'scripts.test=node test.js') - t.strictSame( - readPackageJson(), - { - ...json, - bin: { - foo: 'foo.js', - }, - scripts: { - test: 'node test.js', - }, - }, - 'should add single field to package.json' - ) + t.end() }) -t.test('set = separate value', async t => { - const json = { - name: 'foo', - version: '1.1.1', - } - const { pkg, readPackageJson } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify(json), - }, +t.test('set', t => { + t.test('set no args', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'foo' }), + }, + }) + await t.rejects( + npm.exec('pkg', ['set']), + { code: 'EUSAGE' }, + 'should throw an error if no args' + ) }) - await pkg('set', 'tap[test-env][0]=LC_ALL=sk') - t.strictSame( - readPackageJson(), - { - ...json, - tap: { - 'test-env': [ - 'LC_ALL=sk', - ], + t.test('set missing value', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'foo' }), }, - }, - 'should add single field to package.json' - ) -}) - -t.test('set --json', async t => { - const { pkg, readPackageJson } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - version: '1.1.1', - }), - }, - config: { json: true }, + }) + await t.rejects( + npm.exec('pkg', ['set', 'key=']), + { code: 'EUSAGE' }, + 'should throw an error if missing value' + ) }) - await pkg('set', 'private=true') - t.strictSame( - readPackageJson(), - { - name: 'foo', - version: '1.1.1', - private: true, - }, - 'should add boolean field to package.json' - ) + t.test('set missing key', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'foo' }), + }, + }) + await t.rejects( + npm.exec('pkg', ['set', '=value']), + { code: 'EUSAGE' }, + 'should throw an error if missing key' + ) + }) - await pkg('set', 'tap.timeout=60') - t.strictSame( - readPackageJson(), - { + t.test('set single field', async t => { + const json = { name: 'foo', version: '1.1.1', - private: true, - tap: { - timeout: 60, + } + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify(json), }, - }, - 'should add number field to package.json' - ) + }) - await pkg('set', 'foo={ "bar": { "baz": "BAZ" } }') - t.strictSame( - readPackageJson(), - { + await npm.exec('pkg', ['set', 'description=Awesome stuff']) + t.matchSnapshot( + readPackageJson(npm.prefix), + 'should add single field to package.json' + ) + }) + + t.test('push to array syntax', async t => { + const json = { name: 'foo', version: '1.1.1', - private: true, - tap: { - timeout: 60, - }, - foo: { - bar: { - baz: 'BAZ', - }, + keywords: [ + 'foo', + ], + } + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify(json), }, - }, - 'should add object field to package.json' - ) + }) + + await npm.exec('pkg', ['set', 'keywords[]=bar', 'keywords[]=baz']) + t.matchSnapshot( + readPackageJson(npm.prefix), + 'should append to arrays using empty bracket syntax' + ) + }) - await pkg('set', 'workspaces=["packages/*"]') - t.strictSame( - readPackageJson(), - { + t.test('set multiple fields', async t => { + const json = { name: 'foo', version: '1.1.1', - private: true, - workspaces: [ - 'packages/*', - ], - tap: { - timeout: 60, - }, - foo: { - bar: { - baz: 'BAZ', - }, + } + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify(json), }, - }, - 'should add object field to package.json' - ) + }) + + await npm.exec('pkg', ['set', 'bin.foo=foo.js', 'scripts.test=node test.js']) + t.matchSnapshot( + readPackageJson(npm.prefix), + 'should add single field to package.json' + ) + }) - await pkg('set', 'description="awesome"') - t.strictSame( - readPackageJson(), - { + t.test('set = separate value', async t => { + const json = { name: 'foo', version: '1.1.1', - description: 'awesome', - private: true, - workspaces: [ - 'packages/*', - ], - tap: { - timeout: 60, + } + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify(json), }, - foo: { - bar: { - baz: 'BAZ', - }, + }) + + await npm.exec('pkg', ['set', 'tap[test-env][0]=LC_ALL=sk']) + t.matchSnapshot( + readPackageJson(npm.prefix), + 'should add single field to package.json' + ) + }) + + t.test('set --json', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.1.1', + }), }, - }, - 'should add object field to package.json' - ) + config: { json: true }, + }) + + await npm.exec('pkg', ['set', 'private=true']) + await npm.exec('pkg', ['set', 'tap.timeout=60']) + await npm.exec('pkg', ['set', 'foo={ "bar": { "baz": "BAZ" } }']) + await npm.exec('pkg', ['set', 'workspaces=["packages/*"]']) + await npm.exec('pkg', ['set', 'description="awesome"']) + t.matchSnapshot( + readPackageJson(npm.prefix), + 'should add fields to package.json' + ) + }) + t.end() }) -t.test('delete no args', async t => { - const { pkg } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ name: 'foo' }), - }, +t.test('delete', t => { + t.test('delete no args', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'foo' }), + }, + }) + await t.rejects( + npm.exec('pkg', ['delete']), + { code: 'EUSAGE' }, + 'should throw an error if deleting no args' + ) }) - await t.rejects( - pkg('delete'), - { code: 'EUSAGE' }, - 'should throw an error if deleting no args' - ) -}) -t.test('delete invalid key', async t => { - const { pkg } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ name: 'foo' }), - }, + t.test('delete invalid key', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'foo' }), + }, + }) + await t.rejects( + npm.exec('pkg', ['delete', '']), + { code: 'EUSAGE' }, + 'should throw an error if deleting invalid args' + ) }) - await t.rejects( - pkg('delete', ''), - { code: 'EUSAGE' }, - 'should throw an error if deleting invalid args' - ) -}) -t.test('delete single field', async t => { - const { pkg, readPackageJson } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - version: '1.0.0', - }), - }, + t.test('delete single field', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.0.0', + }), + }, + }) + await npm.exec('pkg', ['delete', 'version']) + t.matchSnapshot( + readPackageJson(npm.prefix), + 'should delete single field from package.json' + ) }) - await pkg('delete', 'version') - t.strictSame( - readPackageJson(), - { - name: 'foo', - }, - 'should delete single field from package.json' - ) -}) -t.test('delete multiple field', async t => { - const { pkg, readPackageJson } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - version: '1.0.0', - description: 'awesome', - }), - }, + t.test('delete multiple field', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.0.0', + description: 'awesome', + }), + }, + }) + await npm.exec('pkg', ['delete', 'version', 'description']) + t.matchSnapshot( + readPackageJson(npm.prefix), + 'should delete multiple fields from package.json' + ) }) - await pkg('delete', 'version', 'description') - t.strictSame( - readPackageJson(), - { - name: 'foo', - }, - 'should delete multiple fields from package.json' - ) -}) -t.test('delete nested field', async t => { - const { pkg, readPackageJson } = await mockNpm(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - version: '1.0.0', - info: { - foo: { - bar: [ - { - baz: 'deleteme', - }, - ], + t.test('delete nested field', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.0.0', + info: { + foo: { + bar: [ + { + baz: 'deleteme', + }, + ], + }, }, - }, - }), - }, - }) - await pkg('delete', 'info.foo.bar[0].baz') - t.strictSame( - readPackageJson(), - { - name: 'foo', - version: '1.0.0', - info: { - foo: { - bar: [ - {}, - ], - }, + }), }, - }, - 'should delete nested fields from package.json' - ) + }) + await npm.exec('pkg', ['delete', 'info.foo.bar[0].baz']) + t.matchSnapshot( + readPackageJson(npm.prefix), + 'should delete nested fields from package.json' + ) + }) + t.end() }) t.test('workspaces', async t => { - const mockWorkspaces = (t) => mockNpm(t, { + const workspaceSetup = { prefixDir: { 'package.json': JSON.stringify({ name: 'root', @@ -603,76 +529,63 @@ t.test('workspaces', async t => { }, }, config: { workspaces: true }, - }) + } t.test('get', async t => { - const { pkg, OUTPUT } = await mockWorkspaces(t) - await pkg('get', 'name', 'version') - t.strictSame( - JSON.parse(OUTPUT()), - { - a: { - name: 'a', - version: '1.0.0', - }, - b: { - name: 'b', - version: '1.2.3', - }, - }, + const { npm, joinedOutput } = await loadMockNpm(t, workspaceSetup) + await npm.exec('pkg', ['get', 'name', 'version']) + t.matchSnapshot( + joinedOutput(), 'should return expected result for configured workspaces' ) }) + t.test('get json ', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + ...workspaceSetup, + config: { + json: true, + workspaces: true, + }, + }) + await npm.exec('pkg', ['get', 'name', 'version']) + t.matchSnapshot( + joinedOutput(), + 'should return expected json result for configured workspaces' + ) + }) + t.test('set', async t => { - const { pkg, readPackageJson } = await mockWorkspaces(t) + const { npm } = await loadMockNpm(t, workspaceSetup) - await pkg('set', 'funding=http://example.com') + await npm.exec('pkg', ['set', 'funding=http://example.com']) - t.strictSame( - readPackageJson('packages/a'), - { - name: 'a', - version: '1.0.0', - funding: 'http://example.com', - }, + t.matchSnapshot( + readPackageJson(npm.prefix, 'packages/a'), 'should add field to workspace a' ) - t.strictSame( - readPackageJson('packages/b'), - { - name: 'b', - version: '1.2.3', - funding: 'http://example.com', - }, + t.matchSnapshot( + readPackageJson(npm.prefix, 'packages/b'), 'should add field to workspace b' ) - await pkg('delete', 'version') + await npm.exec('pkg', ['delete', 'version']) - t.strictSame( - readPackageJson('packages/a'), - { - name: 'a', - funding: 'http://example.com', - }, + t.matchSnapshot( + readPackageJson(npm.prefix, 'packages/a'), 'should delete version field from workspace a' ) - t.strictSame( - readPackageJson('packages/b'), - { - name: 'b', - funding: 'http://example.com', - }, + t.matchSnapshot( + readPackageJson(npm.prefix, 'packages/b'), 'should delete version field from workspace b' ) }) }) t.test('single workspace', async t => { - const mockWorkspace = (t) => mockNpm(t, { + const workspaceSetup = { prefixDir: { 'package.json': JSON.stringify({ name: 'root', @@ -697,33 +610,31 @@ t.test('single workspace', async t => { }, }, config: { workspace: ['packages/a'] }, - }) + } t.test('multiple args', async t => { - const { pkg, OUTPUT } = await mockWorkspace(t) - await pkg('get', 'name', 'version') + const { npm, joinedOutput } = await loadMockNpm(t, workspaceSetup) + await npm.exec('pkg', ['get', 'name', 'version']) - t.strictSame( - JSON.parse(OUTPUT()), - { a: { name: 'a', version: '1.0.0' } }, + t.matchSnapshot( + joinedOutput(), 'should only return info for one workspace' ) }) t.test('single arg', async t => { - const { pkg, OUTPUT } = await mockWorkspace(t) - await pkg('get', 'version') + const { npm, joinedOutput } = await loadMockNpm(t, workspaceSetup) + await npm.exec('pkg', ['get', 'version']) - t.strictSame( - JSON.parse(OUTPUT()), - { a: '1.0.0' }, + t.matchSnapshot( + joinedOutput(), 'should only return info for one workspace' ) }) }) t.test('fix', async t => { - const { pkg, readPackageJson } = await mockNpm(t, { + const { npm } = await loadMockNpm(t, { prefixDir: { 'package.json': JSON.stringify({ name: 'foo ', @@ -732,10 +643,9 @@ t.test('fix', async t => { }, }) - await pkg('fix') - t.strictSame( - readPackageJson(), - { name: 'foo', version: '1.1.1' }, + await npm.exec('pkg', ['fix']) + t.matchSnapshot( + readPackageJson(npm.prefix), 'fixes package.json issues' ) }) diff --git a/test/lib/commands/profile.js b/test/lib/commands/profile.js index 8bbffd1675d07..15c4d116f25d0 100644 --- a/test/lib/commands/profile.js +++ b/test/lib/commands/profile.js @@ -1,7 +1,16 @@ +const { inspect } = require('node:util') const t = require('tap') const mockNpm = require('../../fixtures/mock-npm') +const tmock = require('../../fixtures/tmock') -const mockProfile = async (t, { npmProfile, readUserInfo, qrcode, config, ...opts } = {}) => { +const mockProfile = async (t, { + npmProfile, readUserInfo, qrcode, config, isTTY, ...opts } = {}) => { + const mockReadUserInfo = { + '{LIB}/utils/read-user-info.js': readUserInfo || { + async password () {}, + async otp () {}, + }, + } const mocks = { 'npm-profile': npmProfile || { async get () {}, @@ -9,10 +18,8 @@ const mockProfile = async (t, { npmProfile, readUserInfo, qrcode, config, ...opt async createToken () {}, }, 'qrcode-terminal': qrcode || { generate: (url, cb) => cb() }, - '{LIB}/utils/read-user-info.js': readUserInfo || { - async password () {}, - async otp () {}, - }, + ...mockReadUserInfo, + '{LIB}/utils/auth.js': tmock(t, '{LIB}/utils/auth.js', mockReadUserInfo), } const mock = await mockNpm(t, { @@ -22,6 +29,10 @@ const mockProfile = async (t, { npmProfile, readUserInfo, qrcode, config, ...opt color: false, ...config, }, + globals: { + 'process.stdin.isTTY': isTTY, + 'process.stdout.isTTY': isTTY, + }, mocks: { ...mocks, ...opts.mocks, @@ -44,8 +55,6 @@ const userProfile = { cidr_whitelist: null, fullname: 'Foo Bar', homepage: 'https://github.com', - freenode: 'foobar', - twitter: 'https://twitter.com/npmjs', github: 'https://github.com/npm', } @@ -516,6 +525,12 @@ t.test('enable-2fa', async t => { t.match(pass, 'bar', 'should use password for basic auth') return {} }, + async get () { + return { + userProfile, + tfa: null, + } + }, } const { npm, profile } = await mockProfile(t, { @@ -543,6 +558,12 @@ t.test('enable-2fa', async t => { async createToken () { return {} }, + async get () { + return { + ...userProfile, + tfa: null, + } + }, } const { npm, profile } = await mockProfile(t, { @@ -577,7 +598,9 @@ t.test('enable-2fa', async t => { }) t.test('from basic auth, asks for otp', async t => { - t.plan(9) + t.plan(10) + + let setCallCount = 0 const npmProfile = { async createToken (pass) { @@ -588,18 +611,36 @@ t.test('enable-2fa', async t => { return userProfile }, async set (newProfile) { - t.match( - newProfile, - { + setCallCount++ + if (setCallCount === 1) { + t.match( + newProfile, + { + tfa: { + mode: 'auth-only', + }, + }, + 'should set tfa mode on first call' + ) + const err = new Error('One-time password required') + err.code = 'EOTP' + throw err + } else if (setCallCount === 2) { + t.match( + newProfile, + { + tfa: { + mode: 'auth-only', + }, + }, + 'should set tfa mode' + ) + return { + ...userProfile, tfa: { mode: 'auth-only', }, - }, - 'should set tfa mode' - ) - return { - ...userProfile, - tfa: null, + } } }, } @@ -612,7 +653,7 @@ t.test('enable-2fa', async t => { async otp (label) { t.equal( label, - 'Enter one-time password: ', + 'This operation requires a one-time password.\nEnter OTP:', 'should ask for otp confirmation' ) return '123456' @@ -620,6 +661,7 @@ t.test('enable-2fa', async t => { } const { npm, profile, result } = await mockProfile(t, { + isTTY: true, npmProfile, readUserInfo, }) @@ -683,7 +725,7 @@ t.test('enable-2fa', async t => { mode: 'auth-only', }, }, - 'should set tfa mode approprietly in follow-up call' + 'should set tfa mode appropriately in follow-up call' ) } else if (setCount === 3) { t.match( @@ -817,12 +859,12 @@ t.test('enable-2fa', async t => { t.equal( result(), - 'Two factor authentication mode changed to: auth-and-writes', + 'Two factor authentication is already enabled and set to auth-and-writes', 'should output success msg' ) }) - t.test('missing tfa from user profile', async t => { + t.test('errors when tfa is return null (not otpauth URL) and tfa is not setup already (with auth-only)', async t => { const npmProfile = { async get () { return { @@ -847,7 +889,7 @@ t.test('enable-2fa', async t => { }, } - const { npm, profile, result } = await mockProfile(t, { + const { npm, profile } = await mockProfile(t, { npmProfile, readUserInfo, }) @@ -856,16 +898,15 @@ t.test('enable-2fa', async t => { return { token: 'token' } } - await profile.exec(['enable-2fa', 'auth-only']) - - t.equal( - result(), - 'Two factor authentication mode changed to: auth-only', - 'should output success msg' - ) + await t.rejects(async () => { + await profile.exec(['enable-2fa', 'auth-only']) + }, new Error( + 'Unknown error enabling two-factor authentication. Expected otpauth URL' + + ', got: ' + inspect(null) + )) }) - t.test('defaults to auth-and-writes permission if no mode specified', async t => { + t.test('errors when tfa is return null (not otpauth URL) and tfa is not setup already', async t => { const npmProfile = { async get () { return { @@ -890,7 +931,7 @@ t.test('enable-2fa', async t => { }, } - const { npm, profile, result } = await mockProfile(t, { + const { npm, profile } = await mockProfile(t, { npmProfile, readUserInfo, }) @@ -899,12 +940,12 @@ t.test('enable-2fa', async t => { return { token: 'token' } } - await profile.exec(['enable-2fa']) - t.equal( - result(), - 'Two factor authentication mode changed to: auth-and-writes', - 'should enable 2fa with auth-and-writes permission' - ) + await t.rejects(async () => { + await profile.exec(['enable-2fa']) + }, new Error( + 'Unknown error enabling two-factor authentication. Expected otpauth URL' + + ', got: ' + inspect(null) + )) }) }) @@ -925,27 +966,37 @@ t.test('disable-2fa', async t => { await profile.exec(['disable-2fa']) t.equal(result(), 'Two factor authentication not enabled.', - 'should output already disalbed msg') + 'should output already disabled msg') }) t.test('requests otp', async t => { - const npmProfile = t => ({ - async get () { - return userProfile - }, - async set (newProfile) { - t.same( - newProfile, - { - tfa: { - password: 'password1234', - mode: 'disable', - }, - }, - 'should send the new info for setting in profile' - ) - }, - }) + const OTP_ERROR = Object.assign(new Error('One-time password required'), { code: 'EOTP' }) + + const npmProfile = (t) => { + let setCallCount = 0 + return { + async get () { + return userProfile + }, + async set (newProfile) { + setCallCount++ + if (setCallCount === 1) { + throw OTP_ERROR + } else if (setCallCount === 2) { + t.same( + newProfile, + { + tfa: { + password: 'password1234', + mode: 'disable', + }, + }, + 'should send the new info for setting in profile' + ) + } + }, + } + } const readUserInfo = t => ({ async password () { @@ -955,7 +1006,7 @@ t.test('disable-2fa', async t => { async otp (label) { t.equal( label, - 'Enter one-time password: ', + 'This operation requires a one-time password.\nEnter OTP:', 'should ask for otp confirmation' ) return '1234' @@ -968,6 +1019,7 @@ t.test('disable-2fa', async t => { const { profile, result } = await mockProfile(t, { npmProfile: npmProfile(t), readUserInfo: readUserInfo(t), + isTTY: true, }) await profile.exec(['disable-2fa']) @@ -983,6 +1035,7 @@ t.test('disable-2fa', async t => { npmProfile: npmProfile(t), readUserInfo: readUserInfo(t), config, + isTTY: true, }) await profile.exec(['disable-2fa']) @@ -999,6 +1052,7 @@ t.test('disable-2fa', async t => { npmProfile: npmProfile(t), readUserInfo: readUserInfo(t), config, + isTTY: true, }) await profile.exec(['disable-2fa']) @@ -1045,7 +1099,7 @@ t.test('disable-2fa', async t => { await profile.exec(['disable-2fa']) - t.equal(result(), 'Two factor authentication disabled.', 'should output already disalbed msg') + t.equal(result(), 'Two factor authentication disabled.', 'should output already disabled msg') }) }) diff --git a/test/lib/commands/prune.js b/test/lib/commands/prune.js index 65cfba5e5c00a..235ca134ce1e7 100644 --- a/test/lib/commands/prune.js +++ b/test/lib/commands/prune.js @@ -19,3 +19,30 @@ t.test('should prune using Arborist', async (t) => { }) await npm.exec('prune', []) }) + +t.test('prune threads allowScripts policy through to arborist', async t => { + let capturedOpts + const FakeArborist = function (opts) { + capturedOpts = opts + this.options = opts + this.actualTree = { inventory: new Map() } + } + FakeArborist.prototype.prune = async () => {} + + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + allowScripts: { canvas: true }, + }), + }, + mocks: { + '@npmcli/arborist': FakeArborist, + '{LIB}/utils/reify-finish.js': async () => {}, + }, + }) + await npm.exec('prune', []) + t.strictSame(capturedOpts.allowScripts, { canvas: true }, + 'opts.allowScripts populated from package.json') +}) diff --git a/test/lib/commands/publish.js b/test/lib/commands/publish.js index fa43994679b97..fe286ff46b748 100644 --- a/test/lib/commands/publish.js +++ b/test/lib/commands/publish.js @@ -1,14 +1,15 @@ const t = require('tap') -const { load: loadMockNpm } = require('../../fixtures/mock-npm') +const { loadNpmWithRegistry } = require('../../fixtures/mock-npm') const { cleanZlib } = require('../../fixtures/clean-snapshot') -const MockRegistry = require('@npmcli/mock-registry') const pacote = require('pacote') const Arborist = require('@npmcli/arborist') const path = require('node:path') const fs = require('node:fs') -const npa = require('npm-package-arg') +const { circleciIdToken, githubIdToken, gitlabIdToken, oidcPublishTest, mockOidc } = require('../../fixtures/mock-oidc') +const { sigstoreIdToken } = require('@npmcli/mock-registry/lib/provenance') +const mockGlobals = require('@npmcli/mock-globals') -const pkg = 'test-package' +const pkg = '@npmcli/test-package' const token = 'test-auth-token' const auth = { '//registry.npmjs.org/:_authToken': token } const alternateRegistry = 'https://other.registry.npmjs.org' @@ -23,172 +24,101 @@ const pkgJson = { t.cleanSnapshot = data => cleanZlib(data) t.test('respects publishConfig.registry, runs appropriate scripts', async t => { - const { npm, joinedOutput, prefix } = await loadMockNpm(t, { + const packageJson = { + ...pkgJson, + scripts: { + prepublishOnly: 'touch scripts-prepublishonly', + prepublish: 'touch scripts-prepublish', // should NOT run this one + publish: 'touch scripts-publish', + postpublish: 'touch scripts-postpublish', + }, + publishConfig: { + other: 'not defined', + registry: alternateRegistry, + }, + } + const { npm, joinedOutput, logs, prefix, registry } = await loadNpmWithRegistry(t, { config: { - loglevel: 'silent', + loglevel: 'warn', [`${alternateRegistry.slice(6)}/:_authToken`]: 'test-other-token', }, prefixDir: { - 'package.json': JSON.stringify({ - ...pkgJson, - scripts: { - prepublishOnly: 'touch scripts-prepublishonly', - prepublish: 'touch scripts-prepublish', // should NOT run this one - publish: 'touch scripts-publish', - postpublish: 'touch scripts-postpublish', - }, - publishConfig: { registry: alternateRegistry }, - }, null, 2), + 'package.json': JSON.stringify(packageJson, null, 2), }, - }) - const registry = new MockRegistry({ - tap: t, registry: alternateRegistry, authorization: 'test-other-token', }) - registry.nock.put(`/${pkg}`, body => { - return t.match(body, { - _id: pkg, - name: pkg, - 'dist-tags': { latest: '1.0.0' }, - access: null, - versions: { - '1.0.0': { - name: pkg, - version: '1.0.0', - _id: `${pkg}@1.0.0`, - dist: { - shasum: /\.*/, - tarball: `http:${alternateRegistry.slice(6)}/test-package/-/test-package-1.0.0.tgz`, - }, - publishConfig: { - registry: alternateRegistry, - }, - }, - }, - _attachments: { - [`${pkg}-1.0.0.tgz`]: {}, - }, - }) - }).reply(200, {}) + registry.publish(pkg, { packageJson }) await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'new package version') t.equal(fs.existsSync(path.join(prefix, 'scripts-prepublishonly')), true, 'ran prepublishOnly') t.equal(fs.existsSync(path.join(prefix, 'scripts-prepublish')), false, 'did not run prepublish') t.equal(fs.existsSync(path.join(prefix, 'scripts-publish')), true, 'ran publish') t.equal(fs.existsSync(path.join(prefix, 'scripts-postpublish')), true, 'ran postpublish') + t.same(logs.warn, ['Unknown publishConfig config "other". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.']) }) t.test('re-loads publishConfig.registry if added during script process', async t => { - const { joinedOutput, npm } = await loadMockNpm(t, { + const initPackageJson = { + ...pkgJson, + scripts: { + prepare: 'cp new.json package.json', + }, + } + const packageJson = { + ...initPackageJson, + publishConfig: { registry: alternateRegistry }, + } + const { joinedOutput, npm, registry } = await loadNpmWithRegistry(t, { config: { [`${alternateRegistry.slice(6)}/:_authToken`]: 'test-other-token', // Keep output from leaking into tap logs for readability 'foreground-scripts': false, }, prefixDir: { - 'package.json': JSON.stringify({ - ...pkgJson, - scripts: { - prepare: 'cp new.json package.json', - }, - }, null, 2), - 'new.json': JSON.stringify({ - ...pkgJson, - publishConfig: { registry: alternateRegistry }, - }), + 'package.json': JSON.stringify(initPackageJson, null, 2), + 'new.json': JSON.stringify(packageJson, null, 2), }, - }) - const registry = new MockRegistry({ - tap: t, registry: alternateRegistry, authorization: 'test-other-token', }) - registry.nock.put(`/${pkg}`, body => { - return t.match(body, { - _id: pkg, - name: pkg, - 'dist-tags': { latest: '1.0.0' }, - access: null, - versions: { - '1.0.0': { - name: pkg, - version: '1.0.0', - _id: `${pkg}@1.0.0`, - dist: { - shasum: /\.*/, - tarball: `http:${alternateRegistry.slice(6)}/test-package/-/test-package-1.0.0.tgz`, - }, - publishConfig: { - registry: alternateRegistry, - }, - }, - }, - _attachments: { - [`${pkg}-1.0.0.tgz`]: {}, - }, - }) - }).reply(200, {}) + registry.publish(pkg, { packageJson }) await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'new package version') }) t.test('prioritize CLI flags over publishConfig', async t => { - const publishConfig = { registry: 'http://publishconfig' } - const { joinedOutput, npm } = await loadMockNpm(t, { + const initPackageJson = { + ...pkgJson, + scripts: { + prepare: 'cp new.json package.json', + }, + } + const packageJson = { + ...initPackageJson, + publishConfig: { registry: alternateRegistry }, + } + const { joinedOutput, npm, registry } = await loadNpmWithRegistry(t, { config: { [`${alternateRegistry.slice(6)}/:_authToken`]: 'test-other-token', // Keep output from leaking into tap logs for readability 'foreground-scripts': false, }, prefixDir: { - 'package.json': JSON.stringify({ - ...pkgJson, - scripts: { - prepare: 'cp new.json package.json', - }, - }, null, 2), - 'new.json': JSON.stringify({ - ...pkgJson, - publishConfig, - }), + 'package.json': JSON.stringify(initPackageJson, null, 2), + 'new.json': JSON.stringify(packageJson, null, 2), }, argv: ['--registry', alternateRegistry], - }) - const registry = new MockRegistry({ - tap: t, - registry: alternateRegistry, + registryUrl: alternateRegistry, authorization: 'test-other-token', }) - registry.nock.put(`/${pkg}`, body => { - return t.match(body, { - _id: pkg, - name: pkg, - 'dist-tags': { latest: '1.0.0' }, - access: null, - versions: { - '1.0.0': { - name: pkg, - version: '1.0.0', - _id: `${pkg}@1.0.0`, - dist: { - shasum: /\.*/, - tarball: `http:${alternateRegistry.slice(6)}/test-package/-/test-package-1.0.0.tgz`, - }, - publishConfig, - }, - }, - _attachments: { - [`${pkg}-1.0.0.tgz`]: {}, - }, - }) - }).reply(200, {}) + registry.publish(pkg, { packageJson }) await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'new package version') }) t.test('json', async t => { - const { joinedOutput, npm, logs } = await loadMockNpm(t, { + const { joinedOutput, npm, logs, registry } = await loadNpmWithRegistry(t, { config: { json: true, ...auth, @@ -196,20 +126,16 @@ t.test('json', async t => { prefixDir: { 'package.json': JSON.stringify(pkgJson, null, 2), }, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), authorization: token, }) - registry.nock.put(`/${pkg}`).reply(200, {}) + registry.publish(pkg) await npm.exec('publish', []) t.matchSnapshot(logs.notice) t.matchSnapshot(joinedOutput(), 'new package json') }) t.test('dry-run', async t => { - const { joinedOutput, npm, logs } = await loadMockNpm(t, { + const { joinedOutput, npm, logs, registry } = await loadNpmWithRegistry(t, { config: { 'dry-run': true, ...auth, @@ -217,14 +143,16 @@ t.test('dry-run', async t => { prefixDir: { 'package.json': JSON.stringify(pkgJson, null, 2), }, + authorization: token, }) + registry.publish(pkg, { noPut: true }) await npm.exec('publish', []) t.equal(joinedOutput(), `+ ${pkg}@1.0.0`) t.matchSnapshot(logs.notice) }) t.test('foreground-scripts defaults to true', async t => { - const { outputs, npm, logs } = await loadMockNpm(t, { + const { outputs, npm, logs, registry } = await loadNpmWithRegistry(t, { config: { 'dry-run': true, ...auth, @@ -241,23 +169,17 @@ t.test('foreground-scripts defaults to true', async t => { ), }, }) - + registry.publish('test-fg-scripts', { noPut: true }) await npm.exec('publish', []) - t.matchSnapshot(logs.notice) - t.strictSame( outputs, - [ - '\n> test-fg-scripts@0.0.0 prepack\n> echo prepack!\n', - '\n> test-fg-scripts@0.0.0 postpack\n> echo postpack!\n', - `+ test-fg-scripts@0.0.0`, - ], - 'prepack and postpack log to stdout') + [`+ test-fg-scripts@0.0.0`], + 'published package is the only stdout output') }) t.test('foreground-scripts can still be set to false', async t => { - const { outputs, npm, logs } = await loadMockNpm(t, { + const { outputs, npm, logs, registry } = await loadNpmWithRegistry(t, { config: { 'dry-run': true, 'foreground-scripts': false, @@ -276,6 +198,7 @@ t.test('foreground-scripts can still be set to false', async t => { }, }) + registry.publish('test-fg-scripts', { noPut: true }) await npm.exec('publish', []) t.matchSnapshot(logs.notice) @@ -287,12 +210,73 @@ t.test('foreground-scripts can still be set to false', async t => { }) t.test('shows usage with wrong set of arguments', async t => { - const { publish } = await loadMockNpm(t, { command: 'publish' }) + const { publish } = await loadNpmWithRegistry(t, { command: 'publish' }) await t.rejects(publish.exec(['a', 'b', 'c']), publish.usage) }) +t.test('fails for a non-private package containing packageExtensions', async t => { + const { npm } = await loadNpmWithRegistry(t, { + config: { ...auth }, + prefixDir: { + 'package.json': JSON.stringify({ + ...pkgJson, + packageExtensions: { 'foo@1': { dependencies: { bar: '^1.0.0' } } }, + }, null, 2), + }, + authorization: token, + }) + await t.rejects( + npm.exec('publish', []), + { code: 'EPACKAGEEXTENSIONS', message: /must not be published/ }, + 'refuses to publish' + ) +}) + +t.test('fails on --dry-run for a package containing packageExtensions', async t => { + const { npm } = await loadNpmWithRegistry(t, { + config: { 'dry-run': true, ...auth }, + prefixDir: { + 'package.json': JSON.stringify({ + ...pkgJson, + packageExtensions: { 'foo@1': { dependencies: { bar: '^1.0.0' } } }, + }, null, 2), + }, + authorization: token, + }) + await t.rejects( + npm.exec('publish', []), + { code: 'EPACKAGEEXTENSIONS' }, + 'dry-run also reports the failure' + ) +}) + +t.test('fails when a lifecycle script injects packageExtensions before the re-read', async t => { + const { npm } = await loadNpmWithRegistry(t, { + config: { ...auth }, + prefixDir: { + 'package.json': JSON.stringify({ + ...pkgJson, + scripts: { prepublishOnly: 'node inject.js' }, + }, null, 2), + // the first manifest read is clean; this hook adds packageExtensions before the authoritative re-read + 'inject.js': [ + "const fs = require('fs')", + "const p = JSON.parse(fs.readFileSync('package.json'))", + "p.packageExtensions = { 'foo@1': { dependencies: { bar: '^1.0.0' } } }", + "fs.writeFileSync('package.json', JSON.stringify(p))", + ].join('\n'), + }, + authorization: token, + }) + await t.rejects( + npm.exec('publish', []), + { code: 'EPACKAGEEXTENSIONS' }, + 'the post-script manifest re-read catches the injected field' + ) +}) + t.test('throws when invalid tag is semver', async t => { - const { npm } = await loadMockNpm(t, { + const { npm } = await loadNpmWithRegistry(t, { config: { tag: '0.0.13', }, @@ -307,7 +291,7 @@ t.test('throws when invalid tag is semver', async t => { }) t.test('throws when invalid tag when not url encodable', async t => { - const { npm } = await loadMockNpm(t, { + const { npm } = await loadNpmWithRegistry(t, { config: { tag: '@test', }, @@ -318,14 +302,13 @@ t.test('throws when invalid tag when not url encodable', async t => { await t.rejects( npm.exec('publish', []), { - /* eslint-disable-next-line max-len */ - message: 'Invalid tag name "@test" of package "test-package@@test": Tags may not have any characters that encodeURIComponent encodes.', + message: `Invalid tag name "@test" of package "${pkg}@@test": Tags may not have any characters that encodeURIComponent encodes.`, } ) }) t.test('tarball', async t => { - const { npm, joinedOutput, logs, home } = await loadMockNpm(t, { + const { npm, joinedOutput, logs, home, registry } = await loadNpmWithRegistry(t, { config: { 'fetch-retries': 0, ...auth, @@ -338,27 +321,19 @@ t.test('tarball', async t => { }, null, 2), 'index.js': 'console.log("hello world"}', }, + authorization: token, }) const tarball = await pacote.tarball(home, { Arborist }) const tarFilename = path.join(home, 'tarball.tgz') fs.writeFileSync(tarFilename, tarball) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), - authorization: token, - }) - registry.nock.put('/test-tar-package', body => { - return t.match(body, { - name: 'test-tar-package', - }) - }).reply(200, {}) + registry.publish('test-tar-package') await npm.exec('publish', [tarFilename]) t.matchSnapshot(logs.notice) t.matchSnapshot(joinedOutput(), 'new package json') }) t.test('no auth default registry', async t => { - const { npm } = await loadMockNpm(t, { + const { npm } = await loadNpmWithRegistry(t, { prefixDir: { 'package.json': JSON.stringify(pkgJson, null, 2), }, @@ -373,7 +348,7 @@ t.test('no auth default registry', async t => { }) t.test('no auth dry-run', async t => { - const { npm, joinedOutput, logs } = await loadMockNpm(t, { + const { npm, joinedOutput, logs, registry } = await loadNpmWithRegistry(t, { config: { 'dry-run': true, }, @@ -381,13 +356,14 @@ t.test('no auth dry-run', async t => { 'package.json': JSON.stringify(pkgJson, null, 2), }, }) + registry.publish(pkg, { noPut: true }) await npm.exec('publish', []) t.matchSnapshot(joinedOutput()) t.matchSnapshot(logs.warn, 'warns about auth being needed') }) t.test('no auth for configured registry', async t => { - const { npm } = await loadMockNpm(t, { + const { npm } = await loadNpmWithRegistry(t, { config: { registry: alternateRegistry, ...auth, @@ -406,7 +382,7 @@ t.test('no auth for configured registry', async t => { }) t.test('no auth for scope configured registry', async t => { - const { npm } = await loadMockNpm(t, { + const { npm } = await loadNpmWithRegistry(t, { config: { scope: '@npm', registry: alternateRegistry, @@ -429,8 +405,7 @@ t.test('no auth for scope configured registry', async t => { }) t.test('has token auth for scope configured registry', async t => { - const spec = npa('@npm/test-package') - const { npm, joinedOutput } = await loadMockNpm(t, { + const { npm, joinedOutput, registry } = await loadNpmWithRegistry(t, { config: { scope: '@npm', registry: alternateRegistry, @@ -442,22 +417,16 @@ t.test('has token auth for scope configured registry', async t => { version: '1.0.0', }, null, 2), }, - }) - const registry = new MockRegistry({ - tap: t, registry: alternateRegistry, authorization: 'test-scope-token', }) - registry.nock.put(`/${spec.escapedName}`, body => { - return t.match(body, { name: '@npm/test-package' }) - }).reply(200, {}) + registry.publish('@npm/test-package') await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'new package version') }) t.test('has mTLS auth for scope configured registry', async t => { - const spec = npa('@npm/test-package') - const { npm, joinedOutput } = await loadMockNpm(t, { + const { npm, joinedOutput, registry } = await loadNpmWithRegistry(t, { config: { scope: '@npm', registry: alternateRegistry, @@ -470,14 +439,9 @@ t.test('has mTLS auth for scope configured registry', async t => { version: '1.0.0', }, null, 2), }, - }) - const registry = new MockRegistry({ - tap: t, registry: alternateRegistry, }) - registry.nock.put(`/${spec.escapedName}`, body => { - return t.match(body, { name: '@npm/test-package' }) - }).reply(200, {}) + registry.publish('@npm/test-package') await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'new package version') }) @@ -519,101 +483,71 @@ t.test('workspaces', t => { } t.test('all workspaces - no color', async t => { - const { npm, joinedOutput, logs } = await loadMockNpm(t, { + const { npm, joinedOutput, logs, registry } = await loadNpmWithRegistry(t, { config: { + tag: 'latest', color: false, ...auth, workspaces: true, }, prefixDir: dir, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), authorization: token, }) - registry.nock - .put('/workspace-a', body => { - return t.match(body, { name: 'workspace-a' }) - }).reply(200, {}) - .put('/workspace-b', body => { - return t.match(body, { name: 'workspace-b' }) - }).reply(200, {}) - .put('/workspace-n', body => { - return t.match(body, { name: 'workspace-n' }) - }).reply(200, {}) + ;['workspace-a', 'workspace-b', 'workspace-n'].forEach(name => { + registry.publish(name) + }) await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'all public workspaces') t.matchSnapshot(logs.warn, 'warns about skipped private workspace') }) t.test('all workspaces - color', async t => { - const { npm, joinedOutput, logs } = await loadMockNpm(t, { + const { npm, joinedOutput, logs, registry } = await loadNpmWithRegistry(t, { config: { ...auth, + tag: 'latest', color: 'always', workspaces: true, }, prefixDir: dir, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), authorization: token, }) - registry.nock - .put('/workspace-a', body => { - return t.match(body, { name: 'workspace-a' }) - }).reply(200, {}) - .put('/workspace-b', body => { - return t.match(body, { name: 'workspace-b' }) - }).reply(200, {}) - .put('/workspace-n', body => { - return t.match(body, { name: 'workspace-n' }) - }).reply(200, {}) + ;['workspace-a', 'workspace-b', 'workspace-n'].forEach(name => { + registry.publish(name) + }) await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'all public workspaces') t.matchSnapshot(logs.warn, 'warns about skipped private workspace in color') }) t.test('one workspace - success', async t => { - const { npm, joinedOutput } = await loadMockNpm(t, { + const { npm, joinedOutput, registry } = await loadNpmWithRegistry(t, { config: { ...auth, + tag: 'latest', workspace: ['workspace-a'], }, prefixDir: dir, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), authorization: token, }) - registry.nock - .put('/workspace-a', body => { - return t.match(body, { name: 'workspace-a' }) - }).reply(200, {}) + ;['workspace-a'].forEach(name => { + registry.publish(name) + }) await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'single workspace') }) t.test('one workspace - failure', async t => { - const { npm } = await loadMockNpm(t, { + const { npm, registry } = await loadNpmWithRegistry(t, { config: { ...auth, + tag: 'latest', workspace: ['workspace-a'], }, prefixDir: dir, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), authorization: token, }) - registry.nock - .put('/workspace-a', body => { - return t.match(body, { name: 'workspace-a' }) - }).reply(404, {}) + registry.publish('workspace-a', { putCode: 404 }) await t.rejects(npm.exec('publish', []), { code: 'E404' }) }) @@ -639,30 +573,25 @@ t.test('workspaces', t => { }, } - const { npm, joinedOutput } = await loadMockNpm(t, { + const { npm, joinedOutput, registry } = await loadNpmWithRegistry(t, { config: { ...auth, + tag: 'latest', workspaces: true, }, prefixDir: testDir, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), authorization: token, }) - registry.nock - .put('/workspace-a', body => { - return t.match(body, { name: 'workspace-a' }) - }).reply(200, {}) + registry.publish('workspace-a') await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'one marked private') }) t.test('invalid workspace', async t => { - const { npm } = await loadMockNpm(t, { + const { npm } = await loadNpmWithRegistry(t, { config: { ...auth, + tag: 'latest', workspace: ['workspace-x'], }, prefixDir: dir, @@ -674,37 +603,63 @@ t.test('workspaces', t => { }) t.test('json', async t => { - const { npm, joinedOutput } = await loadMockNpm(t, { + const { npm, joinedOutput, registry } = await loadNpmWithRegistry(t, { config: { ...auth, + tag: 'latest', workspaces: true, json: true, }, prefixDir: dir, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), authorization: token, }) - registry.nock - .put('/workspace-a', body => { - return t.match(body, { name: 'workspace-a' }) - }).reply(200, {}) - .put('/workspace-b', body => { - return t.match(body, { name: 'workspace-b' }) - }).reply(200, {}) - .put('/workspace-n', body => { - return t.match(body, { name: 'workspace-n' }) - }).reply(200, {}) + ;['workspace-a', 'workspace-b', 'workspace-n'].forEach(name => { + registry.publish(name) + }) await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'all workspaces in json') }) + + t.test('different package spec', async t => { + const testDir = { + 'package.json': JSON.stringify( + { + ...pkgJson, + workspaces: ['workspace-a'], + }, null, 2), + 'workspace-a': { + 'package.json': JSON.stringify({ + name: 'workspace-a', + version: '1.2.3-a', + }), + }, + 'dir/pkg': { + 'package.json': JSON.stringify({ + name: 'pkg', + version: '1.2.3', + }), + }, + } + + const { npm, joinedOutput, registry } = await loadNpmWithRegistry(t, { + config: { + ...auth, + tag: 'latest', + }, + prefixDir: testDir, + chdir: ({ prefix }) => path.resolve(prefix, './workspace-a'), + authorization: token, + }) + registry.publish('pkg') + await npm.exec('publish', ['../dir/pkg']) + t.matchSnapshot(joinedOutput(), 'publish different package spec') + }) + t.end() }) t.test('ignore-scripts', async t => { - const { npm, joinedOutput, prefix } = await loadMockNpm(t, { + const { npm, joinedOutput, prefix, registry } = await loadNpmWithRegistry(t, { config: { ...auth, 'ignore-scripts': true, @@ -720,13 +675,9 @@ t.test('ignore-scripts', async t => { }, }, null, 2), }, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), authorization: token, }) - registry.nock.put(`/${pkg}`).reply(200, {}) + registry.publish(pkg) await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'new package version') t.equal( @@ -752,27 +703,22 @@ t.test('ignore-scripts', async t => { }) t.test('_auth config default registry', async t => { - const { npm, joinedOutput } = await loadMockNpm(t, { + const { npm, joinedOutput, registry } = await loadNpmWithRegistry(t, { config: { '//registry.npmjs.org/:_auth': basic, }, prefixDir: { 'package.json': JSON.stringify(pkgJson), }, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), basic, }) - registry.nock.put(`/${pkg}`).reply(200, {}) + registry.publish(pkg) await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'new package version') }) t.test('bare _auth and registry config', async t => { - const spec = npa('@npm/test-package') - const { npm, joinedOutput } = await loadMockNpm(t, { + const { npm, joinedOutput, registry } = await loadNpmWithRegistry(t, { config: { registry: alternateRegistry, '//other.registry.npmjs.org/:_auth': basic, @@ -783,19 +729,16 @@ t.test('bare _auth and registry config', async t => { version: '1.0.0', }, null, 2), }, - }) - const registry = new MockRegistry({ - tap: t, registry: alternateRegistry, basic, }) - registry.nock.put(`/${spec.escapedName}`).reply(200, {}) + registry.publish('@npm/test-package') await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'new package version') }) t.test('bare _auth config scoped registry', async t => { - const { npm } = await loadMockNpm(t, { + const { npm } = await loadNpmWithRegistry(t, { config: { scope: '@npm', registry: alternateRegistry, @@ -815,8 +758,7 @@ t.test('bare _auth config scoped registry', async t => { }) t.test('scoped _auth config scoped registry', async t => { - const spec = npa('@npm/test-package') - const { npm, joinedOutput } = await loadMockNpm(t, { + const { npm, joinedOutput, registry } = await loadNpmWithRegistry(t, { config: { scope: '@npm', registry: alternateRegistry, @@ -828,48 +770,58 @@ t.test('scoped _auth config scoped registry', async t => { version: '1.0.0', }, null, 2), }, - }) - const registry = new MockRegistry({ - tap: t, registry: alternateRegistry, basic, }) - registry.nock.put(`/${spec.escapedName}`).reply(200, {}) + registry.publish('@npm/test-package') await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'new package version') }) t.test('restricted access', async t => { - const spec = npa('@npm/test-package') - const { npm, joinedOutput, logs } = await loadMockNpm(t, { + const packageJson = { + name: '@npm/test-package', + version: '1.0.0', + } + const { npm, joinedOutput, logs, registry } = await loadNpmWithRegistry(t, { config: { ...auth, access: 'restricted', }, prefixDir: { - 'package.json': JSON.stringify({ - name: '@npm/test-package', - version: '1.0.0', - }, null, 2), + 'package.json': JSON.stringify(packageJson, null, 2), }, + authorization: token, }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), + registry.publish('@npm/test-package', { packageJson, access: 'restricted' }) + await npm.exec('publish', []) + t.matchSnapshot(joinedOutput(), 'new package version') + t.matchSnapshot(logs.notice) +}) + +t.test('private access', async t => { + const packageJson = { + name: '@npm/test-package', + version: '1.0.0', + } + const { npm, joinedOutput, logs, registry } = await loadNpmWithRegistry(t, { + config: { + ...auth, + access: 'private', + }, + prefixDir: { + 'package.json': JSON.stringify(packageJson, null, 2), + }, authorization: token, }) - registry.nock.put(`/${spec.escapedName}`, body => { - t.equal(body.access, 'restricted', 'access is explicitly set to restricted') - return true - }).reply(200, {}) + registry.publish('@npm/test-package', { packageJson, access: 'restricted' }) await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'new package version') t.matchSnapshot(logs.notice) }) t.test('public access', async t => { - const spec = npa('@npm/test-package') - const { npm, joinedOutput, logs } = await loadMockNpm(t, { + const { npm, joinedOutput, logs, registry } = await loadNpmWithRegistry(t, { config: { ...auth, access: 'public', @@ -880,16 +832,9 @@ t.test('public access', async t => { version: '1.0.0', }, null, 2), }, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), authorization: token, }) - registry.nock.put(`/${spec.escapedName}`, body => { - t.equal(body.access, 'public', 'access is explicitly set to public') - return true - }).reply(200, {}) + registry.publish('@npm/test-package', { access: 'public' }) await npm.exec('publish', []) t.matchSnapshot(joinedOutput(), 'new package version') t.matchSnapshot(logs.notice) @@ -909,9 +854,10 @@ t.test('manifest', async t => { t.cleanSnapshot = (s) => s.replace(new RegExp(npmPkg.version, 'g'), '{VERSION}') let manifest = null - const { npm } = await loadMockNpm(t, { + const { npm, registry } = await loadNpmWithRegistry(t, { config: { ...auth, + tag: 'latest', 'foreground-scripts': false, }, chdir: () => root, @@ -921,6 +867,9 @@ t.test('manifest', async t => { }, }, }) + + registry.publish('npm', { noPut: true }) + await npm.exec('publish', []) const okKeys = [ @@ -942,7 +891,827 @@ t.test('manifest', async t => { } delete manifest.gitHead - manifest.man.sort() + manifest.man?.sort() t.matchSnapshot(manifest, 'manifest') }) + +t.test('prerelease dist tag', (t) => { + t.test('aborts when prerelease and no tag', async t => { + const { npm } = await loadNpmWithRegistry(t, { + config: { + loglevel: 'silent', + [`${alternateRegistry.slice(6)}/:_authToken`]: 'test-other-token', + }, + prefixDir: { + 'package.json': JSON.stringify({ + ...pkgJson, + version: '1.0.0-0', + publishConfig: { registry: alternateRegistry }, + }, null, 2), + }, + }) + await t.rejects(async () => { + await npm.exec('publish', []) + }, new Error('You must specify a tag using --tag when publishing a prerelease version')) + }) + + t.test('does not abort when prerelease and authored tag latest', async t => { + const packageJson = { + ...pkgJson, + version: '1.0.0-0', + publishConfig: { registry: alternateRegistry }, + } + const { npm, registry } = await loadNpmWithRegistry(t, { + config: { + loglevel: 'silent', + tag: 'latest', + [`${alternateRegistry.slice(6)}/:_authToken`]: 'test-other-token', + }, + prefixDir: { + 'package.json': JSON.stringify(packageJson, null, 2), + }, + registry: alternateRegistry, + authorization: 'test-other-token', + }) + registry.publish(pkg, { packageJson }) + await npm.exec('publish', []) + }) + + t.test('does not abort when prerelease and force', async t => { + const packageJson = { + ...pkgJson, + version: '1.0.0-0', + publishConfig: { registry: alternateRegistry }, + } + const { npm, registry } = await loadNpmWithRegistry(t, { + config: { + loglevel: 'silent', + force: true, + [`${alternateRegistry.slice(6)}/:_authToken`]: 'test-other-token', + }, + prefixDir: { + 'package.json': JSON.stringify(packageJson, null, 2), + }, + registry: alternateRegistry, + authorization: 'test-other-token', + }) + registry.publish(pkg, { noGet: true, packageJson }) + await npm.exec('publish', []) + }) + + t.end() +}) + +t.test('semver highest dist tag', async t => { + const init = ({ version, pkgExtra = {} }) => ({ + config: { + loglevel: 'silent', + ...auth, + }, + prefixDir: { + 'package.json': JSON.stringify({ + ...pkgJson, + ...pkgExtra, + version, + }, null, 2), + }, + authorization: token, + }) + + const packuments = [ + // this needs more than one item in it to cover the sort logic + { version: '50.0.0' }, + { version: '100.0.0' }, + { version: '102.0.0', deprecated: 'oops' }, + { version: '105.0.0-pre' }, + ] + + await t.test('PREVENTS publish when highest version is HIGHER than publishing version', async t => { + const version = '99.0.0' + const { npm, registry } = await loadNpmWithRegistry(t, init({ version })) + registry.publish(pkg, { noPut: true, packuments }) + await t.rejects(async () => { + await npm.exec('publish', []) + }, new Error('Cannot implicitly apply the "latest" tag because previously published version 100.0.0 is higher than the new version 99.0.0. You must specify a tag using --tag.')) + }) + + await t.test('ALLOWS publish when highest is HIGHER than publishing version and flag', async t => { + const version = '99.0.0' + const { npm, registry } = await loadNpmWithRegistry(t, { + ...init({ version }), + argv: ['--tag', 'latest'], + }) + registry.publish(pkg, { packuments }) + await npm.exec('publish', []) + }) + + await t.test('ALLOWS publish when highest versions are LOWER than publishing version', async t => { + const version = '101.0.0' + const { npm, registry } = await loadNpmWithRegistry(t, init({ version })) + registry.publish(pkg, { packuments }) + await npm.exec('publish', []) + }) + + await t.test('ALLOWS publish when packument has empty versions (for coverage)', async t => { + const version = '1.0.0' + const { npm, registry } = await loadNpmWithRegistry(t, init({ version })) + registry.publish(pkg, { manifest: { versions: { } } }) + await npm.exec('publish', []) + }) + + await t.test('ALLOWS publish when packument has empty manifest (for coverage)', async t => { + const version = '1.0.0' + const { npm, registry } = await loadNpmWithRegistry(t, init({ version })) + registry.publish(pkg, { manifest: {} }) + await npm.exec('publish', []) + }) + + await t.test('ALLOWS publish when highest version is HIGHER than publishing version with publishConfig', async t => { + const version = '99.0.0' + const { npm, registry } = await loadNpmWithRegistry(t, init({ + version, + pkgExtra: { + publishConfig: { + tag: 'next', + }, + }, + })) + registry.publish(pkg, { packuments }) + await npm.exec('publish', []) + }) + + await t.test('PREVENTS publish when latest version is SAME AS publishing version', async t => { + const version = '100.0.0' + const { npm, registry } = await loadNpmWithRegistry(t, init({ version })) + registry.publish(pkg, { noPut: true, packuments }) + await t.rejects(async () => { + await npm.exec('publish', []) + }, new Error('You cannot publish over the previously published versions: 100.0.0.')) + }) + + await t.test('PREVENTS publish when publishing version EXISTS ALREADY in the registry', async t => { + const version = '50.0.0' + const { npm, registry } = await loadNpmWithRegistry(t, init({ version })) + registry.publish(pkg, { noPut: true, packuments }) + await t.rejects(async () => { + await npm.exec('publish', []) + }, new Error('You cannot publish over the previously published versions: 50.0.0.')) + }) + + await t.test('ALLOWS publish when latest is HIGHER than publishing version and flag --force', async t => { + const version = '99.0.0' + const { npm, registry } = await loadNpmWithRegistry(t, { + ...init({ version }), + argv: ['--force'], + }) + registry.publish(pkg, { noGet: true, packuments }) + await npm.exec('publish', []) + }) +}) + +t.test('oidc token exchange - no provenance', t => { + const githubPrivateIdToken = githubIdToken({ visibility: 'private' }) + const gitlabPrivateIdToken = gitlabIdToken({ visibility: 'private' }) + + t.test('oidc token 500 with fallback', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + statusCode: 500, + }, + publishOptions: { + token: 'existing-fallback-token', + }, + logsContain: [ + 'verbose oidc Failed to fetch id_token from GitHub: received an invalid response', + ], + })) + + t.test('oidc token invalid body with fallback', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: null, + }, + publishOptions: { + token: 'existing-fallback-token', + }, + logsContain: [ + 'verbose oidc Failed to fetch id_token from GitHub: missing value', + ], + })) + + t.test('token exchange 500 with fallback', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: githubPrivateIdToken, + }, + mockOidcTokenExchangeOptions: { + statusCode: 500, + idToken: githubPrivateIdToken, + body: { + message: 'oidc token exchange failed', + }, + }, + publishOptions: { + token: 'existing-fallback-token', + }, + logsContain: [ + 'verbose oidc Failed token exchange request with body message: oidc token exchange failed', + ], + })) + + t.test('token exchange 500 with no body message with fallback', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: githubPrivateIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPrivateIdToken, + statusCode: 500, + body: undefined, + }, + publishOptions: { + token: 'existing-fallback-token', + }, + logsContain: [ + 'verbose oidc Failed token exchange request with body message: Unknown error', + ], + })) + + t.test('token exchange invalid body with fallback', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: githubPrivateIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPrivateIdToken, + body: { + token: null, + }, + }, + publishOptions: { + token: 'existing-fallback-token', + }, + logsContain: [ + 'verbose oidc Failed because token exchange was missing the token in the response body', + ], + })) + + t.test('github missing ACTIONS_ID_TOKEN_REQUEST_URL', oidcPublishTest({ + oidcOptions: { github: true, ACTIONS_ID_TOKEN_REQUEST_URL: '' }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + publishOptions: { + token: 'existing-fallback-token', + }, + logsContain: [ + 'silly oidc Skipped because incorrect permissions for id-token within GitHub workflow', + ], + })) + + t.test('gitlab missing NPM_ID_TOKEN', oidcPublishTest({ + oidcOptions: { gitlab: true, NPM_ID_TOKEN: '' }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + publishOptions: { + token: 'existing-fallback-token', + }, + logsContain: [ + 'silly oidc Skipped because no id_token available', + ], + })) + + t.test('no ci', oidcPublishTest({ + oidcOptions: { github: false, gitlab: false }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + publishOptions: { + token: 'existing-fallback-token', + }, + })) + + // default registry success + + t.test('default registry success github', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: githubPrivateIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPrivateIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + })) + + t.test('global try-catch failure via malformed url', oidcPublishTest({ + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + oidcOptions: { + github: true, + // malformed url should trigger a global try-catch + ACTIONS_ID_TOKEN_REQUEST_URL: '//github.com', + }, + publishOptions: { + token: 'existing-fallback-token', + }, + logsContain: [ + 'verbose oidc Failure with message: Invalid URL', + ], + })) + + t.test('global try-catch failure via throw non Error', async t => { + const { npm, logs, joinedOutput, ACTIONS_ID_TOKEN_REQUEST_URL } = await mockOidc(t, { + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + oidcOptions: { + github: true, + }, + publishOptions: { + token: 'existing-fallback-token', + }, + }) + + class URLOverride extends URL { + constructor (...args) { + const [url] = args + if (url === ACTIONS_ID_TOKEN_REQUEST_URL) { + throw 'Specifically throwing a non error object to test global try-catch' + } + super(...args) + } + } + + mockGlobals(t, { + URL: URLOverride, + }) + + await npm.exec('publish', []) + t.match(joinedOutput(), '+ @npmcli/test-package@1.0.0') + t.ok(logs.includes('verbose oidc Failure with message: Unknown error')) + }) + + t.test('default registry success gitlab', oidcPublishTest({ + oidcOptions: { gitlab: true, NPM_ID_TOKEN: gitlabPrivateIdToken }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockOidcTokenExchangeOptions: { + idToken: gitlabPrivateIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + })) + + t.test('circleci missing NPM_ID_TOKEN', oidcPublishTest({ + oidcOptions: { circleci: true, NPM_ID_TOKEN: '' }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + publishOptions: { + token: 'existing-fallback-token', + }, + logsContain: [ + 'silly oidc Skipped because no id_token available', + ], + })) + + t.test('default registry success circleci', oidcPublishTest({ + oidcOptions: { circleci: true, NPM_ID_TOKEN: circleciIdToken() }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockOidcTokenExchangeOptions: { + idToken: circleciIdToken(), + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + })) + + // custom registry success + + t.test('custom registry config success github', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + registry: 'https://registry.zzz.org', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.zzz.org', + idToken: githubPrivateIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPrivateIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + })) + + t.test('custom registry scoped config success github', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '@npmcli:registry': 'https://registry.zzz.org', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.zzz.org', + idToken: githubPrivateIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPrivateIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + load: { + registry: 'https://registry.zzz.org', + }, + })) + + t.test('custom registry publishConfig success github', oidcPublishTest({ + oidcOptions: { github: true }, + packageJson: { + publishConfig: { + registry: 'https://registry.zzz.org', + }, + }, + mockGithubOidcOptions: { + audience: 'npm:registry.zzz.org', + idToken: githubPrivateIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPrivateIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + load: { + registry: 'https://registry.zzz.org', + }, + })) + + t.test('dry-run can be used to check oidc config but not publish', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + 'dry-run': true, + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: githubPrivateIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPrivateIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + noPut: true, + }, + })) + + t.end() +}) + +t.test('oidc token exchange - provenance', (t) => { + const githubPrivateIdToken = githubIdToken({ visibility: 'private' }) + const githubPublicIdToken = githubIdToken({ visibility: 'public' }) + const gitlabPublicIdToken = gitlabIdToken({ visibility: 'public' }) + const SIGSTORE_ID_TOKEN = sigstoreIdToken() + + t.test('default registry success github', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: githubPublicIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPublicIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + provenance: true, + oidcVisibilityOptions: { public: true }, + })) + + t.test('default registry success gitlab', oidcPublishTest({ + oidcOptions: { gitlab: true, NPM_ID_TOKEN: gitlabPublicIdToken, SIGSTORE_ID_TOKEN }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockOidcTokenExchangeOptions: { + idToken: gitlabPublicIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + provenance: true, + oidcVisibilityOptions: { public: true }, + })) + + t.test('default registry success gitlab without SIGSTORE_ID_TOKEN', oidcPublishTest({ + oidcOptions: { gitlab: true, NPM_ID_TOKEN: gitlabPublicIdToken }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockOidcTokenExchangeOptions: { + idToken: gitlabPublicIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + provenance: false, + })) + + /** + * when the user sets provenance to true or false + * the OIDC flow should not concern itself with provenance at all + */ + t.test('setting provenance true in config should enable provenance', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + provenance: true, + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: githubPublicIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPublicIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + provenance: true, + })) + + t.test('setting provenance false in config should not use provenance', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + provenance: false, + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: githubPublicIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPublicIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + })) + + const brokenJwts = [ + 'x.invalid-jwt.x', + 'x.invalid-jwt.', + 'x.invalid-jwt', + 'x.', + 'x', + ] + + brokenJwts.map((brokenJwt) => { + // windows does not like `.` in the filename + t.test(`broken jwt ${brokenJwt.replaceAll('.', '_')}`, oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: brokenJwt, + }, + mockOidcTokenExchangeOptions: { + idToken: brokenJwt, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + })) + }) + + t.test('token exchange 500 with fallback should not have provenance by default', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: githubPublicIdToken, + }, + mockOidcTokenExchangeOptions: { + statusCode: 500, + idToken: githubPublicIdToken, + body: { + message: 'oidc token exchange failed', + }, + }, + publishOptions: { + token: 'existing-fallback-token', + }, + logsContain: [ + 'verbose oidc Failed token exchange request with body message: oidc token exchange failed', + ], + provenance: false, + })) + + t.test('attempt to publish a private package with OIDC provenance should be false', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: githubPublicIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPublicIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + provenance: false, + oidcVisibilityOptions: { public: false }, + })) + + /** this call shows that if the repo is private, the visibility check will not be called */ + t.test('attempt to publish a private repository with OIDC provenance should be false', oidcPublishTest({ + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: githubPrivateIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPrivateIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + provenance: false, + })) + + const provenanceFailures = [[ + new Error('Valid error'), + 'verbose oidc Failed to set provenance with message: Valid error', + ], [ + 'Valid error', + 'verbose oidc Failed to set provenance with message: Unknown error', + ]] + + provenanceFailures.forEach(([error, logMessage], index) => { + t.test(`provenance visibility check failure, coverage for try-catch ${index}`, async t => { + const { npm, logs, joinedOutput } = await mockOidc(t, { + load: { + mocks: { + libnpmaccess: { + getVisibility: () => { + throw error + }, + }, + }, + }, + oidcOptions: { github: true }, + config: { + '//registry.npmjs.org/:_authToken': 'existing-fallback-token', + }, + mockGithubOidcOptions: { + audience: 'npm:registry.npmjs.org', + idToken: githubPublicIdToken, + }, + mockOidcTokenExchangeOptions: { + idToken: githubPublicIdToken, + body: { + token: 'exchange-token', + }, + }, + publishOptions: { + token: 'exchange-token', + }, + provenance: false, + }) + + await npm.exec('publish', []) + t.match(joinedOutput(), '+ @npmcli/test-package@1.0.0') + t.ok(logs.includes(logMessage)) + }) + }) + + t.end() +}) + +t.test('passes script-shell config to lifecycle hooks', async t => { + const CAPTURED = [] + const { npm, registry } = await loadNpmWithRegistry(t, { + config: { + ...auth, + 'script-shell': '/bin/bash', + }, + prefixDir: { + 'package.json': JSON.stringify({ + ...pkgJson, + scripts: { + prepublishOnly: 'exit 0', + publish: 'exit 0', + postpublish: 'exit 0', + }, + }), + }, + mocks: { + '@npmcli/run-script': async (opts) => { + CAPTURED.push(opts) + }, + }, + }) + + registry.publish(pkg, {}) + await npm.exec('publish', []) + + for (const event of ['prepublishOnly', 'publish', 'postpublish']) { + const rs = CAPTURED.find(r => r.event === event) + t.ok(rs, `ran ${event}`) + t.equal(rs?.scriptShell, '/bin/bash', `${event} receives scriptShell`) + } +}) diff --git a/test/lib/commands/query.js b/test/lib/commands/query.js index 0907a9d0f4206..40dadc8885836 100644 --- a/test/lib/commands/query.js +++ b/test/lib/commands/query.js @@ -236,6 +236,98 @@ t.test('package-lock-only', t => { await npm.exec('query', ['*']) t.matchSnapshot(joinedOutput(), 'should return valid response with only lock info') }) + + t.test('with package lock and workspace', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { + 'package-lock-only': true, + workspace: ['a'], + }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root', + workspaces: ['packages/*'], + }), + 'package-lock.json': JSON.stringify({ + name: 'root', + lockfileVersion: 3, + requires: true, + packages: { + '': { + name: 'root', + workspaces: ['packages/*'], + }, + 'node_modules/a': { + resolved: 'packages/a', + link: true, + }, + 'packages/a': { + name: 'a', + version: '1.0.0', + }, + }, + }), + packages: { + a: { + 'package.json': JSON.stringify({ + name: 'a', + version: '1.0.0', + }), + }, + }, + }, + }) + await npm.exec('query', ['*']) + t.matchSnapshot(joinedOutput(), 'should return workspace object with package-lock-only') + }) + + t.test('no package lock and workspace', async t => { + const { npm } = await loadMockNpm(t, { + config: { + 'package-lock-only': true, + workspace: ['a'], + }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root', + workspaces: ['packages/*'], + }), + packages: { + a: { + 'package.json': JSON.stringify({ + name: 'a', + version: '1.0.0', + }), + }, + }, + }, + }) + await t.rejects(npm.exec('query', ['*']), { code: 'EUSAGE' }) + }) + + t.test('missing workspace in tree', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { + workspace: ['a'], + }, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root', + workspaces: ['packages/*'], + }), + packages: { + a: { + 'package.json': JSON.stringify({ + name: 'a', + version: '1.0.0', + }), + }, + }, + }, + }) + await npm.exec('query', ['*']) + t.matchSnapshot(joinedOutput(), 'should return empty array for missing workspace') + }) t.end() }) diff --git a/test/lib/commands/rebuild.js b/test/lib/commands/rebuild.js index aa5578460b90f..cfd2d2511e193 100644 --- a/test/lib/commands/rebuild.js +++ b/test/lib/commands/rebuild.js @@ -205,3 +205,198 @@ t.test('global prefix', async t => { 'should output success msg' ) }) + +t.test('completion', async t => { + const { rebuild } = await setupMockNpm(t, { + command: 'rebuild', + prefixDir: { + node_modules: { + foo: { + 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }), + }, + }, + 'package.json': JSON.stringify({ name: 'project', version: '1.0.0' }), + }, + }) + const res = await rebuild.completion({ conf: { argv: { remain: ['npm', 'rebuild'] } } }) + t.type(res, Array) +}) + +t.test('emits blocked warning for unreviewed install scripts', async t => { + const { npm, logs } = await setupMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'host', version: '1.0.0' }), + node_modules: { + canvas: { + 'package.json': JSON.stringify({ + name: 'canvas', + version: '1.0.0', + scripts: { install: 'echo install' }, + }), + }, + }, + }, + }) + await npm.exec('rebuild', []) + t.match( + logs.warn.byTitle('rebuild'), + [/install scripts blocked because they are not covered by allowScripts/] + ) +}) + +t.test('global advisory warning points at npm config set, not approve-scripts', async t => { + const { npm, logs } = await setupMockNpm(t, { + config: { + global: true, + }, + globalPrefixDir: { + node_modules: { + canvas: { + 'index.js': '', + 'package.json': JSON.stringify({ + name: 'canvas', + version: '1.0.0', + scripts: { install: 'echo install' }, + }), + }, + }, + }, + }) + await npm.exec('rebuild', []) + const warn = logs.warn.byTitle('rebuild').join('\n') + t.match(warn, /install scripts blocked because they are not covered by allowScripts/) + t.match(warn, /npm config set allow-scripts=canvas/) + t.notMatch(warn, /approve-scripts/) +}) + +t.test('no advisory warning when allowScripts covers the package', async t => { + const { npm, logs } = await setupMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + dependencies: { canvas: '1.0.0' }, + allowScripts: { canvas: true }, + }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'host', version: '1.0.0', dependencies: { canvas: '1.0.0' } }, + 'node_modules/canvas': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/canvas/-/canvas-1.0.0.tgz', + hasInstallScript: true, + }, + }, + }), + node_modules: { + canvas: { + 'package.json': JSON.stringify({ + name: 'canvas', + version: '1.0.0', + scripts: { install: 'echo install' }, + }), + }, + }, + }, + }) + await npm.exec('rebuild', []) + t.strictSame(logs.warn.byTitle('rebuild'), []) +}) + +t.test('rebuild honors the gate for an unreviewed package', async t => { + const { npm, logs, prefix: path } = await setupMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + dependencies: { canvas: '1.0.0' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'host', version: '1.0.0', dependencies: { canvas: '1.0.0' } }, + 'node_modules/canvas': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/canvas/-/canvas-1.0.0.tgz', + hasInstallScript: true, + }, + }, + }), + node_modules: { + canvas: { + 'package.json': JSON.stringify({ + name: 'canvas', + version: '1.0.0', + scripts: { + install: "node -e \"require('fs').writeFileSync('ran', '')\"", + }, + }), + }, + }, + }, + }) + + const ranFile = resolve(path, 'node_modules/canvas/ran') + t.throws(() => fs.statSync(ranFile)) + + await npm.exec('rebuild', ['canvas']) + + t.throws(() => fs.statSync(ranFile), 'unreviewed install script must not run') + t.match( + logs.warn.byTitle('rebuild'), + [/install scripts blocked because they are not covered by allowScripts/] + ) +}) + +t.test('rebuild never targets a bundled dependency', async t => { + const { npm, prefix: path } = await setupMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + dependencies: { parent: '1.0.0' }, + }), + node_modules: { + parent: { + 'index.js': '', + 'package.json': JSON.stringify({ + name: 'parent', + version: '1.0.0', + bundleDependencies: ['bcrypt'], + dependencies: { bcrypt: '1.0.0' }, + }), + node_modules: { + bcrypt: { + 'index.js': '', + 'package.json': JSON.stringify({ + name: 'bcrypt', + version: '1.0.0', + bin: 'index.js', + scripts: { + install: "node -e \"require('fs').writeFileSync('ran', '')\"", + }, + }), + }, + }, + }, + }, + }, + }) + + const ranFile = resolve(path, 'node_modules/parent/node_modules/bcrypt/ran') + t.throws(() => fs.statSync(ranFile)) + + await npm.exec('rebuild', ['bcrypt']) + + t.throws( + () => fs.statSync(ranFile), + 'bundled bcrypt install script must not run' + ) +}) diff --git a/test/lib/commands/run-script.js b/test/lib/commands/run-script.js deleted file mode 100644 index 6906a7de67d0b..0000000000000 --- a/test/lib/commands/run-script.js +++ /dev/null @@ -1,723 +0,0 @@ -const t = require('tap') -const { resolve } = require('node:path') -const realRunScript = require('@npmcli/run-script') -const mockNpm = require('../../fixtures/mock-npm') -const { cleanCwd } = require('../../fixtures/clean-snapshot') - -const mockRs = async (t, { windows = false, runScript, ...opts } = {}) => { - let RUN_SCRIPTS = [] - - t.afterEach(() => RUN_SCRIPTS = []) - - const mock = await mockNpm(t, { - ...opts, - command: 'run-script', - mocks: { - '@npmcli/run-script': Object.assign( - async rs => { - if (runScript) { - await runScript(rs) - } - RUN_SCRIPTS.push(rs) - }, - realRunScript - ), - '{LIB}/utils/is-windows.js': { isWindowsShell: windows }, - }, - }) - - return { - ...mock, - RUN_SCRIPTS: () => RUN_SCRIPTS, - runScript: mock['run-script'], - cleanLogs: () => mock.logs.error.map(cleanCwd).join('\n'), - } -} - -t.test('completion', async t => { - const completion = async (t, remain, pkg, isFish = false) => { - const { runScript } = await mockRs(t, - pkg ? { prefixDir: { 'package.json': JSON.stringify(pkg) } } : {} - ) - return runScript.completion({ conf: { argv: { remain } }, isFish }) - } - - t.test('already have a script name', async t => { - const res = await completion(t, ['npm', 'run', 'x']) - t.equal(res, undefined) - }) - t.test('no package.json', async t => { - const res = await completion(t, ['npm', 'run']) - t.strictSame(res, []) - }) - t.test('has package.json, no scripts', async t => { - const res = await completion(t, ['npm', 'run'], {}) - t.strictSame(res, []) - }) - t.test('has package.json, with scripts', async t => { - const res = await completion(t, ['npm', 'run'], { - scripts: { hello: 'echo hello', world: 'echo world' }, - }) - t.strictSame(res, ['hello', 'world']) - }) - - t.test('fish shell', async t => { - const res = await completion(t, ['npm', 'run'], { - scripts: { hello: 'echo hello', world: 'echo world' }, - }, true) - t.strictSame(res, ['hello\techo hello', 'world\techo world']) - }) -}) - -t.test('fail if no package.json', async t => { - const { runScript } = await mockRs(t) - await t.rejects(runScript.exec([]), { code: 'ENOENT' }) - await t.rejects(runScript.exec(['test']), { code: 'ENOENT' }) -}) - -t.test('default env, start, and restart scripts', async t => { - const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { - prefixDir: { - 'package.json': JSON.stringify({ name: 'x', version: '1.2.3' }), - 'server.js': 'console.log("hello, world")', - }, - }) - - t.test('start', async t => { - await runScript.exec(['start']) - t.match(RUN_SCRIPTS(), [ - { - path: npm.localPrefix, - args: [], - scriptShell: undefined, - stdio: 'inherit', - pkg: { name: 'x', version: '1.2.3', _id: 'x@1.2.3', scripts: {} }, - event: 'start', - }, - ]) - }) - - t.test('env', async t => { - await runScript.exec(['env']) - t.match(RUN_SCRIPTS(), [ - { - path: npm.localPrefix, - args: [], - scriptShell: undefined, - stdio: 'inherit', - pkg: { - name: 'x', - version: '1.2.3', - _id: 'x@1.2.3', - scripts: { - env: 'env', - }, - }, - event: 'env', - }, - ]) - }) - - t.test('restart', async t => { - await runScript.exec(['restart']) - - t.match(RUN_SCRIPTS(), [ - { - path: npm.localPrefix, - args: [], - scriptShell: undefined, - stdio: 'inherit', - pkg: { - name: 'x', - version: '1.2.3', - _id: 'x@1.2.3', - scripts: { - restart: 'npm stop --if-present && npm start', - }, - }, - event: 'restart', - }, - ]) - }) -}) - -t.test('default windows env', async t => { - const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { - windows: true, - prefixDir: { - 'package.json': JSON.stringify({ name: 'x', version: '1.2.3' }), - 'server.js': 'console.log("hello, world")', - }, - }) - await runScript.exec(['env']) - t.match(RUN_SCRIPTS(), [ - { - path: npm.localPrefix, - args: [], - scriptShell: undefined, - stdio: 'inherit', - pkg: { - name: 'x', - version: '1.2.3', - _id: 'x@1.2.3', - scripts: { - env: 'SET', - }, - }, - event: 'env', - }, - ]) -}) - -t.test('non-default env script', async t => { - const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'x', - version: '1.2.3', - scripts: { - env: 'hello', - }, - }), - }, - }) - - t.test('env', async t => { - await runScript.exec(['env']) - t.match(RUN_SCRIPTS(), [ - { - path: npm.localPrefix, - args: [], - scriptShell: undefined, - stdio: 'inherit', - pkg: { - name: 'x', - version: '1.2.3', - _id: 'x@1.2.3', - scripts: { - env: 'hello', - }, - }, - event: 'env', - }, - ]) - }) -}) - -t.test('non-default env script windows', async t => { - const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { - windows: true, - prefixDir: { - 'package.json': JSON.stringify({ - name: 'x', - version: '1.2.3', - scripts: { - env: 'hello', - }, - }), - }, - }) - - await runScript.exec(['env']) - - t.match(RUN_SCRIPTS(), [ - { - path: npm.localPrefix, - args: [], - scriptShell: undefined, - stdio: 'inherit', - pkg: { - name: 'x', - version: '1.2.3', - _id: 'x@1.2.3', - scripts: { - env: 'hello', - }, - }, - event: 'env', - }, - ]) -}) - -t.test('try to run missing script', async t => { - t.test('errors', async t => { - const { runScript } = await mockRs(t, { - prefixDir: { - 'package.json': JSON.stringify({ - scripts: { hello: 'world' }, - bin: { goodnight: 'moon' }, - }), - }, - }) - t.test('no suggestions', async t => { - await t.rejects(runScript.exec(['notevenclose']), 'Missing script: "notevenclose"') - }) - t.test('script suggestions', async t => { - await t.rejects(runScript.exec(['helo']), /Missing script: "helo"/) - await t.rejects(runScript.exec(['helo']), /npm run hello/) - }) - t.test('bin suggestions', async t => { - await t.rejects(runScript.exec(['goodneght']), /Missing script: "goodneght"/) - await t.rejects(runScript.exec(['goodneght']), /npm exec goodnight/) - }) - }) - - t.test('with --if-present', async t => { - const { runScript, RUN_SCRIPTS } = await mockRs(t, { - config: { 'if-present': true }, - prefixDir: { - 'package.json': JSON.stringify({ - scripts: { hello: 'world' }, - bin: { goodnight: 'moon' }, - }), - }, - }) - await runScript.exec(['goodbye']) - t.strictSame(RUN_SCRIPTS(), [], 'did not try to run anything') - }) -}) - -t.test('run pre/post hooks', async t => { - const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'x', - version: '1.2.3', - scripts: { - preenv: 'echo before the env', - postenv: 'echo after the env', - }, - }), - }, - }) - - await runScript.exec(['env']) - - t.match(RUN_SCRIPTS(), [ - { event: 'preenv' }, - { - path: npm.localPrefix, - args: [], - scriptShell: undefined, - stdio: 'inherit', - pkg: { - name: 'x', - version: '1.2.3', - _id: 'x@1.2.3', - scripts: { - env: 'env', - }, - }, - event: 'env', - }, - { event: 'postenv' }, - ]) -}) - -t.test('skip pre/post hooks when using ignoreScripts', async t => { - const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'x', - version: '1.2.3', - scripts: { - preenv: 'echo before the env', - postenv: 'echo after the env', - }, - }), - }, - config: { 'ignore-scripts': true }, - }) - - await runScript.exec(['env']) - - t.same(RUN_SCRIPTS(), [ - { - path: npm.localPrefix, - args: [], - scriptShell: undefined, - stdio: 'inherit', - pkg: { - name: 'x', - version: '1.2.3', - _id: 'x@1.2.3', - scripts: { - preenv: 'echo before the env', - postenv: 'echo after the env', - env: 'env', - }, - }, - event: 'env', - }, - ]) -}) - -t.test('run silent', async t => { - const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'x', - version: '1.2.3', - scripts: { - preenv: 'echo before the env', - postenv: 'echo after the env', - }, - }), - }, - config: { silent: true }, - }) - - await runScript.exec(['env']) - t.match(RUN_SCRIPTS(), [ - { - event: 'preenv', - stdio: 'inherit', - }, - { - path: npm.localPrefix, - args: [], - scriptShell: undefined, - stdio: 'inherit', - pkg: { - name: 'x', - version: '1.2.3', - _id: 'x@1.2.3', - scripts: { - env: 'env', - }, - }, - event: 'env', - }, - { - event: 'postenv', - stdio: 'inherit', - }, - ]) -}) - -t.test('list scripts', async t => { - const scripts = { - test: 'exit 2', - start: 'node server.js', - stop: 'node kill-server.js', - preenv: 'echo before the env', - postenv: 'echo after the env', - } - - const mockList = async (t, config = {}) => { - const mock = await mockRs(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'x', - version: '1.2.3', - scripts, - }), - }, - config, - }) - - await mock.runScript.exec([]) - - return mock.joinedOutput() - } - - t.test('no args', async t => { - const output = await mockList(t) - t.matchSnapshot(output, 'basic report') - }) - - t.test('silent', async t => { - const output = await mockList(t, { silent: true }) - t.strictSame(output, '') - }) - t.test('warn json', async t => { - const output = await mockList(t, { json: true }) - t.matchSnapshot(output, 'json report') - }) - - t.test('parseable', async t => { - const output = await mockList(t, { parseable: true }) - t.matchSnapshot(output) - }) -}) - -t.test('list scripts when no scripts', async t => { - const { runScript, joinedOutput } = await mockRs(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'x', - version: '1.2.3', - }), - }, - }) - - await runScript.exec([]) - t.strictSame(joinedOutput(), '', 'nothing to report') -}) - -t.test('list scripts, only commands', async t => { - const { runScript, joinedOutput } = await mockRs(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'x', - version: '1.2.3', - scripts: { preversion: 'echo doing the version dance' }, - }), - }, - }) - - await runScript.exec([]) - t.matchSnapshot(joinedOutput()) -}) - -t.test('list scripts, only non-commands', async t => { - const { runScript, joinedOutput } = await mockRs(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'x', - version: '1.2.3', - scripts: { glorp: 'echo doing the glerp glop' }, - }), - }, - }) - - await runScript.exec([]) - t.matchSnapshot(joinedOutput()) -}) - -t.test('workspaces', async t => { - const mockWorkspaces = async (t, { - runScript, - prefixDir, - workspaces = true, - exec = [], - ...config - } = {}) => { - const mock = await mockRs(t, { - prefixDir: prefixDir || { - packages: { - a: { - 'package.json': JSON.stringify({ - name: 'a', - version: '1.0.0', - scripts: { glorp: 'echo a doing the glerp glop' }, - }), - }, - b: { - 'package.json': JSON.stringify({ - name: 'b', - version: '2.0.0', - scripts: { glorp: 'echo b doing the glerp glop' }, - }), - }, - c: { - 'package.json': JSON.stringify({ - name: 'c', - version: '1.0.0', - scripts: { - test: 'exit 0', - posttest: 'echo posttest', - lorem: 'echo c lorem', - }, - }), - }, - d: { - 'package.json': JSON.stringify({ - name: 'd', - version: '1.0.0', - scripts: { - test: 'exit 0', - posttest: 'echo posttest', - }, - }), - }, - e: { - 'package.json': JSON.stringify({ - name: 'e', - scripts: { test: 'exit 0', start: 'echo start something' }, - }), - }, - noscripts: { - 'package.json': JSON.stringify({ - name: 'noscripts', - version: '1.0.0', - }), - }, - }, - 'package.json': JSON.stringify({ - name: 'x', - version: '1.2.3', - workspaces: ['packages/*'], - }), - }, - config: { - ...Array.isArray(workspaces) ? { workspace: workspaces } : { workspaces }, - ...config, - }, - runScript, - }) - if (exec) { - await mock.runScript.exec(exec) - } - return mock - } - - t.test('list all scripts', async t => { - const { joinedOutput } = await mockWorkspaces(t) - t.matchSnapshot(joinedOutput()) - }) - - t.test('list regular scripts, filtered by name', async t => { - const { joinedOutput } = await mockWorkspaces(t, { workspaces: ['a', 'b'] }) - t.matchSnapshot(joinedOutput()) - }) - - t.test('list regular scripts, filtered by path', async t => { - const { joinedOutput } = await mockWorkspaces(t, { workspaces: ['./packages/a'] }) - t.matchSnapshot(joinedOutput()) - }) - - t.test('list regular scripts, filtered by parent folder', async t => { - const { joinedOutput } = await mockWorkspaces(t, { workspaces: ['./packages'] }) - t.matchSnapshot(joinedOutput()) - }) - - t.test('list all scripts with colors', async t => { - const { joinedOutput } = await mockWorkspaces(t, { color: 'always' }) - t.matchSnapshot(joinedOutput()) - }) - - t.test('list all scripts --json', async t => { - const { joinedOutput } = await mockWorkspaces(t, { json: true }) - t.matchSnapshot(joinedOutput()) - }) - - t.test('list all scripts --parseable', async t => { - const { joinedOutput } = await mockWorkspaces(t, { parseable: true }) - t.matchSnapshot(joinedOutput()) - }) - - t.test('list no scripts --loglevel=silent', async t => { - const { joinedOutput } = await mockWorkspaces(t, { silent: true }) - t.strictSame(joinedOutput(), '') - }) - - t.test('run scripts across all workspaces', async t => { - const { npm, RUN_SCRIPTS } = await mockWorkspaces(t, { exec: ['test'] }) - - t.match(RUN_SCRIPTS(), [ - { - path: resolve(npm.localPrefix, 'packages/c'), - pkg: { name: 'c', version: '1.0.0' }, - event: 'test', - }, - { - path: resolve(npm.localPrefix, 'packages/c'), - pkg: { name: 'c', version: '1.0.0' }, - event: 'posttest', - }, - { - path: resolve(npm.localPrefix, 'packages/d'), - pkg: { name: 'd', version: '1.0.0' }, - event: 'test', - }, - { - path: resolve(npm.localPrefix, 'packages/d'), - pkg: { name: 'd', version: '1.0.0' }, - event: 'posttest', - }, - { - path: resolve(npm.localPrefix, 'packages/e'), - pkg: { name: 'e' }, - event: 'test', - }, - ]) - }) - - t.test('missing scripts in all workspaces', async t => { - const { runScript, RUN_SCRIPTS, cleanLogs } = await mockWorkspaces(t, { exec: null }) - - await runScript.exec(['missing-script']) - t.match(RUN_SCRIPTS(), []) - t.matchSnapshot( - cleanLogs(), - 'should log error msgs for each workspace script' - ) - }) - - t.test('missing scripts in some workspaces', async t => { - const { RUN_SCRIPTS, cleanLogs } = await mockWorkspaces(t, { - exec: ['test'], - workspaces: ['a', 'b', 'c', 'd'], - }) - - t.match(RUN_SCRIPTS(), []) - t.matchSnapshot( - cleanLogs(), - 'should log error msgs for each workspace script' - ) - }) - - t.test('no workspaces when filtering by user args', async t => { - await t.rejects( - mockWorkspaces(t, { workspaces: ['foo', 'bar'] }), - 'No workspaces found:\n --workspace=foo --workspace=bar', - 'should throw error msg' - ) - }) - - t.test('no workspaces', async t => { - await t.rejects( - mockWorkspaces(t, { - prefixDir: { - 'package.json': JSON.stringify({ - name: 'foo', - version: '1.0.0', - }), - }, - }), - /No workspaces found!/, - 'should throw error msg' - ) - }) - - t.test('single failed workspace run', async t => { - const { cleanLogs } = await mockWorkspaces(t, { - runScript: () => { - throw new Error('err') - }, - exec: ['test'], - workspaces: ['c'], - }) - - t.matchSnapshot( - cleanLogs(), - 'should log error msgs for each workspace script' - ) - }) - - t.test('failed workspace run with succeeded runs', async t => { - const { cleanLogs, RUN_SCRIPTS, prefix } = await mockWorkspaces(t, { - runScript: (opts) => { - if (opts.pkg.name === 'a') { - throw new Error('ERR') - } - }, - exec: ['glorp'], - workspaces: ['a', 'b'], - }) - - t.matchSnapshot( - cleanLogs(), - 'should log error msgs for each workspace script' - ) - - t.match(RUN_SCRIPTS(), [ - { - path: resolve(prefix, 'packages/b'), - pkg: { name: 'b', version: '2.0.0' }, - event: 'glorp', - }, - ]) - }) -}) diff --git a/test/lib/commands/run.js b/test/lib/commands/run.js new file mode 100644 index 0000000000000..aeb93ae7dbd5a --- /dev/null +++ b/test/lib/commands/run.js @@ -0,0 +1,757 @@ +const t = require('tap') +const { resolve } = require('node:path') +const realRunScript = require('@npmcli/run-script') +const mockNpm = require('../../fixtures/mock-npm') +const { cleanCwd } = require('../../fixtures/clean-snapshot') +const path = require('node:path') + +const mockRs = async (t, { windows = false, runScript, ...opts } = {}) => { + let RUN_SCRIPTS = [] + + t.afterEach(() => RUN_SCRIPTS = []) + + const mock = await mockNpm(t, { + ...opts, + command: 'run', + mocks: { + '@npmcli/run-script': Object.assign( + async rs => { + if (runScript) { + await runScript(rs) + } + RUN_SCRIPTS.push(rs) + }, + realRunScript + ), + '{LIB}/utils/is-windows.js': { isWindowsShell: windows }, + }, + }) + + return { + ...mock, + RUN_SCRIPTS: () => RUN_SCRIPTS, + runScript: mock.run, + cleanLogs: () => mock.logs.error.map(cleanCwd).join('\n'), + } +} + +t.test('completion', async t => { + const completion = async (t, remain, pkg, isFish = false) => { + const { runScript } = await mockRs(t, + pkg ? { prefixDir: { 'package.json': JSON.stringify(pkg) } } : {} + ) + return runScript.completion({ conf: { argv: { remain } }, isFish }) + } + + t.test('already have a script name', async t => { + const res = await completion(t, ['npm', 'run', 'x']) + t.equal(res, undefined) + }) + t.test('no package.json', async t => { + const res = await completion(t, ['npm', 'run']) + t.strictSame(res, []) + }) + t.test('has package.json, no scripts', async t => { + const res = await completion(t, ['npm', 'run'], {}) + t.strictSame(res, []) + }) + t.test('has package.json, with scripts', async t => { + const res = await completion(t, ['npm', 'run'], { + scripts: { hello: 'echo hello', world: 'echo world' }, + }) + t.strictSame(res, ['hello', 'world']) + }) + + t.test('fish shell', async t => { + const res = await completion(t, ['npm', 'run'], { + scripts: { hello: 'echo hello', world: 'echo world' }, + }, true) + t.strictSame(res, ['hello\techo hello', 'world\techo world']) + }) +}) + +t.test('fail if no package.json', async t => { + const { runScript } = await mockRs(t) + await t.rejects(runScript.exec([]), { code: 'ENOENT' }) + await t.rejects(runScript.exec(['test']), { code: 'ENOENT' }) +}) + +t.test('default env, start, and restart scripts', async t => { + const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'x', version: '1.2.3' }), + 'server.js': 'console.log("hello, world")', + }, + }) + + t.test('start', async t => { + // run-script@11 removed the implicit `node server.js` behavior, so a + // package with a server.js file but no start script now errors. + await t.rejects( + runScript.exec(['start']), + /Missing script: "start"/ + ) + }) + + t.test('env', async t => { + await runScript.exec(['env']) + t.match(RUN_SCRIPTS(), [ + { + path: npm.localPrefix, + args: [], + scriptShell: undefined, + stdio: 'inherit', + pkg: { + name: 'x', + version: '1.2.3', + _id: 'x@1.2.3', + scripts: { + env: 'env', + }, + }, + event: 'env', + }, + ]) + }) + + t.test('restart', async t => { + await runScript.exec(['restart']) + + t.match(RUN_SCRIPTS(), [ + { + path: npm.localPrefix, + args: [], + scriptShell: undefined, + stdio: 'inherit', + pkg: { + name: 'x', + version: '1.2.3', + _id: 'x@1.2.3', + scripts: { + restart: 'npm stop --if-present && npm start', + }, + }, + event: 'restart', + }, + ]) + }) +}) + +t.test('default windows env', async t => { + const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { + windows: true, + prefixDir: { + 'package.json': JSON.stringify({ name: 'x', version: '1.2.3' }), + 'server.js': 'console.log("hello, world")', + }, + }) + await runScript.exec(['env']) + t.match(RUN_SCRIPTS(), [ + { + path: npm.localPrefix, + args: [], + scriptShell: undefined, + stdio: 'inherit', + pkg: { + name: 'x', + version: '1.2.3', + _id: 'x@1.2.3', + scripts: { + env: 'SET', + }, + }, + event: 'env', + }, + ]) +}) + +t.test('non-default env script', async t => { + const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'x', + version: '1.2.3', + scripts: { + env: 'hello', + }, + }), + }, + }) + + t.test('env', async t => { + await runScript.exec(['env']) + t.match(RUN_SCRIPTS(), [ + { + path: npm.localPrefix, + args: [], + scriptShell: undefined, + stdio: 'inherit', + pkg: { + name: 'x', + version: '1.2.3', + _id: 'x@1.2.3', + scripts: { + env: 'hello', + }, + }, + event: 'env', + }, + ]) + }) +}) + +t.test('non-default env script windows', async t => { + const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { + windows: true, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'x', + version: '1.2.3', + scripts: { + env: 'hello', + }, + }), + }, + }) + + await runScript.exec(['env']) + + t.match(RUN_SCRIPTS(), [ + { + path: npm.localPrefix, + args: [], + scriptShell: undefined, + stdio: 'inherit', + pkg: { + name: 'x', + version: '1.2.3', + _id: 'x@1.2.3', + scripts: { + env: 'hello', + }, + }, + event: 'env', + }, + ]) +}) + +t.test('try to run missing script', async t => { + t.test('errors', async t => { + const { runScript } = await mockRs(t, { + prefixDir: { + 'package.json': JSON.stringify({ + scripts: { hello: 'world' }, + bin: { goodnight: 'moon' }, + }), + }, + }) + t.test('no suggestions', async t => { + await t.rejects(runScript.exec(['notevenclose']), 'Missing script: "notevenclose"') + }) + t.test('script suggestions', async t => { + await t.rejects(runScript.exec(['helo']), /Missing script: "helo"/) + await t.rejects(runScript.exec(['helo']), /npm run hello/) + }) + t.test('bin suggestions', async t => { + await t.rejects(runScript.exec(['goodneght']), /Missing script: "goodneght"/) + await t.rejects(runScript.exec(['goodneght']), /npm exec goodnight/) + }) + }) + + t.test('with --if-present', async t => { + const { runScript, RUN_SCRIPTS } = await mockRs(t, { + config: { 'if-present': true }, + prefixDir: { + 'package.json': JSON.stringify({ + scripts: { hello: 'world' }, + bin: { goodnight: 'moon' }, + }), + }, + }) + await runScript.exec(['goodbye']) + t.strictSame(RUN_SCRIPTS(), [], 'did not try to run anything') + }) +}) + +t.test('run pre/post hooks', async t => { + const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'x', + version: '1.2.3', + scripts: { + preenv: 'echo before the env', + postenv: 'echo after the env', + }, + }), + }, + }) + + await runScript.exec(['env']) + + t.match(RUN_SCRIPTS(), [ + { event: 'preenv' }, + { + path: npm.localPrefix, + args: [], + scriptShell: undefined, + stdio: 'inherit', + pkg: { + name: 'x', + version: '1.2.3', + _id: 'x@1.2.3', + scripts: { + env: 'env', + }, + }, + event: 'env', + }, + { event: 'postenv' }, + ]) +}) + +t.test('skip pre/post hooks when using ignoreScripts', async t => { + const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'x', + version: '1.2.3', + scripts: { + preenv: 'echo before the env', + postenv: 'echo after the env', + }, + }), + }, + config: { 'ignore-scripts': true }, + }) + + await runScript.exec(['env']) + + t.same(RUN_SCRIPTS(), [ + { + path: npm.localPrefix, + args: [], + scriptShell: undefined, + stdio: 'inherit', + pkg: { + name: 'x', + version: '1.2.3', + _id: 'x@1.2.3', + scripts: { + preenv: 'echo before the env', + postenv: 'echo after the env', + env: 'env', + }, + }, + nodeGyp: npm.config.get('node-gyp'), + event: 'env', + }, + ]) +}) + +t.test('run silent', async t => { + const { npm, runScript, RUN_SCRIPTS } = await mockRs(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'x', + version: '1.2.3', + scripts: { + preenv: 'echo before the env', + postenv: 'echo after the env', + }, + }), + }, + config: { silent: true }, + }) + + await runScript.exec(['env']) + t.match(RUN_SCRIPTS(), [ + { + event: 'preenv', + stdio: 'inherit', + }, + { + path: npm.localPrefix, + args: [], + scriptShell: undefined, + stdio: 'inherit', + pkg: { + name: 'x', + version: '1.2.3', + _id: 'x@1.2.3', + scripts: { + env: 'env', + }, + }, + event: 'env', + }, + { + event: 'postenv', + stdio: 'inherit', + }, + ]) +}) + +t.test('list scripts', async t => { + const scripts = { + test: 'exit 2', + start: 'node server.js', + stop: 'node kill-server.js', + preenv: 'echo before the env', + postenv: 'echo after the env', + } + + const mockList = async (t, config = {}) => { + const mock = await mockRs(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'x', + version: '1.2.3', + scripts, + }), + }, + config, + }) + + await mock.runScript.exec([]) + + return mock.joinedOutput() + } + + t.test('no args', async t => { + const output = await mockList(t) + t.matchSnapshot(output, 'basic report') + }) + + t.test('silent', async t => { + const output = await mockList(t, { silent: true }) + t.strictSame(output, '') + }) + t.test('warn json', async t => { + const output = await mockList(t, { json: true }) + t.matchSnapshot(output, 'json report') + }) + + t.test('parseable', async t => { + const output = await mockList(t, { parseable: true }) + t.matchSnapshot(output) + }) +}) + +t.test('list scripts when no scripts', async t => { + const { runScript, joinedOutput } = await mockRs(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'x', + version: '1.2.3', + }), + }, + }) + + await runScript.exec([]) + t.strictSame(joinedOutput(), '', 'nothing to report') +}) + +t.test('list scripts, only commands', async t => { + const { runScript, joinedOutput } = await mockRs(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'x', + version: '1.2.3', + scripts: { preversion: 'echo doing the version dance' }, + }), + }, + }) + + await runScript.exec([]) + t.matchSnapshot(joinedOutput()) +}) + +t.test('list scripts, only non-commands', async t => { + const { runScript, joinedOutput } = await mockRs(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'x', + version: '1.2.3', + scripts: { glorp: 'echo doing the glerp glop' }, + }), + }, + }) + + await runScript.exec([]) + t.matchSnapshot(joinedOutput()) +}) + +t.test('node-gyp config', async t => { + const { runScript, RUN_SCRIPTS, npm } = await mockRs(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'x', + version: '1.2.3', + }), + }, + config: { 'node-gyp': '/test/node-gyp.js' }, + }) + + await runScript.exec(['env']) + t.match(RUN_SCRIPTS(), [ + { + nodeGyp: npm.config.get('node-gyp'), + }, + ]) +}) + +t.test('workspaces', async t => { + const mockWorkspaces = async (t, { + runScript, + prefixDir, + workspaces = true, + exec = [], + chdir = ({ prefix }) => prefix, + ...config + } = {}) => { + const mock = await mockRs(t, { + prefixDir: prefixDir || { + packages: { + a: { + 'package.json': JSON.stringify({ + name: 'a', + version: '1.0.0', + scripts: { glorp: 'echo a doing the glerp glop' }, + }), + }, + b: { + 'package.json': JSON.stringify({ + name: 'b', + version: '2.0.0', + scripts: { glorp: 'echo b doing the glerp glop' }, + }), + }, + c: { + 'package.json': JSON.stringify({ + name: 'c', + version: '1.0.0', + scripts: { + test: 'exit 0', + posttest: 'echo posttest', + lorem: 'echo c lorem', + }, + }), + }, + d: { + 'package.json': JSON.stringify({ + name: 'd', + version: '1.0.0', + scripts: { + test: 'exit 0', + posttest: 'echo posttest', + }, + }), + }, + e: { + 'package.json': JSON.stringify({ + name: 'e', + scripts: { test: 'exit 0', start: 'echo start something' }, + }), + }, + noscripts: { + 'package.json': JSON.stringify({ + name: 'noscripts', + version: '1.0.0', + }), + }, + }, + 'package.json': JSON.stringify({ + name: 'x', + version: '1.2.3', + workspaces: ['packages/*'], + }), + }, + config: { + ...Array.isArray(workspaces) ? { workspace: workspaces } : { workspaces }, + ...config, + }, + chdir, + runScript, + }) + if (exec) { + await mock.runScript.exec(exec) + } + return mock + } + + t.test('completion', async t => { + t.test('in root dir', async t => { + const { runScript } = await mockWorkspaces(t) + const res = await runScript.completion({ conf: { argv: { remain: ['npm', 'run'] } } }) + t.strictSame(res, []) + }) + + t.test('in workspace dir', async t => { + const { runScript } = await mockWorkspaces(t, { + chdir: ({ prefix }) => path.join(prefix, 'packages/c'), + }) + const res = await runScript.completion({ conf: { argv: { remain: ['npm', 'run'] } } }) + t.strictSame(res, ['test', 'posttest', 'lorem']) + }) + }) + + t.test('list all scripts', async t => { + const { joinedOutput } = await mockWorkspaces(t) + t.matchSnapshot(joinedOutput()) + }) + + t.test('list regular scripts, filtered by name', async t => { + const { joinedOutput } = await mockWorkspaces(t, { workspaces: ['a', 'b'] }) + t.matchSnapshot(joinedOutput()) + }) + + t.test('list regular scripts, filtered by path', async t => { + const { joinedOutput } = await mockWorkspaces(t, { workspaces: ['./packages/a'] }) + t.matchSnapshot(joinedOutput()) + }) + + t.test('list regular scripts, filtered by parent folder', async t => { + const { joinedOutput } = await mockWorkspaces(t, { workspaces: ['./packages'] }) + t.matchSnapshot(joinedOutput()) + }) + + t.test('list all scripts with colors', async t => { + const { joinedOutput } = await mockWorkspaces(t, { color: 'always' }) + t.matchSnapshot(joinedOutput()) + }) + + t.test('list all scripts --json', async t => { + const { joinedOutput } = await mockWorkspaces(t, { json: true }) + t.matchSnapshot(joinedOutput()) + }) + + t.test('list all scripts --parseable', async t => { + const { joinedOutput } = await mockWorkspaces(t, { parseable: true }) + t.matchSnapshot(joinedOutput()) + }) + + t.test('list no scripts --loglevel=silent', async t => { + const { joinedOutput } = await mockWorkspaces(t, { silent: true }) + t.strictSame(joinedOutput(), '') + }) + + t.test('run scripts across all workspaces', async t => { + const { npm, RUN_SCRIPTS } = await mockWorkspaces(t, { exec: ['test'] }) + + t.match(RUN_SCRIPTS(), [ + { + path: resolve(npm.localPrefix, 'packages/c'), + pkg: { name: 'c', version: '1.0.0' }, + event: 'test', + }, + { + path: resolve(npm.localPrefix, 'packages/c'), + pkg: { name: 'c', version: '1.0.0' }, + event: 'posttest', + }, + { + path: resolve(npm.localPrefix, 'packages/d'), + pkg: { name: 'd', version: '1.0.0' }, + event: 'test', + }, + { + path: resolve(npm.localPrefix, 'packages/d'), + pkg: { name: 'd', version: '1.0.0' }, + event: 'posttest', + }, + { + path: resolve(npm.localPrefix, 'packages/e'), + pkg: { name: 'e' }, + event: 'test', + }, + ]) + }) + + t.test('missing scripts in all workspaces', async t => { + const { runScript, RUN_SCRIPTS, cleanLogs } = await mockWorkspaces(t, { exec: null }) + + await runScript.exec(['missing-script']) + t.match(RUN_SCRIPTS(), []) + t.matchSnapshot( + cleanLogs(), + 'should log error msgs for each workspace script' + ) + }) + + t.test('missing scripts in some workspaces', async t => { + const { RUN_SCRIPTS, cleanLogs } = await mockWorkspaces(t, { + exec: ['test'], + workspaces: ['a', 'b', 'c', 'd'], + }) + + t.match(RUN_SCRIPTS(), []) + t.matchSnapshot( + cleanLogs(), + 'should log error msgs for each workspace script' + ) + }) + + t.test('no workspaces when filtering by user args', async t => { + await t.rejects( + mockWorkspaces(t, { workspaces: ['foo', 'bar'] }), + 'No workspaces found:\n --workspace=foo --workspace=bar', + 'should throw error msg' + ) + }) + + t.test('no workspaces', async t => { + await t.rejects( + mockWorkspaces(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.0.0', + }), + }, + }), + /No workspaces found!/, + 'should throw error msg' + ) + }) + + t.test('single failed workspace run', async t => { + const { cleanLogs } = await mockWorkspaces(t, { + runScript: () => { + throw new Error('err') + }, + exec: ['test'], + workspaces: ['c'], + }) + + t.matchSnapshot( + cleanLogs(), + 'should log error msgs for each workspace script' + ) + }) + + t.test('failed workspace run with succeeded runs', async t => { + const { cleanLogs, RUN_SCRIPTS, prefix } = await mockWorkspaces(t, { + runScript: (opts) => { + if (opts.pkg.name === 'a') { + throw new Error('ERR') + } + }, + exec: ['glorp'], + workspaces: ['a', 'b'], + }) + + t.matchSnapshot( + cleanLogs(), + 'should log error msgs for each workspace script' + ) + + t.match(RUN_SCRIPTS(), [ + { + path: resolve(prefix, 'packages/b'), + pkg: { name: 'b', version: '2.0.0' }, + event: 'glorp', + }, + ]) + }) +}) diff --git a/test/lib/commands/sbom.js b/test/lib/commands/sbom.js index 25f6135ef8a14..a0cbca0ed4e31 100644 --- a/test/lib/commands/sbom.js +++ b/test/lib/commands/sbom.js @@ -2,7 +2,7 @@ const t = require('tap') const mockNpm = require('../../fixtures/mock-npm.js') const FAKE_TIMESTAMP = '2020-01-01T00:00:00.000Z' -const FAKE_UUID = '00000000-0000-0000-0000-000000000000' +const FAKE_UUID = '12345678-90ab-cdef-1234-567890abcdef' t.cleanSnapshot = s => { let sbom @@ -205,6 +205,97 @@ t.test('sbom', async t => { t.matchSnapshot(result()) }) + const dupDepsNmFixture = { + node_modules: { + foo: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.0.0', + dependencies: { + chai: '^1.0.0', + }, + }), + node_modules: { + chai: { + 'package.json': JSON.stringify({ + name: 'chai', + version: '1.0.0', + }), + }, + }, + }, + bar: { + 'package.json': JSON.stringify({ + name: 'bar', + version: '1.0.0', + dependencies: { + chai: '^1.0.0', + }, + }), + node_modules: { + chai: { + 'package.json': JSON.stringify({ + name: 'chai', + version: '1.0.0', + }), + }, + }, + }, + chai: { + 'package.json': JSON.stringify({ + name: 'chai', + version: '2.0.0', + }), + }, + }, + } + + t.test('duplicate deps - spdx', async t => { + const config = { + 'sbom-format': 'spdx', + } + const { result, sbom } = await mockSbom(t, { + config, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'test-npm-sbom', + version: '1.0.0', + dependencies: { + foo: '^1.0.0', + bar: '^1.0.0', + chai: '^2.0.0', + }, + }), + ...dupDepsNmFixture, + }, + }) + await sbom.exec([]) + t.matchSnapshot(result()) + }) + + t.test('duplicate deps - cyclonedx', async t => { + const config = { + 'sbom-format': 'cyclonedx', + } + const { result, sbom } = await mockSbom(t, { + config, + prefixDir: { + 'package.json': JSON.stringify({ + name: 'test-npm-sbom', + version: '1.0.0', + dependencies: { + foo: '^1.0.0', + bar: '^1.0.0', + chai: '^2.0.0', + }, + }), + ...dupDepsNmFixture, + }, + }) + await sbom.exec([]) + t.matchSnapshot(result()) + }) + t.test('missing format', async t => { const config = {} const { result, sbom } = await mockSbom(t, { @@ -382,7 +473,7 @@ t.test('sbom', async t => { }) await t.rejects(sbom.exec([]), { code: 'EUSAGE', - message: 'A package lock or shrinkwrap file is required in package-lock-only mode', + message: 'A package-lock.json file is required in package-lock-only mode', }, 'should throw error') @@ -490,7 +581,7 @@ t.test('sbom', async t => { workspaces: false, })) - t.test('should filter worksapces with --workspace', t => mockWorkspaces(t, [], { + t.test('should filter workspaces with --workspace', t => mockWorkspaces(t, [], { 'sbom-format': 'spdx', workspace: 'a', })) diff --git a/test/lib/commands/search.js b/test/lib/commands/search.js index de4a58ca78a8f..97adffd8e1432 100644 --- a/test/lib/commands/search.js +++ b/test/lib/commands/search.js @@ -26,6 +26,18 @@ t.test('search', t => { t.matchSnapshot(joinedOutput(), 'should have expected search results') }) + t.test('multiple terms text', async t => { + const { npm, joinedOutput } = await loadMockNpm(t) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + }) + + registry.search({ results: libnpmsearchResultFixture }) + await npm.exec('search', ['libnpm', 'publish']) + t.matchSnapshot(joinedOutput(), 'should have expected search results') + }) + t.test(' --json', async t => { const { npm, joinedOutput } = await loadMockNpm(t, { config: { json: true } }) const registry = new MockRegistry({ @@ -68,6 +80,18 @@ t.test('search', t => { t.matchSnapshot(joinedOutput(), 'should have expected search results with color') }) + t.test('multiple terms --color', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { config: { color: 'always' } }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + }) + + registry.search({ results: libnpmsearchResultFixture }) + await npm.exec('search', ['libnpm', 'publish']) + t.matchSnapshot(joinedOutput(), 'should have expected search results with color') + }) + t.test('//--color', async t => { const { npm, joinedOutput } = await loadMockNpm(t, { config: { color: 'always' } }) const registry = new MockRegistry({ diff --git a/test/lib/commands/set.js b/test/lib/commands/set.js index a4a2a7349ef1a..fbb46571ecd1d 100644 --- a/test/lib/commands/set.js +++ b/test/lib/commands/set.js @@ -4,6 +4,12 @@ const mockNpm = require('../../fixtures/mock-npm') const { join } = require('node:path') const { cleanNewlines } = require('../../fixtures/clean-snapshot') +t.test('completion', async t => { + const { set } = await mockNpm(t, { command: 'set' }) + const res = await set.completion({ conf: { argv: { remain: ['npm', 'set'] } } }) + t.type(res, Array) +}) + t.test('no args', async t => { const { npm } = await mockNpm(t) t.rejects(npm.exec('set', []), /Usage:/, 'prints usage') @@ -12,13 +18,13 @@ t.test('no args', async t => { t.test('test-config-item', async t => { const { npm, home, joinedOutput } = await mockNpm(t, { homeDir: { - '.npmrc': 'original-config-test=original value', + '.npmrc': 'tag=beta', }, }) t.equal( - npm.config.get('original-config-test'), - 'original value', + npm.config.get('tag'), + 'beta', 'original config is set from npmrc' ) @@ -40,7 +46,7 @@ t.test('test-config-item', async t => { t.equal( cleanNewlines(await fs.readFile(join(home, '.npmrc'), 'utf-8')), [ - 'original-config-test=original value', + 'tag=beta', 'fund=true', '', ].join('\n'), diff --git a/test/lib/commands/shrinkwrap.js b/test/lib/commands/shrinkwrap.js deleted file mode 100644 index ec65ca604a88b..0000000000000 --- a/test/lib/commands/shrinkwrap.js +++ /dev/null @@ -1,232 +0,0 @@ -const t = require('tap') -const fs = require('node:fs') -const { resolve } = require('node:path') -const { load: loadMockNpm } = require('../../fixtures/mock-npm') - -// Attempt to parse json values in snapshots before -// stringifying to remove escaped values like \\" -// This also doesn't reorder the keys of the object -// like tap does by default which is nice in this case -t.formatSnapshot = obj => - JSON.stringify( - obj, - (k, v) => { - try { - return JSON.parse(v) - } catch { - // leave invalid JSON as a string - } - return v - }, - 2 - ) - -// Run shrinkwrap against a specified prefixDir with config items -// and make some assertions that should always be true. Sets -// the results on t.context for use in child tests -const shrinkwrap = async (t, prefixDir = {}, config = {}) => { - const { npm, logs } = await loadMockNpm(t, { - config, - prefixDir, - }) - - await npm.exec('shrinkwrap', []) - - const newFile = resolve(npm.prefix, 'npm-shrinkwrap.json') - const oldFile = resolve(npm.prefix, 'package-lock.json') - - t.notOk(fs.existsSync(oldFile), 'package-lock is always deleted') - t.teardown(() => delete t.context) - t.context = { - localPrefix: prefixDir, - config, - shrinkwrap: JSON.parse(fs.readFileSync(newFile)), - logs: logs.notice, - warn: logs.warn, - } -} - -// Run shrinkwrap against all combinations of existing and config -// lockfile versions -const shrinkwrapMatrix = async (t, file, assertions) => { - const ancient = JSON.stringify({ lockfileVersion: 1 }) - const existing = JSON.stringify({ lockfileVersion: 2 }) - const upgrade = { 'lockfile-version': 3 } - const downgrade = { 'lockfile-version': 1 } - - let ancientDir = {} - let existingDir = null - if (file === 'package-lock') { - ancientDir = { 'package-lock.json': ancient } - existingDir = { 'package-lock.json': existing } - } else if (file === 'npm-shrinkwrap') { - ancientDir = { 'npm-shrinkwrap.json': ancient } - existingDir = { 'npm-shrinkwrap.json': existing } - } else if (file === 'hidden-lockfile') { - ancientDir = { node_modules: { '.package-lock.json': ancient } } - existingDir = { node_modules: { '.package-lock.json': existing } } - } - - await t.test('ancient', async t => { - await shrinkwrap(t, ancientDir) - t.match(t.context, assertions.ancient) - t.matchSnapshot(t.context) - }) - await t.test('ancient upgrade', async t => { - await shrinkwrap(t, ancientDir, upgrade) - t.match(t.context, assertions.ancientUpgrade) - t.matchSnapshot(t.context) - }) - - if (existingDir) { - await t.test('existing', async t => { - await shrinkwrap(t, existingDir) - t.match(t.context, assertions.existing) - t.matchSnapshot(t.context) - }) - await t.test('existing upgrade', async t => { - await shrinkwrap(t, existingDir, upgrade) - t.match(t.context, assertions.existingUpgrade) - t.matchSnapshot(t.context) - }) - await t.test('existing downgrade', async t => { - await shrinkwrap(t, existingDir, downgrade) - t.match(t.context, assertions.existingDowngrade) - t.matchSnapshot(t.context) - }) - } -} - -const NOTICES = { - CREATED: (v = '') => [`created a lockfile as npm-shrinkwrap.json${v && ` with version ${v}`}`], - RENAMED: (v = '') => [ - `package-lock.json has been renamed to npm-shrinkwrap.json${ - v && ` and updated to version ${v}` - }`, - ], - UPDATED: (v = '') => [`npm-shrinkwrap.json updated to version ${v}`], - SAME: () => [`npm-shrinkwrap.json up to date`], - CONVERTING: (current, next) => - [`Converting lock file (npm-shrinkwrap.json) from v${current} -> v${next}`], -} - -t.test('with nothing', t => - shrinkwrapMatrix(t, null, { - ancient: { - shrinkwrap: { lockfileVersion: 3 }, - logs: NOTICES.CREATED(3), - warn: [], - }, - ancientUpgrade: { - shrinkwrap: { lockfileVersion: 3 }, - logs: NOTICES.CREATED(3), - warn: [], - }, - }) -) - -t.test('with package-lock.json', t => - shrinkwrapMatrix(t, 'package-lock', { - ancient: { - shrinkwrap: { lockfileVersion: 3 }, - logs: NOTICES.RENAMED(3), - warn: NOTICES.CONVERTING(1, 3), - }, - ancientUpgrade: { - shrinkwrap: { lockfileVersion: 3 }, - logs: NOTICES.RENAMED(3), - warn: NOTICES.CONVERTING(1, 3), - }, - existing: { - shrinkwrap: { lockfileVersion: 2 }, - logs: NOTICES.RENAMED(), - warn: [], - }, - existingUpgrade: { - shrinkwrap: { lockfileVersion: 3 }, - logs: NOTICES.RENAMED(3), - warn: NOTICES.CONVERTING(2, 3), - }, - existingDowngrade: { - shrinkwrap: { lockfileVersion: 1 }, - logs: NOTICES.RENAMED(1), - warn: NOTICES.CONVERTING(2, 1), - }, - }) -) - -t.test('with npm-shrinkwrap.json', t => - shrinkwrapMatrix(t, 'npm-shrinkwrap', { - ancient: { - shrinkwrap: { lockfileVersion: 3 }, - logs: NOTICES.UPDATED(3), - warn: NOTICES.CONVERTING(1, 3), - }, - ancientUpgrade: { - shrinkwrap: { lockfileVersion: 3 }, - logs: NOTICES.UPDATED(3), - warn: NOTICES.CONVERTING(1, 3), - }, - existing: { - shrinkwrap: { lockfileVersion: 2 }, - logs: NOTICES.SAME(), - warn: [], - }, - existingUpgrade: { - shrinkwrap: { lockfileVersion: 3 }, - logs: NOTICES.UPDATED(3), - warn: NOTICES.CONVERTING(2, 3), - }, - existingDowngrade: { - shrinkwrap: { lockfileVersion: 1 }, - logs: NOTICES.UPDATED(1), - warn: NOTICES.CONVERTING(2, 1), - }, - }) -) - -t.test('with hidden lockfile', t => - shrinkwrapMatrix(t, 'hidden-lockfile', { - ancient: { - shrinkwrap: { lockfileVersion: 1 }, - logs: NOTICES.CREATED(), - warn: [], - }, - ancientUpgrade: { - shrinkwrap: { lockfileVersion: 3 }, - logs: NOTICES.CREATED(), - warn: NOTICES.CONVERTING(1, 3), - }, - existing: { - shrinkwrap: { lockfileVersion: 2 }, - logs: NOTICES.CREATED(), - warn: [], - }, - existingUpgrade: { - shrinkwrap: { lockfileVersion: 3 }, - logs: NOTICES.CREATED(3), - warn: NOTICES.CONVERTING(2, 3), - }, - existingDowngrade: { - shrinkwrap: { lockfileVersion: 1 }, - logs: NOTICES.CREATED(1), - warn: NOTICES.CONVERTING(2, 1), - }, - }) -) - -t.test('throws in global mode', async t => { - t.rejects( - shrinkwrap( - t, - {}, - { - global: true, - } - ), - { - message: '`npm shrinkwrap` does not work for global packages', - code: 'ESHRINKWRAPGLOBAL', - } - ) -}) diff --git a/test/lib/commands/stage/approve.js b/test/lib/commands/stage/approve.js new file mode 100644 index 0000000000000..dac2b244764d8 --- /dev/null +++ b/test/lib/commands/stage/approve.js @@ -0,0 +1,73 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../../../fixtures/mock-npm.js') +const MockRegistry = require('@npmcli/mock-registry') + +const token = 'test-auth-token' +const authConfig = { '//registry.npmjs.org/:_authToken': token } +const stageId = '1de6f3db-2ed9-4d72-b3dd-8f0e2b474a2f' + +t.test('approves a staged package', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { ...authConfig, otp: '123456' }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.post(`/-/stage/${stageId}/approve`) + .reply(201, { message: 'Package version approved and published successfully.' }) + await npm.exec('stage', ['approve', stageId]) + t.match(joinedOutput(), /approved and published successfully/) +}) + +t.test('throws usageError without stage-id', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + }) + await t.rejects(npm.exec('stage', ['approve']), { + code: 'EUSAGE', + message: /npm stage approve /, + }) +}) + +t.test('throws on invalid uuid', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + }) + await t.rejects(npm.exec('stage', ['approve', 'not-a-uuid']), { + message: /stage-id must be a valid UUID/, + }) +}) + +t.test('throws on 404 (stage-id not found)', async t => { + const { npm } = await loadMockNpm(t, { + config: { ...authConfig, otp: '123456' }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.post(`/-/stage/${stageId}/approve`) + .reply(404, { error: 'Not found' }) + await t.rejects(npm.exec('stage', ['approve', stageId]), { + statusCode: 404, + }) +}) + +t.test('throws on 403 (not an owner)', async t => { + const { npm } = await loadMockNpm(t, { + config: { ...authConfig, otp: '123456' }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.post(`/-/stage/${stageId}/approve`) + .reply(403, { error: 'You do not have permission to approve this package' }) + await t.rejects(npm.exec('stage', ['approve', stageId]), { + statusCode: 403, + }) +}) diff --git a/test/lib/commands/stage/download.js b/test/lib/commands/stage/download.js new file mode 100644 index 0000000000000..807c1282edc86 --- /dev/null +++ b/test/lib/commands/stage/download.js @@ -0,0 +1,139 @@ +const t = require('tap') +const fs = require('node:fs') +const path = require('node:path') +const { load: loadMockNpm } = require('../../../fixtures/mock-npm.js') +const MockRegistry = require('@npmcli/mock-registry') +const mockGlobals = require('@npmcli/mock-globals') +const libpack = require('libnpmpack') + +const token = 'test-auth-token' +const authConfig = { '//registry.npmjs.org/:_authToken': token } +const stageId = '1de6f3db-2ed9-4d72-b3dd-8f0e2b474a2f' + +t.test('downloads a staged tarball', async t => { + const { npm, joinedOutput, prefix } = await loadMockNpm(t, { + config: authConfig, + prefixDir: { + 'package.json': JSON.stringify({ + name: '@npmcli/test-package', + version: '1.0.0', + }), + 'index.js': 'module.exports = 42', + }, + }) + const tarballData = await libpack(prefix) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get(`/-/stage/${stageId}/tarball`) + .reply(200, tarballData, { 'content-type': 'application/octet-stream' }) + + mockGlobals(t, { 'process.cwd': () => prefix }) + + await npm.exec('stage', ['download', stageId]) + const out = joinedOutput() + const expectedFilename = `npmcli-test-package-1.0.0-${stageId}.tgz` + t.match(out, expectedFilename) + t.ok(fs.existsSync(path.join(prefix, expectedFilename))) +}) + +t.test('downloads with --json', async t => { + const { npm, joinedOutput, prefix } = await loadMockNpm(t, { + config: { ...authConfig, json: true }, + prefixDir: { + 'package.json': JSON.stringify({ + name: '@npmcli/test-package', + version: '1.0.0', + }), + }, + }) + const tarballData = await libpack(prefix) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get(`/-/stage/${stageId}/tarball`) + .reply(200, tarballData, { 'content-type': 'application/octet-stream' }) + + mockGlobals(t, { 'process.cwd': () => prefix }) + + await npm.exec('stage', ['download', stageId]) + const out = joinedOutput() + t.notMatch(out, `npmcli-test-package-1.0.0-${stageId}.tgz`) + const expectedFilename = `npmcli-test-package-1.0.0-${stageId}.tgz` + t.ok(fs.existsSync(path.join(prefix, expectedFilename))) +}) + +t.test('throws usageError without stage-id', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + }) + await t.rejects(npm.exec('stage', ['download']), { + code: 'EUSAGE', + }) +}) + +t.test('throws on invalid uuid', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + }) + await t.rejects(npm.exec('stage', ['download', 'not-a-uuid']), { + message: /stage-id must be a valid UUID/, + }) +}) + +t.test('throws on 404 (stage-id not found)', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get(`/-/stage/${stageId}/tarball`) + .reply(404, { error: 'Not found' }) + await t.rejects(npm.exec('stage', ['download', stageId]), { + statusCode: 404, + }) +}) + +t.test('throws on 403 (not an owner)', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get(`/-/stage/${stageId}/tarball`) + .reply(403, { error: 'You do not have permission to download this package' }) + await t.rejects(npm.exec('stage', ['download', stageId]), { + statusCode: 403, + }) +}) + +t.test('throws when tarball has no package.json', async t => { + const { npm, prefix } = await loadMockNpm(t, { + config: authConfig, + prefixDir: {}, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + // Empty tar (two 512-byte zero blocks) has no entries + registry.nock.get(`/-/stage/${stageId}/tarball`) + .reply(200, Buffer.alloc(1024), { 'content-type': 'application/octet-stream' }) + + mockGlobals(t, { 'process.cwd': () => prefix }) + + await t.rejects(npm.exec('stage', ['download', stageId]), { + message: /Could not read package.json from tarball/, + }) +}) diff --git a/test/lib/commands/stage/index.js b/test/lib/commands/stage/index.js new file mode 100644 index 0000000000000..bd81c7aab5e42 --- /dev/null +++ b/test/lib/commands/stage/index.js @@ -0,0 +1,332 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../../../fixtures/mock-npm') +const MockRegistry = require('@npmcli/mock-registry') +const path = require('node:path') +const fs = require('node:fs') + +const pkg = '@npmcli/test-package' +const token = 'test-auth-token' +const authConfig = { '//registry.npmjs.org/:_authToken': token } + +const pkgJson = { + name: pkg, + description: 'npm test package', + version: '1.0.0', +} + +t.test('stages a package from cwd', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: authConfig, + prefixDir: { + 'package.json': JSON.stringify(pkgJson), + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.post('/-/stage/package/@npmcli%2ftest-package').reply(201, {}) + await npm.exec('stage', ['publish']) + t.match(joinedOutput(), /\+ @npmcli\/test-package@1\.0\.0 \(staged\)/) +}) + +t.test('stages with --dry-run', async t => { + const { npm, joinedOutput, logs } = await loadMockNpm(t, { + config: { ...authConfig, 'dry-run': true }, + prefixDir: { + 'package.json': JSON.stringify(pkgJson), + }, + }) + await npm.exec('stage', ['publish']) + t.ok(logs.notice.some(n => /Staging to .* \(dry-run\)/.test(n))) + t.match(joinedOutput(), /\+ @npmcli\/test-package@1\.0\.0 \(staged\)/) +}) + +t.test('stages with --json', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { ...authConfig, json: true }, + prefixDir: { + 'package.json': JSON.stringify(pkgJson), + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.post('/-/stage/package/@npmcli%2ftest-package').reply(201, {}) + await npm.exec('stage', ['publish']) + const out = JSON.parse(joinedOutput()) + t.equal(out[pkg].name, pkg) + t.equal(out[pkg].version, '1.0.0') +}) + +t.test('stages with --json includes stageId', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { ...authConfig, json: true }, + prefixDir: { + 'package.json': JSON.stringify(pkgJson), + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + const stageId = 'f8e7a45b-7a5f-4f31-8e6d-9dd1c6ef38c0' + registry.nock.post('/-/stage/package/@npmcli%2ftest-package').reply(201, { stageId }) + await npm.exec('stage', ['publish']) + const out = JSON.parse(joinedOutput()) + t.equal(out[pkg].name, pkg) + t.equal(out[pkg].stageId, stageId) +}) + +t.test('completion returns subcommands', async t => { + const Stage = require('../../../../lib/commands/stage/index.js') + const res = await Stage.completion({ conf: { argv: { remain: ['npm', 'stage'] } } }) + t.strictSame(res, ['publish', 'list', 'view', 'approve', 'reject', 'download']) +}) + +t.test('completion returns empty for subcommand', async t => { + const Stage = require('../../../../lib/commands/stage/index.js') + const res = await Stage.completion({ conf: { argv: { remain: ['npm', 'stage', 'publish'] } } }) + t.strictSame(res, []) +}) + +t.test('throws on invalid semver tag', async t => { + const { npm } = await loadMockNpm(t, { + config: { ...authConfig, tag: '1.0.0' }, + prefixDir: { + 'package.json': JSON.stringify(pkgJson), + }, + }) + await t.rejects(npm.exec('stage', ['publish']), { + message: /Tag name must not be a valid SemVer range/, + }) +}) + +t.test('throws ENEEDAUTH with no credentials', async t => { + const { npm } = await loadMockNpm(t, { + config: {}, + prefixDir: { + 'package.json': JSON.stringify(pkgJson), + }, + }) + await t.rejects(npm.exec('stage', ['publish']), { + code: 'ENEEDAUTH', + }) +}) + +t.test('warns on --dry-run with no credentials', async t => { + const { npm, logs } = await loadMockNpm(t, { + config: { 'dry-run': true }, + prefixDir: { + 'package.json': JSON.stringify(pkgJson), + }, + }) + await npm.exec('stage', ['publish']) + t.match(logs.warn, [/requires you to be logged in.*\(dry-run\)/]) +}) + +t.test('stages a package with positional arg', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: authConfig, + prefixDir: { + 'package.json': JSON.stringify(pkgJson), + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.post('/-/stage/package/@npmcli%2ftest-package').reply(201, {}) + await npm.exec('stage', ['publish', '.']) + t.match(joinedOutput(), /\+ @npmcli\/test-package@1\.0\.0 \(staged\)/) +}) + +t.test('respects ignore-scripts', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { ...authConfig, 'ignore-scripts': true }, + prefixDir: { + 'package.json': JSON.stringify({ + ...pkgJson, + scripts: { + prepublishOnly: 'exit 1', + publish: 'exit 1', + postpublish: 'exit 1', + }, + }), + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.post('/-/stage/package/@npmcli%2ftest-package').reply(201, {}) + await npm.exec('stage', ['publish']) + t.match(joinedOutput(), /\(staged\)/) +}) + +t.test('foreground-scripts can be set to false', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { ...authConfig, 'foreground-scripts': false }, + prefixDir: { + 'package.json': JSON.stringify(pkgJson), + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.post('/-/stage/package/@npmcli%2ftest-package').reply(201, {}) + await npm.exec('stage', ['publish']) + t.match(joinedOutput(), /\(staged\)/) +}) + +t.test('runs lifecycle scripts', async t => { + const { npm, prefix } = await loadMockNpm(t, { + config: authConfig, + prefixDir: { + 'package.json': JSON.stringify({ + ...pkgJson, + scripts: { + prepublishOnly: 'touch scripts-prepublishonly', + publish: 'touch scripts-publish', + postpublish: 'touch scripts-postpublish', + }, + }), + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.post('/-/stage/package/@npmcli%2ftest-package').reply(201, {}) + await npm.exec('stage', ['publish']) + t.equal(fs.existsSync(path.join(prefix, 'scripts-prepublishonly')), true) + t.equal(fs.existsSync(path.join(prefix, 'scripts-publish')), true) + t.equal(fs.existsSync(path.join(prefix, 'scripts-postpublish')), true) +}) + +t.test('respects publishConfig', async t => { + const alternateRegistry = 'https://other.registry.npmjs.org' + const { npm, joinedOutput, logs } = await loadMockNpm(t, { + config: { + [`${alternateRegistry.slice(6)}/:_authToken`]: 'test-other-token', + }, + prefixDir: { + 'package.json': JSON.stringify({ + ...pkgJson, + publishConfig: { + registry: alternateRegistry, + other: 'unknown-key', + }, + }), + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: alternateRegistry, + authorization: 'test-other-token', + }) + registry.nock.post('/-/stage/package/@npmcli%2ftest-package').reply(201, {}) + await npm.exec('stage', ['publish']) + t.match(joinedOutput(), /\(staged\)/) + t.match(logs.warn, [/Unknown publishConfig/]) +}) + +t.test('warns about auto-corrected package.json errors', async t => { + const { npm, logs } = await loadMockNpm(t, { + config: authConfig, + prefixDir: { + 'package.json': JSON.stringify({ + name: pkg, + version: '1.0.0', + repository: 'github:user/repo', + }), + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.post('/-/stage/package/@npmcli%2ftest-package').reply(201, {}) + await npm.exec('stage', ['publish']) + t.ok(logs.warn.some(w => /auto-corrected/.test(w))) + t.ok(logs.warn.some(w => /errors corrected/.test(w))) +}) + +t.test('stages with basic auth (username)', async t => { + const basic = Buffer.from('test-user:test-password').toString('base64') + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { + '//registry.npmjs.org/:username': 'test-user', + '//registry.npmjs.org/:_password': Buffer.from('test-password').toString('base64'), + }, + prefixDir: { + 'package.json': JSON.stringify(pkgJson), + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + basic, + }) + registry.nock.post('/-/stage/package/@npmcli%2ftest-package').reply(201, {}) + await npm.exec('stage', ['publish']) + t.match(joinedOutput(), /\(staged\)/) +}) + +t.test('stages with cert auth', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { + '//registry.npmjs.org/:certfile': '/path/to/cert', + '//registry.npmjs.org/:keyfile': '/path/to/key', + }, + prefixDir: { + 'package.json': JSON.stringify(pkgJson), + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + }) + registry.nock.post('/-/stage/package/@npmcli%2ftest-package').reply(201, {}) + await npm.exec('stage', ['publish']) + t.match(joinedOutput(), /\(staged\)/) +}) + +t.test('throws EPRIVATE for private packages', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + prefixDir: { + 'package.json': JSON.stringify({ ...pkgJson, private: true }), + }, + }) + await t.rejects(npm.exec('stage', ['publish']), { + code: 'EPRIVATE', + }) +}) + +t.test('outputs stageId when returned', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: authConfig, + prefixDir: { + 'package.json': JSON.stringify(pkgJson), + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.post('/-/stage/package/@npmcli%2ftest-package').reply(201, { stageId: 'abc-123' }) + await npm.exec('stage', ['publish']) + t.match(joinedOutput(), /staged with id abc-123/) +}) diff --git a/test/lib/commands/stage/list.js b/test/lib/commands/stage/list.js new file mode 100644 index 0000000000000..e66680db8277f --- /dev/null +++ b/test/lib/commands/stage/list.js @@ -0,0 +1,147 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../../../fixtures/mock-npm.js') +const MockRegistry = require('@npmcli/mock-registry') + +const token = 'test-auth-token' +const authConfig = { '//registry.npmjs.org/:_authToken': token } + +const stageItems = [ + { + id: '1de6f3db-2ed9-4d72-b3dd-8f0e2b474a2f', + packageName: '@npmcli/example-package', + version: '1.2.3', + tag: 'latest', + createdAt: '2026-03-16T09:00:00.000Z', + actor: 'octocat', + actorType: 'user', + shasum: '4f7f5f1d5bcf2f72f6e4d6c4f3b2812d8a2f6c19', + }, + { + id: 'f8e7a45b-7a5f-4f31-8e6d-9dd1c6ef38c0', + packageName: 'example-lib', + version: '0.4.0', + tag: 'next', + createdAt: '2026-03-15T18:22:11.000Z', + actor: 'npm-bot', + actorType: 'trusted automation', + shasum: '8eb3b4e9b6e3d0d2c86be1e6d4f43f4be62e80ad', + }, +] + +t.test('lists all staged packages', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { ...authConfig }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get('/-/stage?page=0&perPage=100') + .reply(200, { items: stageItems, page: 0, perPage: 100, total: 2 }) + await npm.exec('stage', ['list']) + const out = joinedOutput() + t.match(out, 'package name: @npmcli/example-package') + t.match(out, 'package name: example-lib') + t.match(out, 'version: 1.2.3') + t.match(out, 'version: 0.4.0') +}) + +t.test('lists with package filter', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { ...authConfig }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get('/-/stage?page=0&perPage=100&package=%40npmcli%2Fexample-package') + .reply(200, { items: [stageItems[0]], page: 0, perPage: 100, total: 1 }) + await npm.exec('stage', ['list', '@npmcli/example-package']) + const out = joinedOutput() + t.match(out, '@npmcli/example-package') + t.notMatch(out, 'example-lib') +}) + +t.test('lists with --json', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { ...authConfig, json: true }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get('/-/stage?page=0&perPage=100') + .reply(200, { items: stageItems, page: 0, perPage: 100, total: 2 }) + await npm.exec('stage', ['list']) + const out = JSON.parse(joinedOutput()) + t.equal(out.length, 2) + t.equal(out[0].packageName, '@npmcli/example-package') + t.equal(out[0].id, '1de6f3db-2ed9-4d72-b3dd-8f0e2b474a2f', 'uuid id is not redacted') +}) + +t.test('shows message when no packages', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { ...authConfig }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get('/-/stage?page=0&perPage=100') + .reply(200, { items: [], page: 0, perPage: 100, total: 0 }) + await npm.exec('stage', ['list']) + t.match(joinedOutput(), 'No staged packages found.') +}) + +t.test('shows filtered message when no packages with filter', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { ...authConfig }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get('/-/stage?page=0&perPage=100&package=nonexistent') + .reply(200, { items: [], page: 0, perPage: 100, total: 0 }) + await npm.exec('stage', ['list', 'nonexistent']) + t.match(joinedOutput(), 'No staged versions of package name "nonexistent".') +}) + +t.test('throws on version specifier', async t => { + const { npm } = await loadMockNpm(t, { + config: { ...authConfig }, + }) + await t.rejects(npm.exec('stage', ['list', 'area@1.0.0']), { + code: 'EUSAGE', + }) +}) + +t.test('paginates through multiple pages', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { ...authConfig }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + // page 0: 100 items, total 101 + const page0Items = Array.from({ length: 100 }, (_, i) => ({ + ...stageItems[0], + id: `id-${i}`, + version: `1.0.${i}`, + })) + registry.nock.get('/-/stage?page=0&perPage=100') + .reply(200, { items: page0Items, page: 0, perPage: 100, total: 101 }) + registry.nock.get('/-/stage?page=1&perPage=100') + .reply(200, { items: [stageItems[1]], page: 1, perPage: 100, total: 101 }) + await npm.exec('stage', ['list']) + const out = joinedOutput() + t.match(out, 'version: 1.0.0') + t.match(out, 'version: 0.4.0') +}) diff --git a/test/lib/commands/stage/reject.js b/test/lib/commands/stage/reject.js new file mode 100644 index 0000000000000..d021075a24523 --- /dev/null +++ b/test/lib/commands/stage/reject.js @@ -0,0 +1,72 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../../../fixtures/mock-npm.js') +const MockRegistry = require('@npmcli/mock-registry') + +const token = 'test-auth-token' +const authConfig = { '//registry.npmjs.org/:_authToken': token } +const stageId = '1de6f3db-2ed9-4d72-b3dd-8f0e2b474a2f' + +t.test('rejects a staged package', async t => { + const { npm, joinedOutput, logs } = await loadMockNpm(t, { + config: { ...authConfig, otp: '123456' }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.delete(`/-/stage/${stageId}`).reply(204) + await npm.exec('stage', ['reject', stageId]) + t.match(joinedOutput(), /has been rejected/) + t.match(logs.warn, [/permanently delete/]) +}) + +t.test('throws usageError without stage-id', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + }) + await t.rejects(npm.exec('stage', ['reject']), { + code: 'EUSAGE', + }) +}) + +t.test('throws on invalid uuid', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + }) + await t.rejects(npm.exec('stage', ['reject', 'not-a-uuid']), { + message: /stage-id must be a valid UUID/, + }) +}) + +t.test('throws on 404 (stage-id not found)', async t => { + const { npm } = await loadMockNpm(t, { + config: { ...authConfig, otp: '123456' }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.delete(`/-/stage/${stageId}`) + .reply(404, { error: 'Not found' }) + await t.rejects(npm.exec('stage', ['reject', stageId]), { + statusCode: 404, + }) +}) + +t.test('throws on 403 (not an owner)', async t => { + const { npm } = await loadMockNpm(t, { + config: { ...authConfig, otp: '123456' }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.delete(`/-/stage/${stageId}`) + .reply(403, { error: 'You do not have permission to reject this package' }) + await t.rejects(npm.exec('stage', ['reject', stageId]), { + statusCode: 403, + }) +}) diff --git a/test/lib/commands/stage/view.js b/test/lib/commands/stage/view.js new file mode 100644 index 0000000000000..604caf98fb23b --- /dev/null +++ b/test/lib/commands/stage/view.js @@ -0,0 +1,100 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../../../fixtures/mock-npm.js') +const MockRegistry = require('@npmcli/mock-registry') + +const token = 'test-auth-token' +const authConfig = { '//registry.npmjs.org/:_authToken': token } + +const stageItem = { + id: '1de6f3db-2ed9-4d72-b3dd-8f0e2b474a2f', + packageName: '@npmcli/example-package', + version: '1.2.3', + tag: 'latest', + createdAt: '2026-03-16T09:00:00.000Z', + actor: 'octocat', + actorType: 'user', + shasum: '4f7f5f1d5bcf2f72f6e4d6c4f3b2812d8a2f6c19', +} + +t.test('views a staged package', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: authConfig, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get(`/-/stage/${stageItem.id}`).reply(200, stageItem) + await npm.exec('stage', ['view', stageItem.id]) + const out = joinedOutput() + t.match(out, /id:/) + t.match(out, 'package name: @npmcli/example-package') + t.match(out, 'version: 1.2.3') +}) + +t.test('views with --json', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { ...authConfig, json: true }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get(`/-/stage/${stageItem.id}`).reply(200, stageItem) + await npm.exec('stage', ['view', stageItem.id]) + const out = JSON.parse(joinedOutput()) + t.ok(out.id) + t.equal(out.packageName, '@npmcli/example-package') +}) + +t.test('throws usageError without stage-id', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + }) + await t.rejects(npm.exec('stage', ['view']), { + code: 'EUSAGE', + }) +}) + +t.test('throws on invalid uuid', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + }) + await t.rejects(npm.exec('stage', ['view', 'not-a-uuid']), { + message: /stage-id must be a valid UUID/, + }) +}) + +t.test('throws on 404 (stage-id not found)', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get(`/-/stage/${stageItem.id}`) + .reply(404, { error: 'Not found' }) + await t.rejects(npm.exec('stage', ['view', stageItem.id]), { + statusCode: 404, + }) +}) + +t.test('throws on 403 (not an owner)', async t => { + const { npm } = await loadMockNpm(t, { + config: authConfig, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + registry.nock.get(`/-/stage/${stageItem.id}`) + .reply(403, { error: 'You do not have permission to view this package' }) + await t.rejects(npm.exec('stage', ['view', stageItem.id]), { + statusCode: 403, + }) +}) diff --git a/test/lib/commands/star.js b/test/lib/commands/star.js deleted file mode 100644 index c5f233f01cc4a..0000000000000 --- a/test/lib/commands/star.js +++ /dev/null @@ -1,61 +0,0 @@ -const t = require('tap') -const { load: loadMockNpm } = require('../../fixtures/mock-npm.js') -const MockRegistry = require('@npmcli/mock-registry') - -const pkgName = '@npmcli/test-package' -const authToken = 'test-auth-token' -const username = 'test-user' -const auth = { '//registry.npmjs.org/:_authToken': authToken } - -t.test('no args', async t => { - const { npm } = await loadMockNpm(t) - await t.rejects( - npm.exec('star', []), - { code: 'EUSAGE' }, - 'should throw usage error' - ) -}) - -t.test('first person to star a package unicode:false', async t => { - const { npm, joinedOutput } = await loadMockNpm(t, { - config: { unicode: false, ...auth }, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), - authorization: authToken, - }) - const manifest = registry.manifest({ name: pkgName }) - await registry.package({ manifest, query: { write: true } }) - registry.whoami({ username }) - registry.star(manifest, { [username]: true }) - - await npm.exec('star', [pkgName]) - t.equal( - joinedOutput(), - '(*) @npmcli/test-package', - 'should output starred package msg' - ) -}) - -t.test('second person to star a package unicode:true', async t => { - const { npm, joinedOutput } = await loadMockNpm(t, { - config: { unicode: true, ...auth }, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), - authorization: authToken, - }) - const manifest = registry.manifest({ name: pkgName, users: { otheruser: true } }) - await registry.package({ manifest, query: { write: true } }) - registry.whoami({ username }) - registry.star(manifest, { otheruser: true, [username]: true }) - - await npm.exec('star', [pkgName]) - t.equal( - joinedOutput(), - '★ @npmcli/test-package', - 'should output starred package msg' - ) -}) diff --git a/test/lib/commands/stars.js b/test/lib/commands/stars.js deleted file mode 100644 index fc38ca77ac781..0000000000000 --- a/test/lib/commands/stars.js +++ /dev/null @@ -1,127 +0,0 @@ -const t = require('tap') -const realFetch = require('npm-registry-fetch') -const mockNpm = require('../../fixtures/mock-npm') - -const noop = () => {} - -const mockStars = async (t, { npmFetch = noop, exec = true, ...opts }) => { - const mock = await mockNpm(t, { - command: 'stars', - exec, - mocks: { - 'npm-registry-fetch': Object.assign(noop, realFetch, { json: npmFetch }), - '{LIB}/utils/get-identity.js': async () => 'foo', - }, - ...opts, - }) - - return { - ...mock, - result: mock.stars.output, - logs: () => mock.logs.byTitle('stars'), - } -} - -t.test('no args', async t => { - t.plan(3) - - const npmFetch = async (uri, opts) => { - t.equal(uri, '/-/_view/starredByUser', 'should fetch from expected uri') - t.equal(opts.query.key, '"foo"', 'should match logged in username') - - return { - rows: [ - { value: '@npmcli/arborist' }, - { value: '@npmcli/map-workspaces' }, - { value: 'libnpmfund' }, - { value: 'libnpmpublish' }, - { value: 'ipt' }, - ], - } - } - - const { result } = await mockStars(t, { npmFetch }) - - t.matchSnapshot( - result, - 'should output a list of starred packages' - ) -}) - -t.test('npm star ', async t => { - t.plan(3) - - const npmFetch = async (uri, opts) => { - t.equal(uri, '/-/_view/starredByUser', 'should fetch from expected uri') - t.equal(opts.query.key, '"ruyadorno"', 'should match username') - - return { - rows: [{ value: '@npmcli/arborist' }], - } - } - - const { result } = await mockStars(t, { npmFetch, exec: ['ruyadorno'] }) - - t.match( - result, - '@npmcli/arborist', - 'should output expected list of starred packages' - ) -}) - -t.test('unauthorized request', async t => { - const npmFetch = async () => { - throw Object.assign( - new Error('Not logged in'), - { code: 'ENEEDAUTH' } - ) - } - - const { joinedOutput, stars, logs } = await mockStars(t, { npmFetch, exec: false }) - - await t.rejects( - stars.exec([]), - /Not logged in/, - 'should throw unauthorized request msg' - ) - - t.strictSame( - logs(), - ['stars auth is required to look up your username'], - 'should warn auth required msg' - ) - - t.equal( - joinedOutput(), - '', - 'should have empty output' - ) -}) - -t.test('unexpected error', async t => { - const npmFetch = async () => { - throw new Error('ERROR') - } - - const { stars, logs } = await mockStars(t, { npmFetch, exec: false }) - - await t.rejects( - stars.exec([]), - /ERROR/, - 'should throw unexpected error message' - ) - - t.strictSame(logs(), [], 'no logs') -}) - -t.test('no pkg starred', async t => { - const npmFetch = async () => ({ rows: [] }) - - const { logs } = await mockStars(t, { npmFetch }) - - t.strictSame( - logs(), - ['stars user has not starred any packages'], - 'should warn no starred packages msg' - ) -}) diff --git a/test/lib/commands/team.js b/test/lib/commands/team.js index 1a5480293edc9..1a00e64cadddc 100644 --- a/test/lib/commands/team.js +++ b/test/lib/commands/team.js @@ -422,7 +422,7 @@ t.test('completion', async t => { t.test('npm team unknown subcommand autocomplete', async t => { t.rejects( team.completion({ conf: { argv: { remain: ['npm', 'team', 'missing-subcommand'] } } }), - { message: 'missing-subcommand not recognized' }, 'should throw a a not recognized error' + { message: 'missing-subcommand not recognized' }, 'should throw a not recognized error' ) t.end() diff --git a/test/lib/commands/token.js b/test/lib/commands/token.js index f60a938b5b34b..56ab906d921be 100644 --- a/test/lib/commands/token.js +++ b/test/lib/commands/token.js @@ -1,11 +1,8 @@ const t = require('tap') const { load: loadMockNpm } = require('../../fixtures/mock-npm.js') const MockRegistry = require('@npmcli/mock-registry') -const mockGlobals = require('@npmcli/mock-globals') -const stream = require('node:stream') const authToken = 'abcd1234' -const password = 'this is not really a password' const auth = { '//registry.npmjs.org/:_authToken': authToken, @@ -66,9 +63,9 @@ t.test('token list', async t => { registry.getTokens(tokens) await npm.exec('token', []) t.strictSame(outputs, [ - `Publish token efgh5678efgh5678… with id abcd123 created ${now.slice(0, 10)}`, + `Token efgh5678efgh5678… with id abcd123 created ${now.slice(0, 10)}`, '', - `Read only token hgfe8765… with id abcd125 created ${now.slice(0, 10)}`, + `Token hgfe8765… with id abcd125 created ${now.slice(0, 10)}`, 'with IP whitelist: 192.168.1.1/32', '', ]) @@ -113,7 +110,7 @@ t.test('token list parseable output', async t => { ]) }) -t.test('token revoke', async t => { +t.test('token revoke single', async t => { const { npm, joinedOutput } = await loadMockNpm(t, { config: { ...auth }, }) @@ -124,13 +121,13 @@ t.test('token revoke', async t => { }) registry.getTokens(tokens) - registry.nock.delete(`/-/npm/v1/tokens/token/${tokens[0].key}`).reply(200) + registry.revokeToken(tokens[0].key) await npm.exec('token', ['rm', tokens[0].key.slice(0, 8)]) t.equal(joinedOutput(), 'Removed 1 token') }) -t.test('token revoke multiple tokens', async t => { +t.test('token revoke multiple', async t => { const { npm, joinedOutput } = await loadMockNpm(t, { config: { ...auth }, }) @@ -141,8 +138,8 @@ t.test('token revoke multiple tokens', async t => { }) registry.getTokens(tokens) - registry.nock.delete(`/-/npm/v1/tokens/token/${tokens[0].key}`).reply(200) - registry.nock.delete(`/-/npm/v1/tokens/token/${tokens[1].key}`).reply(200) + registry.revokeToken(tokens[0].key) + registry.revokeToken(tokens[1].key) await npm.exec('token', ['rm', tokens[0].key.slice(0, 8), tokens[1].key.slice(0, 8)]) t.equal(joinedOutput(), 'Removed 2 tokens') @@ -162,7 +159,7 @@ t.test('token revoke json output', async t => { }) registry.getTokens(tokens) - registry.nock.delete(`/-/npm/v1/tokens/token/${tokens[0].key}`).reply(200) + registry.revokeToken(tokens[0].key) await npm.exec('token', ['rm', tokens[0].key.slice(0, 8)]) const parsed = JSON.parse(joinedOutput()) @@ -183,7 +180,7 @@ t.test('token revoke parseable output', async t => { }) registry.getTokens(tokens) - registry.nock.delete(`/-/npm/v1/tokens/token/${tokens[0].key}`).reply(200) + registry.revokeToken(tokens[0].key) await npm.exec('token', ['rm', tokens[0].key.slice(0, 8)]) t.equal(joinedOutput(), tokens[0].key, 'logs the token as a string') }) @@ -198,7 +195,7 @@ t.test('token revoke by token', async t => { authorization: authToken, }) registry.getTokens(tokens) - registry.nock.delete(`/-/npm/v1/tokens/token/${tokens[0].token}`).reply(200) + registry.revokeToken(tokens[0].token) await npm.exec('token', ['rm', tokens[0].token]) t.equal(joinedOutput(), 'Removed 1 token') }) @@ -243,116 +240,208 @@ t.test('token revoke unknown token', async t => { ) }) -t.test('token create', async t => { - const cidr = ['10.0.0.0/8', '192.168.1.0/24'] +t.test('token create defaults', async t => { const { npm, outputs } = await loadMockNpm(t, { config: { ...auth, - cidr, + name: 'test-token', + password: 'test-password', }, }) + const registry = new MockRegistry({ tap: t, registry: npm.config.get('registry'), authorization: authToken, }) - const stdin = new stream.PassThrough() - stdin.write(`${password}\n`) - mockGlobals(t, { - 'process.stdin': stdin, - 'process.stdout': new stream.PassThrough(), // to quiet readline - }, { replace: true }) - registry.createToken({ password, cidr }) + + registry.createToken({ + name: 'test-token', + password: 'test-password', + }, { + access: 'publish', + }) + await npm.exec('token', ['create']) - t.strictSame(outputs, [ - '', - 'Created publish token n3wt0k3n', + t.match(outputs, ['Created token n3wt0k3n']) +}) + +t.test('token create extra token attributes', async t => { + const { npm, outputs } = await loadMockNpm(t, { + config: { + ...auth, + 'bypass-2fa': true, + cidr: ['10.0.0.0/8', '192.168.1.0/24'], + expires: 1000, + name: 'extras-token', + orgs: ['@npmcli'], + 'orgs-permission': 'read-write', + packages: ['@npmcli/test-package'], + 'packages-and-scopes-permission': 'read-only', + 'packages-all': true, + password: 'test-password', + scopes: ['@npmcli'], + 'token-description': 'test token', + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: authToken, + }) + + const expires = new Date() + registry.createToken({ + bypass_2fa: true, + cidr_whitelist: ['10.0.0.0/8', '192.168.1.0/24'], + description: 'test token', + expires: 1000, + name: 'extras-token', + orgs_permission: 'read-write', + orgs: ['@npmcli'], + packages_all: true, + packages_and_scopes_permission: 'read-only', + packages: ['@npmcli/test-package'], + password: 'test-password', + scopes: ['@npmcli'], + }, { + cidr_whitelist: ['10.0.0.0/8', '192.168.1.0/24'], + expires, + }) + + await npm.exec('token', ['create']) + t.match(outputs, [ + 'Created token n3wt0k3n', 'with IP whitelist: 10.0.0.0/8,192.168.1.0/24', + `expires: ${expires.toISOString()}`, ]) }) -t.test('token create read only', async t => { +t.test('token create access.read-only', async t => { const { npm, outputs } = await loadMockNpm(t, { config: { ...auth, - 'read-only': true, + name: 'test-token', + password: 'test-password', }, }) + const registry = new MockRegistry({ tap: t, registry: npm.config.get('registry'), authorization: authToken, }) - const stdin = new stream.PassThrough() - stdin.write(`${password}\n`) - mockGlobals(t, { - 'process.stdin': stdin, - 'process.stdout': new stream.PassThrough(), // to quiet readline - }, { replace: true }) - registry.createToken({ readonly: true, password }) + + registry.createToken({ + name: 'test-token', + password: 'test-password', + }, { + access: 'read-only', + }) + await npm.exec('token', ['create']) - t.strictSame(outputs, [ - '', - 'Created read only token n3wt0k3n', - ]) + t.match(outputs, ['Created token n3wt0k3n']) +}) + +t.test('token create readonly', async t => { + const { npm, outputs } = await loadMockNpm(t, { + config: { + ...auth, + name: 'test-token', + password: 'test-password', + }, + }, { + readonly: true, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: authToken, + }) + + registry.createToken({ + name: 'test-token', + password: 'test-password', + }, { + access: 'read-only', + }) + + await npm.exec('token', ['create']) + t.match(outputs, ['Created token n3wt0k3n']) }) t.test('token create json output', async t => { - const cidr = ['10.0.0.0/8', '192.168.1.0/24'] const { npm, joinedOutput } = await loadMockNpm(t, { config: { ...auth, json: true, - cidr, + name: 'test-token', + password: 'test-password', }, }) + const registry = new MockRegistry({ tap: t, registry: npm.config.get('registry'), authorization: authToken, }) - const stdin = new stream.PassThrough() - stdin.write(`${password}\n`) - mockGlobals(t, { - 'process.stdin': stdin, - 'process.stdout': new stream.PassThrough(), // to quiet readline - }, { replace: true }) - registry.createToken({ password, cidr }) + + const created = new Date() + registry.createToken({ + name: 'test-token', + password: 'test-password', + }, { + created, + other: 'attr', + }) + await npm.exec('token', ['create']) - const parsed = JSON.parse(joinedOutput()) - t.match( - parsed, - { token: 'n3wt0k3n', readonly: false, cidr_whitelist: cidr } - ) - t.ok(parsed.created, 'also returns created') + t.match(JSON.parse(joinedOutput()), { + access: 'read-only', + created: created.toISOString(), + id: '0xdeadbeef', + name: 'test-token', + other: 'attr', + password: 'test-password', + token: 'n3wt0k3n', + }) }) t.test('token create parseable output', async t => { - const cidr = ['10.0.0.0/8', '192.168.1.0/24'] const { npm, outputs } = await loadMockNpm(t, { config: { ...auth, parseable: true, - cidr, + name: 'test-token', + password: 'test-password', }, }) + const registry = new MockRegistry({ tap: t, registry: npm.config.get('registry'), authorization: authToken, }) - const stdin = new stream.PassThrough() - stdin.write(`${password}\n`) - mockGlobals(t, { - 'process.stdin': stdin, - 'process.stdout': new stream.PassThrough(), // to quiet readline - }, { replace: true }) - registry.createToken({ password, cidr }) + + const created = new Date() + registry.createToken({ + name: 'test-token', + password: 'test-password', + }, { + access: 'publish', + created, + }) + await npm.exec('token', ['create']) - t.equal(outputs[1], 'token\tn3wt0k3n') - t.ok(outputs[2].startsWith('created\t')) - t.equal(outputs[3], 'readonly\tfalse') - t.equal(outputs[4], 'cidr_whitelist\t10.0.0.0/8,192.168.1.0/24') + t.match(outputs, [ + 'id\t0xdeadbeef', + 'token\tn3wt0k3n', + `created\t${created.toISOString()}`, + 'access\tpublish', + 'name\ttest-token', + 'password\ttest-password', + ]) }) t.test('token create ipv6 cidr', async t => { @@ -360,12 +449,14 @@ t.test('token create ipv6 cidr', async t => { config: { ...auth, cidr: '::1/128', + name: 'ipv6-test', + access: 'read-only', }, }) - await t.rejects(npm.exec('token', ['create'], { + await t.rejects(npm.exec('token', ['create']), { code: 'EINVALIDCIDR', message: /CIDR whitelist can only contain IPv4 addresses, ::1\/128 is IPv6/, - })) + }) }) t.test('token create invalid cidr', async t => { @@ -373,10 +464,12 @@ t.test('token create invalid cidr', async t => { config: { ...auth, cidr: 'apple/cider', + name: 'invalid-cidr-test', + access: 'read-only', }, }) - await t.rejects(npm.exec('token', ['create'], { + await t.rejects(npm.exec('token', ['create']), { code: 'EINVALIDCIDR', message: 'CIDR whitelist contains invalid CIDR entry: apple/cider', - })) + }) }) diff --git a/test/lib/commands/trust/circleci.js b/test/lib/commands/trust/circleci.js new file mode 100644 index 0000000000000..51211785c5748 --- /dev/null +++ b/test/lib/commands/trust/circleci.js @@ -0,0 +1,487 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../../../fixtures/mock-npm.js') +const MockRegistry = require('@npmcli/mock-registry') +const realProcLog = require('proc-log') + +const packageName = '@npmcli/test-package' + +t.test('circleci with all options provided', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'y', + }, + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', [ + 'circleci', + packageName, + '--yes', + '--org-id', '550e8400-e29b-41d4-a716-446655440000', + '--project-id', '7c9e6679-7425-40de-944b-e07fc1f90ae7', + '--pipeline-definition-id', '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + '--vcs-origin', 'github.com/owner/repo', + '--context-id', '123e4567-e89b-12d3-a456-426614174000', + '--allow-publish', + ]) +}) + +t.test('circleci without optional context-id', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'y', + }, + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', [ + 'circleci', + packageName, + '--yes', + '--org-id', '550e8400-e29b-41d4-a716-446655440000', + '--project-id', '7c9e6679-7425-40de-944b-e07fc1f90ae7', + '--pipeline-definition-id', '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + '--vcs-origin', 'github.com/owner/repo', + '--allow-publish', + ]) +}) + +t.test('circleci with multiple context-ids', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'y', + }, + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', [ + 'circleci', + packageName, + '--yes', + '--org-id', '550e8400-e29b-41d4-a716-446655440000', + '--project-id', '7c9e6679-7425-40de-944b-e07fc1f90ae7', + '--pipeline-definition-id', '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + '--vcs-origin', 'github.com/owner/repo', + '--context-id', '123e4567-e89b-12d3-a456-426614174000', + '--context-id', 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', + '--allow-publish', + ]) +}) + +t.test('circleci missing required org-id', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', [ + 'circleci', + packageName, + '--yes', + '--project-id', '7c9e6679-7425-40de-944b-e07fc1f90ae7', + '--pipeline-definition-id', '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + '--vcs-origin', 'github.com/owner/repo', + '--allow-publish', + ]), + { message: /org-id is required/ } + ) +}) + +t.test('circleci missing required project-id', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', [ + 'circleci', + packageName, + '--yes', + '--org-id', '550e8400-e29b-41d4-a716-446655440000', + '--pipeline-definition-id', '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + '--vcs-origin', 'github.com/owner/repo', + '--allow-publish', + ]), + { message: /project-id is required/ } + ) +}) + +t.test('circleci missing required pipeline-definition-id', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', [ + 'circleci', + packageName, + '--yes', + '--org-id', '550e8400-e29b-41d4-a716-446655440000', + '--project-id', '7c9e6679-7425-40de-944b-e07fc1f90ae7', + '--vcs-origin', 'github.com/owner/repo', + '--allow-publish', + ]), + { message: /pipeline-definition-id is required/ } + ) +}) + +t.test('circleci missing required vcs-origin', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', [ + 'circleci', + packageName, + '--yes', + '--org-id', '550e8400-e29b-41d4-a716-446655440000', + '--project-id', '7c9e6679-7425-40de-944b-e07fc1f90ae7', + '--pipeline-definition-id', '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + '--allow-publish', + ]), + { message: /vcs-origin is required/ } + ) +}) + +t.test('circleci with invalid org-id uuid format', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', [ + 'circleci', + packageName, + '--yes', + '--org-id', 'not-a-uuid', + '--project-id', '7c9e6679-7425-40de-944b-e07fc1f90ae7', + '--pipeline-definition-id', '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + '--vcs-origin', 'github.com/owner/repo', + '--allow-publish', + ]), + { message: /org-id must be a valid UUID/ } + ) +}) + +t.test('circleci with invalid vcs-origin format', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', [ + 'circleci', + packageName, + '--yes', + '--org-id', '550e8400-e29b-41d4-a716-446655440000', + '--project-id', '7c9e6679-7425-40de-944b-e07fc1f90ae7', + '--pipeline-definition-id', '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + '--vcs-origin', 'invalid-format', + '--allow-publish', + ]), + { message: /vcs-origin must be in format 'provider\/owner\/repo'/ } + ) +}) + +t.test('circleci with vcs-origin containing scheme prefix', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', [ + 'circleci', + packageName, + '--yes', + '--org-id', '550e8400-e29b-41d4-a716-446655440000', + '--project-id', '7c9e6679-7425-40de-944b-e07fc1f90ae7', + '--pipeline-definition-id', '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + '--vcs-origin', 'https://github.com/owner/repo', + '--allow-publish', + ]), + { message: /vcs-origin must not include a scheme/ } + ) +}) + +t.test('circleci missing package name', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', [ + 'circleci', + '--yes', + '--org-id', '550e8400-e29b-41d4-a716-446655440000', + '--project-id', '7c9e6679-7425-40de-944b-e07fc1f90ae7', + '--pipeline-definition-id', '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + '--vcs-origin', 'github.com/owner/repo', + '--allow-publish', + ]), + { message: /Package name must be specified either as an argument or in package.json file/ } + ) +}) + +t.test('bodyToOptions with all fields', t => { + const TrustCircleCI = require('../../../../lib/commands/trust/circleci.js') + + const body = { + id: 'test-id', + type: 'circleci', + claims: { + 'oidc.circleci.com/org-id': '550e8400-e29b-41d4-a716-446655440000', + 'oidc.circleci.com/project-id': '7c9e6679-7425-40de-944b-e07fc1f90ae7', + 'oidc.circleci.com/pipeline-definition-id': '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + 'oidc.circleci.com/vcs-origin': 'github.com/owner/repo', + 'oidc.circleci.com/context-ids': ['123e4567-e89b-12d3-a456-426614174000'], + }, + } + + const options = TrustCircleCI.bodyToOptions(body) + + t.equal(options.id, 'test-id', 'id should be set') + t.equal(options.type, 'circleci', 'type should be set') + t.equal(options.orgId, '550e8400-e29b-41d4-a716-446655440000', 'orgId should be set') + t.equal(options.projectId, '7c9e6679-7425-40de-944b-e07fc1f90ae7', 'projectId should be set') + t.equal(options.pipelineDefinitionId, '6ba7b810-9dad-11d1-80b4-00c04fd430c8', 'pipelineDefinitionId should be set') + t.equal(options.vcsOrigin, 'github.com/owner/repo', 'vcsOrigin should be set') + t.same(options.contextIds, ['123e4567-e89b-12d3-a456-426614174000'], 'contextIds should be set') + t.end() +}) + +t.test('bodyToOptions without optional context_ids', t => { + const TrustCircleCI = require('../../../../lib/commands/trust/circleci.js') + + const body = { + id: 'test-id', + type: 'circleci', + claims: { + 'oidc.circleci.com/org-id': '550e8400-e29b-41d4-a716-446655440000', + 'oidc.circleci.com/project-id': '7c9e6679-7425-40de-944b-e07fc1f90ae7', + 'oidc.circleci.com/pipeline-definition-id': '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + 'oidc.circleci.com/vcs-origin': 'github.com/owner/repo', + }, + } + + const options = TrustCircleCI.bodyToOptions(body) + + t.equal(options.contextIds, undefined, 'contextIds should be undefined') + t.end() +}) + +t.test('optionsToBody with all fields', t => { + const TrustCircleCI = require('../../../../lib/commands/trust/circleci.js') + + const options = { + orgId: '550e8400-e29b-41d4-a716-446655440000', + projectId: '7c9e6679-7425-40de-944b-e07fc1f90ae7', + pipelineDefinitionId: '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + vcsOrigin: 'github.com/owner/repo', + contextIds: ['123e4567-e89b-12d3-a456-426614174000'], + } + + const body = TrustCircleCI.optionsToBody(options) + + t.equal(body.type, 'circleci', 'type should be circleci') + t.equal(body.claims['oidc.circleci.com/org-id'], '550e8400-e29b-41d4-a716-446655440000', 'org-id should be set') + t.equal(body.claims['oidc.circleci.com/project-id'], '7c9e6679-7425-40de-944b-e07fc1f90ae7', 'project-id should be set') + t.equal(body.claims['oidc.circleci.com/pipeline-definition-id'], '6ba7b810-9dad-11d1-80b4-00c04fd430c8', 'pipeline-definition-id should be set') + t.equal(body.claims['oidc.circleci.com/vcs-origin'], 'github.com/owner/repo', 'vcs-origin should be set') + t.same(body.claims['oidc.circleci.com/context-ids'], ['123e4567-e89b-12d3-a456-426614174000'], 'context-ids should be set') + t.end() +}) + +t.test('optionsToBody without optional contextIds', t => { + const TrustCircleCI = require('../../../../lib/commands/trust/circleci.js') + + const options = { + orgId: '550e8400-e29b-41d4-a716-446655440000', + projectId: '7c9e6679-7425-40de-944b-e07fc1f90ae7', + pipelineDefinitionId: '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + vcsOrigin: 'github.com/owner/repo', + } + + const body = TrustCircleCI.optionsToBody(options) + + t.equal(body.claims['oidc.circleci.com/context-ids'], undefined, 'context-ids should be undefined') + t.end() +}) + +t.test('optionsToBody with multiple contextIds', t => { + const TrustCircleCI = require('../../../../lib/commands/trust/circleci.js') + + const options = { + orgId: '550e8400-e29b-41d4-a716-446655440000', + projectId: '7c9e6679-7425-40de-944b-e07fc1f90ae7', + pipelineDefinitionId: '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + vcsOrigin: 'github.com/owner/repo', + contextIds: [ + '123e4567-e89b-12d3-a456-426614174000', + 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', + ], + } + + const body = TrustCircleCI.optionsToBody(options) + + t.same(body.claims['oidc.circleci.com/context-ids'], [ + '123e4567-e89b-12d3-a456-426614174000', + 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', + ], 'context-ids should contain both UUIDs') + t.end() +}) + +t.test('getVcsOriginUrl generates correct URL', t => { + const TrustCircleCI = require('../../../../lib/commands/trust/circleci.js') + + t.equal( + TrustCircleCI.prototype.getVcsOriginUrl('github.com/npm/cli'), + 'https://github.com/npm/cli', + 'should generate https URL from vcs-origin' + ) + t.equal( + TrustCircleCI.prototype.getVcsOriginUrl('bitbucket.org/owner/repo'), + 'https://bitbucket.org/owner/repo', + 'should work with bitbucket' + ) + t.equal( + TrustCircleCI.prototype.getVcsOriginUrl(null), + null, + 'should return null for null input' + ) + t.equal( + TrustCircleCI.prototype.getVcsOriginUrl(undefined), + null, + 'should return null for undefined input' + ) + t.end() +}) diff --git a/test/lib/commands/trust/github.js b/test/lib/commands/trust/github.js new file mode 100644 index 0000000000000..6cc65bff354d0 --- /dev/null +++ b/test/lib/commands/trust/github.js @@ -0,0 +1,153 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../../../fixtures/mock-npm.js') +const MockRegistry = require('@npmcli/mock-registry') +const realProcLog = require('proc-log') + +const packageName = '@npmcli/test-package' + +t.test('github with all options provided', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'y', + }, + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', ['github', packageName, '--yes', '--file', 'workflow.yml', '--repository', 'owner/repo', '--environment', 'production', '--allow-publish']) +}) + +t.test('github with invalid repository format', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'y', + }, + }, + }, + }) + + await t.rejects( + npm.exec('trust', ['github', packageName, '--yes', '--file', 'workflow.yml', '--repository', 'invalid', '--allow-publish']), + { message: /must be specified in the format owner\/repository/ } + ) +}) + +t.test('github with file as path', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'y', + }, + }, + }, + }) + + await t.rejects( + npm.exec('trust', ['github', packageName, '--yes', '--file', '.github/workflows/ci.yml', '--repository', 'owner/repo', '--allow-publish']), + { message: /must be just a file not a path/ } + ) +}) + +t.test('github without environment', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'y', + }, + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', ['github', packageName, '--yes', '--file', 'workflow.yml', '--repository', 'owner/repo', '--allow-publish']) +}) + +t.test('bodyToOptions with all fields', t => { + const TrustGitHub = require('../../../../lib/commands/trust/github.js') + + const body = { + id: 'test-id', + type: 'github', + claims: { + repository: 'owner/repo', + workflow_ref: { + file: 'test.yml', + }, + environment: 'prod', + }, + } + + const options = TrustGitHub.bodyToOptions(body) + + t.equal(options.id, 'test-id', 'id should be set') + t.equal(options.type, 'github', 'type should be set') + t.equal(options.file, 'test.yml', 'file should be set') + t.equal(options.repository, 'owner/repo', 'repository should be set') + t.equal(options.environment, 'prod', 'environment should be set') + t.end() +}) diff --git a/test/lib/commands/trust/gitlab.js b/test/lib/commands/trust/gitlab.js new file mode 100644 index 0000000000000..16f3804f97896 --- /dev/null +++ b/test/lib/commands/trust/gitlab.js @@ -0,0 +1,153 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../../../fixtures/mock-npm.js') +const MockRegistry = require('@npmcli/mock-registry') +const realProcLog = require('proc-log') + +const packageName = '@npmcli/test-package' + +t.test('gitlab with all options provided', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'y', + }, + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', ['gitlab', packageName, '--yes', '--file', '.gitlab-ci.yml', '--project', 'group/subgroup/repo', '--environment', 'production', '--allow-publish']) +}) + +t.test('gitlab with invalid project format', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'y', + }, + }, + }, + }) + + await t.rejects( + npm.exec('trust', ['gitlab', packageName, '--yes', '--file', '.gitlab-ci.yml', '--project', 'invalid', '--allow-publish']), + { message: /must be specified in the format/ } + ) +}) + +t.test('gitlab with file as path', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'y', + }, + }, + }, + }) + + await t.rejects( + npm.exec('trust', ['gitlab', packageName, '--yes', '--file', '.gitlab/ci.yml', '--project', 'group/repo', '--allow-publish']), + { message: /must be just a file not a path/ } + ) +}) + +t.test('gitlab without environment', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'y', + }, + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', ['gitlab', packageName, '--yes', '--file', '.gitlab-ci.yml', '--project', 'group/repo', '--allow-publish']) +}) + +t.test('bodyToOptions with all fields', t => { + const TrustGitLab = require('../../../../lib/commands/trust/gitlab.js') + + const body = { + id: 'test-id', + type: 'gitlab', + claims: { + project_path: 'group/repo', + ci_config_ref_uri: { + file: '.gitlab-ci.yml', + }, + environment: 'prod', + }, + } + + const options = TrustGitLab.bodyToOptions(body) + + t.equal(options.id, 'test-id', 'id should be set') + t.equal(options.type, 'gitlab', 'type should be set') + t.equal(options.file, '.gitlab-ci.yml', 'file should be set') + t.equal(options.project, 'group/repo', 'project should be set') + t.equal(options.environment, 'prod', 'environment should be set') + t.end() +}) diff --git a/test/lib/commands/trust/list.js b/test/lib/commands/trust/list.js new file mode 100644 index 0000000000000..8a66f390aaa31 --- /dev/null +++ b/test/lib/commands/trust/list.js @@ -0,0 +1,294 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../../../fixtures/mock-npm.js') +const MockRegistry = require('@npmcli/mock-registry') + +const packageName = '@npmcli/test-package' + +t.test('list with package name argument', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustConfigs = [ + { + id: 'test-id-1', + type: 'github', + claims: { + repository: 'owner/repo', + workflow_ref: { + file: 'test.yml', + }, + }, + environment: 'production', + }, + { + id: 'test-id-2', + type: 'gitlab', + claims: { + project_id: '12345', + ref_path: 'refs/heads/main', + pipeline_source: 'push', + }, + }, + ] + + registry.trustList({ packageName, body: trustConfigs }) + + await npm.exec('trust', ['list', packageName]) +}) + +t.test('list without package name (uses package.json)', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustConfigs = [ + { + id: 'test-id-1', + type: 'github', + claims: { + repository: 'owner/repo', + workflow_ref: { + file: 'workflow.yml', + }, + }, + }, + ] + + registry.trustList({ packageName, body: trustConfigs }) + + await npm.exec('trust', ['list']) +}) + +t.test('list with no trust configurations', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustList({ packageName, body: [] }) + + await npm.exec('trust', ['list', packageName]) +}) + +t.test('list without package name and no package.json', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: {}, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', ['list']), + { message: /Package name must be specified either as an argument or in the package\.json file/ } + ) +}) + +t.test('list without package name and no name in package.json', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', ['list']), + { message: /Package name must be specified either as an argument or in the package\.json file/ } + ) +}) + +t.test('list with --json flag', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + json: true, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustConfigs = [ + { + id: 'test-id-1', + type: 'github', + claims: { + repository: 'owner/repo', + workflow_ref: { + file: 'test.yml', + }, + }, + environment: 'production', + }, + ] + + registry.trustList({ packageName, body: trustConfigs }) + + await npm.exec('trust', ['list', packageName]) +}) + +t.test('list with scoped package', async t => { + const scopedPackage = '@scope/package' + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: scopedPackage, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustConfigs = [ + { + id: 'test-id-1', + type: 'github', + claims: { + repository: 'owner/repo', + workflow_ref: { + file: 'test.yml', + }, + }, + }, + ] + + registry.trustList({ packageName: scopedPackage, body: trustConfigs }) + + await npm.exec('trust', ['list', scopedPackage]) +}) + +t.test('list with circleci trust type', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustConfigs = [ + { + id: 'test-id-1', + type: 'circleci', + claims: { + 'oidc.circleci.com/org-id': '550e8400-e29b-41d4-a716-446655440000', + 'oidc.circleci.com/project-id': '7c9e6679-7425-40de-944b-e07fc1f90ae7', + 'oidc.circleci.com/pipeline-definition-id': '6ba7b810-9dad-11d1-80b4-00c04fd430c8', + 'oidc.circleci.com/vcs-origin': 'github.com/owner/repo', + 'oidc.circleci.com/context-ids': ['123e4567-e89b-12d3-a456-426614174000'], + }, + }, + ] + + registry.trustList({ packageName, body: trustConfigs }) + + await npm.exec('trust', ['list', packageName]) +}) + +t.test('list with unknown trust type', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustConfigs = [ + { + id: 'test-id-1', + type: 'unknown-type', + claims: { + custom: 'value', + }, + }, + ] + + registry.trustList({ packageName, body: trustConfigs }) + + await npm.exec('trust', ['list', packageName]) +}) diff --git a/test/lib/commands/trust/revoke.js b/test/lib/commands/trust/revoke.js new file mode 100644 index 0000000000000..d44d576664c86 --- /dev/null +++ b/test/lib/commands/trust/revoke.js @@ -0,0 +1,319 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../../../fixtures/mock-npm.js') +const MockRegistry = require('@npmcli/mock-registry') + +const packageName = '@npmcli/test-package' + +t.test('revoke with package name argument and id', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustId = 'test-id-1' + registry.trustRevoke({ packageName, id: trustId }) + + await npm.exec('trust', ['revoke', packageName, '--id', trustId]) +}) + +t.test('revoke without package name (uses package.json)', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustId = 'test-id-2' + registry.trustRevoke({ packageName, id: trustId }) + + await npm.exec('trust', ['revoke', '--id', trustId]) +}) + +t.test('revoke with dry-run flag', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + 'dry-run': true, + }, + }) + + // No registry mock needed since dry-run should not make network requests + const trustId = 'test-id-3' + + await npm.exec('trust', ['revoke', packageName, '--id', trustId]) +}) + +t.test('revoke without package name and no package.json', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: {}, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', ['revoke', '--id', 'test-id']), + { message: /Package name must be specified either as an argument or in the package\.json file/ } + ) +}) + +t.test('revoke without package name and no name in package.json', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', ['revoke', '--id', 'test-id']), + { message: /Package name must be specified either as an argument or in the package\.json file/ } + ) +}) + +t.test('revoke without id flag', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', ['revoke', packageName]), + { message: /ID of the trusted relationship to revoke must be specified with the --id option/ } + ) +}) + +t.test('revoke with scoped package', async t => { + const scopedPackage = '@scope/package' + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: scopedPackage, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustId = 'test-id-scoped' + registry.trustRevoke({ packageName: scopedPackage, id: trustId }) + + await npm.exec('trust', ['revoke', scopedPackage, '--id', trustId]) +}) + +t.test('revoke with special characters in id', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustId = 'test-id/with:special@chars' + registry.trustRevoke({ packageName, id: trustId }) + + await npm.exec('trust', ['revoke', packageName, '--id', trustId]) +}) + +t.test('revoke with 404 response', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustId = 'non-existent-id' + registry.trustRevoke({ + packageName, + id: trustId, + responseCode: 404, + body: { error: 'Not Found' }, + }) + + await t.rejects( + npm.exec('trust', ['revoke', packageName, '--id', trustId]), + { statusCode: 404 } + ) +}) + +t.test('revoke with 500 response', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustId = 'test-id-error' + registry.trustRevoke({ + packageName, + id: trustId, + responseCode: 500, + body: { error: 'Internal Server Error' }, + }) + + await t.rejects( + npm.exec('trust', ['revoke', packageName, '--id', trustId]), + { statusCode: 500 } + ) +}) + +t.test('revoke with unscoped package name', async t => { + const unscopedPackage = 'test-package' + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: unscopedPackage, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustId = 'test-id-unscoped' + registry.trustRevoke({ packageName: unscopedPackage, id: trustId }) + + await npm.exec('trust', ['revoke', unscopedPackage, '--id', trustId]) +}) + +t.test('revoke with very long id', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustId = 'a'.repeat(100) + registry.trustRevoke({ packageName, id: trustId }) + + await npm.exec('trust', ['revoke', packageName, '--id', trustId]) +}) + +t.test('revoke with UUID id format', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + const trustId = '550e8400-e29b-41d4-a716-446655440000' + registry.trustRevoke({ packageName, id: trustId }) + + await npm.exec('trust', ['revoke', packageName, '--id', trustId]) +}) diff --git a/test/lib/commands/undeprecate.js b/test/lib/commands/undeprecate.js new file mode 100644 index 0000000000000..775a2183a1299 --- /dev/null +++ b/test/lib/commands/undeprecate.js @@ -0,0 +1,72 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../../fixtures/mock-npm') + +const MockRegistry = require('@npmcli/mock-registry') + +const token = 'test-auth-token' +const auth = { '//registry.npmjs.org/:_authToken': token } +const versions = ['1.0.0', '1.0.1', '1.0.1-pre'] + +t.test('no args', async t => { + const { npm } = await loadMockNpm(t) + await t.rejects( + npm.exec('undeprecate', []), + { code: 'EUSAGE' }, + 'logs usage' + ) +}) + +t.test('undeprecate', async t => { + const { npm, logs, joinedOutput } = await loadMockNpm(t, { config: { ...auth } }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + const manifest = registry.manifest({ + name: 'foo', + versions, + }) + await registry.package({ manifest, query: { write: true } }) + registry.nock.put('/foo', body => { + for (const version of versions) { + if (body.versions[version].deprecated !== '') { + return false + } + } + return true + }).reply(200, {}) + + await npm.exec('undeprecate', ['foo']) + t.match(logs.notice, [ + 'undeprecating foo@1.0.0', + 'undeprecating foo@1.0.1', + 'undeprecating foo@1.0.1-pre', + ]) + t.match(joinedOutput(), '') +}) + +t.test('dry-run', async t => { + const { npm, logs, joinedOutput } = await loadMockNpm(t, { config: { + 'dry-run': true, + ...auth, + } }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: token, + }) + const manifest = registry.manifest({ + name: 'foo', + versions, + }) + await registry.package({ manifest, query: { write: true } }) + + await npm.exec('undeprecate', ['foo']) + t.match(logs.notice, [ + 'undeprecating foo@1.0.0', + 'undeprecating foo@1.0.1', + 'undeprecating foo@1.0.1-pre', + ]) + t.match(joinedOutput(), '') +}) diff --git a/test/lib/commands/uninstall.js b/test/lib/commands/uninstall.js index a1ef1745d0f55..049bf2da8b1c3 100644 --- a/test/lib/commands/uninstall.js +++ b/test/lib/commands/uninstall.js @@ -200,3 +200,44 @@ t.test('non ENOENT error reading from localPrefix package.json', async t => { 'should throw non ENOENT error' ) }) + +t.test('completion', async t => { + const { uninstall } = await _mockNpm(t, { + command: 'uninstall', + prefixDir: { + node_modules: { + foo: {}, + bar: {}, + }, + }, + }) + const res = await uninstall.completion({ conf: { argv: { remain: ['npm', 'uninstall'] } } }) + t.match(res, ['bar', 'foo']) +}) + +t.test('uninstall threads allowScripts policy through to arborist', async t => { + let capturedOpts + const FakeArborist = function (opts) { + capturedOpts = opts + this.options = opts + this.actualTree = { inventory: new Map() } + } + FakeArborist.prototype.reify = async () => {} + + const { npm } = await _mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + allowScripts: { canvas: true }, + }), + }, + mocks: { + '@npmcli/arborist': FakeArborist, + '{LIB}/utils/reify-finish.js': async () => {}, + }, + }) + await npm.exec('uninstall', ['canvas']) + t.strictSame(capturedOpts.allowScripts, { canvas: true }, + 'opts.allowScripts populated from package.json') +}) diff --git a/test/lib/commands/unpublish.js b/test/lib/commands/unpublish.js index 31dc77ea46cd0..4c8bc5e058afa 100644 --- a/test/lib/commands/unpublish.js +++ b/test/lib/commands/unpublish.js @@ -380,7 +380,7 @@ t.test('dryRun with no args', async t => { t.test('publishConfig no spec', async t => { const alternateRegistry = 'https://other.registry.npmjs.org' - const { joinedOutput, npm } = await loadMockNpm(t, { + const { logs, joinedOutput, npm } = await loadMockNpm(t, { config: { force: true, '//other.registry.npmjs.org/:_authToken': 'test-other-token', @@ -390,6 +390,7 @@ t.test('publishConfig no spec', async t => { name: pkg, version: '1.0.0', publishConfig: { + other: 'not defined', registry: alternateRegistry, }, }, null, 2), @@ -406,6 +407,10 @@ t.test('publishConfig no spec', async t => { registry.unpublish({ manifest }) await npm.exec('unpublish', []) t.equal(joinedOutput(), '- test-package') + t.same(logs.warn, [ + 'using --force Recommended protections disabled.', + 'Unknown publishConfig config "other". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.', + ]) }) t.test('prioritize CLI flags over publishConfig no spec', async t => { diff --git a/test/lib/commands/unstar.js b/test/lib/commands/unstar.js deleted file mode 100644 index ee31428546d06..0000000000000 --- a/test/lib/commands/unstar.js +++ /dev/null @@ -1,62 +0,0 @@ -const t = require('tap') -const { load: loadMockNpm } = require('../../fixtures/mock-npm.js') -const MockRegistry = require('@npmcli/mock-registry') - -const pkgName = '@npmcli/test-package' -const authToken = 'test-auth-token' -const username = 'test-user' -const auth = { '//registry.npmjs.org/:_authToken': authToken } - -t.test('no args', async t => { - const { npm } = await loadMockNpm(t) - await t.rejects( - npm.exec('unstar', []), - { code: 'EUSAGE' }, - 'should throw usage error' - ) -}) - -t.test('unstar a package unicode:false', async t => { - const { npm, joinedOutput } = await loadMockNpm(t, { - config: { unicode: false, ...auth }, - }) - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), - authorization: authToken, - }) - const manifest = registry.manifest({ name: pkgName, users: { [username]: true } }) - await registry.package({ manifest, query: { write: true } }) - registry.whoami({ username }) - registry.star(manifest, {}) - - await npm.exec('unstar', [pkgName]) - t.equal( - joinedOutput(), - '( ) @npmcli/test-package', - 'should output unstarred package msg' - ) -}) - -t.test('unstar a package unicode:true', async t => { - const { npm, joinedOutput } = await loadMockNpm(t, { - config: { unicode: true, ...auth }, - }) - - const registry = new MockRegistry({ - tap: t, - registry: npm.config.get('registry'), - authorization: authToken, - }) - const manifest = registry.manifest({ name: pkgName, users: { [username]: true } }) - await registry.package({ manifest, query: { write: true } }) - registry.whoami({ username }) - registry.star(manifest, {}) - - await npm.exec('unstar', [pkgName]) - t.equal( - joinedOutput(), - '☆ @npmcli/test-package', - 'should output unstarred package msg' - ) -}) diff --git a/test/lib/commands/update.js b/test/lib/commands/update.js index e84e2c3142141..68067b8af8168 100644 --- a/test/lib/commands/update.js +++ b/test/lib/commands/update.js @@ -79,3 +79,49 @@ t.test('update --global', async t => { t.match(ctor.path, globalPrefix) t.ok(ctor.path.startsWith(globalPrefix)) }) + +t.test('completion', async t => { + const { update } = await _mockNpm(t, { + command: 'update', + prefixDir: { + node_modules: { + foo: { + 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }), + }, + }, + 'package.json': JSON.stringify({ name: 'project', version: '1.0.0' }), + }, + }) + const res = await update.completion({ conf: { argv: { remain: ['npm', 'update'] } } }) + t.type(res, Array) +}) + +t.test('update threads allowScripts policy through to arborist', async t => { + // The reify step uses the resolved policy. The advisory warning is + // emitted from reifyFinish (already covered by install.js tests), + // so here we verify the call site populates opts.allowScripts. + let capturedOpts + const FakeArborist = function (opts) { + capturedOpts = opts + this.options = opts + this.actualTree = { inventory: new Map() } + } + FakeArborist.prototype.reify = async function () {} + + const mock = await _mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + allowScripts: { canvas: true }, + }), + }, + mocks: { + '@npmcli/arborist': FakeArborist, + '{LIB}/utils/reify-finish.js': async () => {}, + }, + }) + await mock.npm.exec('update', []) + t.strictSame(capturedOpts.allowScripts, { canvas: true }, + 'opts.allowScripts populated from package.json') +}) diff --git a/test/lib/commands/view.js b/test/lib/commands/view.js index 5da9182ddd55e..dbf4560bf46ab 100644 --- a/test/lib/commands/view.js +++ b/test/lib/commands/view.js @@ -36,10 +36,25 @@ const packument = (nv, opts) => { _id: 'blue', name: 'blue', 'dist-tags': { + v1: '1.0.0', + next: '1.0.1', + prev: '1.0.0', latest: '1.0.0', + a: '1.0.0', + c: '1.0.0', + b: '1.0.0', + d: '1.0.0', + f: '1.0.1', + g: '1.0.1', + h: '1.0.1', + e: '1.0.1', + z: '1.0.0', + x: '1.0.1', + y: '1.0.0', }, time: { '1.0.0': yesterday, + '1.0.1': '2012-12-20T00:00:00.000Z', }, versions: { '1.0.0': { @@ -64,6 +79,29 @@ const packument = (nv, opts) => { }, }, }, + // package with no time attribute + gray: { + _id: 'gray', + name: 'gray', + 'dist-tags': { + latest: '1.1.0', + beta: '1.2.0-beta', + alpha: '1.2.0-alpha', + old: '1.0.0', + stable: '1.1.0', + }, + versions: { + '1.1.0': { + name: 'gray', + version: '1.1.0', + dist: { + shasum: 'b', + tarball: 'http://gray/1.1.0.tgz', + fileCount: 1, + }, + }, + }, + }, cyan: { _npmUser: { name: 'claudia', @@ -88,6 +126,34 @@ const packument = (nv, opts) => { '1.0.1': {}, }, }, + 'cyan-oidc': { + _npmUser: { + name: 'claudia', + email: 'claudia@cyan.com', + trustedPublisher: { + id: 'github', + oidcConfigId: 'oidc:a0e127d0-8d66-45d0-8264-e4f8372c7249', + }, + }, + name: 'cyan', + 'dist-tags': { + latest: '1.0.0', + }, + versions: { + '1.0.0': { + version: '1.0.0', + name: 'cyan', + dist: { + shasum: '123', + tarball: 'http://hm.cyan.com/1.0.0.tgz', + integrity: '---', + fileCount: 1, + unpackedSize: 1000000, + }, + }, + '1.0.1': {}, + }, + }, brown: { name: 'brown', }, @@ -312,7 +378,7 @@ const packument = (nv, opts) => { } const loadMockNpm = async function (t, opts = {}) { - const mockNpm = await _loadMockNpm(t, { + return _loadMockNpm(t, { command: 'view', mocks: { pacote: { @@ -325,11 +391,12 @@ const loadMockNpm = async function (t, opts = {}) { ...opts.config, }, }) - return mockNpm } t.test('package from git', async t => { - const { view, joinedOutput } = await loadMockNpm(t, { config: { unicode: false } }) + const { view, joinedOutput } = await loadMockNpm(t, { + config: { unicode: false, 'allow-git': 'all' }, + }) await view.exec(['https://github.com/npm/green']) t.matchSnapshot(joinedOutput()) }) @@ -400,6 +467,35 @@ t.test('package with --json and semver range', async t => { t.matchSnapshot(joinedOutput()) }) +t.test('package with --json and single-match semver range preserves array output', async t => { + const { view, joinedOutput } = await loadMockNpm(t, { config: { json: true } }) + await view.exec(['single-version@^1']) + const parsed = JSON.parse(joinedOutput()) + t.ok(Array.isArray(parsed), 'preserves the top-level array for semver ranges') + t.equal(parsed.length, 1, 'returns the single matching version in an array') + t.match(parsed[0], { + name: 'single-version', + version: '1.0.0', + dist: { + shasum: '123', + tarball: 'http://hm.single-version.com/1.0.0.tgz', + fileCount: 1, + }, + }, 'returns the expected package data') +}) + +t.test('package field with --json and single-match semver range preserves array output', async t => { + const { view, joinedOutput } = await loadMockNpm(t, { config: { json: true } }) + await view.exec(['single-version@^1', 'version']) + t.strictSame(JSON.parse(joinedOutput()), ['1.0.0'], 'does not unwrap single field matches for semver ranges') +}) + +t.test('package with _npmUser.trustedPublisher shows cleaned up property with --json', async t => { + const { view, joinedOutput } = await loadMockNpm(t, { config: { json: true } }) + await view.exec(['cyan-oidc@^1.0.0']) + t.match(joinedOutput(), /claudia /, 'uses oidc trustedPublisher info for _npmUser') +}) + t.test('package with --json and no versions', async t => { const { view, joinedOutput } = await loadMockNpm(t, { config: { json: true } }) await view.exec(['brown']) @@ -409,7 +505,7 @@ t.test('package with --json and no versions', async t => { t.test('package with --json and single string arg', async t => { const { view, joinedOutput } = await loadMockNpm(t, { config: { json: true } }) await view.exec(['blue', 'dist-tags.latest']) - t.equal(JSON.parse(joinedOutput()), '1.0.0', 'no info to display') + t.strictSame(JSON.parse(joinedOutput()), ['1.0.0'], 'returns single string value as array') }) t.test('package with single version', async t => { @@ -423,7 +519,7 @@ t.test('package with single version', async t => { const { view, joinedOutput } = await loadMockNpm(t, { config: { json: true } }) await view.exec(['single-version', 'versions']) const parsed = JSON.parse(joinedOutput()) - t.strictSame(parsed, ['1.0.0'], 'does not unwrap single item arrays in json') + t.strictSame(parsed, [['1.0.0']], 'does not unwrap single item arrays in json') }) t.test('no json and versions arg', async t => { @@ -754,3 +850,18 @@ t.test('no package completion', async t => { t.notOk(res, 'there is no package completion') t.end() }) + +t.test('allow-git=root, package with multiple dist‑tags and no time', async t => { + const { view, joinedOutput } = await loadMockNpm(t, { config: { unicode: false, 'allow-git': 'root' } }) + await view.exec(['https://github.com/npm/gray']) + t.matchSnapshot(joinedOutput()) +}) + +t.test('allow-git=none', async t => { + const { view } = await loadMockNpm(t, { config: { 'allow-git': 'none' }, mocks: {} }) + await t.rejects(view.exec(['npm/npm']), { + code: 'EALLOWGIT', + package: 'github:npm/npm', + message: 'Fetching packages of type "git" have been disabled', + }) +}) diff --git a/test/lib/docs.js b/test/lib/docs.js index 833e58831ea51..4b4a438997f15 100644 --- a/test/lib/docs.js +++ b/test/lib/docs.js @@ -90,16 +90,27 @@ t.test('basic usage', async t => { t.test('usage', async t => { const readdir = async (dir, ext) => { - const files = await fs.readdir(dir) - return files.filter(f => extname(f) === ext).map(f => basename(f, ext)) + const files = await fs.readdir(dir, { withFileTypes: true }) + return files + .filter(f => { + // Include .js files + if (f.isFile() && extname(f.name) === ext) { + return true + } + // Include directories (which should have an index.js) + if (f.isDirectory()) { + return true + } + return false + }) + .map(f => f.isDirectory() ? f.name : basename(f.name, ext)) } const fsCommands = await readdir(resolve(__dirname, '../../lib/commands'), '.js') const docsCommands = await readdir(join(docs.paths.content, 'commands'), docs.DOC_EXT) const bareCommands = ['npm', 'npx'] - // XXX: These extra commands exist as js files but not as docs pages - const allDocs = docsCommands.concat(['get', 'set', 'll']).map(n => n.replace('npm-', '')) + const allDocs = docsCommands.map(n => n.replace('npm-', '')) // ensure that the list of js files in commands, docs files, and the command list // are all in sync. eg, this will error if a command is removed but not its docs file @@ -125,7 +136,7 @@ t.test('usage', async t => { } const usage = docs.usage(docs.TAGS.USAGE, { path: cmd }) - const params = docs.params(docs.TAGS.CONFIG, { path: cmd }) + const params = docs.definitions(docs.TAGS.CONFIG, { path: cmd }) .split('\n') .filter(l => l.startsWith('#### ')) .join('\n') || 'NO PARAMS' diff --git a/test/lib/lifecycle-cmd.js b/test/lib/lifecycle-cmd.js index c2701931cac6e..010746d02f283 100644 --- a/test/lib/lifecycle-cmd.js +++ b/test/lib/lifecycle-cmd.js @@ -6,7 +6,7 @@ t.test('create a lifecycle command', async t => { let runArgs = null const { npm } = await mockNpm(t) npm.exec = async (cmd, args) => { - if (cmd === 'run-script') { + if (cmd === 'run') { runArgs = args return 'called the right thing' } diff --git a/test/lib/load-all-commands.js b/test/lib/load-all-commands.js index 892dd466ac5c4..454dcf984fb91 100644 --- a/test/lib/load-all-commands.js +++ b/test/lib/load-all-commands.js @@ -1,4 +1,4 @@ -// Our coverage mapping means that stuff like this doen't count for coverage. +// Our coverage mapping means that stuff like this doesn't count for coverage. // It does ensure that every command has a usage that renders, contains its // name, a description, and if it has completion it is a function. That it // renders also ensures that any params we've defined in our commands work. @@ -37,7 +37,7 @@ t.test('load each command', async t => { t.ok(impl.exec.length <= 1, 'exec fn has 0 or 1 args') // workspaces - t.type(ctor.ignoreImplicitWorkspace, 'boolean', 'ctor has ignoreImplictWorkspace boolean') + t.type(ctor.ignoreImplicitWorkspace, 'boolean', 'ctor has ignoreImplicitWorkspace boolean') if (ctor.ignoreImplicitWorkspace !== BaseCommand.ignoreImplicitWorkspace) { counts.ignoreImplicitWorkspace++ } @@ -78,7 +78,7 @@ t.test('load each command', async t => { }) } - // make sure refactors dont move or rename these static properties since + // make sure refactors don't move or rename these static properties since // we guard against the tests for them above t.ok(counts.completion > 0, 'has some completion functions') t.ok(counts.ignoreImplicitWorkspace > 0, 'has some commands that change ignoreImplicitWorkspace') diff --git a/test/lib/npm.js b/test/lib/npm.js index 00ef3f79b04c1..0957baa499fa0 100644 --- a/test/lib/npm.js +++ b/test/lib/npm.js @@ -1,6 +1,6 @@ const t = require('tap') -const { resolve, dirname, join } = require('node:path') -const fs = require('node:fs') +const { resolve, join } = require('node:path') +const fs = require('node:fs/promises') const { time } = require('proc-log') const { load: loadMockNpm } = require('../fixtures/mock-npm.js') const mockGlobals = require('@npmcli/mock-globals') @@ -35,6 +35,26 @@ t.test('npm.load', async t => { ) }) + await t.test('rejects extension-file from a disallowed config source', async t => { + const { npm } = await loadMockNpm(t, { load: false }) + // a disallowed (env) source; mockGlobals restores process.env on teardown + mockGlobals(t, { 'process.env.npm_config_extension_file': 'tools/ext.mjs' }) + await t.rejects( + () => npm.load(), + { code: 'ENPMEXTENSIONCONFIG' }, + 'env config source is rejected with a surfaced error' + ) + }) + + await t.test('accepts extension-file from project config', async t => { + // config.load() exports npm_config_* to the real env, so clean it up to avoid leaking into raw-env tests + t.teardown(() => delete process.env.npm_config_extension_file) + const { npm } = await loadMockNpm(t, { + prefixDir: { '.npmrc': 'extension-file=tools/ext.mjs' }, + }) + t.equal(npm.config.find('extension-file'), 'project', 'loaded from project config without error') + }) + await t.test('basic loading', async t => { const { npm, logs, cache } = await loadMockNpm(t, { prefixDir: { node_modules: {} }, @@ -88,73 +108,6 @@ t.test('npm.load', async t => { ]) }) - await t.test('node is a symlink', async t => { - const node = process.platform === 'win32' ? 'node.exe' : 'node' - const { Npm, npm, logs, outputs, prefix } = await loadMockNpm(t, { - prefixDir: { - bin: t.fixture('symlink', dirname(process.execPath)), - }, - config: { - timing: true, - usage: '', - scope: 'foo', - }, - argv: [ - 'token', - 'revoke', - 'blergggg', - ], - globals: (dirs) => ({ - 'process.env.PATH': resolve(dirs.prefix, 'bin'), - 'process.argv': [ - node, - process.argv[1], - ], - }), - }) - - t.equal(npm.config.get('scope'), '@foo', 'added the @ sign to scope') - - t.match([ - ...logs.timing.filter((p) => p.startsWith('npm:load:whichnode')), - ...logs.verbose, - ...logs.timing.filter((p) => p.startsWith('npm:load')), - ], [ - /npm:load:whichnode Completed in [0-9.]+ms/, - `node symlink ${resolve(prefix, 'bin', node)}`, - /title npm token revoke blergggg/, - /argv "token" "revoke" "blergggg".*"--usage" "--scope" "foo"/, - /logfile logs-max:\d+ dir:.*/, - /logfile .*-debug-0.log/, - /npm:load:.* Completed in [0-9.]+ms/, - ]) - t.equal(process.execPath, resolve(prefix, 'bin', node)) - - outputs.length = 0 - logs.length = 0 - await npm.exec('ll', []) - - t.equal(npm.command, 'll', 'command set to first npm command') - t.equal(npm.flatOptions.npmCommand, 'll', 'npmCommand flatOption set') - - const ll = Npm.cmd('ll') - t.same(outputs, [ll.describeUsage], 'print usage') - npm.config.set('usage', false) - - outputs.length = 0 - logs.length = 0 - await npm.exec('get', ['scope', 'usage']) - - t.strictSame([npm.command, npm.flatOptions.npmCommand], ['ll', 'll'], - 'does not change npm.command when another command is called') - - t.match(logs, [ - /timing command:config Completed in [0-9.]+ms/, - /timing command:get Completed in [0-9.]+ms/, - ]) - t.same(outputs, ['scope=@foo\nusage=false']) - }) - await t.test('--no-workspaces with --workspace', async t => { const { npm } = await loadMockNpm(t, { prefixDir: { @@ -180,7 +133,7 @@ t.test('npm.load', async t => { }) await t.rejects( npm.exec('run', []), - /Can not use --no-workspaces and --workspace at the same time/ + /Cannot use --no-workspaces and --workspace at the same time/ ) }) @@ -214,9 +167,9 @@ t.test('npm.load', async t => { }, }) - await npm.exec('run', []) + await npm.exec('run-script', []) - t.equal(npm.command, 'run-script', 'npm.command set to canonical name') + t.equal(npm.command, 'run', 'npm.command set to canonical name') t.matchSnapshot(joinedOutput(), 'should exec workspaces version of commands') }) @@ -327,11 +280,11 @@ t.test('debug log', async t => { const logsDir = join(testdir, 'my_logs_dir') // make logs dir a file before load so it files - fs.writeFileSync(logsDir, 'A_TEXT_FILE') + await fs.writeFile(logsDir, 'A_TEXT_FILE') await t.resolves(npm.load(), 'loads with invalid logs dir') t.equal(npm.logFiles.length, 0, 'no log files array') - t.strictSame(fs.readFileSync(logsDir, 'utf-8'), 'A_TEXT_FILE') + t.strictSame(await fs.readFile(logsDir, 'utf-8'), 'A_TEXT_FILE') }) }) @@ -339,7 +292,7 @@ t.test('cache dir', async t => { t.test('creates a cache dir', async t => { const { npm } = await loadMockNpm(t) - t.ok(fs.existsSync(npm.cache), 'cache dir exists') + await t.resolves(fs.access(npm.cache), 'cache dir exists') }) t.test('can load with a bad cache dir', async t => { @@ -352,7 +305,7 @@ t.test('cache dir', async t => { await t.resolves(npm.load(), 'loads with cache dir as a file') - t.equal(fs.readFileSync(cache, 'utf-8'), 'A_TEXT_FILE') + t.equal(await fs.readFile(cache, 'utf-8'), 'A_TEXT_FILE') }) }) @@ -497,6 +450,233 @@ t.test('implicit workspace accept', async t => { await t.rejects(mock.npm.exec('org', []), /.*Usage/) }) +t.test('subcommand handling', async t => { + t.test('no subcommand provided', async t => { + const { npm } = await loadMockNpm(t) + await t.rejects( + npm.exec('trust', []), + /Usage/, + 'throws usage error when no subcommand provided' + ) + }) + + t.test('unknown subcommand', async t => { + const { npm } = await loadMockNpm(t) + await t.rejects( + npm.exec('trust', ['unknown-subcommand']), + /Unknown subcommand: unknown-subcommand/, + 'throws error for unknown subcommand' + ) + }) + + t.test('subcommand help with --usage', async t => { + const { npm, outputs } = await loadMockNpm(t, { + config: { + usage: true, + }, + }) + await npm.exec('trust', ['github']) + t.ok(outputs.length > 0, 'outputs help text') + // Check if output was generated - the format may be different + t.ok(outputs.some(o => o && o[0]), 'has output content') + }) +}) + +t.test('exec edge cases', async t => { + t.test('command calls exec again - covers else branch at line 207', async t => { + const { npm, outputs } = await loadMockNpm(t) + // 'get' command calls npm.exec('config', ['get', ...]) internally + // The first exec() sets #command, then when it re-enters exec(), + // the else branch (line 217) is taken because #command is already set + await npm.exec('get', ['registry']) + t.ok(outputs.length > 0, 'command executed and produced output') + }) + + t.test('exec without args parameter - covers default args branch', async t => { + const Npm = require('../../lib/npm.js') + const npm = new Npm() + await npm.load() + npm.argv = ['test'] + // Call exec without second parameter - should use default args = this.argv + await npm.exec('run') + t.pass('exec called without second argument') + }) + + t.test('--versions flag sets argv to version', async t => { + const { npm } = await loadMockNpm(t, { + config: { versions: true }, + }) + t.equal(npm.argv.length, 0, 'argv is empty after version command runs') + t.equal(npm.config.get('usage'), false, 'usage is set to false') + }) + + t.test('color true sets COLOR env to 1', async t => { + await loadMockNpm(t, { + config: { color: 'always' }, + }) + t.equal(process.env.COLOR, '1', 'COLOR env is set to 1 when color is truthy') + }) + + t.test('command without subcommands', async t => { + const { npm } = await loadMockNpm(t) + // Test a command that doesn't have subcommands (line 249 branch) + await t.rejects(npm.exec('org', []), /Usage/) + }) + + t.test('command with workspaces support', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + packages: { + a: { + 'package.json': JSON.stringify({ + name: 'a', + version: '1.0.0', + scripts: { test: 'echo test' }, + }), + }, + }, + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + workspaces: ['./packages/a'], + }), + }, + config: { + workspace: ['./packages/a'], + }, + }) + // Test a command that supports workspaces to trigger execWorkspaces path (line 321) + await npm.exec('run', ['test']) + t.pass('executes with workspaces') + }) + + t.test('execCommandClass with default commandPath', async t => { + const { npm } = await loadMockNpm(t) + // Create a simple command instance + const Command = npm.constructor.cmd('version') + const commandInstance = new Command(npm) + + // Call execCommandClass without providing commandPath (using default []) + await npm.execCommandClass(commandInstance, []) + + t.pass('execCommandClass works with default commandPath parameter') + }) + + t.test('command with definitions executes exec() without workspaces', async t => { + const BaseCommand = require('../../lib/base-cmd.js') + const Definition = require('@npmcli/config/lib/definitions/definition.js') + + let execCalled = false + let execArgs = null + let execFlags = null + + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'test-pkg', + version: '1.0.0', + }), + }, + }) + + class TestCommand extends BaseCommand { + static name = 'test-cmd' + static description = 'Test command with definitions' + static workspaces = true + static definitions = [ + new Definition('testflag', { + type: String, + default: 'default-value', + description: 'A test flag', + }), + ] + + async exec (args, flags) { + execCalled = true + execArgs = args + execFlags = flags + } + + async execWorkspaces () { + throw new Error('execWorkspaces should not be called') + } + } + + const command = new TestCommand(npm) + // Set config.argv so flags() can parse the positional args + npm.config.argv = [process.argv[0], process.argv[1], 'test-cmd', 'arg1', 'arg2'] + await npm.execCommandClass(command, ['arg1', 'arg2'], ['test-cmd']) + + t.equal(execCalled, true, 'exec() was called') + t.same(execArgs, ['arg1', 'arg2'], 'positional args passed correctly') + t.ok(execFlags, 'flags object passed') + t.equal(execFlags.testflag, 'default-value', 'flag has default value') + }) + + t.test('command with definitions executes execWorkspaces() with workspaces', async t => { + const BaseCommand = require('../../lib/base-cmd.js') + const Definition = require('@npmcli/config/lib/definitions/definition.js') + + let execWorkspacesCalled = false + let execArgs = null + let execFlags = null + + const { npm } = await loadMockNpm(t, { + prefixDir: { + packages: { + a: { + 'package.json': JSON.stringify({ + name: 'workspace-a', + version: '1.0.0', + }), + }, + }, + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + workspaces: ['./packages/a'], + }), + }, + config: { + workspace: ['./packages/a'], + }, + }) + + class TestCommand extends BaseCommand { + static name = 'test-cmd' + static description = 'Test command with definitions' + static workspaces = true + static definitions = [ + new Definition('testflag', { + type: String, + default: 'ws-default', + description: 'A test flag', + }), + ] + + async exec () { + throw new Error('exec should not be called') + } + + async execWorkspaces (args, flags) { + execWorkspacesCalled = true + execArgs = args + execFlags = flags + } + } + + const command = new TestCommand(npm) + // Set config.argv so flags() can parse the positional args + npm.config.argv = [process.argv[0], process.argv[1], 'test-cmd', 'wsarg1'] + await npm.execCommandClass(command, ['wsarg1'], ['test-cmd']) + + t.equal(execWorkspacesCalled, true, 'execWorkspaces() was called') + t.same(execArgs, ['wsarg1'], 'positional args passed correctly') + t.ok(execFlags, 'flags object passed') + t.equal(execFlags.testflag, 'ws-default', 'flag has default value') + }) +}) + t.test('usage', async t => { t.test('with browser', async t => { const { npm } = await loadMockNpm(t, { globals: { process: { platform: 'posix' } } }) @@ -559,11 +739,3 @@ t.test('usage', async t => { } }) }) - -t.test('print usage if non-command param provided', async t => { - const { npm, joinedOutput } = await loadMockNpm(t) - - await t.rejects(npm.exec('tset'), { command: 'tset', exitCode: 1 }) - t.match(joinedOutput(), 'Unknown command: "tset"') - t.match(joinedOutput(), 'Did you mean this?') -}) diff --git a/test/lib/trust-cmd.js b/test/lib/trust-cmd.js new file mode 100644 index 0000000000000..57d70702818a5 --- /dev/null +++ b/test/lib/trust-cmd.js @@ -0,0 +1,943 @@ +const t = require('tap') +const { load: loadMockNpm } = require('../fixtures/mock-npm.js') +const MockRegistry = require('@npmcli/mock-registry') +const realProcLog = require('proc-log') +const TrustCommand = require('../../lib/trust-cmd.js') + +const packageName = '@npmcli/test-package' + +t.test('trust-cmd via trust github with read function called', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + read: { + read: async () => 'y', + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']) +}) + +t.test('trust-cmd via trust github with all options', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + yes: true, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli', '--environment', 'production']) +}) + +t.test('trust-cmd via trust github with --allow-stage-publish', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + yes: true, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', ['github', '--allow-stage-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']) +}) + +t.test('trust-cmd via trust github with --allow-staged-publish alias', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + yes: true, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', ['github', '--allow-staged-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']) +}) + +t.test('trust-cmd via trust github missing permissions', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + yes: true, + }, + }) + + await t.rejects( + npm.exec('trust', ['github', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']), + { message: /At least one permission flag is required/ } + ) +}) + +t.test('trust-cmd via trust github infers from package.json', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + repository: 'https://github.com/npm/cli', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'y', + }, + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', ['github', '--allow-publish', '--yes', '--file', 'workflow.yml']) +}) + +t.test('trust-cmd via trust github with dry-run', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + 'dry-run': true, + }, + }) + + await npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']) + + t.ok(joinedOutput().includes('Establishing trust'), 'shows notice about establishing trust') +}) + +t.test('trust-cmd via trust github missing package name', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: {}, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', ['github', '--allow-publish', '--file', 'workflow.yml', '--repository', 'npm/cli']), + { message: /Package name must be specified/ }, + 'throws when no package name' + ) +}) + +t.test('trust-cmd via trust github missing file', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', ['github', '--allow-publish', packageName, '--repository', 'npm/cli']), + { message: /must be specified with the file option/ }, + 'throws when no file' + ) +}) + +t.test('trust-cmd via trust github invalid file extension', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.txt', '--repository', 'npm/cli']), + { message: /must end in \.yml or \.yaml/ }, + 'throws when file has wrong extension' + ) +}) + +t.test('trust-cmd via trust github missing repository', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml']), + { message: /must be specified with repository option/ }, + 'throws when no repository' + ) +}) + +t.test('trust-cmd via trust github with custom registry warning', async t => { + const { npm, logs } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + registry: 'https://custom.registry.com/', + 'dry-run': true, + }, + }) + + await npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']) + + t.ok(logs.warn.some(l => l.includes('may not support trusted publishing')), 'warns about custom registry') +}) + +t.test('trust-cmd via trust github with --json', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + json: true, + 'dry-run': true, + }, + }) + + await npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']) + + const output = joinedOutput() + t.ok(output.includes(packageName), 'JSON output includes package name') + t.ok(output.includes('workflow.yml'), 'JSON output includes file') +}) + +t.test('trust-cmd via trust github with user confirmation no', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'n', + }, + }, + }, + }) + + await t.rejects( + npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']), + { message: 'User cancelled operation' }, + 'throws when user declines' + ) +}) + +t.test('trust-cmd via trust github with --no-yes', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + yes: false, + }, + }) + + await t.rejects( + npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']), + { message: 'User cancelled operation' }, + 'throws when --no-yes flag is set' + ) +}) + +t.test('trust-cmd via trust github with invalid answer', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'maybe', + }, + }, + }, + }) + + await t.rejects( + npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']), + { message: 'User cancelled operation' }, + 'throws when user gives invalid answer' + ) +}) + +t.test('trust-cmd via trust github with user confirmation Y uppercase', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'Y', + }, + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']) +}) + +t.test('trust-cmd via trust github with user enters empty string', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => '', + }, + }, + }, + }) + + await t.rejects( + npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']), + { message: 'User cancelled operation' }, + 'throws when user enters empty string' + ) +}) + +t.test('trust-cmd via trust github with mismatched repo type', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + repository: 'https://gitlab.com/npm/cli', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', ['github', '--allow-publish', '--file', 'workflow.yml']), + { message: /Repository in package.json is not a GitHub repository/ }, + 'throws when repository type does not match provider' + ) +}) + +t.test('trust-cmd via trust github with mismatched repo type but flag provided', async t => { + const { npm, logs } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + repository: 'https://gitlab.com/owner/old-repo', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + 'dry-run': true, + }, + }) + + await npm.exec('trust', ['github', '--allow-publish', '--file', 'workflow.yml', '--repository', 'owner/new-repo']) + + t.ok(logs.warn.some(l => l.includes('Repository in package.json is not a GitHub repository')), 'warns about repository type mismatch') +}) + +t.test('trust-cmd via trust github with different repo in package.json', async t => { + const { npm, logs } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + repository: 'https://github.com/owner/old-repo', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + 'dry-run': true, + }, + }) + + await npm.exec('trust', ['github', '--allow-publish', '--file', 'workflow.yml', '--repository', 'owner/new-repo']) + + t.ok(logs.warn.some(l => l.includes('differs from provided')), 'warns about repository mismatch') +}) + +t.test('trust-cmd via trust github with user confirmation yes spelled out', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + 'proc-log': { + ...realProcLog, + input: { + ...realProcLog.input, + read: async () => 'yes', + }, + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + await npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']) +}) + +t.test('trust-cmd via trust github showing response with id and type', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + read: { + read: async () => 'y', + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ + packageName, + body: { + id: 'config-id-123', + type: 'github', + claims: { + repository: 'npm/cli', + workflow_ref: { + file: 'workflow.yml', + }, + }, + }, + }) + + await npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']) + + const output = joinedOutput() + t.ok(output.includes('type:'), 'output shows type field') + t.ok(output.includes('id:'), 'output shows id field') +}) + +t.test('trust-cmd via trust github missing repository when package name differs', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'other-package', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + await t.rejects( + npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml']), + { message: /must be specified with repository option/ }, + 'throws when no repository and package name differs' + ) +}) + +t.test('TrustCommand - createConfig', async t => { + const { npm } = await loadMockNpm(t, { + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + class TestTrustCmd extends TrustCommand { + static name = 'test' + static description = 'Test command' + } + + const cmd = new TestTrustCmd(npm) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ packageName }) + + const response = await cmd.createConfig(packageName, [{ type: 'test' }]) + t.ok(response, 'returns a response') +}) + +t.test('TrustCommand - bodyToOptions', t => { + const body = { + id: 'test-id', + type: 'test-type', + other: 'ignored', + } + + const options = TrustCommand.bodyToOptions(body) + + t.equal(options.id, 'test-id', 'includes id') + t.equal(options.type, 'test-type', 'includes type') + t.notOk(options.other, 'does not include other fields') + t.end() +}) + +t.test('TrustCommand - bodyToOptions with missing fields', t => { + const body = {} + + const options = TrustCommand.bodyToOptions(body) + + t.same(options, {}, 'returns empty object when no fields') + t.end() +}) + +t.test('TrustCommand - NPM_FRONTEND constant', t => { + t.equal(TrustCommand.NPM_FRONTEND, 'https://www.npmjs.com', 'exports NPM_FRONTEND constant') + t.end() +}) +t.test('trust-cmd via trust github showing fromPackageJson indicator', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + repository: 'https://github.com/npm/cli', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + read: { + read: async () => 'y', + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ + packageName, + body: { + id: 'config-id-123', + type: 'github', + claims: { + repository: 'npm/cli', + workflow_ref: { + file: 'workflow.yml', + }, + }, + }, + }) + + await npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml']) + + const output = joinedOutput() + t.ok(output.includes('from package.json'), 'output shows fromPackageJson indicator') +}) + +t.test('trust-cmd via trust github showing URLs for fields', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + mocks: { + read: { + read: async () => 'y', + }, + }, + }) + + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + + registry.trustCreate({ + packageName, + body: { + id: 'config-id-123', + type: 'github', + claims: { + repository: 'npm/cli', + workflow_ref: { + file: 'workflow.yml', + }, + }, + }, + }) + + await npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']) + + const output = joinedOutput() + t.match(output, /https:\/\/github\.com\/npm\/cli\b/, 'output shows repository URL') +}) + +t.test('trust-cmd via trust github with yes=false flag', async t => { + const { npm } = await loadMockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: packageName, + version: '1.0.0', + }), + }, + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + yes: false, + }, + }) + + await t.rejects( + npm.exec('trust', ['github', '--allow-publish', packageName, '--file', 'workflow.yml', '--repository', 'npm/cli']), + { message: /User cancelled operation/ }, + 'throws when yes is explicitly false' + ) +}) + +t.test('TrustCommand - logOptions with no values', async t => { + const { npm } = await loadMockNpm(t, { + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + class TestTrustCmd extends TrustCommand { + static name = 'test' + static description = 'Test command' + } + + const cmd = new TestTrustCmd(npm) + + // Call logOptions with no values object + cmd.logOptions({}) + t.pass('logOptions handles missing values object') +}) + +t.test('TrustCommand - logOptions with falsey value', async t => { + const { npm } = await loadMockNpm(t, { + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + class TestTrustCmd extends TrustCommand { + static name = 'test' + static description = 'Test command' + } + + const cmd = new TestTrustCmd(npm) + + // Call logOptions with a falsey but not null/undefined value + cmd.logOptions({ values: { type: 'test', falseyField: 0, anotherFalsey: false, emptyString: '' } }) + t.pass('logOptions handles falsey values that are not null/undefined') +}) + +t.test('TrustCommand - logOptions with null and undefined values', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + class TestTrustCmd extends TrustCommand { + static name = 'test' + static description = 'Test command' + } + + const cmd = new TestTrustCmd(npm) + + // Call logOptions with null and undefined values that should be skipped + cmd.logOptions({ values: { type: 'test', id: 'test-id', nullField: null, undefinedField: undefined, validField: 'value' } }) + const output = joinedOutput() + t.ok(output.includes('validField'), 'shows valid field') + t.notOk(output.includes('nullField'), 'skips null field') + t.notOk(output.includes('undefinedField'), 'skips undefined field') +}) + +t.test('TrustCommand - logOptions with fromPackageJson and urls', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + class TestTrustCmd extends TrustCommand { + static name = 'test' + static description = 'Test command' + } + + const cmd = new TestTrustCmd(npm) + + // Call logOptions with fromPackageJson and urls objects + cmd.logOptions({ + values: { + type: 'github', + id: 'test-id', + repository: 'npm/cli', + file: 'workflow.yml', + }, + fromPackageJson: { + repository: true, + }, + urls: { + repository: 'https://github.com/npm/cli', + file: 'https://github.com/npm/cli/-/blob/HEAD/workflow.yml', + }, + }) + const output = joinedOutput() + t.ok(output.includes('from package.json'), 'shows fromPackageJson indicator') + t.match(output, /https:\/\/github\.com\/npm\/cli\b/, 'shows URL') +}) + +t.test('TrustCommand - logOptions with no urls', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + class TestTrustCmd extends TrustCommand { + static name = 'test' + static description = 'Test command' + } + + const cmd = new TestTrustCmd(npm) + + // Call logOptions without urls object + cmd.logOptions({ + values: { + type: 'github', + id: 'test-id', + repository: 'npm/cli', + file: 'workflow.yml', + }, + }) + const output = joinedOutput() + t.ok(output.includes('repository'), 'shows repository field') + t.ok(output.includes('file'), 'shows file field') + t.notOk(output.includes('Links to verify manually'), 'does not show links header when no urls') +}) + +t.test('TrustCommand - logOptions with urls but all values are null', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + class TestTrustCmd extends TrustCommand { + static name = 'test' + static description = 'Test command' + } + + const cmd = new TestTrustCmd(npm) + + // Call logOptions with urls object but all values are null/undefined + cmd.logOptions({ + values: { + type: 'github', + id: 'test-id', + repository: 'npm/cli', + file: 'workflow.yml', + }, + urls: { + repository: null, + file: undefined, + }, + }) + const output = joinedOutput() + t.ok(output.includes('repository'), 'shows repository field') + t.ok(output.includes('file'), 'shows file field') + t.notOk(output.includes('Links to verify manually'), 'does not show links header when all urls are null') +}) + +t.test('formatPermissions with unknown permission falls back to raw value', t => { + const result = TrustCommand.formatPermissions(['unknownPermission']) + t.equal(result, 'unknownPermission', 'returns raw value for unknown permission') + t.end() +}) + +t.test('displayResponseBody with empty body', async t => { + const { npm, joinedOutput } = await loadMockNpm(t, { + config: { + '//registry.npmjs.org/:_authToken': 'test-auth-token', + }, + }) + + class TestTrustCmd extends TrustCommand { + static name = 'test' + static description = 'Test command' + } + + const cmd = new TestTrustCmd(npm) + cmd.displayResponseBody({ body: [], packageName: '@npmcli/test-package' }) + + const output = joinedOutput() + t.match(output, /No trust configurations found/, 'shows no configurations message') +}) diff --git a/test/lib/utils/allow-scripts-writer.js b/test/lib/utils/allow-scripts-writer.js new file mode 100644 index 0000000000000..f72a84eef113b --- /dev/null +++ b/test/lib/utils/allow-scripts-writer.js @@ -0,0 +1,679 @@ +const t = require('tap') +const path = require('node:path') +const { + applyApprovalForPackage, + applyDenyForPackage, + nameKeyFor, + versionedKeyFor, + isSingleVersionPin, +} = require('../../../lib/utils/allow-scripts-writer.js') + +const node = (overrides = {}) => { + const name = overrides.name ?? overrides.packageName ?? 'pkg' + const packageName = overrides.packageName ?? name + const version = overrides.version ?? '1.0.0' + const urlPkg = packageName + return { + name, + packageName, + version, + resolved: overrides.resolved + ?? `https://registry.npmjs.org/${urlPkg}/-/${urlPkg}-${version}.tgz`, + location: overrides.location ?? `node_modules/${name}`, + isRegistryDependency: overrides.isRegistryDependency ?? true, + } +} + +t.test('nameKeyFor / versionedKeyFor — registry', async t => { + const n = node({ name: 'canvas', version: '2.11.0' }) + t.equal(nameKeyFor(n), 'canvas') + t.equal(versionedKeyFor(n), 'canvas@2.11.0') +}) + +t.test('nameKeyFor / versionedKeyFor — git', async t => { + const n = node({ + name: 'bar', + resolved: 'git+ssh://git@github.com/foo/bar.git#deadbeefcafebabe1234567890abcdef12345678', + }) + t.equal(nameKeyFor(n), 'github:foo/bar') + t.equal(versionedKeyFor(n), 'github:foo/bar#deadbeefcafebabe1234567890abcdef12345678') +}) + +t.test('nameKeyFor / versionedKeyFor — file', async t => { + const n = node({ name: 'local', resolved: 'file:../local' }) + t.equal(nameKeyFor(n), 'file:../local') + t.equal(versionedKeyFor(n), 'file:../local') +}) + +t.test('nameKeyFor / versionedKeyFor — local directory link target', async t => { + const targetPath = path.resolve('local') + const n = { + name: 'local', + packageName: 'local', + version: '1.0.0', + resolved: null, + path: targetPath, + realpath: targetPath, + linksIn: new Set([{ resolved: 'file:../local' }]), + } + + t.equal(nameKeyFor(n), 'file:../local') + t.equal(versionedKeyFor(n), 'file:../local') + + t.strictSame( + applyApprovalForPackage({}, [n], { pin: true }).allowScripts, + { 'file:../local': true } + ) + t.match( + applyApprovalForPackage({ 'file:local': false }, [n], { pin: true }).warning, + /denied|versioned deny/ + ) +}) + +t.test('nameKeyFor / versionedKeyFor — empty link target has no portable file key', async t => { + const targetPath = path.resolve('local') + const n = { + name: 'local', + packageName: 'local', + version: '1.0.0', + resolved: null, + path: targetPath, + realpath: targetPath, + linksIn: new Set(), + } + + t.equal(nameKeyFor(n), null) + t.equal(versionedKeyFor(n), null) + t.strictSame(applyApprovalForPackage({}, [n], { pin: true }).allowScripts, {}) +}) + +t.test('isSingleVersionPin', async t => { + t.ok(isSingleVersionPin('pkg@1.2.3')) + t.notOk(isSingleVersionPin('pkg')) + t.notOk(isSingleVersionPin('pkg@^1')) + t.notOk(isSingleVersionPin('pkg@1.2.3 || 2.0.0')) + t.notOk(isSingleVersionPin('@@@bad')) +}) + +t.test('applyApprovalForPackage — empty allowScripts, --pin', async t => { + const { allowScripts, changes } = applyApprovalForPackage( + {}, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + t.strictSame(allowScripts, { 'canvas@2.11.0': true }) + t.strictSame(changes, [{ key: 'canvas@2.11.0', change: 'added' }]) +}) + +t.test('applyApprovalForPackage — empty allowScripts, --no-pin', async t => { + const { allowScripts, changes } = applyApprovalForPackage( + {}, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: false } + ) + t.strictSame(allowScripts, { canvas: true }) + t.strictSame(changes, [{ key: 'canvas', change: 'added' }]) +}) + +t.test('applyApprovalForPackage — stale pin rewritten to new installed version', async t => { + const { allowScripts, changes } = applyApprovalForPackage( + { 'canvas@2.10.0': true }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + t.strictSame(allowScripts, { 'canvas@2.11.0': true }) + t.match(changes, [ + { key: 'canvas@2.10.0', change: 'removed-stale' }, + { key: 'canvas@2.11.0', change: 'added' }, + ]) +}) + +t.test('applyApprovalForPackage — multi-version disjunction is preserved', async t => { + const { allowScripts } = applyApprovalForPackage( + { 'canvas@2.10.0 || 2.11.0': true }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + t.strictSame(allowScripts, { + 'canvas@2.10.0 || 2.11.0': true, + 'canvas@2.11.0': true, + }) +}) + +t.test('applyApprovalForPackage — already-allowed exact version is a no-op', async t => { + const { allowScripts, changes } = applyApprovalForPackage( + { 'canvas@2.11.0': true }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + t.strictSame(allowScripts, { 'canvas@2.11.0': true }) + t.strictSame(changes, []) +}) + +t.test('applyApprovalForPackage — existing deny wins, returns warning', async t => { + const { allowScripts, changes, warning } = applyApprovalForPackage( + { canvas: false }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + t.strictSame(allowScripts, { canvas: false }) + t.strictSame(changes, []) + t.match(warning, /canvas is denied/) +}) + +t.test('applyApprovalForPackage — versioned deny wins too', async t => { + const { changes, warning } = applyApprovalForPackage( + { 'canvas@2.11.0': false }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + t.strictSame(changes, []) + t.match(warning, /denied|versioned deny/) +}) + +t.test('applyApprovalForPackage — name-only existing, --no-pin no-op', async t => { + const { allowScripts, changes } = applyApprovalForPackage( + { canvas: true }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: false } + ) + t.strictSame(allowScripts, { canvas: true }) + t.strictSame(changes, []) +}) + +t.test('applyApprovalForPackage — --no-pin downgrades pinned entry to name-only', async t => { + const { allowScripts } = applyApprovalForPackage( + { 'canvas@2.10.0': true }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: false } + ) + t.strictSame(allowScripts, { canvas: true }) +}) + +t.test('applyApprovalForPackage — multiple installed versions write multiple pins', async t => { + const { allowScripts } = applyApprovalForPackage( + {}, + [ + node({ name: 'lodash', version: '4.17.21' }), + node({ name: 'lodash', version: '3.10.1' }), + ], + { pin: true } + ) + t.strictSame(allowScripts, { 'lodash@3.10.1': true, 'lodash@4.17.21': true }) +}) + +t.test('applyApprovalForPackage — keeps existing pin matching one installed, adds pin for other', async t => { + const { allowScripts } = applyApprovalForPackage( + { 'lodash@4.17.21': true }, + [ + node({ name: 'lodash', version: '4.17.21' }), + node({ name: 'lodash', version: '3.10.1' }), + ], + { pin: true } + ) + t.strictSame(allowScripts, { 'lodash@3.10.1': true, 'lodash@4.17.21': true }) +}) + +t.test('applyDenyForPackage — empty allowScripts adds name-only false', async t => { + const { allowScripts, changes } = applyDenyForPackage( + {}, + [node({ name: 'core-js', version: '3.0.0' })] + ) + t.strictSame(allowScripts, { 'core-js': false }) + t.strictSame(changes, [{ key: 'core-js', change: 'added' }]) +}) + +t.test('applyDenyForPackage — pinned allow is replaced by name-only deny', async t => { + const { allowScripts } = applyDenyForPackage( + { 'core-js@3.0.0': true }, + [node({ name: 'core-js', version: '3.0.0' })] + ) + t.strictSame(allowScripts, { 'core-js': false }) +}) + +t.test('applyDenyForPackage — already-denied is a no-op', async t => { + const { changes } = applyDenyForPackage( + { 'core-js': false }, + [node({ name: 'core-js', version: '3.0.0' })] + ) + t.strictSame(changes, []) +}) + +t.test('applyDenyForPackage — name-only true is replaced by name-only false', async t => { + const { allowScripts } = applyDenyForPackage( + { 'core-js': true }, + [node({ name: 'core-js', version: '3.0.0' })] + ) + t.strictSame(allowScripts, { 'core-js': false }) +}) + +t.test('applyApprovalForPackage — preserves unrelated entries', async t => { + const { allowScripts } = applyApprovalForPackage( + { other: true, 'unrelated@1.0.0': false }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + t.strictSame(allowScripts, { + other: true, + 'unrelated@1.0.0': false, + 'canvas@2.11.0': true, + }) +}) + +t.test('applyApprovalForPackage — git node writes hosted shortcut with commit', async t => { + const { allowScripts } = applyApprovalForPackage( + {}, + [node({ + name: 'bar', + resolved: 'git+ssh://git@github.com/foo/bar.git#deadbeefcafebabe1234567890abcdef12345678', + })], + { pin: true } + ) + t.strictSame(allowScripts, { + 'github:foo/bar#deadbeefcafebabe1234567890abcdef12345678': true, + }) +}) + +t.test('applyApprovalForPackage — git node --no-pin writes hosted shortcut without commit', async t => { + const { allowScripts } = applyApprovalForPackage( + {}, + [node({ + name: 'bar', + resolved: 'git+ssh://git@github.com/foo/bar.git#deadbeef', + })], + { pin: false } + ) + t.strictSame(allowScripts, { 'github:foo/bar': true }) +}) + +t.test('applyApprovalForPackage — file dep uses resolved as both keys', async t => { + const { allowScripts } = applyApprovalForPackage( + {}, + [node({ name: 'local', resolved: 'file:../local' })], + { pin: true } + ) + t.strictSame(allowScripts, { 'file:../local': true }) +}) + +t.test('applyApprovalForPackage — empty nodes returns unchanged', async t => { + const { allowScripts, changes } = applyApprovalForPackage({ x: true }, [], { pin: true }) + t.strictSame(allowScripts, { x: true }) + t.strictSame(changes, []) +}) + +t.test('applyApprovalForPackage — name-only entry is replaced by pin (RFC table)', async t => { + const { allowScripts, changes } = applyApprovalForPackage( + { canvas: true }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + // Per RFC table: pkg: true + --pin must upgrade to pkg@x.y.z: true. + // Both entries left behind would be wrong. + t.strictSame(allowScripts, { 'canvas@2.11.0': true }) + t.match(changes, [ + { key: 'canvas@2.11.0', change: 'added' }, + { key: 'canvas', change: 'replaced-by-pin' }, + ]) +}) + +t.test('applyApprovalForPackage — name-only + multi-version installs replaces with all pins', async t => { + const { allowScripts } = applyApprovalForPackage( + { lodash: true }, + [ + node({ name: 'lodash', version: '4.17.21' }), + node({ name: 'lodash', version: '3.10.1' }), + ], + { pin: true } + ) + t.strictSame(allowScripts, { 'lodash@3.10.1': true, 'lodash@4.17.21': true }) +}) + +t.test('applyApprovalForPackage — name-only is preserved when --no-pin', async t => { + const { allowScripts, changes } = applyApprovalForPackage( + { canvas: true }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: false } + ) + t.strictSame(allowScripts, { canvas: true }) + t.strictSame(changes, []) +}) + +t.test('applyApprovalForPackage — name-only NOT dropped when no pinning could happen', async t => { + // Node has no version, so installedKeys is empty. The name-only entry + // must NOT be dropped or we silently lose the policy. + const noVersion = { name: 'pkg', packageName: 'pkg', version: undefined, resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.tgz' } + const { allowScripts } = applyApprovalForPackage( + { pkg: true }, + [noVersion], + { pin: true } + ) + t.strictSame(allowScripts, { pkg: true }) +}) + +t.test('applyApprovalForPackage — convergent: running twice gives the same result', async t => { + // Start with stale state including a name-only entry. + const start = { canvas: true, 'canvas@2.10.0': true } + const nodes = [node({ name: 'canvas', version: '2.11.0' })] + + const run1 = applyApprovalForPackage(start, nodes, { pin: true }) + const run2 = applyApprovalForPackage(run1.allowScripts, nodes, { pin: true }) + + t.strictSame(run1.allowScripts, { 'canvas@2.11.0': true }) + t.strictSame(run2.allowScripts, { 'canvas@2.11.0': true }) + t.strictSame(run2.changes, [], 'second run is a no-op') +}) + +t.test('applyApprovalForPackage — deny still wins even when name-only is upgraded', async t => { + const { allowScripts, warning } = applyApprovalForPackage( + { canvas: true, 'canvas@2.11.0': false }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + // Existing deny on the version blocks the approval. + t.strictSame(allowScripts, { canvas: true, 'canvas@2.11.0': false }) + t.match(warning, /denied|versioned deny/) +}) + +t.test('keyTargetsNode — unparseable key returns false (via applyApproval)', async t => { + // An unparseable key in the existing object should be ignored. + const { allowScripts } = applyApprovalForPackage( + { '@@@invalid': true }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + t.equal(allowScripts['canvas@2.11.0'], true) + t.equal(allowScripts['@@@invalid'], true) +}) + +t.test('applyDenyForPackage — empty nodes array returns unchanged', async t => { + const { allowScripts, changes } = applyDenyForPackage({ existing: true }, []) + t.strictSame(allowScripts, { existing: true }) + t.strictSame(changes, []) +}) + +t.test('applyDenyForPackage — node with no nameable identity is a no-op', async t => { + // A node whose resolved field is unparseable as a git URL and has no + // version/name produces a null name; the writer must short-circuit. + const weird = { name: '', packageName: '', version: undefined, resolved: undefined } + const { allowScripts, changes } = applyDenyForPackage({}, [weird]) + t.strictSame(allowScripts, {}) + t.strictSame(changes, []) +}) + +t.test('applyApprovalForPackage — file dep with deny entry blocks approval', async t => { + const { warning } = applyApprovalForPackage( + { 'file:../local': false }, + [node({ name: 'local', resolved: 'file:../local' })], + { pin: true } + ) + t.match(warning, /denied|versioned deny/) +}) + +t.test('applyApprovalForPackage — remote tarball deny blocks approval', async t => { + const remote = { name: 'pkg', packageName: 'pkg', version: '1.0.0', resolved: 'https://example.com/pkg.tgz' } + const { warning } = applyApprovalForPackage( + { 'https://example.com/pkg.tgz': false }, + [remote], + { pin: true } + ) + t.match(warning, /denied|versioned deny/) +}) + +t.test('applyApprovalForPackage — no-pin with no name produces no-op', async t => { + const weird = { name: '', packageName: '', resolved: 'git+ssh://no.parse' } + const { allowScripts, changes } = applyApprovalForPackage({}, [weird], { pin: false }) + t.strictSame(allowScripts, {}) + t.strictSame(changes, []) +}) + +t.test('applyApprovalForPackage — pin with no versioned key is a no-op', async t => { + const noVersion = { name: 'pkg', packageName: 'pkg', version: undefined, resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.tgz' } + const { allowScripts, changes } = applyApprovalForPackage({}, [noVersion], { pin: true }) + t.strictSame(allowScripts, {}) + t.strictSame(changes, []) +}) + +t.test('applyApprovalForPackage — pin with no versioned key and existing name-only is no-op', async t => { + const noVersion = { name: 'pkg', packageName: 'pkg', version: undefined, resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.tgz' } + const { changes } = applyApprovalForPackage({ pkg: true }, [noVersion], { pin: true }) + t.strictSame(changes, []) +}) + +t.test('keyTargetsNode handles file with directory-typed key', async t => { + // A "directory" spec for a relative path. + const dirNode = { name: 'local', packageName: 'local', resolved: 'file:./local-dir' } + const { allowScripts } = applyApprovalForPackage( + {}, + [dirNode], + { pin: true } + ) + t.equal(allowScripts['file:./local-dir'], true) +}) + +t.test('nameKeyFor / versionedKeyFor — null node', async t => { + t.equal(nameKeyFor(null), null) + t.equal(versionedKeyFor(null), null) +}) + +t.test('nameKeyFor / versionedKeyFor — non-hosted git url returns null', async t => { + const n = { name: 'pkg', packageName: 'pkg', resolved: 'git+https://example.invalid/foo/bar.git#abc' } + t.equal(nameKeyFor(n), null) + t.equal(versionedKeyFor(n), null) +}) + +t.test('versionedKeyFor — absolute path resolved field', async t => { + const n = { name: 'pkg', packageName: 'pkg', resolved: '/abs/path/local' } + t.equal(versionedKeyFor(n), '/abs/path/local') + t.equal(nameKeyFor(n), '/abs/path/local') +}) + +t.test('applyApprovalForPackage — node.resolved parse error in keyTargetsNode is safe', async t => { + // An existing git-style key for a package whose own resolved field + // doesn't parse: the key just doesn't target anything. + const gitNode = node({ + name: 'bar', + resolved: 'git+ssh://git@github.com/foo/bar.git#abc', + }) + // Add an explicit unparseable existing entry. + const { allowScripts } = applyApprovalForPackage( + { 'github:other/other': true }, + [gitNode], + { pin: true } + ) + // Existing entry unchanged; new git entry added. + t.equal(allowScripts['github:other/other'], true) + t.equal(allowScripts['github:foo/bar#abc'], true) +}) + +t.test('keyTargetsNode — alias key does not target anything (via writer)', async t => { + // Alias-typed key falls through the switch default. + const { allowScripts } = applyApprovalForPackage( + { 'foo@npm:bar@1.0.0': true }, + [node({ name: 'foo', packageName: 'foo', version: '1.0.0' })], + { pin: true } + ) + // Alias entry untouched, new pin added separately. + t.equal(allowScripts['foo@npm:bar@1.0.0'], true) + t.equal(allowScripts['foo@1.0.0'], true) +}) +t.test('keyTargetsNode handles tag-type key', async t => { + // 'canvas@latest' parses as type='tag'. The writer should treat it like + // a name-only match (any installed version of canvas). + const { allowScripts } = applyApprovalForPackage( + { 'canvas@latest': true }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + // The tag key targets the canvas node (same package name), so the + // 'canvas@2.11.0' pin gets added; tag key is preserved. + t.equal(allowScripts['canvas@latest'], true) + t.equal(allowScripts['canvas@2.11.0'], true) +}) + +t.test('keyTargetsNode handles file-type tarball key matching saveSpec', async t => { + // 'file:pkg.tgz' parses as type='file' with saveSpec='file:pkg.tgz'. + const tarballNode = { + name: 'pkg', + packageName: 'pkg', + version: '1.0.0', + resolved: 'file:pkg.tgz', + } + const { allowScripts } = applyApprovalForPackage( + { 'file:pkg.tgz': false }, + [tarballNode], + { pin: true } + ) + // saveSpec match: deny wins, no pin added. + t.equal(allowScripts['file:pkg.tgz'], false) +}) + +t.test('keyTargetsNode handles file-type tarball key matching fetchSpec', async t => { + // When node.resolved is an absolute path matching parsed.fetchSpec. + // Use path.resolve so the absolute path is platform-correct (npa + // parses POSIX-style `/abs/...` as a directory on Windows). + const absTgz = path.resolve('pkg.tgz') + const tarballNode = { + name: 'pkg', + packageName: 'pkg', + version: '1.0.0', + resolved: absTgz, + } + const { allowScripts, warning } = applyApprovalForPackage( + { './pkg.tgz': false }, + [tarballNode], + { pin: true } + ) + t.equal(allowScripts['./pkg.tgz'], false) + t.match(warning, /denied|versioned deny/) +}) + +t.test('versionedKeyFor — git node without committish', async t => { + // versionedKeyFor's ternary takes the "no committish" branch. + t.equal( + versionedKeyFor({ + name: 'bar', + resolved: 'git+ssh://git@github.com/foo/bar.git', + }), + 'github:foo/bar' + ) +}) + +t.test('versionedKeyFor / nameKeyFor — absolute path resolved field', async t => { + // Hits the `resolved.startsWith('/')` branch in both helpers. + const n = { name: 'pkg', packageName: 'pkg', resolved: '/abs/local-dir' } + t.equal(versionedKeyFor(n), '/abs/local-dir') + t.equal(nameKeyFor(n), '/abs/local-dir') +}) + +t.test('keyTargetsNode — git key against a node with no resolved field', async t => { + // Defensive: if existing has a git-shaped key and the installed node + // has no resolved field, keyTargetsNode bails out and no policy entry + // can be derived from untrusted sources. + const noResolved = { name: 'bar', packageName: 'bar', resolved: undefined } + const { allowScripts } = applyApprovalForPackage( + { 'github:foo/bar': true }, + [noResolved], + { pin: false } + ) + // Existing entry untouched. No new key written: nameKeyFor returns + // null for a node with no trusted identity source. + t.equal(allowScripts['github:foo/bar'], true) + t.notOk('bar' in allowScripts, 'no entry written under attacker-controlled node.name') +}) + +t.test('applyApprovalForPackage — default args (no options object)', async t => { + // Hits the `{ pin = true } = {}` default-arg branch. + const { allowScripts } = applyApprovalForPackage( + {}, + [node({ name: 'canvas', version: '2.11.0' })] + ) + t.strictSame(allowScripts, { 'canvas@2.11.0': true }) +}) + +t.test('applyApprovalForPackage — deny-wins warning when node has no name', async t => { + // Hits the `name || 'this package'` fallback in the warning message. + const noName = { name: '', packageName: '', resolved: 'git+ssh://no.parse' } + const { warning } = applyApprovalForPackage( + { 'github:foo/bar': false }, + [noName], + { pin: true } + ) + // No keys target this node (its resolved doesn't parse to a hosted URL), + // so deny-wins doesn't trigger. Result is no warning. + t.notOk(warning) +}) + +t.test('denyWarning branches on key shape per RFC §approve-scripts', async t => { + // Name-only deny: only remedy is to remove the entry. + const nameOnly = applyApprovalForPackage( + { canvas: false }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + t.match(nameOnly.warning, /remove the entry from allowScripts/) + t.notMatch(nameOnly.warning, /widen the deny/) + + // Pinned deny on a different version: suggest both widen and remove. + const pinned = applyApprovalForPackage( + { 'canvas@2.10.0': false }, + [node({ name: 'canvas', version: '2.10.0' })], + { pin: true } + ) + t.match(pinned.warning, /versioned deny/) + t.match(pinned.warning, /npm deny-scripts canvas/) + t.match(pinned.warning, /widen the deny to all versions/) + t.match(pinned.warning, /remove the entry/) + + // Multi-version deny disjunction: same as pinned (versioned). + const multi = applyApprovalForPackage( + { 'canvas@2.10.0 || 2.11.0': false }, + [node({ name: 'canvas', version: '2.10.0' })], + { pin: true } + ) + t.match(multi.warning, /versioned deny/) + t.match(multi.warning, /npm deny-scripts canvas/) +}) + +t.test('denyWarning: tag-type key (pkg@latest: false) is name-only', async t => { + // `canvas@latest` parses as type='tag'. Treat the same as a bare name. + const { warning } = applyApprovalForPackage( + { 'canvas@latest': false }, + [node({ name: 'canvas', version: '2.11.0' })], + { pin: true } + ) + t.match(warning, /remove the entry/) + t.notMatch(warning, /versioned deny/) +}) + +t.test('applyApprovalForPackage — multi-version entry + --pin=false adds name-only alongside', async t => { + // RFC table: existing `pkg@a.b.c || d.e.f: true` + installed `pkg@x.y.z` + // + --pin=false adds `pkg: true`. The multi-version disjunction stays + // (it captures intent the command can't infer), and the name-only + // entry is added. + const { allowScripts } = applyApprovalForPackage( + { 'canvas@1.0.0 || 2.0.0': true }, + [node({ name: 'canvas', version: '3.0.0' })], + { pin: false } + ) + t.strictSame(allowScripts, { + 'canvas@1.0.0 || 2.0.0': true, + canvas: true, + }) +}) + +t.test('versionedKeyFor — registry resolved that versionFromTgz cannot parse returns null', async t => { + // Private-registry mirror / alternate CDN URL shape that doesn't match + // the standard `/-/name-version.tgz` pattern. Exercises the log.silly + // breadcrumb path in versionedKeyFor, including each fallback branch + // of the `node.path || node.name || ''` label expression. + const resolved = 'https://private-mirror.example.com/blobs/abc123' + t.equal(versionedKeyFor({ + path: '/fake/mystery', name: 'mystery', resolved, isRegistryDependency: true, + }), null, 'falls back when node has a path') + t.equal(versionedKeyFor({ + name: 'mystery', resolved, isRegistryDependency: true, + }), null, 'falls back when node has only a name') + t.equal(versionedKeyFor({ + resolved, isRegistryDependency: true, + }), null, 'falls back when node has neither path nor name') +}) diff --git a/test/lib/utils/check-allow-scripts.js b/test/lib/utils/check-allow-scripts.js new file mode 100644 index 0000000000000..c67ec2a7cd703 --- /dev/null +++ b/test/lib/utils/check-allow-scripts.js @@ -0,0 +1,236 @@ +const t = require('tap') + +const mockCheck = (t, mocks = {}) => + t.mock('../../../lib/utils/check-allow-scripts.js', mocks) + +// Build a minimal "arborist tree" fixture for the walker. +const arb = ({ nodes, allowScripts = null, ignoreScripts = false } = {}) => ({ + options: { allowScripts, ignoreScripts }, + actualTree: { + inventory: new Map(nodes.map((n, i) => [`node_modules/${n.name || `n${i}`}`, n])), + }, +}) + +const node = ({ + name = 'pkg', + packageName, + version = '1.0.0', + resolved, + scripts = {}, + gypfile, + path: nodePath = `/fake/${name}`, + isProjectRoot = false, + isWorkspace = false, + isLink = false, + isRegistryDependency, +} = {}) => { + const pkgName = packageName ?? name + const resolvedUrl = resolved + ?? `https://registry.npmjs.org/${pkgName}/-/${pkgName}-${version}.tgz` + // Default isRegistryDependency to match the shape of resolved: registry + // tarballs are registry, anything else (git, file, remote) is not. + const isReg = isRegistryDependency ?? /^https?:\/\/[^/]+\/.+\/-\/[^/]+-\d/.test(resolvedUrl) + return { + name, + packageName: pkgName, + version, + resolved: resolvedUrl, + location: `node_modules/${name}`, + isRegistryDependency: isReg, + path: nodePath, + isProjectRoot, + isWorkspace, + isLink, + package: { scripts, ...(gypfile !== undefined ? { gypfile } : {}) }, + } +} + +t.test('returns [] when ignoreScripts is set', async t => { + const checkAllowScripts = mockCheck(t) + const result = await checkAllowScripts({ + arb: arb({ + nodes: [node({ scripts: { install: 'do-stuff' } })], + ignoreScripts: true, + }), + npm: { flatOptions: {} }, + }) + t.strictSame(result, []) +}) + +t.test('returns unreviewed nodes when ignoreScripts is set but includeWhenIgnored is true', async t => { + const checkAllowScripts = mockCheck(t) + const result = await checkAllowScripts({ + arb: arb({ + nodes: [node({ name: 'a', scripts: { install: 'do-stuff' } })], + ignoreScripts: true, + }), + npm: { flatOptions: {} }, + includeWhenIgnored: true, + }) + t.equal(result.length, 1) + t.strictSame(result[0].scripts, { install: 'do-stuff' }) +}) + +t.test('returns [] when dangerouslyAllowAllScripts is set', async t => { + const checkAllowScripts = mockCheck(t) + const result = await checkAllowScripts({ + arb: arb({ nodes: [node({ scripts: { install: 'do-stuff' } })] }), + npm: { flatOptions: { dangerouslyAllowAllScripts: true } }, + }) + t.strictSame(result, []) +}) + +t.test('skips project root, workspace, and linked nodes', async t => { + const checkAllowScripts = mockCheck(t) + const result = await checkAllowScripts({ + arb: arb({ + nodes: [ + node({ name: 'root', scripts: { install: 'x' }, isProjectRoot: true }), + node({ name: 'ws', scripts: { install: 'x' }, isWorkspace: true }), + node({ name: 'linked', scripts: { install: 'x' }, isLink: true }), + ], + }), + npm: { flatOptions: {} }, + }) + t.strictSame(result, []) +}) + +t.test('skips nodes with no install-relevant scripts', async t => { + const checkAllowScripts = mockCheck(t) + const result = await checkAllowScripts({ + arb: arb({ + nodes: [node({ scripts: { test: 'jest' } })], + }), + npm: { flatOptions: {} }, + }) + t.strictSame(result, []) +}) + +t.test('includes nodes with preinstall/install/postinstall', async t => { + const checkAllowScripts = mockCheck(t) + const result = await checkAllowScripts({ + arb: arb({ + nodes: [ + node({ name: 'a', scripts: { preinstall: 'pre' } }), + node({ name: 'b', scripts: { install: 'inst' } }), + node({ name: 'c', scripts: { postinstall: 'post' } }), + ], + }), + npm: { flatOptions: {} }, + }) + t.equal(result.length, 3) + t.strictSame(result[0].scripts, { preinstall: 'pre' }) + t.strictSame(result[1].scripts, { install: 'inst' }) + t.strictSame(result[2].scripts, { postinstall: 'post' }) +}) + +t.test('prepare counts for non-registry sources only', async t => { + const checkAllowScripts = mockCheck(t) + const result = await checkAllowScripts({ + arb: arb({ + nodes: [ + // registry: prepare ignored + node({ + name: 'registry-pkg', + resolved: 'https://registry.npmjs.org/registry-pkg/-/registry-pkg-1.0.0.tgz', + scripts: { prepare: 'do' }, + }), + // git: prepare counts + node({ + name: 'git-pkg', + resolved: 'git+ssh://git@github.com/foo/bar.git#abcdef0123456789', + scripts: { prepare: 'do' }, + }), + ], + }), + npm: { flatOptions: {} }, + }) + t.equal(result.length, 1) + t.equal(result[0].node.name, 'git-pkg') +}) + +t.test('skips approved nodes', async t => { + const checkAllowScripts = mockCheck(t) + const result = await checkAllowScripts({ + arb: arb({ + nodes: [node({ name: 'allowed', scripts: { install: 'x' } })], + allowScripts: { allowed: true }, + }), + npm: { flatOptions: {} }, + }) + t.strictSame(result, []) +}) + +t.test('skips denied nodes (false counts as reviewed)', async t => { + const checkAllowScripts = mockCheck(t) + const result = await checkAllowScripts({ + arb: arb({ + nodes: [node({ name: 'denied', scripts: { install: 'x' } })], + allowScripts: { denied: false }, + }), + npm: { flatOptions: {} }, + }) + t.strictSame(result, []) +}) + +t.test('includes unreviewed nodes when policy is set but does not cover them', async t => { + const checkAllowScripts = mockCheck(t) + const result = await checkAllowScripts({ + arb: arb({ + nodes: [ + node({ name: 'allowed', scripts: { install: 'x' } }), + node({ name: 'unreviewed', scripts: { install: 'y' } }), + ], + allowScripts: { allowed: true }, + }), + npm: { flatOptions: {} }, + }) + t.equal(result.length, 1) + t.equal(result[0].node.name, 'unreviewed') +}) + +t.test('reports every install-script node when no policy is set', async t => { + const checkAllowScripts = mockCheck(t) + const result = await checkAllowScripts({ + arb: arb({ + nodes: [ + node({ name: 'a', scripts: { install: 'x' } }), + node({ name: 'b', scripts: { postinstall: 'y' } }), + ], + }), + npm: { flatOptions: {} }, + }) + t.equal(result.length, 2) +}) + +t.test('survives missing actualTree', async t => { + const checkAllowScripts = mockCheck(t) + const result = await checkAllowScripts({ + arb: { options: {} }, + npm: { flatOptions: {} }, + }) + t.strictSame(result, []) +}) + +t.test('bundled dep with install scripts is never reported (never runs, never pending)', async t => { + const checkAllowScripts = mockCheck(t) + const bundled = node({ + name: 'bundled-pkg', + version: '1.0.0', + resolved: undefined, + scripts: { install: 'do-stuff' }, + }) + bundled.inBundle = true + + const result = await checkAllowScripts({ + arb: arb({ + nodes: [bundled], + // Even with an explicit allow entry, a bundled dep never runs its + // install scripts and is never counted as pending, so the walker + // must not flag it. + allowScripts: { 'bundled-pkg': true }, + }), + npm: { flatOptions: {} }, + }) + t.strictSame(result, [], 'bundled dep never flagged') +}) diff --git a/test/lib/utils/cli-only-flag.js b/test/lib/utils/cli-only-flag.js new file mode 100644 index 0000000000000..a30d97bc450c9 --- /dev/null +++ b/test/lib/utils/cli-only-flag.js @@ -0,0 +1,33 @@ +const t = require('tap') +const cliOnlyFlag = require('../../../lib/utils/cli-only-flag.js') +const { patchRelaxOpts } = require('../../../lib/utils/cli-only-flag.js') + +// minimal config stub: `where` is the layer find() would resolve the key from +const mockConfig = (where, value) => ({ + find: () => where, + get: () => value, +}) + +t.test('returns the value when set on the cli layer', t => { + t.equal(cliOnlyFlag(mockConfig('cli', true), 'x'), true) + t.end() +}) + +t.test('returns undefined when resolved from any non-cli layer', t => { + for (const where of ['env', 'project', 'user', 'global', 'default']) { + t.equal(cliOnlyFlag(mockConfig(where, true), 'x'), undefined, `${where} is ignored`) + } + t.end() +}) + +t.test('patchRelaxOpts maps the cli-only patch flags to arborist options', t => { + const config = { + find: key => (key === 'allow-unused-patches' ? 'cli' : 'project'), + get: () => true, + } + t.strictSame(patchRelaxOpts(config), { + allowUnusedPatches: true, + ignorePatchFailures: undefined, + }) + t.end() +}) diff --git a/test/lib/utils/display.js b/test/lib/utils/display.js index 78bffa0221d03..b33ab69a36594 100644 --- a/test/lib/utils/display.js +++ b/test/lib/utils/display.js @@ -15,7 +15,7 @@ const mockDisplay = async (t, { mocks, load } = {}) => { const displayLoad = async (opts) => display.load({ loglevel: 'silly', stderrColor: false, - stdoutColot: false, + stdoutColor: false, heading: 'npm', ...opts, }) @@ -37,7 +37,9 @@ t.test('can log cleanly', async (t) => { const { log, logs } = await mockDisplay(t) log.error('', 'test\x00message') + log.info('', 'fetch DELETE 200 https://registry.npmjs.org/-/user/token/npm_000000000000000000000000000000000000 477ms') t.match(logs.error, ['test^@message']) + t.match(logs.info, ['fetch DELETE 200 https://registry.npmjs.org/-/user/token/npm_*** 477ms']) }) t.test('can handle special eresolves', async (t) => { @@ -130,6 +132,77 @@ t.test('incorrect levels', async t => { t.strictSame(outputs, [], 'output is ignored') }) +t.test('notice deduplication', async t => { + const { log, logs, display } = await mockDisplay(t, { + load: { loglevel: 'notice' }, + }) + + // Log the same notice multiple times - should be deduplicated + log.notice('', 'This is a duplicate notice') + log.notice('', 'This is a duplicate notice') + log.notice('', 'This is a duplicate notice') + + // Should only appear once in logs + t.equal(logs.notice.length, 1, 'notice appears only once') + t.strictSame(logs.notice, ['This is a duplicate notice']) + + // Different notice should appear + log.notice('', 'This is a different notice') + t.equal(logs.notice.length, 2, 'different notice is shown') + t.strictSame(logs.notice, [ + 'This is a duplicate notice', + 'This is a different notice', + ]) + + // Same notice with different title should appear + log.notice('title', 'This is a duplicate notice') + t.equal(logs.notice.length, 3, 'notice with different title is shown') + t.match(logs.notice[2], /title.*This is a duplicate notice/) + + // Log the first notice again - should still be deduplicated + log.notice('', 'This is a duplicate notice') + t.equal(logs.notice.length, 3, 'original notice still deduplicated') + + // Call off() to simulate end of command and clear deduplication + display.off() + + // Create a new display instance to simulate a new command + const logsResult = mockLogs() + const Display = tmock(t, '{LIB}/utils/display') + const display2 = new Display(logsResult.streams) + await display2.load({ + loglevel: 'silly', + stderrColor: false, + stdoutColor: false, + heading: 'npm', + }) + t.teardown(() => display2.off()) + + // Log the same notice again - should appear since deduplication was cleared + log.notice('', 'This is a duplicate notice') + t.equal(logsResult.logs.logs.notice.length, 1, 'notice appears after display.off() clears deduplication') + t.strictSame(logsResult.logs.logs.notice, ['This is a duplicate notice']) +}) + +t.test('notice deduplication does not apply in verbose mode', async t => { + const { log, logs } = await mockDisplay(t, { + load: { loglevel: 'verbose' }, + }) + + // Log the same notice multiple times in verbose mode + log.notice('', 'Repeated notice') + log.notice('', 'Repeated notice') + log.notice('', 'Repeated notice') + + // Should appear all three times in verbose mode + t.equal(logs.notice.length, 3, 'all notices appear in verbose mode') + t.strictSame(logs.notice, [ + 'Repeated notice', + 'Repeated notice', + 'Repeated notice', + ]) +}) + t.test('Display.clean', async (t) => { const { output, outputs, clearOutput } = await mockDisplay(t) @@ -197,3 +270,75 @@ t.test('Display.clean', async (t) => { clearOutput() } }) + +t.test('json output redacts by default', async t => { + // Do not set redact: false globally in the json flush path of display.js. + // If a command needs unredacted output (e.g. UUIDs), pass + // { [META]: true, redact: false } at the call site via output.standard(). + const { META } = require('proc-log') + const { output, outputs, clearOutput } = await mockDisplay(t) + + output.buffer({ + url: 'https://registry.npmjs.org/', + id: '550e8400-e29b-41d4-a716-446655440000', + }) + output.flush({ [META]: true, json: true }) + + t.equal(outputs.length, 1, 'one output') + const parsed = JSON.parse(outputs[0]) + t.equal(parsed.id, '***', 'uuid values are redacted in json output') + + // commands that need unredacted output should use output.standard + // with redact: false at the call site instead of disabling globally + clearOutput() + output.standard( + JSON.stringify({ id: '550e8400-e29b-41d4-a716-446655440000' }, null, 2), + { [META]: true, redact: false } + ) + const inlineParsed = JSON.parse(outputs[0]) + t.equal(inlineParsed.id, '550e8400-e29b-41d4-a716-446655440000', + 'inline redact: false preserves uuid values') +}) + +t.test('prompt functionality', async t => { + t.test('regular prompt completion works', async t => { + const { input } = await mockDisplay(t) + + const result = await input.read(() => Promise.resolve('user-input')) + + t.equal(result, 'user-input', 'should return the input result') + }) + + t.test('silent prompt completion works', async t => { + const { input } = await mockDisplay(t) + + const result = await input.read( + () => Promise.resolve('secret-password'), + { silent: true } + ) + + t.equal(result, 'secret-password', 'should return the input result for silent prompts') + }) + + t.test('metadata is correctly passed through', async t => { + const { input } = await mockDisplay(t) + + await input.read( + () => Promise.resolve('result1'), + { silent: false } + ) + t.pass('should handle silent false option') + + await input.read( + () => Promise.resolve('result2'), + {} + ) + t.pass('should handle empty options') + + await input.read( + () => Promise.resolve('result3'), + { silent: true } + ) + t.pass('should handle silent true option') + }) +}) diff --git a/test/lib/utils/error-message.js b/test/lib/utils/error-message.js index 1939e27c8ba92..44a57eca645d7 100644 --- a/test/lib/utils/error-message.js +++ b/test/lib/utils/error-message.js @@ -91,7 +91,7 @@ t.test('just simple messages', async t => { } }) -t.test('replace message/stack sensistive info', async t => { +t.test('replace message/stack sensitive info', async t => { const { errorMessage } = await loadMockNpm(t, { command: 'audit' }) const er = Object.assign(new Error('Error at registry: https://user:pass@registry.npmjs.org/'), { code: 'ENOAUDIT', @@ -281,6 +281,17 @@ t.test('eotp/e401', async t => { t.end() }) + t.test('one-time pass webauth challenge', t => { + t.matchSnapshot(errorMessage(Object.assign(new Error('nope'), { + code: 'EOTP', + body: { + authUrl: 'https://registry.npmjs.org/-/auth/login/abc123', + doneUrl: 'https://registry.npmjs.org/-/auth/done/abc123', + }, + }))) + t.end() + }) + t.test('www-authenticate challenges', t => { const auths = [ 'Bearer realm=do, charset="UTF-8", challenge="yourself"', diff --git a/test/lib/utils/explain-dep.js b/test/lib/utils/explain-dep.js index a90c0e90d5da6..30f7167e70657 100644 --- a/test/lib/utils/explain-dep.js +++ b/test/lib/utils/explain-dep.js @@ -1,6 +1,6 @@ const { resolve } = require('node:path') const t = require('tap') -const { explainNode, printNode } = require('../../../lib/utils/explain-dep.js') +const { explainNode, printNode, explainEdge } = require('../../../lib/utils/explain-dep.js') const { cleanCwd } = require('../../fixtures/clean-snapshot') t.cleanSnapshot = (str) => cleanCwd(str) @@ -140,6 +140,40 @@ const getCases = (testdir) => { }, }], }, + + packageExtensions: { + name: 'bar', + version: '1.2.3', + location: 'node_modules/bar', + dependents: [{ + type: 'prod', + name: 'bar', + spec: '^1.0.0', + packageExtensions: { selector: 'foo@1', field: 'dependencies' }, + from: { + name: 'foo', + version: '1.0.0', + location: 'node_modules/foo', + }, + }], + }, + + npmExtension: { + name: 'bar', + version: '1.2.3', + location: 'node_modules/bar', + dependents: [{ + type: 'prod', + name: 'bar', + spec: '^1.0.0', + npmExtension: { extensionPoint: 'transformManifest', field: 'dependencies' }, + from: { + name: 'foo', + version: '1.0.0', + location: 'node_modules/foo', + }, + }], + }, } cases.manyDeps = { @@ -268,6 +302,47 @@ t.test('basic', async t => { }) } + // Regression test for https://github.com/npm/cli/issues/9109 + // Circular dependency graphs (common in linked strategy store nodes) should not cause infinite recursion in explainNode. + const cycleA = { + name: 'cycle-a', + version: '1.0.0', + location: 'node_modules/cycle-a', + dependents: [], + } + const cycleB = { + name: 'cycle-b', + version: '2.0.0', + location: 'node_modules/cycle-b', + dependents: [{ + type: 'prod', + name: 'cycle-b', + spec: '2.x', + from: cycleA, + }], + } + cycleA.dependents = [{ + type: 'prod', + name: 'cycle-a', + spec: '1.x', + from: cycleB, + }] + t.matchSnapshot(explainNode(cycleA, Infinity, noColor), 'circular dependency does not recurse infinitely') + t.matchSnapshot(explainNode(cycleB, Infinity, noColor), 'circular dependency from other side') + + // explainEdge called without seen parameter (covers default seen = new Set() branch on explainEdge and explainFrom) + t.matchSnapshot(explainEdge({ + type: 'prod', + name: 'some-dep', + spec: '1.x', + from: { + name: 'parent-pkg', + version: '2.0.0', + location: 'node_modules/parent-pkg', + dependents: [], + }, + }, 2, noColor), 'explainEdge without seen parameter') + // make sure that we show the last one if it's the only one that would // hit the ... cases.manyDeps.dependents.pop() diff --git a/test/lib/utils/key-values.js b/test/lib/utils/key-values.js new file mode 100644 index 0000000000000..5e61f9e55fe59 --- /dev/null +++ b/test/lib/utils/key-values.js @@ -0,0 +1,84 @@ +const t = require('tap') +const { logObject, logStageItem, defaultPredicate } = require('../../../lib/utils/key-values.js') +const { load: loadMockNpm } = require('../../fixtures/mock-npm.js') + +t.test('defaultPredicate skips null and undefined', t => { + const chalk = { green: v => v } + t.equal(defaultPredicate('k', null, chalk), null) + t.equal(defaultPredicate('k', undefined, chalk), null) + t.equal(defaultPredicate('k', 'val', chalk), 'val') + t.end() +}) + +t.test('logObject json mode', async t => { + const { joinedOutput } = await loadMockNpm(t) + const chalk = { cyan: v => v, green: v => v } + logObject({ a: 1, b: 2 }, { chalk, json: true }) + const out = JSON.parse(joinedOutput()) + t.same(out, { a: 1, b: 2 }) +}) + +t.test('logObject skips null values with default predicate', async t => { + const { joinedOutput } = await loadMockNpm(t) + const chalk = { cyan: v => v, green: v => v } + logObject({ a: 'yes', b: null, c: 'also' }, { chalk }) + const out = joinedOutput() + t.match(out, /a: yes/) + t.match(out, /c: also/) + t.notMatch(out, /b:/) +}) + +t.test('logStageItem includes extra properties', async t => { + const { joinedOutput } = await loadMockNpm(t) + const chalk = { cyan: v => v, green: v => v } + logStageItem({ + id: 'abc', + packageName: 'pkg', + version: '1.0.0', + tag: 'latest', + createdAt: '2026-01-01', + actor: 'user', + actorType: 'human', + shasum: 'sha1', + extra: 'bonus', + }, { chalk }) + const out = joinedOutput() + t.match(out, /extra: bonus/) + t.match(out, /package name: pkg/) +}) + +t.test('logObject with custom predicate', async t => { + const { joinedOutput } = await loadMockNpm(t) + const chalk = { cyan: v => v, green: v => v } + logObject({ a: 'one', b: 'two' }, { + chalk, + predicate: (key, value) => `[${value}]`, + }) + const out = joinedOutput() + t.match(out, /a: \[one\]/) + t.match(out, /b: \[two\]/) +}) + +t.test('logStageItem without actorType shows actor alone', async t => { + const { joinedOutput } = await loadMockNpm(t) + const chalk = { cyan: v => v, green: v => v } + logStageItem({ + id: 'abc', + packageName: 'pkg', + version: '1.0.0', + tag: 'latest', + createdAt: '2026-01-01', + actor: 'user', + shasum: 'sha1', + }, { chalk }) + const out = joinedOutput() + t.match(out, /staged by: user/) + t.notMatch(out, /\(/) +}) + +t.test('logObject with all values skipped produces no output', async t => { + const { joinedOutput } = await loadMockNpm(t) + const chalk = { cyan: v => v, green: v => v } + logObject({ a: null, b: undefined }, { chalk }) + t.equal(joinedOutput(), '') +}) diff --git a/test/lib/utils/open-url.js b/test/lib/utils/open-url.js index 096533140757e..e094effea2efe 100644 --- a/test/lib/utils/open-url.js +++ b/test/lib/utils/open-url.js @@ -180,7 +180,7 @@ t.test('open url prompt', async t => { t.equal(openerUrl, 'https://www.npmjs.com', 'did not open') }) - t.test('does not error when opener can not find command', async t => { + t.test('does not error when opener cannot find command', async t => { const { OUTPUT, error, openerUrl } = await mockOpenUrlPrompt(t, { openerResult: Object.assign(new Error('Opener failed'), { code: 127 }), }) diff --git a/test/lib/utils/patch-diff.js b/test/lib/utils/patch-diff.js new file mode 100644 index 0000000000000..dd571651be8ec --- /dev/null +++ b/test/lib/utils/patch-diff.js @@ -0,0 +1,149 @@ +const t = require('tap') +const { resolve } = require('node:path') +const { readFileSync, existsSync, symlinkSync } = require('node:fs') +const { diffDirs } = require('../../../lib/utils/patch-diff.js') +const { applyPatchToDir } = require('@npmcli/arborist/lib/patch.js') + +// Helper to read a file from a dir as utf8. +const read = (...p) => readFileSync(resolve(...p), 'utf8') + +t.test('modified file produces a unified diff', async t => { + const dir = t.testdir({ + orig: { 'index.js': 'hello\n' }, + edit: { 'index.js': 'world\n' }, + }) + const { diff } = await diffDirs(resolve(dir, 'orig'), resolve(dir, 'edit')) + t.match(diff, '--- a/index.js', 'has old header') + t.match(diff, '+++ b/index.js', 'has new header') + t.match(diff, '-hello', 'removes old line') + t.match(diff, '+world', 'adds new line') + t.notMatch(diff, '====', 'index separator is stripped') +}) + +t.test('added file uses --- /dev/null', async t => { + const dir = t.testdir({ + orig: { 'keep.js': 'same\n' }, + edit: { 'keep.js': 'same\n', 'added.js': 'brand new\n' }, + }) + const { diff } = await diffDirs(resolve(dir, 'orig'), resolve(dir, 'edit')) + t.match(diff, '--- /dev/null', 'old side is /dev/null') + t.match(diff, '+++ b/added.js', 'new side names the added file') + t.match(diff, '+brand new', 'includes added content') + t.notMatch(diff, 'keep.js', 'identical file is not in the diff') +}) + +t.test('deleted file uses +++ /dev/null', async t => { + const dir = t.testdir({ + orig: { 'gone.js': 'remove me\n' }, + edit: {}, + }) + const { diff } = await diffDirs(resolve(dir, 'orig'), resolve(dir, 'edit')) + t.match(diff, '--- a/gone.js', 'old side names the deleted file') + t.match(diff, '+++ /dev/null', 'new side is /dev/null') + t.match(diff, '-remove me', 'includes removed content') +}) + +t.test('nested file path is posix-separated in the diff', async t => { + const dir = t.testdir({ + orig: { lib: { deep: { 'x.js': 'a\n' } } }, + edit: { lib: { deep: { 'x.js': 'b\n' } } }, + }) + const { diff } = await diffDirs(resolve(dir, 'orig'), resolve(dir, 'edit')) + t.match(diff, '--- a/lib/deep/x.js', 'old header uses posix separators') + t.match(diff, '+++ b/lib/deep/x.js', 'new header uses posix separators') +}) + +t.test('identical files produce no diff', async t => { + const dir = t.testdir({ + orig: { 'a.js': 'x\n', sub: { 'b.js': 'y\n' } }, + edit: { 'a.js': 'x\n', sub: { 'b.js': 'y\n' } }, + }) + const { diff } = await diffDirs(resolve(dir, 'orig'), resolve(dir, 'edit')) + t.equal(diff, '', 'empty diff for identical trees') +}) + +t.test('node_modules and .git are ignored', async t => { + const dir = t.testdir({ + orig: { + 'index.js': 'v1\n', + node_modules: { dep: { 'index.js': 'old\n' } }, + '.git': { HEAD: 'ref: refs/heads/main\n' }, + }, + edit: { + 'index.js': 'v2\n', + node_modules: { dep: { 'index.js': 'changed\n' } }, + '.git': { HEAD: 'ref: refs/heads/other\n' }, + }, + }) + const { diff } = await diffDirs(resolve(dir, 'orig'), resolve(dir, 'edit')) + t.match(diff, 'index.js', 'top-level change is captured') + t.notMatch(diff, 'node_modules', 'node_modules contents are excluded') + t.notMatch(diff, 'HEAD', '.git contents are excluded') +}) + +t.test('root package.json is excluded and flagged, nested is kept', async t => { + const dir = t.testdir({ + orig: { + 'package.json': '{ "version": "1.0.0" }\n', + 'index.js': 'a\n', + sub: { 'package.json': '{ "private": true }\n' }, + }, + edit: { + 'package.json': '{ "version": "2.0.0" }\n', + 'index.js': 'b\n', + sub: { 'package.json': '{ "private": false }\n' }, + }, + }) + const { diff, packageJsonChanged } = await diffDirs(resolve(dir, 'orig'), resolve(dir, 'edit')) + t.equal(packageJsonChanged, true, 'root package.json change is flagged') + t.notMatch(diff, 'a/package.json\t', 'root package.json is not in the diff') + t.match(diff, 'a/sub/package.json', 'nested package.json is still diffed') + t.match(diff, 'a/index.js', 'other files are still diffed') +}) + +t.test('packageJsonChanged is false when only other files change', async t => { + const dir = t.testdir({ + orig: { 'package.json': '{ "version": "1.0.0" }\n', 'index.js': 'a\n' }, + edit: { 'package.json': '{ "version": "1.0.0" }\n', 'index.js': 'b\n' }, + }) + const { diff, packageJsonChanged } = await diffDirs(resolve(dir, 'orig'), resolve(dir, 'edit')) + t.equal(packageJsonChanged, false, 'unchanged package.json is not flagged') + t.match(diff, 'a/index.js', 'the real change is captured') +}) + +t.test('non-file entries like symlinks are skipped', async t => { + const dir = t.testdir({ + orig: { 'real.js': 'a\n' }, + edit: { 'real.js': 'b\n' }, + }) + // A symlink is neither a directory nor a regular file so it is ignored. + symlinkSync(resolve(dir, 'orig', 'real.js'), resolve(dir, 'edit', 'link.js')) + const { diff } = await diffDirs(resolve(dir, 'orig'), resolve(dir, 'edit')) + t.match(diff, 'real.js', 'regular file is diffed') + t.notMatch(diff, 'link.js', 'symlink entry is skipped') +}) + +t.test('round-trip: applying the diff reproduces the edited tree', async t => { + const dir = t.testdir({ + orig: { + 'mod.js': 'original line\n', + 'del.js': 'doomed\n', + lib: { deep: { 'x.js': 'before\n' } }, + }, + edit: { + 'mod.js': 'patched line\n', + 'add.js': 'fresh content\n', + lib: { deep: { 'x.js': 'after\n' } }, + }, + }) + const orig = resolve(dir, 'orig') + const { diff } = await diffDirs(orig, resolve(dir, 'edit')) + + // Apply the diff back onto a copy of the original and check the result. + await applyPatchToDir({ patch: diff, cwd: orig }) + + t.equal(read(orig, 'mod.js'), 'patched line\n', 'modified file matches edit') + t.equal(read(orig, 'add.js'), 'fresh content\n', 'added file was created') + t.equal(read(orig, 'lib', 'deep', 'x.js'), 'after\n', 'nested file matches edit') + t.notOk(existsSync(resolve(orig, 'del.js')), 'deleted file was removed') +}) diff --git a/test/lib/utils/queryable.js b/test/lib/utils/queryable.js index fb0db5d021b57..5eca84214cd65 100644 --- a/test/lib/utils/queryable.js +++ b/test/lib/utils/queryable.js @@ -829,7 +829,7 @@ t.test('set arrays', async t => { t.throws( () => qqqqq.set('lorem[]', 4), { code: 'ENOAPPEND' }, - 'should throw error if using empty square bracket in an non-array item' + 'should throw error if using empty square bracket in a non-array item' ) qqqqq.set('lorem[0]', 3) t.strictSame( @@ -960,6 +960,45 @@ t.test('bracket lovers', async t => { '[iLoveBrackets]': 'seriously?', '[0]': '-.-', }, - 'any top-level item can not be parsed with square bracket notation' + 'any top-level item cannot be parsed with square bracket notation' + ) +}) + +t.test('forbidden keys', async t => { + // defensive cleanup in case any assertion below unexpectedly mutates the prototype + t.teardown(() => { + delete Object.prototype.scripts + delete Object.prototype.polluted + }) + + for (const key of ['__proto__', 'constructor', 'prototype']) { + t.throws( + () => new Queryable({ name: 'demo' }).set(`${key}.scripts.postinstall`, 'cmd'), + { code: 'EFORBIDDENKEY' }, + `should throw EFORBIDDENKEY when '${key}' is used as a top-level key` + ) + } + + t.throws( + () => new Queryable({}).set('a.__proto__.scripts.postinstall', 'cmd'), + { code: 'EFORBIDDENKEY' }, + 'should throw when __proto__ appears nested in a dotted path' + ) + + t.throws( + () => new Queryable({}).set('foo[__proto__].scripts.postinstall', 'cmd'), + { code: 'EFORBIDDENKEY' }, + 'should throw when __proto__ is used via square bracket notation' + ) + + t.throws( + () => new Queryable({ scripts: { postinstall: 'x' } }).delete('__proto__.scripts'), + { code: 'EFORBIDDENKEY' }, + 'should block forbidden keys via delete() as well as set()' + ) + + t.notOk( + Object.prototype.scripts, + 'Object.prototype must not be polluted by any forbidden-key attempt' ) }) diff --git a/test/lib/utils/read-user-info.js b/test/lib/utils/read-user-info.js index 35628f7f2faac..74463175f5e8e 100644 --- a/test/lib/utils/read-user-info.js +++ b/test/lib/utils/read-user-info.js @@ -118,3 +118,35 @@ t.test('email - invalid warns and retries', async (t) => { t.equal(result, 'foo@bar.baz', 'received the email') t.equal(logMsg, 'invalid email') }) + +t.test('read-user-info integration works', async (t) => { + t.teardown(() => { + readResult = null + readOpts = null + }) + + readResult = 'regular-input' + const username = await readUserInfo.username('Username: ') + t.equal(username, 'regular-input', 'should return username from regular prompt') + t.notOk(readOpts.silent, 'username prompt should not set silent') + + readResult = 'secret-password' + const password = await readUserInfo.password('Password: ') + t.equal(password, 'secret-password', 'should return password from silent prompt') + t.match(readOpts, { silent: true }, 'password prompt should set silent: true') +}) + +t.test('silent metadata is passed correctly by read-user-info', async (t) => { + t.teardown(() => { + readResult = null + readOpts = null + }) + + readResult = 'username' + await readUserInfo.username('Username: ') + t.notOk(readOpts?.silent, 'username prompt should not set silent') + + readResult = 'password' + await readUserInfo.password('Password: ') + t.equal(readOpts?.silent, true, 'password prompt should set silent: true') +}) diff --git a/test/lib/utils/reify-output.js b/test/lib/utils/reify-output.js index 184f934c97013..06143c1377735 100644 --- a/test/lib/utils/reify-output.js +++ b/test/lib/utils/reify-output.js @@ -13,7 +13,7 @@ const mockReify = async (t, reify, { command, ...config } = {}) => { // Hack to adapt existing fake test. Make npm.command // return whatever was passed in to this function. // What it should be doing is npm.exec(command) but that - // breaks most of these tests because they dont expect + // breaks most of these tests because they don't expect // a command to actually run. Object.defineProperty(mock.npm, 'command', { get () { @@ -310,16 +310,16 @@ t.test('packages changed message', async t => { }, } for (let i = 0; i < added; i++) { - mock.diff.children.push({ action: 'ADD', ideal: { location: 'loc' } }) + mock.diff.children.push({ action: 'ADD', ideal: { path: `test/${i}`, name: `@npmcli/pkg${i}`, location: 'loc', package: { version: `1.0.${i}` } } }) } for (let i = 0; i < removed; i++) { - mock.diff.children.push({ action: 'REMOVE', actual: { location: 'loc' } }) + mock.diff.children.push({ action: 'REMOVE', actual: { path: `test/${i}`, name: `@npmcli/pkg${i}`, location: 'loc', package: { version: `1.0.${i}` } } }) } for (let i = 0; i < changed; i++) { - const actual = { location: 'loc' } - const ideal = { location: 'loc' } + const actual = { path: `test/a/${i}`, name: `@npmcli/pkg${i}`, location: 'loc', package: { version: `1.0.${i}` } } + const ideal = { path: `test/i/${i}`, name: `@npmcli/pkg${i}`, location: 'loc', package: { version: `1.1.${i}` } } mock.diff.children.push({ action: 'CHANGE', actual, ideal }) } @@ -366,7 +366,7 @@ t.test('added packages should be looked up within returned tree', async t => { }, diff: { children: [ - { action: 'ADD', ideal: { name: 'baz' } }, + { action: 'ADD', ideal: { path: 'test/baz', name: 'baz', package: { version: '1.0.0' } } }, ], }, }) @@ -384,7 +384,7 @@ t.test('added packages should be looked up within returned tree', async t => { }, diff: { children: [ - { action: 'ADD', ideal: { name: 'baz' } }, + { action: 'ADD', ideal: { path: 'test/baz', name: 'baz', package: { version: '1.0.0' } } }, ], }, }) @@ -403,12 +403,12 @@ t.test('prints dedupe difference on dry-run', async t => { }, diff: { children: [ - { action: 'ADD', ideal: { name: 'foo', package: { version: '1.0.0' } } }, - { action: 'REMOVE', actual: { name: 'bar', package: { version: '1.0.0' } } }, + { action: 'ADD', ideal: { path: 'test/foo', name: 'foo', package: { version: '1.0.0' } } }, + { action: 'REMOVE', actual: { path: 'test/foo', name: 'bar', package: { version: '1.0.0' } } }, { action: 'CHANGE', - actual: { name: 'bar', package: { version: '1.0.0' } }, - ideal: { package: { version: '2.1.0' } }, + actual: { path: 'test/a/bar', name: 'bar', package: { version: '1.0.0' } }, + ideal: { path: 'test/i/bar', name: 'bar', package: { version: '2.1.0' } }, }, ], }, @@ -431,12 +431,12 @@ t.test('prints dedupe difference on long', async t => { }, diff: { children: [ - { action: 'ADD', ideal: { name: 'foo', package: { version: '1.0.0' } } }, - { action: 'REMOVE', actual: { name: 'bar', package: { version: '1.0.0' } } }, + { action: 'ADD', ideal: { path: 'test/foo', name: 'foo', package: { version: '1.0.0' } } }, + { action: 'REMOVE', actual: { path: 'test/bar', name: 'bar', package: { version: '1.0.0' } } }, { action: 'CHANGE', - actual: { name: 'bar', package: { version: '1.0.0' } }, - ideal: { package: { version: '2.1.0' } }, + actual: { path: 'test/a/bar', name: 'bar', package: { version: '1.0.0' } }, + ideal: { path: 'test/i/bar', name: 'bar', package: { version: '2.1.0' } }, }, ], }, @@ -448,3 +448,171 @@ t.test('prints dedupe difference on long', async t => { t.matchSnapshot(out, 'diff table') }) + +t.test('prints unreviewed install scripts summary', async t => { + const mockReifyWithExtras = async (t, reify, extras, { command, ...config } = {}) => { + const mock = await mockNpm(t, { command, config }) + Object.defineProperty(mock.npm, 'command', { + get () { + return command + }, + enumerable: true, + }) + reifyOutput(mock.npm, reify, extras) + mock.npm.finish() + return mock + } + + const baseReify = { + actualTree: { name: 'host', inventory: { has: () => false } }, + diff: { children: [] }, + } + + const unreviewedScripts = [ + { + node: { packageName: 'canvas', name: 'canvas', version: '2.11.0', path: '/x/canvas' }, + scripts: { install: 'node-gyp rebuild' }, + }, + { + node: { packageName: 'sharp', name: 'sharp', version: '0.33.2', path: '/x/sharp' }, + scripts: { preinstall: 'pre', postinstall: 'post' }, + }, + ] + + const mock = await mockReifyWithExtras(t, baseReify, { unreviewedScripts }) + const warn = mock.logs.warn.byTitle('allow-scripts').join('\n') + t.match(warn, /2 packages had install scripts blocked because they are not covered by allowScripts/) + t.match(warn, /canvas@2\.11\.0 \(install: node-gyp rebuild\)/) + t.match(warn, /sharp@0\.33\.2 \(preinstall: pre; postinstall: post\)/) + t.match(warn, /npm approve-scripts --allow-scripts-pending/) +}) + +t.test('global install suggests --allow-scripts, not approve-scripts', async t => { + const mockReifyWithExtras = async (t, reify, extras, config = {}) => { + const mock = await mockNpm(t, { config }) + reifyOutput(mock.npm, reify, extras) + mock.npm.finish() + return mock + } + + const baseReify = { + actualTree: { name: 'host', inventory: { has: () => false } }, + diff: { children: [] }, + } + + const unreviewedScripts = [ + { + node: { packageName: 'canvas', name: 'canvas', version: '2.11.0', path: '/x/canvas' }, + scripts: { install: 'node-gyp rebuild' }, + }, + { + node: { packageName: 'sharp', name: 'sharp', version: '0.33.2', path: '/x/sharp' }, + scripts: { preinstall: 'pre', postinstall: 'post' }, + }, + ] + + const mock = await mockReifyWithExtras(t, baseReify, { unreviewedScripts }, { global: true }) + const warn = mock.logs.warn.byTitle('allow-scripts').join('\n') + t.match(warn, /2 packages had install scripts blocked because they are not covered by allowScripts/) + t.match(warn, /canvas@2\.11\.0 \(install: node-gyp rebuild\)/) + t.match(warn, /npm install -g --allow-scripts=canvas,sharp/) + t.match(warn, /npm config set allow-scripts=canvas,sharp/) + t.notMatch(warn, /approve-scripts/) +}) + +t.test('single unreviewed script uses singular wording', async t => { + const mockReifyWithExtras = async (t, reify, extras) => { + const mock = await mockNpm(t, {}) + reifyOutput(mock.npm, reify, extras) + mock.npm.finish() + return mock + } + + const mock = await mockReifyWithExtras( + t, + { actualTree: { inventory: { has: () => false } }, diff: { children: [] } }, + { + unreviewedScripts: [{ + node: { packageName: 'one', name: 'one', version: '1.0.0', path: '/x' }, + scripts: { install: 'do' }, + }], + } + ) + t.match(mock.logs.warn.byTitle('allow-scripts').join('\n'), /1 package had install scripts blocked/) +}) + +t.test('optional dep with blocked scripts appears in the summary', async t => { + const mock = await mockNpm(t, {}) + reifyOutput(mock.npm, { + actualTree: { inventory: { has: () => false } }, + diff: { children: [] }, + }, { + unreviewedScripts: [{ + node: { + packageName: 'opt', + name: 'opt', + version: '1.0.0', + path: '/x/opt', + optional: true, + devOptional: true, + }, + scripts: { install: 'cmd' }, + }], + }) + mock.npm.finish() + const warn = mock.logs.warn.byTitle('allow-scripts').join('\n') + t.match(warn, /1 package had install scripts blocked/) + t.match(warn, /opt@1\.0\.0 \(install: cmd\)/) +}) + +t.test('json output includes unreviewedScripts', async t => { + const mock = await mockNpm(t, { config: { json: true } }) + reifyOutput(mock.npm, { + actualTree: { inventory: { size: 0 } }, + diff: null, + }, { + unreviewedScripts: [{ + node: { packageName: 'pkg', name: 'pkg', version: '1.0.0', path: '/x' }, + scripts: { install: 'cmd' }, + }], + }) + mock.npm.finish() + const parsed = JSON.parse(mock.joinedOutput()) + t.match(parsed.unreviewedScripts, [{ + name: 'pkg', + version: '1.0.0', + path: '/x', + scripts: { install: 'cmd' }, + }]) +}) + +t.test('unreviewed script with node.name only (no packageName) still renders', async t => { + const mock = await mockNpm(t, {}) + reifyOutput(mock.npm, { + actualTree: { inventory: { has: () => false } }, + diff: { children: [] }, + }, { + unreviewedScripts: [{ + node: { name: 'fallback', path: '/x' }, // no packageName, no version + scripts: { install: 'cmd' }, + }], + }) + mock.npm.finish() + t.match(mock.logs.warn.byTitle('allow-scripts').join('\n'), / fallback \(install: cmd\)/) +}) + +t.test('json output includes node.name when packageName is missing', async t => { + const mock = await mockNpm(t, { config: { json: true } }) + reifyOutput(mock.npm, { + actualTree: { inventory: { size: 0 } }, + diff: null, + }, { + unreviewedScripts: [{ + node: { name: 'fallback', path: '/x' }, + scripts: { install: 'cmd' }, + }], + }) + mock.npm.finish() + const parsed = JSON.parse(mock.joinedOutput()) + t.equal(parsed.unreviewedScripts[0].name, 'fallback') +}) diff --git a/test/lib/utils/resolve-allow-scripts.js b/test/lib/utils/resolve-allow-scripts.js new file mode 100644 index 0000000000000..0d6cdb8c040ac --- /dev/null +++ b/test/lib/utils/resolve-allow-scripts.js @@ -0,0 +1,347 @@ +const t = require('tap') +const mockNpm = require('../../fixtures/mock-npm') +const tmock = require('../../fixtures/tmock') + +const loadResolver = (t) => tmock(t, '{LIB}/utils/resolve-allow-scripts.js') + +// Helper that simulates config layering. `cliConfig` sets the value at +// the 'cli' source; `npmrcConfig` sets it at the 'user' source. mockNpm +// puts all `config` keys into the 'cli' source by default, so for npmrc +// tests we use an .npmrc file instead. + +t.test('returns null when no policy is set anywhere', async t => { + const { npm } = await mockNpm(t, { + prefixDir: { 'package.json': JSON.stringify({ name: 'p' }) }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm) + t.strictSame(result, { policy: null, source: null }) +}) + +t.test('global install: skips package.json but still consults CLI', async t => { + const { npm } = await mockNpm(t, { + config: { global: true, 'allow-scripts': 'canvas' }, + prefixDir: { 'package.json': JSON.stringify({ name: 'p', allowScripts: { sharp: true } }) }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm) + t.equal(result.source, 'cli') + t.strictSame(result.policy, { canvas: true }) +}) + +t.test('global install: skips package.json but still consults .npmrc', async t => { + const { npm } = await mockNpm(t, { + config: { global: true }, + homeDir: { '.npmrc': 'allow-scripts = canvas' }, + prefixDir: { + 'package.json': JSON.stringify({ name: 'p', allowScripts: { sharp: true } }), + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm) + t.equal(result.source, '.npmrc') + t.strictSame(result.policy, { canvas: true }) +}) + +t.test('global install with no CLI or .npmrc returns null', async t => { + const { npm } = await mockNpm(t, { + config: { global: true }, + prefixDir: { 'package.json': JSON.stringify({ name: 'p', allowScripts: { x: true } }) }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm) + t.strictSame(result, { policy: null, source: null }) +}) + +t.test('reads from package.json when only package.json is set', async t => { + const { npm } = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'p', + allowScripts: { canvas: true, 'core-js': false, 'sharp@0.33.2': true }, + }), + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm) + t.equal(result.source, 'package.json') + t.strictSame(result.policy, { canvas: true, 'core-js': false, 'sharp@0.33.2': true }) +}) + +t.test('--allow-scripts CLI flag is rejected in project-scoped installs', async t => { + const mock = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'p', + allowScripts: { sharp: true }, + }), + }, + // mock-npm puts all config keys at the 'cli' source. + config: { 'allow-scripts': 'canvas' }, + }) + const resolveAllowScripts = loadResolver(t) + await t.rejects( + resolveAllowScripts(mock.npm), + { code: 'EALLOWSCRIPTS', message: /--allow-scripts is not allowed/ } + ) +}) + +t.test('--allow-scripts CLI flag is accepted in global installs (RFC layer 1 wins)', async t => { + const mock = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'p', + allowScripts: { sharp: true }, + }), + }, + config: { 'allow-scripts': 'canvas', global: true }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(mock.npm) + t.equal(result.source, 'cli') + t.strictSame(result.policy, { canvas: true }) +}) + +t.test('package.json wins over .npmrc setting (RFC layer 2 > layer 3)', async t => { + // Put the allow-scripts setting in an .npmrc file so it loads at the + // 'user' source, not 'cli'. + const mock = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'p', + allowScripts: { sharp: true }, + }), + '.npmrc': 'allow-scripts = canvas', + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(mock.npm) + t.equal(result.source, 'package.json') + t.strictSame(result.policy, { sharp: true }) + t.match( + mock.logs.warn.byTitle('allow-scripts'), + [/\.npmrc allow-scripts setting is being ignored because package.json/] + ) +}) + +t.test('.npmrc setting is used when nothing higher is set', async t => { + const { npm } = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'p' }), + '.npmrc': 'allow-scripts = canvas, sharp', + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm) + t.equal(result.source, '.npmrc') + t.strictSame(result.policy, { canvas: true, sharp: true }) +}) + +t.test('--allow-scripts CLI flag is accepted via skipProjectConfig (npm exec)', async t => { + const mock = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'p' }), + '.npmrc': 'allow-scripts = canvas', + }, + config: { 'allow-scripts': 'sharp' }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(mock.npm, { skipProjectConfig: true }) + t.equal(result.source, 'cli') + t.strictSame(result.policy, { sharp: true }) + t.match( + mock.logs.warn.byTitle('allow-scripts'), + [/\.npmrc allow-scripts setting is being ignored because --allow-scripts/] + ) +}) + +t.test('empty allowScripts object in package.json falls through to .npmrc', async t => { + const { npm } = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'p', allowScripts: {} }), + '.npmrc': 'allow-scripts = canvas', + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm) + t.equal(result.source, '.npmrc') + t.strictSame(result.policy, { canvas: true }) +}) + +t.test('missing package.json with .npmrc setting uses .npmrc', async t => { + const { npm } = await mockNpm(t, { + prefixDir: { + '.npmrc': 'allow-scripts = canvas', + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm) + t.equal(result.source, '.npmrc') + t.strictSame(result.policy, { canvas: true }) +}) + +t.test('reads from npm.prefix, not cwd, so workspace sub-installs find root policy', async t => { + const { npm } = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'root', + workspaces: ['packages/*'], + allowScripts: { sharp: true }, + }), + packages: { + sub: { 'package.json': JSON.stringify({ name: 'sub' }) }, + }, + }, + chdir: ({ prefix }) => require('node:path').join(prefix, 'packages', 'sub'), + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm) + t.equal(result.source, 'package.json') + t.strictSame(result.policy, { sharp: true }) +}) + +t.test('drops package.json entries with forbidden semver ranges and warns', async t => { + const mock = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'p', + allowScripts: { + 'sharp@^0.33.0': true, // forbidden: caret range + 'canvas@~2.11.0': true, // forbidden: tilde range + 'core-js@>=3.0.0': true, // forbidden: gte range + 'good@1.2.3': true, // OK: exact pin + 'also-good': true, // OK: bare name + 'disjunction@1.0.0 || 2.0.0': true, // OK: exact disjunction + }, + }), + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(mock.npm) + t.equal(result.source, 'package.json') + t.strictSame(result.policy, { + 'good@1.2.3': true, + 'also-good': true, + 'disjunction@1.0.0 || 2.0.0': true, + }) + const warnings = mock.logs.warn.byTitle('allow-scripts') + t.equal(warnings.filter(m => /semver ranges/.test(m)).length, 3) +}) + +t.test('drops package.json entries with dist-tag specs and warns', async t => { + const mock = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'p', + allowScripts: { + 'sharp@latest': true, // forbidden: dist-tag + 'canvas@next': true, // forbidden: dist-tag + 'good@1.2.3': true, // OK: exact pin + }, + }), + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(mock.npm) + t.equal(result.source, 'package.json') + t.strictSame(result.policy, { 'good@1.2.3': true }) + const warnings = mock.logs.warn.byTitle('allow-scripts') + t.equal(warnings.filter(m => /dist-tag specs/.test(m)).length, 2) +}) + +t.test('drops .npmrc forbidden ranges (and warns) but keeps valid entries', async t => { + const mock = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ name: 'p' }), + '.npmrc': 'allow-scripts = canvas, sharp@^0.33.0, lodash@4.17.21', + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(mock.npm) + t.equal(result.source, '.npmrc') + t.strictSame(result.policy, { canvas: true, 'lodash@4.17.21': true }) + const warnings = mock.logs.warn.byTitle('allow-scripts') + t.ok(warnings.some(m => /sharp@\^0\.33\.0/.test(m) && /semver ranges/.test(m))) +}) + +t.test('drops package.json entries that fail npa parse', async t => { + const mock = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'p', + allowScripts: { + '@@@invalid@@@': true, + good: true, + }, + }), + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(mock.npm) + t.equal(result.source, 'package.json') + t.strictSame(result.policy, { good: true }) + t.ok(mock.logs.warn.byTitle('allow-scripts').some(m => /unparseable/.test(m))) +}) + +t.test('returns null when all package.json entries are dropped as invalid', async t => { + const { npm } = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'p', + allowScripts: { 'sharp@^0.33.0': true }, + }), + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm) + t.strictSame(result, { policy: null, source: null }) +}) + +t.test('skipProjectConfig: ignores package.json even when present', async t => { + // Per RFC line 299, exec/npx consults only user/global .npmrc. + const { npm } = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'p', + allowScripts: { sharp: true }, + }), + '.npmrc': 'allow-scripts = canvas', + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm, { skipProjectConfig: true }) + // package.json is skipped, falls through to .npmrc. + t.equal(result.source, '.npmrc') + t.strictSame(result.policy, { canvas: true }) +}) + +t.test('skipProjectConfig: CLI still wins over .npmrc', async t => { + const { npm } = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'p', + allowScripts: { sharp: true }, + }), + '.npmrc': 'allow-scripts = canvas', + }, + config: { 'allow-scripts': 'lodash' }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm, { skipProjectConfig: true }) + t.equal(result.source, 'cli') + t.strictSame(result.policy, { lodash: true }) +}) + +t.test('skipProjectConfig: returns null when only package.json is set', async t => { + const { npm } = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'p', + allowScripts: { sharp: true }, + }), + }, + }) + const resolveAllowScripts = loadResolver(t) + const result = await resolveAllowScripts(npm, { skipProjectConfig: true }) + t.strictSame(result, { policy: null, source: null }) +}) diff --git a/test/lib/utils/sbom-cyclonedx.js b/test/lib/utils/sbom-cyclonedx.js index da9b3f757988b..5dd5bf606e704 100644 --- a/test/lib/utils/sbom-cyclonedx.js +++ b/test/lib/utils/sbom-cyclonedx.js @@ -83,6 +83,19 @@ t.test('single node - package lock only', t => { t.end() }) +t.test('single node - uses package name for root component name', t => { + const node = { + ...root, + name: '', + packageName: '@scope/root-package', + pkgid: '@scope/root-package@1.0.0', + } + const res = cyclonedxOutput({ npm, nodes: [node] }) + t.equal(res.metadata.component.name, '@scope/root-package') + t.equal(res.metadata.component['bom-ref'], '@scope/root-package@1.0.0') + t.end() +}) + t.test('single node - optional ', t => { const node = { ...root, optional: true } const res = cyclonedxOutput({ npm, nodes: [node] }) @@ -107,7 +120,6 @@ t.test('single node - with author object', t => { }) t.test('single node - with integrity', t => { - /* eslint-disable-next-line max-len */ const node = { ...root, integrity: 'sha512-1RkbFGUKex4lvsB9yhIfWltJM5cZKUftB2eNajaDv3dCMEp49iBG0K14uH8NnX9IPux2+mK7JGEOB0jn48/J6w==' } const res = cyclonedxOutput({ npm, nodes: [node] }) t.matchSnapshot(JSON.stringify(res)) @@ -182,6 +194,53 @@ t.test('single node - with single license', t => { t.end() }) +t.test('single node - with legacy licenses array (single)', t => { + const pkg = { + ...rootPkg, + licenses: [ + { + type: 'MIT', + url: 'http://opensource.org/licenses/mit-license.php', + }, + ], + } + const node = { ...root, package: pkg } + const res = cyclonedxOutput({ npm, nodes: [node] }) + t.matchSnapshot(JSON.stringify(res)) + t.end() +}) + +t.test('single node - with legacy licenses array (multiple)', t => { + const pkg = { + ...rootPkg, + licenses: [ + { + type: 'MIT', + url: 'http://opensource.org/licenses/mit-license.php', + }, + { + type: 'Apache-2.0', + url: 'http://opensource.org/licenses/apache2.0.php', + }, + ], + } + const node = { ...root, package: pkg } + const res = cyclonedxOutput({ npm, nodes: [node] }) + t.matchSnapshot(JSON.stringify(res)) + t.end() +}) + +t.test('single node - with legacy licenses array (string entries)', t => { + const pkg = { + ...rootPkg, + licenses: ['MIT'], + } + const node = { ...root, package: pkg } + const res = cyclonedxOutput({ npm, nodes: [node] }) + t.matchSnapshot(JSON.stringify(res)) + t.end() +}) + t.test('single node - with license expression', t => { const pkg = { ...rootPkg, license: '(MIT OR Apache-2.0)' } const node = { ...root, package: pkg } @@ -233,6 +292,37 @@ t.test('node - with deps', t => { t.end() }) +t.test('node - with duplicate deps', t => { + const node = { + ...root, + edgesOut: [ + { to: dep1 }, + ], + } + const res = cyclonedxOutput({ npm, nodes: [node, dep1, dep1] }) + t.matchSnapshot(JSON.stringify(res)) + t.end() +}) + +t.test('node - with duplicate edges to same dep', t => { + // A node can have multiple outgoing edges resolving to the same + // `name@version` (e.g. a direct `dep1: ^1` plus an alias + // `dep1-aliased: npm:dep1@^1`). The resulting `dependsOn` array must + // still contain each ref at most once, since CycloneDX 1.5 requires + // unique items. + const node = { + ...root, + edgesOut: [ + { to: dep1 }, + { to: dep1 }, + ], + } + const res = cyclonedxOutput({ npm, nodes: [node, dep1] }) + t.same(res.dependencies[0].dependsOn, ['dep1@0.0.1']) + t.matchSnapshot(JSON.stringify(res)) + t.end() +}) + // Check that all of the generated test snapshots validate against the CycloneDX schema t.test('schema validation', t => { // Load schemas diff --git a/test/lib/utils/sbom-spdx.js b/test/lib/utils/sbom-spdx.js index d69e85667dc85..d2599b0824510 100644 --- a/test/lib/utils/sbom-spdx.js +++ b/test/lib/utils/sbom-spdx.js @@ -131,6 +131,53 @@ t.test('single node - with license object', t => { t.end() }) +t.test('single node - with legacy licenses array (single)', t => { + const pkg = { + ...rootPkg, + licenses: [ + { + type: 'MIT', + url: 'http://opensource.org/licenses/mit-license.php', + }, + ], + } + const node = { ...root, package: pkg } + const res = spdxOutput({ npm, nodes: [node] }) + t.matchSnapshot(JSON.stringify(res)) + t.end() +}) + +t.test('single node - with legacy licenses array (multiple)', t => { + const pkg = { + ...rootPkg, + licenses: [ + { + type: 'MIT', + url: 'http://opensource.org/licenses/mit-license.php', + }, + { + type: 'Apache-2.0', + url: 'http://opensource.org/licenses/apache2.0.php', + }, + ], + } + const node = { ...root, package: pkg } + const res = spdxOutput({ npm, nodes: [node] }) + t.matchSnapshot(JSON.stringify(res)) + t.end() +}) + +t.test('single node - with legacy licenses array (string entries)', t => { + const pkg = { + ...rootPkg, + licenses: ['MIT'], + } + const node = { ...root, package: pkg } + const res = spdxOutput({ npm, nodes: [node] }) + t.matchSnapshot(JSON.stringify(res)) + t.end() +}) + t.test('single node - with license expression', t => { const pkg = { ...rootPkg, license: '(MIT OR Apache-2.0)' } const node = { ...root, package: pkg } @@ -163,7 +210,6 @@ t.test('single node - with homepage', t => { }) t.test('single node - with integrity', t => { - /* eslint-disable-next-line max-len */ const node = { ...root, integrity: 'sha512-1RkbFGUKex4lvsB9yhIfWltJM5cZKUftB2eNajaDv3dCMEp49iBG0K14uH8NnX9IPux2+mK7JGEOB0jn48/J6w==' } const res = spdxOutput({ npm, nodes: [node] }) t.matchSnapshot(JSON.stringify(res)) @@ -199,6 +245,38 @@ t.test('node - with deps', t => { t.end() }) +t.test('node - with duplicate deps', t => { + const node = { ...root, + edgesOut: [ + { to: dep1 }, + { to: dep2 }, + ] } + const res = spdxOutput({ npm, nodes: [node, dep1, dep2, dep1, dep2] }) + t.matchSnapshot(JSON.stringify(res)) + t.end() +}) + +t.test('node - with duplicate edges to same dep', t => { + // A node can have multiple outgoing edges resolving to the same + // `name@version` of the same edge type (e.g. a direct `dep1: ^1` plus an + // alias `dep1-aliased: npm:dep1@^1`). The resulting relationships must + // still be unique per (source, target, type) triple. + const node = { ...root, + edgesOut: [ + { to: dep1 }, + { to: dep1 }, + ] } + const res = spdxOutput({ npm, nodes: [node, dep1] }) + const depRels = res.relationships.filter( + r => r.spdxElementId === 'SPDXRef-Package-dep1-0.0.1' + && r.relatedSpdxElement === 'SPDXRef-Package-root-1.0.0' + && r.relationshipType === 'DEPENDENCY_OF' + ) + t.equal(depRels.length, 1) + t.matchSnapshot(JSON.stringify(res)) + t.end() +}) + // Check that all of the generated test snapshots validate against the SPDX schema t.test('schema validation', t => { const ajv = new Ajv() diff --git a/test/lib/utils/strict-allow-scripts-preflight.js b/test/lib/utils/strict-allow-scripts-preflight.js new file mode 100644 index 0000000000000..e0c54105f8863 --- /dev/null +++ b/test/lib/utils/strict-allow-scripts-preflight.js @@ -0,0 +1,221 @@ +const t = require('tap') + +const preflight = require('../../../lib/utils/strict-allow-scripts-preflight.js') + +// Build a node fixture that checkAllowScripts will pick up as "unreviewed": +// registry-resolved, hasInstallScript true, not project root / workspace / +// link, and no allowScripts entry covering it. +const node = ({ + name = 'pkg', + version = '1.0.0', + scripts = { install: 'node-gyp rebuild' }, +} = {}) => ({ + name, + resolved: `https://registry.npmjs.org/${name}/-/${name}-${version}.tgz`, + hasInstallScript: !!Object.keys(scripts).length, + path: `/fake/${name}`, + isProjectRoot: false, + isWorkspace: false, + isLink: false, + package: { name, version, scripts }, +}) + +const tree = (nodes) => ({ + inventory: new Map(nodes.map((n, i) => [`node_modules/${n.name}-${i}`, n])), +}) + +const makeArb = ({ ideal, actual, allowScripts = null } = {}) => { + const arb = { + options: { allowScripts, ignoreScripts: false }, + idealTree: ideal ?? null, + actualTree: actual ?? null, + } + arb.buildIdealTree = async () => arb.idealTree + return arb +} + +t.test('no-op when strictAllowScripts is not set', async t => { + const arb = makeArb({ ideal: tree([node()]) }) + await preflight({ arb, npm: { flatOptions: {} }, idealTreeOpts: {} }) + t.pass('returned without throwing') +}) + +t.test('no-op when dangerouslyAllowAllScripts overrides', async t => { + const arb = makeArb({ ideal: tree([node()]) }) + await preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true, dangerouslyAllowAllScripts: true } }, + idealTreeOpts: {}, + }) + t.pass('returned without throwing') +}) + +t.test('no-op when ignoreScripts overrides', async t => { + const arb = makeArb({ ideal: tree([node()]) }) + arb.options.ignoreScripts = true + await preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: {}, + }) + t.pass('returned without throwing') +}) + +t.test('throws when unreviewed install scripts exist (idealTree path)', async t => { + const arb = makeArb({ ideal: tree([node({ name: 'canvas' }), node({ name: 'sharp' })]) }) + await t.rejects( + preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: {}, + }), + { + code: 'ESTRICTALLOWSCRIPTS', + message: /2 package\(s\) have install scripts not covered/, + } + ) +}) + +t.test('passes when all install-script nodes are explicitly approved', async t => { + const arb = makeArb({ + ideal: tree([node({ name: 'canvas' })]), + allowScripts: { canvas: true }, + }) + await preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: {}, + }) + t.pass('no error thrown') +}) + +t.test('passes when all install-script nodes are explicitly denied', async t => { + const arb = makeArb({ + ideal: tree([node({ name: 'canvas' })]), + allowScripts: { canvas: false }, + }) + await preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: {}, + }) + t.pass('no error thrown') +}) + +t.test('skips buildIdealTree when arb.idealTree already exists (npm ci path)', async t => { + // `npm ci` builds the ideal tree before calling the preflight. The + // helper must not rebuild it. + const ideal = tree([node({ name: 'pre-built' })]) + const arb = makeArb({ ideal, allowScripts: { 'pre-built': true } }) + let buildCalls = 0 + arb.buildIdealTree = async () => { + buildCalls++ + return arb.idealTree + } + await preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: {}, + }) + t.equal(buildCalls, 0, 'buildIdealTree was not called a second time') +}) + +t.test('builds the ideal tree when arb.idealTree is empty (npm install path)', async t => { + // `npm install` does not pre-build the ideal tree. The helper must + // build it so checkAllowScripts has something to walk. + const arb = makeArb({ allowScripts: { 'fresh-pkg': true } }) + let buildCalls = 0 + arb.buildIdealTree = async () => { + buildCalls++ + arb.idealTree = tree([node({ name: 'fresh-pkg' })]) + } + await preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: {}, + }) + t.equal(buildCalls, 1, 'buildIdealTree was called once') +}) + +t.test('uses actualTree when idealTreeOpts is not provided (rebuild path)', async t => { + const arb = makeArb({ actual: tree([node({ name: 'rebuild-pkg' })]) }) + await t.rejects( + preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + }), + { + code: 'ESTRICTALLOWSCRIPTS', + message: /rebuild-pkg@1\.0\.0/, + } + ) +}) + +t.test('error message includes script bodies', async t => { + const arb = makeArb({ + ideal: tree([node({ name: 'canvas', version: '2.11.0', scripts: { install: 'node-gyp rebuild' } })]), + }) + await t.rejects( + preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: {}, + }), + { message: /canvas@2\.11\.0 \(install: node-gyp rebuild\)/ } + ) +}) + +t.test('error label falls back to node.name when package.version is missing', async t => { + // Exercises the `version ? '${name}@${version}' : name` branch in the + // error formatter when a node has no package.version (and the name + // falls back to node.name via `node.package?.name || node.name`). + const bare = { + name: 'no-version-pkg', + resolved: 'https://registry.npmjs.org/no-version-pkg/-/no-version-pkg-1.0.0.tgz', + hasInstallScript: true, + path: '/fake/no-version-pkg', + isProjectRoot: false, + isWorkspace: false, + isLink: false, + package: { scripts: { install: 'node-gyp rebuild' } }, + } + const arb = makeArb({ ideal: tree([bare]) }) + await t.rejects( + preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: {}, + }), + { message: /no-version-pkg \(install: node-gyp rebuild\)/ } + ) +}) + +t.test('project-scoped error suggests approve-scripts / deny-scripts', async t => { + const arb = makeArb({ ideal: tree([node({ name: 'canvas' })]) }) + await t.rejects( + preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: {}, + }), + { message: /Approve them with `npm approve-scripts`/ } + ) +}) + +t.test('global error points at --allow-scripts, not approve-scripts', async t => { + const arb = makeArb({ ideal: tree([node({ name: 'canvas' })]) }) + await t.rejects( + preflight({ + arb, + npm: { global: true, flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: {}, + }), + (err) => { + t.equal(err.code, 'ESTRICTALLOWSCRIPTS') + t.match(err.message, /--allow-scripts/) + t.match(err.message, /npm config set allow-scripts=canvas/) + t.notMatch(err.message, /approve-scripts/) + return true + } + ) +}) diff --git a/test/lib/utils/tar.js b/test/lib/utils/tar.js index a0a37a3356eea..85a95e5776685 100644 --- a/test/lib/utils/tar.js +++ b/test/lib/utils/tar.js @@ -1,3 +1,4 @@ +const path = require('node:path') const t = require('tap') const tar = require('tar') const pack = require('libnpmpack') @@ -163,13 +164,14 @@ t.test('should getContents of a tarball with a node_modules directory included', }, }) + const fileName = path.join(testDir, 'npm-example-v1.tgz') await tar.c({ gzip: true, - file: 'npm-example-v1.tgz', + file: fileName, C: testDir, }, ['package']) - const tarball = await readFile(`npm-example-v1.tgz`) + const tarball = await readFile(fileName) const tarballContents = await getContents({ name: 'my-cool-pkg', @@ -223,3 +225,37 @@ t.test('should getContents of a tarball with a node_modules directory included', }, 'contents are correct') t.end() }) + +t.test('should log byte sizes correctly', async (t) => { + const cases = [ + [0, '0 B', '0B'], + [1, '1 B', '1B'], + [10, '10 B', '10B'], + [999, '999 B', '999B'], + [1000, '1.0 kB', '1.0kB'], + [1001, '1.0 kB', '1.0kB'], + [1500, '1.5 kB', '1.5kB'], + [999999, '1.0 MB', '1.0MB'], + [1000000, '1.0 MB', '1.0MB'], + [999999999, '1.0 GB', '1.0GB'], + [1000000000, '1.0 GB', '1.0GB'], + ] + + for (const [size, expected, expectedNoSpace] of cases) { + const logs = printLogs({ + name: 'pkg', + version: '1.0.0', + files: [ + { path: 'file.txt', size: size }, + ], + bundled: [], + size: size, + unpackedSize: size, + integrity: 'sha512-xxx', + }) + + t.match(logs, `package size: ${expected}`, `package size: ${expected}`) + t.match(logs, `unpacked size: ${expected}`, `unpacked size: ${expected}`) + t.match(logs, `${expectedNoSpace} file.txt`, `file size: ${expectedNoSpace}`) + } +}) diff --git a/test/lib/utils/validate-lockfile.js b/test/lib/utils/validate-lockfile.js index 25939c5f89cda..cee1891f49183 100644 --- a/test/lib/utils/validate-lockfile.js +++ b/test/lib/utils/validate-lockfile.js @@ -1,5 +1,102 @@ const t = require('tap') const validateLockfile = require('../../../lib/utils/validate-lockfile.js') +const { validatePackageExtensions } = require('../../../lib/utils/validate-lockfile.js') + +// build mock virtual/ideal trees for validatePackageExtensions +const tree = ({ hash = null, packageExtensions, nodes = [] }) => ({ + meta: { packageExtensionsHash: hash }, + target: { package: packageExtensions === undefined ? {} : { packageExtensions } }, + inventory: { values: () => nodes }, +}) + +t.test('packageExtensions: matching hashes and clean tree', async t => { + const errors = validatePackageExtensions( + tree({ hash: 'sha512-abc' }), + tree({ hash: 'sha512-abc' }) + ) + t.strictSame(errors, [], 'no errors when hashes match and no provenance') +}) + +t.test('packageExtensions: both absent', async t => { + t.strictSame(validatePackageExtensions(tree({}), tree({})), [], 'no errors when neither has state') +}) + +t.test('packageExtensions: missing from lock file', async t => { + const errors = validatePackageExtensions(tree({ hash: null }), tree({ hash: 'sha512-abc' })) + t.match(errors[0], /Missing: packageExtensions state from lock file/, 'reports missing lock state') +}) + +t.test('packageExtensions: present in lock but not package.json', async t => { + const errors = validatePackageExtensions(tree({ hash: 'sha512-abc' }), tree({ hash: null })) + t.match(errors[0], /lock file records packageExtensions state but package.json has none/, 'reports stray lock state') +}) + +t.test('packageExtensions: hash mismatch', async t => { + const errors = validatePackageExtensions(tree({ hash: 'sha512-aaa' }), tree({ hash: 'sha512-bbb' })) + t.match(errors[0], /do not match the lock file/, 'reports a mismatch') +}) + +t.test('packageExtensions: stale provenance with matching hash', async t => { + // both hashes equal, but a locked node references a selector that no longer exists + const node = { name: 'foo', version: '1.0.0', packageExtensionsApplied: { selector: 'foo@1', dependencies: ['bar'] } } + const errors = validatePackageExtensions( + tree({ hash: 'h', nodes: [node] }), + tree({ hash: 'h', packageExtensions: {} }) + ) + t.match(errors[0], /stale packageExtensions provenance for foo@1.0.0/, 'reports stale provenance') +}) + +t.test('packageExtensions: valid provenance with matching hash', async t => { + const node = { name: 'foo', version: '1.0.0', packageExtensionsApplied: { selector: 'foo@1', dependencies: ['bar'] } } + // root and workspace nodes are skipped by the validation + const root = { name: 'root', version: '1.0.0', isProjectRoot: true } + const errors = validatePackageExtensions( + tree({ hash: 'h', nodes: [root, node] }), + tree({ hash: 'h', packageExtensions: { 'foo@1': { dependencies: { bar: '^1' } } } }) + ) + t.strictSame(errors, [], 'no errors when provenance still matches a selector') +}) + +t.test('packageExtensions: ideal tree without a target uses the tree itself', async t => { + const idealTree = { + meta: { packageExtensionsHash: 'h' }, + package: { packageExtensions: { 'foo@1': { dependencies: { bar: '^1' } } } }, + inventory: { values: () => [] }, + } + t.strictSame(validatePackageExtensions(tree({ hash: 'h' }), idealTree), [], 'reads package off the tree directly') +}) + +t.test('packageExtensions: invalid rule set surfaces the engine error', async t => { + const errors = validatePackageExtensions( + tree({ hash: 'h' }), + tree({ hash: 'h', packageExtensions: { foo: { devDependencies: { a: '1' } } } }) + ) + t.match(errors[0], /Invalid: .*unsupported field/, 'reports the engine validation error') +}) + +t.test('packageExtensions: alias node matches the underlying package name', async t => { + // an aliased install: node.name is the alias, node.packageName is the real package + const node = { + name: 'my-alias', + packageName: 'real-pkg', + version: '1.0.0', + packageExtensionsApplied: { selector: 'real-pkg@1', dependencies: ['bar'] }, + } + const errors = validatePackageExtensions( + tree({ hash: 'h', nodes: [node] }), + tree({ hash: 'h', packageExtensions: { 'real-pkg@1': { dependencies: { bar: '^1' } } } }) + ) + t.strictSame(errors, [], 'provenance validated against the underlying package name, not the alias') +}) + +t.test('packageExtensions: locked identity matching two selectors', async t => { + const node = { name: 'foo', version: '1.0.0' } + const errors = validatePackageExtensions( + tree({ hash: 'h', nodes: [node] }), + tree({ hash: 'h', packageExtensions: { foo: { dependencies: { a: '^1' } }, 'foo@1': { dependencies: { b: '^1' } } } }) + ) + t.match(errors[0], /Multiple packageExtensions selectors match foo@1.0.0/, 'reports a selector conflict') +}) t.test('identical inventory for both idealTree and virtualTree', async t => { t.matchSnapshot( @@ -67,6 +164,38 @@ t.test('mismatching versions on inventory', async t => { ) }) +t.test('mismatching patch integrity or path', async t => { + t.matchSnapshot( + validateLockfile( + new Map([ + ['foo', { name: 'foo', version: '1.0.0', patched: { path: 'patches/foo.patch', integrity: 'sha512-aaa' } }], + ['bar', { name: 'bar', version: '2.0.0', patched: { path: 'patches/bar.patch', integrity: 'sha512-bbb' } }], + ['baz', { name: 'baz', version: '3.0.0' }], + ]), + new Map([ + ['foo', { name: 'foo', version: '1.0.0', patched: { path: 'patches/foo.patch', integrity: 'sha512-CHANGED' } }], + ['bar', { name: 'bar', version: '2.0.0', patched: { path: 'patches/moved.patch', integrity: 'sha512-bbb' } }], + ['baz', { name: 'baz', version: '3.0.0', patched: { path: 'patches/baz.patch', integrity: 'sha512-ccc' } }], + ]) + ), + 'should error on integrity drift, path drift, and a newly added patch' + ) +}) + +t.test('lock file records a patch package.json no longer declares', async t => { + t.matchSnapshot( + validateLockfile( + new Map([ + ['foo', { name: 'foo', version: '1.0.0', patched: { path: 'patches/foo.patch', integrity: 'sha512-aaa' } }], + ]), + new Map([ + ['foo', { name: 'foo', version: '1.0.0' }], + ]) + ), + 'should report a stray lock file patch' + ) +}) + t.test('missing virtualTree inventory', async t => { t.matchSnapshot( validateLockfile( @@ -80,3 +209,41 @@ t.test('missing virtualTree inventory', async t => { 'should have errors for each mismatching version' ) }) + +const { validateNpmExtension } = require('../../../lib/utils/validate-lockfile.js') + +// build a mock virtual tree with a root hash and optional provenance-bearing nodes +const extVirtual = (hash, nodes = []) => ({ + meta: { npmExtensionHash: hash }, + inventory: { values: () => nodes }, +}) + +t.test('npmExtension: matching hashes', async t => { + t.strictSame(validateNpmExtension(extVirtual('h'), 'h'), [], 'no errors when hashes match') +}) + +t.test('npmExtension: both absent', async t => { + t.strictSame(validateNpmExtension(extVirtual(null), null), [], 'no errors when both absent') +}) + +t.test('npmExtension: missing from lock file', async t => { + const errors = validateNpmExtension(extVirtual(null), 'h') + t.match(errors[0], /Missing: \.npm-extension state from lock file/, 'reports missing lock state') +}) + +t.test('npmExtension: present in lock but no file', async t => { + const errors = validateNpmExtension(extVirtual('h'), null) + t.match(errors[0], /records \.npm-extension state but no \.npm-extension file is present/, 'reports stray lock state') +}) + +t.test('npmExtension: hash mismatch', async t => { + const errors = validateNpmExtension(extVirtual('h1'), 'h2') + t.match(errors[0], /\.npm-extension file does not match the lock file/, 'reports a hash mismatch') +}) + +t.test('npmExtension: provenance without a root hash and no file fails', async t => { + const nodes = [{ name: 'foo', npmExtensionApplied: { extensionPoint: 'transformManifest', dependencies: ['bar'] } }] + const errors = validateNpmExtension(extVirtual(null, nodes), null) + t.match(errors[0], /records \.npm-extension state but no \.npm-extension file is present/, + 'per-node provenance counts as extension state even without a root hash') +}) diff --git a/test/lib/utils/warn-workspace-allow-scripts.js b/test/lib/utils/warn-workspace-allow-scripts.js new file mode 100644 index 0000000000000..c9a5727157c21 --- /dev/null +++ b/test/lib/utils/warn-workspace-allow-scripts.js @@ -0,0 +1,108 @@ +const t = require('tap') +const { + findWorkspaceAllowScripts, + warnWorkspaceAllowScripts, +} = require('../../../lib/utils/warn-workspace-allow-scripts.js') + +const node = ({ + name = 'pkg', + packageName, + isWorkspace = false, + isProjectRoot = false, + allowScripts, + path = `/fake/${name}`, +} = {}) => ({ + name, + packageName: packageName ?? name, + path, + isWorkspace, + isProjectRoot, + package: allowScripts !== undefined ? { allowScripts } : {}, +}) + +const tree = (nodes) => ({ + inventory: new Map(nodes.map((n, i) => [`node_modules/${n.name || `n${i}`}`, n])), +}) + +t.test('returns [] for empty tree', async t => { + t.strictSame(findWorkspaceAllowScripts(tree([])), []) +}) + +t.test('returns [] for missing tree', async t => { + t.strictSame(findWorkspaceAllowScripts(null), []) + t.strictSame(findWorkspaceAllowScripts(undefined), []) +}) + +t.test('ignores project root with allowScripts', async t => { + const t1 = tree([ + node({ name: 'root', isProjectRoot: true, isWorkspace: true, allowScripts: { x: true } }), + ]) + t.strictSame(findWorkspaceAllowScripts(t1), []) +}) + +t.test('ignores non-workspace dep with allowScripts', async t => { + const t1 = tree([ + node({ name: 'dep', allowScripts: { x: true } }), + ]) + t.strictSame(findWorkspaceAllowScripts(t1), []) +}) + +t.test('finds non-root workspace with allowScripts', async t => { + const ws = node({ name: 'ws', isWorkspace: true, allowScripts: { x: true } }) + const t1 = tree([ + node({ name: 'root', isProjectRoot: true, isWorkspace: true }), + ws, + ]) + t.equal(findWorkspaceAllowScripts(t1).length, 1) + t.equal(findWorkspaceAllowScripts(t1)[0], ws) +}) + +t.test('finds workspace with empty allowScripts object too', async t => { + const ws = node({ name: 'ws', isWorkspace: true, allowScripts: {} }) + t.equal(findWorkspaceAllowScripts(tree([ws])).length, 1) +}) + +t.test('warnWorkspaceAllowScripts emits one log.warn per offender', async t => { + const warnings = [] + const listener = (level, ...args) => { + if (level === 'warn') { + warnings.push(args) + } + } + process.on('log', listener) + t.teardown(() => process.off('log', listener)) + + const t1 = tree([ + node({ name: 'root', isProjectRoot: true, isWorkspace: true }), + node({ name: 'a', isWorkspace: true, allowScripts: { x: true } }), + node({ name: 'b', isWorkspace: true, allowScripts: { y: false } }), + node({ name: 'c', isWorkspace: true }), // no allowScripts; no warning + ]) + warnWorkspaceAllowScripts(t1) + + t.equal(warnings.length, 2) + t.match(warnings[0][1], /allowScripts in workspace a/) + t.match(warnings[1][1], /allowScripts in workspace b/) +}) + +t.test('warnWorkspaceAllowScripts uses node.name when packageName missing', async t => { + const warnings = [] + const listener = (level, ...args) => { + if (level === 'warn') { + warnings.push(args) + } + } + process.on('log', listener) + t.teardown(() => process.off('log', listener)) + + // packageName undefined, name set + const ws = { + name: 'fallback-name', + path: '/x', + isWorkspace: true, + isProjectRoot: false, + package: { allowScripts: { x: true } }, + } + warnWorkspaceAllowScripts({ inventory: new Map([['node_modules/ws', ws]]) }) + t.match(warnings[0][1], /workspace fallback-name/) +}) diff --git a/workspaces/arborist/.gitignore b/workspaces/arborist/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/workspaces/arborist/.gitignore +++ b/workspaces/arborist/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/workspaces/arborist/CHANGELOG.md b/workspaces/arborist/CHANGELOG.md index 76a1361d6f8ec..177fc16c1a1d6 100644 --- a/workspaces/arborist/CHANGELOG.md +++ b/workspaces/arborist/CHANGELOG.md @@ -1,5 +1,329 @@ # Changelog +## [10.0.0-pre.1](https://github.com/npm/cli/compare/arborist-v10.0.0-pre.0...arborist-v10.0.0-pre.1) (2026-06-19) +### ⚠️ BREAKING CHANGES +* Preserve https protocol when working with git (#8703) +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +### Features +* [`ce7681f`](https://github.com/npm/cli/commit/ce7681fe7dbcc20abb5f1379558e14ddd069654f) [#9496](https://github.com/npm/cli/pull/9496) packageExtensions for root-owned dependency manifest repairs (#9496) (@manzoorwanijk) +* [`1db885c`](https://github.com/npm/cli/commit/1db885c84b2dfc5126ab663abb12262b533922c1) [#9439](https://github.com/npm/cli/pull/9439) native dependency patching (npm patch add/commit/update/ls/rm) (#9439) (@manzoorwanijk) +* [`be8053c`](https://github.com/npm/cli/commit/be8053c390a2be3902b9382d3c7d4ad9012fa1c2) [#9544](https://github.com/npm/cli/pull/9544) warn when min-release-age blocks an audit fix (#9544) (@JamieMagee) +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +* [`c3e1a71`](https://github.com/npm/cli/commit/c3e1a7175c6475553e212e2f7671bd31bfe07aba) [#9532](https://github.com/npm/cli/pull/9532) add min-release-age-exclude config (@JamieMagee, @caseyjhol) +* [`5cd5150`](https://github.com/npm/cli/commit/5cd5150d3e85dcf5d246e7e5c9de216c2ff849db) [#9424](https://github.com/npm/cli/pull/9424) default-deny install scripts (allowScripts opt-in) [v12] (@JamieMagee) +* [`64e3f79`](https://github.com/npm/cli/commit/64e3f798344e66f4c500636cb8aec5c8111a1fe9) [#9480](https://github.com/npm/cli/pull/9480) allowScripts tooling and inBundle hardening (#9480) (@JamieMagee) +* [`7068d42`](https://github.com/npm/cli/commit/7068d4286eb446fdb0ded08d15d7b5c3883d80f5) [#9360](https://github.com/npm/cli/pull/9360) Phase 1 of `allowScripts` opt-in install-script policy (#9360) (@JamieMagee) +### Bug Fixes +* [`e96a7de`](https://github.com/npm/cli/commit/e96a7decbd00d637ec8d9121c62cef2930abbb69) [#8703](https://github.com/npm/cli/pull/8703) Preserve https protocol when working with git (#8703) (@oldium) +* [`afce424`](https://github.com/npm/cli/commit/afce42408b4643d01ce0c9303effe8f94cc02d64) [#9551](https://github.com/npm/cli/pull/9551) arborist: expose store node_modules via NODE_PATH for linked-strategy install scripts (#9551) (@manzoorwanijk) +* [`8bbd70d`](https://github.com/npm/cli/commit/8bbd70d939cec237b4e045993955895971c9eb85) [#9550](https://github.com/npm/cli/pull/9550) arborist: allow-remote exemption for proxy/mirror-fronted registry tarballs (#9550) (@manzoorwanijk) +* [`315e3bd`](https://github.com/npm/cli/commit/315e3bd7c8ece0e118131c423deb6c8240695089) [#9574](https://github.com/npm/cli/pull/9574) arborist: drop orphaned patch entry on uninstall instead of EPATCHUNUSED (#9574) (@manzoorwanijk) +* [`62b0694`](https://github.com/npm/cli/commit/62b0694d5ec4c529076bf968c3fe6cd47c3f2bb0) [#9576](https://github.com/npm/cli/pull/9576) patch: explain out-of-sync lockfile after --ignore-patch-failures (#9576) (@manzoorwanijk) +* [`cfda867`](https://github.com/npm/cli/commit/cfda86742b2cfd992c730a5ec5cfd74ef863104a) [#9570](https://github.com/npm/cli/pull/9570) arborist: warn once for workspace packageExtensions selector match (#9570) (@manzoorwanijk) +* [`f9c977c`](https://github.com/npm/cli/commit/f9c977c2e28896a31e873ed8ffe0ec88b30ec8ef) [#9569](https://github.com/npm/cli/pull/9569) arborist: re-apply packageExtensions to the linked actual tree (#9569) (@manzoorwanijk) +* [`fc3ef5a`](https://github.com/npm/cli/commit/fc3ef5a096854a73817af407fabb5eb5f98b50b1) [#9559](https://github.com/npm/cli/pull/9559) adapt to @npmcli/run-script@11 breaking changes (@owlstronaut) +* [`fc6268a`](https://github.com/npm/cli/commit/fc6268ab7fa4ce1dcaefd6cd470a1f73eb192565) [#9523](https://github.com/npm/cli/pull/9523) keep nested file: deps and re-resolve changed git refs (#9523) (@owlstronaut) +* [`34dbdf5`](https://github.com/npm/cli/commit/34dbdf51ce4877055fe46751c15c4a445694256f) [#9525](https://github.com/npm/cli/pull/9525) arborist: enforce allowScripts for file:/link: dep scripts (@JamieMagee) +* [`d70e116`](https://github.com/npm/cli/commit/d70e116f01af63bac49ad611cd63ac7709bb0bc5) [#9510](https://github.com/npm/cli/pull/9510) arborist: honor allow-remote=root for root-direct remote tarballs (#9510) (@manzoorwanijk) +* [`4bcba54`](https://github.com/npm/cli/commit/4bcba546420119ebf9ee73e903b00b757f643fdf) [#9495](https://github.com/npm/cli/pull/9495) arborist: apply registry-tarball allow-remote exemption in linked strategy (#9495) (@manzoorwanijk) +* [`2cbb13b`](https://github.com/npm/cli/commit/2cbb13b77edd9410704eac6f30ffea30a18c7046) [#9490](https://github.com/npm/cli/pull/9490) recognize allowScripts for local link targets (#9490) (@cyphercodes, @cyphercodes) +* [`bf623e0`](https://github.com/npm/cli/commit/bf623e0a9ea568a47b777c563e48a097cb12e442) [#9473](https://github.com/npm/cli/pull/9473) validate registry path for allow-remote tarballs (@Abhinav-143x) +* [`a105799`](https://github.com/npm/cli/commit/a10579959a5ed83d459f4c6d2f039ef5b62b4ff1) [#9461](https://github.com/npm/cli/pull/9461) arborist: link meta-only optional peers in linked strategy (@manzoorwanijk) +* [`275bc69`](https://github.com/npm/cli/commit/275bc6934cc2d7c645e2c18dc2c12dc75d148e61) [#9441](https://github.com/npm/cli/pull/9441) arborist: clean up orphaned scoped store entries in linked strategy (@manzoorwanijk) +* [`9f3c97f`](https://github.com/npm/cli/commit/9f3c97f83443ee00b9ca6beaf3e8cec95d3199ad) [#9452](https://github.com/npm/cli/pull/9452) sanitize package name in linked-strategy path construction (@owlstronaut) +* [`a81f2f8`](https://github.com/npm/cli/commit/a81f2f8f4e89c202e57c32b60ee9d27020b49be0) [#9428](https://github.com/npm/cli/pull/9428) arborist: read install scripts from disk on lockfile installs instead of a sentinel (@JamieMagee) +* [`c5292fa`](https://github.com/npm/cli/commit/c5292fa8a09a56b25394d393faf21e47ffb096c0) [#9422](https://github.com/npm/cli/pull/9422) use prerelease strategy without a bug (@owlstronaut) +* [`dac7ff6`](https://github.com/npm/cli/commit/dac7ff6d3d62422bb8dad136fcb8f48e99a4594a) [#9399](https://github.com/npm/cli/pull/9399) arborist: drop self-link materialization for undeclared workspaces (#9399) (@manzoorwanijk) +* [`b77850e`](https://github.com/npm/cli/commit/b77850e550a15c6205fdafc9e3843323b7135923) [#9395](https://github.com/npm/cli/pull/9395) skip hidden lockfile save on dry run (#9395) (@puneetdixit200, @puneetdixit200) +### Dependencies +* [`cc45055`](https://github.com/npm/cli/commit/cc450554861ec9f6ec8f1c4494fa9144379eb741) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/node-gyp@6.0.0` +* [`a12e2c8`](https://github.com/npm/cli/commit/a12e2c8f40e0d551e79f12df25e1f1d93ac90ac5) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/name-from-folder@5.0.0` +* [`cc96d57`](https://github.com/npm/cli/commit/cc96d57246df7cbcaedca6c2540d4e45190d9bb8) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/installed-package-contents@5.0.0` +* [`b62db95`](https://github.com/npm/cli/commit/b62db95b7768049f58a0aca0d7266cba6ed17757) [#9559](https://github.com/npm/cli/pull/9559) `bin-links@7.0.0` +* [`2f5da83`](https://github.com/npm/cli/commit/2f5da83be1e90f00542f0445f06b142084f1ec5a) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/fs@6.0.0` +* [`1502286`](https://github.com/npm/cli/commit/15022869509f110510fa8336144500108cdc6677) [#9559](https://github.com/npm/cli/pull/9559) `ssri@14.0.0` +* [`21df0ab`](https://github.com/npm/cli/commit/21df0ab3c629496511a3c481ee721b0e62c16e92) [#9559](https://github.com/npm/cli/pull/9559) `proc-log@7.0.0` +* [`8f85646`](https://github.com/npm/cli/commit/8f856463d0e85f7083312b3825d0b72304f369e7) [#9559](https://github.com/npm/cli/pull/9559) `parse-conflict-json@6.0.0` +* [`a44c1cf`](https://github.com/npm/cli/commit/a44c1cf1635de5ecda02ed80af70f5d7360111b6) [#9559](https://github.com/npm/cli/pull/9559) `pacote@22.0.0` +* [`1f9c567`](https://github.com/npm/cli/commit/1f9c56792493f80fb3b3d61710086ed748312f2a) [#9559](https://github.com/npm/cli/pull/9559) `npm-registry-fetch@20.0.1` +* [`998ff1d`](https://github.com/npm/cli/commit/998ff1d50816061706c88c56664d131fcfe83f31) [#9559](https://github.com/npm/cli/pull/9559) `npm-pick-manifest@12.0.0` +* [`d80859a`](https://github.com/npm/cli/commit/d80859a2dd97376e4ea621812b3bc7de6a218d21) [#9559](https://github.com/npm/cli/pull/9559) `npm-package-arg@14.0.0` +* [`5e1d513`](https://github.com/npm/cli/commit/5e1d513b9c5e8eef7e318125bd2c34276ffe3858) [#9559](https://github.com/npm/cli/pull/9559) `npm-install-checks@9.0.0` +* [`471309f`](https://github.com/npm/cli/commit/471309f580efdf7f8055020ac0a08610f692a4f4) [#9559](https://github.com/npm/cli/pull/9559) `nopt@10.0.1` +* [`d867351`](https://github.com/npm/cli/commit/d867351cf9d3b75956b555659040c56334f8f4c1) [#9559](https://github.com/npm/cli/pull/9559) `hosted-git-info@10.1.1` +* [`66d46bc`](https://github.com/npm/cli/commit/66d46bc23909f06433237985452c0102181e8fc9) [#9559](https://github.com/npm/cli/pull/9559) `cacache@21.0.1` +* [`9d13ebf`](https://github.com/npm/cli/commit/9d13ebfc2adca5543e4797632039adaa7a318985) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/run-script@11.0.0` +* [`27c4dcc`](https://github.com/npm/cli/commit/27c4dcc7e4aa3521563c1af80617e7697d88cd16) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/redact@5.0.0` +* [`0be6ae2`](https://github.com/npm/cli/commit/0be6ae21c79eb3986a76d5d769d5dd5ef00283c2) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/package-json@8.0.0` +* [`f86a019`](https://github.com/npm/cli/commit/f86a0198bec5a70153bbb29d276fddb30c682792) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/metavuln-calculator@10.0.0` +* [`4d234b2`](https://github.com/npm/cli/commit/4d234b22e59416f6307eb75bef52ac9b43ee6628) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/map-workspaces@6.0.0` +### Chores +* [`1453954`](https://github.com/npm/cli/commit/1453954f9328a6b2480c183f9d1903ac93764915) [#9559](https://github.com/npm/cli/pull/9559) `nock@14.0.0` (@owlstronaut) +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) + +## [10.0.0-pre.0.0](https://github.com/npm/cli/compare/arborist-v9.4.2...arborist-v10.0.0-pre.0.0) (2026-05-20) +### ⚠️ BREAKING CHANGES +* `npm shrinkwrap` is removed, the `shrinkwrap` config alias is removed, and `npm-shrinkwrap.json` is no longer loaded or honored at the project root or from inside dependency tarballs. Rename project-root `npm-shrinkwrap.json` to `package-lock.json`; use `bundleDependencies` if you need to ship a locked dependency tree. +### Features +* [`e0f12f7`](https://github.com/npm/cli/commit/e0f12f7e57aca36f71c9615bd971f427ed23e91a) [#9348](https://github.com/npm/cli/pull/9348) add allow-git/allow-file/allow-directory/allow-remote configs (@owlstronaut) +* [`b8655c7`](https://github.com/npm/cli/commit/b8655c7b12a3e299b159f879a2b1dfed71016ec2) [#9282](https://github.com/npm/cli/pull/9282) arborist: add lockfileString() for in-memory lockfile generation (@ljharb) +* [`2e5dcad`](https://github.com/npm/cli/commit/2e5dcad17a59ee9f69eeec27fc5b087b5b032df7) [#9262](https://github.com/npm/cli/pull/9262) drop npm-shrinkwrap.json support (@owlstronaut) +### Bug Fixes +* [`822ce86`](https://github.com/npm/cli/commit/822ce861a056c599be38ddf58683179f4c9bd9c6) [#9343](https://github.com/npm/cli/pull/9343) arborist: skip lockfile entries for optional deps with incomplete manifests (#9343) (@ecanturk, @owlstronaut) +* [`2c9587e`](https://github.com/npm/cli/commit/2c9587e92b4490bcfb6e7cef6beb5ee6d9c9b730) [#9359](https://github.com/npm/cli/pull/9359) arborist: only forward Link overrides when a rule names a target dep (@manzoorwanijk) +* [`f550eb4`](https://github.com/npm/cli/commit/f550eb415de0aff83a5fa297850104f5390a6e30) [#9348](https://github.com/npm/cli/pull/9348) refactor #failureNode, adjust tests and safety (@owlstronaut) +* [`1f17566`](https://github.com/npm/cli/commit/1f17566ad90353b88e81fa1f8a4da5879d3ec7a3) [#9348](https://github.com/npm/cli/pull/9348) allow-remote=none does not block registry tarballs (@owlstronaut) +* [`81793ae`](https://github.com/npm/cli/commit/81793aeabcd862ed2be3d62b7864bf7ea34d0b2b) [#9332](https://github.com/npm/cli/pull/9332) arborist: skip extraneous fsChildren in linked-strategy reify (@manzoorwanijk) +* [`4c7f6ba`](https://github.com/npm/cli/commit/4c7f6baf70bba8200b4a9fe335fd66d3e8314523) [#9330](https://github.com/npm/cli/pull/9330) arborist: prune removed-workspace entries from package-lock.json (@manzoorwanijk) +* [`076551b`](https://github.com/npm/cli/commit/076551b8724741b0c615b26d44595348c3111dc2) [#9309](https://github.com/npm/cli/pull/9309) arborist: clean up orphan top-level symlinks in linked strategy (#9309) (@manzoorwanijk) +* [`32940e2`](https://github.com/npm/cli/commit/32940e231e34121aaf378309361b4b34fafdf939) [#9299](https://github.com/npm/cli/pull/9299) arborist: ignore hidden entries in global update (#9299) (@Grynn) +* [`0629fbf`](https://github.com/npm/cli/commit/0629fbf736eafcb555428d96bd86a69f8e791d70) [#9283](https://github.com/npm/cli/pull/9283) prefer existing tree nodes for peerOptional deps (#9249) (#9283) (@everett1992) +* [`bc32d94`](https://github.com/npm/cli/commit/bc32d94d3845078784603022e9c3504e1c5cde4a) [#9198](https://github.com/npm/cli/pull/9198) arborist: propagate overrides through Link nodes to targets (#9198) (@manzoorwanijk) +* [`1ab20c8`](https://github.com/npm/cli/commit/1ab20c8abd58cadc976429bb3b7b35cd6b627db4) [#9235](https://github.com/npm/cli/pull/9235) arborist: fix infinite loop with bundledDependencies and overrides (#9235) (@everett1992) +* [`0dc5585`](https://github.com/npm/cli/commit/0dc5585fa284f5c8cac36579983119304775c1c8) [#9167](https://github.com/npm/cli/pull/9167) arborist: handle `npm link` with install-strategy=linked (@manzoorwanijk) +* [`1d058b0`](https://github.com/npm/cli/commit/1d058b0cc7161fa728cba2020a265a81e0ec7cdf) [#9221](https://github.com/npm/cli/pull/9221) arborist: do not install inert optional extraneous shared dependencies (#9221) (@lovell) +* [`dcad8ec`](https://github.com/npm/cli/commit/dcad8ec1f830874d2ec1c3312f2c15d03109ce49) [#9206](https://github.com/npm/cli/pull/9206) pass _isRoot context where missing (#9206) (@wraithgar) +### Chores +* [`b61281d`](https://github.com/npm/cli/commit/b61281da2d4e0a60a93f7138392bfc5893595705) [#9349](https://github.com/npm/cli/pull/9349) change test wording to not collide with tap (#9349) (@owlstronaut) + +## [9.4.2](https://github.com/npm/cli/compare/arborist-v9.4.1...arborist-v9.4.2) (2026-03-18) +### Bug Fixes +* [`21ea382`](https://github.com/npm/cli/commit/21ea382a60b3693ff6c44c81447caa5d0294169c) [#9110](https://github.com/npm/cli/pull/9110) arborist: resolve sibling override sets via common ancestor (#9110) (@manzoorwanijk) +* [`51365b1`](https://github.com/npm/cli/commit/51365b1b8a7924d082f00c27a4aedcb1f81110ec) [#9107](https://github.com/npm/cli/pull/9107) arborist: update store symlinks when hash changes in linked strategy (#9107) (@manzoorwanijk) +* [`8e0a731`](https://github.com/npm/cli/commit/8e0a7315d0719227c83ce9921c2bd56d201ad3ca) [#9108](https://github.com/npm/cli/pull/9108) arborist: skip linked actual tree diff in package-lock-only mode (#9108) (@manzoorwanijk) + +## [9.4.1](https://github.com/npm/cli/compare/arborist-v9.4.0...arborist-v9.4.1) (2026-03-10) +### Bug Fixes +* [`5b7c0cc`](https://github.com/npm/cli/commit/5b7c0cc83b6957a2478aff90b64343555919da84) [#9096](https://github.com/npm/cli/pull/9096) arborist: exclude store nodes from :root > * in linked strategy (#9096) (@manzoorwanijk) +* [`3b70a9d`](https://github.com/npm/cli/commit/3b70a9d1ade5aa5e7edebd0dbc84f0c5f6f202a9) [#9097](https://github.com/npm/cli/pull/9097) arborist: simplify rootDeclaredDeps initialization (#9097) (@manzoorwanijk) +* [`c7702d0`](https://github.com/npm/cli/commit/c7702d044907e56e06c769fa7a42ed1ed308f29a) [#9094](https://github.com/npm/cli/pull/9094) arborist: fix non-idempotent linked install with workspace projects (#9094) (@manzoorwanijk) +* [`1a744b5`](https://github.com/npm/cli/commit/1a744b5e030c82ec205ef2be1995ec8d36fba49b) [#9081](https://github.com/npm/cli/pull/9081) arborist: omit root dev deps in linked strategy when shared with workspaces (#9081) (@manzoorwanijk) +* [`ff51827`](https://github.com/npm/cli/commit/ff51827ba603b069afababf0292016ffb8841bd2) [#9076](https://github.com/npm/cli/pull/9076) arborist: do not hoist undeclared workspaces in linked strategy (#9076) (@manzoorwanijk) +* [`1206f8b`](https://github.com/npm/cli/commit/1206f8b97b5a57df00518eecb7b9aa7ab24ef73c) [#9069](https://github.com/npm/cli/pull/9069) consolidate isolated node/link attributes (#9069) (@wraithgar) +* [`a774fb7`](https://github.com/npm/cli/commit/a774fb77aadf01b46c13fe3d48bc2393fc6ef0ff) [#9066](https://github.com/npm/cli/pull/9066) arborist: respect --omit flag in linked install strategy (#9066) (@manzoorwanijk) +* [`8614b2a`](https://github.com/npm/cli/commit/8614b2af5c912e1ab293bdc41f9b8ae189cfa901) [#9031](https://github.com/npm/cli/pull/9031) arborist: avoid full reinstall on subsequent linked strategy runs (#9031) (@manzoorwanijk) +* [`16fbe13`](https://github.com/npm/cli/commit/16fbe135b86908426ffb8d4caa73e66cd7a679b1) [#9030](https://github.com/npm/cli/pull/9030) resolve relative file: dependencies correctly with install-strategy=linked (#9030) (@manzoorwanijk) +* [`983742b`](https://github.com/npm/cli/commit/983742b7ed70673b31f4607836fd156bf2d22f1d) [#9055](https://github.com/npm/cli/pull/9055) isolated mode code cleanup (#9055) (@wraithgar) +* [`a29aeee`](https://github.com/npm/cli/commit/a29aeee18f3ddc2348a8e00787d237c874642789) [#9028](https://github.com/npm/cli/pull/9028) arborist: retry bin-links on Windows EPERM (#9028) (@manzoorwanijk) +* [`10d5302`](https://github.com/npm/cli/commit/10d530242c7d893c562456013bb1c5104ca3e3b8) [#9051](https://github.com/npm/cli/pull/9051) arborist: unwrap Link nodes in legacyPeerDeps for linked strategy (#9051) (@manzoorwanijk) +* [`94bfef5`](https://github.com/npm/cli/commit/94bfef5a9f1a841840deee77cd961c90fbed5f3c) [#9044](https://github.com/npm/cli/pull/9044) audit: exclude locally linked packages from vulnerability audit (#9044) (@lucas-gomes-santana) +* [`26fa40e`](https://github.com/npm/cli/commit/26fa40eeafdbbb616d48fe254c92544cb13fba60) [#9041](https://github.com/npm/cli/pull/9041) fix workspace-filtered install with linked strategy (@owlstronaut) + +## [9.4.0](https://github.com/npm/cli/compare/arborist-v9.3.1...arborist-v9.4.0) (2026-02-25) +### Features +* [`4fcd352`](https://github.com/npm/cli/commit/4fcd352c553fdc0f13a87ad71ef66d7515c11886) [#9017](https://github.com/npm/cli/pull/9017) add :type(registry) to query selector syntax (#9017) (@wraithgar) +### Bug Fixes +* [`880ecb7`](https://github.com/npm/cli/commit/880ecb786d83e7bc95b1ed75660769e2af253579) [#9013](https://github.com/npm/cli/pull/9013) arborist: skip postinstall on store links in linked strategy (#9013) (@manzoorwanijk) +* [`07e6edd`](https://github.com/npm/cli/commit/07e6edd9d0f21ab65bd98e444598ddcb50b66551) [#9025](https://github.com/npm/cli/pull/9025) save libc field to package-lock.json (@owlstronaut) +* [`a2154cd`](https://github.com/npm/cli/commit/a2154cd91370c9c611cc19c943d00c3d0bbfa4ef) [#8996](https://github.com/npm/cli/pull/8996) linked strategy fixes for scoped packages, aliases, and peer deps (#8996) (@manzoorwanijk) + +## [9.3.1](https://github.com/npm/cli/compare/arborist-v9.3.0...arborist-v9.3.1) (2026-02-19) +### Bug Fixes +* [`bb135cc`](https://github.com/npm/cli/commit/bb135cc8998b8b936f2cb412ec3303ae02d6920c) [#8981](https://github.com/npm/cli/pull/8981) arborist: fix `peerOptional` dependency resolution in `buildIdealTree` (#8981) (@Saibamen, @cursoragent) +### Chores +* [`40fcab4`](https://github.com/npm/cli/commit/40fcab45d356545f8db7f34df3e5630116d0dd40) [#8991](https://github.com/npm/cli/pull/8991) `@npmcli/template-oss@4.29.0` (@wraithgar) + +## [9.3.0](https://github.com/npm/cli/compare/arborist-v9.2.0...arborist-v9.3.0) (2026-02-11) +### Features +* [`7c038b7`](https://github.com/npm/cli/commit/7c038b75d4738635a3dd7140b63ead711de3d8d5) [#8968](https://github.com/npm/cli/pull/8968) add support for git-256 sha lengths (#8968) (@wraithgar) + +## [9.2.0](https://github.com/npm/cli/compare/arborist-v9.1.10...arborist-v9.2.0) (2026-02-04) +### Features +* [`f5f6cf7`](https://github.com/npm/cli/commit/f5f6cf7c9fc9315b96eb29c5c7d5ab63ad3a9122) [#8943](https://github.com/npm/cli/pull/8943) config: add --allow-git (@wraithgar) + +## [9.1.10](https://github.com/npm/cli/compare/arborist-v9.1.9...arborist-v9.1.10) (2026-01-21) +### Dependencies +* [`f951820`](https://github.com/npm/cli/commit/f95182001771ad5d52dfc57934d7ce1b97055b70) [#8919](https://github.com/npm/cli/pull/8919) `common-ancestor-path@2.0.0` + +## [9.1.9](https://github.com/npm/cli/compare/arborist-v9.1.8...arborist-v9.1.9) (2025-12-09) +### Bug Fixes +* [`0765289`](https://github.com/npm/cli/commit/07652896c44bd21a585255151f90f171eefbb00e) [#8721](https://github.com/npm/cli/pull/8721) handle ENOTEMPTY errors in moveFile (@keegancsmith) + +## [9.1.8](https://github.com/npm/cli/compare/arborist-v9.1.7...arborist-v9.1.8) (2025-11-25) +### Bug Fixes +* [`b118364`](https://github.com/npm/cli/commit/b1183644faea618ee36af513c5bfc3387ada0f7e) [#8760](https://github.com/npm/cli/pull/8760) undefined override set conflicts shouldn't error (@owlstronaut) +### Dependencies +* [`f963223`](https://github.com/npm/cli/commit/f96322350e497f90a54c8a1cfd952b3329f00492) [#8770](https://github.com/npm/cli/pull/8770) `proggy@4.0.0` +* [`f51e4aa`](https://github.com/npm/cli/commit/f51e4aaf06ac6703abe053a95fe25b8efca3c527) [#8770](https://github.com/npm/cli/pull/8770) `nopt@9.0.0` +* [`2d15040`](https://github.com/npm/cli/commit/2d15040390697cd78c9a9db3f0dbafab51a6e3e9) [#8770](https://github.com/npm/cli/pull/8770) `@npmcli/query@5.0.0` +* [`58650dc`](https://github.com/npm/cli/commit/58650dc089c74d090c51d1cb2f269f2d605dcca0) [#8770](https://github.com/npm/cli/pull/8770) `@npmcli/fs@5.0.0` + +## [9.1.7](https://github.com/npm/cli/compare/arborist-v9.1.6...arborist-v9.1.7) (2025-11-19) +### Bug Fixes +* [`3225fa3`](https://github.com/npm/cli/commit/3225fa3200cb0217bdd0735bba390268f8362532) [#8737](https://github.com/npm/cli/pull/8737) fix usage of path of custom registry (#8737) (@flj2mu2) +* [`e9f0418`](https://github.com/npm/cli/commit/e9f0418250aa47216e449d3a63b8607e530ed27f) [#8689](https://github.com/npm/cli/pull/8689) arborist: improve override conflict detection with semantic comparison (#8689) (@Artur-) +* [`05319f0`](https://github.com/npm/cli/commit/05319f0cc3fee6680e4f59a13ed9420785cf673b) [#8677](https://github.com/npm/cli/pull/8677) code cleanup (#8677) (@wraithgar) +* [`49a4eef`](https://github.com/npm/cli/commit/49a4eefd613dbb60bcff3dac39129f70586d3cff) [#8676](https://github.com/npm/cli/pull/8676) use look behind regex for trailing slash stripping (#8676) (@wraithgar) +* [`b1aee62`](https://github.com/npm/cli/commit/b1aee62082d7b25ec07f64e906afd76840907fbd) [#8645](https://github.com/npm/cli/pull/8645) dep flag calculation (#8645) (@liamcmitchell) +### Dependencies +* [`8cc9f70`](https://github.com/npm/cli/commit/8cc9f70c2769f068ea0ef77a602162cdd949998e) [#8723](https://github.com/npm/cli/pull/8723) `ssri@13.0.0` +* [`59b3c6a`](https://github.com/npm/cli/commit/59b3c6adf5fb7e5c8e0f990ade7417677270057a) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/redact@4.0.0` +* [`6cb77df`](https://github.com/npm/cli/commit/6cb77df37989cb7c165cb2c35c735fb12dc1385a) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/installed-package-contents@4.0.0` +* [`05ac7a7`](https://github.com/npm/cli/commit/05ac7a7ea2a4d258658537a19ba350e07df34fda) [#8723](https://github.com/npm/cli/pull/8723) `proc-log@6.0.0` +* [`0a74f6d`](https://github.com/npm/cli/commit/0a74f6d1d8643f3a089f6e63502df77e6e3038ff) [#8723](https://github.com/npm/cli/pull/8723) `bin-links@6.0.0` +* [`041b9b2`](https://github.com/npm/cli/commit/041b9b29b30c539c5bf8b8cd26ea2202f94862b3) [#8723](https://github.com/npm/cli/pull/8723) `parse-conflict-json@5.0.1` +* [`a1b0fea`](https://github.com/npm/cli/commit/a1b0feac64ff681b2aec6938eb5136f5e177a07a) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/name-from-folder@4.0.0` +* [`3404dca`](https://github.com/npm/cli/commit/3404dca3d986d1bf0de3e74cf8b61856778711c6) [#8723](https://github.com/npm/cli/pull/8723) `npm-install-checks@8.0.0` +* [`542fcf3`](https://github.com/npm/cli/commit/542fcf3eee92cc41e86838c97c4036a97d749155) [#8723](https://github.com/npm/cli/pull/8723) `@npmcli/node-gyp@5.0.0` + +## [9.1.6](https://github.com/npm/cli/compare/arborist-v9.1.5...arborist-v9.1.6) (2025-10-08) +### Bug Fixes +* [`0a8b8c2`](https://github.com/npm/cli/commit/0a8b8c2ba37872b08a24bcf067f6da34d718f6d8) [#8621](https://github.com/npm/cli/pull/8621) typo bugs and other spelling fixes (#8621) (@jsoref) +* [`54fd27f`](https://github.com/npm/cli/commit/54fd27f9f6af54ca9fd11165aafbc8a13a38f39e) [#8602](https://github.com/npm/cli/pull/8602) refactor node.ideallyInert to node.inert (#8602) (@liamcmitchell) +* [`13d8df6`](https://github.com/npm/cli/commit/13d8df64e78dc13c49ab0607b252de1d54f0122a) [#8537](https://github.com/npm/cli/pull/8537) optional set calculation (#8537) (@liamcmitchell) +### Chores +* [`180e9f7`](https://github.com/npm/cli/commit/180e9f709d10c959556c19205bb3636220bed9c7) [#8610](https://github.com/npm/cli/pull/8610) fix spelling in workspaces/arborist (#8610) (@jsoref) +* [`91393de`](https://github.com/npm/cli/commit/91393deaf71bad084bb1d2aa868d5f895cc5f103) [#8599](https://github.com/npm/cli/pull/8599) Update references for arborist to cli (#8599) (@jsoref) + +## [9.1.5](https://github.com/npm/cli/compare/arborist-v9.1.4...arborist-v9.1.5) (2025-09-23) +### Bug Fixes +* [`60aa94b`](https://github.com/npm/cli/commit/60aa94b0379b2f4491c5d6857c1cff3036d9a3a9) [#8576](https://github.com/npm/cli/pull/8576) attach path to json parse error (@wraithgar) +* [`1eedf82`](https://github.com/npm/cli/commit/1eedf82f2a36df193a51dca2c07fdc82dcb18a68) [#8576](https://github.com/npm/cli/pull/8576) use @npmcli/package-json to parse package.json (@wraithgar) +* [`f6c868d`](https://github.com/npm/cli/commit/f6c868d8a2df4d2961983d4e52095d6e7551e9cb) [#8566](https://github.com/npm/cli/pull/8566) calculate omit in diff (#8566) (@liamcmitchell, Liam Mitchell) +* [`d389614`](https://github.com/npm/cli/commit/d3896147c61b06d6d39a55bbb609f878548e0107) [#8579](https://github.com/npm/cli/pull/8579) corrects peer dependency flag propagation (@owlstronaut) +### Dependencies +* [`566f1b7`](https://github.com/npm/cli/commit/566f1b7b487ad80604c61162ddde769d5ac2b241) [#8576](https://github.com/npm/cli/pull/8576) `minimatch@10.0.3` +* [`ea7ca5f`](https://github.com/npm/cli/commit/ea7ca5f49d6cab81e9ce3d412963c48acd87b7c0) [#8576](https://github.com/npm/cli/pull/8576) `lru-cache@11.2.1` +* [`bf6b686`](https://github.com/npm/cli/commit/bf6b6862731e03002cc6fa3b86b6f090df46b009) [#8576](https://github.com/npm/cli/pull/8576) `npm-package-arg@13.0.0` +* [`9392488`](https://github.com/npm/cli/commit/9392488d6036dfc9696e29cc8d463335517974ca) [#8576](https://github.com/npm/cli/pull/8576) `npm-package-manifest@11.0.1` +* [`633c4ed`](https://github.com/npm/cli/commit/633c4ed76ea13b8dfb5837a397e984e44cccb820) [#8576](https://github.com/npm/cli/pull/8576) `hosted-git-info@9.0.0` +* [`1149971`](https://github.com/npm/cli/commit/11499711e4c10e4ddb97bf3e1ef1652d151894fb) [#8576](https://github.com/npm/cli/pull/8576) `npm-registry-fetch@19.0.0` +* [`6221e27`](https://github.com/npm/cli/commit/6221e277b4b841df09225b4d72f9eda70db1f15a) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/metavuln-calculator@9.0.2` +* [`da81a37`](https://github.com/npm/cli/commit/da81a3702fdf7ea2dc7223fc6ece4c7a19e32ad1) [#8576](https://github.com/npm/cli/pull/8576) `cacache@20.0.1` +* [`6b4c5f9`](https://github.com/npm/cli/commit/6b4c5f92865230ed9a260cd3e8486bf3991120eb) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/run-script@10.0.0` +* [`b6bb9ae`](https://github.com/npm/cli/commit/b6bb9aea4134c47f0593c111a734eda12ec3c20d) [#8576](https://github.com/npm/cli/pull/8576) `pacote@21.0.3` +* [`1b4433f`](https://github.com/npm/cli/commit/1b4433fdb85623e019a6194cb01ff85c7f64ccad) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/map-workspaces@5.0.0` +* [`ceae674`](https://github.com/npm/cli/commit/ceae674c32a080b81e62d79003c2d537d7ca93d2) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/package-json@7.0.1` +* [`4f37534`](https://github.com/npm/cli/commit/4f37534300553e9ddfbc413c14d1ef15b02b46f2) [#8576](https://github.com/npm/cli/pull/8576) remove read-package-json-fast +### Chores +* [`4059dfa`](https://github.com/npm/cli/commit/4059dfa47b0afc982703d8d83fce5574fdc6308f) [#8576](https://github.com/npm/cli/pull/8576) properly use arborist and cache in test (@owlstronaut) +* [`402a0ab`](https://github.com/npm/cli/commit/402a0ab1b4e5d1a8414dd063d0cbde0c0bc5a192) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/template-oss@4.25.1` (@wraithgar) + +## [9.1.4](https://github.com/npm/cli/compare/arborist-v9.1.3...arborist-v9.1.4) (2025-09-03) +### Bug Fixes +* [`208c06e`](https://github.com/npm/cli/commit/208c06e91a187b03d6bdd75bff4e4285b365750c) [#8448](https://github.com/npm/cli/pull/8448) peer edge crash due to no parent or detached node (#8448) (@milaninfy) +* [`3b54e9c`](https://github.com/npm/cli/commit/3b54e9c59c6dba342d2931cce6458a755e55960e) [#8534](https://github.com/npm/cli/pull/8534) installLinks works with transitive external file dependencies (#8534) (@owlstronaut) +* [`ed71acb`](https://github.com/npm/cli/commit/ed71acb89fc3883e735987cc9be77efc2daff26a) [#8473](https://github.com/npm/cli/pull/8473) arborist: #8472 Keeps the registry protocol when modifying resolve URL (#8473) (@Jeepsboucher, Jean-Philippe Boucher) +### Chores +* [`619d43e`](https://github.com/npm/cli/commit/619d43e54ef7408d4ee6b38a776262b5132829b6) [#8540](https://github.com/npm/cli/pull/8540) fix pruner and reify tests for optional peer deps (#8540) (@liamcmitchell, Liam Mitchell) + +## [9.1.3](https://github.com/npm/cli/compare/arborist-v9.1.2...arborist-v9.1.3) (2025-07-24) +### Bug Fixes +* [`6dbe21a`](https://github.com/npm/cli/commit/6dbe21ab659c4e32657fec63fc58bb3f4992f4f1) [#8436](https://github.com/npm/cli/pull/8436) local transitive dependencies with --install-links=true (@owlstronaut) +* [`8042af3`](https://github.com/npm/cli/commit/8042af3a56ad2b3160afc53874a5510be113330c) [#8431](https://github.com/npm/cli/pull/8431) prune optional peer dependencies that are no longer explicitly depended on (#8431) (@G-Rath) +* [`c457c75`](https://github.com/npm/cli/commit/c457c7599afa430e3b0eb01bf9fee61464f6b8b7) [#8430](https://github.com/npm/cli/pull/8430) remove duplicate loop (#8430) (@G-Rath) +* [`f7b056f`](https://github.com/npm/cli/commit/f7b056f28ac1a26fd875662768742df586c0b334) [#8400](https://github.com/npm/cli/pull/8400) clean up audit-report code (#8400) (@wraithgar) +* [`f163d01`](https://github.com/npm/cli/commit/f163d011ade865b05b39b15aeee722809c223ae1) [#8372](https://github.com/npm/cli/pull/8372) use omit when checking ideal tree engine (#8372) (@owlstronaut) +### Chores +* [`3f60b5f`](https://github.com/npm/cli/commit/3f60b5f9621b43ae0b8796d3a7160a603748f756) [#8383](https://github.com/npm/cli/pull/8383) `@npmcli/template-oss@4.24.4` (#8383) (@wraithgar) +* [`01f8cc6`](https://github.com/npm/cli/commit/01f8cc6f001e3211135fa0563f7129aed09dc46c) [#8381](https://github.com/npm/cli/pull/8381) `@npmcli/template-oss@4.24.3` (#8381) (@wraithgar) + +## [9.1.2](https://github.com/npm/cli/compare/arborist-v9.1.1...arborist-v9.1.2) (2025-06-11) +### Bug Fixes +* [`887385d`](https://github.com/npm/cli/commit/887385d7c0b6b584e0973a1f667c3b22eafc6e28) [#8356](https://github.com/npm/cli/pull/8356) arborist: use hosted-git-info to correctly parse resolved git urls (#8356) (@milaninfy) + +## [9.1.1](https://github.com/npm/cli/compare/arborist-v9.1.0...arborist-v9.1.1) (2025-05-21) +### Bug Fixes +* [`8f6eb6b`](https://github.com/npm/cli/commit/8f6eb6b29904b5a807c5c4c01c1246afc70a77f1) [#8312](https://github.com/npm/cli/pull/8312) arborist: fix file dep making wrong link (#8312) (@alexsch01) + +## [9.1.0](https://github.com/npm/cli/compare/arborist-v9.0.2...arborist-v9.1.0) (2025-05-15) +### Features +* [`57aa89f`](https://github.com/npm/cli/commit/57aa89ff70e0c6186a43888b944b5799b25c7bc8) [#8265](https://github.com/npm/cli/pull/8265) use run by default and run-script as the alias (#8265) (@owlstronaut) +### Bug Fixes +* [`d5bcf38`](https://github.com/npm/cli/commit/d5bcf38764dfd05c7677602ae1c22b3a7bfdb486) [#8268](https://github.com/npm/cli/pull/8268) arborist: Add better error message when lockfile is malformed (#8268) (@owlstronaut) +* [`5e1fed9`](https://github.com/npm/cli/commit/5e1fed9f5e8d0ae05e67a3fe644d6e87d0559b7a) [#8290](https://github.com/npm/cli/pull/8290) arborist: improve README markdown (#8290) (@mbtools) +* [`0886e7a`](https://github.com/npm/cli/commit/0886e7abced0d8bdfd564a3b254817ecbdc14857) [#8222](https://github.com/npm/cli/pull/8222) preserve registry path when replacing a host (@owlstronaut) +* [`815311b`](https://github.com/npm/cli/commit/815311b9b8848585f8944f1f2684f10282525cf2) [#8206](https://github.com/npm/cli/pull/8206) arborist: workspaces correctly path to file: packages from overrides (@owlstronaut) + +## [9.0.2](https://github.com/npm/cli/compare/arborist-v9.0.1...arborist-v9.0.2) (2025-04-08) +### Bug Fixes +* [`a96d8f6`](https://github.com/npm/cli/commit/a96d8f6295886c219076178460718837d2fe45d6) [#8184](https://github.com/npm/cli/pull/8184) arborist: omit failed optional dependencies from installed deps (#8184) (@owlstronaut, @zkat) +* [`04f53ce`](https://github.com/npm/cli/commit/04f53ce13201b460123067d7153f1681342548e1) [#8180](https://github.com/npm/cli/pull/8180) arborist: safely fallback on unresolved $ dependency references (#8180) (@owlstronaut) +* [`885accd`](https://github.com/npm/cli/commit/885accdc750dd45fc9e4b5faf11bcc81292e17ad) [#8185](https://github.com/npm/cli/pull/8185) arborist: only replace hostname for resolved URL (#8185) (@billy-briggs-dev) +* [`8b7bb12`](https://github.com/npm/cli/commit/8b7bb12617e80f3e5061c96d06dd723331fffa2d) [#8168](https://github.com/npm/cli/pull/8168) arborist: Allow downgrades to hoisted version dedupe workspace i… (#8168) (@owlstronaut) +* [`1642556`](https://github.com/npm/cli/commit/1642556fe47d837ab7d0800d96bd2eebd0c908fd) [#8160](https://github.com/npm/cli/pull/8160) arborist: workspaces respect overrides on subsequent installs (#8160) (@owlstronaut) +### Chores +* [`88a7b52`](https://github.com/npm/cli/commit/88a7b52a69ba6a4f44216220d09000bf8468cae1) [#8174](https://github.com/npm/cli/pull/8174) add load-virtual and reify tests for workspace override test coverage (#8174) (@owlstronaut, @TrevorBurnham) + +## [9.0.1](https://github.com/npm/cli/compare/arborist-v9.0.0...arborist-v9.0.1) (2025-03-05) +### Bug Fixes +* [`b9225e5`](https://github.com/npm/cli/commit/b9225e524074239bd8db9a27f3e9ab72f2b5c09e) [#8089](https://github.com/npm/cli/pull/8089) resolve override conflicts and apply correct versions (#8089) (@owlstronaut) +* [`d586f3b`](https://github.com/npm/cli/commit/d586f3b6da5cf864254e894efd3105ad52266599) [#8117](https://github.com/npm/cli/pull/8117) remove duplicate var (#8117) (@TrevorBurnham) +* [`811ca29`](https://github.com/npm/cli/commit/811ca2927eed733c8fabf308bf9d467e7c959163) [#8115](https://github.com/npm/cli/pull/8115) stop working around bug fixed in `npm-package-arg@12.0.2` (@TrevorBurnham) + +## [9.0.0](https://github.com/npm/cli/compare/arborist-v9.0.0-pre.1...arborist-v9.0.0) (2024-12-16) +### Features +* [`a7bfc6d`](https://github.com/npm/cli/commit/a7bfc6df76882996ebb834dbca785fdf33b8c50d) [#7972](https://github.com/npm/cli/pull/7972) trigger release process (#7972) (@wraithgar) +### Chores +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) + +## [9.0.0-pre.1](https://github.com/npm/cli/compare/arborist-v9.0.0-pre.0...arborist-v9.0.0-pre.1) (2024-12-06) +### ⚠️ BREAKING CHANGES +* Upon publishing, in order to apply a default "latest" dist tag, the command now retrieves all prior versions of the package. It will require that the version you're trying to publish is above the latest semver version in the registry, not including pre-release tags. +* `bun.lockb` files are now included in the strict ignore list during packing +### Features +* [`f3ac7b7`](https://github.com/npm/cli/commit/f3ac7b7460e1d9e1f9d3d8056317e36bb9813d5d) [#7939](https://github.com/npm/cli/pull/7939) no implicit latest tag on publish when latest > version (#7939) (@reggi, @ljharb) +### Dependencies +* [`c0bcc2a`](https://github.com/npm/cli/commit/c0bcc2a860fec5c86234dec44f5474364c25aefc) [#7955](https://github.com/npm/cli/pull/7955) `walk-up-path@4.0.0` +* [`4bf1901`](https://github.com/npm/cli/commit/4bf1901f6dc57748d851ebe82262e9bef85a4ba7) [#7945](https://github.com/npm/cli/pull/7945) `@npmcli/metavuln-calculator@9.0.0` +* [`ca84b22`](https://github.com/npm/cli/commit/ca84b22a18806495c37ef6ee2aecd42a1c7bb7f6) [#7945](https://github.com/npm/cli/pull/7945) `pacote@21.0.0` + +## [9.0.0-pre.0](https://github.com/npm/cli/compare/arborist-v8.0.0...arborist-v9.0.0-pre.0) (2024-11-26) +### ⚠️ BREAKING CHANGES +* `--ignore-scripts` now applies to all lifecycle scripts, include `prepare` +* npm will no longer fall back to the old audit endpoint if the bulk advisory request fails. +* @npmcli/arborist now supports node `^20.17.0 || >=22.9.0` +### Features +* [`6995303`](https://github.com/npm/cli/commit/6995303687ab59541b727bf611f73624d1829b6c) [#7850](https://github.com/npm/cli/pull/7850) adds `--ignore-scripts` flag to `pack` (@reggi) +### Bug Fixes +* [`080a0f2`](https://github.com/npm/cli/commit/080a0f2d3f09a81f0a5b2992431e0bc7feb8d701) [#7911](https://github.com/npm/cli/pull/7911) remove old audit fallback request (@wraithgar) +* [`3ffc08b`](https://github.com/npm/cli/commit/3ffc08bc848ed262ab95e37593c8c058fd633caa) [#7831](https://github.com/npm/cli/pull/7831) for @npmcli/arborist sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +### Dependencies +* [`7dbef6f`](https://github.com/npm/cli/commit/7dbef6f3a3ead089b1b8b9fe6b2fa25e24309000) [#7850](https://github.com/npm/cli/pull/7850) `pacote@20.0.0` +* [`75a3f12`](https://github.com/npm/cli/commit/75a3f1228865f426d8790be27f1258e501f2c450) [#7859](https://github.com/npm/cli/pull/7859) remove unused deps (#7859) +### Chores +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) + +## [8.0.0](https://github.com/npm/cli/compare/arborist-v7.5.4...arborist-v8.0.0) (2024-10-03) +### ⚠️ BREAKING CHANGES +* `@npmcli/arborist` now supports node `^18.17.0 || >=20.5.0` +### Features +* [`4d57928`](https://github.com/npm/cli/commit/4d57928ea20c1672864dc0c8ebaff5d877e61c9c) [#7766](https://github.com/npm/cli/pull/7766) devEngines (#7766) (@reggi) +### Bug Fixes +* [`365580a`](https://github.com/npm/cli/commit/365580a2b0d3c645cdbf250c60994007c8e33a89) [#7803](https://github.com/npm/cli/pull/7803) align @npmcli/arborist to npm 10 node engine range (@reggi) +### Dependencies +* [`5795987`](https://github.com/npm/cli/commit/5795987605af9bb163ad3a689a0854b99cd39cbe) [#7803](https://github.com/npm/cli/pull/7803) update `proggy@3.0.0` +* [`99ccae3`](https://github.com/npm/cli/commit/99ccae3ded6f7013b26ed268a208c24473cdeb8f) [#7803](https://github.com/npm/cli/pull/7803) update `bin-links@5.0.0` +* [`75786ad`](https://github.com/npm/cli/commit/75786adb86f763d781f840feea4afb8d01953b99) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/query@4.0.0` +* [`1c25a1d`](https://github.com/npm/cli/commit/1c25a1d74c26364742b59f9d57b9a07bb4f8726f) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/node-gyp@4.0.0` +* [`2d7fc3d`](https://github.com/npm/cli/commit/2d7fc3d320b92a8447e7282df14e2b99047cc426) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/name-from-folder@3.0.0` +* [`1e09334`](https://github.com/npm/cli/commit/1e093347e3723c77bb4dc9214e111a3ec78fbbea) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/metavuln-calculator@8.0.0` +* [`820e983`](https://github.com/npm/cli/commit/820e983b1d5a82d6c9c10895487c2e43b423d6ef) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/installed-package-contents@3.0.0` +* [`9cd6603`](https://github.com/npm/cli/commit/9cd66031ebd2e9a0d6fdee3a7b4d7779694306ff) [#7803](https://github.com/npm/cli/pull/7803) update `read-package-json-fast@4.0.0` +* [`8206c4f`](https://github.com/npm/cli/commit/8206c4f675937e855b60164946c086eb64d7ecb6) [#7803](https://github.com/npm/cli/pull/7803) update `ssri@12.0.0` +* [`f6909a0`](https://github.com/npm/cli/commit/f6909a022c9373c85d980c96a30f47a3a65aa4a9) [#7803](https://github.com/npm/cli/pull/7803) update `proc-log@5.0.0` +* [`f9b2e18`](https://github.com/npm/cli/commit/f9b2e1884fbfe2a2c41e3fcaa4be722209141aed) [#7803](https://github.com/npm/cli/pull/7803) update `parse-conflict-json@4.0.0` +* [`e7ab206`](https://github.com/npm/cli/commit/e7ab206370e5fc62fefe6916e5dcc40b3e577d22) [#7803](https://github.com/npm/cli/pull/7803) update `pacote@19.0.0` +* [`d13a20b`](https://github.com/npm/cli/commit/d13a20bebef1b9932f86c44741ea6d214ad6842b) [#7803](https://github.com/npm/cli/pull/7803) update `npm-registry-fetch@18.0.1` +* [`092f41f`](https://github.com/npm/cli/commit/092f41fec40f418468605557fcb4f4e1babd9d45) [#7803](https://github.com/npm/cli/pull/7803) update `npm-pick-manifest@10.0.0` +* [`50a7bc8`](https://github.com/npm/cli/commit/50a7bc8737bb4e0a8fbc5f00b8f580512153a5bc) [#7803](https://github.com/npm/cli/pull/7803) update `npm-package-arg@12.0.0` +* [`591130d`](https://github.com/npm/cli/commit/591130d0aaaa032f484504287e993d38b6f04d4f) [#7803](https://github.com/npm/cli/pull/7803) update `npm-install-checks@7.1.0` +* [`105fa2b`](https://github.com/npm/cli/commit/105fa2bdb2bbb0502bb8e0c5ccec3dadcff3c2d6) [#7803](https://github.com/npm/cli/pull/7803) update `nopt@8.0.0` +* [`7214149`](https://github.com/npm/cli/commit/72141496fbc7e5f0e0824d584b82690eeee45bb5) [#7803](https://github.com/npm/cli/pull/7803) update `json-parse-even-better-errors@4.0.0` +* [`6deae9e`](https://github.com/npm/cli/commit/6deae9e5d989ac30208fbcbca13ec827c6f2b588) [#7803](https://github.com/npm/cli/pull/7803) update `hosted-git-info@8.0.0` +* [`034c729`](https://github.com/npm/cli/commit/034c7297568d328bcaf79bd2c7226d3593e21810) [#7803](https://github.com/npm/cli/pull/7803) update `cacache@19.0.1` +* [`538a4cc`](https://github.com/npm/cli/commit/538a4cc1dd731a3643ab4477fe545db39997bcdf) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/run-script@9.0.1` +* [`b80d048`](https://github.com/npm/cli/commit/b80d0482cb52fc00275fef9548d86e17eaf28f50) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/redact@3.0.0` +* [`2076368`](https://github.com/npm/cli/commit/207636897aa5544ec28cad5b75fe2e685028dafd) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/package-json@6.0.1` +* [`feac87c`](https://github.com/npm/cli/commit/feac87c7ed6113665bc144ee677017bc66138b70) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/map-workspaces@4.0.1` +* [`dd90f9e`](https://github.com/npm/cli/commit/dd90f9ee7882dbeec073604638b98e68f9873371) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/fs@4.0.0` +### Chores +* [`be1e6da`](https://github.com/npm/cli/commit/be1e6da91380d7a10edb1767dd433ca296b96771) [#7803](https://github.com/npm/cli/pull/7803) update `minify-registry-metadata@4.0.0` (@reggi) +* [`2072705`](https://github.com/npm/cli/commit/2072705aa80d009dc077639adc305692f4a6c0b9) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/eslint-config@5.0.1` (@reggi) +* [`8035725`](https://github.com/npm/cli/commit/80357253ecd8483463cd66c783c4464c330d72df) [#7756](https://github.com/npm/cli/pull/7756) `@npmcli/template-oss@4.23.3` (@wraithgar) + ## [7.5.4](https://github.com/npm/cli/compare/arborist-v7.5.3...arborist-v7.5.4) (2024-07-09) ### Bug Fixes @@ -25,7 +349,7 @@ * [`e290352`](https://github.com/npm/cli/commit/e290352c6b9fd3bc7fa4b8ea2cc2000fb20fdec7) [#7499](https://github.com/npm/cli/pull/7499) revert DepsQueue to re-sort on pop() (#7499) (@lukekarrys) * [`56a27fa`](https://github.com/npm/cli/commit/56a27fa400f157fb9a56182900278c41efc6aba1) [#7494](https://github.com/npm/cli/pull/7494) avoid caching manifests as promises (@wraithgar) * [`722c0fa`](https://github.com/npm/cli/commit/722c0faa387ae6e35886f08eefb238c03ae85db1) [#7463](https://github.com/npm/cli/pull/7463) limit packument cache size based on heap size (@wraithgar) -* [`effe910`](https://github.com/npm/cli/commit/effe9109d6bc7828bf916c4dee49b2a53c72f39d) [#7475](https://github.com/npm/cli/pull/7475) dont omit license from stored manifests (#7475) (@lukekarrys) +* [`effe910`](https://github.com/npm/cli/commit/effe9109d6bc7828bf916c4dee49b2a53c72f39d) [#7475](https://github.com/npm/cli/pull/7475) don't omit license from stored manifests (#7475) (@lukekarrys) ### Dependencies @@ -66,7 +390,7 @@ ### Features -* [`9123de4`](https://github.com/npm/cli/commit/9123de4d282bfd19ea17ad613f5a2acab0e0e162) [#7373](https://github.com/npm/cli/pull/7373) do all ouput over proc-log events (@lukekarrys) +* [`9123de4`](https://github.com/npm/cli/commit/9123de4d282bfd19ea17ad613f5a2acab0e0e162) [#7373](https://github.com/npm/cli/pull/7373) do all output over proc-log events (@lukekarrys) * [`9622597`](https://github.com/npm/cli/commit/9622597399ec93224fddf90a9209a98dbcfd6b2f) [#7339](https://github.com/npm/cli/pull/7339) refactor terminal display (#7339) (@lukekarrys) ### Bug Fixes @@ -654,7 +978,7 @@ ### Bug Fixes -* **arborist:** dont skip adding advisories to audit based on name/range ([aa4a4da](https://github.com/npm/cli/commit/aa4a4da336a6ec1963394fdbd06acb173c842d26)), closes [#4681](https://github.com/npm/cli/issues/4681) +* **arborist:** don't skip adding advisories to audit based on name/range ([aa4a4da](https://github.com/npm/cli/commit/aa4a4da336a6ec1963394fdbd06acb173c842d26)), closes [#4681](https://github.com/npm/cli/issues/4681) * **arborist:** when reloading an edge, also refresh overrides ([4d676e3](https://github.com/npm/cli/commit/4d676e31a68f081b8553eff4e79db1f29acf47e1)) ### [5.0.5](https://github.com/npm/cli/compare/arborist-v5.0.4...arborist-v5.0.5) (2022-04-06) diff --git a/workspaces/arborist/README.md b/workspaces/arborist/README.md index 81d79cbf3021b..7263a83f6b31b 100644 --- a/workspaces/arborist/README.md +++ b/workspaces/arborist/README.md @@ -6,7 +6,7 @@ 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) +![a tree with the word ARBORIST superimposed on it](https://raw.githubusercontent.com/npm/cli/latest/workspaces/arborist/docs/logo.svg?sanitize=true) There's more documentation [in the docs folder](https://github.com/npm/cli/tree/latest/workspaces/arborist/docs). @@ -60,7 +60,7 @@ arb.loadActual().then(tree => { // tree is also stored at arb.virtualTree }) -// read just what the package-lock.json/npm-shrinkwrap says +// read just what the package-lock.json says // This *also* loads the yarn.lock file, but that's only relevant // when building the ideal tree. arb.loadVirtual().then(tree => { @@ -267,53 +267,19 @@ 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 | -+------------+------+-----+----------+-------------+---------------------+-------------------+ -``` +| extraneous | peer | dev | optional | devOptional | meaning | prune? | +|:----------:|:----:|:---:|:--------:|:----------------:|:-------------------------------------------------------------------------------------------------|:-------------------------------------------------------| +| | | | | | production dep | never | +| X | N/A | N/A | N/A | N/A | nothing depends on this, it is trash | always | +| | | X | | X
not in lock | devDependency, or only depended
on by devDependencies | if pruning dev | +| | | | X | X
not in lock | optionalDependency, or only depended
on by optionalDeps | if pruning optional | +| | | X | X | X
not in lock | Optional dependency of dep(s) in the
dev hierarchy | if pruning EITHER
dev OR optional | +| | | | | X
in lock | BOTH a non-optional dep within the
dev hierarchy, AND a dep within
the optional hierarchy | if pruning BOTH
dev AND optional | +| | X | | | | peer dependency, or only depended
on by peer dependencies | if pruning peers | +| | X | X | | X
not in lock | peer dependency of dev node hierarchy | if pruning peer OR
dev deps | +| | X | | X | X
not in lock | peer dependency of optional nodes, or
peerOptional dep | if pruning peer OR
optional deps | +| | X | X | X | X
not in lock | peer optional deps of the dev dep hierarchy | if pruning peer OR
optional OR dev | +| | X | | | X
in lock | BOTH a non-optional peer dep within the
dev hierarchy, AND a peer optional dep | if pruning peer deps OR:
BOTH optional 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. @@ -335,7 +301,7 @@ pruning nodes from the tree. 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 +Note: `devOptional` is only set in the package-lock file if _neither_ `dev` nor `optional` are set, as it would be redundant. ## BIN diff --git a/workspaces/arborist/bin/index.js b/workspaces/arborist/bin/index.js index 7c5d45f1f1fc9..4e8e8adb621f1 100755 --- a/workspaces/arborist/bin/index.js +++ b/workspaces/arborist/bin/index.js @@ -20,8 +20,7 @@ ${message && '\n' + message + '\n'} * 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 + * virtual: read and print the virtual tree in the local package-lock.json * 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. @@ -37,7 +36,7 @@ ${message && '\n' + message + '\n'} Additionally: - * --loglevel=warn|--quiet will supppress the printing of package trees + * --loglevel=warn|--quiet will suppress 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='. diff --git a/workspaces/arborist/bin/shrinkwrap.js b/workspaces/arborist/bin/shrinkwrap.js deleted file mode 100644 index 56603224e9988..0000000000000 --- a/workspaces/arborist/bin/shrinkwrap.js +++ /dev/null @@ -1,7 +0,0 @@ -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)) diff --git a/workspaces/arborist/docs/audit-bundled.md b/workspaces/arborist/docs/audit-bundled.md index c71b2c8009f3e..97ba3c841f130 100644 --- a/workspaces/arborist/docs/audit-bundled.md +++ b/workspaces/arborist/docs/audit-bundled.md @@ -12,7 +12,7 @@ advisory. However, with `bundleDependencies`, any version of `x` whose dependency on `y` _intersects_ with the vulnerable range on the `y` advisory should be -considered potentally vulnerable. +considered potentially vulnerable. When considering the meta-vulnerability of any version of `x`, thus: diff --git a/workspaces/arborist/docs/ideal-tree.md b/workspaces/arborist/docs/ideal-tree.md index 1faec5a3b2187..c508627ab7343 100644 --- a/workspaces/arborist/docs/ideal-tree.md +++ b/workspaces/arborist/docs/ideal-tree.md @@ -25,11 +25,10 @@ Options: ## to BUILD IDEAL TREE: -1. Load the root node's package and (if present) shrinkwrap +1. Load the root node's package and (if present) lockfile 2. Add and remove deps to/from the root node's package if requested 3. If any named updates specified, then for each name on the list: - 1. Find all nodes in the tree by that name that are not in a shrinkwrap - or bundle + 1. Find all nodes in the tree by that name that are not in a bundle 2. For each dependent in their edgesIn set, add the dependent to the queue of packages to be checked for updates 4. Add the root node to the queue of packages to be checked for updates @@ -41,21 +40,19 @@ Options: visited) 4. If node has been moved out of the tree or replaced, continue to next node (it's no longer relevant) - 5. If node has a shrinkwrap, continue to next node (its deps are - locked) - 6. For each dependency in node.edgesOut: - 1. If part of a bundle or shrinkwrap, continue to next dependency + 5. For each dependency in node.edgesOut: + 1. If part of a bundle, continue to next dependency 2. If edge is invalid, or name is on the update.names list: 1. Fetch the manifest for the dependency, and create a new Node 2. Add Node to virtual root node, also load Node's peerDependencies (and meta-peerDependencies) 3. Attempt to PLACE the dep in the tree 3. Add each placed node to the queue to be checked for updates -6. If the shrinkwrap was loaded from disk, and the tree was mutated, reset - all dependency flags to true (dev, optional, devOptionl, extraneous) -7. If the shrinkwrap was not loaded from disk, or the tree was mutated, +6. If the lockfile was loaded from disk, and the tree was mutated, reset + all dependency flags to true (dev, optional, devOptional, extraneous) +7. If the lockfile was not loaded from disk, or the tree was mutated, calculate dependency flags appropriately (like for a `loadActual` walk) -8. If options.prune is not false, and we started from a shrinkwrap and then +8. If options.prune is not false, and we started from a lockfile and then mutated the tree, prune any deps that are now extraneous. ## to PLACE a dep in the tree to satisfy an edge for a node: @@ -66,13 +63,13 @@ dependency can go without causing conflicts. 1. If edge is valid, and dep name is not on the update list, do not place 2. If the node is not a top node, and the dep is a peer dep, then the - starting TARGET is node.parent, otherwise it's node + starting TARGET is node.parent; otherwise, it's node 3. Do until CONFLICT: 1. CHECK if dep can be placed at TARGET 2. If not CONFLICT, set result in CAN PLACE 3. set TARGET to TARGET parent 4. If no satisfying target found, throw Unresolvable Dep Tree error -5. set TARGET to last non-conclict target checked +5. set TARGET to last non-conflict target checked 6. If CAN PLACE is KEEP, do not place 7. add dep to placed list 8. If an existing child by that name at TARGET, diff --git a/workspaces/arborist/docs/parent.md b/workspaces/arborist/docs/parent.md index 4398cbe7205a7..199c4dcf18e92 100644 --- a/workspaces/arborist/docs/parent.md +++ b/workspaces/arborist/docs/parent.md @@ -18,7 +18,7 @@ consistent. ## parent If a package is located in a `node_modules` folder, then its `parent` -represents the the package that contains that `node_modules` folder. +represents the package that contains that `node_modules` folder. For example: @@ -32,7 +32,7 @@ In this tree, `x` is `y`'s parent. `y` can resolve its dependents either within its own `node_modules` folder (ie, it's `children` nodes), or its parent's `node_modules` folder (ie, -it's parent's `children`), or its parent's parent's, and so on up the tree. +its parent's `children`), or its parent's parent's, and so on up the tree. Setting `node.parent` to another Node object will move it into that location in the tree, automatically adding it to `parent.children`, diff --git a/workspaces/arborist/docs/reify.md b/workspaces/arborist/docs/reify.md index ac607ef842e0c..0309bb763d564 100644 --- a/workspaces/arborist/docs/reify.md +++ b/workspaces/arborist/docs/reify.md @@ -113,25 +113,7 @@ a Fail: rimraf sparse tree, fail step 1 -### step 3: load shrinkwraps - -Unpack any shrinkwrapped nodes, and `loadVirtual` on them, and then update -the ideal tree with their virtual tree nodes. These will always be leaf -nodes, because any `hasShrinkwrap` nodes did not have their deps loaded in -the buildIdealTree step. - -If no shrinkwraps present, proceed to step 4. - -Else: - -- loadVirtual in the newly unpacked shrinkwrap node using the current ideal - node as the root of the virtual tree -- diff trees again -- create the sparse tree - -Fail: fail step 2 - -### step 4: unpack bundled deps into sparse tree and update +### step 3: unpack bundled deps into sparse tree and update 1. Group all nodes with bundles by depth. 2. For depth = 0 to max, for all nodes at that depth with bundleDeps, @@ -197,7 +179,7 @@ a ``` This actually means that we move each unchanging node's _contents_ (other -than `node_mdules`) into the new location. (Maybe we ought to _only_ ever +than `node_modules`) into the new location. (Maybe we ought to _only_ ever move files, not directories?) Fail: move unchanging nodes back to retired tree, fail step 2 @@ -248,17 +230,7 @@ Scan actualTree inventory. For each node: `mkdir` every path in ideal tree that does not exist in actualTree -### step 3: extract shrinkwrap modules - -Each node with a shrinkwrap is already a tip of the tree, because its child -nodes are not traversed in the ideal tree. - -Unpack them into place, and then call loadVirtual using the shrinkwrapped -node as the root, this filling out the ideal tree with the virtual nodes. - -Repeat step 2 if any shrinkwrap nodes were created. - -### step 4: extract bundlers +### step 3: extract bundlers 1. Group all nodes with bundles by depth. 2. for depth = 0, for all nodes at that depth with bundleDependencies, @@ -268,7 +240,7 @@ Repeat step 2 if any shrinkwrap nodes were created. depth=1 child node into the ideal tree. 3. if any bundle deps unpacked, prune tree -### step 5: extract all others +### step 4: extract all others Extract all remaining packages in parallel. diff --git a/workspaces/arborist/docs/tree-types.md b/workspaces/arborist/docs/tree-types.md index 5ffc6c261d240..4fa3089a18a7d 100644 --- a/workspaces/arborist/docs/tree-types.md +++ b/workspaces/arborist/docs/tree-types.md @@ -6,18 +6,18 @@ Arborist handles three different types of tree: on disk. It's loaded by calling `arborist.loadActual()`. - `arborist.virtualTree` - This is the package tree as captured in a - `package-lock.json` or `npm-shrinkwrap.json`. It's loaded by calling + `package-lock.json`. It's loaded by calling `arborist.loadVirtual()`. This method _may_ be called with an argument - specifyig the node to use as the `root` of the tree, like + specifying the node to use as the `root` of the tree, like `arborist.loadVirtual({ root: nodeObject })`. If a root is not specified - then a missing shrinkwrap is treated as a failure. If a root is not - specified, then a shrinkwrap file must be present, or the virtual load + then a missing lockfile is treated as a failure. If a root is not + specified, then a lockfile must be present, or the virtual load fails. - `arborist.idealTree` - This is the tree of package data that we intend to - install. It's built up based on the shrinkwrap/lockfile if present, the + install. It's built up based on the lockfile if present, the dependencies in package.json, and any add/remove/update changes requested. This is loaded by calling `arborist.buildIdealTree(options)`. The diff --git a/workspaces/arborist/docs/workspace.md b/workspaces/arborist/docs/workspace.md index 062fb7c91a565..04cb5c823077b 100644 --- a/workspaces/arborist/docs/workspace.md +++ b/workspaces/arborist/docs/workspace.md @@ -141,9 +141,9 @@ workspaces will try to install deps from registry if no satisfying semver versio ### Build Ideal Tree -1. Read list of "workpaces" from `package.json` +1. Read list of "workspaces" from `package.json` 2. Turn globs into actual locations, retrieve the final list of workspaces paths -3. Arborist needs to be made aware of the list of worskpaces paths +3. Arborist needs to be made aware of the list of workspaces paths 1. Workspace info parsed (steps 1 and 2) needs to be attached before build ideal tree 2. On building ideal tree, checks against existing workspaces to append them as child nodes 3. Edge needs to support a `workspace` type @@ -156,7 +156,7 @@ NOTE: ### Load Virtual -1. How to figure out all the structure of workspaces form a pakcage-lock +1. How to figure out all the structure of workspaces form a package-lock 1. How it gets saved? 2. How to build the virtual tree out of reading package-lock 2. maybe support a subset of glob? we need to optimize mapWorkspace regardless @@ -168,7 +168,7 @@ NOTE: ### Reify -1. Correctly symlink workspaces to its dependants `node_modules` +1. Correctly symlink workspaces to its dependents `node_modules` ## Open Ended Questions diff --git a/workspaces/arborist/lib/arborist/build-ideal-tree.js b/workspaces/arborist/lib/arborist/build-ideal-tree.js index 06d03bbce7a32..8e0fc63be04f0 100644 --- a/workspaces/arborist/lib/arborist/build-ideal-tree.js +++ b/workspaces/arborist/lib/arborist/build-ideal-tree.js @@ -1,12 +1,12 @@ // mixin implementing the buildIdealTree method const localeCompare = require('@isaacs/string-locale-compare')('en') -const rpj = require('read-package-json-fast') +const PackageJson = require('@npmcli/package-json') 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 { resolve, dirname, sep } = require('node:path') const treeCheck = require('../tree-check.js') const { readdirScoped } = require('@npmcli/fs') const { lstat, readlink } = require('node:fs/promises') @@ -24,10 +24,24 @@ 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 { isReleaseAgeExcluded, trustedSpecName } = require('../release-age-exclude.js') +const { resolvePatchedDependencies } = require('../patched-dependencies.js') +const PackageExtensions = require('../package-extensions.js') +const NpmExtension = require('../npm-extension.js') +const { hasExtensionFile } = require('../npm-extension.js') const Shrinkwrap = require('../shrinkwrap.js') const { defaultLockfileVersion } = Shrinkwrap const Node = require('../node.js') const Link = require('../link.js') + +// Maps a parsed spec.type to the corresponding allow-* arborist option name. +// Hoisted to module scope so #checkAllow doesn't re-allocate it per call. +const ALLOW_OPTION_FOR_TYPE = { + git: 'allowGit', + remote: 'allowRemote', + file: 'allowFile', + directory: 'allowDirectory', +} const addRmPkgDeps = require('../add-rm-pkg-deps.js') const optionalSet = require('../optional-set.js') const { checkEngine, checkPlatform } = require('npm-install-checks') @@ -41,7 +55,6 @@ 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') @@ -88,6 +101,8 @@ module.exports = cls => class IdealTreeBuilder extends cls { #loadFailures = new Set() #manifests = new Map() #mutateTree = false + #packageExtensions = null + #npmExtension = null // 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. @@ -100,39 +115,28 @@ module.exports = cls => class IdealTreeBuilder extends cls { 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] = [] + + // 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() + this[_flagsSuspect] = false } get explicitRequests () { @@ -176,12 +180,21 @@ module.exports = cls => class IdealTreeBuilder extends cls { try { await this.#initTree() + await this.#loadNpmExtension() + this.#loadPackageExtensions() await this.#inflateAncientLockfile() await this.#applyUserRequests(options) await this.#buildDeps() await this.#fixDepFlags() await this.#pruneFailedOptional() await this.#checkEngineAndPlatform() + await resolvePatchedDependencies(this.idealTree, { + path: this.path, + allowUnusedPatches: this.options.allowUnusedPatches, + rm: options.rm || [], + }) + this.#warnWorkspacePackageExtensions() + this.#warnWorkspaceNpmExtension() } finally { timeEnd() this.finishTracker('idealTree') @@ -191,11 +204,16 @@ module.exports = cls => class IdealTreeBuilder extends cls { } async #checkEngineAndPlatform () { - const { engineStrict, npmVersion, nodeVersion } = this.options + const { engineStrict, npmVersion, nodeVersion, omit = [], cpu, os, libc } = this.options + const omitSet = new Set(omit) + for (const node of this.idealTree.inventory.values()) { - if (!node.optional) { + if (!node.optional && !node.shouldOmit(omitSet)) { try { - checkEngine(node.package, npmVersion, nodeVersion, this.options.force) + // 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 @@ -208,6 +226,144 @@ module.exports = cls => class IdealTreeBuilder extends cls { } checkPlatform(node.package, this.options.force) } + if (node.optional && !node.inert) { + // Mark any optional packages we can't install as inert. + // We ignore the --force and --engine-strict flags. + try { + checkEngine(node.package, npmVersion, nodeVersion, false) + checkPlatform(node.package, false, { cpu, os, libc }) + } catch (error) { + const set = optionalSet(node) + for (const node of set) { + node.inert = true + } + } + } + } + } + + // Load the root project's packageExtensions rule set. + // Only the workspace root is authoritative, matching the root-only model of overrides. + // The canonical hash is stashed on the lockfile meta so commit() can persist it. + #loadPackageExtensions () { + const rootPkg = this.idealTree.target.package + const lockedHash = this.idealTree.meta.packageExtensionsHash + this.#packageExtensions = new PackageExtensions(rootPkg.packageExtensions) + this.idealTree.meta.packageExtensionsHash = this.#packageExtensions.hash + + // When the rule set has changed since the lockfile was written, the locked manifests for affected packages are stale. + // The locked manifest is the effective, already-extended manifest, so detach those nodes and rebuild them from fresh manifests under the current rules. + if (this.idealTree.meta.loadedFromDisk && lockedHash !== this.#packageExtensions.hash) { + for (const node of [...this.idealTree.inventory.values()]) { + if (node.isProjectRoot || node.isWorkspace || node.isTop) { + continue + } + // a node is affected if it carries provenance from the old rules or matches a current selector + const affected = node.packageExtensionsApplied || + this.#packageExtensions.wouldMatch(node.packageName, node.version) + if (affected) { + for (const edge of node.edgesIn) { + this.#depsQueue.push(edge.from) + } + node.parent = null + } + } + } + } + + // Apply a matching root packageExtension to a copy of a candidate manifest. + // Returns the possibly-extended manifest and the provenance to attach to the node. + // Workspace candidates are never extended; that warning is emitted separately. + #applyPackageExtension (pkg) { + if (!this.#packageExtensions?.present) { + return { pkg, applied: null } + } + const res = this.#packageExtensions.apply(pkg) + return res ? { pkg: res.pkg, applied: res.applied } : { pkg, applied: null } + } + + // Load the root project's .npm-extension file and its transformManifest export. + // ignore-extension (and, via flatten, ignore-scripts) disables discovery and execution; the lockfile then carries no extension state. + // The selected file's hash is stashed on the lockfile meta so commit() can persist it and npm ci can detect stale extension state. + async #loadNpmExtension () { + const lockedHash = this.idealTree.meta.npmExtensionHash + // ignore-extension (and, via flatten, ignore-scripts) disables discovery and execution. + // Leave any locked extension state untouched so npm ci reifies the locked graph as-is and the lockfile stays internally consistent. + if (this.options.ignoreExtension) { + return + } + const ext = new NpmExtension({ + root: this.idealTree.realpath, + extensionFile: this.options.extensionFile, + }) + this.#npmExtension = ext + this.idealTree.meta.npmExtensionHash = ext.hash + if (ext.present) { + await ext.load() + } + + // When the extension file changed since the lockfile was written, locked manifests may no longer reflect its output. + // This also covers removal: a now-absent file hashes to null, which differs from the locked hash and reverts the previously transformed nodes. + // Arbitrary code has no selector to predict which packages it affects, so re-resolve any node that carried old provenance or that the current file now transforms. + if (this.idealTree.meta.loadedFromDisk && lockedHash !== ext.hash) { + for (const node of [...this.idealTree.inventory.values()]) { + if (node.isProjectRoot || node.isWorkspace || node.isTop || node.isLink) { + continue + } + // A node with old provenance carries an already-transformed manifest, so always refetch it. + // Otherwise probe the locked manifest (without caching, so the authoritative full-manifest fetch is not pre-seeded). + // The locked manifest carries every resolution-relevant field (name, version, dependencies, peer metadata); a transform that newly targets a node by a field not persisted in the lockfile is the documented edge that may need a manual re-lock. + const affected = node.npmExtensionApplied || ext.apply(node.package, { memoize: false }) + if (affected) { + for (const edge of node.edgesIn) { + this.#depsQueue.push(edge.from) + } + node.parent = null + } + } + } + } + + // Apply the root transformManifest to a copy of a candidate manifest, before any packageExtensions rule. + // Returns the possibly-transformed manifest and the provenance to attach to the node. + #applyNpmExtension (pkg) { + const res = this.#npmExtension?.apply(pkg) + return res ? { pkg: res.pkg, applied: res.applied } : { pkg, applied: null } + } + + // Warn when packageExtensions appears in a non-root workspace, or when a root selector matches a workspace member. + // Workspace package manifests are edited directly and are never extension targets. + #warnWorkspacePackageExtensions () { + if (!this.#packageExtensions?.present) { + return + } + for (const node of this.idealTree.inventory.values()) { + // a workspace is in the inventory as both a Link and its target node; warn once by skipping the link + if (!node.isWorkspace || node.isLink) { + continue + } + if (node.package.packageExtensions !== undefined) { + log.warn('packageExtensions', + `"packageExtensions" in workspace ${node.name} is ignored; it is only honored at the workspace root`) + } + if (this.#packageExtensions.wouldMatch(node.name, node.version)) { + log.warn('packageExtensions', + `selector matches workspace package ${node.name}@${node.version}; edit its package.json directly instead of using packageExtensions`) + } + } + } + + // Warn when a non-root workspace package contains a .npm-extension file; only the workspace root's file is honored. + #warnWorkspaceNpmExtension () { + for (const node of this.idealTree.inventory.values()) { + // a workspace is in the inventory as both a Link and its target node; warn once by skipping the link + if (!node.isWorkspace || node.isLink || node.isProjectRoot) { + continue + } + if (hasExtensionFile(node.realpath)) { + log.warn('npm-extension', + `".npm-extension" in workspace ${node.name} is ignored; it is only honored at the workspace root`) + } } } @@ -262,7 +418,7 @@ module.exports = cls => class IdealTreeBuilder extends cls { root = await this.#globalRootNode() } else { try { - const pkg = await rpj(this.path + '/package.json') + const { content: pkg } = await PackageJson.normalize(this.path) root = await this.#rootNodeFromPackage(pkg) } catch (err) { if (err.code === 'EJSONPARSE') { @@ -276,14 +432,19 @@ module.exports = cls => class IdealTreeBuilder extends cls { // 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 })) + .then(root => { + if (this.options.global) { + return root + } else if (!this.options.usePackageLock || this[_updateAll]) { + return Shrinkwrap.reset({ + path: this.path, + lockfileVersion: this.options.lockfileVersion, + resolveOptions: this.options, + }).then(meta => Object.assign(root, { meta })) + } else { + return 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. @@ -309,7 +470,7 @@ module.exports = cls => class IdealTreeBuilder extends cls { }) .then(tree => { - // search the virtual tree for invalid edges, if any are found add their source to + // search the virtual tree for missing/invalid edges, if any are found add their source to // the depsQueue so that we'll fix it later depth({ tree, @@ -323,7 +484,8 @@ module.exports = cls => class IdealTreeBuilder extends cls { filter: node => node, visit: node => { for (const edge of node.edgesOut.values()) { - if (!edge.valid) { + const skipPeerOptional = edge.type === 'peerOptional' && this.options.save === false + if (!skipPeerOptional && (!edge.to || !edge.valid)) { this.#depsQueue.push(node) break // no need to continue the loop after the first hit } @@ -389,6 +551,7 @@ module.exports = cls => class IdealTreeBuilder extends cls { global: this.options.global, installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, + loadOverrides: true, root, }) } @@ -433,7 +596,11 @@ module.exports = cls => class IdealTreeBuilder extends cls { const paths = await readdirScoped(nm).catch(() => []) for (const p of paths) { const name = p.replace(/\\/g, '/') - tree.package.dependencies = tree.package.dependencies || {} + // Match loadActual behavior: hidden entries and retired scoped package + // folders are not installed global packages. + if (/^(@[^/]+\/)?\./.test(name)) { + continue + } const updateName = this[_updateNames].includes(name) if (this[_updateAll] || updateName) { if (updateName) { @@ -444,7 +611,7 @@ module.exports = cls => class IdealTreeBuilder extends cls { .catch(/* istanbul ignore next */ () => null) if (st && st.isSymbolicLink()) { const target = await readlink(dir) - const real = resolve(dirname(dir), target).replace(/#/g, '%23') + const real = resolve(dirname(dir), target) tree.package.dependencies[name] = `file:${real}` } else { tree.package.dependencies[name] = '*' @@ -489,27 +656,29 @@ module.exports = cls => class IdealTreeBuilder extends cls { 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. + // 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. + // Get the name for each of the specs in the list. + // e.g. 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. + // 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 + // 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 }) + const _isRoot = tree.isProjectRoot || tree.isWorkspace + const mani = await pacote.manifest(spec, { + ...this.options, + _isRoot, + before: this.#releaseAgeBefore(spec), + }) if (isTag) { // translate tag to a version spec = npa(`${mani.name}@${mani.version}`) @@ -519,12 +688,12 @@ module.exports = cls => class IdealTreeBuilder extends cls { const { name } = spec if (spec.type === 'file') { - spec = npa(`file:${relpath(path, spec.fetchSpec).replace(/#/g, '%23')}`, path) + spec = npa(`file:${relpath(path, spec.fetchSpec)}`, 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 = npa(`file:${relpath(path, real)}`, path) spec.name = name } catch { // TODO: create synthetic test case to simulate realpath failure @@ -550,6 +719,17 @@ module.exports = cls => class IdealTreeBuilder extends cls { // and leaving the user subject to getting it overwritten later anyway. async #queueVulnDependents (options) { for (const vuln of this.auditReport.values()) { + // A fix is available in-range but a release-age window blocks the patched + // version, so audit fix leaves this package at a vulnerable version. + if (vuln.fixBlockedByReleaseAge) { + const { version, before } = vuln.fixBlockedByReleaseAge + const cutoff = new Date(before).toISOString().slice(0, 10) + log.warn('audit', `A fix for ${vuln.name} is available (${vuln.name}@${version}) ` + + `but was published after the configured release-age cutoff (${cutoff}), so ` + + `${vuln.name} was left at a vulnerable version.\n` + + `To install it, add "${vuln.name}" to min-release-age-exclude, or relax ` + + 'min-release-age or before.') + } for (const node of vuln.nodes) { const bundler = node.getBundler() @@ -634,6 +814,45 @@ module.exports = cls => class IdealTreeBuilder extends cls { return vuln.range } + // Enforces the allow-git / allow-file / allow-directory / allow-remote configs at the arborist resolution layer, before any branching into the symlink (Link) path or the manifest-fetch path. + // Pacote also enforces these inside FetcherBase.get() as defense-in-depth, but the symlink branch never reaches pacote, and the manifest cache here would bypass pacote on a cached hit. + // Throws the same { code: EALLOW${TYPE} } shape pacote uses, so callers and downstream consumers stay consistent. + #checkAllow (spec, edge) { + const optName = ALLOW_OPTION_FOR_TYPE[spec.type] + if (!optName) { + return + } + const allow = this.options[optName] ?? 'all' + if (allow === 'all') { + return + } + const isRoot = !!(edge?.from?.isProjectRoot || edge?.from?.isWorkspace) + if (allow !== 'none' && isRoot) { + return + } + throw Object.assign( + new Error(`Fetching${allow === 'root' ? ' non-root' : ''} packages of type "${spec.type}" have been disabled`), + { + code: `EALLOW${spec.type.toUpperCase()}`, + package: spec.toString(), + } + ) + } + + // Builds a Node representing a spec we failed to load (allow-* gate, network failure, ENOTARGET, etc.) and records it in #loadFailures so #pruneFailedOptional can later decide whether the failure is fatal or silently dropped for optional deps. + #failureNode (name, parent, error, edge) { + error.requiredBy = edge?.from?.location || '.' + const n = new Node({ + name, + parent, + error, + installLinks: this.installLinks, + legacyPeerDeps: this.legacyPeerDeps, + }) + this.#loadFailures.add(n) + return n + } + #queueNamedUpdates () { // ignore top nodes, since they are not loaded the same way, and // probably have their own project associated with them. @@ -648,7 +867,7 @@ module.exports = cls => class IdealTreeBuilder extends cls { 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) { + !node.isTop && !node.inDepBundle) { for (const edge of node.edgesIn) { this.addTracker('idealTree', edge.from.name, edge.from.location) this.#depsQueue.push(edge.from) @@ -714,6 +933,7 @@ This is a one-time fix-up, please be patient... resolved: resolved, integrity: integrity, fullMetadata: false, + before: this.#releaseAgeBefore(spec), }) node.package = { ...mani, _id: `${mani.name}@${mani.version}` } } catch (er) { @@ -727,6 +947,7 @@ This is a one-time fix-up, please be patient... // have to re-calc dep flags, because the nodes don't have edges // until their packages get assigned, so everything looks extraneous + resetDepFlags(this.idealTree) calcDepFlags(this.idealTree) // yes, yes, this isn't the "original" version, but now that it's been @@ -770,15 +991,11 @@ This is a one-time fix-up, please be patient... 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. + // tree, skip over it and process the rest of the queue. if (this.#depsSeen.has(node) || - node.root !== this.idealTree || - hasShrinkwrap && !this.#complete) { + node.root !== this.idealTree) { return this.#buildDepStep() } @@ -788,15 +1005,16 @@ This is a one-time fix-up, please be patient... // 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 + // look inside if it has bundle deps. note that this is // not necessary during a reification, because we just update the - // ideal tree by reading bundles/shrinkwraps in place. + // ideal tree by reading bundles 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) + hasBundle && + !node.inert if (crackOpen) { const Arborist = this.constructor const opt = { ...this.options } @@ -808,15 +1026,8 @@ This is a one-time fix-up, please be patient... 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 }) - } + await new Arborist({ ...this.options, path }) + .loadActual({ root: node, ignoreMissing: true }) }) } @@ -897,8 +1108,21 @@ This is a one-time fix-up, please be patient... // 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) + let dep = vrDep && vrDep.satisfies(edge) ? vrDep : null + + // A peerOptional conflict can be resolved by finding an existing node in the tree that satisfies the edge, avoiding a registry fetch that may introduce an extraneous package. See npm/cli#9249. + // Skip the shortcut when the user has signaled an explicit re-fetch intent (npm update by name, explicit request, or audit fix), so we honor those signals rather than silently keeping the existing node. + const skipExistingShortcut = this[_updateNames].includes(edge.name) + || this.#explicitRequests.has(edge) + || (edge.to && this.auditReport?.isVulnerable(edge.to)) + if (!dep && edge.type === 'peerOptional' && !skipExistingShortcut) { + dep = this.#findHoistableNode( + /* istanbul ignore next - resolveParent is always set for non-root nodes */ + edge.from.resolveParent || edge.from, edge) + } + if (!dep) { + dep = await this.#nodeFromEdge(edge, parent, null, required) + } /* istanbul ignore next */ debug(() => { @@ -934,7 +1158,7 @@ This is a one-time fix-up, please be patient... tree: pd, getChildren: pd => pd.children, visit: pd => { - const { placed, edge, canPlace: cpd } = pd + const { placed, edge, canPlace: cpd, parent } = pd // if we didn't place anything, nothing to do here if (!placed) { return @@ -951,9 +1175,17 @@ This is a one-time fix-up, please be patient... 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) + if (!peerConflicted && !valid) { + if (this.#depsSeen.has(from) && this.options.save) { + // Re-queue already-processed nodes when a newly placed dep creates an invalid edge during npm install (save=true). + // This handles the case where a peerOptional dep was valid (missing) when the node was first processed, but becomes invalid when the dep is later placed by another path with a version that doesn't satisfy the peer spec. + // See npm/cli#8726. + this.#depsSeen.delete(from) + this.#depsQueue.push(from) + } else if (!this.#depsSeen.has(from)) { + this.addTracker('idealTree', from.name, from.location) + this.#depsQueue.push(from) + } } } } else { @@ -987,8 +1219,7 @@ This is a one-time fix-up, please be patient... return } - // lastly, also check for the missing deps of the node we placed, - // and any holes created by pruning out conflicted peer sets. + // 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) @@ -996,16 +1227,14 @@ This is a one-time fix-up, please be patient... } // 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. + // if it fails at this point, though, don't 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 + // 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))) + this.#fetchManifest(npa.resolve(e.name, e.spec, fromPath(placed, e)), parent, e) .catch(() => null) ) } @@ -1023,26 +1252,36 @@ This is a one-time fix-up, please be patient... 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. + // BFS descendants of `root` for a node satisfying `edge`. + // Prefers nodes closer to root. Skips bundled nodes. + #findHoistableNode (root, edge) { + const queue = [...root.children.values()] + while (queue.length) { + const node = queue.shift() + if (node.name === edge.name + && !node.inDepBundle + && node.satisfies(edge)) { + return node + } + for (const child of node.children.values()) { + queue.push(child) + } + } + return null + } + + // 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. + // 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. + // 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, @@ -1052,7 +1291,7 @@ This is a one-time fix-up, please be patient... ? await this.#nodeFromSpec(edge.name, spec2, parent, secondEdge) : null - // pick the second one if they're both happy with that, otherwise first + // 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 @@ -1135,11 +1374,6 @@ This is a one-time fix-up, please be patient... 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) { @@ -1150,9 +1384,13 @@ This is a one-time fix-up, please be patient... continue } - // If the edge has an error, there's a problem. + // If the edge has an error, there's a problem, unless it's peerOptional and we're not saving (e.g. npm ci), in which case we trust the lockfile and skip re-resolution. + // When saving (npm install), peerOptional invalid edges ARE treated as problems so the lockfile gets fixed. + // See npm/cli#8726. if (!edge.valid) { - problems.push(edge) + if (edge.type !== 'peerOptional' || this.options.save !== false) { + problems.push(edge) + } continue } @@ -1182,11 +1420,28 @@ This is a one-time fix-up, please be patient... return problems } - async #fetchManifest (spec) { + // The effective `before` filter for a package, applying `min-release-age-exclude`. + // Returns null (no age filter) for an exempted package, otherwise the + // configured `before`. The exemption is keyed on the spec's trusted registry + // identity (alias targets are unwrapped) so an `npm:` alias key cannot disable + // the filter for the package it actually resolves to. + #releaseAgeBefore (spec) { + const { before, minReleaseAgeExclude } = this.options + if (!before) { + return before + } + return isReleaseAgeExcluded(trustedSpecName(spec), minReleaseAgeExclude) ? null : before + } + + async #fetchManifest (spec, parent, edge) { + // Enforce allow-* gates before consulting the manifest cache so a cached entry from a different edge cannot bypass the policy. + this.#checkAllow(spec, edge) const options = { ...this.options, avoid: this.#avoidRange(spec.name), fullMetadata: true, + before: this.#releaseAgeBefore(spec), + _isRoot: !!(edge?.from?.isProjectRoot || edge?.from?.isWorkspace), } // get the intended spec and stored metadata from yarn.lock file, // if available and valid. @@ -1202,23 +1457,51 @@ This is a one-time fix-up, please be patient... } } - #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. + async #nodeFromSpec (name, spec, parent, edge) { + // Enforce allow-git / allow-file / allow-directory / allow-remote before any branching, so the symlink (Link) path is enforced as well as the manifest-fetch path. + // Route the failure through #loadFailures so optional-dep semantics apply (e.g. a transitive optionalDependencies entry that resolves to a disallowed git URL is silently dropped rather than failing the install). + try { + this.#checkAllow(spec, edge) + } catch (error) { + return this.#failureNode(name, parent, error, 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 + // spec is a directory, link it if: + // - it's a workspace, OR + // - it's a project-internal file: dependency (always linked), OR + // - it's external and installLinks is false // TODO post arborist refactor, will need to check for installStrategy=linked - if (spec.type === 'directory' && (isWorkspace || !installLinks)) { - return this.#linkFromSpec(name, spec, parent, edge) + let isProjectInternalFileSpec = false + if (edge?.rawSpec.startsWith('file:../') || edge?.rawSpec.startsWith('file:./')) { + const targetPath = resolve(parent.realpath, edge.rawSpec.slice(5)) + const resolvedProjectRoot = resolve(this.idealTree.realpath) + // Check if the target is within the project root + isProjectInternalFileSpec = targetPath.startsWith(resolvedProjectRoot + sep) || targetPath === resolvedProjectRoot } - // 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. + // When using --install-links, we need to handle transitive file dependencies specially + // If the parent was installed (not linked) due to --install-links, and this is a file: dep, we should also install it rather than link it + const parentWasInstalled = parent && !parent.isLink && parent.resolved?.startsWith('file:') + const isTransitiveFileDep = spec.type === 'directory' && parentWasInstalled && installLinks + + // Decide whether to link or copy the dependency + const shouldLink = (isWorkspace || isProjectInternalFileSpec || !installLinks) && !isTransitiveFileDep + if (spec.type === 'directory' && shouldLink) { + const realpath = spec.fetchSpec + const { content: pkg } = await PackageJson.normalize(realpath).catch(() => { + return { content: {} } + }) + const link = new Link({ name, parent, realpath, pkg, installLinks, legacyPeerDeps }) + this.#linkNodes.add(link) + return link + } + + // 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)) { @@ -1226,35 +1509,47 @@ This is a one-time fix-up, please be patient... } } + // For file: dependencies that we're installing (not linking), ensure proper resolution + if (isTransitiveFileDep && edge) { + // For transitive file deps, resolve relative to the parent's original source location + const parentOriginalPath = parent.resolved.slice(5) // Remove 'file:' prefix + const relativePath = edge.rawSpec.slice(5) // Remove 'file:' prefix + const absolutePath = resolve(parentOriginalPath, relativePath) + spec = npa.resolve(name, `file:${absolutePath}`) + } + // 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 - }) + return this.#fetchManifest(spec, parent, edge) + .then( + pkg => { + // When a proxy/upstream registry returns an incomplete manifest + // (e.g. missing version field for platform-specific packages it + // hasn't cached), treat it as a load failure so that optional deps + // are properly pruned instead of written to the lockfile without + // version metadata. Only apply to registry specs — file: deps + // legitimately omit version. + if (!pkg.version && spec.registry) { + const error = Object.assign( + new Error(`incomplete manifest for ${name}, missing version`), + { code: 'EINCOMPLETEMANIFEST' } + ) + return this.#failureNode(name, parent, error, edge) + } + // Transform the manifest copy before any packageExtensions rule and before the Node reads its dependency and peer edges. + const transformed = this.#applyNpmExtension(pkg) + const { pkg: extended, applied } = this.#applyPackageExtension(transformed.pkg) + const node = new Node({ name, pkg: extended, parent, installLinks, legacyPeerDeps }) + if (transformed.applied) { + node.npmExtensionApplied = transformed.applied + } + if (applied) { + node.packageExtensionsApplied = applied + } + return node + }, + error => this.#failureNode(name, parent, error, edge) + ) } // load all peer deps and meta-peer deps into the node's parent @@ -1278,6 +1573,12 @@ This is a one-time fix-up, please be patient... .sort(({ name: a }, { name: b }) => localeCompare(a, b)) for (const edge of peerEdges) { + // node.parent gets mutated during loop execution due to recursive #nodeFromEdge calls. + // When a compatible peer is found (e.g. a@1.1.0 replaces a@1.2.0), the original node loses its parent. + // if node is detached/removed from the tree, or has no parent, so no need to check remaining edgesOut for that node. + if (!node.parent) { + break + } // already placed this one, and we're happy with it. if (edge.valid && edge.to) { continue @@ -1384,7 +1685,8 @@ This is a one-time fix-up, please be patient... // - 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 + // call buildDepStep if anything was added to the queue; otherwise, we're done + // XXX load-virtual also has a #resolveLinks, is there overlap? #resolveLinks () { for (const link of this.#linkNodes) { this.#linkNodes.delete(link) @@ -1448,11 +1750,7 @@ This is a one-time fix-up, please be patient... } 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 + this.idealTree.unsetDepFlags() } // at this point, any node marked as extraneous should be pruned. @@ -1462,11 +1760,6 @@ This is a one-time fix-up, please be patient... 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() @@ -1488,7 +1781,7 @@ This is a one-time fix-up, please be patient... const set = optionalSet(node) for (const node of set) { - node.parent = null + node.inert = true } } } @@ -1509,6 +1802,7 @@ This is a one-time fix-up, please be patient... node.parent !== null && !node.isProjectRoot && !excludeNodes.has(node) + && !node.inert ) { this[_addNodeToTrashList](node) } diff --git a/workspaces/arborist/lib/arborist/index.js b/workspaces/arborist/lib/arborist/index.js index 3622f957b7acd..11581cb4fd940 100644 --- a/workspaces/arborist/lib/arborist/index.js +++ b/workspaces/arborist/lib/arborist/index.js @@ -68,12 +68,42 @@ class Arborist extends Base { constructor (options = {}) { const timeEnd = time.start('arborist:ctor') super(options) + + // normalize trailing slash + const registry = options.registry || 'https://registry.npmjs.org' + options.registry = this.registry = registry.replace(/(? { - 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 - } +// generate short hash key based on the dependency tree starting at this node +const getKey = (startNode) => { + const deps = [] + const branch = [] + depth({ + tree: startNode, + getChildren: node => node.dependencies, + visit: node => { + branch.push(`${node.packageName}@${node.version}`) + // a patch changes the materialized contents, so it must change the store key. + // the patch segment is only appended when present, so unpatched keys are unchanged. + const patch = node.patched ? `::patch:${node.patched.integrity}` : '' + deps.push(`${branch.join('->')}::${node.resolved}${patch}`) + }, + leave: () => { + branch.pop() + }, + }) + deps.sort() + // TODO these replaces were originally to deal with node 14 not supporting base64url and likely don't need to happen anymore + // Changing this is a pretty significant breaking change, but removing parts of the hash increases collision possibilities (even if slight). + const hash = crypto.createHash('shake256', { outputLength: 16 }) + .update(deps.join(',')) + .digest('base64') + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=+$/m, '') + // a patched entry gets a distinct, identifiable side-store key so unpatched consumers keep sharing the original + const patchSuffix = startNode.patched ? '+patch' : '' + return `${startNode.packageName}@${startNode.version}-${hash}${patchSuffix}` } module.exports = cls => class IsolatedReifier extends cls { + #externalProxies = new Map() + #omit = new Set() + #rootDeclaredDeps = new Set() + #processedEdges = new Set() + #workspaceProxies = new Map() + + #generateChild (node, location, pkg, isInStore, root, inBundle = false) { + const newChild = new IsolatedNode({ + isInStore, + inBundle, + isRegistryDependency: node.isRegistryDependency, + isRootDependency: node.isRootDependency, + location, + name: node.packageName || node.name, + optional: node.optional, + package: pkg, + parent: root, + patched: node.patched, + path: join(this.idealGraph.localPath, location), + resolved: node.resolved, + root, + }) + // XXX top is from place-dep not lib/node.js + newChild.top = { path: this.idealGraph.localPath } + root.children.set(newChild.location, newChild) + root.inventory.set(newChild.location, newChild) + } + /** * 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. + * 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. + * 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. + * 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) + async makeIdealGraph () { const idealTree = this.idealTree + this.#omit = new Set(this.options.omit) + const omit = this.#omit - this.rootNode = {} - const root = this.rootNode - this.counter = 0 + // npm auto-creates 'workspace' edges from root to all workspaces. + // For isolated/linked mode, only include workspaces that root explicitly declares as dependencies. + // When omitting dep types, exclude those from the declared set so their workspaces aren't hoisted. + const rootPkg = idealTree.package + this.#rootDeclaredDeps = new Set(Object.keys(Object.assign({}, + rootPkg.dependencies, + (!omit.has('dev') && rootPkg.devDependencies), + (!omit.has('optional') && rootPkg.optionalDependencies), + (!omit.has('peer') && rootPkg.peerDependencies) + ))) - // memoize to cache generating proxy Nodes - this.externalProxyMemo = memoize(this.externalProxy.bind(this)) - this.workspaceProxyMemo = memoize(this.workspaceProxy.bind(this)) + // XXX this sometimes acts like a node too + this.idealGraph = { + external: [], + isProjectRoot: true, + localLocation: idealTree.location, + localPath: idealTree.path, + path: idealTree.path, + } + this.counter = 0 - 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)) + // Skip extraneous fsChildren: workspaces removed from the root manifest can linger in fsChildren via the lockfile, and re-materializing them here would re-create a directory the user just deleted. + const fsChildren = Array.from(idealTree.fsChildren.values()).filter(w => !w.extraneous) + this.idealGraph.workspaces = await Promise.all(fsChildren.map(w => this.#workspaceProxy(w))) const processed = new Set() const queue = [idealTree, ...idealTree.fsChildren] while (queue.length !== 0) { @@ -75,94 +116,149 @@ module.exports = cls => class IsolatedReifier extends cls { continue } processed.add(next.location) - next.edgesOut.forEach(e => { - if (!e.to || (next.package.bundleDependencies || next.package.bundledDependencies || []).includes(e.to.name)) { - return + next.edgesOut.forEach(edge => { + if (edge.to && !(next.package.bundleDependencies || next.package.bundledDependencies || []).includes(edge.to.name) && !edge.to.shouldOmit?.(omit)) { + queue.push(edge.to) } - queue.push(e.to) }) - if (!next.isProjectRoot && !next.isWorkspace) { - root.external.push(await this.externalProxyMemo(next)) + // local `file:` deps are in fsChildren but are not workspaces. + // they are already handled as workspace-like proxies above and should not go through the external/store extraction path. + // Links with file: resolved paths (from `npm link`) should also be treated as local dependencies and symlinked directly instead of being extracted into the store. + const isLocalFileDep = next.isLink && next.resolved?.startsWith('file:') + if (isLocalFileDep && !idealTree.fsChildren.has(next) && !idealTree.fsChildren.has(next.target)) { + this.idealGraph.workspaces.push(await this.#workspaceProxy(next.target)) + } else if (!next.isProjectRoot && !next.isWorkspace && !next.inert && !idealTree.fsChildren.has(next) && !idealTree.fsChildren.has(next.target)) { + this.idealGraph.external.push(await this.#externalProxy(next)) } } - await this.assignCommonProperties(idealTree, root) - - this.idealGraph = root + await this.#assignCommonProperties(idealTree, this.idealGraph) } - async workspaceProxy (result, node) { + async #workspaceProxy (node) { + if (this.#workspaceProxies.has(node)) { + return this.#workspaceProxies.get(node) + } + const result = {} + // XXX this goes recursive if we don't set here because assignCommonProperties also calls this.#workspaceProxy + this.#workspaceProxies.set(node, result) result.localLocation = node.location result.localPath = node.path result.isWorkspace = true result.resolved = node.resolved - await this.assignCommonProperties(node, result) + await this.#assignCommonProperties(node, result) + return 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, - ] + async #externalProxy (node) { + if (this.#externalProxies.has(node)) { + return this.#externalProxies.get(node) } + const result = {} + // XXX this goes recursive if we don't set here because assignCommonProperties also calls this.#externalProxy + this.#externalProxies.set(node, result) + await this.#assignCommonProperties(node, result) result.optional = node.optional result.resolved = node.resolved result.version = node.version + // Carry the source node's registry-dependency flag so the store node retains it. + // IsolatedNode has no edges to recompute it from, and reify's registry-tarball allow-remote exemption depends on it. + result.isRegistryDependency = node.isRegistryDependency + // Same reasoning for allow-remote=root: the store node has no edgesIn, so capture from the source node whether it satisfies a valid edge from the project root or a workspace. + result.isRootDependency = [...node.edgesIn].some(e => + e.valid && (e.from?.isProjectRoot || e.from?.isWorkspace) + ) + return result } - 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)) + async #assignCommonProperties (node, result) { + result.root = this.idealGraph + // XXX does anything need this? + result.id = this.counter++ + /* istanbul ignore next - packageName is always set for real packages */ + result.name = result.isWorkspace ? (node.packageName || node.name) : node.name + // strip any path traversal from package.json name fields before they hit path.join below + result.packageName = nameFromFolder(node.packageName || node.path) + result.patched = node.patched + result.package = { ...node.package } + result.package.bundleDependencies = undefined + + let edges = [...node.edgesOut.values()].filter(edge => + edge.to?.target && + !(node.package.bundledDependencies || node.package.bundleDependencies)?.includes(edge.to.name) + ) + + // Only omit edge types for root and workspace nodes (matching shouldOmit scope) + if ((node.isProjectRoot || node.isWorkspace) && this.#omit.size) { + edges = edges.filter(edge => { + if (edge.dev && this.#omit.has('dev')) { + return false + } + if (edge.optional && this.#omit.has('optional')) { + return false + } + if (edge.peer && this.#omit.has('peer')) { + return false + } + return true + }) + } + + let nonOptionalDeps = edges.filter(edge => !edge.optional).map(edge => edge.to.target) + + // npm auto-creates 'workspace' edges from root to all workspaces. + // For isolated/linked mode, only include workspaces that root explicitly declares as dependencies. + if (node.isProjectRoot) { + nonOptionalDeps = nonOptionalDeps.filter(n => !n.isWorkspace || this.#rootDeclaredDeps.has(n.packageName)) } - 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)) + // When legacyPeerDeps is enabled, peer dep edges are not created on the node. + // Resolve them from the tree so they get symlinked in the store. + const peerDeps = node.package.peerDependencies + if (peerDeps && node.legacyPeerDeps) { + const edgeNames = new Set(edges.map(edge => edge.name)) + for (const peerName in peerDeps) { + if (!edgeNames.has(peerName)) { + const resolved = node.resolve(peerName) + if (resolved && resolved !== node && !resolved.inert) { + nonOptionalDeps.push(resolved.target) + } + } + } + } + + // local `file:` deps (non-workspace fsChildren) should be treated as local dependencies, not external, so they get symlinked directly instead of being extracted into the store. + // A file: dep surfaces as a Link edge whose resolved spec starts with file:; detect it from the edge so the target is treated as local even when it is absent from idealTree.fsChildren (a workspace consumer, or a target outside the repo root via npm link). + const fileLinkTargets = new Set(edges.filter(e => e.to?.isLink && e.to.resolved?.startsWith('file:')).map(e => e.to.target)) + const isLocal = (n) => n.isWorkspace || node.fsChildren?.has(n) || fileLinkTargets.has(n) + const optionalDeps = edges.filter(edge => edge.optional).map(edge => edge.to.target) + + // Optional peers declared only in peerDependenciesMeta (e.g. `@types/react`) have no edge, so the materialization above misses them. + // Resolve each from the tree and link it; if nobody provides it, node.resolve finds nothing and it stays omitted. + const peerMeta = node.package.peerDependenciesMeta + if (peerMeta) { + const resolvedNames = new Set([...nonOptionalDeps, ...optionalDeps].map(n => n.name)) + for (const peerName in peerMeta) { + if (!peerMeta[peerName]?.optional || resolvedNames.has(peerName)) { + continue + } + const resolved = node.resolve(peerName)?.target + if (resolved && resolved !== node && !resolved.inert && !isLocal(resolved)) { + optionalDeps.push(resolved) + } + } + } + result.localDependencies = await Promise.all(nonOptionalDeps.filter(isLocal).map(n => this.#workspaceProxy(n))) + result.externalDependencies = await Promise.all(nonOptionalDeps.filter(n => !isLocal(n) && !n.inert).map(n => this.#externalProxy(n))) + result.externalOptionalDependencies = await Promise.all(optionalDeps.filter(n => !n.inert).map(n => this.#externalProxy(n))) 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] () { + async #createBundledTree () { // TODO: make sure that idealTree object exists const idealTree = this.idealTree // TODO: test workspaces having bundled deps @@ -201,253 +297,179 @@ module.exports = cls => class IsolatedReifier extends cls { 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 => { + to.edgesOut.forEach(edge => { // an edge out should always have a to /* istanbul ignore else */ - if (e.to) { - queue.push({ from: e.from, to: e.to }) + if (edge.to) { + queue.push({ from: edge.from, to: edge.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)}` - } + async createIsolatedTree () { + await this.makeIdealGraph() + const bundledTree = await this.#createBundledTree() - 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 root = new IsolatedNode(this.idealGraph) + root.root = root + root.inventory.set('', root) const processed = new Set() - proxiedIdealTree.workspaces.forEach(c => { - const workspace = { - edgesIn: new Set(), - edgesOut: new Map(), - children: [], - hasInstallScript: c.hasInstallScript, - binPaths: [], - package: c.package, + for (const c of this.idealGraph.workspaces) { + const wsName = c.packageName + // XXX parent? root? + const workspace = new IsolatedNode({ location: c.localLocation, + name: wsName, + package: c.package, path: c.localPath, - realpath: c.localPath, resolved: c.resolved, - } - root.fsChildren.push(workspace) + }) + root.fsChildren.add(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, + root.workspaces.set(wsName, workspace.path) + + // Declared workspaces are symlinked at root node_modules/. + // Undeclared workspaces get a tree-only Link kept for diff/filter participation but not materialized on disk. + const isDeclared = this.#rootDeclaredDeps.has(wsName) + const wsLink = new IsolatedLink({ + location: isDeclared ? join('node_modules', wsName) : join(c.localLocation, 'node_modules', wsName), + name: wsName, + package: workspace.package, + parent: root, + path: isDeclared ? join(root.path, 'node_modules', wsName) : join(root.path, c.localLocation, 'node_modules', wsName), + realpath: workspace.path, + root, + target: workspace, + }) + if (!isDeclared) { + wsLink.isUndeclaredWorkspaceLink = true } - newChild.target = newChild - root.children.push(newChild) - root.inventory.set(newChild.location, newChild) + root.children.set(wsName, wsLink) + root.inventory.set(wsLink.location, wsLink) + workspace.linksIn.add(wsLink) } - proxiedIdealTree.external.forEach(c => { + + this.idealGraph.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) + const location = join('node_modules', '.store', key, 'node_modules', c.packageName) + this.#generateChild(c, location, c.package, true, root) }) + bundledTree.nodes.forEach(node => { - generateChild(node, node.location, node.pkg, false) + this.#generateChild(node, node.location, node.pkg, false, root, true) }) - bundledTree.edges.forEach(e => { - const from = e.from === 'root' ? root : root.inventory.get(e.from) - const to = root.inventory.get(e.to) + + bundledTree.edges.forEach(edge => { + const from = edge.from === 'root' ? root : root.inventory.get(edge.from) + const to = root.inventory.get(edge.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 newEdge = { optional: false, from, to } + from.edgesOut.set(to.name, newEdge) + to.edgesIn.add(newEdge) }) - 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') - } + this.#processEdges(this.idealGraph, false, root) + for (const node of this.idealGraph.workspaces) { + this.#processEdges(node, false, root) + } + return root + } - const processDeps = (dep, optional, external) => { - optional = !!optional - external = !!external + #processEdges (node, externalEdge, root) { + const key = getKey(node) + if (this.#processedEdges.has(key)) { + return + } + this.#processedEdges.add(key) - const location = join(nmFolder, dep.name) - const binNames = dep.package.bin && Object.keys(dep.package.bin) || [] - const toKey = getKey(dep) + let from, nmFolder + if (externalEdge) { + const fromLocation = join('node_modules', '.store', key, 'node_modules', node.packageName) + from = root.children.get(fromLocation) + nmFolder = join('node_modules', '.store', key, 'node_modules') + } else { + from = node.isProjectRoot ? root : root.inventory.get(node.localLocation) + nmFolder = join(node.localLocation, 'node_modules') + } + /* istanbul ignore next - strict-peer-deps can exclude nodes from the tree */ + if (!from) { + return + } - 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) { + this.#processEdges(dep, false, root) + // nonOptional, local + this.#processDeps(dep, false, false, root, from, nmFolder) + } + for (const dep of node.externalDependencies) { + this.#processEdges(dep, true, root) + // nonOptional, external + this.#processDeps(dep, false, true, root, from, nmFolder) + } + for (const dep of node.externalOptionalDependencies) { + this.#processEdges(dep, true, root) + // optional, external + this.#processDeps(dep, true, true, root, from, nmFolder) + } + } - 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) + #processDeps (dep, optional, external, root, from, nmFolder) { + const toKey = getKey(dep) + + let target + if (external) { + const toLocation = join('node_modules', '.store', toKey, 'node_modules', dep.packageName) + target = root.children.get(toLocation) + } else { + target = root.inventory.get(dep.localLocation) + } + // TODO: we should no-op is an edge has already been created with the same fromKey and toKey + /* istanbul ignore next - strict-peer-deps can exclude nodes from the tree */ + if (!target) { + return + } + + if (dep.package.bin) { + for (const bn in dep.package.bin) { + target.binPaths.push(join(dep.root.localPath, nmFolder, '.bin', bn)) } } - processEdges(proxiedIdealTree, false) - for (const node of proxiedIdealTree.workspaces) { - processEdges(node, false) + const pkg = { + _id: dep.package._id, + bin: target.package.bin, + bundleDependencies: undefined, + deprecated: undefined, + scripts: dep.package.scripts, + version: dep.package.version, } - root.children.forEach(c => c.parent = root) - root.children.forEach(c => c.root = root) - root.root = root - root.target = root - return root + const link = new IsolatedLink({ + isStoreLink: true, + location: join(nmFolder, dep.name), + name: toKey, + optional, + parent: root, + package: pkg, + path: join(dep.root.localPath, nmFolder, dep.name), + realpath: target.path, + resolved: external ? `file:.store/${toKey}/node_modules/${dep.packageName}` : dep.resolved, + root, + target, + }) + // XXX top is from place-dep not lib/link.js + link.top = { path: dep.root.localPath } + 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.set(link.location, link) } } diff --git a/workspaces/arborist/lib/arborist/load-actual.js b/workspaces/arborist/lib/arborist/load-actual.js index 22c1c2875f1b1..e23b91dba8a23 100644 --- a/workspaces/arborist/lib/arborist/load-actual.js +++ b/workspaces/arborist/lib/arborist/load-actual.js @@ -1,11 +1,11 @@ // mix-in implementing the loadActual method -const { relative, dirname, resolve, join, normalize } = require('node:path') +const { dirname, join, normalize, relative, resolve } = require('node:path') -const rpj = require('read-package-json-fast') +const PackageJson = require('@npmcli/package-json') const { readdirScoped } = require('@npmcli/fs') const { walkUp } = require('walk-up-path') -const ancestorPath = require('common-ancestor-path') +const { commonAncestorPath } = require('common-ancestor-path') const treeCheck = require('../tree-check.js') const Shrinkwrap = require('../shrinkwrap.js') @@ -13,6 +13,8 @@ const calcDepFlags = require('../calc-dep-flags.js') const Node = require('../node.js') const Link = require('../link.js') const realpath = require('../realpath.js') +const PackageExtensions = require('../package-extensions.js') +const NpmExtension = require('../npm-extension.js') // public symbols const _changePath = Symbol.for('_changePath') @@ -36,24 +38,11 @@ module.exports = cls => class ActualLoader extends cls { // 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 + // 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 = {}) { @@ -186,6 +175,10 @@ module.exports = cls => class ActualLoader extends cls { await Promise.all(promises) } + // .npm-extension runs before packageExtensions, matching the ideal-tree resolution order + await this.#applyNpmExtension() + this.#applyPackageExtensions() + if (!ignoreMissing) { await this.#findMissingEdges() } @@ -216,7 +209,7 @@ module.exports = cls => class ActualLoader extends cls { 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')}` : '*' + const def = kid.isLink ? `file:${kid.realpath}` : '*' dependencies[name] = dependencies[name] || def } actualRoot.package = { ...actualRoot.package, dependencies } @@ -279,12 +272,16 @@ module.exports = cls => class ActualLoader extends cls { } try { - const pkg = await rpj(join(real, 'package.json')) + const { content: pkg } = await PackageJson.normalize(real) params.pkg = pkg if (useRootOverrides && root.overrides) { params.overrides = root.overrides.getNodeRule({ name: pkg.name, version: pkg.version }) } } catch (err) { + if (err.code === 'EJSONPARSE') { + // TODO @npmcli/package-json should be doing this + err.path = join(real, 'package.json') + } params.error = err } @@ -361,6 +358,67 @@ module.exports = cls => class ActualLoader extends cls { } } + // packageExtensions never rewrite a package's package.json, so a filesystem-scanned actual tree lacks the extension-created edges and provenance. + // Re-derive them from the root rule set, as buildIdealTree does. + // This is always required under the linked strategy, whose store layout forces the filesystem-scan path. + #applyPackageExtensions () { + const rootPkg = this.#actualTree.target?.package + const pe = new PackageExtensions(rootPkg?.packageExtensions) + if (!pe.present || !pe.selectors.length) { + return + } + for (const node of this.#actualTree.inventory.values()) { + // only installed dependencies are extended, never the root or a workspace + if (node.isLink || node.isProjectRoot || !node.name || !node.inNodeModules()) { + continue + } + const res = pe.apply(node.package) + if (res) { + node.package = res.pkg + node.packageExtensionsApplied = res.applied + } + } + // mirror the provenance onto links so the logical tree location reports it too + for (const node of this.#actualTree.inventory.values()) { + if (node.isLink && node.target?.packageExtensionsApplied) { + node.packageExtensionsApplied = node.target.packageExtensionsApplied + } + } + } + + // .npm-extension transformManifest, like packageExtensions, never rewrites a package's package.json, so re-derive its edges and provenance on a filesystem-scanned actual tree. + // This executes the root extension code; ignore-extension (and ignore-scripts via flatten) disables it. + async #applyNpmExtension () { + if (this.options.ignoreExtension) { + return + } + const ext = new NpmExtension({ + root: this.#actualTree.realpath, + extensionFile: this.options.extensionFile, + }) + if (!ext.present) { + return + } + await ext.load() + for (const node of this.#actualTree.inventory.values()) { + // only installed dependencies are transformed, never the root or a workspace + if (node.isLink || node.isProjectRoot || !node.name || !node.inNodeModules()) { + continue + } + const res = ext.apply(node.package) + if (res) { + node.package = res.pkg + node.npmExtensionApplied = res.applied + } + } + // mirror the provenance onto links so the logical tree location reports it too + for (const node of this.#actualTree.inventory.values()) { + if (node.isLink && node.target?.npmExtensionApplied) { + node.npmExtensionApplied = node.target.npmExtensionApplied + } + } + } + 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 @@ -373,7 +431,7 @@ module.exports = cls => class ActualLoader extends cls { const nmContents = new Map() const tree = this.#actualTree for (const node of tree.inventory.values()) { - const ancestor = ancestorPath(node.realpath, this.path) + const ancestor = commonAncestorPath(node.realpath, this.path) const depPromises = [] for (const [name, edge] of node.edgesOut.entries()) { diff --git a/workspaces/arborist/lib/arborist/load-virtual.js b/workspaces/arborist/lib/arborist/load-virtual.js index 7c51f8b9bef79..7e876adc016d5 100644 --- a/workspaces/arborist/lib/arborist/load-virtual.js +++ b/workspaces/arborist/lib/arborist/load-virtual.js @@ -1,16 +1,15 @@ +const { resolve } = require('node:path') // mixin providing the loadVirtual method const mapWorkspaces = require('@npmcli/map-workspaces') - -const { resolve } = require('node:path') - +const PackageJson = require('@npmcli/package-json') 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') @@ -19,14 +18,6 @@ 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) { @@ -48,16 +39,17 @@ module.exports = cls => class VirtualLoader extends cls { resolveOptions: this.options, }) if (!s.loadedFromDisk && !options.root) { - const er = new Error('loadVirtual requires existing shrinkwrap file') + const er = new Error('loadVirtual requires existing package-lock.json 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 pkg = await PackageJson.normalize(this.path).then(p => p.content).catch(() => s.data.packages[''] || {}) + // TODO clean this up const { - root = await this.#loadRoot(s), + root = await this[setWorkspaces](this.#loadNode('', pkg, true)), } = options - this.#rootOptionProvided = options.root await this.#loadFromShrinkwrap(s, root) @@ -65,21 +57,11 @@ module.exports = cls => class VirtualLoader extends cls { 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 + root.unsetDepFlags() } else { this[flagsSuspect] = true } @@ -87,7 +69,21 @@ module.exports = cls => class VirtualLoader extends cls { this.#checkRootEdges(s, root) root.meta = s this.virtualTree = root - const { links, nodes } = this.#resolveNodes(s, root) + // separate out link metadata, and create Node objects for nodes + 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)) + } + } await this.#resolveLinks(links, nodes) if (!(s.originalLockfileVersion >= 2)) { this.#assignBundles(nodes) @@ -99,11 +95,7 @@ module.exports = cls => class VirtualLoader extends cls { if (node.isRoot || node === this.#rootOptionProvided) { continue } - node.extraneous = true - node.dev = true - node.optional = true - node.devOptional = true - node.peer = true + node.resetDepFlags() } calcDepFlags(this.virtualTree, !this.#rootOptionProvided) } @@ -149,7 +141,7 @@ module.exports = cls => class VirtualLoader extends cls { }) for (const [name, path] of workspaces.entries()) { - lockWS[name] = `file:${path.replace(/#/g, '%23')}` + lockWS[name] = `file:${path}` } // Should rootNames exclude optional? @@ -174,32 +166,26 @@ module.exports = cls => class VirtualLoader extends cls { } } - // 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) + // XXX build-ideal-tree also has a #resolveLinks, is there overlap? 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) + + if (!target) { + const err = new Error( +`Missing target in lock file: "${targetLoc}" is referenced by "${location}" but does not exist. +To fix: +1. rm package-lock.json +2. npm install` + ) + err.code = 'EMISSINGTARGET' + throw err + } + const link = this.#loadLink(location, targetLoc, target, meta) nodes.set(location, link) nodes.set(targetLoc, link.target) @@ -207,11 +193,7 @@ module.exports = cls => class VirtualLoader extends cls { // 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 - } + await PackageJson.normalize(link.realpath).then(p => link.target.package = p.content).catch(() => null) } } } @@ -253,11 +235,6 @@ module.exports = cls => class VirtualLoader extends cls { 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, @@ -265,21 +242,20 @@ module.exports = cls => class VirtualLoader extends cls { path, realpath: path, integrity: sw.integrity, + patched: sw.patched, + packageExtensionsApplied: sw.packageExtensionsApplied, + npmExtensionApplied: sw.npmExtensionApplied, 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 + extraneous: !!sw.extraneous, + devOptional: !!(sw.devOptional || sw.dev || sw.optional), + peer: !!sw.peer, + optional: !!sw.optional, + dev: !!sw.dev, }) - // 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 } diff --git a/workspaces/arborist/lib/arborist/rebuild.js b/workspaces/arborist/lib/arborist/rebuild.js index 82f84772f9a85..53c6f63e77d94 100644 --- a/workspaces/arborist/lib/arborist/rebuild.js +++ b/workspaces/arborist/lib/arborist/rebuild.js @@ -1,20 +1,21 @@ // Arborist.rebuild({path = this.path}) will do all the binlinks and // bundle building needed. Called by reify, and by `npm rebuild`. +const PackageJson = require('@npmcli/package-json') +const binLinks = require('bin-links') 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 { depth: dfwalk } = require('treeverse') const { isNodeGypPackage, defaultGypInstallScript } = require('@npmcli/node-gyp') +const { promiseRetry } = require('@gar/promise-retry') const { log, time } = require('proc-log') +const { resolve, delimiter } = require('node:path') +const { isScriptAllowed } = require('../script-allowed.js') const boolEnv = b => b ? '1' : '' -const sortNodes = (a, b) => - (a.depth - b.depth) || localeCompare(a.path, b.path) +const sortNodes = (a, b) => (a.depth - b.depth) || localeCompare(a.path, b.path) const _checkBins = Symbol.for('checkBins') @@ -25,13 +26,12 @@ 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() + #queues = { + preinstall: [], + install: [], + postinstall: [], + prepare: [], + bin: [], } async rebuild ({ nodes, handleOptionalFailure = false } = {}) { @@ -63,7 +63,13 @@ module.exports = cls => class Builder extends cls { // build link deps if (linkNodes.size) { - this.#resetQueues() + this.#queues = { + preinstall: [], + install: [], + postinstall: [], + prepare: [], + bin: [], + } await this.#build(linkNodes, { type: 'links' }) } @@ -133,16 +139,6 @@ module.exports = cls => class Builder extends cls { } } - #resetQueues () { - this.#queues = { - preinstall: [], - install: [], - postinstall: [], - prepare: [], - bin: [], - } - } - async #build (nodes, { type = 'deps' }) { const timeEnd = time.start(`build:${type}`) @@ -154,7 +150,9 @@ module.exports = cls => class Builder extends cls { // links should run prepare scripts and only link bins after that if (type === 'links') { - await this.#runScripts('prepare') + if (!this.options.ignoreScripts) { + await this.#runScripts('prepare') + } } if (this.options.binLinks) { await this.#linkAllBins() @@ -201,10 +199,28 @@ module.exports = cls => class Builder extends cls { const { package: { bin, scripts = {} } } = node.target const { preinstall, install, postinstall, prepare } = scripts const tests = { bin, preinstall, install, postinstall, prepare } + // allowScripts gate (RFC npm/rfcs#868): `true` runs lifecycle + // scripts; `false` and `null` (unreviewed) block. Bypassed by + // --dangerously-allow-all-scripts and workspaces (owner-managed). + // --ignore-scripts still wins (in #build); bins are never gated. + // + // Checked on node.target, not the Link: a Link's `resolved` is + // node_modules-relative (`file:../../dep`) so it can't match a + // project-root-relative policy key; the target carries the realpath + // and link specs that script-allowed.js matches on (npm/cli#9498). + // For non-links node.target === node, so registry deps are unaffected. + const scriptsAllowed = + this.options.dangerouslyAllowAllScripts || + node.isWorkspace || + isScriptAllowed(node.target, this.options.allowScripts) === true for (const [key, has] of Object.entries(tests)) { - if (has) { - this.#queues[key].push(node) + if (!has) { + continue + } + if (key !== 'bin' && !scriptsAllowed) { + continue } + this.#queues[key].push(node) } } timeEnd() @@ -248,7 +264,9 @@ module.exports = cls => class Builder extends cls { // 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(() => ({})) + const { content: pkg } = await PackageJson.normalize(node.path).catch(() => { + return { content: {} } + }) set.delete(node) const { scripts = {} } = pkg @@ -289,6 +307,7 @@ module.exports = cls => class Builder extends cls { await promiseCallLimit(queue.map(node => async () => { const { path, + name, integrity, resolved, optional, @@ -297,12 +316,13 @@ module.exports = cls => class Builder extends cls { devOptional, package: pkg, location, - isStoreLink, + isInStore, } = node.target // skip any that we know we'll be deleting - // or storeLinks - if (this[_trashList].has(path) || isStoreLink) { + // or links to store entries (their scripts run on the store + // entry itself, not through the link) + if (this[_trashList].has(path) || (node.isLink && node.target?.isInStore)) { return } @@ -318,6 +338,12 @@ module.exports = cls => class Builder extends cls { npm_package_dev_optional: boolEnv(devOptional && !dev && !optional), } + // In the linked strategy a store package's dependencies are symlinked siblings in its store node_modules. + // A separate bin invoked by the script (e.g. napi-postinstall) resolves modules from its own realpath in the store and cannot see those deps, so expose them via NODE_PATH. + if (isInStore) { + const storeNodeModules = resolve(path, ...name.split('/').map(() => '..')) + env.NODE_PATH = [storeNodeModules, process.env.NODE_PATH].filter(Boolean).join(delimiter) + } const runOpts = { event, path, @@ -383,13 +409,20 @@ module.exports = cls => class Builder extends cls { const timeEnd = time.start(`build:link:${node.location}`) - const p = binLinks({ + // On Windows, antivirus/indexer can transiently lock files, causing EPERM/EACCES/EBUSY on the rename inside write-file-atomic (used by bin-links/fix-bin.js), so, retry with backoff. + const p = promiseRetry((retry) => binLinks({ pkg: node.package, path: node.path, top: !!(node.isTop || node.globalTop), force: this.options.force, global: !!node.globalTop, - }) + }).catch(/* istanbul ignore next - Windows-only transient antivirus locks */ err => { + if (process.platform === 'win32' && + (err.code === 'EPERM' || err.code === 'EACCES' || err.code === 'EBUSY')) { + return retry(err) + } + throw err + }), { retries: 5, minTimeout: 500 }) await (this.#doHandleOptionalFailure ? this[_handleOptionalFailure](node, p) diff --git a/workspaces/arborist/lib/arborist/reify.js b/workspaces/arborist/lib/arborist/reify.js index be920272d48f0..45cd7c0e46c48 100644 --- a/workspaces/arborist/lib/arborist/reify.js +++ b/workspaces/arborist/lib/arborist/reify.js @@ -1,48 +1,41 @@ // 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 hgi = require('hosted-git-info') +const npa = require('npm-package-arg') const packageContents = require('@npmcli/installed-package-contents') +const pacote = require('pacote') +const { pickRegistry } = require('npm-registry-fetch') +const promiseAllRejectLate = require('promise-all-reject-late') const runScript = require('@npmcli/run-script') -const { checkEngine, checkPlatform } = require('npm-install-checks') +const { callLimit: promiseCallLimit } = require('promise-call-limit') +const { depth: dfwalk } = require('treeverse') +const { dirname, resolve, relative, join, sep } = require('node:path') +const { log, time } = require('proc-log') +const { existsSync } = require('node:fs') +const { lstat, mkdir, readdir, readlink, rm, symlink } = require('node:fs/promises') +const { moveFile } = require('@npmcli/fs') +const { subset, intersects } = require('semver') +const { walkUp } = require('walk-up-path') -const treeCheck = require('../tree-check.js') -const relpath = require('../relpath.js') +const AuditReport = require('../audit-report.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 debug = require('../debug.js') +const onExit = require('../signal-handling.js') +const optionalSet = require('../optional-set.js') +const relpath = require('../relpath.js') +const { applyPatchToDir, patchIntegrity } = require('../patch.js') +const { readFile } = require('node:fs/promises') +const retirePath = require('../retire-path.js') +const treeCheck = require('../tree-check.js') +const { defaultLockfileVersion } = require('../shrinkwrap.js') const { saveTypeMap, hasSubKey } = require('../add-rm-pkg-deps.js') - -const Shrinkwrap = require('../shrinkwrap.js') -const { defaultLockfileVersion } = Shrinkwrap +const { IsolatedNode, IsolatedLink } = require('../isolated-classes.js') // 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') @@ -57,7 +50,6 @@ const _checkBins = Symbol.for('checkBins') // 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') @@ -69,30 +61,22 @@ 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 + #omit #retiredPaths = {} #retiredUnchanged = {} - #savePrefix - #shrinkwrapInflated = new Set() #sparseTreeDirs = new Set() #sparseTreeRoots = new Set() + #linkedActualForDiff = null constructor (options) { super(options) @@ -110,10 +94,7 @@ module.exports = cls => class Reifier extends cls { throw er } - const omit = new Set(options.omit || []) - this.#omitDev = omit.has('dev') - this.#omitOptional = omit.has('optional') - this.#omitPeer = omit.has('peer') + this.#omit = new Set(options.omit) // start tracker block this.addTracker('reify') @@ -136,16 +117,33 @@ module.exports = cls => class Reifier extends cls { // 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]() + this.idealTree = await this.createIsolatedTree() + if (this.actualTree) { + this.#linkedActualForDiff = this.#buildLinkedActualForDiff( + this.idealTree, this.actualTree + ) + } } await this[_diffTrees]() - await this[_reifyPackages]() + await this.#reifyPackages() if (linked) { + // The sweep mutates node_modules on disk, so skip it for dry runs and lockfile-only installs (those modes also short-circuit #reifyPackages). + // The sweep itself scopes to in-filter workspaces when a filter is active, so it's safe to run for filtered installs too. + if (!this.options.dryRun && !this.options.packageLockOnly) { + await this.#cleanOrphanedStoreEntries() + } // swap back in the idealTree // so that the lockfile is preserved this.idealTree = oldTree } await this[_saveIdealTree](options) + this.#linkedActualForDiff = null + // clean inert + for (const node of this.idealTree.inventory.values()) { + if (node.inert) { + node.parent = null + } + } // clean up any trash that is still in the tree for (const path of this[_trashList]) { const loc = relpath(this.idealTree.realpath, path) @@ -161,7 +159,7 @@ module.exports = cls => class Reifier extends cls { // 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) { + if (this.diff && this.diff.filterSet.size && !linked) { const reroot = new Set() const { filterSet } = this.diff @@ -241,7 +239,7 @@ module.exports = cls => class Reifier extends cls { this.actualTree = this.idealTree this.idealTree = null - if (!this.options.global) { + if (!this.options.global && !this.options.dryRun) { 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 @@ -272,7 +270,7 @@ module.exports = cls => class Reifier extends cls { return treeCheck(this.actualTree) } - async [_reifyPackages] () { + async #reifyPackages () { // we don't submit the audit report or write to disk on dry runs if (this.options.dryRun) { return @@ -308,8 +306,6 @@ module.exports = cls => class Reifier extends cls { ]], [_rollbackCreateSparseTree, [ _createSparseTree, - _addOmitsToTrashList, - _loadShrinkwrapsAndUpdateTrees, _loadBundlesAndUpdateTrees, _submitQuickAudit, _unpackNewModules, @@ -442,9 +438,14 @@ module.exports = cls => class Reifier extends cls { if (ideal) { filterNodes.push(ideal) } - const actual = this.actualTree.children.get(ws) - if (actual) { - filterNodes.push(actual) + // Skip actual-side filterNodes when using the linked diff wrapper. + // Those nodes have root===actualTree, not root===linkedActualForDiff, and Diff.calculate requires filterNode.root to match actual. + // The ideal filterNode alone is sufficient to scope the workspace diff. + if (!this.#linkedActualForDiff) { + const actual = this.actualTree.children.get(ws) + if (actual) { + filterNodes.push(actual) + } } } } @@ -463,9 +464,9 @@ module.exports = cls => class Reifier extends cls { // find all the nodes that need to change between the actual // and ideal trees. this.diff = Diff.calculate({ - shrinkwrapInflated: this.#shrinkwrapInflated, + omit: this.#omit, filterNodes, - actual: this.actualTree, + actual: this.#linkedActualForDiff || this.actualTree, ideal: this.idealTree, }) @@ -525,7 +526,7 @@ module.exports = cls => class Reifier extends cls { if (er.code === 'ENOENT') { return didMkdirp ? null : mkdir(dirname(to), { recursive: true }).then(() => this[_renamePath](from, to, true)) - } else if (er.code === 'EEXIST') { + } else if (er.code === 'EEXIST' || er.code === 'ENOTEMPTY') { return rm(to, { recursive: true, force: true }).then(() => moveFile(from, to)) } else { throw er @@ -547,43 +548,6 @@ module.exports = cls => class Reifier extends cls { }) } - // 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 @@ -625,6 +589,7 @@ module.exports = cls => class Reifier extends cls { // 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 + /* istanbul ignore next -- pre-existing: mkdir returns undefined when dir exists, covered in reify tests but lost in aggregate coverage merge */ if (made) { this.#sparseTreeRoots.add(made) } @@ -650,67 +615,17 @@ module.exports = cls => class Reifier extends cls { .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 @@ -792,38 +707,217 @@ module.exports = cls => class Reifier extends cls { ...this.options, resolved: node.resolved, integrity: node.integrity, + // A node counts as "root" for allow-* enforcement if it satisfies at least one valid dependency edge declared by the project root or a workspace. + // node.parent is unsafe here: after hoisting, transitive packages can have the project root as their tree parent. + // In the linked strategy the store node has no edgesIn, so isolated-reifier precomputes isRootDependency from the source node's edges. + _isRoot: node.isRootDependency || [...node.edgesIn].some(e => + e.valid && (e.from?.isProjectRoot || e.from?.isWorkspace) + ), + // pacote's npa re-parses our `name@URL` spec as type=remote, so allowRemote would mis-fire on registry tarballs. + // Override only when we can prove the URL is registry-mediated; see #isRegistryResolvedTarball. + ...(this.#isRegistryResolvedTarball(node) ? { allowRemote: 'all' } : {}), }) // 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')) + const { content: pkg } = await PackageJson.normalize(node.path) node.package.scripts = pkg.scripts } + await this.#applyPatch(node) return } // node.isLink + + // Tree-only Link: present in the tree for diff/filter participation, never materialized on disk. + if (node.isUndeclaredWorkspaceLink) { + return + } + await rm(node.path, { recursive: true, force: true }) // symlink const dir = dirname(node.path) const target = node.realpath - const rel = relative(dir, target) + + let rel + if (node.resolved?.startsWith('file:')) { + rel = this.#calculateRelativePath(node, dir, target, nm) + } else { + rel = relative(dir, target) + } + await mkdir(dir, { recursive: true }) return symlink(rel, node.path, 'junction') } + // apply a registered patch to a freshly extracted node, after extract and before rebuild + async #applyPatch (node) { + if (!node.patched) { + return + } + const { path: patchPath, integrity } = node.patched + + // validate the patch file here too, since reify can run on an ideal tree that skipped resolvePatchedDependencies + let contents + try { + contents = await readFile(resolve(this.path, patchPath)) + } catch { + throw Object.assign( + new Error(`patch file not found: ${patchPath}`), + { code: 'EPATCHNOTFOUND', path: patchPath, node: node.name } + ) + } + if (patchIntegrity(contents) !== integrity) { + throw Object.assign( + new Error(`patch file ${patchPath} does not match the recorded integrity`), + { code: 'EPATCHINTEGRITY', path: patchPath, node: node.name } + ) + } + + try { + await applyPatchToDir({ patch: contents, cwd: node.path }) + } catch (er) { + if (this.options.ignorePatchFailures) { + // the linked side-store keys a package by its patch, so an unpatched package cannot be represented at a patched key and would be trusted on later installs + if (node.isInStore) { + throw Object.assign( + new Error(`Cannot skip the failed patch for ${node.name} under install-strategy=linked. ` + + `Fix the patch or install with a different strategy.`), + { code: 'EPATCHFAILED', path: patchPath, node: node.name } + ) + } + log.warn('patch', `failed to apply ${patchPath} to ${node.name}: ${er.message}`) + // the patch was not applied, so do not record it in the lockfile + // the lockfile and package.json now disagree, so warn that npm ci will reject the tree + log.warn('patch', `${node.name} was installed unpatched; package.json still declares this patch, so the lockfile is out of sync and \`npm ci\` will fail until the patch is fixed or its patchedDependencies entry is removed`) + node.patched = null + return + } + throw er + } + } + // 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(() => { + return (node.optional ? p.catch((er) => { + // a declared patch must apply or fail loudly, even on an optional dep + if (typeof er?.code === 'string' && er.code.startsWith('EPATCH')) { + throw er + } const set = optionalSet(node) - for (node of set) { + for (const node of set) { log.verbose('reify', 'failed optional dependency', node.path) + node.inert = true this[_addNodeToTrashList](node) } }) : p).then(() => node) } + #calculateRelativePath (node, dir, target) { + // Check if the node is affected by a root override + let hasRootOverride = [...node.edgesIn].some(edge => edge.from.isRoot && edge.overrides) + // If not set via edges, see if the root package.json explicitly lists an override + if (!hasRootOverride && node.root) { + const rootPackage = node.root.target + hasRootOverride = !!(rootPackage && + rootPackage.package.overrides && + rootPackage.package.overrides[node.name]) + } + if (!hasRootOverride) { + return relative(dir, target) + } + // If an override is detected, attempt to retrieve the override spec from the root package.json + const overrideSpec = node.root?.target?.package?.overrides?.[node.name] + if (typeof overrideSpec === 'string' && overrideSpec.startsWith('file:')) { + const overridePath = overrideSpec.replace(/^file:/, '') + const rootDir = node.root.target.path + return relative(dir, resolve(rootDir, overridePath)) + } + + // Fallback: derive the file path from node.resolved in a platform-agnostic way + const filePath = node.resolved.replace(/^file:/, '') + return join(filePath) + } + + // Build a flat actual tree wrapper for linked installs so the diff can correctly match store entries that already exist on disk. + // The proxy tree from createIsolatedTree() is flat (all children on root), but loadActual() produces a nested tree where store entries are deep link targets. + // This wrapper surfaces them at the root level for comparison. + #buildLinkedActualForDiff (idealTree, actualTree) { + // Combined Map keyed by path (how allChildren() in diff.js keys) + const combined = new Map() + + // Create synthetic actual entries for ALL ideal children that exist on disk. + // The isolated ideal tree is flat (all entries as root children), but loadActual() produces a nested tree where workspace deps are under fsChildren and store entries are deep link targets. + // Synthetic entries ensure the diff compares matching resolved/integrity values (e.g. workspace links have resolved=undefined in the ideal tree but resolved="file:../packages/..." in the actual tree). + for (const child of idealTree.children.values()) { + if (combined.has(child.path) || !existsSync(child.path)) { + continue + } + // Skip store links whose ideal realpath doesn't exist on disk yet — the store hash changed and the symlink needs recreating via ADD. + if (child.isLink && child.resolved?.startsWith('file:.store/') && !existsSync(child.realpath)) { + continue + } + let entry + if (child.isLink) { + entry = new IsolatedLink(child) + } else { + entry = new IsolatedNode(child) + } + if (child.isLink && combined.has(child.realpath)) { + entry.target = combined.get(child.realpath) + } + combined.set(child.path, entry) + } + + // Proxy .get(name) to original actual tree for filterNodes compatibility + // (scoped workspace installs use .get(name), allChildren uses .values()) + const origGet = actualTree.children.get.bind(actualTree.children) + const combinedGet = combined.get.bind(combined) + /* istanbul ignore next -- only reached during scoped workspace installs */ + combined.get = (key) => combinedGet(key) || origGet(key) + + let wrapper + /* istanbul ignore next - untested! */ + if (actualTree.isLink) { + wrapper = new IsolatedLink(actualTree) + } else { + wrapper = new IsolatedNode(actualTree) + } + wrapper.root = wrapper + wrapper.binPaths = actualTree.binPaths + wrapper.children = combined + wrapper.edgesOut = actualTree.edgesOut + // Use empty fsChildren so that allChildren() only picks up entries from the combined map. + // The actual fsChildren have real children with different resolved values (e.g. file:../../../node_modules/.store/... vs file:.store/...) that would overwrite our synthetic entries in allChildren(). + wrapper.fsChildren = new Set() + wrapper.integrity = actualTree.integrity + wrapper.inventory = actualTree.inventory + + return wrapper + } + + // When extracting a registry-resolved package, the spec we hand to pacote is name@URL. + // pacote re-parses that with npa and gets spec.type === 'remote', so without an override the allow-remote gate would fire on every registry tarball (both =none and =root mis-fire). + // Returns true only when we are confident this is a registry-mediated install. + #isRegistryResolvedTarball (node) { + if (!node.resolved || !node.isRegistryDependency) { + return false + } + try { + // Match the effective fetch URL, not the raw lockfile value. + // #registryResolved applies replace-registry-host, rewriting a public-registry pin to the configured proxy/mirror so it matches. + const resolvedURL = new URL(this.#registryResolved(node.resolved)) + // pickRegistry only consults spec.scope, so a bare-name (tag) parse is sufficient and avoids a node.version dependency. + const registry = new URL(pickRegistry(npa(node.name), this.options)) + const registryPath = registry.pathname.replace(/\/?$/, '/') + return resolvedURL.origin === registry.origin && + (registryPath === '/' || resolvedURL.pathname.startsWith(registryPath)) + } catch { + return false + } + } + #registryResolved (resolved) { // the default registry url is a magic value meaning "the currently // configured registry". @@ -833,21 +927,42 @@ module.exports = cls => class Reifier extends cls { // ${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) + try { + const resolvedURL = hgi.parseUrl(resolved) + + if ((this.options.replaceRegistryHost === resolvedURL.hostname) || + this.options.replaceRegistryHost === 'always') { + const registryURL = new URL(this.registry) + + // Replace the host with the registry host while keeping the path intact + resolvedURL.hostname = registryURL.hostname + resolvedURL.port = registryURL.port + resolvedURL.protocol = registryURL.protocol + + // Make sure we don't double-include the path if it's already there + const registryPath = registryURL.pathname.replace(/\/$/, '') + + if (registryPath && registryPath !== '/') { + // Check if the resolved pathname already starts with the registry path + // We need to ensure it's a proper path prefix, not just a string prefix + // e.g., registry path '/npm' should not match '/npm-run-path' + const hasRegistryPath = resolvedURL.pathname === registryPath || + resolvedURL.pathname.startsWith(registryPath + '/') + + if (!hasRegistryPath) { + // Since hostname is changed, we need to ensure the registry path is included + resolvedURL.pathname = registryPath + resolvedURL.pathname + } + } - if (!resolvedURL) { + return resolvedURL.toString() + } + return resolved + } catch (e) { // 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 + return undefined } - - 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 @@ -1088,7 +1203,6 @@ module.exports = cls => class Reifier extends cls { 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. @@ -1098,8 +1212,6 @@ module.exports = cls => class Reifier extends cls { !node.isRoot && // already unpacked to read bundle !bd && - // already unpacked to read sw - !sw && // already unpacked by another dep's bundle (bundleMissing || !node.inDepBundle) @@ -1230,7 +1342,7 @@ module.exports = cls => class Reifier extends cls { // 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 + const linkedFromRoot = (node.parent === tree && !node.inert) || node.target.fsTop === tree if (node.isLink && linkedFromRoot) { nodes.push(node) } @@ -1261,6 +1373,223 @@ module.exports = cls => class Reifier extends cls { timeEnd() } + // After a linked install, scan node_modules/.store/ and remove any directories that are not referenced by the current ideal tree. + // Store entries become orphaned when dependencies are updated or removed, because the diff never sees the old store keys. + // Then sweep the top-level node_modules/ for orphaned symlinks (e.g. an uninstalled dep whose store entry was just removed) so we don't leave dangling links. + async #cleanOrphanedStoreEntries () { + const nmDir = resolve(this.path, 'node_modules') + const storeDir = resolve(nmDir, '.store') + + // Enumerate on-disk store entries as full keys, descending one level into each @scope directory because scoped keys nest as .store/@scope/pkg@version-hash. + let entries + try { + const topLevel = await readdir(storeDir, { withFileTypes: true }) + entries = [] + for (const ent of topLevel) { + if (ent.name.startsWith('@')) { + let scoped + try { + scoped = await readdir(resolve(storeDir, ent.name)) + } catch { + /* istanbul ignore next -- readdir of an entry we just listed should not fail */ + continue + } + for (const name of scoped) { + entries.push(`${ent.name}/${name}`) + } + } else { + entries.push(ent.name) + } + } + } catch { + entries = null + } + + // Collect valid store keys and valid top-level links per node_modules directory. + // Store entries have location node_modules/.store/{key}/node_modules/{pkg}. + // Top-level links have location {prefix}/node_modules/{pkg} or {prefix}/node_modules/@scope/{pkg}, where {prefix} is empty for the root project and the workspace's localLocation for workspace deps. + // Locations are normalized to forward slashes here because IsolatedNode/IsolatedLink locations are built with path.join, which uses backslashes on Windows. + const validKeys = new Set() + const nmDirs = new Map() + const NM_PREFIX = 'node_modules/' + const STORE_MARKER = '/.store/' + for (const child of this.idealTree.children.values()) { + const loc = child.location.replace(/\\/g, '/') + if (child.isInStore) { + // Store location is node_modules/.store/{key}/node_modules/{pkg}. + // For a scoped package the key is @scope/pkg@version-hash, which spans two path segments, so reconstruct both instead of taking only the scope. + const parts = loc.split('/') + const key = parts[2].startsWith('@') ? `${parts[2]}/${parts[3]}` : parts[2] + validKeys.add(key) + continue + } + if (!child.isLink) { + continue + } + // Tree-only Links never exist on disk; skipping them lets the sweep remove any stale self-link left by an older npm version. + if (child.isUndeclaredWorkspaceLink) { + continue + } + const nmIdx = loc.lastIndexOf(NM_PREFIX) + if (nmIdx === -1 || loc.includes(STORE_MARKER)) { + continue + } + const prefix = loc.slice(0, nmIdx) + const dir = resolve(this.path, prefix, 'node_modules') + const rest = loc.slice(nmIdx + NM_PREFIX.length) + let entry + if (rest.startsWith('@')) { + const [scope, name] = rest.split('/') + entry = `${scope}${sep}${name}` + } else { + entry = rest.split('/')[0] + } + let set = nmDirs.get(dir) + if (!set) { + set = new Set() + nmDirs.set(dir, set) + } + set.add(entry) + } + + // Determine which node_modules directories to sweep. + // For an unfiltered install, sweep the project root and every workspace's node_modules even if no top-level links remain (e.g. last dep was just uninstalled). + // For a filtered install (npm install -w ), restrict the sweep to the in-scope workspaces so out-of-scope workspaces are left untouched, mirroring what the diff would do. + // When --include-workspace-root is set, the filter scope pulls in root deps too, so the root node_modules is included in the sweep. + const filteredNames = this.options.workspaces + const isFiltered = Array.isArray(filteredNames) && filteredNames.length > 0 + if (isFiltered) { + const allowedDirs = new Set() + for (const ws of this.idealTree.fsChildren) { + if (filteredNames.includes(ws.packageName) || filteredNames.includes(ws.name)) { + allowedDirs.add(resolve(ws.path, 'node_modules')) + } + } + if (this.options.includeWorkspaceRoot) { + allowedDirs.add(nmDir) + } + for (const dir of [...nmDirs.keys()]) { + if (!allowedDirs.has(dir)) { + nmDirs.delete(dir) + } + } + for (const dir of allowedDirs) { + if (!nmDirs.has(dir)) { + nmDirs.set(dir, new Set()) + } + } + } else { + if (!nmDirs.has(nmDir)) { + nmDirs.set(nmDir, new Set()) + } + for (const ws of this.idealTree.fsChildren) { + const wsNmDir = resolve(ws.path, 'node_modules') + if (!nmDirs.has(wsNmDir)) { + nmDirs.set(wsNmDir, new Set()) + } + } + } + + if (entries) { + const orphaned = entries.filter(e => !validKeys.has(e)) + if (orphaned.length) { + log.silly('reify', 'cleaning orphaned store entries', orphaned) + await promiseAllRejectLate( + orphaned.map(e => + rm(resolve(storeDir, e), { recursive: true, force: true }) + .catch(/* istanbul ignore next -- rm with force rarely fails */ + er => log.warn('cleanup', `Failed to remove orphaned store entry ${e}`, er)) + ) + ) + // Removing the last scoped orphan under a scope leaves an empty @scope directory behind, so prune any scope directory that is now empty. + const scopes = new Set( + orphaned.filter(e => e.startsWith('@')).map(e => e.split('/')[0]) + ) + await promiseAllRejectLate( + [...scopes].map(async scope => { + const scopeDir = resolve(storeDir, scope) + try { + const remaining = await readdir(scopeDir) + if (!remaining.length) { + await rm(scopeDir, { recursive: true, force: true }) + } + } catch { + /* istanbul ignore next -- readdir of a scope dir we just listed should not fail */ + } + }) + ) + } + } + + for (const [dir, valid] of nmDirs) { + await this.#cleanOrphanedTopLevelLinks(dir, valid) + } + } + + // Remove node_modules/ entries that aren't represented in the ideal tree. + // Run for the project root and each workspace's node_modules. + // The linked diff path can't see these because #buildLinkedActualForDiff derives the actual tree from the ideal, so removed deps are never compared. + // Only symlinks whose target resolves inside the project root are removed — that covers store links (node_modules/.store/...) and workspace self-links (e.g. node_modules/ -> ../packages/) that npm itself created. + // Symlinks pointing outside the project (e.g. `npm link foo` without --save targeting the global prefix, or hand-made `ln -s` to an external path) and real directories are preserved. + async #cleanOrphanedTopLevelLinks (nmDir, validTopLevel) { + const projectPrefix = resolve(this.path) + sep + let dirents + try { + dirents = await readdir(nmDir, { withFileTypes: true }) + } catch { + return + } + + const isOurOrphan = async (linkPath) => { + let target + try { + target = await readlink(linkPath) + } catch { + /* istanbul ignore next -- readlink of an entry we just listed as a symlink should not fail */ + return false + } + return resolve(dirname(linkPath), target).startsWith(projectPrefix) + } + + const orphaned = [] + for (const ent of dirents) { + // skip npm-managed entries (.bin, .store, .package-lock.json, etc) + if (ent.name.startsWith('.')) { + continue + } + if (ent.name.startsWith('@')) { + let scoped + try { + scoped = await readdir(resolve(nmDir, ent.name), { withFileTypes: true }) + } catch { + /* istanbul ignore next -- readdir of an entry we just listed should not fail */ + continue + } + for (const pkgEnt of scoped) { + const key = `${ent.name}${sep}${pkgEnt.name}` + if (!validTopLevel.has(key) && pkgEnt.isSymbolicLink() && await isOurOrphan(resolve(nmDir, key))) { + orphaned.push(key) + } + } + } else if (!validTopLevel.has(ent.name) && ent.isSymbolicLink() && await isOurOrphan(resolve(nmDir, ent.name))) { + orphaned.push(ent.name) + } + } + + if (!orphaned.length) { + return + } + + log.silly('reify', 'cleaning orphaned top-level links', orphaned) + await promiseAllRejectLate( + orphaned.map(name => + rm(resolve(nmDir, name), { recursive: true, force: true }) + .catch(/* istanbul ignore next -- rm with force rarely fails */ + er => log.warn('cleanup', `Failed to remove orphaned link ${name}`, er)) + ) + ) + } + // 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) { @@ -1341,10 +1670,10 @@ module.exports = cls => class Reifier extends cls { 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 + // save the git+https url if it has auth; otherwise, shortcut const h = req.hosted const opt = { noCommittish: false } - if (h.https && h.auth) { + if (h.https && (h.auth || h.default === 'https')) { newSpec = `git+${h.https(opt)}` } else { newSpec = h.shortcut(opt) @@ -1364,7 +1693,7 @@ module.exports = cls => class Reifier extends cls { // 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') + const rel = relpath(addTree.realpath, p) newSpec = `file:${rel}` } } else { @@ -1374,8 +1703,7 @@ module.exports = cls => class Reifier extends cls { 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 + // PackageJson.normalize 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] } @@ -1411,12 +1739,12 @@ module.exports = cls => class Reifier extends cls { // 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, + // e.g: should return true if for a given and 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)) { + if (subset(edge.spec, node.version)) { return false } } catch { @@ -1500,6 +1828,8 @@ module.exports = cls => class Reifier extends cls { // field so defaulting this to an empty array would add that field to // every package.json file. bundleDependencies, + // resolvePatchedDependencies drops entries orphaned by uninstall; persist that removal + patchedDependencies, } = tree.package pkgJson.update({ @@ -1508,6 +1838,7 @@ module.exports = cls => class Reifier extends cls { optionalDependencies, peerDependencies, bundleDependencies, + patchedDependencies, }) await pkgJson.save() } @@ -1515,7 +1846,7 @@ module.exports = cls => class Reifier extends cls { // 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]) { + if (this.options.usePackageLock) { // preserve indentation, if possible let format = this.idealTree.package[Symbol.for('indent')] if (format === undefined) { diff --git a/workspaces/arborist/lib/audit-report.js b/workspaces/arborist/lib/audit-report.js index f7700ce9119de..de2e092a96ac1 100644 --- a/workspaces/arborist/lib/audit-report.js +++ b/workspaces/arborist/lib/audit-report.js @@ -1,5 +1,4 @@ // 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') @@ -7,17 +6,17 @@ const pickManifest = require('npm-pick-manifest') const Vuln = require('./vuln.js') const Calculator = require('@npmcli/metavuln-calculator') +const { isReleaseAgeExcluded } = require('./release-age-exclude.js') -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 fetch = require('npm-registry-fetch') +const npmFetch = require('npm-registry-fetch') class AuditReport extends Map { + #omit + error = null + topVulns = new Map() + static load (tree, opts) { return new AuditReport(tree, opts).run() } @@ -91,22 +90,18 @@ class AuditReport extends Map { constructor (tree, opts = {}) { super() - const { omit } = opts - this[_omit] = new Set(omit || []) - this.topVulns = new Map() - + this.#omit = new Set(opts.omit || []) 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]() + this.report = await this.#getReport() log.silly('audit report', this.report) if (this.report) { - await this[_init]() + await this.#init() } return this } @@ -116,7 +111,7 @@ class AuditReport extends Map { return !!(vuln && vuln.isVulnerable(node)) } - async [_init] () { + async #init () { const timeEnd = time.start('auditReport:init') const promises = [] @@ -148,7 +143,7 @@ class AuditReport extends Map { if (!seen.has(k)) { const p = [] for (const node of this.tree.inventory.query('packageName', name)) { - if (!shouldAudit(node, this[_omit], this.filterSet)) { + if (!this.shouldAudit(node)) { continue } @@ -171,7 +166,20 @@ class AuditReport extends Map { vuln.nodes.add(node) for (const { from: dep, spec } of node.edgesIn) { if (dep.isTop && !vuln.topNodes.has(dep)) { - this[_checkTopNode](dep, vuln, spec) + vuln.fixAvailable = this.#fixAvailable(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(dep) + } else { + // An in-range fix exists, but a `min-release-age`/`before` + // window may put the patched version out of reach, leaving the + // vulnerable version installed. + vuln.fixBlockedByReleaseAge = this.#fixBlockedByReleaseAge(vuln, spec) + } } else { // calculate a metavuln, if necessary const calc = this.calculator.calculate(dep.packageName, advisory) @@ -214,33 +222,14 @@ class AuditReport extends Map { 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 - + // given the spec, see if there is a fix available at all, and note whether or not it's a semver major fix or not (i.e. will need --force) + #fixAvailable (vuln, spec) { + // TODO we return true, false, OR an object here. this is probably a bad pattern. 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. + // even if we HAVE a packument, if we're looking for it somewhere other than the registry and we have something vulnerable then we're stuck with it. const specObj = npa(spec) if (!specObj.registry) { return false @@ -250,15 +239,13 @@ class AuditReport extends Map { 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. + // 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 note if that is a semver major bump. try { const { _isSemVerMajor: isSemVerMajor, version, name, - } = pickManifest(paku, spec, { + } = pickManifest(vuln.packument, spec, { ...this.options, before: null, avoid: vuln.range, @@ -270,38 +257,58 @@ class AuditReport extends Map { } } - set () { - throw new Error('do not call AuditReport.set() directly') - } + // A fix that `#fixAvailable` reports as installable in-range can still be + // unreachable when a release-age window (`before` / `min-release-age`) is set, + // because the patched version was published after the cutoff. `npm audit fix` + // then resolves back to a version that is still vulnerable, so detect that + // here and let callers warn about it. Only meaningful when an in-range fix + // exists (fixAvailable === true). Returns the blocked fix as + // `{ version, before }`, or `false` when nothing is blocked. + #fixBlockedByReleaseAge (vuln, spec) { + const { before, minReleaseAgeExclude } = this.options + // No window, or this package is explicitly exempt from it. + if (!before || isReleaseAgeExcluded(vuln.name, minReleaseAgeExclude)) { + return false + } - // convert a quick-audit into a bulk advisory listing - static auditToBulk (report) { - if (!report.advisories) { - // tack on the report json where the response body would go - throw Object.assign(new Error('Invalid advisory report'), { - body: JSON.stringify(report), - }) + // For `npm:` aliases the fix resolves against the alias target, so feed + // pickManifest the underlying range rather than the alias spec (which it + // rejects). Mirrors `#fixAvailable`. + const specObj = npa(spec) + if (specObj.subSpec) { + spec = specObj.subSpec.rawSpec } - const bulk = {} - const { advisories } = report - for (const advisory of Object.values(advisories)) { - const { - id, - url, - title, - severity = 'high', - vulnerable_versions = '*', - module_name: name, - } = advisory - bulk[name] = bulk[name] || [] - bulk[name].push({ id, url, title, severity, vulnerable_versions }) + // The version that would be installed if the window were lifted. + const { version } = pickManifest(vuln.packument, spec, { + ...this.options, + before: null, + avoid: vuln.range, + }) + + // What resolution can actually reach within the window. This mirrors how + // `build-ideal-tree` re-resolves the edge (non-strict avoid + `before`). + let windowed + try { + windowed = pickManifest(vuln.packument, spec, { + ...this.options, + avoid: vuln.range, + }) + } catch { + // Nothing is old enough to install at all: the fix is blocked. + return { version, before } } - return bulk + // `_shouldAvoid` means the best version available within the window is still + // in the vulnerable range, so the only non-vulnerable fix is too new. + return windowed._shouldAvoid ? { version, before } : false } - async [_getReport] () { + 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 @@ -309,39 +316,24 @@ class AuditReport extends Map { const timeEnd = time.start('auditReport:getReport') try { - try { - // first try the super fast bulk advisory listing - 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 body = this.prepareBulkData() + log.silly('audit', 'bulk request', body) - const res = await fetch('/-/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.silly('audit', 'bulk request failed', String(er.body)) - // that failed, try the quick audit endpoint - const body = prepareData(this.tree, this.options) - const res = await fetch('/-/npm/v1/security/audits/quick', { - ...this.options, - registry: this.options.auditRegistry || this.options.registry, - method: 'POST', - gzip: true, - body, - }) - return AuditReport.auditToBulk(await res.json()) + // 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)) @@ -351,64 +343,40 @@ class AuditReport extends Map { 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) + // return true if we should audit this one + shouldAudit (node) { + if ( + !node.version || + node.isRoot || + node.isLink || + node.linksIn?.size > 0 || + (this.filterSet && this.filterSet?.size !== 0 && !this.filterSet?.has(node)) + ) { + return false } - if (set.size) { - payload[name] = [...set] + if (this.#omit.size === 0) { + return true } + return !node.shouldOmit(this.#omit) } - return payload -} -const prepareData = (tree, opts) => { - const { npmVersion: npm_version } = opts - const node_version = process.version - const { platform, arch } = process - const { NODE_ENV: node_env } = process.env - const data = tree.meta.commit() - // the legacy audit endpoint doesn't support any kind of pre-filtering - // we just have to get the advisories and skip over them in the report - return { - name: data.name, - version: data.version, - requires: { - ...(tree.package.devDependencies || {}), - ...(tree.package.peerDependencies || {}), - ...(tree.package.optionalDependencies || {}), - ...(tree.package.dependencies || {}), - }, - dependencies: data.dependencies, - metadata: { - node_version, - npm_version, - platform, - arch, - node_env, - }, + prepareBulkData () { + const payload = {} + for (const name of this.tree.inventory.query('packageName')) { + const set = new Set() + for (const node of this.tree.inventory.query('packageName', name)) { + if (!this.shouldAudit(node)) { + continue + } + + set.add(node.version) + } + if (set.size) { + payload[name] = [...set] + } + } + return payload } } diff --git a/workspaces/arborist/lib/calc-dep-flags.js b/workspaces/arborist/lib/calc-dep-flags.js index bcd30d0f493c7..5f2484858094d 100644 --- a/workspaces/arborist/lib/calc-dep-flags.js +++ b/workspaces/arborist/lib/calc-dep-flags.js @@ -1,125 +1,102 @@ -const { depth } = require('treeverse') - +// Dep flag (dev, peer, etc.) calculation requires default or reset flags. +// Flags are true by default and are unset to false as we walk deps. +// We iterate outward edges looking for dep flags that can +// be unset based on the current nodes flags and edge type. +// Examples: +// - a non-optional node with a non-optional edge out, the edge node should not be optional +// - a non-peer node with a non-peer edge out, the edge node should not be peer +// If a node is changed, we add to the queue and continue until no more changes. +// Flags that remain after all this unsetting should be valid. +// Examples: +// - a node still flagged optional must only be reachable via optional edges +// - a node still flagged peer must only be reachable via peer edges const calcDepFlags = (tree, resetRoot = true) => { if (resetRoot) { - tree.dev = false - tree.optional = false - tree.devOptional = false - tree.peer = false + tree.unsetDepFlags() } - 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 + const seen = new Set() + const queue = [tree] - // 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 + let node + while (node = queue.pop()) { + seen.add(node) - if (unsetPeer) { - unsetFlag(to, 'peer') + // Unset extraneous from all parents to avoid removal of children. + if (!node.extraneous) { + for (let n = node.resolveParent; n?.extraneous; n = n.resolveParent) { + n.extraneous = false + } } - if (unsetDevOpt) { - unsetFlag(to, 'devOptional') + // 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) { + continue + } + node.target.dev = node.dev + node.target.optional = node.optional + node.target.devOptional = node.devOptional + node.target.peer = node.peer + node.target.extraneous = node.extraneous + queue.push(node.target) + continue } - if (unsetDev) { - unsetFlag(to, 'dev') + for (const { peer, optional, dev, to } of node.edgesOut.values()) { + // if the dep is missing, then its flags are already maximally unset + if (!to) { + continue + } + + let changed = false + + // only optional peer dependencies should stay extraneous + if (to.extraneous && !node.extraneous && !(peer && optional)) { + to.extraneous = false + changed = true + } + + if (to.dev && !node.dev && !dev) { + to.dev = false + changed = true + } + + if (to.optional && !node.optional && !optional) { + to.optional = false + changed = true + } + + // devOptional is the *overlap* of the dev and optional tree. + // A node may be depended on by separate dev and optional nodes. + // It SHOULD NOT be removed when pruning dev OR optional. + // It SHOULD be removed when pruning dev AND optional. + // We only unset here if a node is not dev AND not optional because + // if we did unset, it would prevent any overlap deeper in the tree. + // We correct this later by removing if dev OR optional is set. + if (to.devOptional && !node.devOptional && !node.dev && !node.optional && !dev && !optional) { + to.devOptional = false + changed = true + } + + if (to.peer && !node.peer && !peer) { + to.peer = false + changed = true + } + + if (changed) { + queue.push(to) + } } - - 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 - }, - }) + // Remove incorrect devOptional flags now that we have walked all deps. + seen.delete(tree) + for (const node of seen.values()) { + if (node.devOptional && (node.dev || node.optional)) { + node.devOptional = false + } } } diff --git a/workspaces/arborist/lib/consistent-resolve.js b/workspaces/arborist/lib/consistent-resolve.js index 7c988048057c7..20b119ac9ee52 100644 --- a/workspaces/arborist/lib/consistent-resolve.js +++ b/workspaces/arborist/lib/consistent-resolve.js @@ -20,14 +20,13 @@ const consistentResolve = (resolved, fromPath, toPath, relPaths = false) => { 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:${relpath(toPath, fetchSpec)}` } - return `file:${cleanFetchSpec}` + return `file:${fetchSpec}` } if (hosted) { - return `git+${hosted.auth ? hosted.https(hostedOpt) : hosted.sshurl(hostedOpt)}` + return `git+${(hosted.auth || hosted.default === 'https') ? hosted.https(hostedOpt) : hosted.sshurl(hostedOpt)}` } if (type === 'git') { return saveSpec diff --git a/workspaces/arborist/lib/dep-valid.js b/workspaces/arborist/lib/dep-valid.js index e80310d9663a9..db93c2980852a 100644 --- a/workspaces/arborist/lib/dep-valid.js +++ b/workspaces/arborist/lib/dep-valid.js @@ -9,6 +9,27 @@ const npa = require('npm-package-arg') const { relative } = require('node:path') const fromPath = require('./from-path.js') +// A named ref (tag or branch) resolves to a commit hash, so look up the +// committish recorded for this edge in the lockfile to detect spec changes. +const lockedGitCommittish = (child, requestor) => { + const lock = requestor.root?.meta?.data?.packages?.[requestor.location] + const spec = lock && ( + lock.dependencies?.[child.name] || + lock.optionalDependencies?.[child.name] || + lock.devDependencies?.[child.name] || + lock.peerDependencies?.[child.name] + ) + if (!spec) { + return null + } + try { + const parsed = npa.resolve(child.name, spec, requestor.realpath) + return parsed.type === 'git' ? parsed.gitCommittish || '' : null + } catch { + return null + } +} + 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 @@ -82,7 +103,7 @@ const depValid = (child, requested, requestor) => { const resRepo = npa(child.resolved || '') const resHost = resRepo.hosted const reqHost = requested.hosted - const reqCommit = /^[a-fA-F0-9]{40}$/.test(requested.gitCommittish || '') + const reqCommit = /^[a-fA-F0-9]{40,64}$/.test(requested.gitCommittish || '') const nc = { noCommittish: !reqCommit } if (!resHost) { if (resRepo.fetchSpec !== requested.fetchSpec) { @@ -94,6 +115,14 @@ const depValid = (child, requested, requestor) => { } } if (!requested.gitRange) { + // a named ref can't be verified against the resolved commit offline, + // so re-resolve if it differs from the committish in the lockfile + if (!reqCommit) { + const locked = lockedGitCommittish(child, requestor) + if (locked !== null && locked !== (requested.gitCommittish || '')) { + return false + } + } return true } return semver.satisfies(child.package.version, requested.gitRange, { @@ -101,7 +130,7 @@ const depValid = (child, requested, requestor) => { }) } - default: // unpossible, just being cautious + default: // impossible, just being cautious break } diff --git a/workspaces/arborist/lib/diff.js b/workspaces/arborist/lib/diff.js index fb94407bb0166..704dc7bafc42b 100644 --- a/workspaces/arborist/lib/diff.js +++ b/workspaces/arborist/lib/diff.js @@ -11,9 +11,9 @@ const { existsSync } = require('node:fs') const ssri = require('ssri') class Diff { - constructor ({ actual, ideal, filterSet, shrinkwrapInflated }) { + constructor ({ actual, ideal, filterSet, omit }) { + this.omit = omit this.filterSet = filterSet - this.shrinkwrapInflated = shrinkwrapInflated this.children = [] this.actual = actual this.ideal = ideal @@ -35,7 +35,7 @@ class Diff { actual, ideal, filterNodes = [], - shrinkwrapInflated = new Set(), + omit = new Set(), }) { // if there's a filterNode, then: // - get the path from the root to the filterNode. The root or @@ -69,6 +69,7 @@ class Diff { tree: filterNode, visit: node => filterSet.add(node), getChildren: node => { + const orig = node node = node.target const loc = node.location const idealNode = ideal.inventory.get(loc) @@ -85,7 +86,12 @@ class Diff { } } - return ideals.concat(actuals) + const result = ideals.concat(actuals) + // Include link targets so store entries end up in filterSet + if (orig.isLink) { + result.push(node) + } + return result }, }) } @@ -94,7 +100,7 @@ class Diff { } return depth({ - tree: new Diff({ actual, ideal, filterSet, shrinkwrapInflated }), + tree: new Diff({ actual, ideal, filterSet, omit }), getChildren, leave, }) @@ -124,6 +130,16 @@ const getAction = ({ actual, ideal }) => { return 'CHANGE' } + // a change in patch state requires re-extracting and re-applying + if ((ideal.patched?.integrity || null) !== (actual.patched?.integrity || null)) { + return 'CHANGE' + } + + // a node whose patch was just removed must be re-extracted to revert the patched files + if (ideal.patchRemoved) { + return 'CHANGE' + } + const binsExist = ideal.binPaths.every((path) => existsSync(path)) // top nodes, links, and git deps won't have integrity, but do have resolved @@ -183,25 +199,16 @@ const getChildren = diff => { unchanged, removed, filterSet, - shrinkwrapInflated, + omit, } = 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. + // included in the package contents, or part of some other project. + // 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) @@ -213,7 +220,7 @@ const getChildren = diff => { unchanged, removed, filterSet, - shrinkwrapInflated, + omit, }) } @@ -231,21 +238,33 @@ const diffNode = ({ unchanged, removed, filterSet, - shrinkwrapInflated, + omit, }) => { if (filterSet.size && !(filterSet.has(ideal) || filterSet.has(actual))) { return } + if (ideal?.shouldOmit?.(omit)) { + ideal.inert = true + } + + // Treat inert nodes as undefined for the purposes of diffing. + if (ideal?.inert) { + ideal = undefined + } + if (!actual && !ideal) { + 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) { if (action === 'REMOVE') { removed.push(actual) } - children.push(new Diff({ actual, ideal, filterSet, shrinkwrapInflated })) + children.push(new Diff({ actual, ideal, filterSet, omit })) } else { unchanged.push(ideal) // !*! Weird dirty hack warning !*! @@ -284,7 +303,7 @@ const diffNode = ({ unchanged, removed, filterSet, - shrinkwrapInflated, + omit, })) } } diff --git a/workspaces/arborist/lib/edge.js b/workspaces/arborist/lib/edge.js index 77ba196e68eeb..1ed2446c8090a 100644 --- a/workspaces/arborist/lib/edge.js +++ b/workspaces/arborist/lib/edge.js @@ -4,6 +4,7 @@ const util = require('node:util') const npa = require('npm-package-arg') const depValid = require('./dep-valid.js') +const OverrideSet = require('./override-set.js') class ArboristEdge { constructor (edge) { @@ -103,16 +104,40 @@ class Edge { } satisfiedBy (node) { - if (node.name !== this.#name) { + if (node.name !== this.#name || !this.#from) { return false } // NOTE: this condition means we explicitly do not support overriding - // bundled or shrinkwrapped dependencies - if (node.hasShrinkwrap || node.inShrinkwrap || node.inBundle) { + // bundled dependencies + if (node.inDepBundle) { return depValid(node, this.rawSpec, this.#accept, this.#from) } - return depValid(node, this.spec, this.#accept, this.#from) + + // If there's no override we just use the spec. + if (!this.overrides?.keySpec) { + return depValid(node, this.spec, this.#accept, this.#from) + } + // There's some override. If the target node satisfies the overriding spec + // then it's okay. + if (depValid(node, this.spec, this.#accept, this.#from)) { + return true + } + // If it doesn't, then it should at least satisfy the original spec. + if (!depValid(node, this.rawSpec, this.#accept, this.#from)) { + return false + } + // It satisfies the original spec, not the overriding spec. We need to make + // sure it doesn't use the overridden spec. + // For example: + // we might have an ^8.0.0 rawSpec, and an override that makes + // keySpec=8.23.0 and the override value spec=9.0.0. + // If the node is 9.0.0, then it's okay because it's consistent with spec. + // If the node is 8.24.0, then it's okay because it's consistent with the rawSpec. + // If the node is 8.23.0, then it's not okay because even though it's consistent + // with the rawSpec, it's also consistent with the keySpec. + // So we're looking for ^8.0.0 or 9.0.0 and not 8.23.0. + return !depValid(node, this.overrides.keySpec, this.#accept, this.#from) } // return the edge data, and an explanation of how that edge came to be here @@ -135,6 +160,26 @@ class Edge { } if (this.#from) { explanation.from = this.#from.explain(null, seen) + // note when this edge was created or changed by a root packageExtensions repair on the from node + const applied = this.#from.packageExtensionsApplied + if (applied) { + for (const field of ['dependencies', 'optionalDependencies', 'peerDependencies', 'peerDependenciesMeta']) { + if (applied[field]?.includes(this.#name)) { + explanation.packageExtensions = { selector: applied.selector, field } + break + } + } + } + // note when this edge was created or changed by a root .npm-extension transformManifest repair on the from node + const transformed = this.#from.npmExtensionApplied + if (transformed) { + for (const field of ['dependencies', 'optionalDependencies', 'peerDependencies', 'peerDependenciesMeta']) { + if (transformed[field]?.includes(this.#name)) { + explanation.npmExtension = { extensionPoint: transformed.extensionPoint, field } + break + } + } + } } this.#explanation = explanation } @@ -181,24 +226,21 @@ class Edge { 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] + let pkg = this.#from?.sourceReference + ? this.#from?.sourceReference.root.package + : this.#from?.root?.package + + let specValue = this.#calculateReferentialOverrideSpec(ref, pkg) + + // If the package isn't found in the root package, fall back to the local package. + if (!specValue) { + pkg = this.#from?.package + specValue = this.#calculateReferentialOverrideSpec(ref, pkg) } + if (specValue) { + return specValue + } throw new Error(`Unable to resolve reference ${this.overrides.value}`) } return this.overrides.value @@ -206,6 +248,21 @@ class Edge { return this.#spec } + #calculateReferentialOverrideSpec (ref, pkg) { + 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] + } + } + get accept () { return this.#accept } @@ -234,10 +291,21 @@ class Edge { } else { this.#error = 'MISSING' } - } else if (this.peer && this.#from === this.#to.parent && !this.#from.isTop) { + } 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 if (this.overrides && this.#to.overrides && this.#to.edgesOut.size && OverrideSet.doOverrideSetsConflict(this.overrides, this.#to.overrides)) { + // Check for conflicts between the edge's override set and the target node's override set. + // This catches cases where different parts of the tree have genuinely incompatible + // version requirements for the same package. + // The improved conflict detection uses semantic comparison (checking for incompatible + // version ranges) rather than pure structural equality, avoiding false positives from: + // - Reference overrides ($syntax) that resolve to compatible versions + // - Peer dependencies with different but compatible override contexts + // Note: We only check if the target has dependencies (edgesOut.size > 0), since + // override conflicts are only relevant if the target has its own dependencies. + this.#error = 'INVALID' } else { this.#error = 'OK' } @@ -250,15 +318,26 @@ class Edge { reload (hard = false) { this.#explanation = null - if (this.#from.overrides) { - this.overrides = this.#from.overrides.getEdgeRule(this) + + let needToUpdateOverrideSet = false + let newOverrideSet + let oldOverrideSet + if (this.#from?.overrides) { + newOverrideSet = this.#from.overrides.getEdgeRule(this) + if (newOverrideSet && !newOverrideSet.isEqual(this.overrides)) { + // If there's a new different override set we need to propagate it to the nodes. + // If we're deleting the override set then there's no point propagating it right now since it will be filled with another value later. + needToUpdateOverrideSet = true + oldOverrideSet = this.overrides + this.overrides = newOverrideSet + } } else { delete this.overrides } - const newTo = this.#from.resolve(this.#name) + const newTo = this.#from?.resolve(this.#name) if (newTo !== this.#to) { if (this.#to) { - this.#to.edgesIn.delete(this) + this.#to.deleteEdgeIn(this) } this.#to = newTo this.#error = null @@ -267,15 +346,19 @@ class Edge { } } else if (hard) { this.#error = null + } else if (needToUpdateOverrideSet && this.#to) { + // Propagate the new override set to the target node. + this.#to.updateOverridesEdgeInRemoved(oldOverrideSet) + this.#to.updateOverridesEdgeInAdded(newOverrideSet) } } detach () { this.#explanation = null if (this.#to) { - this.#to.edgesIn.delete(this) + this.#to.deleteEdgeIn(this) } - this.#from.edgesOut.delete(this.#name) + this.#from?.edgesOut.delete(this.#name) this.#to = null this.#error = 'DETACHED' this.#from = null diff --git a/workspaces/arborist/lib/gather-dep-set.js b/workspaces/arborist/lib/gather-dep-set.js index 2c85a640fddfb..39180de38db4a 100644 --- a/workspaces/arborist/lib/gather-dep-set.js +++ b/workspaces/arborist/lib/gather-dep-set.js @@ -20,7 +20,7 @@ const gatherDepSet = (set, edgeFilter) => { } } - // now remove all nodes in the set that have a dependant outside the set + // now remove all nodes in the set that have a dependent outside the set // if any change is made, then re-check // continue until no changes made, or deps set evaporates fully. let changed = true diff --git a/workspaces/arborist/lib/index.js b/workspaces/arborist/lib/index.js index 5baaee6ee7c93..4236427d6c4e3 100644 --- a/workspaces/arborist/lib/index.js +++ b/workspaces/arborist/lib/index.js @@ -4,3 +4,5 @@ module.exports.Node = require('./node.js') module.exports.Link = require('./link.js') module.exports.Edge = require('./edge.js') module.exports.Shrinkwrap = require('./shrinkwrap.js') +module.exports.PackageExtensions = require('./package-extensions.js') +module.exports.NpmExtension = require('./npm-extension.js') diff --git a/workspaces/arborist/lib/install-scripts.js b/workspaces/arborist/lib/install-scripts.js new file mode 100644 index 0000000000000..29e9eace8eb96 --- /dev/null +++ b/workspaces/arborist/lib/install-scripts.js @@ -0,0 +1,114 @@ +const { isNodeGypPackage } = require('@npmcli/node-gyp') +const PackageJson = require('@npmcli/package-json') + +// Returns the install-relevant lifecycle scripts that would run for a +// given arborist Node, or `{}` if there are none. +// +// Includes: +// - explicit preinstall/install/postinstall +// - prepare, but only for non-registry sources (git, file, link, remote) +// - synthetic `node-gyp rebuild`, when `binding.gyp` is present on disk +// and the package does not opt out via `gypfile: false` or define its +// own install / preinstall script + +// Lifecycle-script enumeration boundary. +// +// IMPORTANT: this helper decides whether `prepare` should be included +// in the enumerated install scripts (true for non-registry sources only). +// It is NOT a policy-matching predicate. The policy matcher in +// script-allowed.js uses `isRegistryNode`, which is strictly tied to +// versionFromTgz(node.resolved). The two helpers exist separately on +// purpose: +// +// - `hasNonRegistryShape` (here): "should we consider running prepare +// on this node?" — a yes/no for what to enumerate. +// - `isRegistryNode` (script-allowed.js): "do we trust this node's +// identity enough to apply a policy entry?" — a security check. +// +// The looser fallback here (treating unknown-resolved nodes as registry, +// thus skipping `prepare`) is the safer default for enumeration: we'd +// rather omit a script we should have run than synthesise one for a +// non-registry source we couldn't confirm. The policy matcher's stricter +// behaviour is correct for its boundary; the two helpers must not be +// merged. +const hasNonRegistryShape = (node) => { + if (typeof node.isRegistryDependency === 'boolean') { + return !node.isRegistryDependency + } + if (!node.resolved) { + return false + } + return !/^https?:\/\/[^/]+\/.+\/-\/[^/]+-\d/.test(node.resolved) +} + +const getInstallScripts = async (node) => { + /* istanbul ignore next: arborist Nodes always carry a `package` object; + defensive fallbacks for non-arborist callers. */ + const pkg = node.package || {} + /* istanbul ignore next */ + const scripts = pkg.scripts || {} + const collected = {} + + if (scripts.preinstall) { + collected.preinstall = scripts.preinstall + } + if (scripts.install) { + collected.install = scripts.install + } + if (scripts.postinstall) { + collected.postinstall = scripts.postinstall + } + if (scripts.prepare && hasNonRegistryShape(node)) { + collected.prepare = scripts.prepare + } + + const hasExplicitGypGate = !!(collected.preinstall || collected.install) + if ( + !hasExplicitGypGate && + pkg.gypfile !== false && + await isNodeGypPackage(node.path).catch(() => false) + ) { + collected.install = 'node-gyp rebuild' + } + + // Lockfile-only nodes carry `hasInstallScript: true` but no enumerated + // scripts: the lockfile records the presence flag, not the script bodies, + // so `node.package.scripts` is empty on a lockfile-driven install (`npm ci`, + // a repeat `npm install`). Before giving up, read the installed + // package.json from disk to recover the real script bodies. Builder#addToBuildSet + // does the same disk read to decide what to run, but unlike that path this + // one is read-only: we never mutate `node.package`. + if (Object.keys(collected).length === 0 && node.hasInstallScript === true) { + const { content } = await PackageJson.normalize(node.path) + .catch(() => ({ content: {} })) + /* istanbul ignore next: normalize resolves to an object with a scripts + object, or our catch fallback returns {}; defensive guard only. */ + const diskScripts = content?.scripts || {} + + if (diskScripts.preinstall) { + collected.preinstall = diskScripts.preinstall + } + if (diskScripts.install) { + collected.install = diskScripts.install + } + if (diskScripts.postinstall) { + collected.postinstall = diskScripts.postinstall + } + if (diskScripts.prepare && hasNonRegistryShape(node)) { + collected.prepare = diskScripts.prepare + } + + // Still nothing. The package isn't on disk yet (e.g. `npm ci` before + // reify) or its package.json is unreadable. Emit a sentinel so the + // advisory and the strict-allow-scripts preflight still surface that + // install scripts are present. + if (Object.keys(collected).length === 0) { + collected.install = '(install scripts present)' + } + } + + return collected +} + +module.exports = getInstallScripts +module.exports.getInstallScripts = getInstallScripts diff --git a/workspaces/arborist/lib/inventory.js b/workspaces/arborist/lib/inventory.js index 7b3f294fdab2c..5e4a67eeed103 100644 --- a/workspaces/arborist/lib/inventory.js +++ b/workspaces/arborist/lib/inventory.js @@ -1,5 +1,4 @@ -// a class to manage an inventory and set of indexes of a set of objects based -// on specific fields. +// 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') diff --git a/workspaces/arborist/lib/isolated-classes.js b/workspaces/arborist/lib/isolated-classes.js new file mode 100644 index 0000000000000..d451b605d8ca2 --- /dev/null +++ b/workspaces/arborist/lib/isolated-classes.js @@ -0,0 +1,158 @@ +// Alternate versions of different classes that we use for isolated mode +const CaseInsensitiveMap = require('./case-insensitive-map.js') +const { resolve } = require('node:path') + +// fake lib/inventory.js +class IsolatedInventory extends Map { + query () { + return [] + } +} + +// fake lib/node.js +class IsolatedNode { + binPaths = [] + children = new CaseInsensitiveMap() + edgesIn = new Set() + edgesOut = new CaseInsensitiveMap() + fsChildren = new Set() + integrity = null + inventory = new IsolatedInventory() + isInStore = false + inBundle = false + isRegistryDependency = false + isRootDependency = false + linksIn = new Set() + meta = { loadedFromDisk: false } + optional = false + patched = null + parent = null + root = null + tops = new Set() + workspaces = new Map() + + constructor (options) { + this.location = options.location + this.name = options.name + this.package = options.package + this.path = options.path + this.realpath = !this.isLink ? this.path : resolve(options.realpath) + + if (options.parent) { + this.parent = options.parent + } + if (options.resolved) { + this.resolved = options.resolved + } + if (options.root) { + this.root = options.root + } + if (options.isInStore) { + this.isInStore = true + } + if (options.inBundle) { + this.inBundle = true + } + if (options.isRegistryDependency) { + this.isRegistryDependency = true + } + if (options.isRootDependency) { + this.isRootDependency = true + } + if (options.optional) { + this.optional = true + } + if (options.patched) { + this.patched = options.patched + } + } + + get isRoot () { + return this === this.root + } + + // The idealGraph is where this is set to true + get isProjectRoot () { + return false + } + + get inDepBundle () { + return false + } + + get isLink () { + return false + } + + get isTop () { + return !this.parent + } + + /* istanbul ignore next -- emulate lib/node.js */ + get global () { + return false + } + + get globalTop () { + return false + } + + /* istanbul ignore next -- emulate lib/node.js */ + set target (t) { + // nop + // In the real lib/node.js this throws in debug mode + } + + get target () { + return this + } + + /* istanbul ignore next -- emulate lib/node.js */ + getBundler () { + return null + } + + /* istanbul ignore next -- emulate lib/node.js */ + get hasInstallScript () { + const { hasInstallScript, scripts } = this.package + const { install, preinstall, postinstall } = scripts || {} + return !!(hasInstallScript || install || preinstall || postinstall) + } + + /* istanbul ignore next -- emulate lib/node.js */ + get packageName () { + return this.package.name || null + } + + get version () { + return this.package.version + } +} + +// fake lib/link.js +class IsolatedLink extends IsolatedNode { + #target + isStoreLink = false + + constructor (options) { + super(options) + this.#target = options.target + if (options.isStoreLink) { + this.isStoreLink = true + } + } + + get isLink () { + return true + } + + set target (t) { + this.#target = t + } + + get target () { + return this.#target + } +} + +module.exports = { IsolatedNode, IsolatedLink } diff --git a/workspaces/arborist/lib/link.js b/workspaces/arborist/lib/link.js index 266ec45168839..3824dc81ffb3c 100644 --- a/workspaces/arborist/lib/link.js +++ b/workspaces/arborist/lib/link.js @@ -99,7 +99,7 @@ class Link extends Node { // 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')}` + ? `file:${relpath(dirname(this.path), this.realpath)}` : null } @@ -109,6 +109,26 @@ class Link extends Node { // so this is a no-op [_loadDeps] () {} + // When a Link receives overrides (via edgesIn), forward them to the target node which holds the actual edgesOut — but only when the OverrideSet has at least one rule that names a dep the target actually depends on. + // Without this scope, the link forwards a generic ancestor OverrideSet that has no real effect on the target's edges, but still flips the target to "has overrides", which changes downstream `canReplaceWith` / placement decisions and causes `npm ci` to re-resolve lockfile-pinned edges from the registry. + // See npm/cli#9357. + recalculateOutEdgesOverrides () { + if (!this.target || !this.overrides) { + return + } + let hasMatchingRule = false + for (const rule of this.overrides.ruleset.values()) { + if (this.target.edgesOut.has(rule.name)) { + hasMatchingRule = true + break + } + } + if (!hasMatchingRule) { + return + } + this.target.updateOverridesEdgeInAdded(this.overrides) + } + // 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 diff --git a/workspaces/arborist/lib/node.js b/workspaces/arborist/lib/node.js index c519a7b543d4d..01c3b13716d73 100644 --- a/workspaces/arborist/lib/node.js +++ b/workspaces/arborist/lib/node.js @@ -28,21 +28,28 @@ // where we need to quickly find all instances of a given package name within a // tree. -const semver = require('semver') +const PackageJson = require('@npmcli/package-json') const nameFromFolder = require('@npmcli/name-from-folder') +const npa = require('npm-package-arg') +const semver = require('semver') +const util = require('node:util') +const { getPaths: getBinPaths } = require('bin-links') +const { log } = require('proc-log') +const { resolve, relative, dirname, basename } = require('node:path') +const { walkUp } = require('walk-up-path') + +const CaseInsensitiveMap = require('./case-insensitive-map.js') 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 consistentResolve = require('./consistent-resolve.js') const debug = require('./debug.js') const gatherDepSet = require('./gather-dep-set.js') +const printableTree = require('./printable.js') +const querySelectorAll = require('./query-selector-all.js') +const relpath = require('./relpath.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') @@ -57,14 +64,6 @@ 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 @@ -74,33 +73,35 @@ class Node { 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, + dev = true, + devOptional = true, + dummy = false, + error, + extraneous = true, fsChildren, + fsParent, + global = false, + inert = false, installLinks = false, + integrity, + isInStore = false, legacyPeerDeps = false, linksIn, - isInStore = false, - hasShrinkwrap, - overrides, loadOverrides = false, - extraneous = true, - dev = true, + meta, + name, // allow setting name explicitly when we haven't set a path yet optional = true, - devOptional = true, + overrides, + packageExtensionsApplied = null, + npmExtensionApplied = null, + parent, + patched = null, + path, peer = true, - global = false, - dummy = false, + realpath, + resolved, + root, sourceReference = null, } = options // this object gives querySelectorAll somewhere to stash context about a node @@ -119,14 +120,25 @@ class Node { // 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 || {}) + // have to set the internal package ref before assigning the parent, because this.package is read when adding to inventory + if (sourceReference) { + this[_package] = sourceReference.package + } else { + // TODO if this came from pacote.manifest we don't have to do this, we can be told to skip this step + const pkg = new PackageJson() + let content = {} + // TODO this is overly guarded. If pkg is not an object we should not allow it at all. + if (options.pkg && typeof options.pkg === 'object') { + content = options.pkg + } + pkg.fromContent(content) + pkg.syncNormalize() + this[_package] = pkg.content + } this.name = name || - nameFromFolder(path || pkg.name || realpath) || - pkg.name || + nameFromFolder(path || this.package.name || realpath) || + this.package.name || null // should be equal if not a link @@ -154,13 +166,20 @@ class Node { // 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)) { + const resolved = consistentResolve(this.package._resolved) + if (resolved && !(/^file:/.test(resolved) && this.package._where)) { this.resolved = resolved } } - this.integrity = integrity || pkg._integrity || null - this.hasShrinkwrap = hasShrinkwrap || pkg._hasShrinkwrap || false + this.integrity = integrity || this.package._integrity || null + // Patch record { path, integrity } or null, set from patchedDependencies or the lockfile. + this.patched = patched || null + // Provenance for a root packageExtensions repair applied to this node's manifest, or null. + // Shape: { selector, dependencies?, optionalDependencies?, peerDependencies?, peerDependenciesMeta? }. + this.packageExtensionsApplied = packageExtensionsApplied + // Provenance for a root .npm-extension transformManifest repair applied to this node's manifest, or null. + // Shape: { extensionPoint, dependencies?, optionalDependencies?, peerDependencies?, peerDependenciesMeta? }. + this.npmExtensionApplied = npmExtensionApplied this.installLinks = installLinks this.legacyPeerDeps = legacyPeerDeps @@ -196,20 +215,18 @@ class Node { this.extraneous = false } + this.inert = inert + 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 || {} + const overrides = this.package.overrides || {} if (Object.keys(overrides).length > 0) { this.overrides = new OverrideSet({ - overrides: this[_package].overrides, + overrides: this.package.overrides, }) } } @@ -239,7 +256,7 @@ class Node { 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 + // 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 @@ -310,7 +327,7 @@ class Node { } return getBinPaths({ - pkg: this[_package], + pkg: this.package, path: this.path, global: this.global, top: this.globalTop, @@ -324,11 +341,11 @@ class Node { } get version () { - return this[_package].version || '' + return this.package.version || '' } get packageName () { - return this[_package].name || null + return this.package.name || null } get pkgid () { @@ -344,7 +361,28 @@ class Node { } get overridden () { - return !!(this.overrides && this.overrides.value && this.overrides.name === this.name) + if (!this.overrides) { + return false + } + if (!this.overrides.value) { + return false + } + if (this.overrides.name !== this.name) { + return false + } + + // The overrides rule is for a package with this name, but some override rules only apply to specific + // versions. To make sure this package was actually overridden, we check whether any edge going in + // had the rule applied to it, in which case its overrides set is different than its source node. + for (const edge of this.edgesIn) { + if (edge.overrides && edge.overrides.name === this.name && edge.overrides.value === this.version) { + if (!edge.overrides.isEqual(edge.from.overrides)) { + return true + } + } + } + + return false } get package () { @@ -464,6 +502,27 @@ class Node { return false } + shouldOmit (omitSet) { + if (!omitSet.size) { + return false + } + + const { top } = this + + // if the top is not the root or workspace then we do not want to omit it + if (!top.isProjectRoot && !top.isWorkspace) { + return false + } + + // omit node if the dep type matches any omit flags that were set + return ( + this.peer && omitSet.has('peer') || + this.dev && omitSet.has('dev') || + this.optional && omitSet.has('optional') || + this.devOptional && omitSet.has('optional') && omitSet.has('dev') + ) + } + getBundler (path = []) { // made a cycle, definitely not bundled! if (path.includes(this)) { @@ -533,9 +592,7 @@ class Node { } 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. + // 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 } @@ -781,7 +838,7 @@ class Node { edge.reload() } } - // reload all edgesOut where root doens't match, or is missing, since + // reload all edgesOut where root doesn'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) { @@ -822,9 +879,6 @@ class Node { 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) { @@ -842,7 +896,7 @@ class Node { } for (const [name, path] of this.#workspaces.entries()) { - new Edge({ from: this, name, spec: `file:${path.replace(/#/g, '%23')}`, type: 'workspace' }) + new Edge({ from: this, name, spec: `file:${path}`, type: 'workspace' }) } } @@ -1006,10 +1060,21 @@ class Node { return false } - // XXX need to check for two root nodes? - if (node.overrides !== this.overrides) { - return false + // If this node has no dependencies, then it's irrelevant to check the override + // rules of the replacement node. + if (this.edgesOut.size) { + // XXX need to check for two root nodes? + if (node.overrides) { + if (!node.overrides.isEqual(this.overrides)) { + return false + } + } else { + if (this.overrides) { + return false + } + } } + ignorePeers = new Set(ignorePeers) // gather up all the deps of this node and that are only depended @@ -1044,9 +1109,9 @@ class Node { // 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) { + canDedupe (preferDedupe = false, explicitRequest = false) { + // not allowed to mess with bundles + if (this.inDepBundle) { return false } @@ -1077,8 +1142,18 @@ class Node { return false } - // if we prefer dedupe, or if the version is greater/equal, take the other - if (preferDedupe || semver.gte(other.version, this.version)) { + // if we prefer dedupe, or if the version is equal, take the other + if (preferDedupe || semver.eq(other.version, this.version)) { + return true + } + + // if our current version isn't the result of an override, then prefer to take the greater version + if (!this.overridden && semver.gt(other.version, this.version)) { + return true + } + + // if the other version was an explicit request, then prefer to take the other version + if (explicitRequest) { return true } @@ -1183,11 +1258,6 @@ class Node { treeCheck(this) } - get inShrinkwrap () { - return this.parent && - (this.parent.hasShrinkwrap || this.parent.inShrinkwrap) - } - get parent () { // setter prevents _parent from being this return this[_parent] @@ -1199,7 +1269,7 @@ class 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 + // with nodes that don't 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. @@ -1249,10 +1319,6 @@ class Node { 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 } @@ -1346,9 +1412,87 @@ class Node { this.edgesOut.set(edge.name, edge) } - addEdgeIn (edge) { + recalculateOutEdgesOverrides () { + // For each edge out propagate the new overrides through. + for (const edge of this.edgesOut.values()) { + edge.reload(true) + if (edge.to) { + edge.to.updateOverridesEdgeInAdded(edge.overrides) + } + } + } + + updateOverridesEdgeInRemoved (otherOverrideSet) { + // If this edge's overrides isn't equal to this node's overrides, then removing it won't change newOverrideSet later. + if (!this.overrides || !this.overrides.isEqual(otherOverrideSet)) { + return false + } + let newOverrideSet + for (const edge of this.edgesIn) { + if (newOverrideSet && edge.overrides) { + newOverrideSet = OverrideSet.findSpecificOverrideSet(edge.overrides, newOverrideSet) + } else { + newOverrideSet = edge.overrides + } + } + if (this.overrides.isEqual(newOverrideSet)) { + return false + } + this.overrides = newOverrideSet + if (this.overrides) { + // Optimization: if there's any override set at all, then no non-extraneous node has an empty override set. So if we temporarily have no + // override set (for example, we removed all the edges in), there's no use updating all the edges out right now. Let's just wait until + // we have an actual override set later. + this.recalculateOutEdgesOverrides() + } + return true + } + + // This logic isn't perfect either. When we have two edges in that have different override sets, then we have to decide which set is correct. + // This function assumes the more specific override set is applicable, so if we have dependencies A->B->C and A->C + // and an override set that specifies what happens for C under A->B, this will work even if the new A->C edge comes along and tries to change + // the override set. + // The strictly correct logic is not to allow two edges with different overrides to point to the same node, because even if this node can satisfy + // both, one of its dependencies might need to be different depending on the edge leading to it. + // However, this might cause a lot of duplication, because the conflict in the dependencies might never actually happen. + updateOverridesEdgeInAdded (otherOverrideSet) { + if (!otherOverrideSet) { + // Assuming there are any overrides at all, the overrides field is never undefined for any node at the end state of the tree. + // So if the new edge's overrides is undefined it will be updated later. So we can wait with updating the node's overrides field. + return false + } + if (!this.overrides) { + this.overrides = otherOverrideSet + this.recalculateOutEdgesOverrides() + return true + } + if (this.overrides.isEqual(otherOverrideSet)) { + return false + } + const newOverrideSet = OverrideSet.findSpecificOverrideSet(this.overrides, otherOverrideSet) + if (newOverrideSet) { + if (!this.overrides.isEqual(newOverrideSet)) { + this.overrides = newOverrideSet + this.recalculateOutEdgesOverrides() + return true + } + return false + } + // This is an error condition. We can only get here if the new override set is in conflict with the existing. + log.silly('Conflicting override sets', this.name) + } + + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) if (edge.overrides) { - this.overrides = edge.overrides + this.updateOverridesEdgeInRemoved(edge.overrides) + } + } + + addEdgeIn (edge) { + // We need to handle the case where the new edge in has an overrides field which is different from the current value. + if (!this.overrides || !this.overrides.isEqual(edge.overrides)) { + this.updateOverridesEdgeInAdded(edge.overrides) } this.edgesIn.add(edge) @@ -1470,6 +1614,22 @@ class Node { [util.inspect.custom] () { return this.toJSON() } + + resetDepFlags () { + this.extraneous = true + this.dev = true + this.optional = true + this.devOptional = true + this.peer = true + } + + unsetDepFlags () { + this.extraneous = false + this.dev = false + this.optional = false + this.devOptional = false + this.peer = false + } } module.exports = Node diff --git a/workspaces/arborist/lib/npm-extension.js b/workspaces/arborist/lib/npm-extension.js new file mode 100644 index 0000000000000..505920968bee3 --- /dev/null +++ b/workspaces/arborist/lib/npm-extension.js @@ -0,0 +1,237 @@ +// Root-owned `.npm-extension.{mjs,cjs}`: an imperative `transformManifest(pkg, context)` extension point that repairs third-party manifests before Arborist reads a candidate's dependency edges. +// See RFC: https://github.com/npm/rfcs/pull/903 +// This module discovers and hashes the root extension file, loads its `transformManifest` export, and applies it to a deeply isolated manifest copy, returning an extended manifest plus minimal provenance. +// It never mutates the input manifest or any shared cache object. +const { resolve, sep } = require('node:path') +const { readFileSync, existsSync } = require('node:fs') +const { pathToFileURL } = require('node:url') +const { isDeepStrictEqual } = require('node:util') +const { log } = require('proc-log') +const ssri = require('ssri') +const { EXTENSION_FIELDS } = require('./package-extensions.js') + +const EXTENSION_POINT = 'transformManifest' + +// The two supported module formats and their default discovery filenames. +const FORMATS = [ + { ext: 'mjs', file: '.npm-extension.mjs' }, + { ext: 'cjs', file: '.npm-extension.cjs' }, +] + +const err = (message, code, extra = {}) => + Object.assign(new Error(message), { code, ...extra }) + +// Read a file's bytes, or null when it does not exist. +const readBytes = path => { + try { + return readFileSync(path) + } catch (e) { + if (e.code === 'ENOENT') { + return null + } + throw e + } +} + +// Resolve which extension file to load, returning { path, format, bytes } or null when none is present. +// A configured `extension-file` wins over default discovery; it must resolve inside the project root and use a `.mjs` or `.cjs` extension. +// When both default files exist npm fails rather than choosing one implicitly. +const discover = (root, extensionFile) => { + if (extensionFile) { + const path = resolve(root, extensionFile) + if (path !== root && !path.startsWith(root + sep)) { + throw err(`extension-file "${extensionFile}" must resolve inside the project root`, 'ENPMEXTENSIONPATH') + } + const format = FORMATS.find(f => path.endsWith(`.${f.ext}`))?.ext + if (!format) { + throw err(`extension-file "${extensionFile}" must use a .mjs or .cjs extension`, 'ENPMEXTENSIONPATH') + } + const bytes = readBytes(path) + if (bytes === null) { + throw err(`extension-file "${extensionFile}" was not found`, 'ENPMEXTENSIONPATH') + } + return { path, format, bytes } + } + const found = FORMATS + .map(f => ({ path: resolve(root, f.file), format: f.ext, bytes: readBytes(resolve(root, f.file)) })) + .filter(f => f.bytes !== null) + if (found.length > 1) { + throw err('found both .npm-extension.mjs and .npm-extension.cjs; keep only one', 'ENPMEXTENSIONDUP') + } + return found[0] || null +} + +// Hash the selected extension file: a format-tagged prefix plus the raw file bytes, using npm's lockfile digest encoding. +// The prefix keeps `.mjs` and `.cjs` files with identical bytes distinct, and excludes any path so the digest is machine-independent. +const hashFile = (format, bytes) => + ssri.fromData( + Buffer.concat([Buffer.from(`npm-extension:v1:${format}\n`), bytes]), + { algorithms: ['sha512'] } + ).toString() + +class NpmExtension { + #cache = new Map() + #transform = null + + constructor ({ root, extensionFile = null } = {}) { + this.root = root + this.path = null + this.format = null + this.hash = null + + const selected = root ? discover(root, extensionFile) : null + if (!selected) { + this.present = false + return + } + this.present = true + this.path = selected.path + this.format = selected.format + this.hash = hashFile(selected.format, selected.bytes) + } + + // Import the extension module and capture its `transformManifest` export. + // ESM files are loaded with dynamic import; CommonJS files with require. + // The export must be a function; anything else fails the install. + async load () { + if (!this.present) { + return + } + // Key the module load by the file hash so a changed file is reloaded rather than served stale from a module cache within one process. + let mod + if (this.format === 'mjs') { + mod = await import(`${pathToFileURL(this.path).href}?h=${this.hash}`) + } else { + delete require.cache[require.resolve(this.path)] + mod = require(this.path) + } + const transform = mod?.transformManifest ?? mod?.default?.transformManifest + if (typeof transform !== 'function') { + throw err(`.npm-extension must export a transformManifest function`, 'ENPMEXTENSIONSHAPE') + } + this.#transform = transform + } + + // Apply transformManifest to a candidate manifest, returning { pkg, applied } or null when nothing changed. + // Results are cached once per resolved package identity; consumers get a deeply isolated copy so they cannot mutate the cached effective manifest. + // Pass { memoize: false } to run without caching, e.g. a staleness probe over partial lockfile manifests that must not seed the cache used by full-manifest fetches. + apply (pkg, { memoize = true } = {}) { + if (!this.#transform || !pkg?.name) { + return null + } + const key = this.#identity(pkg) + let result + if (this.#cache.has(key)) { + result = this.#cache.get(key) + } else { + result = this.#run(pkg) + if (memoize) { + this.#cache.set(key, result) + } + } + return result && { pkg: structuredClone(result.pkg), applied: structuredClone(result.applied) } + } + + // Identity key for the transform cache: package integrity when available, otherwise resolved source plus name and version. + #identity (pkg) { + return pkg._integrity || `${pkg._resolved || ''}:${pkg.name}@${pkg.version || ''}` + } + + // Run transformManifest on a deeply isolated copy and validate the result. + // Returns { pkg, applied } when dependency or peer metadata changed, or null when it did not. + #run (pkg) { + const context = { + log: message => log.silly('npm-extension', message), + root: this.root, + extensionPoint: EXTENSION_POINT, + } + let returned + try { + returned = this.#transform(structuredClone(pkg), context) + } catch (e) { + throw err( + `.npm-extension transformManifest threw while processing ${pkg.name}@${pkg.version}: ${e.message}`, + 'ENPMEXTENSIONTHROW', { pkgid: `${pkg.name}@${pkg.version}` }) + } + if (returned && typeof returned.then === 'function') { + throw err( + `.npm-extension transformManifest must return a manifest synchronously, not a promise, for ${pkg.name}@${pkg.version}`, + 'ENPMEXTENSIONRETURN', { pkgid: `${pkg.name}@${pkg.version}` }) + } + if (!returned || typeof returned !== 'object' || Array.isArray(returned)) { + throw err( + `.npm-extension transformManifest must return a manifest object for ${pkg.name}@${pkg.version}`, + 'ENPMEXTENSIONRETURN', { pkgid: `${pkg.name}@${pkg.version}` }) + } + // Only dependency and peer fields may change; any other field the returned manifest explicitly alters is rejected. + // Fields the returned object omits are left untouched, so a handler may return a new object with only the fields it repairs. + for (const k of Object.keys(returned)) { + if (!EXTENSION_FIELDS.includes(k) && !isDeepStrictEqual(returned[k], pkg[k])) { + throw err( + `.npm-extension transformManifest changed unsupported field "${k}" on ${pkg.name}@${pkg.version}; only ${EXTENSION_FIELDS.join(', ')} may change`, + 'ENPMEXTENSIONFIELD', { pkgid: `${pkg.name}@${pkg.version}`, field: k }) + } + } + // Build the effective manifest from the normalized baseline plus the returned allowlisted fields. + // A field the handler omits is left as the baseline; delete individual entries by returning a field object without them. + const next = { ...pkg } + for (const field of EXTENSION_FIELDS) { + if (returned[field] === undefined) { + continue + } + this.#validateField(field, returned[field], pkg) + next[field] = returned[field] + } + const applied = this.#provenance(pkg, next) + return applied && { pkg: next, applied } + } + + // Validate a returned allowlisted field and its entries, so invalid output fails with .npm-extension and package context. + // Dependency maps hold version strings; peerDependenciesMeta holds metadata objects. + #validateField (field, value, pkg) { + const fail = (suffix) => err( + `.npm-extension transformManifest set ${suffix} to an invalid value on ${pkg.name}@${pkg.version}`, + 'ENPMEXTENSIONVALUE', { pkgid: `${pkg.name}@${pkg.version}`, field }) + if (value === null || typeof value !== 'object' || Array.isArray(value)) { + throw fail(field) + } + for (const [name, entry] of Object.entries(value)) { + if (field === 'peerDependenciesMeta') { + if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) { + throw fail(`${field}.${name}`) + } + } else if (typeof entry !== 'string') { + throw fail(`${field}.${name}`) + } + } + } + + // Minimal provenance: the extension point plus, for each changed allowlisted field, a sorted array of affected dependency names. + // Returns null when nothing changed. + #provenance (before, after) { + const applied = { extensionPoint: EXTENSION_POINT } + let changed = false + for (const field of EXTENSION_FIELDS) { + const b = before[field] || {} + const a = after[field] || {} + const names = [...new Set([...Object.keys(b), ...Object.keys(a)])] + .filter(n => !isDeepStrictEqual(b[n], a[n])) + .sort() + if (names.length) { + applied[field] = names + changed = true + } + } + return changed ? applied : null + } +} + +// Whether a directory contains any default .npm-extension file; a non-throwing existence check used for non-root workspace warnings. +const hasExtensionFile = dir => FORMATS.some(f => existsSync(resolve(dir, f.file))) + +module.exports = NpmExtension +module.exports.NpmExtension = NpmExtension +module.exports.discover = discover +module.exports.hasExtensionFile = hasExtensionFile +module.exports.hashFile = hashFile +module.exports.EXTENSION_POINT = EXTENSION_POINT diff --git a/workspaces/arborist/lib/optional-set.js b/workspaces/arborist/lib/optional-set.js index 9f5184ea02442..891961fe2cd95 100644 --- a/workspaces/arborist/lib/optional-set.js +++ b/workspaces/arborist/lib/optional-set.js @@ -10,10 +10,6 @@ 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 @@ -29,10 +25,8 @@ const optionalSet = node => { } // 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) + // the optional section that don't have dependents outside the set. + return gatherDepSet(set, edge => !set.has(edge.to) && !edge.from?.inert) } module.exports = optionalSet diff --git a/workspaces/arborist/lib/override-set.js b/workspaces/arborist/lib/override-set.js index bfc5a5d7906ee..ab597a7f33bd4 100644 --- a/workspaces/arborist/lib/override-set.js +++ b/workspaces/arborist/lib/override-set.js @@ -1,5 +1,6 @@ const npa = require('npm-package-arg') const semver = require('semver') +const { log } = require('proc-log') class OverrideSet { constructor ({ overrides, key, parent }) { @@ -44,6 +45,43 @@ class OverrideSet { } } + childrenAreEqual (other) { + if (this.children.size !== other.children.size) { + return false + } + for (const [key] of this.children) { + if (!other.children.has(key)) { + return false + } + if (this.children.get(key).value !== other.children.get(key).value) { + return false + } + if (!this.children.get(key).childrenAreEqual(other.children.get(key))) { + return false + } + } + return true + } + + isEqual (other) { + if (this === other) { + return true + } + if (!other) { + return false + } + if (this.key !== other.key || this.value !== other.value) { + return false + } + if (!this.childrenAreEqual(other)) { + return false + } + if (!this.parent) { + return !other.parent + } + return this.parent.isEqual(other.parent) + } + getEdgeRule (edge) { for (const rule of this.ruleset.values()) { if (rule.name !== edge.name) { @@ -55,7 +93,9 @@ class OverrideSet { return rule } - let spec = npa(`${edge.name}@${edge.spec}`) + // We need to use the rawSpec here, because the spec has the overrides applied to it already. + // rawSpec can be undefined, so we need to use the fallback value of spec if it is. + let spec = npa(`${edge.name}@${edge.rawSpec || edge.spec}`) if (spec.type === 'alias') { spec = spec.subSpec } @@ -142,6 +182,123 @@ class OverrideSet { return ruleset } + + static findSpecificOverrideSet (first, second) { + for (let overrideSet = second; overrideSet; overrideSet = overrideSet.parent) { + if (overrideSet.isEqual(first)) { + return second + } + } + for (let overrideSet = first; overrideSet; overrideSet = overrideSet.parent) { + if (overrideSet.isEqual(second)) { + return first + } + } + + // The override sets are incomparable (e.g. siblings like the "react" and "react-dom" children of the root override set). Check if they have semantically conflicting rules before treating this as an error. + if (this.haveConflictingRules(first, second)) { + log.silly('Conflicting override sets', first, second) + return undefined + } + + // The override sets are structurally incomparable but have compatible rules. Fall back to their nearest common ancestor so the node still has a valid override set. + return this.findCommonAncestor(first, second) + } + + static findCommonAncestor (first, second) { + const firstAncestors = [] + for (const ancestor of first.ancestry()) { + firstAncestors.push(ancestor) + } + for (const secondAnc of second.ancestry()) { + for (const firstAnc of firstAncestors) { + if (firstAnc.isEqual(secondAnc)) { + return firstAnc + } + } + } + return null + } + + static doOverrideSetsConflict (first, second) { + // If override sets contain one another then we can try to use the more specific one. + // If neither one is more specific, check for semantic conflicts. + const specificSet = this.findSpecificOverrideSet(first, second) + if (specificSet !== undefined) { + // One contains the other, so no conflict + return false + } + + // The override sets are structurally incomparable, but this doesn't necessarily + // mean they conflict. We need to check if they have conflicting version requirements + // for any package that appears in both rulesets. + return this.haveConflictingRules(first, second) + } + + static haveConflictingRules (first, second) { + // Get all rules from both override sets + const firstRules = first.ruleset + const secondRules = second.ruleset + + // Check each package that appears in both rulesets + for (const [key, firstRule] of firstRules) { + const secondRule = secondRules.get(key) + if (!secondRule) { + // Package only appears in one ruleset, no conflict + continue + } + + // Same rule object means no conflict + if (firstRule === secondRule || firstRule.isEqual(secondRule)) { + continue + } + + // Both rulesets have rules for this package with different values. + // Check if the version requirements are actually incompatible. + const firstValue = firstRule.value + const secondValue = secondRule.value + + // If either value is a reference (starts with $), we can't determine + // compatibility here - the reference might resolve to compatible versions. + // We defer to runtime resolution rather than failing early. + if (firstValue.startsWith('$') || secondValue.startsWith('$')) { + continue + } + + // Check if the version ranges are compatible using semver + // If both specify version ranges, they conflict only if they have no overlap + try { + const firstSpec = npa(`${firstRule.name}@${firstValue}`) + const secondSpec = npa(`${secondRule.name}@${secondValue}`) + + // For range/version types, check if they intersect + if ((firstSpec.type === 'range' || firstSpec.type === 'version') && + (secondSpec.type === 'range' || secondSpec.type === 'version')) { + // Check if the ranges intersect + const firstRange = firstSpec.fetchSpec + const secondRange = secondSpec.fetchSpec + + // If the ranges don't intersect, we have a real conflict + if (!semver.intersects(firstRange, secondRange)) { + log.silly('Found conflicting override rules', { + package: firstRule.name, + first: firstValue, + second: secondValue, + }) + return true + } + } + // For other types (git, file, directory, tag), we can't easily determine + // compatibility, so we conservatively assume no conflict + } catch { + // If we can't parse the specs, conservatively assume no conflict + // Real conflicts will be caught during dependency resolution + } + } + + // No conflicting rules found + return false + } } module.exports = OverrideSet diff --git a/workspaces/arborist/lib/package-extensions.js b/workspaces/arborist/lib/package-extensions.js new file mode 100644 index 0000000000000..870ac4cbeaf2d --- /dev/null +++ b/workspaces/arborist/lib/package-extensions.js @@ -0,0 +1,236 @@ +// Root-owned `packageExtensions`: declarative repairs to third-party manifests applied before Arborist reads a candidate's dependency edges. +// See RFC: https://github.com/npm/rfcs/pull/889 +// This module is pure: it parses and validates the root rule set, matches a candidate manifest by name and version, and returns an extended manifest copy plus minimal provenance. +// It never mutates the input manifest or any shared cache object. +const semver = require('semver') +const ssri = require('ssri') +const validateName = require('validate-npm-package-name') + +// The only manifest fields a package extension may add or correct, because they are the fields that affect dependency and peer resolution. +const EXTENSION_FIELDS = [ + 'dependencies', + 'optionalDependencies', + 'peerDependencies', + 'peerDependenciesMeta', +] + +// The two normal dependency fields; a name may exist in only one of them. +const NORMAL_DEP_FIELDS = ['dependencies', 'optionalDependencies'] + +const err = (message, code, extra = {}) => + Object.assign(new Error(message), { code, ...extra }) + +// Parse a selector key into { name, range }, where range is null for a name-only key. +// Selectors are a package name with an optional semver range; dist-tags, git, file, directory, url, and alias specs are rejected. +const parseSelector = key => { + if (typeof key !== 'string' || !key) { + throw err(`Invalid packageExtensions selector: ${JSON.stringify(key)}`, 'EEXTENSIONSELECTOR') + } + // The separator @ is the first @ after a leading scope @. + const at = key.indexOf('@', key.startsWith('@') ? 1 : 0) + const name = at === -1 ? key : key.slice(0, at) + const range = at === -1 ? null : key.slice(at + 1) + + const { validForOldPackages, validForNewPackages } = validateName(name) + if (!validForOldPackages && !validForNewPackages) { + throw err(`Invalid package name in packageExtensions selector: "${key}"`, 'EEXTENSIONSELECTOR', { selector: key }) + } + // A blank range such as "foo@" is malformed; the name-only form "foo" is how you match every version. + if (range !== null && range.trim() === '') { + throw err( + `Invalid packageExtensions selector: "${key}". Use the name only to match every version.`, + 'EEXTENSIONSELECTOR', { selector: key }) + } + // A versioned selector must be a valid semver range, which rejects dist-tags, git, file, url, and alias specs. + if (range !== null && semver.validRange(range, { loose: true }) === null) { + throw err( + `Invalid version range in packageExtensions selector: "${key}". Selectors accept a package name with an optional semver range only.`, + 'EEXTENSIONSELECTOR', { selector: key }) + } + return { name, range } +} + +// A selector matches a candidate manifest by its own name and version. +// Name-only selectors match every version, including non-semver versions. +// Versioned selectors only match versions that parse as semver and satisfy the range. +const rangeMatches = (range, version) => { + if (range === null) { + return true + } + return semver.valid(version, { loose: true }) !== null && + semver.satisfies(version, range, { loose: true }) +} + +// Validate a single selector's extension object before it is ever applied. +const validateExtensionObject = (key, ext) => { + if (ext === null || typeof ext !== 'object' || Array.isArray(ext)) { + throw err(`packageExtensions["${key}"] must be an object`, 'EEXTENSIONVALUE', { selector: key }) + } + for (const field of Object.keys(ext)) { + if (!EXTENSION_FIELDS.includes(field)) { + throw err( + `packageExtensions["${key}"] has unsupported field "${field}". Supported fields: ${EXTENSION_FIELDS.join(', ')}.`, + 'EEXTENSIONFIELD', { selector: key, field }) + } + const val = ext[field] + if (val === null || typeof val !== 'object' || Array.isArray(val)) { + throw err(`packageExtensions["${key}"].${field} must be an object`, 'EEXTENSIONVALUE', { selector: key, field }) + } + } + // Deletion is not supported in v1, so a null, false, or "-" value is an error. + for (const field of [...NORMAL_DEP_FIELDS, 'peerDependencies']) { + for (const [name, spec] of Object.entries(ext[field] || {})) { + if (spec === null || spec === false || spec === '-') { + throw err( + `packageExtensions["${key}"].${field}.${name} attempts deletion, which is not supported.`, + 'EEXTENSIONDELETE', { selector: key, field, name }) + } + } + } + // Each peerDependenciesMeta entry must be a non-null metadata object, never a deletion sentinel or primitive. + for (const [name, meta] of Object.entries(ext.peerDependenciesMeta || {})) { + if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) { + throw err( + `packageExtensions["${key}"].peerDependenciesMeta.${name} must be an object`, + 'EEXTENSIONVALUE', { selector: key, field: 'peerDependenciesMeta', name }) + } + } +} + +// Apply a matched extension to a manifest, returning { pkg, applied } where pkg is a copy with extended fields and applied is minimal provenance. +// The input manifest is never mutated. +const applyExtension = (pkg, { key, ext }) => { + const applied = { selector: key } + + // Clone only the fields we may touch; the rest of the manifest is shared by reference since it is never mutated. + const next = { ...pkg } + for (const field of EXTENSION_FIELDS) { + if (pkg[field] && typeof pkg[field] === 'object') { + next[field] = field === 'peerDependenciesMeta' + ? Object.fromEntries(Object.entries(pkg[field]).map(([n, m]) => [n, { ...m }])) + : { ...pkg[field] } + } + } + + // dependencies and optionalDependencies add missing names only. + // A name already declared in either normal dependency field is an error, which also prevents moving a name between the fields. + for (const field of NORMAL_DEP_FIELDS) { + const adds = ext[field] + if (!adds) { + continue + } + for (const [name, spec] of Object.entries(adds)) { + for (const existingField of NORMAL_DEP_FIELDS) { + if (next[existingField] && name in next[existingField]) { + throw err( + `packageExtensions["${key}"].${field}.${name} conflicts with the package's existing ${existingField}.${name}. Use overrides to change a dependency version; packageExtensions only adds missing dependencies.`, + 'EEXTENSIONDUPDEP', { selector: key, field, name, existingField }) + } + } + next[field] = next[field] || {} + next[field][name] = spec + ;(applied[field] = applied[field] || []).push(name) + } + } + + // peerDependencies shallow-merges by peer name, and the extension value replaces an existing range. + if (ext.peerDependencies) { + next.peerDependencies = next.peerDependencies || {} + for (const [name, spec] of Object.entries(ext.peerDependencies)) { + next.peerDependencies[name] = spec + ;(applied.peerDependencies = applied.peerDependencies || []).push(name) + } + } + + // peerDependenciesMeta merges by peer name, then shallow-merges each meta object so an extension can add optional without dropping other meta keys. + if (ext.peerDependenciesMeta) { + next.peerDependenciesMeta = next.peerDependenciesMeta || {} + for (const [name, meta] of Object.entries(ext.peerDependenciesMeta)) { + next.peerDependenciesMeta[name] = { ...next.peerDependenciesMeta[name], ...meta } + ;(applied.peerDependenciesMeta = applied.peerDependenciesMeta || []).push(name) + // Every peerDependenciesMeta entry an extension adds must correspond to a peerDependencies entry present after extension application. + if (!next.peerDependencies || !(name in next.peerDependencies)) { + throw err( + `packageExtensions["${key}"].peerDependenciesMeta.${name} has no corresponding peerDependencies.${name} after extension application.`, + 'EEXTENSIONORPHANMETA', { selector: key, name }) + } + } + } + + return { pkg: next, applied } +} + +// Deterministic JSON for hashing: keys sorted lexicographically at every level, string and number values preserved exactly, no insignificant whitespace. +const canonicalStringify = val => { + if (Array.isArray(val)) { + return `[${val.map(canonicalStringify).join(',')}]` + } + if (val && typeof val === 'object') { + return `{${Object.keys(val).sort() + .map(k => `${JSON.stringify(k)}:${canonicalStringify(val[k])}`) + .join(',')}}` + } + return JSON.stringify(val) +} + +// Hash the canonical form of the root packageExtensions object using npm's existing lockfile digest encoding. +const canonicalHash = packageExtensions => + ssri.fromData(canonicalStringify(packageExtensions), { algorithms: ['sha512'] }).toString() + +class PackageExtensions { + constructor (raw) { + this.raw = raw + this.present = raw !== undefined + this.selectors = [] + this.hash = null + + if (!this.present) { + return + } + if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) { + throw err('packageExtensions must be an object', 'EEXTENSIONROOT') + } + for (const [key, ext] of Object.entries(raw)) { + const { name, range } = parseSelector(key) + validateExtensionObject(key, ext) + this.selectors.push({ key, name, range, ext }) + } + this.hash = canonicalHash(raw) + } + + // Non-throwing check used for warnings: whether any selector matches the candidate. + wouldMatch (name, version) { + return this.selectors.some(s => s.name === name && rangeMatches(s.range, version)) + } + + // Return the single selector matching a candidate manifest, or null. + // Throws EEXTENSIONCONFLICT when more than one selector matches the same candidate. + match (name, version) { + const matches = this.selectors.filter(s => s.name === name && rangeMatches(s.range, version)) + if (matches.length > 1) { + const keys = matches.map(s => `"${s.key}"`).join(', ') + throw err( + `Multiple packageExtensions selectors match ${name}@${version}: ${keys}. Narrow or remove one of the overlapping rules.`, + 'EEXTENSIONCONFLICT', { name, version, selectors: matches.map(s => s.key) }) + } + return matches[0] || null + } + + // Apply the matching extension to a manifest copy, returning { pkg, applied } or null when no selector matches. + // Throws on selector conflict or invalid merge. + apply (pkg) { + if (!this.present || !this.selectors.length || !pkg || !pkg.name) { + return null + } + const sel = this.match(pkg.name, pkg.version) + return sel ? applyExtension(pkg, sel) : null + } +} + +module.exports = PackageExtensions +module.exports.PackageExtensions = PackageExtensions +module.exports.parseSelector = parseSelector +module.exports.rangeMatches = rangeMatches +module.exports.canonicalHash = canonicalHash +module.exports.canonicalStringify = canonicalStringify +module.exports.EXTENSION_FIELDS = EXTENSION_FIELDS diff --git a/workspaces/arborist/lib/packument-cache.js b/workspaces/arborist/lib/packument-cache.js index 26e463eb9d334..d8e163ba23ba1 100644 --- a/workspaces/arborist/lib/packument-cache.js +++ b/workspaces/arborist/lib/packument-cache.js @@ -30,7 +30,7 @@ class PackumentCache extends LRUCache { maxSize, maxEntrySize, sizeCalculation: (p) => { - // Don't cache if we dont know the size + // Don't cache if we don't know the size // Some versions of pacote set this to `0`, newer versions set it to `null` if (!p[sizeKey]) { return maxEntrySize + 1 diff --git a/workspaces/arborist/lib/patch.js b/workspaces/arborist/lib/patch.js new file mode 100644 index 0000000000000..51d3c1878600f --- /dev/null +++ b/workspaces/arborist/lib/patch.js @@ -0,0 +1,111 @@ +// Native dependency patching helpers shared across build-ideal-tree and reify. +// Patches are plain unified diffs (git apply-compatible) applied with jsdiff using a fuzz factor of 0 so that any context drift fails loudly. +const { applyPatch, parsePatch } = require('diff') +const ssri = require('ssri') +const fs = require('node:fs') +const { promises: fsp } = fs +const { resolve, relative, dirname, isAbsolute } = require('node:path') + +// Compute the SSRI integrity of a patch file's contents. +// Accepts a string or Buffer and returns a sha512 SSRI string. +const patchIntegrity = data => + ssri.fromData(Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf8'), { + algorithms: ['sha512'], + }).toString() + +// Strip a leading git-style "a/" or "b/" prefix from a diff path. +const stripPrefix = file => file.replace(/^[ab]\//, '') + +// True when a diff path points at /dev/null, signalling a file add or delete. +const isDevNull = file => !file || file === '/dev/null' || /(^|\/)\.dev\/null$/.test(file) + +const patchError = (message, code, file) => + Object.assign(new Error(message), { code, file }) + +// Resolve a diff path under cwd and refuse anything that escapes the package directory. +const containedTarget = (cwd, file) => { + const target = resolve(cwd, file) + const rel = relative(cwd, target) + if (!rel || rel.startsWith('..') || isAbsolute(rel)) { + throw patchError(`patch path escapes the package directory: ${file}`, 'EPATCHUNSAFE', file) + } + return target +} + +// Run a parsed file patch against a source string with fuzz 0. +// Returns the patched text, or throws EPATCHFAILED on any context mismatch. +const strictApply = (source, filePatch, file) => { + const patched = applyPatch(source, filePatch, { fuzzFactor: 0 }) + if (patched === false) { + throw patchError(`patch could not be applied to ${file}`, 'EPATCHFAILED', file) + } + return patched +} + +// Apply a single parsed file patch under cwd. +// Handles modified, added (--- /dev/null) and deleted (+++ /dev/null) files. +const applyFilePatch = async (filePatch, cwd) => { + const isAdd = isDevNull(filePatch.oldFileName) + const isDelete = isDevNull(filePatch.newFileName) + + if (isDelete) { + const file = stripPrefix(filePatch.oldFileName) + const target = containedTarget(cwd, file) + // verify the file still matches the diff before removing it + const source = await fsp.readFile(target, 'utf8').catch(() => { + throw patchError(`patch target to delete is missing: ${file}`, 'EPATCHFAILED', file) + }) + strictApply(source, filePatch, file) + await fsp.rm(target, { force: true }) + return + } + + const file = stripPrefix(filePatch.newFileName) + const target = containedTarget(cwd, file) + + if (isAdd) { + // a new file must not already exist, otherwise the tarball drifted + if (fs.existsSync(target)) { + throw patchError(`patch adds a file that already exists: ${file}`, 'EPATCHFAILED', file) + } + const created = strictApply('', filePatch, file) + await fsp.mkdir(dirname(target), { recursive: true }) + await fsp.writeFile(target, created) + return + } + + const source = await fsp.readFile(target, 'utf8').catch(() => { + throw patchError(`patch target is missing: ${file}`, 'EPATCHFAILED', file) + }) + const mode = (await fsp.stat(target)).mode + const patched = strictApply(source, filePatch, file) + await fsp.writeFile(target, patched) + await fsp.chmod(target, mode) +} + +// Apply a unified diff to the package extracted at `cwd`. +// `patch` is the raw diff contents (string or Buffer). +// Throws with code EPATCHFAILED on any hunk or file that cannot be applied. +const applyPatchToDir = async ({ patch, cwd }) => { + const filePatches = parsePatch(patch.toString('utf8')) + for (const filePatch of filePatches) { + // jsdiff emits an empty trailing patch for some inputs; skip those. + if (!filePatch.hunks.length && isDevNull(filePatch.oldFileName) && isDevNull(filePatch.newFileName)) { + continue + } + try { + await applyFilePatch(filePatch, cwd) + } catch (er) { + // re-code raw filesystem errors so a patch failure is never mistaken for an optional-install skip + if (typeof er?.code === 'string' && er.code.startsWith('EPATCH')) { + throw er + } + throw Object.assign(new Error(`failed to apply patch: ${er.message}`), { code: 'EPATCHFAILED', cause: er }) + } + } +} + +module.exports = { + applyPatchToDir, + patchIntegrity, +} diff --git a/workspaces/arborist/lib/patched-dependencies.js b/workspaces/arborist/lib/patched-dependencies.js new file mode 100644 index 0000000000000..411406f0df71a --- /dev/null +++ b/workspaces/arborist/lib/patched-dependencies.js @@ -0,0 +1,168 @@ +// Resolve the root patchedDependencies map against an ideal tree. +// Attaches node.patched = { path, integrity } to each matched node. +// Enforces the failure modes (workspace-member entry, missing file, unused patch, non-registry target, ambiguous selectors) as hard errors. +const semver = require('semver') +const npa = require('npm-package-arg') +const { log } = require('proc-log') +const { resolve, relative, isAbsolute } = require('node:path') +const { readFile } = require('node:fs/promises') +const { patchIntegrity } = require('./patch.js') + +// Split a selector key into { name, spec }. spec is null for a name-only key. +const parseSelector = key => { + const at = key.indexOf('@', 1) + return at === -1 + ? { name: key, spec: null } + : { name: key.slice(0, at), spec: key.slice(at + 1) } +} + +const err = (message, code, extra = {}) => + Object.assign(new Error(message), { code, ...extra }) + +// Pick the most specific range among several that all match a version. +// Returns the strict subset, or throws when ordering is ambiguous. +// semver.subset is transitive, so the running minimum is a subset of every range it did not throw on. +const pickRange = (ranges, name, version) => { + let best = ranges[0] + for (const r of ranges.slice(1)) { + if (semver.subset(r.spec, best.spec, { loose: true })) { + best = r + } else if (!semver.subset(best.spec, r.spec, { loose: true })) { + throw err( + `Ambiguous patch selectors for ${name}@${version}: ` + + `"${name}@${best.spec}" and "${name}@${r.spec}" overlap but neither ` + + `is a subset. Add an exact "${name}@${version}" entry to disambiguate.`, + 'EPATCHAMBIGUOUS' + ) + } + } + return best +} + +// Choose the winning selector for a node: exact > range subset > name-only. +const matchSelector = (selectors, node) => { + const { name, version } = node + const matches = selectors.filter(s => s.name === name) + if (!matches.length) { + return null + } + + const exact = matches.find(s => + s.spec && semver.valid(s.spec) && semver.eq(s.spec, version, { loose: true })) + if (exact) { + return exact + } + + const ranges = matches.filter(s => + s.spec && !semver.valid(s.spec) && semver.satisfies(version, s.spec, { loose: true })) + if (ranges.length) { + return pickRange(ranges, name, version) + } + + return matches.find(s => s.spec === null) || null +} + +const resolvePatchedDependencies = async (tree, { path, allowUnusedPatches, rm }) => { + const patchedDependencies = tree.package?.patchedDependencies || {} + const selectors = Object.entries(patchedDependencies) + .map(([key, patchPath]) => ({ ...parseSelector(key), key, patchPath })) + + // cache patch file integrity by path so shared diffs are read once + const integrityCache = new Map() + const readPatch = async patchPath => { + if (integrityCache.has(patchPath)) { + return integrityCache.get(patchPath) + } + // patch files must live inside the project so the patch set stays auditable + const abs = resolve(path, patchPath) + const rel = relative(path, abs) + if (!rel || rel.startsWith('..') || isAbsolute(rel)) { + throw err(`patch path escapes the project: ${patchPath}`, 'EPATCHUNSAFE', { path: patchPath }) + } + let contents + try { + contents = await readFile(abs) + } catch { + throw err(`patch file not found: ${patchPath}`, 'EPATCHNOTFOUND', { path: patchPath }) + } + const integrity = patchIntegrity(contents) + integrityCache.set(patchPath, integrity) + return integrity + } + + const usedKeys = new Set() + for (const node of tree.inventory.values()) { + // patchedDependencies is honoured only in the root manifest + if (node.isWorkspace) { + // Link.package already delegates to its target's package + const pkg = node.package + if (pkg?.patchedDependencies && Object.keys(pkg.patchedDependencies).length) { + throw err( + `patchedDependencies is only supported in the root package.json, ` + + `but was found in workspace "${node.name}". Move the entry to the root.`, + 'EPATCHWORKSPACE', + { workspace: node.name } + ) + } + continue + } + if (node.isProjectRoot) { + continue + } + + const selector = matchSelector(selectors, node) + if (!selector) { + // a node that was patched but no longer matches a selector must be re-extracted to revert its files + if (node.patched) { + node.patchRemoved = true + } + node.patched = null + continue + } + + // a non-registry consumer edge (file:, git:, http(s)) means there is no registry tarball to patch; npm: aliases stay registry. + // checking edges (not isRegistryDependency) avoids rejecting an edgeless node, which is still a registry dep. + if ([...node.edgesIn].some(e => e.spec && !npa(e.spec).registry)) { + throw err( + `Cannot patch non-registry dependency ${node.name}@${node.version} ` + + `(selector "${selector.key}"). Only registry dependencies can be patched.`, + 'EPATCHNONREGISTRY', + { node: node.name } + ) + } + + const integrity = await readPatch(selector.patchPath) + node.patched = { path: selector.patchPath, integrity } + usedKeys.add(selector.key) + } + + if (selectors.length) { + const unused = selectors.filter(s => !usedKeys.has(s.key)) + + // an explicit `npm uninstall ` orphans that package's patch entry, so drop it instead of failing + const removed = new Set(rm) + const dropped = unused.filter(s => removed.has(s.name)) + if (dropped.length) { + const patched = { ...tree.package.patchedDependencies } + for (const s of dropped) { + delete patched[s.key] + log.notice('patch', `Removing patch entry "${s.key}" for uninstalled ${s.name}; left ${s.patchPath} in place.`) + } + // undefined drops the key entirely when reify writes package.json + tree.package.patchedDependencies = Object.keys(patched).length ? patched : undefined + } + + const stillUnused = unused.filter(s => !removed.has(s.name)) + if (stillUnused.length && !allowUnusedPatches) { + throw err( + `The following patches were registered but matched no installed ` + + `package:\n${stillUnused.map(s => ` ${s.key} -> ${s.patchPath}`).join('\n')}\n` + + `Use --allow-unused-patches to install anyway.`, + 'EPATCHUNUSED', + { unused: stillUnused.map(s => s.key) } + ) + } + } +} + +module.exports = { resolvePatchedDependencies, matchSelector, parseSelector } diff --git a/workspaces/arborist/lib/place-dep.js b/workspaces/arborist/lib/place-dep.js index fca36eb685613..83bdd803409e0 100644 --- a/workspaces/arborist/lib/place-dep.js +++ b/workspaces/arborist/lib/place-dep.js @@ -203,7 +203,7 @@ class PlaceDep { this.warnPeerConflict() } - // if we get a KEEP in a update scenario, then we MAY have something + // if we get a KEEP in an update scenario, then we MAY have something // already duplicating this unnecessarily! For example: // ``` // root (dep: y@1) @@ -247,6 +247,12 @@ class PlaceDep { installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, error: this.dep.errors[0], + ...(this.dep.packageExtensionsApplied + ? { packageExtensionsApplied: this.dep.packageExtensionsApplied } + : {}), + ...(this.dep.npmExtensionApplied + ? { npmExtensionApplied: this.dep.npmExtensionApplied } + : {}), ...(this.dep.overrides ? { overrides: this.dep.overrides } : {}), ...(this.dep.isLink ? { target: this.dep.target, realpath: this.dep.realpath } : {}), }) @@ -317,7 +323,7 @@ class PlaceDep { force: this.force, installLinks: this.installLinks, installStrategy: this.installStrategy, - legacyPeerDeps: this.legaycPeerDeps, + legacyPeerDeps: this.legacyPeerDeps, preferDedupe: this.preferDedupe, strictPeerDeps: this.strictPeerDeps, updateNames: this.updateName, @@ -421,9 +427,9 @@ class PlaceDep { // 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. + // Even if installStrategy is nested, we do this amount of deduplication. pruneDedupable (node, descend = true) { - if (node.canDedupe(this.preferDedupe)) { + if (node.canDedupe(this.preferDedupe, this.explicitRequest)) { // 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. diff --git a/workspaces/arborist/lib/printable.js b/workspaces/arborist/lib/printable.js index 53c3f7a5756df..9ade2c0813699 100644 --- a/workspaces/arborist/lib/printable.js +++ b/workspaces/arborist/lib/printable.js @@ -52,11 +52,6 @@ class ArboristNode { 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) } diff --git a/workspaces/arborist/lib/query-selector-all.js b/workspaces/arborist/lib/query-selector-all.js index fa48d5f84b556..3a6c15139d40b 100644 --- a/workspaces/arborist/lib/query-selector-all.js +++ b/workspaces/arborist/lib/query-selector-all.js @@ -8,7 +8,8 @@ const { minimatch } = require('minimatch') const npa = require('npm-package-arg') const pacote = require('pacote') const semver = require('semver') -const fetch = require('npm-registry-fetch') +const npmFetch = require('npm-registry-fetch') +const { isReleaseAgeExcluded } = require('./release-age-exclude.js') // 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 @@ -427,11 +428,19 @@ class Results { if (!this.currentAstNode.typeValue) { return this.initialItems } + // TODO this differs subtly with `:type()` because it now iterates on edgesIn, which means extraneous deps won't show up + // note how "@npmcli/abbrev@2.0.0-beta.45" is in the `:type()` results in the test but not in any of the other results. return this.initialItems .flatMap(node => { const found = [] + const { typeValue } = this.currentAstNode for (const edge of node.edgesIn) { - if (npa(`${edge.name}@${edge.spec}`).type === this.currentAstNode.typeValue) { + const parsedArg = npa(`${edge.name}@${edge.spec}`) + if (typeValue === 'registry') { + if (parsedArg.registry) { + found.push(edge.to) + } + } else if (parsedArg.type === typeValue) { found.push(edge.to) } } @@ -461,7 +470,7 @@ class Results { packages[node.name].push(node.version) } }) - const res = await fetch('/-/npm/v1/security/advisories/bulk', { + const res = await npmFetch('/-/npm/v1/security/advisories/bulk', { ...this.flatOptions, registry: this.flatOptions.auditRegistry || this.flatOptions.registry, method: 'POST', @@ -785,9 +794,14 @@ const hasParent = (node, compareNodes) => { compareNode = compareNode.target } - // follows logical parent for link anscestors + // Follows logical parent for link ancestors (e.g. workspaces whose target lives outside node_modules). + // Only match if the node has a link whose parent is the compareNode. Without this check, nodes deep in the store (linked strategy) would incorrectly match as children of root via their fsParent chain. if (node.isTop && (node.resolveParent === compareNode)) { - return true + for (const link of node.linksIn) { + if (link.parent === compareNode) { + return true + } + } } // follows edges-in to check if they match a possible parent for (const edge of node.edgesIn) { @@ -876,8 +890,9 @@ const getPackageVersions = async (name, opts) => { 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) { + // we filter this list down to only those versions that existed before the specified date. + // packages matching `min-release-age-exclude` are exempt from this filter. + if (packument.time && opts.before && !isReleaseAgeExcluded(name, opts.minReleaseAgeExclude)) { candidates = candidates.filter((version) => { // this version isn't found in the times at all, drop it if (!packument.time[version]) { diff --git a/workspaces/arborist/lib/release-age-exclude.js b/workspaces/arborist/lib/release-age-exclude.js new file mode 100644 index 0000000000000..b85527cfcbede --- /dev/null +++ b/workspaces/arborist/lib/release-age-exclude.js @@ -0,0 +1,45 @@ +// Determine whether a package name is exempt from the `min-release-age` / +// `before` release-age filter, based on the `min-release-age-exclude` config. +// +// Patterns are exact package names or `minimatch` globs (e.g. `@myorg/*`), and +// match against the package name only. This is a "named-only" exemption: a +// matched package's own dependencies still follow the filter unless they match +// a pattern too. +// +// Callers must match against the resolved registry identity of a package, not +// the self-reported alias or dependency-edge name. For `npm:` aliases the +// fetched package is the alias target, so run specs through `trustedSpecName` +// first; otherwise an alias key could match an exclude pattern and turn the +// filter off for the unrelated package it resolves to. +const { minimatch } = require('minimatch') + +// This list only ever widens the exemption (turns the security filter off for a +// package), so disable pattern features that could silently turn it into a +// match-all: `nonegate` keeps a leading `!` literal (so a stray `!foo` exempts +// nothing instead of everything-but-foo), `nocomment` keeps a leading `#` +// literal, and `noext` disables extglobs. +const minimatchOptions = { nonegate: true, nocomment: true, noext: true } + +const isReleaseAgeExcluded = (name, patterns) => { + if (!name || !Array.isArray(patterns) || patterns.length === 0) { + return false + } + return patterns.some(pattern => + name === pattern || minimatch(name, pattern, minimatchOptions)) +} + +// Resolve the trusted registry name for an npa spec. For `npm:` aliases (e.g. +// `"x": "npm:other@1"`) the installed/fetched package is the alias target +// (`subSpec`), not the alias key, so the exemption must be keyed on the +// underlying package name. Mirrors `nameFromEdges` in script-allowed.js. +const trustedSpecName = (spec) => { + if (!spec) { + return undefined + } + if (spec.type === 'alias' && spec.subSpec && spec.subSpec.registry) { + return spec.subSpec.name + } + return spec.name +} + +module.exports = { isReleaseAgeExcluded, trustedSpecName } diff --git a/workspaces/arborist/lib/reset-dep-flags.js b/workspaces/arborist/lib/reset-dep-flags.js index e259e901a5625..6bb4ceceb6972 100644 --- a/workspaces/arborist/lib/reset-dep-flags.js +++ b/workspaces/arborist/lib/reset-dep-flags.js @@ -6,10 +6,6 @@ // 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 + node.resetDepFlags() } } diff --git a/workspaces/arborist/lib/script-allowed.js b/workspaces/arborist/lib/script-allowed.js new file mode 100644 index 0000000000000..89e24339791f1 --- /dev/null +++ b/workspaces/arborist/lib/script-allowed.js @@ -0,0 +1,372 @@ +const npa = require('npm-package-arg') +const semver = require('semver') +const versionFromTgz = require('./version-from-tgz.js') + +// Identity matcher for the allowScripts policy. +// +// Returns: +// - true: at least one allow entry matches and no deny entry matches +// - false: at least one deny entry matches (deny wins on conflict) +// - null: no entry matches (unreviewed) +// +// `policy` is a flat object of `spec-key -> boolean`, where spec-key is +// anything `npm-package-arg` can parse. `node` is an arborist Node. +// +// Identity rules (see RFC npm/rfcs#868): +// - registry deps match by the name+version parsed from the lockfile's +// resolved URL, NOT by `node.packageName` / `node.version`. Those two +// getters return `node.package.name` / `node.package.version`, which +// come from the tarball's own package.json and are therefore +// attacker-controlled. A package can publish a tarball claiming any +// name; the only trusted name is the one baked into the registry URL. +// - tarball / file / link / remote: exact match on node.resolved +// - git: match on hosted.ssh() plus a short-SHA prefix of the +// resolved committish + +const isScriptAllowed = (node, policy) => { + // Bundled dependencies never run their install scripts and cannot be + // allowlisted. Matching by name@version from the bundled tarball would + // reintroduce manifest confusion (a bundled tarball can claim any name + // and version). Returning null marks them as not-allowed regardless of + // any policy entry, so their install scripts are blocked by the + // install-time gate. A package that needs a bundled dep's script must + // forward it as one of its own lifecycle scripts. + if (node.inBundle) { + return null + } + + if (!policy || typeof policy !== 'object') { + return null + } + + let anyAllow = false + let anyDeny = false + + for (const [key, value] of Object.entries(policy)) { + if (!matches(node, key)) { + continue + } + if (value === false) { + anyDeny = true + continue + } + /* istanbul ignore else: policy values are strictly true/false; + defensive guard against unexpected coercions. */ + if (value === true) { + anyAllow = true + } + } + + if (anyDeny) { + return false + } + if (anyAllow) { + return true + } + return null +} + +const matches = (node, key) => { + let parsed + try { + parsed = npa(key) + } catch { + return false + } + + switch (parsed.type) { + case 'tag': + case 'range': + case 'version': + return matchRegistry(node, parsed) + case 'git': + return matchGit(node, parsed) + case 'file': + case 'directory': + return matchFileOrDir(node, parsed) + case 'remote': + return matchRemote(node, parsed) + case 'alias': + // Disallowed: aliases as policy keys do not match anything. + // The user has to address the real package name. + return false + /* istanbul ignore next: switch above covers every npa type we expect; + defensive fallback for future npa types. */ + default: + return false + } +} + +const resolvedSourceSpecs = (node) => { + const specs = [] + const seen = new Set() + const add = (spec) => { + if (typeof spec !== 'string' || spec === '' || seen.has(spec)) { + return + } + seen.add(spec) + specs.push(spec) + } + + add(node?.resolved) + + if (!node?.resolved && node?.linksIn && typeof node.linksIn[Symbol.iterator] === 'function') { + let hasIncomingLink = false + for (const link of node.linksIn) { + hasIncomingLink = true + add(link.resolved) + } + + if (hasIncomingLink) { + // Link targets for local directory deps are separate inventory nodes + // whose own `resolved` is null. The incoming Link carries the saved spec + // (for example `file:../pkg`, relative to node_modules), while policy + // entries written by hand often use the dependency spec from package.json + // (for example `file:pkg`, resolved by npa to this target path). Include + // the real target paths so both forms can match the same local dep. + add(node.realpath) + add(node.path) + } + } + + return specs +} + +const matchRegistry = (node, parsed) => { + // If this node is not a registry dep, refuse the match. A registry-style + // key (`pkg`, `pkg@1`, `pkg@1 || 2`) must not match a tarball or git node + // even if their names happen to coincide. + if (!isRegistryNode(node)) { + return false + } + + // Derive the trusted name+version from the lockfile's resolved URL. + // Never use `node.packageName` / `node.version` here: those read from + // the tarball's own package.json and can be forged by a malicious + // publisher to bypass an allowScripts entry. + const trusted = getTrustedRegistryIdentity(node) + if (!trusted || trusted.name !== parsed.name) { + return false + } + + // `tag` covers `pkg@latest`. Rejected up front by validatePolicy in + // resolve-allow-scripts.js because tags look like a pin but can't be + // verified at install time. Defense-in-depth: if one slips through + // (e.g. arborist invoked directly without the resolver), don't match. + if (parsed.type === 'tag') { + /* istanbul ignore next: validatePolicy filters this; defensive */ + return false + } + + // `range` includes `pkg@^1`, `pkg@1 || 2`, `pkg@*`, `pkg@>=0`, and bare + // names like `pkg` (npa parses these as range with fetchSpec='*'). The + // RFC permits bare names (name-only allow) and exact versions joined by + // `||`; ranges like ^/~/>=/< are rejected because they would silently + // allow versions the user has never reviewed. + if (parsed.type === 'range') { + // Bare name or `pkg@*`: treat as name-only allow. + if (parsed.fetchSpec === '*' || parsed.rawSpec === '' || parsed.rawSpec === '*') { + return true + } + if (!trusted.version || !isExactVersionDisjunction(parsed.fetchSpec)) { + return false + } + return semver.satisfies(trusted.version, parsed.fetchSpec, { loose: true }) + } + + // `version` is an exact pin like `pkg@1.2.3`. + /* istanbul ignore else: parsed.type at this point is always 'version'; + the istanbul-ignored fallback below handles the impossible case. */ + if (parsed.type === 'version') { + return trusted.version === parsed.fetchSpec + } + + /* istanbul ignore next: parsed.type is constrained to tag/range/version + by the caller; this final fallback is defensive. */ + return false +} + +// Derive a registry node's trusted name+version. +// +// Preferred source: the lockfile's resolved URL parsed via +// versionFromTgz. arborist records the URL when it first adds the dep, +// before any tarball is unpacked, so the URL cannot be forged by the +// package's own package.json. +// +// Fallback for lockfiles produced with omit-lockfile-registry-resolved +// (where the URL is absent): take the dep name from an incoming +// dependency edge. The edge's spec was written by the consumer (or by an +// upstream package.json), not by the installed tarball. For aliases like +// `"trusted": "npm:naughty@1.0.0"`, the underlying registered package +// name is parsed out of the alias `subSpec`. The install location +// (`node_modules/trusted`) is deliberately not consulted because for +// aliases it carries only the alias name, which would let a malicious +// publisher bypass an allowScripts entry written for the real package. +// +// Version is left null in the fallback case because the only remaining +// source for it (`node.version`) reads from the tarball. +// +// Returns `{ name, version }` or `null` if no trusted identity exists. +const getTrustedRegistryIdentity = (node) => { + if (node.resolved && typeof node.resolved === 'string') { + const parsed = versionFromTgz('', node.resolved) + /* istanbul ignore else: versionFromTgz returns either a complete + { name, version } or null; partial objects are not produced. */ + if (parsed && parsed.name && parsed.version) { + return parsed + } + } + const name = nameFromEdges(node) + if (name) { + return { name, version: null } + } + return null +} + +const nameFromEdges = (node) => { + if (!node.edgesIn || typeof node.edgesIn[Symbol.iterator] !== 'function') { + return null + } + for (const edge of node.edgesIn) { + let parsed + try { + parsed = npa.resolve(edge.name, edge.spec) + } catch { + continue + } + // Aliases: trust the underlying registered package, not the alias. + if (parsed.type === 'alias' && parsed.subSpec && parsed.subSpec.registry) { + return parsed.subSpec.name + } + // Non-aliased registry edge: the edge name is the package name as + // written by the consumer / upstream, which is trusted (it is not + // read from the installed tarball). + if (parsed.registry) { + return parsed.name + } + } + return null +} + +// True if `rangeSpec` is one or more exact versions joined by `||`. Anything +// containing comparator operators (^, ~, >=, <, *) returns false. +const isExactVersionDisjunction = (rangeSpec) => { + /* istanbul ignore next: caller always passes parsed.fetchSpec, which + npa guarantees to be a non-empty string for range specs. */ + if (typeof rangeSpec !== 'string' || rangeSpec.trim() === '') { + return false + } + const parts = rangeSpec.split('||').map(p => p.trim()) + /* istanbul ignore next: String.prototype.split always returns at least + one element; defensive guard only. */ + if (parts.length === 0) { + return false + } + return parts.every(p => p !== '' && semver.valid(p) !== null) +} + +const matchGit = (node, parsed) => { + if (!node.resolved || !node.resolved.startsWith('git')) { + return false + } + + let nodeParsed + try { + nodeParsed = npa(node.resolved) + } catch { + /* istanbul ignore next: npa parsing a git URL we already validated + starts with `git` should not throw; defensive guard only. */ + return false + } + + // Compare the host/repo. Both sides should resolve to the same canonical + // ssh URL. + const noCommittish = { noCommittish: true } + const keyHost = parsed.hosted?.ssh(noCommittish) + const nodeHost = nodeParsed.hosted?.ssh(noCommittish) + if (keyHost && nodeHost) { + if (keyHost !== nodeHost) { + return false + } + } else if (parsed.fetchSpec && nodeParsed.fetchSpec) { + // Non-hosted git URLs: fall back to fetch spec. + if (parsed.fetchSpec !== nodeParsed.fetchSpec) { + return false + } + } else { + return false + } + + // If the policy key has no committish, name-only match. + const keyCommittish = parsed.gitCommittish || parsed.hosted?.committish + if (!keyCommittish) { + return true + } + + // Match the resolved full SHA against the key's committish. Users + // typically write short SHAs in the policy; the lockfile stores 40-char + // SHAs. Direction matters: the lockfile's full SHA must START WITH the + // key's short SHA, never the reverse. A longer key matching a shorter + // resolved committish would let a malformed lockfile or a divergent + // resolver allow scripts the user never approved. + const nodeCommittish = nodeParsed.gitCommittish || nodeParsed.hosted?.committish || '' + if (!nodeCommittish) { + return false + } + return nodeCommittish.startsWith(keyCommittish) +} + +const matchFileOrDir = (node, parsed) => { + return resolvedSourceSpecs(node) + .some(resolved => resolved === parsed.saveSpec || resolved === parsed.fetchSpec) +} + +const matchRemote = (node, parsed) => { + return resolvedSourceSpecs(node) + .some(resolved => resolved === parsed.fetchSpec || resolved === parsed.saveSpec) +} + +const isRegistryNode = (node) => { + // Prefer arborist's edge-based check when available (real Node objects). + // It inspects the incoming edges' specs and only returns true if every + // edge resolves to a registry spec, which is much harder to spoof than + // the URL. + if (typeof node.isRegistryDependency === 'boolean') { + return node.isRegistryDependency + } + // Fall back to URL parsing for nodes without the arborist getter + // (e.g. test fixtures, lockfiles with omit-lockfile-registry-resolved). + // Treat the node as a registry dep when: + // - resolved is missing entirely (omitLockfileRegistryResolved), + // - resolved is an https/http URL pointing at a registry tarball, or + // - resolved is undefined and the node has a version (defensive). + if (!node.resolved) { + return !!node.version + } + // Registry tarballs live at `//-/-.tgz`. + // Require a path segment before `/-/` so an attacker can't lift a + // registry-style allow entry to a hostile URL like + // `https://evil.com/-/trusted-1.0.0.tgz`. + return /^https?:\/\/[^/]+\/.+\/-\/[^/]+-\d/.test(node.resolved) +} + +// Trusted display identity for human-facing output (the `npm install` +// blocked-scripts summary and `npm approve-scripts --allow-scripts-pending`). +// Same as getTrustedRegistryIdentity, but for display only: version +// falls back to node.version when the URL doesn't carry one. Do not +// use for policy matching. +const trustedDisplay = (node) => { + const trusted = getTrustedRegistryIdentity(node) + /* istanbul ignore next: defensive fallbacks for nodes without name/version */ + return { + name: (trusted && trusted.name) || node.name || null, + version: (trusted && trusted.version) || node.version || null, + } +} + +module.exports = isScriptAllowed +module.exports.isScriptAllowed = isScriptAllowed +module.exports.isExactVersionDisjunction = isExactVersionDisjunction +module.exports.getTrustedRegistryIdentity = getTrustedRegistryIdentity +module.exports.resolvedSourceSpecs = resolvedSourceSpecs +module.exports.trustedDisplay = trustedDisplay diff --git a/workspaces/arborist/lib/shrinkwrap.js b/workspaces/arborist/lib/shrinkwrap.js index 5f720ed9bd440..645a8a64263d8 100644 --- a/workspaces/arborist/lib/shrinkwrap.js +++ b/workspaces/arborist/lib/shrinkwrap.js @@ -1,5 +1,4 @@ -// a module that manages a shrinkwrap file (npm-shrinkwrap.json or -// package-lock.json). +// a module that manages a lockfile (package-lock.json). // Increment whenever the lockfile version updates // v1 - npm <=6 @@ -11,6 +10,12 @@ const localeCompare = require('@isaacs/string-locale-compare')('en') const defaultLockfileVersion = 3 +// Bumped to 4 only when a node carries a patch record, so older clients abort. +const patchedLockfileVersion = 4 +// packageExtensions provenance also forces lockfileVersion 4 so older clients abort rather than silently dropping the repaired graph. +// Both features share version 4: they are root-owned graph repairs an old npm must not drop. +const packageExtensionsLockfileVersion = 4 +const maxLockfileVersion = 4 // for comparing nodes to yarn.lock entries const mismatch = (a, b) => a && b && a !== b @@ -95,9 +100,9 @@ const pkgMetaKeys = [ 'engines', 'os', 'cpu', + 'libc', '_integrity', 'license', - '_hasShrinkwrap', 'hasInstallScript', 'bin', 'deprecated', @@ -107,8 +112,10 @@ const pkgMetaKeys = [ const nodeMetaKeys = [ 'integrity', 'inBundle', - 'hasShrinkwrap', 'hasInstallScript', + 'patched', + 'packageExtensionsApplied', + 'npmExtensionApplied', ] const metaFieldFromPkg = (pkg, key) => { @@ -198,17 +205,14 @@ class Shrinkwrap { const s = new Shrinkwrap(options) s.reset() - const [sw, lock] = await s.resetFiles + const [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) + s.loadedFromDisk = !!lock // TODO what uses this? s.type = basename(s.filename) @@ -285,7 +289,6 @@ class Shrinkwrap { path, indent = 2, newline = '\n', - shrinkwrapOnly = false, hiddenLockfile = false, lockfileVersion, resolveOptions = {}, @@ -311,8 +314,6 @@ class Shrinkwrap { 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, @@ -355,6 +356,8 @@ class Shrinkwrap { reset () { this.tree = null this.#awaitingUpdate = new Map() + this.packageExtensionsHash = null + this.npmExtensionHash = null const lockfileVersion = this.lockfileVersion || defaultLockfileVersion this.originalLockfileVersion = lockfileVersion @@ -368,14 +371,10 @@ class Shrinkwrap { // 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`, ] @@ -395,9 +394,9 @@ class Shrinkwrap { } get resetFiles () { - // slice out yarn, we only care about lock or shrinkwrap when checking + // slice out yarn, we only care about the package-lock when checking // this way, since we're not actually loading the full lock metadata - return Promise.all(this.#filenameSet.slice(0, 2) + return Promise.all(this.#filenameSet.slice(0, 1) .map(file => file && stat(file).then(st => st.isFile(), er => { /* istanbul ignore else - can't test without breaking module itself */ if (er.code === 'ENOENT') { @@ -424,25 +423,18 @@ class Shrinkwrap { } 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 || '{}' + const [lock, yarn] = await this.loadFiles + data = 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) + this.loadedFromDisk = Boolean(lock) if (yarn) { this.yarnLock = new YarnLock() @@ -477,6 +469,13 @@ class Shrinkwrap { this.ancientLockfile = false data = {} } + // refuse lockfiles newer than we understand so we never drop a patched or repaired graph we cannot read + if (data.lockfileVersion > maxLockfileVersion) { + throw Object.assign( + new Error(`Unsupported lockfileVersion ${data.lockfileVersion}. This npm only supports up to ${maxLockfileVersion}. Please upgrade npm.`), + { code: 'ELOCKFILEVERSION' } + ) + } // auto convert v1 lockfiles to v3 // leave v2 in place unless configured // v3 by default @@ -497,6 +496,11 @@ class Shrinkwrap { this.originalLockfileVersion = data.lockfileVersion + // the canonical packageExtensions hash, if the lockfile recorded one on its root entry + this.packageExtensionsHash = data.packages?.['']?.packageExtensionsHash || null + // the .npm-extension file hash, if the lockfile recorded one on its root entry + this.npmExtensionHash = data.packages?.['']?.npmExtensionHash || null + // 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. @@ -808,7 +812,6 @@ class Shrinkwrap { const { resolved, integrity, - hasShrinkwrap, version, } = this.get(node.path) @@ -817,7 +820,7 @@ class Shrinkwrap { if (!/^file:/.test(resolved)) { pathFixed = resolved } else { - pathFixed = `file:${resolve(this.path, resolved.slice(5)).replace(/#/g, '%23')}` + pathFixed = `file:${resolve(this.path, resolved.slice(5))}` } } @@ -835,17 +838,14 @@ class Shrinkwrap { 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) @@ -918,6 +918,14 @@ class Shrinkwrap { this.tree.target, this.path, this.resolveOptions) + // record the canonical packageExtensions hash on the root entry so npm ci can detect stale extension state + if (this.packageExtensionsHash) { + root.packageExtensionsHash = this.packageExtensionsHash + } + // record the .npm-extension file hash on the root entry for the same reason + if (this.npmExtensionHash) { + root.npmExtensionHash = this.npmExtensionHash + } this.data.packages = {} if (Object.keys(root).length) { this.data.packages[''] = root @@ -928,10 +936,30 @@ class Shrinkwrap { continue } const loc = relpath(this.path, node.path) - this.data.packages[loc] = Shrinkwrap.metaFromNode( + // Drop lockfile entries for extraneous nodes outside node_modules that + // are direct fsChildren of the root (or detached link targets). These + // are stale top-level entries: a workspace or file: dep removed from + // the root manifest, or whose directory was deleted. Extraneous + // fsChildren nested under another package (e.g. a file: dep of another + // file: dep) are kept so `npm ci` can resolve the parent's dependency. + if (node.extraneous && !/(^|\/)node_modules\//.test(loc) && loc !== 'node_modules' && + (!node.fsParent || node.fsParent.isRoot)) { + continue + } + const meta = Shrinkwrap.metaFromNode( node, this.path, this.resolveOptions) + // Skip inert nodes — these are optional deps that failed to load + // (e.g. 404 from a proxy registry that hasn't cached the package, + // or incomplete manifest missing version field). + // #pruneFailedOptional marks them inert so they won't be reified; + // writing them to the lockfile produces invalid entries like + // {"optional": true} that cause "Invalid Version:" errors. + if (node.inert && !node.package.version) { + continue + } + this.data.packages[loc] = meta } } else if (this.#awaitingUpdate.size > 0) { for (const loc of this.#awaitingUpdate.keys()) { @@ -943,6 +971,22 @@ class Shrinkwrap { if (!this.lockfileVersion) { this.lockfileVersion = defaultLockfileVersion } + // patched nodes force lockfileVersion 4 so older clients abort the install + // the hidden lockfile is an internal cache pinned to version 3, so it never drives this upgrade + const hasPatched = !this.hiddenLockfile && + Object.values(this.data.packages).some(p => p.patched) + if (hasPatched && this.lockfileVersion < patchedLockfileVersion) { + log.warn('shrinkwrap', `patchedDependencies requires lockfileVersion ${patchedLockfileVersion}; upgrading the lockfile from version ${this.lockfileVersion}.`) + this.lockfileVersion = patchedLockfileVersion + } + // packageExtensions and .npm-extension state likewise force lockfileVersion 4 so older clients abort instead of dropping the repaired graph + const hasExtensionState = !this.hiddenLockfile && + (this.packageExtensionsHash || this.npmExtensionHash || + Object.values(this.data.packages).some(p => p.packageExtensionsApplied || p.npmExtensionApplied)) + if (hasExtensionState && this.lockfileVersion < packageExtensionsLockfileVersion) { + log.warn('shrinkwrap', `manifest extensions require lockfileVersion ${packageExtensionsLockfileVersion}; upgrading the lockfile from version ${this.lockfileVersion}.`) + this.lockfileVersion = packageExtensionsLockfileVersion + } this.data.lockfileVersion = this.lockfileVersion // hidden lockfiles don't include legacy metadata or a root entry @@ -978,7 +1022,7 @@ class Shrinkwrap { // 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 + // racy 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 @@ -1011,7 +1055,7 @@ class Shrinkwrap { } if (node.isLink) { - lock.version = `file:${relpath(this.path, node.realpath).replace(/#/g, '%23')}` + lock.version = `file:${relpath(this.path, node.realpath)}` } else if (spec && (spec.type === 'file' || spec.type === 'remote')) { lock.version = spec.saveSpec } else if (spec && spec.type === 'git' || rSpec.type === 'git') { @@ -1089,7 +1133,7 @@ class Shrinkwrap { // 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')}` + set[k] = `file:${relpath(node.realpath, p)}` } else { set[k] = spec } diff --git a/workspaces/arborist/lib/unreviewed-scripts.js b/workspaces/arborist/lib/unreviewed-scripts.js new file mode 100644 index 0000000000000..587d06bf8fe56 --- /dev/null +++ b/workspaces/arborist/lib/unreviewed-scripts.js @@ -0,0 +1,94 @@ +const isScriptAllowed = require('./script-allowed.js') +const getInstallScripts = require('./install-scripts.js') + +// Shared allowScripts walk used by both the npm CLI +// (lib/utils/check-allow-scripts.js, lib/utils/strict-allow-scripts-preflight.js) +// and libnpmexec (npm exec / npx). It lives in arborist because that is the +// only package both callers can import. +// +// Walks a tree's inventory and returns the dep nodes that have +// install-relevant lifecycle scripts and are not yet covered (or explicitly +// denied) by the allowScripts policy. +// +// Returns an array of `{ node, scripts }` entries. `scripts` is an object +// describing the relevant lifecycle scripts that would run. +const collectUnreviewedScripts = async ({ + tree, + policy, + ignoreScripts = false, + dangerouslyAllowAllScripts = false, + includeWhenIgnored = false, +} = {}) => { + // With ignore-scripts set, no scripts run, so execution callers bail out + // here. approve/deny pass includeWhenIgnored so they keep listing + // unreviewed packages, which is what you need to move from a blanket + // ignore-scripts to an allowlist. Listing never runs anything. + if ((ignoreScripts && !includeWhenIgnored) || dangerouslyAllowAllScripts) { + return [] + } + + if (!tree?.inventory) { + return [] + } + + const resolvedPolicy = policy || null + + const unreviewed = [] + for (const node of tree.inventory.values()) { + if (node.isProjectRoot || node.isWorkspace) { + continue + } + if (node.isLink) { + // Linked workspace dependencies are managed by the workspace owner. + continue + } + if (node.inBundle) { + // Bundled dependencies never run their install scripts and cannot be + // allowlisted, so they are never "pending". Skipping them keeps them + // out of the advisory warning and out of strict-allow-scripts. A + // package that needs a bundled dep's script must forward it as one of + // its own lifecycle scripts. + continue + } + + const verdict = isScriptAllowed(node, resolvedPolicy) + if (verdict === true || verdict === false) { + continue + } + + const scripts = await getInstallScripts(node) + if (Object.keys(scripts).length === 0) { + continue + } + + unreviewed.push({ node, scripts }) + } + + return unreviewed +} + +// Builds the `ESTRICTALLOWSCRIPTS` error thrown by the strict-mode preflight +// from a list of `{ node, scripts }` entries. `remediation` is the +// caller-specific guidance appended after the package list (npm install vs +// npm exec have different remediation commands). +const strictAllowScriptsError = (unreviewed, { remediation } = {}) => { + const lines = unreviewed.map(({ node, scripts }) => { + const events = Object.entries(scripts) + .map(([event, body]) => `${event}: ${body}`) + .join('; ') + const name = node.package?.name || node.name + const version = node.package?.version || '' + const label = version ? `${name}@${version}` : name + return ` ${label} (${events})` + }).join('\n') + + return Object.assign( + new Error( + `--strict-allow-scripts: ${unreviewed.length} package(s) have install ` + + `scripts not covered by allowScripts:\n${lines}\n${remediation}` + ), + { code: 'ESTRICTALLOWSCRIPTS' } + ) +} + +module.exports = { collectUnreviewedScripts, strictAllowScriptsError } diff --git a/workspaces/arborist/lib/vuln.js b/workspaces/arborist/lib/vuln.js index 2bffe54f2dacd..e6c6bbab383ea 100644 --- a/workspaces/arborist/lib/vuln.js +++ b/workspaces/arborist/lib/vuln.js @@ -41,6 +41,7 @@ class Vuln { this.effects = new Set() this.topNodes = new Set() this.nodes = new Set() + this.fixBlockedByReleaseAge = false this.addAdvisory(advisory) this.packument = advisory.packument this.versions = advisory.versions @@ -126,6 +127,9 @@ class Vuln { range: this.simpleRange, nodes: [...this.nodes].map(n => n.location).sort(localeCompare), fixAvailable: this.#fixAvailable, + ...(this.fixBlockedByReleaseAge + ? { fixBlockedByReleaseAge: this.fixBlockedByReleaseAge } + : {}), } } diff --git a/workspaces/arborist/package.json b/workspaces/arborist/package.json index 9fdbbbf8607ad..a649be64ff35d 100644 --- a/workspaces/arborist/package.json +++ b/workspaces/arborist/package.json @@ -1,50 +1,52 @@ { "name": "@npmcli/arborist", - "version": "7.5.4", + "version": "10.0.0-pre.1", "description": "Manage node_modules trees", "dependencies": { + "@gar/promise-retry": "^1.0.0", "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/fs": "^3.1.1", - "@npmcli/installed-package-contents": "^2.1.0", - "@npmcli/map-workspaces": "^3.0.2", - "@npmcli/metavuln-calculator": "^7.1.1", - "@npmcli/name-from-folder": "^2.0.0", - "@npmcli/node-gyp": "^3.0.0", - "@npmcli/package-json": "^5.1.0", - "@npmcli/query": "^3.1.0", - "@npmcli/redact": "^2.0.0", - "@npmcli/run-script": "^8.1.0", - "bin-links": "^4.0.4", - "cacache": "^18.0.3", - "common-ancestor-path": "^1.0.1", - "hosted-git-info": "^7.0.2", - "json-parse-even-better-errors": "^3.0.2", + "@npmcli/fs": "^6.0.0", + "@npmcli/installed-package-contents": "^5.0.0", + "@npmcli/map-workspaces": "^6.0.0", + "@npmcli/metavuln-calculator": "^10.0.0", + "@npmcli/name-from-folder": "^5.0.0", + "@npmcli/node-gyp": "^6.0.0", + "@npmcli/package-json": "^8.0.0", + "@npmcli/query": "^5.0.0", + "@npmcli/redact": "^5.0.0", + "@npmcli/run-script": "^11.0.0", + "bin-links": "^7.0.0", + "cacache": "^21.0.1", + "common-ancestor-path": "^2.0.0", + "diff": "^8.0.2", + "hosted-git-info": "^10.1.1", "json-stringify-nice": "^1.1.4", - "lru-cache": "^10.2.2", - "minimatch": "^9.0.4", - "nopt": "^7.2.1", - "npm-install-checks": "^6.2.0", - "npm-package-arg": "^11.0.2", - "npm-pick-manifest": "^9.0.1", - "npm-registry-fetch": "^17.0.1", - "pacote": "^18.0.6", - "parse-conflict-json": "^3.0.0", - "proc-log": "^4.2.0", - "proggy": "^2.0.0", + "lru-cache": "^11.2.1", + "minimatch": "^10.0.3", + "nopt": "^10.0.1", + "npm-install-checks": "^9.0.0", + "npm-package-arg": "^14.0.0", + "npm-pick-manifest": "^12.0.0", + "npm-registry-fetch": "^20.0.1", + "pacote": "^22.0.0", + "parse-conflict-json": "^6.0.0", + "proc-log": "^7.0.0", + "proggy": "^4.0.0", "promise-all-reject-late": "^1.0.0", "promise-call-limit": "^3.0.1", - "read-package-json-fast": "^3.0.2", "semver": "^7.3.7", - "ssri": "^10.0.6", + "ssri": "^14.0.0", "treeverse": "^3.0.0", - "walk-up-path": "^3.0.1" + "validate-npm-package-name": "^7.0.2", + "walk-up-path": "^4.0.0" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/mock-registry": "^1.0.0", + "@npmcli/template-oss": "5.1.1", "benchmark": "^2.1.4", - "minify-registry-metadata": "^3.0.0", - "nock": "^13.3.3", + "minify-registry-metadata": "^4.0.0", + "nock": "^14.0.0", "tap": "^16.3.8", "tar-stream": "^3.0.0", "tcompare": "^5.0.6" @@ -54,12 +56,13 @@ "posttest": "npm run lint", "snap": "tap", "test-proxy": "ARBORIST_TEST_PROXY=1 tap --snapshot", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", @@ -81,18 +84,22 @@ "test-env": [ "LC_ALL=sk" ], - "timeout": "360", + "node-arg": [ + "--require", + "../../scripts/disable-agent-for-tests.js" + ], + "timeout": "720", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../../scripts/template-oss/index.js" } } diff --git a/workspaces/arborist/scripts/README.md b/workspaces/arborist/scripts/README.md index 08ea92b3f3f97..6f484f633801c 100644 --- a/workspaces/arborist/scripts/README.md +++ b/workspaces/arborist/scripts/README.md @@ -5,18 +5,18 @@ around. They're untested (or, in some sense, some of them _are_ tests, albeit ad hoc ones for use when figuring out what a thing should even be), and really -moroe like spikes or examples than anything dependable or useful. +more like spikes or examples than anything dependable or useful. At some point it would be good to gather up some of this and turn it into a proper `arb` executable. * `actual.js` - Load the metadata about the modules on disk, and print it out nicely. First argument is the path to load, defaults to `cwd`. -* `virtual.js` - Load the metadata from `npm-shrinkwrap.json`, - `package-lock.json`, and/or `yarn-lock.json`, and print it out nicely. +* `virtual.js` - Load the metadata from `package-lock.json` and/or + `yarn-lock.json`, and print it out nicely. First argument is the path to load, defaults to `cwd`. -* `ideal.js` - Build the ideal tree from `package.json` and/or shrinkwrap - and lockfile metadata. First argument is the path to load, defaults to +* `ideal.js` - Build the ideal tree from `package.json` and/or lockfile + metadata. First argument is the path to load, defaults to `cwd`. You may also specify the following options: * `--quiet` - Do not print the result, * `--prefer-dedupe` - Prefer to deduplicate the tree rather than diff --git a/workspaces/arborist/scripts/benchmark/reify.js b/workspaces/arborist/scripts/benchmark/reify.js index 0dec49c363356..49cecd4405cf6 100644 --- a/workspaces/arborist/scripts/benchmark/reify.js +++ b/workspaces/arborist/scripts/benchmark/reify.js @@ -33,7 +33,7 @@ const suite = async (suite, { registry, cache }) => { // do it one time so that we have it in the shared cache // and benchmark the case where we don't have anything to do - // this doens't get pushed into promises, because we need it + // this doesn't get pushed into promises, because we need it // before we do the other ones, so we can write the lockfile. { const path = resolve(dir, 'full') diff --git a/workspaces/arborist/tap-snapshots/test/arborist/build-ideal-tree.js.test.cjs b/workspaces/arborist/tap-snapshots/test/arborist/build-ideal-tree.js.test.cjs index fb847598577b9..e7dc3416004b8 100644 --- a/workspaces/arborist/tap-snapshots/test/arborist/build-ideal-tree.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/arborist/build-ideal-tree.js.test.cjs @@ -8094,160 +8094,6 @@ ArboristNode { } ` -exports[`test/arborist/build-ideal-tree.js TAP bad shrinkwrap file > bad shrinkwrap 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/testing-peer-deps-b" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/testing-peer-deps-b", - "spec": "1", - "type": "prod", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-c" => EdgeOut { - "name": "@isaacs/testing-peer-deps-c", - "spec": "1", - "to": "node_modules/@isaacs/testing-peer-deps-c", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-b", - "path": "{CWD}/test/fixtures/testing-peer-deps-bad-sw/node_modules/@isaacs/testing-peer-deps-b", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-b/-/testing-peer-deps-b-1.2.4.tgz", - "version": "1.2.4", - }, - "@isaacs/testing-peer-deps-c" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-c", - "spec": "1", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-c", - "name": "@isaacs/testing-peer-deps-c", - "path": "{CWD}/test/fixtures/testing-peer-deps-bad-sw/node_modules/@isaacs/testing-peer-deps-c", - "peer": true, - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-c/-/testing-peer-deps-c-1.2.3.tgz", - "version": "1.2.3", - }, - "@isaacs/testing-peer-deps-d" => ArboristNode { - "children": Map { - "@isaacs/testing-peer-deps-a" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-d", - "name": "@isaacs/testing-peer-deps-a", - "spec": "2", - "type": "prod", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-b" => EdgeOut { - "name": "@isaacs/testing-peer-deps-b", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "name": "@isaacs/testing-peer-deps-a", - "path": "{CWD}/test/fixtures/testing-peer-deps-bad-sw/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-a/-/testing-peer-deps-a-2.0.0.tgz", - "version": "2.0.0", - }, - "@isaacs/testing-peer-deps-b" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "name": "@isaacs/testing-peer-deps-b", - "spec": "2", - "type": "peer", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-c" => EdgeOut { - "name": "@isaacs/testing-peer-deps-c", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-b", - "path": "{CWD}/test/fixtures/testing-peer-deps-bad-sw/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", - "peer": true, - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-b/-/testing-peer-deps-b-2.0.1.tgz", - "version": "2.0.1", - }, - "@isaacs/testing-peer-deps-c" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-c", - "spec": "2", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", - "name": "@isaacs/testing-peer-deps-c", - "path": "{CWD}/test/fixtures/testing-peer-deps-bad-sw/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", - "peer": true, - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-c/-/testing-peer-deps-c-2.0.0.tgz", - "version": "2.0.0", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/testing-peer-deps-d", - "spec": "2", - "type": "prod", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-a" => EdgeOut { - "name": "@isaacs/testing-peer-deps-a", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "type": "prod", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d", - "name": "@isaacs/testing-peer-deps-d", - "path": "{CWD}/test/fixtures/testing-peer-deps-bad-sw/node_modules/@isaacs/testing-peer-deps-d", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-d/-/testing-peer-deps-d-2.0.0.tgz", - "version": "2.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-b" => EdgeOut { - "name": "@isaacs/testing-peer-deps-b", - "spec": "1", - "to": "node_modules/@isaacs/testing-peer-deps-b", - "type": "prod", - }, - "@isaacs/testing-peer-deps-d" => EdgeOut { - "name": "@isaacs/testing-peer-deps-d", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "testing-peer-deps-bad-sw", - "packageName": "@isaacs/testing-peer-deps", - "path": "{CWD}/test/fixtures/testing-peer-deps-bad-sw", - "version": "2.0.0", -} -` - exports[`test/arborist/build-ideal-tree.js TAP bundle deps example 1, complete:true > no missing deps, because complete: true 1`] = ` ArboristNode { "children": Map { @@ -14614,7 +14460,7 @@ Object { } ` -exports[`test/arborist/build-ideal-tree.js TAP competing peerSets resolve in both root and workspace overlapping peerSets dont warn > root tree 1`] = ` +exports[`test/arborist/build-ideal-tree.js TAP competing peerSets resolve in both root and workspace overlapping peerSets do not warn > root tree 1`] = ` ArboristNode { "children": Map { "@lukekarrys/workspace-peer-dep-infinite-loop-a" => ArboristNode { @@ -14756,7 +14602,7 @@ ArboristNode { } ` -exports[`test/arborist/build-ideal-tree.js TAP competing peerSets resolve in both root and workspace overlapping peerSets dont warn > root warnings 1`] = ` +exports[`test/arborist/build-ideal-tree.js TAP competing peerSets resolve in both root and workspace overlapping peerSets do not warn > root warnings 1`] = ` Object { "code": "ERESOLVE", "current": Object { @@ -14930,7 +14776,7 @@ Object { } ` -exports[`test/arborist/build-ideal-tree.js TAP competing peerSets resolve in both root and workspace overlapping peerSets dont warn > workspace tree 1`] = ` +exports[`test/arborist/build-ideal-tree.js TAP competing peerSets resolve in both root and workspace overlapping peerSets do not warn > workspace tree 1`] = ` ArboristNode { "children": Map { "@lukekarrys/workspace-peer-dep-infinite-loop-a" => ArboristNode { @@ -15113,7 +14959,7 @@ ArboristNode { } ` -exports[`test/arborist/build-ideal-tree.js TAP competing peerSets resolve in both root and workspace overlapping peerSets dont warn > workspace warnings 1`] = ` +exports[`test/arborist/build-ideal-tree.js TAP competing peerSets resolve in both root and workspace overlapping peerSets do not warn > workspace warnings 1`] = ` Object { "code": "ERESOLVE", "current": Object { @@ -16989,6 +16835,7 @@ ArboristNode { "type": "peerOptional", }, }, + "extraneous": true, "location": "node_modules/@isaacs/test-conflicted-optional-peer-dep-meta-peer-optional/node_modules/@isaacs/test-conflicted-optional-peer-dep-peer", "name": "@isaacs/test-conflicted-optional-peer-dep-peer", "optional": true, @@ -17127,69 +16974,6 @@ ArboristNode { } ` -exports[`test/arborist/build-ideal-tree.js TAP do add shrinkwrapped deps when complete:true is set > expect resolving Promise 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "children": Map { - "abbrev" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "abbrev", - "spec": "^1.0.4", - "type": "prod", - }, - }, - "inShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "name": "abbrev", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "version": "1.0.4", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "^1.0.4", - "to": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "shrinkwrapped-dep-no-lock", - "packageName": "shrinkwrap", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-no-lock", - "version": "1.0.0", -} -` - exports[`test/arborist/build-ideal-tree.js TAP do not ERESOLVE on peerOptionals that are ignored anyway case a > must match snapshot 1`] = ` ArboristNode { "children": Map { @@ -17634,52 +17418,6 @@ ArboristNode { } ` -exports[`test/arborist/build-ideal-tree.js TAP do not add shrinkwrapped deps > expect resolving Promise 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "error": "MISSING", - "name": "abbrev", - "spec": "^1.0.4", - "to": null, - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "shrinkwrapped-dep-no-lock", - "packageName": "shrinkwrap", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-no-lock", - "version": "1.0.0", -} -` - exports[`test/arborist/build-ideal-tree.js TAP do not fail if root peerDep looser than meta peerDep > must match snapshot 1`] = ` ArboristNode { "children": Map { @@ -17753,179 +17491,7 @@ ArboristNode { } ` -exports[`test/arborist/build-ideal-tree.js TAP do not update shrinkwrapped deps > expect resolving Promise 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "children": Map { - "abbrev" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "abbrev", - "spec": "^1.0.4", - "type": "prod", - }, - }, - "inShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "name": "abbrev", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "version": "1.0.4", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "^1.0.4", - "to": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "shrinkwrapped-dep-with-lock", - "packageName": "shrinkwrap", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-with-lock", - "version": "1.0.0", -} -` - -exports[`test/arborist/build-ideal-tree.js TAP do not update shrinkwrapped deps when complete:true is set > expect resolving Promise 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "children": Map { - "abbrev" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "abbrev", - "spec": "^1.0.4", - "type": "prod", - }, - }, - "inShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "name": "abbrev", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "version": "1.0.4", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "^1.0.4", - "to": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "shrinkwrapped-dep-with-lock", - "packageName": "shrinkwrap", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-with-lock", - "version": "1.0.0", -} -` - -exports[`test/arborist/build-ideal-tree.js TAP do not update shrinkwrapped deps, ignore lockfile > expect resolving Promise 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "error": "MISSING", - "name": "abbrev", - "spec": "^1.0.4", - "to": null, - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "shrinkwrapped-dep-with-lock", - "packageName": "shrinkwrap", - "path": "{CWD}/test/fixtures/shrinkwrapped-dep-with-lock", - "version": "1.0.0", -} -` - -exports[`test/arborist/build-ideal-tree.js TAP dont get confused if root matches duped metadep > must match snapshot 1`] = ` +exports[`test/arborist/build-ideal-tree.js TAP do not get confused if root matches duped metadep > must match snapshot 1`] = ` ArboristNode { "children": Map { "test-root-matches-metadep" => ArboristNode { @@ -74672,6 +74238,315 @@ exports[`test/arborist/build-ideal-tree.js TAP more peer dep conflicts metadeps Array [] ` +exports[`test/arborist/build-ideal-tree.js TAP more peer dep conflicts peerDep replacement of top level dep with different version resulting detached top level dep > default result 1`] = ` +ArboristNode { + "children": Map { + "@test/a" => ArboristNode { + "dev": true, + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "@test/a", + "spec": "^1.1.0", + "type": "dev", + }, + EdgeIn { + "from": "node_modules/@test/b", + "name": "@test/a", + "spec": "1.1.0", + "type": "peer", + }, + }, + "edgesOut": Map { + "@test/b" => EdgeOut { + "name": "@test/b", + "spec": "1.1.0", + "to": "node_modules/@test/b", + "type": "peerOptional", + }, + "@test/c" => EdgeOut { + "name": "@test/c", + "spec": "1.1.0", + "to": null, + "type": "peerOptional", + }, + "lodash" => EdgeOut { + "name": "lodash", + "spec": "^4.17.0", + "to": null, + "type": "peerOptional", + }, + "uniq" => EdgeOut { + "name": "uniq", + "spec": "^1.0.0", + "to": null, + "type": "peerOptional", + }, + }, + "location": "node_modules/@test/a", + "name": "@test/a", + "path": "{CWD}/test/arborist/tap-testdir-build-ideal-tree-more-peer-dep-conflicts-peerDep-replacement-of-top-level-dep-with-different-version-resulting-detached-top-level-dep/node_modules/@test/a", + "resolved": "http://localhost:4873/@test/a/-/a-1.1.0.tgz", + "version": "1.1.0", + }, + "@test/b" => ArboristNode { + "dev": true, + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "@test/b", + "spec": "1.1.0", + "type": "dev", + }, + EdgeIn { + "from": "node_modules/@test/a", + "name": "@test/b", + "spec": "1.1.0", + "type": "peerOptional", + }, + }, + "edgesOut": Map { + "@test/a" => EdgeOut { + "name": "@test/a", + "spec": "1.1.0", + "to": "node_modules/@test/a", + "type": "peer", + }, + }, + "location": "node_modules/@test/b", + "name": "@test/b", + "path": "{CWD}/test/arborist/tap-testdir-build-ideal-tree-more-peer-dep-conflicts-peerDep-replacement-of-top-level-dep-with-different-version-resulting-detached-top-level-dep/node_modules/@test/b", + "resolved": "http://localhost:4873/@test/b/-/b-1.1.0.tgz", + "version": "1.1.0", + }, + }, + "edgesOut": Map { + "@test/a" => EdgeOut { + "name": "@test/a", + "spec": "^1.1.0", + "to": "node_modules/@test/a", + "type": "dev", + }, + "@test/b" => EdgeOut { + "name": "@test/b", + "spec": "1.1.0", + "to": "node_modules/@test/b", + "type": "dev", + }, + }, + "isProjectRoot": true, + "location": "", + "name": "tap-testdir-build-ideal-tree-more-peer-dep-conflicts-peerDep-replacement-of-top-level-dep-with-different-version-resulting-detached-top-level-dep", + "path": "{CWD}/test/arborist/tap-testdir-build-ideal-tree-more-peer-dep-conflicts-peerDep-replacement-of-top-level-dep-with-different-version-resulting-detached-top-level-dep", +} +` + +exports[`test/arborist/build-ideal-tree.js TAP more peer dep conflicts peerDep replacement of top level dep with different version resulting detached top level dep > force result 1`] = ` +ArboristNode { + "children": Map { + "@test/a" => ArboristNode { + "dev": true, + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "@test/a", + "spec": "^1.1.0", + "type": "dev", + }, + EdgeIn { + "from": "node_modules/@test/b", + "name": "@test/a", + "spec": "1.1.0", + "type": "peer", + }, + }, + "edgesOut": Map { + "@test/b" => EdgeOut { + "name": "@test/b", + "spec": "1.1.0", + "to": "node_modules/@test/b", + "type": "peerOptional", + }, + "@test/c" => EdgeOut { + "name": "@test/c", + "spec": "1.1.0", + "to": null, + "type": "peerOptional", + }, + "lodash" => EdgeOut { + "name": "lodash", + "spec": "^4.17.0", + "to": null, + "type": "peerOptional", + }, + "uniq" => EdgeOut { + "name": "uniq", + "spec": "^1.0.0", + "to": null, + "type": "peerOptional", + }, + }, + "location": "node_modules/@test/a", + "name": "@test/a", + "path": "{CWD}/test/arborist/tap-testdir-build-ideal-tree-more-peer-dep-conflicts-peerDep-replacement-of-top-level-dep-with-different-version-resulting-detached-top-level-dep/node_modules/@test/a", + "resolved": "http://localhost:4873/@test/a/-/a-1.1.0.tgz", + "version": "1.1.0", + }, + "@test/b" => ArboristNode { + "dev": true, + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "@test/b", + "spec": "1.1.0", + "type": "dev", + }, + EdgeIn { + "from": "node_modules/@test/a", + "name": "@test/b", + "spec": "1.1.0", + "type": "peerOptional", + }, + }, + "edgesOut": Map { + "@test/a" => EdgeOut { + "name": "@test/a", + "spec": "1.1.0", + "to": "node_modules/@test/a", + "type": "peer", + }, + }, + "location": "node_modules/@test/b", + "name": "@test/b", + "path": "{CWD}/test/arborist/tap-testdir-build-ideal-tree-more-peer-dep-conflicts-peerDep-replacement-of-top-level-dep-with-different-version-resulting-detached-top-level-dep/node_modules/@test/b", + "resolved": "http://localhost:4873/@test/b/-/b-1.1.0.tgz", + "version": "1.1.0", + }, + }, + "edgesOut": Map { + "@test/a" => EdgeOut { + "name": "@test/a", + "spec": "^1.1.0", + "to": "node_modules/@test/a", + "type": "dev", + }, + "@test/b" => EdgeOut { + "name": "@test/b", + "spec": "1.1.0", + "to": "node_modules/@test/b", + "type": "dev", + }, + }, + "isProjectRoot": true, + "location": "", + "name": "tap-testdir-build-ideal-tree-more-peer-dep-conflicts-peerDep-replacement-of-top-level-dep-with-different-version-resulting-detached-top-level-dep", + "path": "{CWD}/test/arborist/tap-testdir-build-ideal-tree-more-peer-dep-conflicts-peerDep-replacement-of-top-level-dep-with-different-version-resulting-detached-top-level-dep", +} +` + +exports[`test/arborist/build-ideal-tree.js TAP more peer dep conflicts peerDep replacement of top level dep with different version resulting detached top level dep > strict result 1`] = ` +ArboristNode { + "children": Map { + "@test/a" => ArboristNode { + "dev": true, + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "@test/a", + "spec": "^1.1.0", + "type": "dev", + }, + EdgeIn { + "from": "node_modules/@test/b", + "name": "@test/a", + "spec": "1.1.0", + "type": "peer", + }, + }, + "edgesOut": Map { + "@test/b" => EdgeOut { + "name": "@test/b", + "spec": "1.1.0", + "to": "node_modules/@test/b", + "type": "peerOptional", + }, + "@test/c" => EdgeOut { + "name": "@test/c", + "spec": "1.1.0", + "to": null, + "type": "peerOptional", + }, + "lodash" => EdgeOut { + "name": "lodash", + "spec": "^4.17.0", + "to": null, + "type": "peerOptional", + }, + "uniq" => EdgeOut { + "name": "uniq", + "spec": "^1.0.0", + "to": null, + "type": "peerOptional", + }, + }, + "location": "node_modules/@test/a", + "name": "@test/a", + "path": "{CWD}/test/arborist/tap-testdir-build-ideal-tree-more-peer-dep-conflicts-peerDep-replacement-of-top-level-dep-with-different-version-resulting-detached-top-level-dep/node_modules/@test/a", + "resolved": "http://localhost:4873/@test/a/-/a-1.1.0.tgz", + "version": "1.1.0", + }, + "@test/b" => ArboristNode { + "dev": true, + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "@test/b", + "spec": "1.1.0", + "type": "dev", + }, + EdgeIn { + "from": "node_modules/@test/a", + "name": "@test/b", + "spec": "1.1.0", + "type": "peerOptional", + }, + }, + "edgesOut": Map { + "@test/a" => EdgeOut { + "name": "@test/a", + "spec": "1.1.0", + "to": "node_modules/@test/a", + "type": "peer", + }, + }, + "location": "node_modules/@test/b", + "name": "@test/b", + "path": "{CWD}/test/arborist/tap-testdir-build-ideal-tree-more-peer-dep-conflicts-peerDep-replacement-of-top-level-dep-with-different-version-resulting-detached-top-level-dep/node_modules/@test/b", + "resolved": "http://localhost:4873/@test/b/-/b-1.1.0.tgz", + "version": "1.1.0", + }, + }, + "edgesOut": Map { + "@test/a" => EdgeOut { + "name": "@test/a", + "spec": "^1.1.0", + "to": "node_modules/@test/a", + "type": "dev", + }, + "@test/b" => EdgeOut { + "name": "@test/b", + "spec": "1.1.0", + "to": "node_modules/@test/b", + "type": "dev", + }, + }, + "isProjectRoot": true, + "location": "", + "name": "tap-testdir-build-ideal-tree-more-peer-dep-conflicts-peerDep-replacement-of-top-level-dep-with-different-version-resulting-detached-top-level-dep", + "path": "{CWD}/test/arborist/tap-testdir-build-ideal-tree-more-peer-dep-conflicts-peerDep-replacement-of-top-level-dep-with-different-version-resulting-detached-top-level-dep", +} +` + exports[`test/arborist/build-ideal-tree.js TAP more peer dep conflicts prod dep directly on conflicted peer, full peer set, newer > force result 1`] = ` ArboristNode { "children": Map { @@ -77868,11 +77743,34 @@ ArboristNode { exports[`test/arborist/build-ideal-tree.js TAP optional dependency failures > optional-dep-enotarget 1`] = ` ArboristNode { + "children": Map { + "tap" => ArboristNode { + "edgesIn": Set { + EdgeIn { + "error": "INVALID", + "from": "", + "name": "tap", + "spec": "9999.0000.9999", + "type": "optional", + }, + }, + "errors": Array [ + Object { + "code": "ETARGET", + }, + ], + "location": "node_modules/tap", + "name": "tap", + "optional": true, + "path": "{CWD}/test/fixtures/optional-dep-enotarget/node_modules/tap", + }, + }, "edgesOut": Map { "tap" => EdgeOut { + "error": "INVALID", "name": "tap", "spec": "9999.0000.9999", - "to": null, + "to": "node_modules/tap", "type": "optional", }, }, @@ -77887,11 +77785,32 @@ ArboristNode { exports[`test/arborist/build-ideal-tree.js TAP optional dependency failures > optional-dep-missing 1`] = ` ArboristNode { + "children": Map { + "@isaacs/this-does-not-exist-at-all" => ArboristNode { + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "@isaacs/this-does-not-exist-at-all", + "spec": "*", + "type": "optional", + }, + }, + "errors": Array [ + Object { + "code": "E404", + }, + ], + "location": "node_modules/@isaacs/this-does-not-exist-at-all", + "name": "@isaacs/this-does-not-exist-at-all", + "optional": true, + "path": "{CWD}/test/fixtures/optional-dep-missing/node_modules/@isaacs/this-does-not-exist-at-all", + }, + }, "edgesOut": Map { "@isaacs/this-does-not-exist-at-all" => EdgeOut { "name": "@isaacs/this-does-not-exist-at-all", "spec": "*", - "to": null, + "to": "node_modules/@isaacs/this-does-not-exist-at-all", "type": "optional", }, }, @@ -77906,11 +77825,60 @@ ArboristNode { exports[`test/arborist/build-ideal-tree.js TAP optional dependency failures > optional-metadep-enotarget 1`] = ` ArboristNode { + "children": Map { + "@isaacs/prod-dep-enotarget" => ArboristNode { + "children": Map { + "tap" => ArboristNode { + "edgesIn": Set { + EdgeIn { + "error": "INVALID", + "from": "node_modules/@isaacs/prod-dep-enotarget", + "name": "tap", + "spec": "9999.0000.9999", + "type": "prod", + }, + }, + "errors": Array [ + Object { + "code": "ETARGET", + }, + ], + "location": "node_modules/@isaacs/prod-dep-enotarget/node_modules/tap", + "name": "tap", + "optional": true, + "path": "{CWD}/test/fixtures/optional-metadep-enotarget/node_modules/@isaacs/prod-dep-enotarget/node_modules/tap", + }, + }, + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "@isaacs/prod-dep-enotarget", + "spec": "*", + "type": "optional", + }, + }, + "edgesOut": Map { + "tap" => EdgeOut { + "error": "INVALID", + "name": "tap", + "spec": "9999.0000.9999", + "to": "node_modules/@isaacs/prod-dep-enotarget/node_modules/tap", + "type": "prod", + }, + }, + "location": "node_modules/@isaacs/prod-dep-enotarget", + "name": "@isaacs/prod-dep-enotarget", + "optional": true, + "path": "{CWD}/test/fixtures/optional-metadep-enotarget/node_modules/@isaacs/prod-dep-enotarget", + "resolved": "https://registry.npmjs.org/@isaacs/prod-dep-enotarget/-/prod-dep-enotarget-1.0.0.tgz", + "version": "1.0.0", + }, + }, "edgesOut": Map { "@isaacs/prod-dep-enotarget" => EdgeOut { "name": "@isaacs/prod-dep-enotarget", "spec": "*", - "to": null, + "to": "node_modules/@isaacs/prod-dep-enotarget", "type": "optional", }, }, @@ -77924,11 +77892,58 @@ ArboristNode { exports[`test/arborist/build-ideal-tree.js TAP optional dependency failures > optional-metadep-missing 1`] = ` ArboristNode { + "children": Map { + "@isaacs/testing-prod-dep-metadata-missing" => ArboristNode { + "children": Map { + "@isaacs/this-does-not-exist-at-all" => ArboristNode { + "edgesIn": Set { + EdgeIn { + "from": "node_modules/@isaacs/testing-prod-dep-metadata-missing", + "name": "@isaacs/this-does-not-exist-at-all", + "spec": "*", + "type": "prod", + }, + }, + "errors": Array [ + Object { + "code": "E404", + }, + ], + "location": "node_modules/@isaacs/testing-prod-dep-metadata-missing/node_modules/@isaacs/this-does-not-exist-at-all", + "name": "@isaacs/this-does-not-exist-at-all", + "optional": true, + "path": "{CWD}/test/fixtures/optional-metadep-missing/node_modules/@isaacs/testing-prod-dep-metadata-missing/node_modules/@isaacs/this-does-not-exist-at-all", + }, + }, + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "@isaacs/testing-prod-dep-metadata-missing", + "spec": "*", + "type": "optional", + }, + }, + "edgesOut": Map { + "@isaacs/this-does-not-exist-at-all" => EdgeOut { + "name": "@isaacs/this-does-not-exist-at-all", + "spec": "*", + "to": "node_modules/@isaacs/testing-prod-dep-metadata-missing/node_modules/@isaacs/this-does-not-exist-at-all", + "type": "prod", + }, + }, + "location": "node_modules/@isaacs/testing-prod-dep-metadata-missing", + "name": "@isaacs/testing-prod-dep-metadata-missing", + "optional": true, + "path": "{CWD}/test/fixtures/optional-metadep-missing/node_modules/@isaacs/testing-prod-dep-metadata-missing", + "resolved": "https://registry.npmjs.org/@isaacs/testing-prod-dep-metadata-missing/-/testing-prod-dep-metadata-missing-1.0.0.tgz", + "version": "1.0.0", + }, + }, "edgesOut": Map { "@isaacs/testing-prod-dep-metadata-missing" => EdgeOut { "name": "@isaacs/testing-prod-dep-metadata-missing", "spec": "*", - "to": null, + "to": "node_modules/@isaacs/testing-prod-dep-metadata-missing", "type": "optional", }, }, @@ -97222,6 +97237,7 @@ ArboristNode { "type": "peerOptional", }, }, + "extraneous": true, "location": "node_modules/abbrev", "name": "abbrev", "optional": true, @@ -97447,7 +97463,7 @@ ArboristNode { } ` -exports[`test/arborist/build-ideal-tree.js TAP push conflicted peer deps deeper in to the tree to solve > must match snapshot 1`] = ` +exports[`test/arborist/build-ideal-tree.js TAP push conflicted peer deps deeper into the tree to solve > must match snapshot 1`] = ` ArboristNode { "children": Map { "@isaacs/testing-peer-dep-conflict-chain-a" => ArboristNode { @@ -97921,6 +97937,20 @@ ArboristNode { } ` +exports[`test/arborist/build-ideal-tree.js TAP should take devEngines in account > must match snapshot 1`] = ` +{ + "name": "empty-update", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "empty-update" + } + } +} + +` + exports[`test/arborist/build-ideal-tree.js TAP store files with a custom indenting > must match snapshot 1`] = ` { "name": "tab-indented-package-json", @@ -108880,7 +108910,7 @@ ArboristNode { } ` -exports[`test/arborist/build-ideal-tree.js TAP tap vs react15 with legacy shrinkwrap > tap collision with legacy sw file 1`] = ` +exports[`test/arborist/build-ideal-tree.js TAP tap vs react15 with legacy lockfile > tap collision with legacy lockfile 1`] = ` ArboristNode { "children": Map { "@babel/code-frame" => ArboristNode { @@ -159873,6 +159903,7 @@ ArboristNode { "location": "node_modules/foo", "name": "foo", "path": "{CWD}/test/arborist/tap-testdir-build-ideal-tree-workspaces-should-allow-cyclic-peer-dependencies-between-workspaces-and-packages-from-a-repository/node_modules/foo", + "resolved": "https://registry.npmjs.org/foo/-/foo-1.0.0.tgz", "version": "1.0.0", }, "workspace-a" => ArboristLink { diff --git a/workspaces/arborist/tap-snapshots/test/arborist/load-actual.js.test.cjs b/workspaces/arborist/tap-snapshots/test/arborist/load-actual.js.test.cjs index 35ba9f7cafa84..069478e5c0cb9 100644 --- a/workspaces/arborist/tap-snapshots/test/arborist/load-actual.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/arborist/load-actual.js.test.cjs @@ -1627,7 +1627,7 @@ ArboristNode { "name": "full-git-url", "packageName": "abbrev", "path": "install-types/node_modules/full-git-url", - "resolved": "git+ssh://git@github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", + "resolved": "git+https://github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", "version": "1.1.1", }, "ghshort" => ArboristNode { @@ -3903,7 +3903,7 @@ ArboristNode { } ` -exports[`test/arborist/load-actual.js TAP load workspaces when loading from hidding lockfile > actual tree 1`] = ` +exports[`test/arborist/load-actual.js TAP load workspaces when loading from hidden lockfile > actual tree 1`] = ` ArboristNode { "children": Map { "a" => ArboristLink { @@ -3911,15 +3911,15 @@ ArboristNode { EdgeIn { "from": "", "name": "a", - "spec": "file:{CWD}/test/arborist/tap-testdir-load-actual-load-workspaces-when-loading-from-hidding-lockfile/packages/a", + "spec": "file:{CWD}/test/arborist/tap-testdir-load-actual-load-workspaces-when-loading-from-hidden-lockfile/packages/a", "type": "workspace", }, }, "isWorkspace": true, "location": "node_modules/a", "name": "a", - "path": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidding-lockfile/node_modules/a", - "realpath": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidding-lockfile/packages/a", + "path": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidden-lockfile/node_modules/a", + "realpath": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidden-lockfile/packages/a", "resolved": "file:../packages/a", "target": ArboristNode { "location": "packages/a", @@ -3931,15 +3931,15 @@ ArboristNode { EdgeIn { "from": "", "name": "b", - "spec": "file:{CWD}/test/arborist/tap-testdir-load-actual-load-workspaces-when-loading-from-hidding-lockfile/packages/b", + "spec": "file:{CWD}/test/arborist/tap-testdir-load-actual-load-workspaces-when-loading-from-hidden-lockfile/packages/b", "type": "workspace", }, }, "isWorkspace": true, "location": "node_modules/b", "name": "b", - "path": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidding-lockfile/node_modules/b", - "realpath": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidding-lockfile/packages/b", + "path": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidden-lockfile/node_modules/b", + "realpath": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidden-lockfile/packages/b", "resolved": "file:../packages/b", "target": ArboristNode { "location": "packages/b", @@ -3950,13 +3950,13 @@ ArboristNode { "edgesOut": Map { "a" => EdgeOut { "name": "a", - "spec": "file:{CWD}/test/arborist/tap-testdir-load-actual-load-workspaces-when-loading-from-hidding-lockfile/packages/a", + "spec": "file:{CWD}/test/arborist/tap-testdir-load-actual-load-workspaces-when-loading-from-hidden-lockfile/packages/a", "to": "node_modules/a", "type": "workspace", }, "b" => EdgeOut { "name": "b", - "spec": "file:{CWD}/test/arborist/tap-testdir-load-actual-load-workspaces-when-loading-from-hidding-lockfile/packages/b", + "spec": "file:{CWD}/test/arborist/tap-testdir-load-actual-load-workspaces-when-loading-from-hidden-lockfile/packages/b", "to": "node_modules/b", "type": "workspace", }, @@ -3966,21 +3966,21 @@ ArboristNode { "isWorkspace": true, "location": "packages/a", "name": "a", - "path": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidding-lockfile/packages/a", + "path": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidden-lockfile/packages/a", "version": "1.2.3", }, ArboristNode { "isWorkspace": true, "location": "packages/b", "name": "b", - "path": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidding-lockfile/packages/b", + "path": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidden-lockfile/packages/b", "version": "1.2.3", }, }, "isProjectRoot": true, "location": "", - "name": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidding-lockfile", - "path": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidding-lockfile", + "name": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidden-lockfile", + "path": "tap-testdir-load-actual-load-workspaces-when-loading-from-hidden-lockfile", "workspaces": Map { "a" => "packages/a", "b" => "packages/b", @@ -6392,237 +6392,6 @@ ArboristNode { } ` -exports[`test/arborist/load-actual.js TAP shake out Link target timing issue > loaded tree 1`] = ` -ArboristNode { - "children": Map { - "@scope/y" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@scope/y", - "spec": "*", - "type": "prod", - }, - }, - "edgesOut": Map { - "foo" => EdgeOut { - "name": "foo", - "spec": "*", - "to": "node_modules/foo", - "type": "prod", - }, - }, - "location": "node_modules/@scope/y", - "name": "@scope/y", - "path": "selflink/node_modules/@scope/y", - "version": "1.2.3", - }, - "@scope/z" => ArboristNode { - "children": Map { - "glob" => ArboristLink { - "dev": true, - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@scope/z", - "name": "glob", - "spec": "4", - "type": "prod", - }, - }, - "extraneous": true, - "location": "node_modules/@scope/z/node_modules/glob", - "name": "glob", - "optional": true, - "path": "selflink/node_modules/@scope/z/node_modules/glob", - "peer": true, - "realpath": "selflink/node_modules/foo/node_modules/glob", - "resolved": "file:../../../foo/node_modules/glob", - "target": ArboristNode { - "children": Map { - "graceful-fs" => ArboristNode { - "dev": true, - "extraneous": true, - "location": "node_modules/foo/node_modules/glob/node_modules/graceful-fs", - "name": "graceful-fs", - "optional": true, - "path": "selflink/node_modules/foo/node_modules/glob/node_modules/graceful-fs", - "peer": true, - "version": "3.0.2", - }, - "inherits" => ArboristNode { - "dev": true, - "extraneous": true, - "location": "node_modules/foo/node_modules/glob/node_modules/inherits", - "name": "inherits", - "optional": true, - "path": "selflink/node_modules/foo/node_modules/glob/node_modules/inherits", - "peer": true, - "version": "2.0.1", - }, - "minimatch" => ArboristNode { - "children": Map { - "lru-cache" => ArboristNode { - "dev": true, - "extraneous": true, - "location": "node_modules/foo/node_modules/glob/node_modules/minimatch/node_modules/lru-cache", - "name": "lru-cache", - "optional": true, - "path": "selflink/node_modules/foo/node_modules/glob/node_modules/minimatch/node_modules/lru-cache", - "peer": true, - "version": "2.5.0", - }, - "sigmund" => ArboristNode { - "dev": true, - "extraneous": true, - "location": "node_modules/foo/node_modules/glob/node_modules/minimatch/node_modules/sigmund", - "name": "sigmund", - "optional": true, - "path": "selflink/node_modules/foo/node_modules/glob/node_modules/minimatch/node_modules/sigmund", - "peer": true, - "version": "1.0.0", - }, - }, - "dev": true, - "extraneous": true, - "location": "node_modules/foo/node_modules/glob/node_modules/minimatch", - "name": "minimatch", - "optional": true, - "path": "selflink/node_modules/foo/node_modules/glob/node_modules/minimatch", - "peer": true, - "version": "1.0.0", - }, - "once" => ArboristNode { - "dev": true, - "extraneous": true, - "location": "node_modules/foo/node_modules/glob/node_modules/once", - "name": "once", - "optional": true, - "path": "selflink/node_modules/foo/node_modules/glob/node_modules/once", - "peer": true, - "version": "1.3.0", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "node_modules/foo", - "name": "glob", - "spec": "4", - "type": "prod", - }, - }, - "location": "node_modules/foo/node_modules/glob", - "name": "glob", - "path": "selflink/node_modules/foo/node_modules/glob", - "version": "4.0.5", - }, - "version": "4.0.5", - }, - }, - "dev": true, - "edgesOut": Map { - "glob" => EdgeOut { - "name": "glob", - "spec": "4", - "to": "node_modules/@scope/z/node_modules/glob", - "type": "prod", - }, - }, - "extraneous": true, - "location": "node_modules/@scope/z", - "name": "@scope/z", - "optional": true, - "path": "selflink/node_modules/@scope/z", - "peer": true, - "version": "1.2.3", - }, - "foo" => ArboristNode { - "children": Map { - "glob" => ArboristNode { - "location": "node_modules/foo/node_modules/glob", - }, - "selflink" => ArboristLink { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/foo", - "name": "selflink", - "spec": "*", - "type": "prod", - }, - }, - "location": "node_modules/foo/node_modules/selflink", - "name": "selflink", - "path": "selflink/node_modules/foo/node_modules/selflink", - "realpath": "selflink", - "resolved": "file:../../..", - "target": ArboristNode { - "location": "", - }, - "version": "1.2.3", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "foo", - "spec": "*", - "type": "prod", - }, - EdgeIn { - "from": "node_modules/@scope/y", - "name": "foo", - "spec": "*", - "type": "prod", - }, - }, - "edgesOut": Map { - "glob" => EdgeOut { - "name": "glob", - "spec": "4", - "to": "node_modules/foo/node_modules/glob", - "type": "prod", - }, - "selflink" => EdgeOut { - "name": "selflink", - "spec": "*", - "to": "node_modules/foo/node_modules/selflink", - "type": "prod", - }, - }, - "location": "node_modules/foo", - "name": "foo", - "path": "selflink/node_modules/foo", - "version": "1.2.3", - }, - }, - "edgesOut": Map { - "@scope/x" => EdgeOut { - "error": "MISSING", - "name": "@scope/x", - "spec": "*", - "to": null, - "type": "prod", - }, - "@scope/y" => EdgeOut { - "name": "@scope/y", - "spec": "*", - "to": "node_modules/@scope/y", - "type": "prod", - }, - "foo" => EdgeOut { - "name": "foo", - "spec": "*", - "to": "node_modules/foo", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "selflink", - "path": "selflink", - "version": "1.2.3", -} -` - exports[`test/arborist/load-actual.js TAP symlinked-node-modules/example > loaded tree 1`] = ` ArboristNode { "children": Map { @@ -6691,6 +6460,7 @@ ArboristNode { "type": "prod", }, }, + "extraneous": true, "fsChildren": Set { ArboristNode { "dev": true, @@ -6744,6 +6514,7 @@ ArboristNode { "type": "prod", }, }, + "extraneous": true, "fsChildren": Set { ArboristNode { "dev": true, diff --git a/workspaces/arborist/tap-snapshots/test/arborist/load-virtual.js.test.cjs b/workspaces/arborist/tap-snapshots/test/arborist/load-virtual.js.test.cjs index c0210aabc54f3..99be626625caa 100644 --- a/workspaces/arborist/tap-snapshots/test/arborist/load-virtual.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/arborist/load-virtual.js.test.cjs @@ -259,6 +259,7 @@ ArboristNode { "type": "peerOptional", }, }, + "extraneous": true, "location": "node_modules/semver", "name": "semver", "optional": true, @@ -13530,7 +13531,7 @@ ArboristNode { "location": "node_modules/full-git-url", "name": "full-git-url", "path": "{CWD}/test/fixtures/install-types/node_modules/full-git-url", - "resolved": "git+ssh://git@github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", + "resolved": "git+https://github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", }, "ghshort" => ArboristNode { "edgesIn": Set { @@ -14219,7 +14220,7 @@ ArboristNode { "location": "node_modules/full-git-url", "name": "full-git-url", "path": "{CWD}/test/fixtures/install-types/node_modules/full-git-url", - "resolved": "git+ssh://git@github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", + "resolved": "git+https://github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", }, "ghshort" => ArboristNode { "edgesIn": Set { @@ -14665,7 +14666,7 @@ ArboristNode { } ` -exports[`test/arborist/load-virtual.js TAP load from npm-shrinkwrap.json > loaded virtual tree from fixture 1`] = ` +exports[`test/arborist/load-virtual.js TAP load without a root package.json is fine > loaded virtual no package json 1`] = ` ArboristNode { "children": Map { "abbrev" => ArboristNode { @@ -14684,7 +14685,7 @@ ArboristNode { }, "location": "node_modules/abbrev/node_modules/@scope/name/node_modules/@otherscope/othername", "name": "@otherscope/othername", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/abbrev/node_modules/@scope/name/node_modules/@otherscope/othername", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/abbrev/node_modules/@scope/name/node_modules/@otherscope/othername", "resolved": "fake resolved value", }, }, @@ -14706,20 +14707,12 @@ ArboristNode { }, "location": "node_modules/abbrev/node_modules/@scope/name", "name": "@scope/name", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/abbrev/node_modules/@scope/name", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "abbrev", - "spec": "^1.1.1", - "type": "prod", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/abbrev/node_modules/@scope/name", }, }, "location": "node_modules/abbrev", "name": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/abbrev", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/abbrev", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", "version": "1.1.1", }, @@ -14735,7 +14728,7 @@ ArboristNode { "location": "node_modules/balanced-match", "name": "balanced-match", "optional": true, - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/balanced-match", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/balanced-match", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", "version": "1.0.0", }, @@ -14765,7 +14758,7 @@ ArboristNode { "location": "node_modules/brace-expansion", "name": "brace-expansion", "optional": true, - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/brace-expansion", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/brace-expansion", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "version": "1.1.11", }, @@ -14795,7 +14788,7 @@ ArboristNode { }, "location": "node_modules/bundler/node_modules/a", "name": "a", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/bundler/node_modules/a", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/bundler/node_modules/a", "resolved": "https://registry.internal/a/-/a-1.2.3.tgz", "version": "1.2.3", }, @@ -14820,7 +14813,7 @@ ArboristNode { }, "location": "node_modules/bundler/node_modules/b", "name": "b", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/bundler/node_modules/b", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/bundler/node_modules/b", "resolved": "https://registry.internal/b/-/b-1.2.3.tgz", "version": "1.2.3", }, @@ -14837,19 +14830,11 @@ ArboristNode { }, "location": "node_modules/bundler/node_modules/c", "name": "c", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/bundler/node_modules/c", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/bundler/node_modules/c", "resolved": "https://registry.internal/c/-/c-1.2.3.tgz", "version": "1.2.3", }, }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "bundler", - "spec": "1.2.3", - "type": "prod", - }, - }, "edgesOut": Map { "a" => EdgeOut { "name": "a", @@ -14860,7 +14845,7 @@ ArboristNode { }, "location": "node_modules/bundler", "name": "bundler", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/bundler", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/bundler", "resolved": "https://registry.internal/bundler/-/bundler-1.2.3.tgz", "version": "1.2.3", }, @@ -14876,7 +14861,7 @@ ArboristNode { "location": "node_modules/concat-map", "name": "concat-map", "optional": true, - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/concat-map", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/concat-map", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "version": "0.0.1", }, @@ -14892,42 +14877,26 @@ ArboristNode { "location": "node_modules/fs.realpath", "name": "fs.realpath", "optional": true, - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/fs.realpath", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/fs.realpath", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "version": "1.0.0", }, "full-git-url" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "full-git-url", - "spec": "git+https://github.com/isaacs/abbrev-js.git", - "type": "prod", - }, - }, "location": "node_modules/full-git-url", "name": "full-git-url", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/full-git-url", - "resolved": "git+ssh://git@github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/full-git-url", + "resolved": "git+https://github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", }, "ghshort" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "ghshort", - "spec": "github:isaacs/abbrev-js", - "type": "prod", - }, - }, "location": "node_modules/ghshort", "name": "ghshort", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/ghshort", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/ghshort", "resolved": "git+ssh://git@github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", }, "ghtgz" => ArboristNode { "location": "node_modules/ghtgz", "name": "ghtgz", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/ghtgz", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/ghtgz", "resolved": "https://codeload.github.com/isaacs/abbrev-js/tar.gz/a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", }, "glob" => ArboristNode { @@ -14980,7 +14949,7 @@ ArboristNode { "location": "node_modules/glob", "name": "glob", "optional": true, - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/glob", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/glob", "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", "version": "7.1.4", }, @@ -15010,7 +14979,7 @@ ArboristNode { "location": "node_modules/inflight", "name": "inflight", "optional": true, - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/inflight", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/inflight", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "version": "1.0.6", }, @@ -15026,7 +14995,7 @@ ArboristNode { "location": "node_modules/inherits", "name": "inherits", "optional": true, - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/inherits", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/inherits", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "version": "2.0.4", }, @@ -15050,23 +15019,15 @@ ArboristNode { "location": "node_modules/minimatch", "name": "minimatch", "optional": true, - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/minimatch", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/minimatch", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "version": "3.0.4", }, "old" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "old", - "spec": "npm:abbrev@^1.0.3", - "type": "prod", - }, - }, "location": "node_modules/old", "name": "old", "packageName": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/old", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/old", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.3.tgz", "version": "1.0.3", }, @@ -15095,8 +15056,8 @@ ArboristNode { }, "location": "node_modules/once", "name": "once", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/once", - "resolved": "file:{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/once-1.4.0.tgz", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/once", + "resolved": "file:{CWD}/test/fixtures/install-types-sw-only/once-1.4.0.tgz", "version": "1.4.0", }, "path-is-absolute" => ArboristNode { @@ -15111,60 +15072,36 @@ ArboristNode { "location": "node_modules/path-is-absolute", "name": "path-is-absolute", "optional": true, - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/path-is-absolute", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/path-is-absolute", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "version": "1.0.1", }, "pinned" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "pinned", - "spec": "npm:abbrev@^1.1.1", - "type": "prod", - }, - }, "location": "node_modules/pinned", "name": "pinned", "packageName": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/pinned", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/pinned", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", "version": "1.1.1", }, "really-bad-invalid" => ArboristNode { "location": "node_modules/really-bad-invalid", "name": "really-bad-invalid", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/really-bad-invalid", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/really-bad-invalid", }, "reg" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "reg", - "spec": "npm:abbrev@^1.1.1", - "type": "prod", - }, - }, "location": "node_modules/reg", "name": "reg", "packageName": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/reg", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/reg", "resolved": "https://localhost:8080/abbrev/-/abbrev-1.1.1.tgz", "version": "1.1.1", }, "remote" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "remote", - "spec": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", - "type": "prod", - }, - }, "location": "node_modules/remote", "name": "remote", "packageName": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/remote", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/remote", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", "version": "1.1.1", }, @@ -15179,24 +15116,16 @@ ArboristNode { }, "location": "node_modules/rimraf", "name": "rimraf", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/rimraf", - "resolved": "file:{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/rimraf-2.6.3.tgz", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/rimraf", + "resolved": "file:{CWD}/test/fixtures/install-types-sw-only/rimraf-2.6.3.tgz", "version": "2.6.3", }, "symlink" => ArboristLink { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "symlink", - "spec": "file:./abbrev-link-target", - "type": "prod", - }, - }, "location": "node_modules/symlink", "name": "symlink", "packageName": "abbrev-link-target", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/symlink", - "realpath": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/abbrev-link-target", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/symlink", + "realpath": "{CWD}/test/fixtures/install-types-sw-only/abbrev-link-target", "resolved": "file:../abbrev-link-target", "target": ArboristNode { "location": "abbrev-link-target", @@ -15206,8 +15135,8 @@ ArboristNode { "location": "node_modules/symlink-in-tree", "name": "symlink-in-tree", "packageName": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/symlink-in-tree", - "realpath": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/abbrev", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/symlink-in-tree", + "realpath": "{CWD}/test/fixtures/install-types-sw-only/node_modules/abbrev", "resolved": "file:abbrev", "target": ArboristNode { "location": "node_modules/abbrev", @@ -15216,30 +15145,22 @@ ArboristNode { }, "tarball" => ArboristNode { "dev": true, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "tarball", - "spec": "file:abbrev-1.1.1.tgz", - "type": "prod", - }, - }, "location": "node_modules/tarball", "name": "tarball", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/tarball", - "resolved": "file:{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/abbrev-1.1.1.tgz", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/tarball", + "resolved": "file:{CWD}/test/fixtures/install-types-sw-only/abbrev-1.1.1.tgz", }, "tarball-no-integrity" => ArboristNode { "dev": true, "location": "node_modules/tarball-no-integrity", "name": "tarball-no-integrity", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/tarball-no-integrity", - "resolved": "file:{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/abbrev-1.1.1.tgz", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/tarball-no-integrity", + "resolved": "file:{CWD}/test/fixtures/install-types-sw-only/abbrev-1.1.1.tgz", }, "unhosted-git" => ArboristNode { "location": "node_modules/unhosted-git", "name": "unhosted-git", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/unhosted-git", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/unhosted-git", "resolved": "git+https://mygit.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", }, "wrappy" => ArboristNode { @@ -15259,633 +15180,36 @@ ArboristNode { }, "location": "node_modules/wrappy", "name": "wrappy", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/node_modules/wrappy", + "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/wrappy", "resolved": "https://localhost:8080/wrappy/-/wrappy-1.0.2.tgz", "version": "1.0.2", }, }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "^1.1.1", - "to": "node_modules/abbrev", - "type": "prod", - }, - "bundler" => EdgeOut { - "name": "bundler", - "spec": "1.2.3", - "to": "node_modules/bundler", - "type": "prod", - }, - "full-git-url" => EdgeOut { - "name": "full-git-url", - "spec": "git+https://github.com/isaacs/abbrev-js.git", - "to": "node_modules/full-git-url", - "type": "prod", - }, - "ghshort" => EdgeOut { - "name": "ghshort", - "spec": "github:isaacs/abbrev-js", - "to": "node_modules/ghshort", - "type": "prod", - }, - "old" => EdgeOut { - "name": "old", - "spec": "npm:abbrev@^1.0.3", - "to": "node_modules/old", - "type": "prod", - }, - "pinned" => EdgeOut { - "name": "pinned", - "spec": "npm:abbrev@^1.1.1", - "to": "node_modules/pinned", - "type": "prod", - }, - "reg" => EdgeOut { - "name": "reg", - "spec": "npm:abbrev@^1.1.1", - "to": "node_modules/reg", - "type": "prod", - }, - "remote" => EdgeOut { - "name": "remote", - "spec": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", - "to": "node_modules/remote", - "type": "prod", - }, - "symlink" => EdgeOut { - "name": "symlink", - "spec": "file:./abbrev-link-target", - "to": "node_modules/symlink", - "type": "prod", - }, - "tarball" => EdgeOut { - "name": "tarball", - "spec": "file:abbrev-1.1.1.tgz", - "to": "node_modules/tarball", - "type": "prod", - }, - }, "fsChildren": Set { ArboristNode { "location": "abbrev-link-target", "name": "abbrev-link-target", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json/abbrev-link-target", + "path": "{CWD}/test/fixtures/install-types-sw-only/abbrev-link-target", }, }, "isProjectRoot": true, "location": "", - "name": "tap-testdir-load-virtual-load-from-npm-shrinkwrap.json", + "name": "install-types-sw-only", "packageName": "a", - "path": "{CWD}/test/arborist/tap-testdir-load-virtual-load-from-npm-shrinkwrap.json", + "path": "{CWD}/test/fixtures/install-types-sw-only", "version": "1.2.3", } ` -exports[`test/arborist/load-virtual.js TAP load without a root package.json is fine > loaded virtual no package json 1`] = ` +exports[`test/arborist/load-virtual.js TAP tree with link deps of link deps > expect resolving Promise 1`] = ` ArboristNode { "children": Map { - "abbrev" => ArboristNode { - "children": Map { - "@scope/name" => ArboristNode { - "children": Map { - "@otherscope/othername" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "error": "INVALID", - "from": "node_modules/abbrev/node_modules/@scope/name", - "name": "@otherscope/othername", - "spec": "1.2.3", - "type": "prod", - }, - }, - "location": "node_modules/abbrev/node_modules/@scope/name/node_modules/@otherscope/othername", - "name": "@otherscope/othername", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/abbrev/node_modules/@scope/name/node_modules/@otherscope/othername", - "resolved": "fake resolved value", - }, - }, - "edgesOut": Map { - "@otherscope/othername" => EdgeOut { - "error": "INVALID", - "name": "@otherscope/othername", - "spec": "1.2.3", - "to": "node_modules/abbrev/node_modules/@scope/name/node_modules/@otherscope/othername", - "type": "prod", - }, - "a-thing-which-is-not-here" => EdgeOut { - "error": "MISSING", - "name": "a-thing-which-is-not-here", - "spec": "2.4.5", - "to": null, - "type": "prod", - }, - }, - "location": "node_modules/abbrev/node_modules/@scope/name", - "name": "@scope/name", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/abbrev/node_modules/@scope/name", - }, - }, - "location": "node_modules/abbrev", - "name": "abbrev", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/abbrev", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", - "version": "1.1.1", - }, - "balanced-match" => ArboristNode { + "app" => ArboristLink { "edgesIn": Set { EdgeIn { - "from": "node_modules/brace-expansion", - "name": "balanced-match", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "location": "node_modules/balanced-match", - "name": "balanced-match", - "optional": true, - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/balanced-match", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "version": "1.0.0", - }, - "brace-expansion" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/minimatch", - "name": "brace-expansion", - "spec": "^1.1.7", - "type": "prod", - }, - }, - "edgesOut": Map { - "balanced-match" => EdgeOut { - "name": "balanced-match", - "spec": "^1.0.0", - "to": "node_modules/balanced-match", - "type": "prod", - }, - "concat-map" => EdgeOut { - "name": "concat-map", - "spec": "0.0.1", - "to": "node_modules/concat-map", - "type": "prod", - }, - }, - "location": "node_modules/brace-expansion", - "name": "brace-expansion", - "optional": true, - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/brace-expansion", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "version": "1.1.11", - }, - "bundler" => ArboristNode { - "bundleDependencies": Array [ - "a", - ], - "children": Map { - "a" => ArboristNode { - "bundled": true, - "bundler": "node_modules/bundler", - "edgesIn": Set { - EdgeIn { - "from": "node_modules/bundler", - "name": "a", - "spec": "*", - "type": "prod", - }, - }, - "edgesOut": Map { - "b" => EdgeOut { - "name": "b", - "spec": "*", - "to": "node_modules/bundler/node_modules/b", - "type": "prod", - }, - }, - "location": "node_modules/bundler/node_modules/a", - "name": "a", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/bundler/node_modules/a", - "resolved": "https://registry.internal/a/-/a-1.2.3.tgz", - "version": "1.2.3", - }, - "b" => ArboristNode { - "bundled": true, - "bundler": "node_modules/bundler", - "edgesIn": Set { - EdgeIn { - "from": "node_modules/bundler/node_modules/a", - "name": "b", - "spec": "*", - "type": "prod", - }, - }, - "edgesOut": Map { - "c" => EdgeOut { - "name": "c", - "spec": "*", - "to": "node_modules/bundler/node_modules/c", - "type": "prod", - }, - }, - "location": "node_modules/bundler/node_modules/b", - "name": "b", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/bundler/node_modules/b", - "resolved": "https://registry.internal/b/-/b-1.2.3.tgz", - "version": "1.2.3", - }, - "c" => ArboristNode { - "bundled": true, - "bundler": "node_modules/bundler", - "edgesIn": Set { - EdgeIn { - "from": "node_modules/bundler/node_modules/b", - "name": "c", - "spec": "*", - "type": "prod", - }, - }, - "location": "node_modules/bundler/node_modules/c", - "name": "c", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/bundler/node_modules/c", - "resolved": "https://registry.internal/c/-/c-1.2.3.tgz", - "version": "1.2.3", - }, - }, - "edgesOut": Map { - "a" => EdgeOut { - "name": "a", - "spec": "*", - "to": "node_modules/bundler/node_modules/a", - "type": "prod", - }, - }, - "location": "node_modules/bundler", - "name": "bundler", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/bundler", - "resolved": "https://registry.internal/bundler/-/bundler-1.2.3.tgz", - "version": "1.2.3", - }, - "concat-map" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/brace-expansion", - "name": "concat-map", - "spec": "0.0.1", - "type": "prod", - }, - }, - "location": "node_modules/concat-map", - "name": "concat-map", - "optional": true, - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/concat-map", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "version": "0.0.1", - }, - "fs.realpath" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/glob", - "name": "fs.realpath", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "location": "node_modules/fs.realpath", - "name": "fs.realpath", - "optional": true, - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/fs.realpath", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "version": "1.0.0", - }, - "full-git-url" => ArboristNode { - "location": "node_modules/full-git-url", - "name": "full-git-url", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/full-git-url", - "resolved": "git+ssh://git@github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", - }, - "ghshort" => ArboristNode { - "location": "node_modules/ghshort", - "name": "ghshort", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/ghshort", - "resolved": "git+ssh://git@github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", - }, - "ghtgz" => ArboristNode { - "location": "node_modules/ghtgz", - "name": "ghtgz", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/ghtgz", - "resolved": "https://codeload.github.com/isaacs/abbrev-js/tar.gz/a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", - }, - "glob" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/rimraf", - "name": "glob", - "spec": "^7.1.3", - "type": "optional", - }, - }, - "edgesOut": Map { - "fs.realpath" => EdgeOut { - "name": "fs.realpath", - "spec": "^1.0.0", - "to": "node_modules/fs.realpath", - "type": "prod", - }, - "inflight" => EdgeOut { - "name": "inflight", - "spec": "^1.0.4", - "to": "node_modules/inflight", - "type": "prod", - }, - "inherits" => EdgeOut { - "name": "inherits", - "spec": "2", - "to": "node_modules/inherits", - "type": "prod", - }, - "minimatch" => EdgeOut { - "name": "minimatch", - "spec": "^3.0.4", - "to": "node_modules/minimatch", - "type": "prod", - }, - "once" => EdgeOut { - "name": "once", - "spec": "^1.3.0", - "to": "node_modules/once", - "type": "prod", - }, - "path-is-absolute" => EdgeOut { - "name": "path-is-absolute", - "spec": "^1.0.0", - "to": "node_modules/path-is-absolute", - "type": "prod", - }, - }, - "location": "node_modules/glob", - "name": "glob", - "optional": true, - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/glob", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", - "version": "7.1.4", - }, - "inflight" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/glob", - "name": "inflight", - "spec": "^1.0.4", - "type": "prod", - }, - }, - "edgesOut": Map { - "once" => EdgeOut { - "name": "once", - "spec": "^1.3.0", - "to": "node_modules/once", - "type": "prod", - }, - "wrappy" => EdgeOut { - "name": "wrappy", - "spec": "1", - "to": "node_modules/wrappy", - "type": "prod", - }, - }, - "location": "node_modules/inflight", - "name": "inflight", - "optional": true, - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/inflight", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "version": "1.0.6", - }, - "inherits" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/glob", - "name": "inherits", - "spec": "2", - "type": "prod", - }, - }, - "location": "node_modules/inherits", - "name": "inherits", - "optional": true, - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/inherits", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "version": "2.0.4", - }, - "minimatch" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/glob", - "name": "minimatch", - "spec": "^3.0.4", - "type": "prod", - }, - }, - "edgesOut": Map { - "brace-expansion" => EdgeOut { - "name": "brace-expansion", - "spec": "^1.1.7", - "to": "node_modules/brace-expansion", - "type": "prod", - }, - }, - "location": "node_modules/minimatch", - "name": "minimatch", - "optional": true, - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/minimatch", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "version": "3.0.4", - }, - "old" => ArboristNode { - "location": "node_modules/old", - "name": "old", - "packageName": "abbrev", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/old", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.3.tgz", - "version": "1.0.3", - }, - "once" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/glob", - "name": "once", - "spec": "^1.3.0", - "type": "prod", - }, - EdgeIn { - "from": "node_modules/inflight", - "name": "once", - "spec": "^1.3.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "wrappy" => EdgeOut { - "name": "wrappy", - "spec": "1", - "to": "node_modules/wrappy", - "type": "prod", - }, - }, - "location": "node_modules/once", - "name": "once", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/once", - "resolved": "file:{CWD}/test/fixtures/install-types-sw-only/once-1.4.0.tgz", - "version": "1.4.0", - }, - "path-is-absolute" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/glob", - "name": "path-is-absolute", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "location": "node_modules/path-is-absolute", - "name": "path-is-absolute", - "optional": true, - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/path-is-absolute", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "version": "1.0.1", - }, - "pinned" => ArboristNode { - "location": "node_modules/pinned", - "name": "pinned", - "packageName": "abbrev", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/pinned", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", - "version": "1.1.1", - }, - "really-bad-invalid" => ArboristNode { - "location": "node_modules/really-bad-invalid", - "name": "really-bad-invalid", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/really-bad-invalid", - }, - "reg" => ArboristNode { - "location": "node_modules/reg", - "name": "reg", - "packageName": "abbrev", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/reg", - "resolved": "https://localhost:8080/abbrev/-/abbrev-1.1.1.tgz", - "version": "1.1.1", - }, - "remote" => ArboristNode { - "location": "node_modules/remote", - "name": "remote", - "packageName": "abbrev", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/remote", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", - "version": "1.1.1", - }, - "rimraf" => ArboristNode { - "edgesOut": Map { - "glob" => EdgeOut { - "name": "glob", - "spec": "^7.1.3", - "to": "node_modules/glob", - "type": "optional", - }, - }, - "location": "node_modules/rimraf", - "name": "rimraf", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/rimraf", - "resolved": "file:{CWD}/test/fixtures/install-types-sw-only/rimraf-2.6.3.tgz", - "version": "2.6.3", - }, - "symlink" => ArboristLink { - "location": "node_modules/symlink", - "name": "symlink", - "packageName": "abbrev-link-target", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/symlink", - "realpath": "{CWD}/test/fixtures/install-types-sw-only/abbrev-link-target", - "resolved": "file:../abbrev-link-target", - "target": ArboristNode { - "location": "abbrev-link-target", - }, - }, - "symlink-in-tree" => ArboristLink { - "location": "node_modules/symlink-in-tree", - "name": "symlink-in-tree", - "packageName": "abbrev", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/symlink-in-tree", - "realpath": "{CWD}/test/fixtures/install-types-sw-only/node_modules/abbrev", - "resolved": "file:abbrev", - "target": ArboristNode { - "location": "node_modules/abbrev", - }, - "version": "1.1.1", - }, - "tarball" => ArboristNode { - "dev": true, - "location": "node_modules/tarball", - "name": "tarball", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/tarball", - "resolved": "file:{CWD}/test/fixtures/install-types-sw-only/abbrev-1.1.1.tgz", - }, - "tarball-no-integrity" => ArboristNode { - "dev": true, - "location": "node_modules/tarball-no-integrity", - "name": "tarball-no-integrity", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/tarball-no-integrity", - "resolved": "file:{CWD}/test/fixtures/install-types-sw-only/abbrev-1.1.1.tgz", - }, - "unhosted-git" => ArboristNode { - "location": "node_modules/unhosted-git", - "name": "unhosted-git", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/unhosted-git", - "resolved": "git+https://mygit.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", - }, - "wrappy" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/inflight", - "name": "wrappy", - "spec": "1", - "type": "prod", - }, - EdgeIn { - "from": "node_modules/once", - "name": "wrappy", - "spec": "1", - "type": "prod", - }, - }, - "location": "node_modules/wrappy", - "name": "wrappy", - "path": "{CWD}/test/fixtures/install-types-sw-only/node_modules/wrappy", - "resolved": "https://localhost:8080/wrappy/-/wrappy-1.0.2.tgz", - "version": "1.0.2", - }, - }, - "fsChildren": Set { - ArboristNode { - "location": "abbrev-link-target", - "name": "abbrev-link-target", - "path": "{CWD}/test/fixtures/install-types-sw-only/abbrev-link-target", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "install-types-sw-only", - "packageName": "a", - "path": "{CWD}/test/fixtures/install-types-sw-only", - "version": "1.2.3", -} -` - -exports[`test/arborist/load-virtual.js TAP tree with link deps of link deps > expect resolving Promise 1`] = ` -ArboristNode { - "children": Map { - "app" => ArboristLink { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "app", - "spec": "file:./app", + "from": "", + "name": "app", + "spec": "file:./app", "type": "prod", }, }, @@ -16375,6 +15699,95 @@ ArboristNode { } ` +exports[`test/arborist/load-virtual.js TAP workspaces load installed workspace with dependency overrides > virtual tree with overrides 1`] = ` +ArboristNode { + "children": Map { + "arg" => ArboristNode { + "edgesIn": Set { + EdgeIn { + "from": "ws", + "name": "arg", + "override": "4.1.3", + "spec": "4.1.2", + "type": "prod", + }, + }, + "location": "node_modules/arg", + "name": "arg", + "overrides": Map { + "arg" => "4.1.3", + }, + "path": "{CWD}/test/fixtures/workspaces-with-overrides/node_modules/arg", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "version": "4.1.3", + }, + "ws" => ArboristLink { + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "ws", + "spec": "file:{CWD}/test/fixtures/workspaces-with-overrides/ws", + "type": "workspace", + }, + }, + "isWorkspace": true, + "location": "node_modules/ws", + "name": "ws", + "overrides": Map { + "arg" => "4.1.3", + }, + "path": "{CWD}/test/fixtures/workspaces-with-overrides/node_modules/ws", + "realpath": "{CWD}/test/fixtures/workspaces-with-overrides/ws", + "resolved": "file:../ws", + "target": ArboristNode { + "location": "ws", + }, + "version": "1.0.0", + }, + }, + "edgesOut": Map { + "ws" => EdgeOut { + "name": "ws", + "spec": "file:{CWD}/test/fixtures/workspaces-with-overrides/ws", + "to": "node_modules/ws", + "type": "workspace", + }, + }, + "fsChildren": Set { + ArboristNode { + "edgesOut": Map { + "arg" => EdgeOut { + "name": "arg", + "override": "4.1.3", + "spec": "4.1.2", + "to": "node_modules/arg", + "type": "prod", + }, + }, + "isWorkspace": true, + "location": "ws", + "name": "ws", + "overrides": Map { + "arg" => "4.1.3", + }, + "path": "{CWD}/test/fixtures/workspaces-with-overrides/ws", + "version": "1.0.0", + }, + }, + "isProjectRoot": true, + "location": "", + "name": "workspaces-with-overrides", + "overrides": Map { + "arg" => "4.1.3", + }, + "packageName": "workspace-with-overrides", + "path": "{CWD}/test/fixtures/workspaces-with-overrides", + "workspaces": Map { + "ws" => "ws", + }, +} +` + exports[`test/arborist/load-virtual.js TAP workspaces load installed workspace with transitive dependencies > virtual tree with transitive deps 1`] = ` ArboristNode { "children": Map { diff --git a/workspaces/arborist/tap-snapshots/test/arborist/reify.js.test.cjs b/workspaces/arborist/tap-snapshots/test/arborist/reify.js.test.cjs index ffe63992d8c34..e29f0cf0ea0d7 100644 --- a/workspaces/arborist/tap-snapshots/test/arborist/reify.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/arborist/reify.js.test.cjs @@ -165,11 +165,11 @@ ArboristNode { } ` -exports[`test/arborist/reify.js TAP add a dep present in the tree, with v1 shrinkwrap > must match snapshot 1`] = ` +exports[`test/arborist/reify.js TAP add a dep present in the tree, with v1 lockfile > must match snapshot 1`] = ` {"dependencies":{"once":"^1.4.0","wrappy":"^1.0.2"}} ` -exports[`test/arborist/reify.js TAP add a new pkg to a prefix that needs to be mkdirpd > should output a successful tree in mkdirp folder 1`] = ` +exports[`test/arborist/reify.js TAP add a new pkg to a prefix that needs to be mkdirpd not dry run > should output a successful tree in mkdirp folder 1`] = ` ArboristNode { "children": Map { "abbrev" => ArboristNode { @@ -183,7 +183,7 @@ ArboristNode { }, "location": "node_modules/abbrev", "name": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-reify-add-a-new-pkg-to-a-prefix-that-needs-to-be-mkdirpd/missing/path/to/root/node_modules/abbrev", + "path": "{CWD}/test/arborist/tap-testdir-reify-add-a-new-pkg-to-a-prefix-that-needs-to-be-mkdirpd-not-dry-run/missing/path/to/root/node_modules/abbrev", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", "version": "1.1.1", }, @@ -199,11 +199,11 @@ ArboristNode { "isProjectRoot": true, "location": "", "name": "root", - "path": "{CWD}/test/arborist/tap-testdir-reify-add-a-new-pkg-to-a-prefix-that-needs-to-be-mkdirpd/missing/path/to/root", + "path": "{CWD}/test/arborist/tap-testdir-reify-add-a-new-pkg-to-a-prefix-that-needs-to-be-mkdirpd-not-dry-run/missing/path/to/root", } ` -exports[`test/arborist/reify.js TAP add a new pkg to a prefix that needs to be mkdirpd > should place expected lockfile file into place 1`] = ` +exports[`test/arborist/reify.js TAP add a new pkg to a prefix that needs to be mkdirpd not dry run > should place expected lockfile file into place 1`] = ` { "name": "root", "lockfileVersion": 3, @@ -225,7 +225,7 @@ exports[`test/arborist/reify.js TAP add a new pkg to a prefix that needs to be m ` -exports[`test/arborist/reify.js TAP add a new pkg to a prefix that needs to be mkdirpd > should place expected package.json file into place 1`] = ` +exports[`test/arborist/reify.js TAP add a new pkg to a prefix that needs to be mkdirpd not dry run > should place expected package.json file into place 1`] = ` { "dependencies": { "abbrev": "^1.1.1" @@ -1857,177 +1857,6 @@ exports[`test/arborist/reify.js TAP add spec * with semver prefix range gets upd ` -exports[`test/arborist/reify.js TAP adding an unresolvable optional dep is OK > must match snapshot 1`] = ` -ArboristNode { - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "999999", - "to": null, - "type": "optional", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-adding-an-unresolvable-optional-dep-is-OK", - "path": "{CWD}/test/arborist/tap-testdir-reify-adding-an-unresolvable-optional-dep-is-OK", -} -` - -exports[`test/arborist/reify.js TAP bad shrinkwrap file > expect resolving Promise 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/testing-peer-deps-b" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/testing-peer-deps-b", - "spec": "1", - "type": "prod", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-c" => EdgeOut { - "name": "@isaacs/testing-peer-deps-c", - "spec": "1", - "to": "node_modules/@isaacs/testing-peer-deps-c", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-b", - "path": "{CWD}/test/arborist/tap-testdir-reify-bad-shrinkwrap-file/node_modules/@isaacs/testing-peer-deps-b", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-b/-/testing-peer-deps-b-1.2.4.tgz", - "version": "1.2.4", - }, - "@isaacs/testing-peer-deps-c" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-c", - "spec": "1", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-c", - "name": "@isaacs/testing-peer-deps-c", - "path": "{CWD}/test/arborist/tap-testdir-reify-bad-shrinkwrap-file/node_modules/@isaacs/testing-peer-deps-c", - "peer": true, - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-c/-/testing-peer-deps-c-1.2.3.tgz", - "version": "1.2.3", - }, - "@isaacs/testing-peer-deps-d" => ArboristNode { - "children": Map { - "@isaacs/testing-peer-deps-a" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-d", - "name": "@isaacs/testing-peer-deps-a", - "spec": "2", - "type": "prod", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-b" => EdgeOut { - "name": "@isaacs/testing-peer-deps-b", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "name": "@isaacs/testing-peer-deps-a", - "path": "{CWD}/test/arborist/tap-testdir-reify-bad-shrinkwrap-file/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-a/-/testing-peer-deps-a-2.0.0.tgz", - "version": "2.0.0", - }, - "@isaacs/testing-peer-deps-b" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "name": "@isaacs/testing-peer-deps-b", - "spec": "2", - "type": "peer", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-c" => EdgeOut { - "name": "@isaacs/testing-peer-deps-c", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-b", - "path": "{CWD}/test/arborist/tap-testdir-reify-bad-shrinkwrap-file/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", - "peer": true, - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-b/-/testing-peer-deps-b-2.0.1.tgz", - "version": "2.0.1", - }, - "@isaacs/testing-peer-deps-c" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-c", - "spec": "2", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", - "name": "@isaacs/testing-peer-deps-c", - "path": "{CWD}/test/arborist/tap-testdir-reify-bad-shrinkwrap-file/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", - "peer": true, - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-c/-/testing-peer-deps-c-2.0.0.tgz", - "version": "2.0.0", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/testing-peer-deps-d", - "spec": "2", - "type": "prod", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-a" => EdgeOut { - "name": "@isaacs/testing-peer-deps-a", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "type": "prod", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d", - "name": "@isaacs/testing-peer-deps-d", - "path": "{CWD}/test/arborist/tap-testdir-reify-bad-shrinkwrap-file/node_modules/@isaacs/testing-peer-deps-d", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-d/-/testing-peer-deps-d-2.0.0.tgz", - "version": "2.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-b" => EdgeOut { - "name": "@isaacs/testing-peer-deps-b", - "spec": "1", - "to": "node_modules/@isaacs/testing-peer-deps-b", - "type": "prod", - }, - "@isaacs/testing-peer-deps-d" => EdgeOut { - "name": "@isaacs/testing-peer-deps-d", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-bad-shrinkwrap-file", - "packageName": "@isaacs/testing-peer-deps", - "path": "{CWD}/test/arborist/tap-testdir-reify-bad-shrinkwrap-file", - "version": "2.0.0", -} -` - exports[`test/arborist/reify.js TAP bundled file dep with same name as other dep > must match snapshot 1`] = ` ArboristNode { "children": Map { @@ -2134,7 +1963,6 @@ ArboristNode { }, }, }, - "dev": true, "edgesOut": Map { "abbrev" => EdgeOut { "error": "MISSING", @@ -2492,69 +2320,6 @@ ArboristNode { } ` -exports[`test/arborist/reify.js TAP do not add shrinkwrapped deps > expect resolving Promise 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "children": Map { - "abbrev" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "abbrev", - "spec": "^1.0.4", - "type": "prod", - }, - }, - "inShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "name": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-reify-do-not-add-shrinkwrapped-deps/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "version": "1.0.4", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "^1.0.4", - "to": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/arborist/tap-testdir-reify-do-not-add-shrinkwrapped-deps/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-do-not-add-shrinkwrapped-deps", - "packageName": "shrinkwrap", - "path": "{CWD}/test/arborist/tap-testdir-reify-do-not-add-shrinkwrapped-deps", - "version": "1.0.0", -} -` - exports[`test/arborist/reify.js TAP do not delete root-bundled deps in global update > after first install 1`] = ` { "name": "dep" @@ -2840,88 +2605,6 @@ ArboristNode { } ` -exports[`test/arborist/reify.js TAP do not install optional deps with mismatched platform specifications > expect resolving Promise 1`] = ` -ArboristNode { - "edgesOut": Map { - "platform-specifying-test-package" => EdgeOut { - "name": "platform-specifying-test-package", - "spec": "1.0.0", - "to": null, - "type": "optional", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-do-not-install-optional-deps-with-mismatched-platform-specifications", - "packageName": "platform-test", - "path": "{CWD}/test/arborist/tap-testdir-reify-do-not-install-optional-deps-with-mismatched-platform-specifications", - "version": "1.0.0", -} -` - -exports[`test/arborist/reify.js TAP do not update shrinkwrapped deps > expect resolving Promise 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "children": Map { - "abbrev" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "abbrev", - "spec": "^1.0.4", - "type": "prod", - }, - }, - "inShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "name": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-reify-do-not-update-shrinkwrapped-deps/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "version": "1.0.4", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "^1.0.4", - "to": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/arborist/tap-testdir-reify-do-not-update-shrinkwrapped-deps/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-do-not-update-shrinkwrapped-deps", - "packageName": "shrinkwrap", - "path": "{CWD}/test/arborist/tap-testdir-reify-do-not-update-shrinkwrapped-deps", - "version": "1.0.0", -} -` - exports[`test/arborist/reify.js TAP dry run, do not get anything wet link-dep-empty > must match snapshot 1`] = ` ArboristNode { "children": Map { @@ -3059,132 +2742,6 @@ ArboristNode { } ` -exports[`test/arborist/reify.js TAP dry run, do not get anything wet shrinkwrapped-dep-no-lock-empty > must match snapshot 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "children": Map { - "abbrev" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "abbrev", - "spec": "^1.0.4", - "type": "prod", - }, - }, - "inShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "name": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-reify-dry-run-do-not-get-anything-wet-shrinkwrapped-dep-no-lock-empty/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "version": "1.0.4", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "^1.0.4", - "to": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/arborist/tap-testdir-reify-dry-run-do-not-get-anything-wet-shrinkwrapped-dep-no-lock-empty/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-dry-run-do-not-get-anything-wet-shrinkwrapped-dep-no-lock-empty", - "packageName": "shrinkwrap", - "path": "{CWD}/test/arborist/tap-testdir-reify-dry-run-do-not-get-anything-wet-shrinkwrapped-dep-no-lock-empty", - "version": "1.0.0", -} -` - -exports[`test/arborist/reify.js TAP dry run, do not get anything wet shrinkwrapped-dep-with-lock-empty > must match snapshot 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "children": Map { - "abbrev" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "abbrev", - "spec": "^1.0.4", - "type": "prod", - }, - }, - "inShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "name": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-reify-dry-run-do-not-get-anything-wet-shrinkwrapped-dep-with-lock-empty/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "version": "1.0.4", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "^1.0.4", - "to": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/arborist/tap-testdir-reify-dry-run-do-not-get-anything-wet-shrinkwrapped-dep-with-lock-empty/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-dry-run-do-not-get-anything-wet-shrinkwrapped-dep-with-lock-empty", - "packageName": "shrinkwrap", - "path": "{CWD}/test/arborist/tap-testdir-reify-dry-run-do-not-get-anything-wet-shrinkwrapped-dep-with-lock-empty", - "version": "1.0.0", -} -` - exports[`test/arborist/reify.js TAP dry run, do not get anything wet testing-bundledeps-empty > must match snapshot 1`] = ` ArboristNode { "children": Map { @@ -3318,63 +2875,6 @@ ArboristNode { } ` -exports[`test/arborist/reify.js TAP fail to install optional deps with matched os and matched cpu and mismatched libc with os and cpu and libc options > expect resolving Promise 1`] = ` -ArboristNode { - "edgesOut": Map { - "platform-specifying-test-package" => EdgeOut { - "name": "platform-specifying-test-package", - "spec": "1.0.0", - "to": null, - "type": "optional", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-fail-to-install-optional-deps-with-matched-os-and-matched-cpu-and-mismatched-libc-with-os-and-cpu-and-libc-options", - "packageName": "platform-test", - "path": "{CWD}/test/arborist/tap-testdir-reify-fail-to-install-optional-deps-with-matched-os-and-matched-cpu-and-mismatched-libc-with-os-and-cpu-and-libc-options", - "version": "1.0.0", -} -` - -exports[`test/arborist/reify.js TAP fail to install optional deps with matched os and mismatched cpu with os and cpu and libc options > expect resolving Promise 1`] = ` -ArboristNode { - "edgesOut": Map { - "platform-specifying-test-package" => EdgeOut { - "name": "platform-specifying-test-package", - "spec": "1.0.0", - "to": null, - "type": "optional", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-fail-to-install-optional-deps-with-matched-os-and-mismatched-cpu-with-os-and-cpu-and-libc-options", - "packageName": "platform-test", - "path": "{CWD}/test/arborist/tap-testdir-reify-fail-to-install-optional-deps-with-matched-os-and-mismatched-cpu-with-os-and-cpu-and-libc-options", - "version": "1.0.0", -} -` - -exports[`test/arborist/reify.js TAP fail to install optional deps with mismatched os and matched cpu with os and cpu and libc options > expect resolving Promise 1`] = ` -ArboristNode { - "edgesOut": Map { - "platform-specifying-test-package" => EdgeOut { - "name": "platform-specifying-test-package", - "spec": "1.0.0", - "to": null, - "type": "optional", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-fail-to-install-optional-deps-with-mismatched-os-and-matched-cpu-with-os-and-cpu-and-libc-options", - "packageName": "platform-test", - "path": "{CWD}/test/arborist/tap-testdir-reify-fail-to-install-optional-deps-with-mismatched-os-and-matched-cpu-with-os-and-cpu-and-libc-options", - "version": "1.0.0", -} -` - exports[`test/arborist/reify.js TAP failing script means install failure, unless ignoreScripts prod-dep-allinstall-fail --ignore-scripts > expect resolving Promise 1`] = ` ArboristNode { "children": Map { @@ -3683,10 +3183,6 @@ exports[`test/arborist/reify.js TAP filtered reification in workspaces > hidden "apps/x": { "version": "1.2.3" }, - "foo/x": { - "version": "1.2.3", - "extraneous": true - }, "node_modules/c": { "resolved": "packages/c", "link": true @@ -4536,7 +4032,7 @@ ArboristNode { } ` -exports[`test/arborist/reify.js TAP just the shrinkwrap cli-750-fresh > must match snapshot 1`] = ` +exports[`test/arborist/reify.js TAP just the lockfile cli-750-fresh > must match snapshot 1`] = ` { "name": "monorepo", "lockfileVersion": 3, @@ -4567,9 +4063,9 @@ exports[`test/arborist/reify.js TAP just the shrinkwrap cli-750-fresh > must mat ` -exports[`test/arborist/reify.js TAP just the shrinkwrap yarn-lock-mkdirp > must match snapshot 1`] = ` +exports[`test/arborist/reify.js TAP just the lockfile yarn-lock-mkdirp > must match snapshot 1`] = ` { - "name": "tap-testdir-reify-just-the-shrinkwrap-yarn-lock-mkdirp", + "name": "tap-testdir-reify-just-the-lockfile-yarn-lock-mkdirp", "lockfileVersion": 3, "requires": true, "packages": { @@ -17206,7 +16702,6 @@ Array [ "reify:retireShallow", "reify:save", "reify:trash", - "reify:trashOmits", "reify:unpack", "reify:unretire", "reifyNode:node_modules/@isaacs/testing-peer-deps-b", @@ -32172,258 +31667,6 @@ ArboristNode { } ` -exports[`test/arborist/reify.js TAP reifying with shronk warp dep shrinkwrapped-dep-no-lock > must match snapshot 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "children": Map { - "abbrev" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "abbrev", - "spec": "^1.0.4", - "type": "prod", - }, - }, - "inShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "name": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "version": "1.0.4", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "^1.0.4", - "to": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/arborist/tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-no-lock", - "packageName": "shrinkwrap", - "path": "{CWD}/test/arborist/tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-no-lock", - "version": "1.0.0", -} -` - -exports[`test/arborist/reify.js TAP reifying with shronk warp dep shrinkwrapped-dep-no-lock-empty > must match snapshot 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "children": Map { - "abbrev" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "abbrev", - "spec": "^1.0.4", - "type": "prod", - }, - }, - "inShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "name": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-no-lock-empty/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "version": "1.0.4", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "^1.0.4", - "to": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/arborist/tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-no-lock-empty/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-no-lock-empty", - "packageName": "shrinkwrap", - "path": "{CWD}/test/arborist/tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-no-lock-empty", - "version": "1.0.0", -} -` - -exports[`test/arborist/reify.js TAP reifying with shronk warp dep shrinkwrapped-dep-with-lock > must match snapshot 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "children": Map { - "abbrev" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "abbrev", - "spec": "^1.0.4", - "type": "prod", - }, - }, - "inShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "name": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "version": "1.0.4", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "^1.0.4", - "to": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/arborist/tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-with-lock", - "packageName": "shrinkwrap", - "path": "{CWD}/test/arborist/tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-with-lock", - "version": "1.0.0", -} -` - -exports[`test/arborist/reify.js TAP reifying with shronk warp dep shrinkwrapped-dep-with-lock-empty > must match snapshot 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/shrinkwrapped-dependency" => ArboristNode { - "children": Map { - "abbrev" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "abbrev", - "spec": "^1.0.4", - "type": "prod", - }, - }, - "inShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "name": "abbrev", - "path": "{CWD}/test/arborist/tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-with-lock-empty/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "version": "1.0.4", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "edgesOut": Map { - "abbrev" => EdgeOut { - "name": "abbrev", - "spec": "^1.0.4", - "to": "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev", - "type": "prod", - }, - }, - "hasShrinkwrap": true, - "location": "node_modules/@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "path": "{CWD}/test/arborist/tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-with-lock-empty/node_modules/@isaacs/shrinkwrapped-dependency", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/shrinkwrapped-dependency" => EdgeOut { - "name": "@isaacs/shrinkwrapped-dependency", - "spec": "^1.0.0", - "to": "node_modules/@isaacs/shrinkwrapped-dependency", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-with-lock-empty", - "packageName": "shrinkwrap", - "path": "{CWD}/test/arborist/tap-testdir-reify-reifying-with-shronk-warp-dep-shrinkwrapped-dep-with-lock-empty", - "version": "1.0.0", -} -` - exports[`test/arborist/reify.js TAP rollbacks fail removing retired and deleted nodes > expect resolving Promise 1`] = ` ArboristNode { "children": Map { @@ -33120,9 +32363,6 @@ Object { "e", ], }, - "e": Object { - "extraneous": true, - }, "node_modules/a": Object { "extraneous": true, "inBundle": true, @@ -33172,25 +32412,6 @@ exports[`test/arborist/reify.js TAP scoped registries > should preserve original @ruyadorno/theoretically-private-pkg@https://npm.pkg.github.com/@ruyadorno/theoretically-private-pkg/-/theoretically-private-pkg-1.2.3.tgz ` -exports[`test/arborist/reify.js TAP still do not install optional deps with mismatched platform specifications even when forced > expect resolving Promise 1`] = ` -ArboristNode { - "edgesOut": Map { - "platform-specifying-test-package" => EdgeOut { - "name": "platform-specifying-test-package", - "spec": "1.0.0", - "to": null, - "type": "optional", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-still-do-not-install-optional-deps-with-mismatched-platform-specifications-even-when-forced", - "packageName": "platform-test", - "path": "{CWD}/test/arborist/tap-testdir-reify-still-do-not-install-optional-deps-with-mismatched-platform-specifications-even-when-forced", - "version": "1.0.0", -} -` - exports[`test/arborist/reify.js TAP store files with a custom indenting > must match snapshot 1`] = ` { "name": "tab-indented-package-json", @@ -33227,43 +32448,6 @@ exports[`test/arborist/reify.js TAP store files with a custom indenting > must m ` -exports[`test/arborist/reify.js TAP success to install optional deps with matched platform specifications with os and cpu and libc options > expect resolving Promise 1`] = ` -ArboristNode { - "children": Map { - "platform-specifying-test-package" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "platform-specifying-test-package", - "spec": "1.0.0", - "type": "optional", - }, - }, - "location": "node_modules/platform-specifying-test-package", - "name": "platform-specifying-test-package", - "optional": true, - "path": "{CWD}/test/arborist/tap-testdir-reify-success-to-install-optional-deps-with-matched-platform-specifications-with-os-and-cpu-and-libc-options/node_modules/platform-specifying-test-package", - "resolved": "https://registry.npmjs.org/platform-specifying-test-package/-/platform-specifying-test-package-1.0.0.tgz", - "version": "1.0.0", - }, - }, - "edgesOut": Map { - "platform-specifying-test-package" => EdgeOut { - "name": "platform-specifying-test-package", - "spec": "1.0.0", - "to": "node_modules/platform-specifying-test-package", - "type": "optional", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-success-to-install-optional-deps-with-matched-platform-specifications-with-os-and-cpu-and-libc-options", - "packageName": "platform-test", - "path": "{CWD}/test/arborist/tap-testdir-reify-success-to-install-optional-deps-with-matched-platform-specifications-with-os-and-cpu-and-libc-options", - "version": "1.0.0", -} -` - exports[`test/arborist/reify.js TAP tarball deps with transitive tarball deps > expect resolving Promise 1`] = ` ArboristNode { "children": Map { @@ -33481,298 +32665,7 @@ ArboristNode { }, "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", "name": "@isaacs/testing-peer-deps-b", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", - "peer": true, - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-b/-/testing-peer-deps-b-2.0.1.tgz", - "version": "2.0.1", - }, - "@isaacs/testing-peer-deps-c" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-c", - "spec": "2", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", - "name": "@isaacs/testing-peer-deps-c", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", - "peer": true, - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-c/-/testing-peer-deps-c-2.0.0.tgz", - "version": "2.0.0", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps", - "name": "@isaacs/testing-peer-deps-d", - "spec": "2", - "type": "prod", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-a" => EdgeOut { - "name": "@isaacs/testing-peer-deps-a", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "type": "prod", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d", - "name": "@isaacs/testing-peer-deps-d", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested/node_modules/@isaacs/testing-peer-deps-d", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-d/-/testing-peer-deps-d-2.0.0.tgz", - "version": "2.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps" => EdgeOut { - "name": "@isaacs/testing-peer-deps", - "spec": "2 || 3", - "to": "node_modules/@isaacs/testing-peer-deps", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-testing-peer-deps-nested", - "packageName": "testing-peer-deps-nested", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested", - "version": "1.0.0", -} -` - -exports[`test/arborist/reify.js TAP testing-peer-deps nested with update > expect resolving Promise 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/testing-peer-deps" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/testing-peer-deps", - "spec": "2 || 3", - "type": "prod", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-b" => EdgeOut { - "name": "@isaacs/testing-peer-deps-b", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-b", - "type": "prod", - }, - "@isaacs/testing-peer-deps-d" => EdgeOut { - "name": "@isaacs/testing-peer-deps-d", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d", - "type": "prod", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps", - "name": "@isaacs/testing-peer-deps", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested-with-update/node_modules/@isaacs/testing-peer-deps", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps/-/testing-peer-deps-3.0.0.tgz", - "version": "3.0.0", - }, - "@isaacs/testing-peer-deps-b" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps", - "name": "@isaacs/testing-peer-deps-b", - "spec": "2", - "type": "prod", - }, - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "name": "@isaacs/testing-peer-deps-b", - "spec": "2", - "type": "peer", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-c" => EdgeOut { - "name": "@isaacs/testing-peer-deps-c", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-c", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-b", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested-with-update/node_modules/@isaacs/testing-peer-deps-b", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-b/-/testing-peer-deps-b-2.0.1.tgz", - "version": "2.0.1", - }, - "@isaacs/testing-peer-deps-c" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-c", - "spec": "2", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-c", - "name": "@isaacs/testing-peer-deps-c", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested-with-update/node_modules/@isaacs/testing-peer-deps-c", - "peer": true, - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-c/-/testing-peer-deps-c-2.0.0.tgz", - "version": "2.0.0", - }, - "@isaacs/testing-peer-deps-d" => ArboristNode { - "children": Map { - "@isaacs/testing-peer-deps-a" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-d", - "name": "@isaacs/testing-peer-deps-a", - "spec": "2", - "type": "prod", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-b" => EdgeOut { - "name": "@isaacs/testing-peer-deps-b", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-b", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "name": "@isaacs/testing-peer-deps-a", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested-with-update/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-a/-/testing-peer-deps-a-2.0.0.tgz", - "version": "2.0.0", - }, - }, - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps", - "name": "@isaacs/testing-peer-deps-d", - "spec": "2", - "type": "prod", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-a" => EdgeOut { - "name": "@isaacs/testing-peer-deps-a", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "type": "prod", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d", - "name": "@isaacs/testing-peer-deps-d", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested-with-update/node_modules/@isaacs/testing-peer-deps-d", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-d/-/testing-peer-deps-d-2.0.0.tgz", - "version": "2.0.0", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps" => EdgeOut { - "name": "@isaacs/testing-peer-deps", - "spec": "2 || 3", - "to": "node_modules/@isaacs/testing-peer-deps", - "type": "prod", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "tap-testdir-reify-testing-peer-deps-nested-with-update", - "packageName": "testing-peer-deps-nested", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested-with-update", - "version": "1.0.0", -} -` - -exports[`test/arborist/reify.js TAP testing-peer-deps package > expect resolving Promise 1`] = ` -ArboristNode { - "children": Map { - "@isaacs/testing-peer-deps-b" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "@isaacs/testing-peer-deps-b", - "spec": "1", - "type": "prod", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-c" => EdgeOut { - "name": "@isaacs/testing-peer-deps-c", - "spec": "1", - "to": "node_modules/@isaacs/testing-peer-deps-c", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-b", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package/node_modules/@isaacs/testing-peer-deps-b", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-b/-/testing-peer-deps-b-1.2.4.tgz", - "version": "1.2.4", - }, - "@isaacs/testing-peer-deps-c" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-c", - "spec": "1", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-c", - "name": "@isaacs/testing-peer-deps-c", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package/node_modules/@isaacs/testing-peer-deps-c", - "peer": true, - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-c/-/testing-peer-deps-c-1.2.3.tgz", - "version": "1.2.3", - }, - "@isaacs/testing-peer-deps-d" => ArboristNode { - "children": Map { - "@isaacs/testing-peer-deps-a" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-d", - "name": "@isaacs/testing-peer-deps-a", - "spec": "2", - "type": "prod", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-b" => EdgeOut { - "name": "@isaacs/testing-peer-deps-b", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "name": "@isaacs/testing-peer-deps-a", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-a/-/testing-peer-deps-a-2.0.0.tgz", - "version": "2.0.0", - }, - "@isaacs/testing-peer-deps-b" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", - "name": "@isaacs/testing-peer-deps-b", - "spec": "2", - "type": "peer", - }, - }, - "edgesOut": Map { - "@isaacs/testing-peer-deps-c" => EdgeOut { - "name": "@isaacs/testing-peer-deps-c", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", - "type": "peer", - }, - }, - "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", - "name": "@isaacs/testing-peer-deps-b", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", "peer": true, "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-b/-/testing-peer-deps-b-2.0.1.tgz", "version": "2.0.1", @@ -33788,7 +32681,7 @@ ArboristNode { }, "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", "name": "@isaacs/testing-peer-deps-c", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", "peer": true, "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-c/-/testing-peer-deps-c-2.0.0.tgz", "version": "2.0.0", @@ -33796,7 +32689,7 @@ ArboristNode { }, "edgesIn": Set { EdgeIn { - "from": "", + "from": "node_modules/@isaacs/testing-peer-deps", "name": "@isaacs/testing-peer-deps-d", "spec": "2", "type": "prod", @@ -33812,241 +32705,322 @@ ArboristNode { }, "location": "node_modules/@isaacs/testing-peer-deps-d", "name": "@isaacs/testing-peer-deps-d", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package/node_modules/@isaacs/testing-peer-deps-d", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested/node_modules/@isaacs/testing-peer-deps-d", "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-d/-/testing-peer-deps-d-2.0.0.tgz", "version": "2.0.0", }, }, "edgesOut": Map { - "@isaacs/testing-peer-deps-b" => EdgeOut { - "name": "@isaacs/testing-peer-deps-b", - "spec": "1", - "to": "node_modules/@isaacs/testing-peer-deps-b", - "type": "prod", - }, - "@isaacs/testing-peer-deps-d" => EdgeOut { - "name": "@isaacs/testing-peer-deps-d", - "spec": "2", - "to": "node_modules/@isaacs/testing-peer-deps-d", + "@isaacs/testing-peer-deps" => EdgeOut { + "name": "@isaacs/testing-peer-deps", + "spec": "2 || 3", + "to": "node_modules/@isaacs/testing-peer-deps", "type": "prod", }, }, "isProjectRoot": true, "location": "", - "name": "tap-testdir-reify-testing-peer-deps-package", - "packageName": "@isaacs/testing-peer-deps", - "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package", - "version": "2.0.0", + "name": "tap-testdir-reify-testing-peer-deps-nested", + "packageName": "testing-peer-deps-nested", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested", + "version": "1.0.0", } ` -exports[`test/arborist/reify.js TAP tracks changes of shrinkwrapped dep correctly > install added the correct tree 1`] = ` +exports[`test/arborist/reify.js TAP testing-peer-deps nested with update > expect resolving Promise 1`] = ` ArboristNode { "children": Map { - "@nlf/shrinkwrapped-dep-updates-a" => ArboristNode { - "children": Map { - "@nlf/shrinkwrapped-dep-updates-b" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@nlf/shrinkwrapped-dep-updates-a", - "name": "@nlf/shrinkwrapped-dep-updates-b", - "spec": "^1.0.0", - "type": "prod", - }, - }, - "inShrinkwrap": true, - "location": "node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-b", - "name": "@nlf/shrinkwrapped-dep-updates-b", - "path": "{CWD}/test/arborist/tap-testdir-reify-tracks-changes-of-shrinkwrapped-dep-correctly/node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-b", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-1.0.0.tgz", - "version": "1.0.0", + "@isaacs/testing-peer-deps" => ArboristNode { + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "@isaacs/testing-peer-deps", + "spec": "2 || 3", + "type": "prod", + }, + }, + "edgesOut": Map { + "@isaacs/testing-peer-deps-b" => EdgeOut { + "name": "@isaacs/testing-peer-deps-b", + "spec": "2", + "to": "node_modules/@isaacs/testing-peer-deps-b", + "type": "prod", + }, + "@isaacs/testing-peer-deps-d" => EdgeOut { + "name": "@isaacs/testing-peer-deps-d", + "spec": "2", + "to": "node_modules/@isaacs/testing-peer-deps-d", + "type": "prod", + }, + }, + "location": "node_modules/@isaacs/testing-peer-deps", + "name": "@isaacs/testing-peer-deps", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested-with-update/node_modules/@isaacs/testing-peer-deps", + "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps/-/testing-peer-deps-3.0.0.tgz", + "version": "3.0.0", + }, + "@isaacs/testing-peer-deps-b" => ArboristNode { + "edgesIn": Set { + EdgeIn { + "from": "node_modules/@isaacs/testing-peer-deps", + "name": "@isaacs/testing-peer-deps-b", + "spec": "2", + "type": "prod", + }, + EdgeIn { + "from": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", + "name": "@isaacs/testing-peer-deps-b", + "spec": "2", + "type": "peer", + }, + }, + "edgesOut": Map { + "@isaacs/testing-peer-deps-c" => EdgeOut { + "name": "@isaacs/testing-peer-deps-c", + "spec": "2", + "to": "node_modules/@isaacs/testing-peer-deps-c", + "type": "peer", + }, + }, + "location": "node_modules/@isaacs/testing-peer-deps-b", + "name": "@isaacs/testing-peer-deps-b", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested-with-update/node_modules/@isaacs/testing-peer-deps-b", + "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-b/-/testing-peer-deps-b-2.0.1.tgz", + "version": "2.0.1", + }, + "@isaacs/testing-peer-deps-c" => ArboristNode { + "edgesIn": Set { + EdgeIn { + "from": "node_modules/@isaacs/testing-peer-deps-b", + "name": "@isaacs/testing-peer-deps-c", + "spec": "2", + "type": "peer", }, - "@nlf/shrinkwrapped-dep-updates-c" => ArboristNode { + }, + "location": "node_modules/@isaacs/testing-peer-deps-c", + "name": "@isaacs/testing-peer-deps-c", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested-with-update/node_modules/@isaacs/testing-peer-deps-c", + "peer": true, + "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-c/-/testing-peer-deps-c-2.0.0.tgz", + "version": "2.0.0", + }, + "@isaacs/testing-peer-deps-d" => ArboristNode { + "children": Map { + "@isaacs/testing-peer-deps-a" => ArboristNode { "edgesIn": Set { EdgeIn { - "from": "node_modules/@nlf/shrinkwrapped-dep-updates-a", - "name": "@nlf/shrinkwrapped-dep-updates-c", - "spec": "^1.0.0", + "from": "node_modules/@isaacs/testing-peer-deps-d", + "name": "@isaacs/testing-peer-deps-a", + "spec": "2", "type": "prod", }, }, - "inShrinkwrap": true, - "location": "node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-c", - "name": "@nlf/shrinkwrapped-dep-updates-c", - "path": "{CWD}/test/arborist/tap-testdir-reify-tracks-changes-of-shrinkwrapped-dep-correctly/node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-c", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-c/-/shrinkwrapped-dep-updates-c-1.0.0.tgz", - "version": "1.0.0", - }, - "@nlf/shrinkwrapped-dep-updates-d" => ArboristNode { - "edgesIn": Set { - EdgeIn { - "from": "node_modules/@nlf/shrinkwrapped-dep-updates-a", - "name": "@nlf/shrinkwrapped-dep-updates-d", - "spec": "^1.0.0", - "type": "prod", + "edgesOut": Map { + "@isaacs/testing-peer-deps-b" => EdgeOut { + "name": "@isaacs/testing-peer-deps-b", + "spec": "2", + "to": "node_modules/@isaacs/testing-peer-deps-b", + "type": "peer", }, }, - "inShrinkwrap": true, - "location": "node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-d", - "name": "@nlf/shrinkwrapped-dep-updates-d", - "path": "{CWD}/test/arborist/tap-testdir-reify-tracks-changes-of-shrinkwrapped-dep-correctly/node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-d", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-d/-/shrinkwrapped-dep-updates-d-1.0.0.tgz", - "version": "1.0.0", + "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", + "name": "@isaacs/testing-peer-deps-a", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested-with-update/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", + "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-a/-/testing-peer-deps-a-2.0.0.tgz", + "version": "2.0.0", }, }, "edgesIn": Set { EdgeIn { - "from": "", - "name": "@nlf/shrinkwrapped-dep-updates-a", - "spec": "^1.0.0", + "from": "node_modules/@isaacs/testing-peer-deps", + "name": "@isaacs/testing-peer-deps-d", + "spec": "2", "type": "prod", }, }, "edgesOut": Map { - "@nlf/shrinkwrapped-dep-updates-b" => EdgeOut { - "name": "@nlf/shrinkwrapped-dep-updates-b", - "spec": "^1.0.0", - "to": "node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-b", - "type": "prod", - }, - "@nlf/shrinkwrapped-dep-updates-c" => EdgeOut { - "name": "@nlf/shrinkwrapped-dep-updates-c", - "spec": "^1.0.0", - "to": "node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-c", - "type": "prod", - }, - "@nlf/shrinkwrapped-dep-updates-d" => EdgeOut { - "name": "@nlf/shrinkwrapped-dep-updates-d", - "spec": "^1.0.0", - "to": "node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-d", + "@isaacs/testing-peer-deps-a" => EdgeOut { + "name": "@isaacs/testing-peer-deps-a", + "spec": "2", + "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", "type": "prod", }, }, - "hasShrinkwrap": true, - "location": "node_modules/@nlf/shrinkwrapped-dep-updates-a", - "name": "@nlf/shrinkwrapped-dep-updates-a", - "path": "{CWD}/test/arborist/tap-testdir-reify-tracks-changes-of-shrinkwrapped-dep-correctly/node_modules/@nlf/shrinkwrapped-dep-updates-a", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-a/-/shrinkwrapped-dep-updates-a-1.0.0.tgz", - "version": "1.0.0", + "location": "node_modules/@isaacs/testing-peer-deps-d", + "name": "@isaacs/testing-peer-deps-d", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested-with-update/node_modules/@isaacs/testing-peer-deps-d", + "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-d/-/testing-peer-deps-d-2.0.0.tgz", + "version": "2.0.0", }, }, "edgesOut": Map { - "@nlf/shrinkwrapped-dep-updates-a" => EdgeOut { - "name": "@nlf/shrinkwrapped-dep-updates-a", - "spec": "^1.0.0", - "to": "node_modules/@nlf/shrinkwrapped-dep-updates-a", + "@isaacs/testing-peer-deps" => EdgeOut { + "name": "@isaacs/testing-peer-deps", + "spec": "2 || 3", + "to": "node_modules/@isaacs/testing-peer-deps", "type": "prod", }, }, "isProjectRoot": true, "location": "", - "name": "tap-testdir-reify-tracks-changes-of-shrinkwrapped-dep-correctly", - "path": "{CWD}/test/arborist/tap-testdir-reify-tracks-changes-of-shrinkwrapped-dep-correctly", + "name": "tap-testdir-reify-testing-peer-deps-nested-with-update", + "packageName": "testing-peer-deps-nested", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-nested-with-update", + "version": "1.0.0", } ` -exports[`test/arborist/reify.js TAP tracks changes of shrinkwrapped dep correctly > installing new version brings in the correct children 1`] = ` +exports[`test/arborist/reify.js TAP testing-peer-deps package > expect resolving Promise 1`] = ` ArboristNode { "children": Map { - "@nlf/shrinkwrapped-dep-updates-a" => ArboristNode { + "@isaacs/testing-peer-deps-b" => ArboristNode { + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "@isaacs/testing-peer-deps-b", + "spec": "1", + "type": "prod", + }, + }, + "edgesOut": Map { + "@isaacs/testing-peer-deps-c" => EdgeOut { + "name": "@isaacs/testing-peer-deps-c", + "spec": "1", + "to": "node_modules/@isaacs/testing-peer-deps-c", + "type": "peer", + }, + }, + "location": "node_modules/@isaacs/testing-peer-deps-b", + "name": "@isaacs/testing-peer-deps-b", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package/node_modules/@isaacs/testing-peer-deps-b", + "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-b/-/testing-peer-deps-b-1.2.4.tgz", + "version": "1.2.4", + }, + "@isaacs/testing-peer-deps-c" => ArboristNode { + "edgesIn": Set { + EdgeIn { + "from": "node_modules/@isaacs/testing-peer-deps-b", + "name": "@isaacs/testing-peer-deps-c", + "spec": "1", + "type": "peer", + }, + }, + "location": "node_modules/@isaacs/testing-peer-deps-c", + "name": "@isaacs/testing-peer-deps-c", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package/node_modules/@isaacs/testing-peer-deps-c", + "peer": true, + "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-c/-/testing-peer-deps-c-1.2.3.tgz", + "version": "1.2.3", + }, + "@isaacs/testing-peer-deps-d" => ArboristNode { "children": Map { - "@nlf/shrinkwrapped-dep-updates-b" => ArboristNode { + "@isaacs/testing-peer-deps-a" => ArboristNode { "edgesIn": Set { EdgeIn { - "from": "node_modules/@nlf/shrinkwrapped-dep-updates-a", - "name": "@nlf/shrinkwrapped-dep-updates-b", - "spec": "^2.0.0", + "from": "node_modules/@isaacs/testing-peer-deps-d", + "name": "@isaacs/testing-peer-deps-a", + "spec": "2", "type": "prod", }, }, - "inShrinkwrap": true, - "location": "node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-b", - "name": "@nlf/shrinkwrapped-dep-updates-b", - "path": "{CWD}/test/arborist/tap-testdir-reify-tracks-changes-of-shrinkwrapped-dep-correctly/node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-b", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-2.0.0.tgz", + "edgesOut": Map { + "@isaacs/testing-peer-deps-b" => EdgeOut { + "name": "@isaacs/testing-peer-deps-b", + "spec": "2", + "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", + "type": "peer", + }, + }, + "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", + "name": "@isaacs/testing-peer-deps-a", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", + "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-a/-/testing-peer-deps-a-2.0.0.tgz", "version": "2.0.0", }, - "@nlf/shrinkwrapped-dep-updates-c" => ArboristNode { + "@isaacs/testing-peer-deps-b" => ArboristNode { "edgesIn": Set { EdgeIn { - "from": "node_modules/@nlf/shrinkwrapped-dep-updates-a", - "name": "@nlf/shrinkwrapped-dep-updates-c", - "spec": "^1.0.0", - "type": "prod", + "from": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", + "name": "@isaacs/testing-peer-deps-b", + "spec": "2", + "type": "peer", }, }, - "inShrinkwrap": true, - "location": "node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-c", - "name": "@nlf/shrinkwrapped-dep-updates-c", - "path": "{CWD}/test/arborist/tap-testdir-reify-tracks-changes-of-shrinkwrapped-dep-correctly/node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-c", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-c/-/shrinkwrapped-dep-updates-c-1.0.0.tgz", - "version": "1.0.0", + "edgesOut": Map { + "@isaacs/testing-peer-deps-c" => EdgeOut { + "name": "@isaacs/testing-peer-deps-c", + "spec": "2", + "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", + "type": "peer", + }, + }, + "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", + "name": "@isaacs/testing-peer-deps-b", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", + "peer": true, + "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-b/-/testing-peer-deps-b-2.0.1.tgz", + "version": "2.0.1", }, - "@nlf/shrinkwrapped-dep-updates-e" => ArboristNode { + "@isaacs/testing-peer-deps-c" => ArboristNode { "edgesIn": Set { EdgeIn { - "from": "node_modules/@nlf/shrinkwrapped-dep-updates-a", - "name": "@nlf/shrinkwrapped-dep-updates-e", - "spec": "^1.0.0", - "type": "prod", + "from": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-b", + "name": "@isaacs/testing-peer-deps-c", + "spec": "2", + "type": "peer", }, }, - "inShrinkwrap": true, - "location": "node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-e", - "name": "@nlf/shrinkwrapped-dep-updates-e", - "path": "{CWD}/test/arborist/tap-testdir-reify-tracks-changes-of-shrinkwrapped-dep-correctly/node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-e", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-e/-/shrinkwrapped-dep-updates-e-1.0.0.tgz", - "version": "1.0.0", + "location": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", + "name": "@isaacs/testing-peer-deps-c", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package/node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-c", + "peer": true, + "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-c/-/testing-peer-deps-c-2.0.0.tgz", + "version": "2.0.0", }, }, "edgesIn": Set { EdgeIn { "from": "", - "name": "@nlf/shrinkwrapped-dep-updates-a", - "spec": "^2.0.0", + "name": "@isaacs/testing-peer-deps-d", + "spec": "2", "type": "prod", }, }, "edgesOut": Map { - "@nlf/shrinkwrapped-dep-updates-b" => EdgeOut { - "name": "@nlf/shrinkwrapped-dep-updates-b", - "spec": "^2.0.0", - "to": "node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-b", - "type": "prod", - }, - "@nlf/shrinkwrapped-dep-updates-c" => EdgeOut { - "name": "@nlf/shrinkwrapped-dep-updates-c", - "spec": "^1.0.0", - "to": "node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-c", - "type": "prod", - }, - "@nlf/shrinkwrapped-dep-updates-e" => EdgeOut { - "name": "@nlf/shrinkwrapped-dep-updates-e", - "spec": "^1.0.0", - "to": "node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-e", + "@isaacs/testing-peer-deps-a" => EdgeOut { + "name": "@isaacs/testing-peer-deps-a", + "spec": "2", + "to": "node_modules/@isaacs/testing-peer-deps-d/node_modules/@isaacs/testing-peer-deps-a", "type": "prod", }, }, - "hasShrinkwrap": true, - "location": "node_modules/@nlf/shrinkwrapped-dep-updates-a", - "name": "@nlf/shrinkwrapped-dep-updates-a", - "path": "{CWD}/test/arborist/tap-testdir-reify-tracks-changes-of-shrinkwrapped-dep-correctly/node_modules/@nlf/shrinkwrapped-dep-updates-a", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-a/-/shrinkwrapped-dep-updates-a-2.0.0.tgz", + "location": "node_modules/@isaacs/testing-peer-deps-d", + "name": "@isaacs/testing-peer-deps-d", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package/node_modules/@isaacs/testing-peer-deps-d", + "resolved": "https://registry.npmjs.org/@isaacs/testing-peer-deps-d/-/testing-peer-deps-d-2.0.0.tgz", "version": "2.0.0", }, }, "edgesOut": Map { - "@nlf/shrinkwrapped-dep-updates-a" => EdgeOut { - "name": "@nlf/shrinkwrapped-dep-updates-a", - "spec": "^2.0.0", - "to": "node_modules/@nlf/shrinkwrapped-dep-updates-a", + "@isaacs/testing-peer-deps-b" => EdgeOut { + "name": "@isaacs/testing-peer-deps-b", + "spec": "1", + "to": "node_modules/@isaacs/testing-peer-deps-b", + "type": "prod", + }, + "@isaacs/testing-peer-deps-d" => EdgeOut { + "name": "@isaacs/testing-peer-deps-d", + "spec": "2", + "to": "node_modules/@isaacs/testing-peer-deps-d", "type": "prod", }, }, "isProjectRoot": true, "location": "", - "name": "tap-testdir-reify-tracks-changes-of-shrinkwrapped-dep-correctly", - "path": "{CWD}/test/arborist/tap-testdir-reify-tracks-changes-of-shrinkwrapped-dep-correctly", + "name": "tap-testdir-reify-testing-peer-deps-package", + "packageName": "@isaacs/testing-peer-deps", + "path": "{CWD}/test/arborist/tap-testdir-reify-testing-peer-deps-package", + "version": "2.0.0", } ` @@ -53494,6 +52468,39 @@ Object { } ` +exports[`test/arborist/reify.js TAP workspaces reify workspaces with overrides > should retain override version (4.1.3) 1`] = ` +Object { + "lockfileVersion": 3, + "name": "workspace-with-overrides", + "packages": Object { + "": Object { + "name": "workspace-with-overrides", + "workspaces": Array [ + "ws", + ], + }, + "node_modules/a": Object { + "link": true, + "resolved": "ws", + }, + "node_modules/arg": Object { + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "license": "MIT", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "version": "4.1.3", + }, + "ws": Object { + "dependencies": Object { + "arg": "4.1.2", + }, + "name": "a", + "version": "1.0.0", + }, + }, + "requires": true, +} +` + exports[`test/arborist/reify.js TAP workspaces root as-a-workspace > should produce expected package-lock file 1`] = ` Object { "lockfileVersion": 3, diff --git a/workspaces/arborist/tap-snapshots/test/audit-report.js.test.cjs b/workspaces/arborist/tap-snapshots/test/audit-report.js.test.cjs index cc1354e64c818..a31e072da2f79 100644 --- a/workspaces/arborist/tap-snapshots/test/audit-report.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/audit-report.js.test.cjs @@ -1131,375 +1131,10 @@ exports[`test/audit-report.js TAP audit outdated nyc and mkdirp with before: opt "name": "nyc", "version": "15.1.0", "isSemVerMajor": true - } - }, - "nyc": { - "name": "nyc", - "severity": "low", - "isDirect": true, - "via": [ - "mkdirp", - "yargs" - ], - "effects": [], - "range": "6.2.0-alpha - 13.1.0", - "nodes": [ - "node_modules/nyc" - ], - "fixAvailable": { - "name": "nyc", - "version": "15.1.0", - "isSemVerMajor": true - } - }, - "optimist": { - "name": "optimist", - "severity": "low", - "isDirect": false, - "via": [ - "minimist" - ], - "effects": [ - "handlebars" - ], - "range": ">=0.6.0", - "nodes": [ - "node_modules/nyc/node_modules/optimist" - ], - "fixAvailable": true - }, - "os-locale": { - "name": "os-locale", - "severity": "low", - "isDirect": false, - "via": [ - "mem" - ], - "effects": [ - "yargs" - ], - "range": "2.0.0 - 3.0.0", - "nodes": [ - "node_modules/nyc/node_modules/os-locale" - ], - "fixAvailable": { - "name": "nyc", - "version": "15.1.0", - "isSemVerMajor": true - } - }, - "set-value": { - "name": "set-value", - "severity": "high", - "isDirect": false, - "via": [ - { - "source": 1012, - "name": "set-value", - "dependency": "set-value", - "title": "Prototype Pollution", - "url": "https://npmjs.com/advisories/1012", - "severity": "high", - "range": "<2.0.1 || >=3.0.0 <3.0.1" - } - ], - "effects": [ - "union-value" - ], - "range": "<=2.0.0 || 3.0.0", - "nodes": [ - "node_modules/nyc/node_modules/set-value", - "node_modules/nyc/node_modules/union-value/node_modules/set-value" - ], - "fixAvailable": true - }, - "union-value": { - "name": "union-value", - "severity": "high", - "isDirect": false, - "via": [ - "set-value" - ], - "effects": [], - "range": "<=1.0.0 || 2.0.0", - "nodes": [ - "node_modules/nyc/node_modules/union-value" - ], - "fixAvailable": true - }, - "yargs": { - "name": "yargs", - "severity": "low", - "isDirect": false, - "via": [ - "os-locale" - ], - "effects": [ - "nyc" - ], - "range": "8.0.1 - 11.1.0 || 12.0.0-candidate.0 - 12.0.1", - "nodes": [ - "node_modules/nyc/node_modules/yargs" - ], - "fixAvailable": { - "name": "nyc", - "version": "15.1.0", - "isSemVerMajor": true - } - } - }, - "metadata": { - "vulnerabilities": { - "info": 0, - "low": 8, - "moderate": 0, - "high": 4, - "critical": 1, - "total": 13 - }, - "dependencies": { - "prod": 318, - "dev": 0, - "optional": 12, - "peer": 0, - "peerOptional": 0, - "total": 329 - } - } -} -` - -exports[`test/audit-report.js TAP audit outdated nyc and mkdirp with newer endpoint > json version 1`] = ` -{ - "auditReportVersion": 2, - "vulnerabilities": { - "handlebars": { - "name": "handlebars", - "severity": "critical", - "isDirect": false, - "via": [ - { - "source": 1164, - "name": "handlebars", - "dependency": "handlebars", - "title": "Prototype Pollution", - "url": "https://npmjs.com/advisories/1164", - "severity": "high", - "range": "<3.0.8 || >=4.0.0 <4.3.0" - }, - { - "source": 1300, - "name": "handlebars", - "dependency": "handlebars", - "title": "Denial of Service", - "url": "https://npmjs.com/advisories/1300", - "severity": "moderate", - "range": ">=4.0.0 <4.4.5" - }, - { - "source": 1316, - "name": "handlebars", - "dependency": "handlebars", - "title": "Arbitrary Code Execution", - "url": "https://npmjs.com/advisories/1316", - "severity": "high", - "range": "<3.0.8 || >=4.0.0 <4.5.2" - }, - { - "source": 1324, - "name": "handlebars", - "dependency": "handlebars", - "title": "Arbitrary Code Execution", - "url": "https://npmjs.com/advisories/1324", - "severity": "high", - "range": "<3.0.8 || >=4.0.0 <4.5.3" - }, - { - "source": 1325, - "name": "handlebars", - "dependency": "handlebars", - "title": "Prototype Pollution", - "url": "https://npmjs.com/advisories/1325", - "severity": "high", - "range": "<3.0.8 || >=4.0.0 <4.5.3" - }, - { - "source": 755, - "name": "handlebars", - "dependency": "handlebars", - "title": "Prototype Pollution", - "url": "https://npmjs.com/advisories/755", - "severity": "critical", - "range": "<=4.0.13 || >=4.1.0 <4.1.2" - }, - "optimist" - ], - "effects": [], - "range": "<=4.7.3", - "nodes": [ - "node_modules/nyc/node_modules/handlebars" - ], - "fixAvailable": true - }, - "kind-of": { - "name": "kind-of", - "severity": "low", - "isDirect": false, - "via": [ - { - "source": 1490, - "name": "kind-of", - "dependency": "kind-of", - "title": "Validation Bypass", - "url": "https://npmjs.com/advisories/1490", - "severity": "low", - "range": ">=6.0.0 <6.0.3" - } - ], - "effects": [], - "range": "6.0.0 - 6.0.2", - "nodes": [ - "node_modules/nyc/node_modules/base/node_modules/kind-of", - "node_modules/nyc/node_modules/define-property/node_modules/kind-of", - "node_modules/nyc/node_modules/extglob/node_modules/kind-of", - "node_modules/nyc/node_modules/micromatch/node_modules/kind-of", - "node_modules/nyc/node_modules/nanomatch/node_modules/kind-of", - "node_modules/nyc/node_modules/snapdragon-node/node_modules/kind-of", - "node_modules/nyc/node_modules/test-exclude/node_modules/kind-of", - "node_modules/nyc/node_modules/use/node_modules/kind-of" - ], - "fixAvailable": true - }, - "lodash": { - "name": "lodash", - "severity": "high", - "isDirect": false, - "via": [ - { - "source": 1065, - "name": "lodash", - "dependency": "lodash", - "title": "Prototype Pollution", - "url": "https://npmjs.com/advisories/1065", - "severity": "high", - "range": "<4.17.12" - }, - { - "source": 782, - "name": "lodash", - "dependency": "lodash", - "title": "Prototype Pollution", - "url": "https://npmjs.com/advisories/782", - "severity": "high", - "range": "<4.17.11" - } - ], - "effects": [], - "range": "<=4.17.11", - "nodes": [ - "node_modules/nyc/node_modules/lodash" - ], - "fixAvailable": true - }, - "mem": { - "name": "mem", - "severity": "low", - "isDirect": false, - "via": [ - { - "source": 1084, - "name": "mem", - "dependency": "mem", - "title": "Denial of Service", - "url": "https://npmjs.com/advisories/1084", - "severity": "low", - "range": "<4.0.0" - } - ], - "effects": [ - "os-locale" - ], - "range": "<4.0.0", - "nodes": [ - "node_modules/nyc/node_modules/mem" - ], - "fixAvailable": { - "name": "nyc", - "version": "15.1.0", - "isSemVerMajor": true - } - }, - "minimist": { - "name": "minimist", - "severity": "low", - "isDirect": false, - "via": [ - { - "source": 1179, - "name": "minimist", - "dependency": "minimist", - "title": "Prototype Pollution", - "url": "https://npmjs.com/advisories/1179", - "severity": "low", - "range": "<0.2.1 || >=1.0.0 <1.2.3" - } - ], - "effects": [ - "mkdirp", - "optimist" - ], - "range": "<0.2.1 || >=1.0.0 <1.2.3", - "nodes": [ - "node_modules/minimist", - "node_modules/nyc/node_modules/minimist" - ], - "fixAvailable": { - "name": "nyc", - "version": "15.1.0", - "isSemVerMajor": true - } - }, - "mixin-deep": { - "name": "mixin-deep", - "severity": "high", - "isDirect": false, - "via": [ - { - "source": 1013, - "name": "mixin-deep", - "dependency": "mixin-deep", - "title": "Prototype Pollution", - "url": "https://npmjs.com/advisories/1013", - "severity": "high", - "range": "<1.3.2 || >=2.0.0 <2.0.1" - } - ], - "effects": [], - "range": "<=1.3.1 || 2.0.0", - "nodes": [ - "node_modules/nyc/node_modules/mixin-deep" - ], - "fixAvailable": true - }, - "mkdirp": { - "name": "mkdirp", - "severity": "low", - "isDirect": true, - "via": [ - "minimist" - ], - "effects": [ - "nyc" - ], - "range": "0.4.1 - 0.5.1", - "nodes": [ - "node_modules/mkdirp", - "node_modules/nyc/node_modules/mkdirp" - ], - "fixAvailable": { - "name": "nyc", - "version": "15.1.0", - "isSemVerMajor": true + }, + "fixBlockedByReleaseAge": { + "version": "0.5.5", + "before": "2020-01-01T00:00:00.000Z" } }, "nyc": { diff --git a/workspaces/arborist/tap-snapshots/test/calc-dep-flags.js.test.cjs b/workspaces/arborist/tap-snapshots/test/calc-dep-flags.js.test.cjs index d56b3921c8f42..e3318d2e0ad69 100644 --- a/workspaces/arborist/tap-snapshots/test/calc-dep-flags.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/calc-dep-flags.js.test.cjs @@ -186,6 +186,12 @@ ArboristNode { "spec": "*", "type": "optional", }, + EdgeIn { + "from": "node_modules/peeroptional", + "name": "optional", + "spec": "*", + "type": "prod", + }, }, "edgesOut": Map { "devoptional" => EdgeOut { @@ -246,6 +252,31 @@ ArboristNode { "peer": true, "version": "1.2.3", }, + "peeroptional" => ArboristNode { + "edgesIn": Set { + EdgeIn { + "from": "", + "name": "peeroptional", + "spec": "*", + "type": "peerOptional", + }, + }, + "edgesOut": Map { + "optional" => EdgeOut { + "name": "optional", + "spec": "*", + "to": "node_modules/optional", + "type": "prod", + }, + }, + "extraneous": true, + "location": "node_modules/peeroptional", + "name": "peeroptional", + "optional": true, + "path": "/x/node_modules/peeroptional", + "peer": true, + "version": "1.2.3", + }, "prod" => ArboristNode { "edgesIn": Set { EdgeIn { @@ -328,6 +359,12 @@ ArboristNode { "to": "node_modules/peer", "type": "peer", }, + "peeroptional" => EdgeOut { + "name": "peeroptional", + "spec": "*", + "to": "node_modules/peeroptional", + "type": "peerOptional", + }, "prod" => EdgeOut { "name": "prod", "spec": "*", @@ -423,215 +460,3 @@ ArboristNode { "peer": true, } ` - -exports[`test/calc-dep-flags.js TAP set parents to not extraneous when visiting > after 1`] = ` -ArboristNode { - "children": Map { - "asdf" => ArboristNode { - "children": Map { - "baz" => ArboristNode { - "location": "node_modules/asdf/node_modules/baz", - "name": "baz", - "path": "/some/path/node_modules/asdf/node_modules/baz", - "version": "1.2.3", - }, - }, - "location": "node_modules/asdf", - "name": "asdf", - "path": "/some/path/node_modules/asdf", - "version": "1.2.3", - }, - "baz" => ArboristLink { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "baz", - "spec": "file:node_modules/asdf/node_modules/baz", - "type": "prod", - }, - }, - "location": "node_modules/baz", - "name": "baz", - "path": "/some/path/node_modules/baz", - "realpath": "/some/path/node_modules/asdf/node_modules/baz", - "resolved": "file:asdf/node_modules/baz", - "target": ArboristNode { - "location": "node_modules/asdf/node_modules/baz", - }, - "version": "1.2.3", - }, - "foo" => ArboristLink { - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "foo", - "spec": "file:bar/foo", - "type": "prod", - }, - }, - "location": "node_modules/foo", - "name": "foo", - "path": "/some/path/node_modules/foo", - "realpath": "/some/path/bar/foo", - "resolved": "file:../bar/foo", - "target": ArboristNode { - "location": "bar/foo", - }, - "version": "1.2.3", - }, - }, - "edgesOut": Map { - "baz" => EdgeOut { - "name": "baz", - "spec": "file:node_modules/asdf/node_modules/baz", - "to": "node_modules/baz", - "type": "prod", - }, - "foo" => EdgeOut { - "name": "foo", - "spec": "file:bar/foo", - "to": "node_modules/foo", - "type": "prod", - }, - }, - "fsChildren": Set { - ArboristNode { - "fsChildren": Set { - ArboristNode { - "location": "bar/foo", - "name": "foo", - "path": "/some/path/bar/foo", - "version": "1.2.3", - }, - }, - "location": "bar", - "name": "bar", - "path": "/some/path/bar", - }, - }, - "isProjectRoot": true, - "location": "", - "name": "path", - "path": "/some/path", -} -` - -exports[`test/calc-dep-flags.js TAP set parents to not extraneous when visiting > before 1`] = ` -ArboristNode { - "children": Map { - "asdf" => ArboristNode { - "children": Map { - "baz" => ArboristNode { - "dev": true, - "extraneous": true, - "location": "node_modules/asdf/node_modules/baz", - "name": "baz", - "optional": true, - "path": "/some/path/node_modules/asdf/node_modules/baz", - "peer": true, - "version": "1.2.3", - }, - }, - "dev": true, - "extraneous": true, - "location": "node_modules/asdf", - "name": "asdf", - "optional": true, - "path": "/some/path/node_modules/asdf", - "peer": true, - "version": "1.2.3", - }, - "baz" => ArboristLink { - "dev": true, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "baz", - "spec": "file:node_modules/asdf/node_modules/baz", - "type": "prod", - }, - }, - "extraneous": true, - "location": "node_modules/baz", - "name": "baz", - "optional": true, - "path": "/some/path/node_modules/baz", - "peer": true, - "realpath": "/some/path/node_modules/asdf/node_modules/baz", - "resolved": "file:asdf/node_modules/baz", - "target": ArboristNode { - "location": "node_modules/asdf/node_modules/baz", - }, - "version": "1.2.3", - }, - "foo" => ArboristLink { - "dev": true, - "edgesIn": Set { - EdgeIn { - "from": "", - "name": "foo", - "spec": "file:bar/foo", - "type": "prod", - }, - }, - "extraneous": true, - "location": "node_modules/foo", - "name": "foo", - "optional": true, - "path": "/some/path/node_modules/foo", - "peer": true, - "realpath": "/some/path/bar/foo", - "resolved": "file:../bar/foo", - "target": ArboristNode { - "location": "bar/foo", - }, - "version": "1.2.3", - }, - }, - "dev": true, - "edgesOut": Map { - "baz" => EdgeOut { - "name": "baz", - "spec": "file:node_modules/asdf/node_modules/baz", - "to": "node_modules/baz", - "type": "prod", - }, - "foo" => EdgeOut { - "name": "foo", - "spec": "file:bar/foo", - "to": "node_modules/foo", - "type": "prod", - }, - }, - "extraneous": true, - "fsChildren": Set { - ArboristNode { - "dev": true, - "extraneous": true, - "fsChildren": Set { - ArboristNode { - "dev": true, - "extraneous": true, - "location": "bar/foo", - "name": "foo", - "optional": true, - "path": "/some/path/bar/foo", - "peer": true, - "version": "1.2.3", - }, - }, - "location": "bar", - "name": "bar", - "optional": true, - "path": "/some/path/bar", - "peer": true, - }, - }, - "isProjectRoot": true, - "location": "", - "name": "path", - "optional": true, - "path": "/some/path", - "peer": true, -} -` diff --git a/workspaces/arborist/tap-snapshots/test/diff.js.test.cjs b/workspaces/arborist/tap-snapshots/test/diff.js.test.cjs index 5ce161a3be681..18afa6649c831 100644 --- a/workspaces/arborist/tap-snapshots/test/diff.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/diff.js.test.cjs @@ -267,52 +267,6 @@ Diff { } ` -exports[`test/diff.js TAP diff doesnt break unchanged shrinkwrapped deps > made no changes 1`] = ` -Diff { - "action": null, - "actual": Node { - "name": "a", - "path": "/path/to/actual", - "integrity": null, - }, - "ideal": Node { - "name": "a", - "path": "/path/to/actual", - "integrity": null, - }, - "leaves": Array [ - "/path/to/actual/node_modules/shrinkwrapped-dep", - ], - "unchanged": Array [ - "/path/to/actual/node_modules/regular-dep", - "/path/to/actual/node_modules/regular-dep/node_modules/shrinkwrapped-inner", - "/path/to/actual/node_modules/regular-dep/node_modules/shrinkwrapped-inner/node_modules/shrinkwrap-inner-c", - ], - "removed": Array [], - "children": Array [ - Diff { - "action": null, - "actual": Node { - "name": "shrinkwrapped-dep", - "path": "/path/to/actual/node_modules/shrinkwrapped-dep", - "integrity": "sha512-ddd", - }, - "ideal": Node { - "name": "shrinkwrapped-dep", - "path": "/path/to/actual/node_modules/shrinkwrapped-dep", - "integrity": "sha512-ddd", - }, - "leaves": Array [ - "/path/to/actual/node_modules/shrinkwrapped-dep", - ], - "unchanged": Array [], - "removed": Array [], - "children": Array [], - }, - ], -} -` - exports[`test/diff.js TAP extraneous pruning in workspaces > prune in workspace A 1`] = ` Diff { "action": null, diff --git a/workspaces/arborist/tap-snapshots/test/edge.js.test.cjs b/workspaces/arborist/tap-snapshots/test/edge.js.test.cjs index 17dc0b0c9fb0b..70be4d7566d86 100644 --- a/workspaces/arborist/tap-snapshots/test/edge.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/edge.js.test.cjs @@ -52,6 +52,7 @@ Edge { "from": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "b" => Edge { @@ -69,6 +70,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -91,6 +93,7 @@ Edge { "root": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -122,6 +125,7 @@ Edge { "to": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set { Edge { "peerConflicted": false, @@ -139,6 +143,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -173,6 +178,7 @@ Edge { "from": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "b" => Edge { @@ -190,6 +196,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -212,6 +219,7 @@ Edge { "root": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -243,6 +251,7 @@ Edge { "to": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set { Edge { "peerConflicted": false, @@ -260,6 +269,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -294,6 +304,7 @@ Edge { "from": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -334,6 +345,7 @@ Edge { "from": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "aa" => Edge { @@ -351,6 +363,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "b" => Edge { @@ -368,6 +381,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -390,6 +404,7 @@ Edge { "root": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -424,6 +439,7 @@ Edge { "to": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set { Edge { "peerConflicted": false, @@ -441,6 +457,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "b" => Edge { @@ -458,6 +475,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -480,6 +498,7 @@ Edge { "root": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -516,6 +535,7 @@ Edge { "from": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "aa" => Edge { @@ -533,6 +553,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -576,6 +597,7 @@ Edge { "from": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "aa" => Edge { @@ -593,6 +615,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set { Edge { "peerConflicted": false, @@ -610,6 +633,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -645,6 +669,7 @@ Edge { "to": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set { Edge { "peerConflicted": false, @@ -662,6 +687,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "b" => Edge { @@ -679,6 +705,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -701,6 +728,7 @@ Edge { "root": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -730,13 +758,14 @@ Edge { } ` -exports[`test/edge.js TAP > peer dep at top level, nesting is ok 1`] = ` +exports[`test/edge.js TAP > peer dep at top level, nesting allowed 1`] = ` Edge { "dev": false, "error": null, "from": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "a" => Edge { @@ -766,6 +795,7 @@ Edge { "to": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set { Edge { "peerConflicted": false, @@ -783,6 +813,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "a" => Edge { @@ -805,6 +836,7 @@ Edge { "root": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "a" => Edge { @@ -831,13 +863,14 @@ Edge { } ` -exports[`test/edge.js TAP > peer dep below top level, nesting not ok 1`] = ` +exports[`test/edge.js TAP > peer dep below top level, nesting disallowed 1`] = ` Edge { "dev": false, "error": "PEER LOCAL", "from": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "aa" => Edge { @@ -855,6 +888,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -877,6 +911,7 @@ Edge { "root": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -908,6 +943,7 @@ Edge { "to": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set { Edge { "peerConflicted": false, @@ -925,6 +961,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "aa" => Edge { @@ -942,6 +979,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -964,6 +1002,7 @@ Edge { "root": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -993,13 +1032,14 @@ Edge { } ` -exports[`test/edge.js TAP > peer dep below top level, parallel ok 1`] = ` +exports[`test/edge.js TAP > peer dep below top level, parallel allowed 1`] = ` Edge { "dev": false, "error": null, "from": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "b" => Edge { @@ -1017,6 +1057,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -1039,6 +1080,7 @@ Edge { "root": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { @@ -1070,6 +1112,7 @@ Edge { "to": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set { Edge { "peerConflicted": false, @@ -1087,6 +1130,7 @@ Edge { "parent": Object { "addEdgeIn": Function addEdgeIn(edge), "addEdgeOut": Function addEdgeOut(edge), + "deleteEdgeIn": Function deleteEdgeIn(edge), "edgesIn": Set {}, "edgesOut": Map { "missing" => Edge { diff --git a/workspaces/arborist/tap-snapshots/test/link.js.test.cjs b/workspaces/arborist/tap-snapshots/test/link.js.test.cjs index 1978f7dd6f575..268a5b5ef7bdc 100644 --- a/workspaces/arborist/tap-snapshots/test/link.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/link.js.test.cjs @@ -15,7 +15,7 @@ Link { "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -25,7 +25,10 @@ Link { "linksIn": Set {}, "location": "../../../../../some/other/path", "name": "path", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/some/other/path", "peer": true, "queryContext": Object {}, @@ -45,7 +48,7 @@ exports[`test/link.js TAP > instantiate without providing target 1`] = ` "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -60,7 +63,7 @@ exports[`test/link.js TAP > instantiate without providing target 1`] = ` "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -71,7 +74,10 @@ exports[`test/link.js TAP > instantiate without providing target 1`] = ` }, "location": "", "name": "path", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/some/kind/of/path", "peer": true, "queryContext": Object {}, @@ -87,7 +93,10 @@ exports[`test/link.js TAP > instantiate without providing target 1`] = ` "linksIn": Set {}, "location": "../../../../../some/other/path", "name": "path", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/some/other/path", "peer": true, "queryContext": Object {}, @@ -104,7 +113,7 @@ exports[`test/link.js TAP > instantiate without providing target 1`] = ` "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -115,7 +124,10 @@ exports[`test/link.js TAP > instantiate without providing target 1`] = ` }, "location": "", "name": "path", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/some/kind/of/path", "peer": true, "queryContext": Object {}, diff --git a/workspaces/arborist/tap-snapshots/test/node.js.test.cjs b/workspaces/arborist/tap-snapshots/test/node.js.test.cjs index c025e3509a150..4ad88295da7ed 100644 --- a/workspaces/arborist/tap-snapshots/test/node.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/node.js.test.cjs @@ -16,7 +16,7 @@ exports[`test/node.js TAP basic instantiation > just a lone root node 1`] = ` "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -27,6 +27,7 @@ exports[`test/node.js TAP basic instantiation > just a lone root node 1`] = ` "linksIn": Set {}, "location": "", "name": "root", + "npmExtensionApplied": null, "optional": true, "overrides": &ref_2 OverrideSet { "children": Map { @@ -41,6 +42,8 @@ exports[`test/node.js TAP basic instantiation > just a lone root node 1`] = ` }, "parent": undefined, }, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root", "peer": true, "queryContext": Object {}, @@ -206,7 +209,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -216,7 +219,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "linksIn": Set {}, "location": "node_modules/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/node_modules/foo", "peer": true, "queryContext": Object {}, @@ -233,7 +239,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -243,7 +249,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "linksIn": Set {}, "location": "node_modules/unknown", "name": "unknown", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/node_modules/unknown", "peer": true, "queryContext": Object {}, @@ -277,7 +286,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -297,7 +306,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -307,7 +316,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "linksIn": Set {}, "location": "node_modules/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/node_modules/foo", "peer": true, "queryContext": Object {}, @@ -318,7 +330,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works }, "location": "foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/foo", "peer": true, "queryContext": Object {}, @@ -337,7 +352,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -353,7 +368,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -363,7 +378,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "linksIn": Set {}, "location": "node_modules/unknown", "name": "unknown", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/node_modules/unknown", "peer": true, "queryContext": Object {}, @@ -374,7 +392,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works }, "location": "unknown", "name": "unknown", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/unknown", "peer": true, "queryContext": Object {}, @@ -384,7 +405,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -402,7 +423,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -412,7 +433,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "linksIn": Set {}, "location": "node_modules/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/node_modules/foo", "peer": true, "queryContext": Object {}, @@ -430,7 +454,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -450,7 +474,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -460,7 +484,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "linksIn": Set {}, "location": "node_modules/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/node_modules/foo", "peer": true, "queryContext": Object {}, @@ -471,7 +498,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works }, "location": "foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/foo", "peer": true, "queryContext": Object {}, @@ -489,7 +519,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -499,7 +529,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "linksIn": Set {}, "location": "node_modules/unknown", "name": "unknown", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/node_modules/unknown", "peer": true, "queryContext": Object {}, @@ -517,7 +550,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -533,7 +566,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -543,7 +576,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "linksIn": Set {}, "location": "node_modules/unknown", "name": "unknown", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/node_modules/unknown", "peer": true, "queryContext": Object {}, @@ -554,7 +590,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works }, "location": "unknown", "name": "unknown", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/unknown", "peer": true, "queryContext": Object {}, @@ -569,7 +608,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "linksIn": Set {}, "location": "", "name": "workspaces_root", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root", "peer": true, "queryContext": Object {}, @@ -587,7 +629,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -607,7 +649,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -617,7 +659,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "linksIn": Set {}, "location": "node_modules/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/node_modules/foo", "peer": true, "queryContext": Object {}, @@ -628,7 +673,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works }, "location": "foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/foo", "peer": true, "queryContext": Object {}, @@ -647,7 +695,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -663,7 +711,7 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -673,7 +721,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works "linksIn": Set {}, "location": "node_modules/unknown", "name": "unknown", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/node_modules/unknown", "peer": true, "queryContext": Object {}, @@ -684,7 +735,10 @@ exports[`test/node.js TAP set workspaces > should setup edges out for each works }, "location": "unknown", "name": "unknown", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/workspaces_root/unknown", "peer": true, "queryContext": Object {}, @@ -713,7 +767,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -723,7 +777,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -751,7 +808,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -760,7 +817,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -803,7 +863,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -812,7 +872,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -822,7 +885,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -831,7 +894,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -861,7 +927,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -870,7 +936,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -893,7 +962,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -902,7 +971,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -925,7 +997,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -934,7 +1006,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -957,7 +1032,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -966,7 +1041,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -985,7 +1063,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -994,7 +1072,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -1021,7 +1102,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -1037,7 +1118,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -1047,7 +1128,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -1058,7 +1142,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p }, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -1098,7 +1185,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -1116,7 +1203,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -1126,7 +1213,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -1154,7 +1244,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -1163,7 +1253,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -1206,7 +1299,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -1215,7 +1308,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -1225,7 +1321,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -1234,7 +1330,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -1257,7 +1356,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -1266,7 +1365,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -1296,7 +1398,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -1305,7 +1407,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -1328,7 +1433,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -1337,7 +1442,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -1360,7 +1468,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -1369,7 +1477,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -1392,7 +1503,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -1401,7 +1512,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -1420,7 +1534,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -1429,7 +1543,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -1456,7 +1573,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -1472,7 +1589,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -1482,7 +1599,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -1493,7 +1613,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p }, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -1513,7 +1636,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -1523,7 +1646,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -1551,7 +1677,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -1560,7 +1686,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -1578,7 +1707,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -1588,7 +1717,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -1602,7 +1734,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "", "name": "root", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root", "peer": true, "queryContext": Object {}, @@ -1624,7 +1759,7 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -1633,7 +1768,10 @@ exports[`test/node.js TAP testing with dep tree with meta > add new meta under p "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -1672,7 +1810,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -1681,7 +1819,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -1724,7 +1865,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -1733,7 +1874,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -1743,7 +1887,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -1752,7 +1896,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -1782,7 +1929,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -1791,7 +1938,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -1814,7 +1964,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -1823,7 +1973,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -1846,7 +1999,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -1855,7 +2008,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -1878,7 +2034,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -1887,7 +2043,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -1906,7 +2065,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -1915,7 +2074,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -1955,7 +2117,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -1983,7 +2145,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -1992,7 +2154,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -2035,7 +2200,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -2044,7 +2209,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -2054,7 +2222,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -2063,7 +2231,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -2086,7 +2257,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -2095,7 +2266,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -2125,7 +2299,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -2134,7 +2308,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -2164,7 +2341,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -2173,7 +2350,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -2196,7 +2376,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -2205,7 +2385,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -2228,7 +2411,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -2237,7 +2420,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -2260,7 +2446,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -2269,7 +2455,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -2288,7 +2477,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -2297,7 +2486,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -2312,7 +2504,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "", "name": "root", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root", "peer": true, "queryContext": Object {}, @@ -2334,7 +2529,7 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -2343,7 +2538,10 @@ exports[`test/node.js TAP testing with dep tree with meta > initial load with so "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -2394,7 +2592,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -2403,7 +2601,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -2413,7 +2614,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -2422,7 +2623,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -2452,7 +2656,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -2461,7 +2665,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -2484,7 +2691,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -2493,7 +2700,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -2516,7 +2726,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -2525,7 +2735,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -2548,7 +2761,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -2557,7 +2770,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -2576,7 +2792,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -2585,7 +2801,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -2618,7 +2837,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -2627,7 +2846,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -2667,7 +2889,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -2707,7 +2929,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -2716,7 +2938,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -2726,7 +2951,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -2735,7 +2960,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -2758,7 +2986,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -2767,7 +2995,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -2797,7 +3028,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -2806,7 +3037,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -2829,7 +3063,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -2838,7 +3072,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -2861,7 +3098,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -2870,7 +3107,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -2893,7 +3133,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -2902,7 +3142,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -2921,7 +3164,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -2930,7 +3173,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -2963,7 +3209,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -2972,7 +3218,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -2987,7 +3236,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "", "name": "root", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root", "peer": true, "queryContext": Object {}, @@ -3009,7 +3261,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -3018,7 +3270,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move meta to top lev "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -3069,7 +3324,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -3078,7 +3333,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -3088,7 +3346,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -3097,7 +3355,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -3124,7 +3385,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -3133,7 +3394,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -3156,7 +3420,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -3165,7 +3429,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -3188,7 +3455,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -3197,7 +3464,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -3220,7 +3490,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -3229,7 +3499,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -3248,7 +3521,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -3257,7 +3530,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -3277,7 +3553,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -3287,7 +3563,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -3318,7 +3597,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -3334,7 +3613,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -3344,7 +3623,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -3355,7 +3637,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top }, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -3395,7 +3680,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -3435,7 +3720,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -3444,7 +3729,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -3454,7 +3742,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -3463,7 +3751,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -3486,7 +3777,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -3495,7 +3786,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -3522,7 +3816,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -3531,7 +3825,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -3554,7 +3851,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -3563,7 +3860,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -3586,7 +3886,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -3595,7 +3895,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -3618,7 +3921,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -3627,7 +3930,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -3646,7 +3952,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -3655,7 +3961,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -3673,7 +3982,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -3683,7 +3992,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -3702,7 +4014,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -3712,7 +4024,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -3743,7 +4058,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -3759,7 +4074,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -3769,7 +4084,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -3780,7 +4098,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top }, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -3795,7 +4116,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "", "name": "root", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root", "peer": true, "queryContext": Object {}, @@ -3817,7 +4141,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -3826,7 +4150,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -3877,7 +4204,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -3886,7 +4213,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -3896,7 +4226,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -3905,7 +4235,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -3932,7 +4265,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -3941,7 +4274,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -3964,7 +4300,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -3973,7 +4309,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -3996,7 +4335,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -4005,7 +4344,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -4028,7 +4370,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -4037,7 +4379,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -4056,7 +4401,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -4065,7 +4410,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -4085,7 +4433,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -4095,7 +4443,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -4126,7 +4477,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -4142,7 +4493,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -4152,7 +4503,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -4163,7 +4517,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top }, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -4203,7 +4560,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -4243,7 +4600,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -4252,7 +4609,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -4262,7 +4622,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -4271,7 +4631,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -4294,7 +4657,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -4303,7 +4666,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -4330,7 +4696,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -4339,7 +4705,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -4362,7 +4731,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -4371,7 +4740,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -4394,7 +4766,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -4403,7 +4775,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -4426,7 +4801,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -4435,7 +4810,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -4454,7 +4832,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -4463,7 +4841,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -4481,7 +4862,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -4491,7 +4872,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -4510,7 +4894,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -4520,7 +4904,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -4551,7 +4938,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -4567,7 +4954,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -4577,7 +4964,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -4588,7 +4978,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top }, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -4603,7 +4996,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "", "name": "root", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root", "peer": true, "queryContext": Object {}, @@ -4625,7 +5021,7 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -4634,7 +5030,10 @@ exports[`test/node.js TAP testing with dep tree with meta > move new meta to top "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -4663,7 +5062,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -4673,7 +5072,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -4701,7 +5103,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -4710,7 +5112,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -4753,7 +5158,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -4762,7 +5167,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -4772,7 +5180,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -4781,7 +5189,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -4811,7 +5222,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -4820,7 +5231,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -4843,7 +5257,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -4852,7 +5266,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -4875,7 +5292,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -4884,7 +5301,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -4907,7 +5327,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -4916,7 +5336,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -4935,7 +5358,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -4944,7 +5367,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -4971,7 +5397,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -4987,7 +5413,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -4997,7 +5423,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -5008,7 +5437,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde }, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -5048,7 +5480,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -5066,7 +5498,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -5076,7 +5508,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -5104,7 +5539,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -5113,7 +5548,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -5156,7 +5594,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -5165,7 +5603,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -5175,7 +5616,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -5184,7 +5625,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -5207,7 +5651,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -5216,7 +5660,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -5246,7 +5693,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -5255,7 +5702,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -5278,7 +5728,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -5287,7 +5737,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -5310,7 +5763,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -5319,7 +5772,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -5342,7 +5798,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -5351,7 +5807,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -5370,7 +5829,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -5379,7 +5838,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -5406,7 +5868,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -5422,7 +5884,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -5432,7 +5894,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -5443,7 +5908,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde }, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -5463,7 +5931,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -5473,7 +5941,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -5501,7 +5972,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -5510,7 +5981,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -5528,7 +6002,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -5538,7 +6012,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -5552,7 +6029,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "", "name": "root", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root", "peer": true, "queryContext": Object {}, @@ -5574,7 +6054,7 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -5583,7 +6063,10 @@ exports[`test/node.js TAP testing with dep tree without meta > add new meta unde "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -5622,7 +6105,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -5631,7 +6114,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -5674,7 +6160,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -5683,7 +6169,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -5693,7 +6182,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -5702,7 +6191,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -5732,7 +6224,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -5741,7 +6233,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -5764,7 +6259,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -5773,7 +6268,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -5796,7 +6294,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -5805,7 +6303,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -5828,7 +6329,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -5837,7 +6338,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -5856,7 +6360,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -5865,7 +6369,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -5905,7 +6412,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -5933,7 +6440,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -5942,7 +6449,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -5985,7 +6495,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -5994,7 +6504,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -6004,7 +6517,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -6013,7 +6526,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -6036,7 +6552,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -6045,7 +6561,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -6075,7 +6594,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -6084,7 +6603,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/prod/node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -6114,7 +6636,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -6123,7 +6645,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -6146,7 +6671,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -6155,7 +6680,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -6178,7 +6706,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -6187,7 +6715,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -6210,7 +6741,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -6219,7 +6750,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -6238,7 +6772,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -6247,7 +6781,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -6262,7 +6799,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "", "name": "root", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root", "peer": true, "queryContext": Object {}, @@ -6284,7 +6824,7 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -6293,7 +6833,10 @@ exports[`test/node.js TAP testing with dep tree without meta > initial load with "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -6344,7 +6887,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -6353,7 +6896,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -6363,7 +6909,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -6372,7 +6918,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -6402,7 +6951,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -6411,7 +6960,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -6434,7 +6986,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -6443,7 +6995,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -6466,7 +7021,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -6475,7 +7030,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -6498,7 +7056,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -6507,7 +7065,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -6526,7 +7087,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -6535,7 +7096,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -6568,7 +7132,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -6577,7 +7141,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -6617,7 +7184,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -6657,7 +7224,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -6666,7 +7233,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -6676,7 +7246,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -6685,7 +7255,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -6708,7 +7281,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -6717,7 +7290,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -6747,7 +7323,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -6756,7 +7332,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -6779,7 +7358,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -6788,7 +7367,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -6811,7 +7393,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -6820,7 +7402,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -6843,7 +7428,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -6852,7 +7437,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -6871,7 +7459,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -6880,7 +7468,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -6913,7 +7504,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "meta", "inventory": Inventory {}, @@ -6922,7 +7513,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -6937,7 +7531,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "", "name": "root", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root", "peer": true, "queryContext": Object {}, @@ -6959,7 +7556,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -6968,7 +7565,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move meta to top "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -7019,7 +7619,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -7028,7 +7628,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -7038,7 +7641,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -7047,7 +7650,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -7074,7 +7680,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -7083,7 +7689,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -7106,7 +7715,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -7115,7 +7724,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -7138,7 +7750,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -7147,7 +7759,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -7170,7 +7785,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -7179,7 +7794,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -7198,7 +7816,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -7207,7 +7825,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -7227,7 +7848,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -7237,7 +7858,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -7268,7 +7892,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -7284,7 +7908,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -7294,7 +7918,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -7305,7 +7932,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to }, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -7345,7 +7975,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -7385,7 +8015,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -7394,7 +8024,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -7404,7 +8037,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -7413,7 +8046,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -7436,7 +8072,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -7445,7 +8081,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -7472,7 +8111,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -7481,7 +8120,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -7504,7 +8146,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -7513,7 +8155,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -7536,7 +8181,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -7545,7 +8190,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -7568,7 +8216,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -7577,7 +8225,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -7596,7 +8247,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -7605,7 +8256,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -7623,7 +8277,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -7633,7 +8287,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -7652,7 +8309,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -7662,7 +8319,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -7693,7 +8353,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -7709,7 +8369,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -7719,7 +8379,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -7730,7 +8393,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to }, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -7745,7 +8411,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "", "name": "root", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root", "peer": true, "queryContext": Object {}, @@ -7767,7 +8436,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -7776,7 +8445,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -7827,7 +8499,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -7836,7 +8508,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -7846,7 +8521,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -7855,7 +8530,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -7882,7 +8560,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -7891,7 +8569,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -7914,7 +8595,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -7923,7 +8604,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -7946,7 +8630,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -7955,7 +8639,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -7978,7 +8665,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -7987,7 +8674,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -8006,7 +8696,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -8015,7 +8705,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -8035,7 +8728,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -8045,7 +8738,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -8076,7 +8772,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -8092,7 +8788,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -8102,7 +8798,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -8113,7 +8812,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to }, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -8153,7 +8855,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory { @@ -8193,7 +8895,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -8202,7 +8904,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -8212,7 +8917,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "tops": Set {}, }, }, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "prod", "inventory": Inventory {}, @@ -8221,7 +8926,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/prod", "name": "prod", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod", "peer": true, "queryContext": Object {}, @@ -8244,7 +8952,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -8253,7 +8961,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, @@ -8280,7 +8991,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "bundled", "inventory": Inventory {}, @@ -8289,7 +9000,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/bundled", "name": "bundled", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/bundled", "peer": true, "queryContext": Object {}, @@ -8312,7 +9026,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "dev", "inventory": Inventory {}, @@ -8321,7 +9035,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/dev", "name": "dev", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/dev", "peer": true, "queryContext": Object {}, @@ -8344,7 +9061,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "opt", "inventory": Inventory {}, @@ -8353,7 +9070,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/optional", "name": "optional", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/optional", "peer": true, "queryContext": Object {}, @@ -8376,7 +9096,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "peer", "inventory": Inventory {}, @@ -8385,7 +9105,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/peer", "name": "peer", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/peer", "peer": true, "queryContext": Object {}, @@ -8404,7 +9127,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "extraneous", "inventory": Inventory {}, @@ -8413,7 +9136,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/extraneous", "name": "extraneous", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/extraneous", "peer": true, "queryContext": Object {}, @@ -8431,7 +9157,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -8441,7 +9167,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -8460,7 +9189,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -8470,7 +9199,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -8501,7 +9233,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "newMeta", "inventory": Inventory {}, @@ -8517,7 +9249,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": "metameta", "inventory": Inventory {}, @@ -8527,7 +9259,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/meta/node_modules/metameta", "name": "metameta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta/node_modules/metameta", "peer": true, "queryContext": Object {}, @@ -8538,7 +9273,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to }, "location": "node_modules/meta", "name": "meta", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/meta", "peer": true, "queryContext": Object {}, @@ -8553,7 +9291,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "", "name": "root", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root", "peer": true, "queryContext": Object {}, @@ -8575,7 +9316,7 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "errors": Array [], "extraneous": true, "fsChildren": Set {}, - "hasShrinkwrap": false, + "inert": false, "installLinks": false, "integrity": null, "inventory": Inventory {}, @@ -8584,7 +9325,10 @@ exports[`test/node.js TAP testing with dep tree without meta > move new meta to "linksIn": Set {}, "location": "node_modules/prod/foo", "name": "foo", + "npmExtensionApplied": null, "optional": true, + "packageExtensionsApplied": null, + "patched": null, "path": "/home/user/projects/root/node_modules/prod/foo", "peer": true, "queryContext": Object {}, diff --git a/workspaces/arborist/tap-snapshots/test/printable.js.test.cjs b/workspaces/arborist/tap-snapshots/test/printable.js.test.cjs index ce2396d1c5c6a..78a9a7ab5b4b2 100644 --- a/workspaces/arborist/tap-snapshots/test/printable.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/printable.js.test.cjs @@ -5,7 +5,7 @@ * Make sure to inspect the output below. Do not ignore changes! */ 'use strict' -exports[`test/printable.js TAP broken links dont break the printing > must match snapshot 1`] = ` +exports[`test/printable.js TAP broken links do not break the printing > must match snapshot 1`] = ` { "children":Map{ "devnull" => ArboristLink{ @@ -223,7 +223,7 @@ peer:true, target:{location:'c'}}}} ` -exports[`test/printable.js TAP show bundle/shrinkwrap info > must match snapshot 1`] = ` +exports[`test/printable.js TAP show bundle info > must match snapshot 1`] = ` { "children":Map{ "a" =>{ @@ -479,45 +479,6 @@ EdgeIn{ "optional":true, "path":"/path/to/root/node_modules/extraneous", "peer":true, -"version":"1.2.3",}, -"wrapper" =>{ -"children":Map{ -"a" =>{ -"dev":true, -"edgesIn":Set{ -EdgeIn{ -"from":"node_modules/wrapper", -"name":"a", -"spec":"1", -"type":"prod",},}, -"extraneous":true, -"inShrinkwrap":true, -"location":"node_modules/wrapper/node_modules/a", -"name":"a", -"optional":true, -"path":"/path/to/root/node_modules/wrapper/node_modules/a", -"peer":true, -"version":"1.2.3",},}, -"dev":true, -"edgesIn":Set{ -EdgeIn{ -"from":"", -"name":"wrapper", -"spec":"*", -"type":"prod",},}, -"edgesOut":Map{ -"a" => EdgeOut{ -"name":"a", -"spec":"1", -"to":"node_modules/wrapper/node_modules/a", -"type":"prod",},}, -"extraneous":true, -"hasShrinkwrap":true, -"location":"node_modules/wrapper", -"name":"wrapper", -"optional":true, -"path":"/path/to/root/node_modules/wrapper", -"peer":true, "version":"1.2.3",},}, "dev":true, "edgesOut":Map{ @@ -540,11 +501,6 @@ EdgeIn{ "name":"c", "spec":"3", "to":"node_modules/c", -"type":"prod",}, -"wrapper" => EdgeOut{ -"name":"wrapper", -"spec":"*", -"to":"node_modules/wrapper", "type":"prod",},}, "extraneous":true, "isProjectRoot":true, diff --git a/workspaces/arborist/tap-snapshots/test/shrinkwrap.js.test.cjs b/workspaces/arborist/tap-snapshots/test/shrinkwrap.js.test.cjs index 9103febb644ee..5c048ba77b912 100644 --- a/workspaces/arborist/tap-snapshots/test/shrinkwrap.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/shrinkwrap.js.test.cjs @@ -390,6 +390,9 @@ Object { "funding": Object { "url": "https://example.com/", }, + "libc": Array [ + "glibc", + ], "os": Array [ "any", "!win32", @@ -547,6 +550,9 @@ Object { "funding": Object { "url": "https://example.com/", }, + "libc": Array [ + "glibc", + ], "os": Array [ "any", "!win32", @@ -941,7 +947,7 @@ Object { "version": "1.0.0", }, "node_modules/full-git-url": Object { - "resolved": "git+ssh://git@github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", + "resolved": "git+https://github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", }, "node_modules/ghshort": Object { "resolved": "git+ssh://git@github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", @@ -1686,7 +1692,7 @@ Object { "node_modules/full-git-url": Object { "license": "ISC", "name": "abbrev", - "resolved": "git+ssh://git@github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", + "resolved": "git+https://github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", "version": "1.1.1", }, "node_modules/ghshort": Object { @@ -2728,14 +2734,6 @@ Object { "name": "example", "version": "1.0.0", }, - "../bar": Object { - "extraneous": true, - "version": "1.0.0", - }, - "../linked-node-modules/foo": Object { - "extraneous": true, - "version": "1.0.0", - }, "node_modules/bar": Object { "link": true, "resolved": "../bar", @@ -9749,16 +9747,6 @@ Object { "": Object { "name": "workspace3", }, - "app": Object { - "dependencies": Object { - "a": "", - "b": "", - "c": "", - "i": "", - }, - "extraneous": true, - "version": "1.2.3", - }, "app/node_modules/i": Object { "extraneous": true, "version": "1.2.3", @@ -9779,41 +9767,14 @@ Object { "link": true, "resolved": "packages/c", }, - "packages/a": Object { - "dependencies": Object { - "b": "", - "c": "", - "x": "", - }, - "extraneous": true, - "version": "1.2.3", - }, "packages/a/node_modules/x": Object { "extraneous": true, "version": "1.2.3", }, - "packages/b": Object { - "dependencies": Object { - "a": "", - "c": "", - "y": "", - }, - "extraneous": true, - "version": "1.2.3", - }, "packages/b/node_modules/y": Object { "extraneous": true, "version": "1.2.3", }, - "packages/c": Object { - "dependencies": Object { - "a": "", - "b": "", - "z": "", - }, - "extraneous": true, - "version": "1.2.3", - }, "packages/c/node_modules/z": Object { "extraneous": true, "version": "1.2.3", @@ -9925,7 +9886,7 @@ Object { exports[`test/shrinkwrap.js TAP look up from locks and such lockfile > full git 1`] = ` Object { - "resolved": "git+ssh://git@github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", + "resolved": "git+https://github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb", } ` diff --git a/workspaces/arborist/tap-snapshots/test/yarn-lock.js.test.cjs b/workspaces/arborist/tap-snapshots/test/yarn-lock.js.test.cjs index 020a88fda3868..423153dedb53b 100644 --- a/workspaces/arborist/tap-snapshots/test/yarn-lock.js.test.cjs +++ b/workspaces/arborist/tap-snapshots/test/yarn-lock.js.test.cjs @@ -5,7 +5,7 @@ * Make sure to inspect the output below. Do not ignore changes! */ 'use strict' -exports[`test/yarn-lock.js TAP deduped prior entries that dont match one another > yarn.lock with mismatching previous resolutions 1`] = ` +exports[`test/yarn-lock.js TAP deduped prior entries that do not match one another > yarn.lock with mismatching previous resolutions 1`] = ` # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 @@ -122,7 +122,7 @@ fs.realpath@^1.0.0: "full-git-url@git+https://github.com/isaacs/abbrev-js.git": version "1.1.1" - resolved "git+ssh://git@github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb" + resolved "git+https://github.com/isaacs/abbrev-js.git#a9ee72ebc8fe3975f1b0c7aeb3a8f2a806a432eb" "ghshort@github:isaacs/abbrev-js": version "1.1.1" diff --git a/workspaces/arborist/test/arborist/audit.js b/workspaces/arborist/test/arborist/audit.js index 11205899057a3..aeb9ec42dd32b 100644 --- a/workspaces/arborist/test/arborist/audit.js +++ b/workspaces/arborist/test/arborist/audit.js @@ -1,26 +1,32 @@ const t = require('tap') -const { resolve } = require('node:path') +const { join, resolve } = require('node:path') const Arborist = require('../../lib/arborist/index.js') const { normalizePath, printTree } = require('../fixtures/utils.js') -const { auditResponse, advisoryBulkResponse, ...mockRegistry } = require('../fixtures/server.js') +const MockRegistry = require('@npmcli/mock-registry') const fixtures = resolve(__dirname, '../fixtures') const fixture = (t, p) => require(fixtures + '/reify-cases/' + p)(t) -t.before(mockRegistry.start) -t.teardown(mockRegistry.stop) - const cache = t.testdir() -const newArb = (path, options = {}) => - new Arborist({ path, cache, registry: mockRegistry.registry, ...options }) +const newArb = (path, options = {}) => new Arborist({ path, cache, ...options }) const cwd = normalizePath(process.cwd()) t.cleanSnapshot = s => s.split(cwd).join('{CWD}') - .split(mockRegistry.registry).join('https://registry.npmjs.org/') + +const createRegistry = (t) => { + const registry = new MockRegistry({ + strict: true, + tap: t, + registry: 'https://registry.npmjs.org', + }) + return registry +} t.test('audit finds the bad deps', async t => { const path = resolve(fixtures, 'deprecated-dep') - t.teardown(auditResponse(resolve(fixtures, 'audit-nyc-mkdirp/audit.json'))) + const registry = createRegistry(t, false) + registry.audit({ convert: true, results: require(resolve(fixtures, 'audit-nyc-mkdirp', 'audit.json')) }) + registry.mocks({ dir: join(__dirname, '..', 'fixtures') }) const arb = newArb(path) const report = await arb.audit() t.equal(report.topVulns.size, 0) @@ -29,7 +35,9 @@ t.test('audit finds the bad deps', async t => { t.test('no package lock finds no bad deps', async t => { const path = resolve(fixtures, 'deprecated-dep') - t.teardown(auditResponse(resolve(fixtures, 'audit-nyc-mkdirp/audit.json'))) + const registry = createRegistry(t, false) + registry.audit({ convert: true, results: require(resolve(fixtures, 'audit-nyc-mkdirp', 'audit.json')) }) + registry.mocks({ dir: join(__dirname, '..', 'fixtures') }) const arb = newArb(path, { packageLock: false }) const report = await arb.audit() t.equal(report.topVulns.size, 0) @@ -38,22 +46,26 @@ t.test('no package lock finds no bad deps', async t => { t.test('audit fix reifies out the bad deps', async t => { const path = fixture(t, 'deprecated-dep') - t.teardown(auditResponse(resolve(fixtures, 'audit-nyc-mkdirp/audit.json'))) + const registry = createRegistry(t, false) + registry.audit({ convert: true, results: require(resolve(fixtures, 'audit-nyc-mkdirp', 'audit.json')) }) + registry.mocks({ dir: join(__dirname, '..', 'fixtures') }) const arb = newArb(path) const tree = printTree(await arb.audit({ fix: true })) t.matchSnapshot(tree, 'reified out the bad mkdirp and minimist') }) -t.test('audit does not do globals', t => - t.rejects(newArb('.', { global: true }).audit(), { +t.test('audit does not do globals', async t => { + await t.rejects(newArb('.', { global: true }).audit(), { message: '`npm audit` does not support testing globals', code: 'EAUDITGLOBAL', - })) + }) +}) t.test('audit in a workspace', async t => { const src = resolve(fixtures, 'audit-nyc-mkdirp') - const auditFile = resolve(src, 'advisory-bulk.json') - t.teardown(advisoryBulkResponse(auditFile)) + const registry = createRegistry(t) + registry.audit({ results: require(resolve(src, 'advisory-bulk.json')) }) + registry.mocks({ dir: join(__dirname, '..', 'fixtures') }) const path = t.testdir({ 'package.json': JSON.stringify({ @@ -104,8 +116,9 @@ t.test('audit in a workspace', async t => { t.test('audit with workspaces disabled', async t => { const src = resolve(fixtures, 'audit-nyc-mkdirp') - const auditFile = resolve(src, 'advisory-bulk.json') - t.teardown(advisoryBulkResponse(auditFile)) + const registry = createRegistry(t) + registry.audit({ results: require(resolve(src, 'advisory-bulk.json')) }) + registry.mocks({ dir: join(__dirname, '..', 'fixtures') }) const path = t.testdir({ 'package.json': JSON.stringify({ diff --git a/workspaces/arborist/test/arborist/build-ideal-tree.js b/workspaces/arborist/test/arborist/build-ideal-tree.js index 807287c73cf11..ef46f9c60caa1 100644 --- a/workspaces/arborist/test/arborist/build-ideal-tree.js +++ b/workspaces/arborist/test/arborist/build-ideal-tree.js @@ -4,34 +4,38 @@ if (process.platform === 'win32') { process.env.ARBORIST_DEBUG = 0 } -const { basename, resolve, relative } = require('node:path') +const { join, basename, resolve, relative } = require('node:path') const pacote = require('pacote') const t = require('tap') const Arborist = require('../..') const fixtures = resolve(__dirname, '../fixtures') // load the symbolic links that we depend on require(fixtures) -const { start, stop, registry, auditResponse } = require('../fixtures/server.js') const npa = require('npm-package-arg') const fs = require('node:fs') -const nock = require('nock') -const semver = require('semver') +const MockRegistry = require('@npmcli/mock-registry') -t.before(start) -t.teardown(stop) - -const cache = t.testdir() +const createRegistry = (t, mocks = false) => { + const registry = new MockRegistry({ + strict: true, + tap: t, + registry: 'https://registry.npmjs.org', + }) + if (mocks) { + registry.mocks({ dir: join(__dirname, '..', 'fixtures') }) + } + return registry +} -// track the warnings that are emitted. returns a function that removes -// the listener and provides the list of what it saw. -const warningTracker = () => { - const list = [] - const onlog = (...msg) => msg[0] === 'warn' && list.push(msg) +// track the warnings that are emitted. returns the list of what it saw +const warningTracker = (t) => { + const warnings = [] + const onlog = (...msg) => msg[0] === 'warn' && warnings.push(msg) process.on('log', onlog) - return () => { + t.teardown(() => { process.removeListener('log', onlog) - return list - } + }) + return warnings } const { @@ -53,83 +57,29 @@ This is a one-time fix-up, please be patient... const cwd = normalizePath(process.cwd()) t.cleanSnapshot = s => s.split(cwd).join('{CWD}') - .split(registry).join('https://registry.npmjs.org/') - -const printIdeal = (path, opt) => buildIdeal(path, opt).then(printTree) +const cache = t.testdir() // give it a very long timeout so CI doesn't crash as easily -const OPT = { cache, registry, timeout: 30 * 60 * 1000 } - -const newArb = (path, opt = {}) => new Arborist({ ...OPT, path, ...opt }) +const newArb = (path, opt = {}) => new Arborist({ timeout: 30 * 60 * 1000, path, cache, ...opt }) const buildIdeal = (path, opt) => newArb(path, opt).buildIdealTree(opt) - -const generateNocks = (t, spec) => { - nock.disableNetConnect() - - const getDeps = (version, deps) => - (deps || []).reduce((result, dep) => { - if (typeof dep === 'string') { - return { - ...result, - [dep]: version, - } - } else { - return { - ...result, - ...(version in dep ? { [dep[version]]: version } : {}), - } - } - }, {}) - - for (const name in spec) { - const pkg = spec[name] - - const packument = { - name, - 'dist-tags': { - latest: pkg.latest || semver.maxSatisfying(pkg.versions, '*'), - }, - versions: pkg.versions.reduce((versions, version) => { - return { - ...versions, - [version]: { - name, - version, - dependencies: getDeps(version, pkg.dependencies), - peerDependencies: getDeps(version, pkg.peerDependencies), - }, - } - }, {}), - } - - nock(registry) - .persist() - .get(`/${name}`) - .reply(200, packument) - } - - t.teardown(async () => { - nock.enableNetConnect() - nock.cleanAll() - }) -} +const printIdeal = (path, opt) => buildIdeal(path, opt).then(printTree) t.test('fail on mismatched engine when engineStrict is set', async t => { const path = resolve(fixtures, 'engine-specification') - t.rejects(buildIdeal(path, { - ...OPT, + await t.rejects(buildIdeal(path, { nodeVersion: '12.18.4', engineStrict: true, - }).then(() => { - throw new Error('failed to fail') - }), { code: 'EBADENGINE' }) + }), + { code: 'EBADENGINE' }, + 'should fail with EBADENGINE error' + ) }) -t.test('fail on malformed package.json', t => { +t.test('fail on malformed package.json', async t => { const path = resolve(fixtures, 'malformed-json') - return t.rejects( + await t.rejects( buildIdeal(path), { code: 'EJSONPARSE' }, 'should fail with EJSONPARSE error' @@ -139,7 +89,6 @@ t.test('fail on malformed package.json', t => { t.test('ignore mismatched engine for optional dependencies', async () => { const path = resolve(fixtures, 'optional-engine-specification') await buildIdeal(path, { - ...OPT, nodeVersion: '12.18.4', engineStrict: true, }) @@ -147,52 +96,51 @@ t.test('ignore mismatched engine for optional dependencies', async () => { t.test('warn on mismatched engine when engineStrict is false', t => { const path = resolve(fixtures, 'engine-specification') - const check = warningTracker() + createRegistry(t, false) + const warnings = warningTracker(t) return buildIdeal(path, { - ...OPT, nodeVersion: '12.18.4', engineStrict: false, - }).then(() => t.match(check(), [ + }).then(() => t.match(warnings, [ ['warn', 'EBADENGINE'], ])) }) t.test('fail on mismatched platform', async t => { const path = resolve(fixtures, 'platform-specification') - t.rejects(buildIdeal(path, { - ...OPT, + createRegistry(t, true) + await t.rejects(buildIdeal(path, { nodeVersion: '4.0.0', - }).then(() => { - throw new Error('failed to fail') }), { code: 'EBADPLATFORM' }) }) t.test('ignore mismatched platform for optional dependencies', async t => { const path = resolve(fixtures, 'optional-platform-specification') + createRegistry(t, true) const tree = await buildIdeal(path, { - ...OPT, nodeVersion: '12.18.4', engineStrict: true, }) t.equal(tree.children.get('platform-specifying-test-package').package.version, '1.0.0', 'added the optional dep to the ideal tree') }) -t.test('no options', t => { +t.test('no options', async t => { const arb = new Arborist() t.match( arb.registry, 'https://registry.npmjs.org', 'should use default registry' ) - t.end() }) t.test('a workspace with a conflicted nested duplicated dep', async t => { + createRegistry(t, true) t.matchSnapshot(await printIdeal(resolve(fixtures, 'workspace4'))) }) t.test('a tree with an outdated dep, missing dep, no lockfile', async t => { const path = resolve(fixtures, 'outdated-no-lockfile') + createRegistry(t, true) const tree = await buildIdeal(path) const expected = { once: '1.3.3', @@ -205,14 +153,17 @@ t.test('a tree with an outdated dep, missing dep, no lockfile', async t => { t.matchSnapshot(printTree(tree), 'should not update all') }) -t.test('tarball deps with transitive tarball deps', t => - t.resolveMatchSnapshot(printIdeal( - resolve(fixtures, 'tarball-dependencies')))) +t.test('tarball deps with transitive tarball deps', async t => { + createRegistry(t, false) + await t.resolveMatchSnapshot(printIdeal( + resolve(fixtures, 'tarball-dependencies'))) +}) t.test('testing-peer-deps-overlap package', async t => { const path = resolve(fixtures, 'testing-peer-deps-overlap') + createRegistry(t, true) const idealTree = await buildIdeal(path) - const arb = new Arborist({ path, idealTree, ...OPT }) + const arb = newArb(path, { idealTree }) const tree2 = await arb.buildIdealTree() t.equal(tree2, idealTree) t.matchSnapshot(printTree(idealTree), 'build ideal tree with overlapping peer dep ranges') @@ -220,95 +171,98 @@ t.test('testing-peer-deps-overlap package', async t => { t.test('testing-peer-deps package', async t => { const path = resolve(fixtures, 'testing-peer-deps') + createRegistry(t, true) const idealTree = await buildIdeal(path) - const arb = new Arborist({ path, idealTree, ...OPT }) + const arb = newArb(path, { idealTree }) const tree2 = await arb.buildIdealTree() t.equal(tree2, idealTree) t.matchSnapshot(printTree(idealTree), 'build ideal tree with peer deps') }) -t.test('testing-peer-deps package with symlinked root', t => { +t.test('testing-peer-deps package with symlinked root', async t => { const path = resolve(fixtures, 'testing-peer-deps-link') - return buildIdeal(path).then(idealTree => { - t.ok(idealTree.isLink, 'ideal tree is rooted on a Link') - return new Arborist({ path, idealTree, ...OPT }) - .buildIdealTree().then(tree2 => t.equal(tree2, idealTree)) - .then(() => t.matchSnapshot(printTree(idealTree), 'build ideal tree with peer deps')) - }) + createRegistry(t, true) + const idealTree = await buildIdeal(path) + t.ok(idealTree.isLink, 'ideal tree is rooted on a Link') + const arb = newArb(path, { idealTree }) + const tree2 = await arb.buildIdealTree() + t.equal(tree2, idealTree) + t.matchSnapshot(printTree(idealTree), 'build ideal tree with peer deps') }) -t.test('testing-peer-deps nested', t => { +t.test('testing-peer-deps nested', async t => { const path = resolve(fixtures, 'testing-peer-deps-nested') - return t.resolveMatchSnapshot(printIdeal(path), 'build ideal tree') - .then(() => t.resolveMatchSnapshot(printIdeal(path, { - // hit the branch where update is just a list of names - update: ['@isaacs/testing-peer-deps'], - }), 'can update a peer dep cycle')) + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(path), 'build ideal tree') + await t.resolveMatchSnapshot(printIdeal(path, { + // hit the branch where update is just a list of names + update: ['@isaacs/testing-peer-deps'], + }), 'can update a peer dep cycle') }) -t.test('tap vs react15', t => { +t.test('tap vs react15', async t => { const path = resolve(fixtures, 'tap-react15-collision') - return t.resolveMatchSnapshot(printIdeal(path), 'build ideal tree with tap collision') + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(path), 'build ideal tree with tap collision') }) -t.test('tap vs react15 with legacy shrinkwrap', t => { +t.test('tap vs react15 with legacy lockfile', async t => { const path = resolve(fixtures, 'tap-react15-collision-legacy-sw') - return t.resolveMatchSnapshot(printIdeal(path), 'tap collision with legacy sw file') -}) - -t.test('bad shrinkwrap file', t => { - const path = resolve(fixtures, 'testing-peer-deps-bad-sw') - return t.resolveMatchSnapshot(printIdeal(path), 'bad shrinkwrap') + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(path), 'tap collision with legacy lockfile') }) -t.test('a direct link dep has a dep with optional dependencies', t => { +t.test('a direct link dep has a dep with optional dependencies', async t => { const path = resolve(fixtures, 'link-dep-has-dep-with-optional-dep') - return t.resolveMatchSnapshot(printIdeal(path), 'should not mark children of the optional dep as extraneous') + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(path), 'should not mark children of the optional dep as extraneous') }) -t.test('cyclical peer deps', t => { +t.test('cyclical peer deps', async t => { const paths = [ resolve(fixtures, 'peer-dep-cycle'), resolve(fixtures, 'peer-dep-cycle-with-sw'), ] - - t.plan(paths.length) - paths.forEach(path => t.test(basename(path), t => - t.resolveMatchSnapshot(printIdeal(path), 'cyclical peer deps') - .then(() => t.resolveMatchSnapshot(printIdeal(path, { + createRegistry(t, true) + for (const path of paths) { + await t.test(basename(path), async t => { + await t.resolveMatchSnapshot(printIdeal(path), 'cyclical peer deps') + await t.resolveMatchSnapshot(printIdeal(path, { // just reload the dep at its current required version add: ['@isaacs/peer-dep-cycle-a'], - }), 'cyclical peer deps - reload a dependency')) - .then(() => t.resolveMatchSnapshot(printIdeal(path, { + }), 'cyclical peer deps - reload a dependency') + await t.resolveMatchSnapshot(printIdeal(path, { add: ['@isaacs/peer-dep-cycle-a@2.x'], - }), 'cyclical peer deps - upgrade a package')) - .then(() => t.rejects(printIdeal(path, { + }), 'cyclical peer deps - upgrade a package') + await t.rejects(printIdeal(path, { // this conflicts with the direct dep on a@1 PEER-> b@1 add: ['@isaacs/peer-dep-cycle-b@2.x'], - }))) - // this conflict is ok since we're using legacy peer deps - .then(() => t.resolveMatchSnapshot(printIdeal(path, { + })) + // this conflict is ok since we're using legacy peer deps + await t.resolveMatchSnapshot(printIdeal(path, { add: ['@isaacs/peer-dep-cycle-b@2.x'], legacyPeerDeps: true, - }), 'add b@2.x with legacy peer deps')) - .then(() => t.resolveMatchSnapshot(printIdeal(path, { + }), 'add b@2.x with legacy peer deps') + await t.resolveMatchSnapshot(printIdeal(path, { // use @latest rather than @2.x to exercise the 'explicit tag' path add: ['@isaacs/peer-dep-cycle-b@latest'], rm: ['@isaacs/peer-dep-cycle-a'], - }), 'can add b@2 if we remove a@1 dep')) - .then(() => t.resolveMatchSnapshot(printIdeal(path, { + }), 'can add b@2 if we remove a@1 dep') + await t.resolveMatchSnapshot(printIdeal(path, { rm: ['@isaacs/peer-dep-cycle-a'], - }), 'remove the dep, prune everything')) - )) + }), 'remove the dep, prune everything') + }) + } }) -t.test('nested cyclical peer deps', t => { +t.test('nested cyclical peer deps', async t => { + const registry = createRegistry(t, true) const paths = [ resolve(fixtures, 'peer-dep-cycle-nested'), resolve(fixtures, 'peer-dep-cycle-nested-with-sw'), ] - // if we have a shrinkwrap, then we'll get a collision with the current + // if we have a lockfile, then we'll get a collision with the current // version already there. if we don't, then we'll get a peerConflict // when we try to put the second one there. const ers = { @@ -320,96 +274,100 @@ t.test('nested cyclical peer deps', t => { }, } - t.plan(paths.length) - paths.forEach(path => t.test(basename(path), async t => { - t.matchSnapshot(await printIdeal(path), 'nested peer deps cycle') - - t.matchSnapshot(await printIdeal(path, { - // just make sure it works if it gets a spec object - add: [npa('@isaacs/peer-dep-cycle-a@2.x')], - }), 'upgrade a') - - t.matchSnapshot(await printIdeal(path, { - // a dep whose name we don't yet know - add: [ - '@isaacs/peer-dep-cycle-a@2.x', - `${registry}@isaacs/peer-dep-cycle-b/-/peer-dep-cycle-b-2.0.0.tgz`, - ], - }), 'upgrade b') - - t.matchSnapshot(await printIdeal(path, { - force: true, - add: ['@isaacs/peer-dep-cycle-c@2.x'], - }), 'upgrade c, forcibly') - - await t.rejects(printIdeal(path, { - add: [ - '@isaacs/peer-dep-cycle-a@1.x', - '@isaacs/peer-dep-cycle-c@2.x', - ], - }), ers[path], 'try (and fail) to upgrade c and a incompatibly') - })) + for (const path of paths) { + await t.test(basename(path), async t => { + await t.resolveMatchSnapshot(printIdeal(path), 'nested peer deps cycle') + await t.resolveMatchSnapshot(printIdeal(path, { + // just make sure it works if it gets a spec object + add: [npa('@isaacs/peer-dep-cycle-a@2.x')], + }), 'upgrade a') + await t.resolveMatchSnapshot(printIdeal(path, { + // a dep whose name we don't yet know + add: [ + '@isaacs/peer-dep-cycle-a@2.x', + `${registry.origin}/@isaacs/peer-dep-cycle-b/-/peer-dep-cycle-b-2.0.0.tgz`, + ], + }), 'upgrade b') + await t.resolveMatchSnapshot(printIdeal(path, { + force: true, + add: ['@isaacs/peer-dep-cycle-c@2.x'], + }), 'upgrade c, forcibly') + await t.rejects(printIdeal(path, { + add: [ + '@isaacs/peer-dep-cycle-a@1.x', + '@isaacs/peer-dep-cycle-c@2.x', + ], + }), ers[path], 'try (and fail) to upgrade c and a incompatibly') + }) + } }) -t.test('dedupe example - not deduped', t => { +t.test('dedupe example - not deduped', async t => { + createRegistry(t, true) const path = resolve(fixtures, 'dedupe-tests') - return t.resolveMatchSnapshot(printIdeal(path), 'dedupe testing') + await t.resolveMatchSnapshot(printIdeal(path), 'dedupe testing') }) -t.test('dedupe example - deduped because preferDedupe=true', t => { +t.test('dedupe example - deduped because preferDedupe=true', async t => { + createRegistry(t, true) const path = resolve(fixtures, 'dedupe-tests') - return t.resolveMatchSnapshot(printIdeal(path, { preferDedupe: true })) + await t.resolveMatchSnapshot(printIdeal(path, { preferDedupe: true })) }) -t.test('dedupe example - nested because legacyBundling=true', t => { +t.test('dedupe example - nested because legacyBundling=true', async t => { const path = resolve(fixtures, 'dedupe-tests') - return t.resolveMatchSnapshot(printIdeal(path, { + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(path, { installStrategy: 'nested', preferDedupe: true, })) }) -t.test('dedupe example - deduped', t => { +t.test('dedupe example - deduped', async t => { const path = resolve(fixtures, 'dedupe-tests-2') - return t.resolveMatchSnapshot(printIdeal(path), 'dedupe testing') + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(path), 'dedupe testing') }) t.test('expose explicitRequest', async t => { const path = resolve(fixtures, 'simple') - const arb = new Arborist({ ...OPT, path }) + createRegistry(t, true) + const arb = newArb(path) await arb.buildIdealTree({ add: ['abbrev'] }) t.match(arb.explicitRequests, Set, 'exposes the explicit request Set') t.strictSame([...arb.explicitRequests].map(e => e.name), ['abbrev']) - t.end() }) -t.test('bundle deps example 1, empty', t => { +t.test('bundle deps example 1, empty', async t => { // NB: this results in ignoring the bundled deps when building the // ideal tree. When we reify, we'll have to ignore the deps that // got placed as part of the bundle. const path = resolve(fixtures, 'testing-bundledeps-empty') - return t.resolveMatchSnapshot(printIdeal(path), 'bundle deps testing') - .then(() => t.resolveMatchSnapshot(printIdeal(path, { - saveBundle: true, - add: ['@isaacs/testing-bundledeps'], - }), 'should have some missing deps in the ideal tree')) + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(path), 'bundle deps testing') + await t.resolveMatchSnapshot(printIdeal(path, { + saveBundle: true, + add: ['@isaacs/testing-bundledeps'], + }), 'should have some missing deps in the ideal tree') }) -t.test('bundle deps example 1, full', t => { +t.test('bundle deps example 1, full', async t => { // In this test, bundle deps show up, because they're present in // the actual tree to begin with. const path = resolve(fixtures, 'testing-bundledeps') - return t.resolveMatchSnapshot(printIdeal(path), 'no missing deps') - .then(() => t.resolveMatchSnapshot(printIdeal(path, { - saveBundle: true, - add: ['@isaacs/testing-bundledeps'], - }), 'add stuff, no missing deps')) + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(path), 'no missing deps') + await t.resolveMatchSnapshot(printIdeal(path, { + saveBundle: true, + add: ['@isaacs/testing-bundledeps'], + }), 'add stuff, no missing deps') }) t.test('bundle deps example 1, complete:true', async t => { // When complete:true is set, we extract into a temp dir to read // the bundled deps, so they ARE included, just like during reify() const path = resolve(fixtures, 'testing-bundledeps-empty') + createRegistry(t, true) // wrap pacote.extract in a spy so we can be sure the integrity and resolved // options both made it through @@ -427,141 +385,113 @@ t.test('bundle deps example 1, complete:true', async t => { return res } - t.matchSnapshot(await printIdeal(path, { + await t.resolveMatchSnapshot(printIdeal(path, { complete: true, }), 'no missing deps, because complete: true') - t.matchSnapshot(await printIdeal(path, { + await t.resolveMatchSnapshot(printIdeal(path, { saveBundle: true, add: ['@isaacs/testing-bundledeps'], complete: true, }), 'no missing deps, because complete: true, add dep, save bundled') }) -t.test('bundle deps example 2', t => { +t.test('bundle deps example 2', async t => { // bundled deps at the root level are NOT ignored when building ideal trees const path = resolve(fixtures, 'testing-bundledeps-2') - return t.resolveMatchSnapshot(printIdeal(path), 'bundle deps testing') - .then(() => t.resolveMatchSnapshot(printIdeal(path, { - saveBundle: true, - add: ['@isaacs/testing-bundledeps-c'], - }), 'add new bundled dep c')) - .then(() => t.resolveMatchSnapshot(printIdeal(path, { - rm: ['@isaacs/testing-bundledeps-a'], - }), 'remove bundled dependency a')) + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(path), 'bundle deps testing') + await t.resolveMatchSnapshot(printIdeal(path, { + saveBundle: true, + add: ['@isaacs/testing-bundledeps-c'], + }), 'add new bundled dep c') + await t.resolveMatchSnapshot(printIdeal(path, { + rm: ['@isaacs/testing-bundledeps-a'], + }), 'remove bundled dependency a') }) -t.test('bundle deps example 2, link', t => { +t.test('bundle deps example 2, link', async t => { // bundled deps at the root level are NOT ignored when building ideal trees const path = resolve(fixtures, 'testing-bundledeps-link') - return t.resolveMatchSnapshot(printIdeal(path), 'bundle deps testing') - .then(() => t.resolveMatchSnapshot(printIdeal(path, { - saveBundle: true, - add: ['@isaacs/testing-bundledeps-c'], - }), 'add new bundled dep c')) - .then(() => t.resolveMatchSnapshot(printIdeal(path, { - rm: ['@isaacs/testing-bundledeps-a'], - }), 'remove bundled dependency a')) + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(path), 'bundle deps testing') + await t.resolveMatchSnapshot(printIdeal(path, { + saveBundle: true, + add: ['@isaacs/testing-bundledeps-c'], + }), 'add new bundled dep c') + await t.resolveMatchSnapshot(printIdeal(path, { + rm: ['@isaacs/testing-bundledeps-a'], + }), 'remove bundled dependency a') }) -t.test('unresolvable peer deps', t => { +t.test('unresolvable peer deps', async t => { const path = resolve(fixtures, 'testing-peer-deps-unresolvable') + createRegistry(t, true) - return t.rejects(printIdeal(path, { strictPeerDeps: true }), { + await t.rejects(printIdeal(path, { strictPeerDeps: true }), { message: 'unable to resolve dependency tree', code: 'ERESOLVE', }, 'unacceptable') }) -t.test('do not add shrinkwrapped deps', t => { - const path = resolve(fixtures, 'shrinkwrapped-dep-no-lock') - return t.resolveMatchSnapshot(printIdeal(path, { update: true })) -}) - -t.test('do add shrinkwrapped deps when complete:true is set', t => { - const path = resolve(fixtures, 'shrinkwrapped-dep-no-lock') - return t.resolveMatchSnapshot(printIdeal(path, { - complete: true, - update: true, - })) -}) - -t.test('do not update shrinkwrapped deps', t => { - const path = resolve(fixtures, 'shrinkwrapped-dep-with-lock') - return t.resolveMatchSnapshot(printIdeal(path, - { update: { names: ['abbrev'] } })) -}) - -t.test('do not update shrinkwrapped deps, ignore lockfile', t => { - const path = resolve(fixtures, 'shrinkwrapped-dep-with-lock') - return t.resolveMatchSnapshot(printIdeal(path, - { packageLock: false, update: { names: ['abbrev'] } })) -}) - -t.test('do not update shrinkwrapped deps when complete:true is set', t => { - const path = resolve(fixtures, 'shrinkwrapped-dep-with-lock') - return t.resolveMatchSnapshot(printIdeal(path, - { update: { names: ['abbrev'] }, complete: true })) +t.test('deduped transitive deps with asymmetrical bin declaration', async t => { + const path = resolve(fixtures, 'testing-asymmetrical-bin-no-lock') + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(path), 'with no lockfile') }) -t.test('deduped transitive deps with asymmetrical bin declaration', t => { - const path = - resolve(fixtures, 'testing-asymmetrical-bin-no-lock') - return t.resolveMatchSnapshot(printIdeal(path), 'with no lockfile') +t.test('deduped transitive deps with asymmetrical bin declaration', async t => { + const path = resolve(fixtures, 'testing-asymmetrical-bin-with-lock') + createRegistry(t, false) + await t.resolveMatchSnapshot(printIdeal(path), 'with lockfile') }) -t.test('deduped transitive deps with asymmetrical bin declaration', t => { - const path = - resolve(fixtures, 'testing-asymmetrical-bin-with-lock') - return t.resolveMatchSnapshot(printIdeal(path), 'with lockfile') -}) - -t.test('update', t => { - t.test('flow outdated', t => { +t.test('update', async t => { + await t.test('flow outdated', async t => { + createRegistry(t, true) const flowOutdated = resolve(fixtures, 'flow-outdated') - - t.resolveMatchSnapshot(printIdeal(flowOutdated, { + await t.resolveMatchSnapshot(printIdeal(flowOutdated, { update: { names: ['flow-parser'], }, }), 'update flow parser') - - t.resolveMatchSnapshot(printIdeal(flowOutdated, { + await t.resolveMatchSnapshot(printIdeal(flowOutdated, { update: true, }), 'update everything') - - t.end() }) - t.test('tap and flow', t => { + await t.test('tap and flow', async t => { + createRegistry(t, true) const tapAndFlow = resolve(fixtures, 'tap-and-flow') - t.resolveMatchSnapshot(printIdeal(tapAndFlow, { + await t.resolveMatchSnapshot(printIdeal(tapAndFlow, { update: { all: true, }, }), 'update everything') - t.resolveMatchSnapshot(printIdeal(tapAndFlow, { + await t.resolveMatchSnapshot(printIdeal(tapAndFlow, { update: { names: ['ink'], }, }), 'update ink') - - t.end() }) - - t.end() }) -t.test('link meta deps', t => - t.resolveMatchSnapshot(printIdeal( - resolve(fixtures, 'link-meta-deps-empty')))) +t.test('link meta deps', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal( + resolve(fixtures, 'link-meta-deps-empty'))) +}) -t.test('respect the yarn.lock file', t => - t.resolveMatchSnapshot(printIdeal( - resolve(fixtures, 'yarn-lock-mkdirp')))) +t.test('respect the yarn.lock file', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal( + resolve(fixtures, 'yarn-lock-mkdirp'))) +}) -t.test('respect the yarn.lock file version, if lacking resolved', t => - t.resolveMatchSnapshot(printIdeal( - resolve(fixtures, 'yarn-lock-mkdirp-no-resolved')))) +t.test('respect the yarn.lock file version, if lacking resolved', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal( + resolve(fixtures, 'yarn-lock-mkdirp-no-resolved'))) +}) t.test('optional dependency failures', async t => { const cases = [ @@ -571,34 +501,37 @@ t.test('optional dependency failures', async t => { 'optional-metadep-enotarget', 'optional-metadep-missing', ] - t.plan(cases.length) + createRegistry(t, true) for (const c of cases) { const tree = await printIdeal(resolve(fixtures, c)) t.matchSnapshot(tree, c) } }) -t.test('prod dependency failures', t => { +t.test('prod dependency failures', async t => { const cases = [ 'prod-dep-enotarget', 'prod-dep-missing', ] - t.plan(cases.length) - cases.forEach(c => t.rejects(printIdeal( - resolve(fixtures, c)), c)) + createRegistry(t, true) + for (const c of cases) { + await t.rejects(printIdeal(resolve(fixtures, c)), c) + } }) -t.test('link dep with a link dep', t => { +t.test('link dep with a link dep', async t => { const path = resolve(fixtures, 'cli-750') - return Promise.all([ + createRegistry(t, false) + await Promise.all([ t.resolveMatchSnapshot(printIdeal(path), 'link metadeps with lockfile'), t.resolveMatchSnapshot(printIdeal(path, { update: true }), 'link metadeps without lockfile'), ]) }) -t.test('link dep within node_modules and outside root', t => { +t.test('link dep within node_modules and outside root', async t => { const path = resolve(fixtures, 'external-link-dep') - return Promise.all([ + createRegistry(t, true) + await Promise.all([ t.resolveMatchSnapshot(printIdeal(path), 'linky deps with lockfile'), t.resolveMatchSnapshot(printIdeal(path, { update: true }), 'linky deps without lockfile'), t.resolveMatchSnapshot(printIdeal(path, { follow: true }), 'linky deps followed'), @@ -606,27 +539,37 @@ t.test('link dep within node_modules and outside root', t => { ]) }) -t.test('global style', t => t.resolveMatchSnapshot(printIdeal(t.testdir(), { - installStrategy: 'shallow', - add: ['rimraf'], -}))) +t.test('global style', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(t.testdir(), { + installStrategy: 'shallow', + add: ['rimraf'], + })) +}) -t.test('global', t => t.resolveMatchSnapshot(printIdeal(t.testdir(), { - global: true, - add: ['rimraf'], -}))) +t.test('global', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printIdeal(t.testdir(), { + global: true, + add: ['rimraf'], + })) +}) -t.test('global has to add or remove', t => t.rejects(printIdeal(t.testdir(), { - global: true, -}))) +t.test('global has to add or remove', async t => { + createRegistry(t, false) + await t.rejects(printIdeal(t.testdir(), { + global: true, + })) +}) -// somewhat copy-pasta from the test/arborist/audit.js to exercise -// the buildIdealTree code paths +// // somewhat copy-pasta from the test/arborist/audit.js to exercise +// // the buildIdealTree code paths t.test('update mkdirp to non-minimist-using version', async t => { const path = resolve(fixtures, 'deprecated-dep') - t.teardown(auditResponse(resolve(fixtures, 'audit-nyc-mkdirp/audit.json'))) + const registry = createRegistry(t, true) + registry.audit({ convert: true, results: require('../fixtures/audit-nyc-mkdirp/audit.json') }) - const arb = new Arborist({ path, ...OPT }) + const arb = newArb(path) await arb.audit() t.matchSnapshot(printTree(await arb.buildIdealTree())) @@ -634,29 +577,44 @@ t.test('update mkdirp to non-minimist-using version', async t => { t.test('force a new nyc (and update mkdirp nicely)', async t => { const path = resolve(fixtures, 'audit-nyc-mkdirp') - t.teardown(auditResponse(resolve(fixtures, 'audit-nyc-mkdirp/audit.json'))) - - const arb = new Arborist({ - force: true, - path, - ...OPT, - }) + const registry = createRegistry(t, true) + // TODO why does this infinite loop if no results? + registry.audit({ convert: true, results: require('../fixtures/audit-nyc-mkdirp/audit.json') }) + const arb = newArb(path, { force: true }) await arb.audit() t.matchSnapshot(printTree(await arb.buildIdealTree())) t.equal(arb.idealTree.children.get('mkdirp').package.version, '0.5.5') t.equal(arb.idealTree.children.get('nyc').package.version, '15.1.0') }) +t.test('audit fix warns when min-release-age blocks a fix', async t => { + const path = resolve(fixtures, 'audit-nyc-mkdirp') + const registry = createRegistry(t, true) + registry.audit({ convert: true, results: require('../fixtures/audit-nyc-mkdirp/audit.json') }) + const warnings = warningTracker(t) + + // mkdirp's fix (0.5.5) was published after this cutoff, so audit fix can't + // install it and should warn that the package is left vulnerable. + const arb = newArb(path, { before: new Date('2020-01-01') }) + await arb.audit() + await arb.buildIdealTree() + + t.not(arb.idealTree.children.get('mkdirp').package.version, '0.5.5', + 'mkdirp was not upgraded to the release-age-blocked fix') + t.ok( + warnings.some(w => w[1] === 'audit' && + /A fix for mkdirp is available \(mkdirp@0\.5\.5\) but was published after/.test(w[2])), + 'warned that the mkdirp fix is blocked by the release-age window' + ) +}) + t.test('force a new mkdirp (but not semver major)', async t => { const path = resolve(fixtures, 'mkdirp-pinned') - t.teardown(auditResponse(resolve(fixtures, 'audit-nyc-mkdirp/audit.json'))) + const registry = createRegistry(t, true) + registry.audit({ convert: true, results: require('../fixtures/audit-nyc-mkdirp/audit.json') }) - const arb = new Arborist({ - force: true, - path, - ...OPT, - }) + const arb = newArb(path, { force: true }) await arb.audit() t.matchSnapshot(printTree(await arb.buildIdealTree())) @@ -665,6 +623,7 @@ t.test('force a new mkdirp (but not semver major)', async t => { }) t.test('empty update should not trigger old lockfile', async t => { + createRegistry(t, false) const path = t.testdir({ 'package.json': JSON.stringify({ name: 'empty-update', @@ -683,15 +642,16 @@ t.test('empty update should not trigger old lockfile', async t => { }, }), }) - const checkLogs = warningTracker() + const warnings = warningTracker(t) const arb = newArb(path) await arb.reify({ update: true }) - t.strictSame(checkLogs(), []) + t.strictSame(warnings, []) }) t.test('update v3 doesnt downgrade lockfile', async t => { + createRegistry(t, false) const fixt = t.testdir({ 'package-lock.json': JSON.stringify({ name: 'empty-update-v3', @@ -721,19 +681,16 @@ t.test('update v3 doesnt downgrade lockfile', async t => { t.test('no fix available', async t => { const path = resolve(fixtures, 'audit-mkdirp/mkdirp-unfixable') - const checkLogs = warningTracker() - t.teardown(auditResponse(resolve(path, 'audit.json'))) + const warnings = warningTracker(t) + const registry = createRegistry(t, true) + registry.audit({ convert: true, results: require(resolve(path, 'audit.json')) }) - const arb = new Arborist({ - force: true, - path, - ...OPT, - }) + const arb = newArb(path, { force: true }) await arb.audit() t.matchSnapshot(printTree(await arb.buildIdealTree())) t.equal(arb.idealTree.children.get('mkdirp').package.version, '0.5.1') - t.match(checkLogs(), [ + t.match(warnings, [ oldLockfileWarning, ['warn', 'audit', 'No fix available for mkdirp@*'], ]) @@ -741,18 +698,15 @@ t.test('no fix available', async t => { t.test('no fix available, linked top package', async t => { const path = resolve(fixtures, 'audit-mkdirp') - const checkLogs = warningTracker() - t.teardown(auditResponse(resolve(path, 'mkdirp-unfixable/audit.json'))) + const warnings = warningTracker(t) + const registry = createRegistry(t, true) + registry.audit({ convert: true, results: require(resolve(path, 'mkdirp-unfixable', 'audit.json')) }) - const arb = new Arborist({ - force: true, - path, - ...OPT, - }) + const arb = newArb(path, { force: true }) await arb.audit() t.matchSnapshot(printTree(await arb.buildIdealTree())) - t.strictSame(checkLogs(), [ + t.strictSame(warnings, [ oldLockfileWarning, ['warn', 'audit', 'Manual fix required in linked project at ./mkdirp-unfixable for mkdirp@*.\n' + @@ -760,71 +714,84 @@ t.test('no fix available, linked top package', async t => { ]]) }) -t.test('workspaces', t => { - t.test('should install a simple example', t => { +t.test('workspaces', async t => { + await t.test('should install a simple example', async t => { + createRegistry(t, false) const path = resolve(__dirname, '../fixtures/workspaces-simple') - return t.resolveMatchSnapshot(printIdeal(path)) + await t.resolveMatchSnapshot(printIdeal(path)) }) - t.test('should update a simple example', t => { + await t.test('should update a simple example', async t => { + createRegistry(t, false) const path = resolve(__dirname, '../fixtures/workspaces-simple') - return t.resolveMatchSnapshot(printIdeal(path, { update: { all: true } })) + await t.resolveMatchSnapshot(printIdeal(path, { update: { all: true } })) }) - t.test('should install a simple scoped pkg example', t => { + await t.test('should install a simple scoped pkg example', async t => { + createRegistry(t, false) const path = resolve(__dirname, '../fixtures/workspaces-scoped-pkg') - return t.resolveMatchSnapshot(printIdeal(path)) + await t.resolveMatchSnapshot(printIdeal(path)) }) - t.test('should not work with duplicate names', t => { + await t.test('should not work with duplicate names', async t => { + createRegistry(t, false) const path = resolve(__dirname, '../fixtures/workspaces-duplicate') - return t.rejects(printIdeal(path), { code: 'EDUPLICATEWORKSPACE' }, 'throws EDUPLICATEWORKSPACE error') + await t.rejects(printIdeal(path), { code: 'EDUPLICATEWORKSPACE' }, 'throws EDUPLICATEWORKSPACE error') }) - t.test('should install shared dependencies into root folder', t => { + await t.test('should install shared dependencies into root folder', async t => { + createRegistry(t, true) const path = resolve(__dirname, '../fixtures/workspaces-shared-deps') - return t.resolveMatchSnapshot(printIdeal(path)) + await t.resolveMatchSnapshot(printIdeal(path)) }) - t.test('should install conflicting dep versions', t => { + await t.test('should install conflicting dep versions', async t => { + createRegistry(t, true) const path = resolve(__dirname, '../fixtures/workspaces-conflicting-versions') - return t.resolveMatchSnapshot(printIdeal(path)) + await t.resolveMatchSnapshot(printIdeal(path)) }) - t.test('should prefer linking nested workspaces', t => { + await t.test('should prefer linking nested workspaces', async t => { + createRegistry(t, false) const path = resolve(__dirname, '../fixtures/workspaces-prefer-linking') - return t.resolveMatchSnapshot(printIdeal(path)) + await t.resolveMatchSnapshot(printIdeal(path)) }) - t.test('should install from registry on version not satisfied', t => { + await t.test('should install from registry on version not satisfied', async t => { + createRegistry(t, true) const path = resolve(__dirname, '../fixtures/workspaces-version-unsatisfied') - return t.resolveMatchSnapshot(printIdeal(path)) + await t.resolveMatchSnapshot(printIdeal(path)) }) - t.test('should link top level nested workspaces', t => { + await t.test('should link top level nested workspaces', async t => { + createRegistry(t, false) const path = resolve(__dirname, '../fixtures/workspaces-top-level-link') - return t.resolveMatchSnapshot(printIdeal(path)) + await t.resolveMatchSnapshot(printIdeal(path)) }) - t.test('should install workspace transitive dependencies', t => { + await t.test('should install workspace transitive dependencies', async t => { + createRegistry(t, true) const path = resolve(__dirname, '../fixtures/workspaces-transitive-deps') - return t.resolveMatchSnapshot(printIdeal(path)) + await t.resolveMatchSnapshot(printIdeal(path)) }) - t.test('should ignore nested node_modules folders', t => { + await t.test('should ignore nested node_modules folders', async t => { // packages/a/node_modules/nested-workspaces should not be installed + createRegistry(t, false) const path = resolve(__dirname, '../fixtures/workspaces-ignore-nm') - return t.resolveMatchSnapshot(printIdeal(path)) + await t.resolveMatchSnapshot(printIdeal(path)) }) - t.test('should work with files spec', t => { + await t.test('should work with files spec', async t => { + createRegistry(t, false) const path = resolve(__dirname, '../fixtures/workspaces-with-files-spec') - return t.resolveMatchSnapshot(printIdeal(path)) + await t.resolveMatchSnapshot(printIdeal(path)) }) - t.test('should handle conflicting peer deps ranges', t => { + await t.test('should handle conflicting peer deps ranges', async t => { + createRegistry(t, true) const path = resolve(__dirname, '../fixtures/workspaces-peer-ranges') - return t.rejects( + await t.rejects( printIdeal(path), { code: 'ERESOLVE', @@ -833,10 +800,8 @@ t.test('workspaces', t => { ) }) - t.test('should allow adding a workspace as a dep to a workspace', async t => { - // turn off networking, this should never make a registry request - nock.disableNetConnect() - t.teardown(() => nock.enableNetConnect()) + await t.test('should allow adding a workspace as a dep to a workspace', async t => { + createRegistry(t, false) const path = t.testdir({ 'package.json': JSON.stringify({ @@ -857,11 +822,7 @@ t.test('workspaces', t => { }, }) - const arb = new Arborist({ - ...OPT, - path, - workspaces: ['workspace-a'], - }) + const arb = newArb(path, { workspaces: ['workspace-a'] }) const tree = arb.buildIdealTree({ path, @@ -877,13 +838,15 @@ t.test('workspaces', t => { t.matchSnapshot(printTree(await tree)) }) - t.test('should allow cyclic peer dependencies between workspaces and packages from a repository', async t => { - generateNocks(t, { - foo: { - versions: ['1.0.0'], - peerDependencies: ['workspace-a'], - }, + await t.test('should allow cyclic peer dependencies between workspaces and packages from a repository', async t => { + const registry = createRegistry(t, false) + const packument = registry.packument({ + name: 'foo', + version: '1.0.0', + peerDependencies: { 'workspace-a': '1.0.0' }, }) + const manifest = registry.manifest({ name: 'foo', packuments: [packument] }) + await registry.package({ manifest }) const path = t.testdir({ 'package.json': JSON.stringify({ name: 'root', @@ -903,31 +866,13 @@ t.test('workspaces', t => { }, }) - const arb = new Arborist({ - ...OPT, - path, - workspaces: ['workspace-a'], - }) - - const tree = arb.buildIdealTree({ - path, - add: [ - 'foo', - ], - }) - - // just assert that the buildIdealTree call resolves, if there's a - // problem here it will reject because of nock disabling requests - await t.resolves(tree) - - t.matchSnapshot(printTree(await tree)) + const arb = newArb(path, { workspaces: ['workspace-a'] }) + const tree = await arb.buildIdealTree({ path, add: ['foo'] }) + t.matchSnapshot(printTree(tree)) }) t.test('workspace nodes are used instead of fetching manifests when they are valid', async t => { - // turn off networking, this should never make a registry request - nock.disableNetConnect() - t.teardown(() => nock.enableNetConnect()) - + createRegistry(t, false) const path = t.testdir({ 'package.json': JSON.stringify({ name: 'root', @@ -999,11 +944,7 @@ t.test('workspaces', t => { }, }) - const arb = new Arborist({ - ...OPT, - path, - workspaces: ['workspace-a', 'workspace-b'], - }) + const arb = newArb(path, { workspaces: ['workspace-a', 'workspace-b'] }) // this will reject if we try to fetch a manifest for some reason const tree = await arb.buildIdealTree({ @@ -1021,11 +962,10 @@ t.test('workspaces', t => { const nodeBfromA = nodeA.edgesOut.get('workspace-b').to.target t.equal(nodeBfromA, nodeB, 'workspace-b edgeOut from workspace-a is the workspace') }) - - t.end() }) t.test('adding tarball to global prefix that is a symlink at a different path depth', async t => { + createRegistry(t, false) const fixt = t.testdir({ 'real-root': {}, 'another-path': { @@ -1033,11 +973,7 @@ t.test('adding tarball to global prefix that is a symlink at a different path de }, }) const path = resolve(fixt, 'another-path/global-root') - const arb = new Arborist({ - path, - global: true, - ...OPT, - }) + const arb = newArb(path, { global: true }) const tarballpath = resolve(__dirname, '../fixtures/registry-mocks/content/mkdirp/-/mkdirp-1.0.2.tgz') const tree = await arb.buildIdealTree({ @@ -1052,6 +988,7 @@ t.test('adding tarball to global prefix that is a symlink at a different path de }) t.test('add symlink that points to a symlink', t => { + createRegistry(t, false) const fixt = t.testdir({ 'global-prefix': { lib: { @@ -1071,10 +1008,7 @@ t.test('add symlink that points to a symlink', t => { }, }) const path = resolve(fixt, 'my-project') - const arb = new Arborist({ - path, - ...OPT, - }) + const arb = newArb(path) return arb.buildIdealTree({ add: [ // simulates the string used by `npm link ` when @@ -1089,7 +1023,8 @@ t.test('add symlink that points to a symlink', t => { ) }) -t.test('update global space single dep', t => { +t.test('update global space single dep', async t => { + createRegistry(t, true) const fixt = t.testdir({ 'global-prefix': { lib: { @@ -1109,19 +1044,18 @@ t.test('update global space single dep', t => { path, global: true, update: true, - ...OPT, } - const arb = new Arborist(opts) - return arb.buildIdealTree(opts).then(tree => - t.matchSnapshot( - printTree(tree), - 'should update global dependencies' - ) + const arb = newArb(path, opts) + const tree = await arb.buildIdealTree(opts) + t.matchSnapshot( + printTree(tree), + 'should update global dependencies' ) }) // if we get this wrong, it'll spin forever and use up all the memory t.test('pathologically nested dependency cycle', async t => { + createRegistry(t, true) t.matchSnapshot(await printIdeal( resolve(fixtures, 'pathological-dep-nesting-cycle'))) }) @@ -1129,17 +1063,14 @@ t.test('pathologically nested dependency cycle', async t => { t.test('resolve file deps from cwd', async t => { const cwd = process.cwd() t.teardown(() => process.chdir(cwd)) + createRegistry(t, false) const path = t.testdir({ global: {}, local: {}, }) const fixturedir = resolve(fixtures, 'root-bundler') process.chdir(fixturedir) - const arb = new Arborist({ - global: true, - path: resolve(path, 'global'), - ...OPT, - }) + const arb = newArb(resolve(path, 'global'), { global: true }) const tree = await arb.buildIdealTree({ path: `${path}/local`, add: ['child-1.2.3.tgz'], @@ -1152,6 +1083,7 @@ t.test('resolve file deps from cwd', async t => { t.test('resolve links in global mode', async t => { const cwd = process.cwd() t.teardown(() => process.chdir(cwd)) + createRegistry(t, false) const path = t.testdir({ global: {}, lib: { @@ -1167,11 +1099,7 @@ t.test('resolve links in global mode', async t => { const fixturedir = resolve(path, 'lib', 'my-project') process.chdir(fixturedir) - const arb = new Arborist({ - ...OPT, - global: true, - path: resolve(path, 'global'), - }) + const arb = newArb(resolve(path, 'global'), { global: true }) const tree = await arb.buildIdealTree({ add: ['file:../../linked-dep'], global: true, @@ -1180,20 +1108,22 @@ t.test('resolve links in global mode', async t => { t.equal(tree.children.get('linked-dep').resolved, resolved) }) -t.test('dont get confused if root matches duped metadep', async t => { +t.test('do not get confused if root matches duped metadep', async t => { + createRegistry(t, true) const path = resolve(fixtures, 'test-root-matches-metadep') - const arb = new Arborist({ path, installStrategy: 'hoisted', ...OPT }) + const arb = newArb(path, { installStrategy: 'hoisted' }) const tree = await arb.buildIdealTree() t.matchSnapshot(printTree(tree)) }) t.test('inflate an ancient lockfile by hitting the registry', async t => { - const checkLogs = warningTracker() + const warnings = warningTracker(t) + createRegistry(t, true) const path = resolve(fixtures, 'sax') - const arb = new Arborist({ path, ...OPT }) + const arb = newArb(path) const tree = await arb.buildIdealTree() t.matchSnapshot(printTree(tree)) - t.strictSame(checkLogs(), [ + t.strictSame(warnings, [ [ 'warn', 'ancient lockfile', @@ -1208,12 +1138,12 @@ This is a one-time fix-up, please be patient... }) t.test('inflating a link node in an old lockfile skips registry', async t => { - const checkLogs = warningTracker() + const warnings = warningTracker(t) const path = resolve(fixtures, 'old-lock-with-link') - const arb = new Arborist({ path, ...OPT, registry: 'http://invalid.host' }) + const arb = newArb(path, { registry: 'http://invalid.host' }) const tree = await arb.buildIdealTree() t.matchSnapshot(printTree(tree)) - t.strictSame(checkLogs(), [ + t.strictSame(warnings, [ [ 'warn', 'old lockfile', @@ -1228,12 +1158,13 @@ This is a one-time fix-up, please be patient... }) t.test('warn for ancient lockfile, even if we use v1', async t => { - const checkLogs = warningTracker() + const warnings = warningTracker(t) const path = resolve(fixtures, 'sax') - const arb = new Arborist({ path, lockfileVersion: 1, ...OPT }) + createRegistry(t, true) + const arb = newArb(path, { lockfileVersion: 1 }) const tree = await arb.buildIdealTree() t.matchSnapshot(printTree(tree)) - t.strictSame(checkLogs(), [ + t.strictSame(warnings, [ [ 'warn', 'ancient lockfile', @@ -1248,21 +1179,23 @@ This is a one-time fix-up, please be patient... }) t.test('no old lockfile warning if we write back v1', async t => { - const checkLogs = warningTracker() + const warnings = warningTracker(t) const path = resolve(fixtures, 'old-package-lock') - const arb = new Arborist({ path, lockfileVersion: 1, ...OPT }) + createRegistry(t, true) + const arb = newArb(path, { lockfileVersion: 1 }) const tree = await arb.buildIdealTree() t.matchSnapshot(printTree(tree)) - t.strictSame(checkLogs(), []) + t.strictSame(warnings, []) }) t.test('inflate an ancient lockfile with a dep gone missing', async t => { - const checkLogs = warningTracker() + const warnings = warningTracker(t) const path = resolve(fixtures, 'ancient-lockfile-invalid') - const arb = new Arborist({ path, ...OPT }) + createRegistry(t, true) + const arb = newArb(path) const tree = await arb.buildIdealTree() t.matchSnapshot(printTree(tree)) - t.match(checkLogs(), [ + t.match(warnings, [ [ 'warn', 'ancient lockfile', @@ -1283,12 +1216,13 @@ This is a one-time fix-up, please be patient... }) t.test('complete build for project with old lockfile', async t => { - const checkLogs = warningTracker() + const warnings = warningTracker(t) + createRegistry(t, false) const path = resolve(fixtures, 'link-dep-empty') - const arb = new Arborist({ path, ...OPT }) + const arb = newArb(path) const tree = await arb.buildIdealTree({ complete: true }) t.matchSnapshot(printTree(tree)) - t.match(checkLogs(), [ + t.match(warnings, [ oldLockfileWarning, ]) }) @@ -1310,9 +1244,11 @@ t.test('no old lockfile warning with no package-lock', async t => { }, }), }) - const checkLogs = warningTracker() + const warnings = warningTracker(t) + const registry = createRegistry(t, false) + registry.audit() await newArb(fixt).reify() - t.strictSame(checkLogs(), []) + t.strictSame(warnings, []) }) t.test('no old lockfile warning with a conflict package-lock', async t => { @@ -1335,9 +1271,11 @@ t.test('no old lockfile warning with a conflict package-lock', async t => { resolve(fixtures, 'conflict-package-lock/package-lock.json') ), }) - const checkLogs = warningTracker() + const warnings = warningTracker(t) + const registry = createRegistry(t, false) + registry.audit() await newArb(fixt).reify() - t.strictSame(checkLogs(), []) + t.strictSame(warnings, []) }) t.test('override a conflict with the root dep (with force)', async t => { @@ -1346,6 +1284,7 @@ t.test('override a conflict with the root dep (with force)', async t => { await t.rejects(() => buildIdeal(path), { code: 'ERESOLVE', }) + createRegistry(t, false) t.matchSnapshot(await printIdeal(path, { strictPeerDeps: true, force: true }), 'strict and force override') t.matchSnapshot(await printIdeal(path, { strictPeerDeps: false, force: true }), 'non-strict and force override') }) @@ -1355,12 +1294,14 @@ t.test('override a conflict with the root peer dep (with force)', async t => { await t.rejects(() => buildIdeal(path, { strictPeerDeps: true }), { code: 'ERESOLVE', }) + createRegistry(t, false) t.matchSnapshot(await printIdeal(path, { strictPeerDeps: true, force: true }), 'strict and force override') t.matchSnapshot(await printIdeal(path, { strictPeerDeps: false, force: true }), 'non-strict and force override') }) -t.test('push conflicted peer deps deeper in to the tree to solve', async t => { +t.test('push conflicted peer deps deeper into the tree to solve', async t => { const path = resolve(fixtures, 'testing-peer-dep-conflict-chain/override-dep') + createRegistry(t, true) t.matchSnapshot(await printIdeal(path)) }) @@ -1394,13 +1335,14 @@ t.test('do not continually re-resolve deps that failed to load', async t => { }, }), }) - const arb = new Arborist({ ...OPT, path }) - t.rejects(() => arb.buildIdealTree({ add: [ - '@isaacs/this-does-not-exist-actually@2.x', - ] }), { code: 'E404' }) + createRegistry(t, true) + const arb = newArb(path) + await t.rejects(() => arb.buildIdealTree({ + add: ['@isaacs/this-does-not-exist-actually@2.x'], + }), { code: 'E404' }) }) -t.test('update a node if its bundled by the root project', async t => { +t.test('update a node if it is bundled by the root project', async t => { const path = t.testdir({ node_modules: { abbrev: { @@ -1417,12 +1359,13 @@ t.test('update a node if its bundled by the root project', async t => { }, }), }) - const arb = new Arborist({ ...OPT, path }) + createRegistry(t, true) + const arb = newArb(path) await arb.buildIdealTree({ update: ['abbrev'] }) t.equal(arb.idealTree.children.get('abbrev').version, '1.1.1') }) -t.test('more peer dep conflicts', t => { +t.test('more peer dep conflicts', async t => { // each of these is installed and should pass in force mode, // fail in strictPeerDeps mode, and pass/fail based on the // 'error' field in non-strict/non-forced mode. @@ -1691,15 +1634,21 @@ t.test('more peer dep conflicts', t => { error: false, resolvable: true, }, + 'peerDep replacement of top level dep with different version resulting detached top level dep': { + pkg: { + description: 'a@ -> (PeerOptional(b, c, dep, dep)) b -> ( Peer(a) ) c -> ( Peer(a) )', + devDependencies: { + '@test/a': '^1.1.0', + '@test/b': '1.1.0', + }, + }, + error: false, + resolvable: true }, }) - if (process.platform !== 'win32') { - t.jobs = cases.length - } - t.plan(cases.length) - + createRegistry(t, true) for (const [name, { pkg, error, resolvable, add }] of cases) { - t.test(name, { buffer: true }, async t => { + await t.test(name, { buffer: true }, async t => { const path = t.testdir({ 'package.json': JSON.stringify(pkg), }) @@ -1712,9 +1661,9 @@ t.test('more peer dep conflicts', t => { error: () => {}, warn: (...msg) => warnings.push(normalizePaths(msg)), } - const strict = new Arborist({ ...OPT, path, strictPeerDeps: true }) - const force = new Arborist({ ...OPT, path, force: true }) - const def = new Arborist({ ...OPT, path, log }) + const strict = newArb(path, { strictPeerDeps: true }) + const force = newArb(path, { force: true }) + const def = newArb(path, { log }) // cannot do this in parallel on Windows machines, or it // crashes in CI with an EBUSY error when it tries to read @@ -1768,14 +1717,14 @@ t.test('more peer dep conflicts', t => { } }) -t.test('cases requiring peer sets to be nested', t => { +t.test('cases requiring peer sets to be nested', async t => { const cases = [ 'multi', 'simple', ] - t.plan(cases.length) for (const c of cases) { - t.test(c, async t => { + await t.test(c, async t => { + createRegistry(t, true) const path = resolve(`${fixtures}/testing-peer-dep-nesting/${c}`) t.matchSnapshot(await printIdeal(path)) }) @@ -1787,13 +1736,13 @@ t.test('make sure yargs works', async t => { // tests faster and force us to fully understand a problem, yargs has // been a bountiful source of complicated eslint peerDep issues. const yargs = resolve(fixtures, 'yargs') + createRegistry(t, true) t.matchSnapshot(await printIdeal(yargs), 'yargs should build fine') }) -t.test('allow updating when peer outside of explicit update set', t => { +t.test('allow updating when peer outside of explicit update set', async t => { // see https://github.com/npm/cli/issues/2000 - t.plan(2) - t.test('valid, no force required', async t => { + await t.test('valid, no force required', async t => { const path = t.testdir({ 'package.json': JSON.stringify({ name: 'x', @@ -1929,6 +1878,7 @@ t.test('allow updating when peer outside of explicit update set', t => { }, }), }) + createRegistry(t, true) t.matchSnapshot(await printIdeal(path, { add: [ '@isaacs/testing-peer-dep-conflict-chain-single-a@2', @@ -1937,7 +1887,7 @@ t.test('allow updating when peer outside of explicit update set', t => { })) }) - t.test('conflict, but resolves appropriately with --force', async t => { + await t.test('conflict, but resolves appropriately with --force', async t => { const path = t.testdir({ 'package.json': JSON.stringify({ name: 'x', @@ -2072,6 +2022,7 @@ t.test('allow updating when peer outside of explicit update set', t => { }, }), }) + createRegistry(t, true) t.matchSnapshot(await printIdeal(path, { force: true, add: [ @@ -2090,6 +2041,7 @@ t.test('allow updating when peer outside of explicit update set', t => { t.test('carbonium eslint conflicts', async t => { const path = resolve(fixtures, 'carbonium') + createRegistry(t, true) t.matchSnapshot(await printIdeal(path, { add: [ '@typescript-eslint/eslint-plugin@4', @@ -2100,7 +2052,8 @@ t.test('carbonium eslint conflicts', async t => { t.test('peerOptionals that are devDeps or explicit request', async t => { const path = resolve(fixtures, 'peer-optional-installs') - const arb = new Arborist({ path, ...OPT }) + createRegistry(t, true) + const arb = newArb(path) const tree = await arb.buildIdealTree({ add: ['abbrev'] }) t.matchSnapshot(printTree(tree), 'should install the abbrev dep') t.ok(tree.children.get('abbrev'), 'should install abbrev dep') @@ -2128,7 +2081,8 @@ t.test('weird thing when theres a link to ..', async t => { }), }, }) + '/y' - const arb = new Arborist({ path, ...OPT }) + createRegistry(t, false) + const arb = newArb(path) const tree = await arb.buildIdealTree() t.equal(tree.children.get('x').target.fsParent, null) }) @@ -2145,6 +2099,7 @@ t.test('always prefer deduping peer deps', async t => { }, }), }) + createRegistry(t, true) t.matchSnapshot(await printIdeal(path)) }) @@ -2162,7 +2117,8 @@ t.test('do not ever nest peer deps underneath their dependent ever', async t => }, }), }) - t.rejects(printIdeal(path), { code: 'ERESOLVE' }) + createRegistry(t, true) + await t.rejects(printIdeal(path), { code: 'ERESOLVE' }) }) t.test('properly fail on conflicted peerOptionals', async t => { @@ -2178,12 +2134,14 @@ t.test('properly fail on conflicted peerOptionals', async t => { }, }), }) + createRegistry(t, true) await t.rejects(printIdeal(path), { code: 'ERESOLVE' }) }) t.test('properly assign fsParent when paths have .. in them', async t => { const path = resolve(fixtures, 'fs-parent-dots/x/y/z') - const arb = new Arborist({ ...OPT, path }) + createRegistry(t, false) + const arb = newArb(path) const tree = await arb.buildIdealTree() t.matchSnapshot(printTree(tree)) for (const child of tree.children.values()) { @@ -2256,6 +2214,7 @@ t.test('update global', async t => { }, }) + createRegistry(t, true) t.matchSnapshot(await printIdeal(path, { global: true, update: ['abbrev'] }), 'updating missing dep should have no effect, but fix the invalid node') @@ -2270,7 +2229,7 @@ t.test('update global', async t => { 'once@2', ] for (const updateName of invalidArgs) { - t.rejects( + await t.rejects( printIdeal(path, { global: true, update: [updateName] }), { code: 'EUPDATEARGS' }, 'should throw an error when using semver ranges' @@ -2290,6 +2249,7 @@ t.test('update global when nothing in global', async t => { node_modules: {}, }, }) + createRegistry(t, false) const opts = { global: true, update: true } t.matchSnapshot(await printIdeal(path + '/no_nm', opts), 'update without node_modules') @@ -2297,6 +2257,44 @@ t.test('update global when nothing in global', async t => { 'update with empty node_modules') }) +t.test('update global ignores hidden node_modules entries', async t => { + const path = t.testdir({ + node_modules: { + '.hidden-non-package': { + node_modules: {}, + }, + '@scope': { + '.retired-package': { + node_modules: {}, + }, + }, + once: { + 'package.json': JSON.stringify({ + name: 'once', + version: '1.3.1', + dependencies: { + wrappy: '1', + }, + }), + node_modules: { + wrappy: { + 'package.json': JSON.stringify({ + name: 'wrappy', + version: '1.0.1', + }), + }, + }, + }, + }, + }) + createRegistry(t, true) + const tree = await buildIdeal(path, { global: true, update: true }) + const deps = tree.target.package.dependencies + t.notOk(deps['.hidden-non-package'], 'hidden entries are not queued for global update') + t.notOk(deps['@scope/.retired-package'], 'retired scoped entries are not queued for global update') + t.equal(deps.once, '*', 'visible global packages are queued for global update') +}) + t.test('peer dep that needs to be replaced', async t => { // this verifies that the webpack 5 that gets placed by default for // the initial dep will be successfully replaced by webpack 4 that @@ -2310,6 +2308,7 @@ t.test('peer dep that needs to be replaced', async t => { }, }), }) + createRegistry(t, true) t.matchSnapshot(await printIdeal(path)) }) @@ -2324,11 +2323,10 @@ t.test('transitive conflicted peer dependency', async t => { }, }), }) - const strict = { strictPeerDeps: true } - const force = { force: true } + createRegistry(t, true) t.matchSnapshot(await printIdeal(path)) - t.matchSnapshot(await printIdeal(path, force)) - await t.rejects(printIdeal(path, strict), { code: 'ERESOLVE' }) + t.matchSnapshot(await printIdeal(path, { force: true })) + await t.rejects(printIdeal(path, { strictPeerDeps: true }), { code: 'ERESOLVE' }) }) t.test('remove deps when initializing tree from actual tree', async t => { @@ -2343,17 +2341,18 @@ t.test('remove deps when initializing tree from actual tree', async t => { }, }) - const arb = new Arborist({ path, ...OPT }) + createRegistry(t, false) + const arb = newArb(path) const tree = await arb.buildIdealTree({ rm: ['foo'] }) t.equal(tree.children.get('foo'), undefined, 'removed foo child') }) -t.test('detect conflicts in transitive peerOptional deps', t => { - t.plan(2) +t.test('detect conflicts in transitive peerOptional deps', async t => { const base = resolve(fixtures, 'test-conflicted-optional-peer-dep') - t.test('nest when peerOptional conflicts', async t => { + await t.test('nest when peerOptional conflicts', async t => { const path = resolve(base, 'nest-peer-optional') + createRegistry(t, true) const tree = await buildIdeal(path) t.matchSnapshot(printTree(tree)) const name = '@isaacs/test-conflicted-optional-peer-dep-peer' @@ -2361,8 +2360,9 @@ t.test('detect conflicts in transitive peerOptional deps', t => { t.equal(peers.size, 2, 'installed the peer dep twice to avoid conflict') }) - t.test('omit peerOptionals when not needed for conflicts', async t => { + await t.test('omit peerOptionals when not needed for conflicts', async t => { const path = resolve(base, 'omit-peer-optional') + createRegistry(t, true) const tree = await buildIdeal(path) t.matchSnapshot(printTree(tree)) const name = '@isaacs/test-conflicted-optional-peer-dep-peer' @@ -2373,6 +2373,7 @@ t.test('detect conflicts in transitive peerOptional deps', t => { t.test('do not fail if root peerDep looser than meta peerDep', async t => { const path = resolve(fixtures, 'test-peer-looser-than-dev') + createRegistry(t, true) t.matchSnapshot(await printIdeal(path)) }) @@ -2392,6 +2393,7 @@ t.test('adding existing dep with updateable version in package.json', async t => }), }) + createRegistry(t, true) t.matchSnapshot(await printIdeal(path, { add: ['lodash'] })) }) @@ -2409,8 +2411,9 @@ t.test('set the current on ERESOLVE triggered by devDeps', async t => { }), }) - const arb = new Arborist({ path, ...OPT }) - t.rejects(arb.buildIdealTree(), { + createRegistry(t, true) + const arb = newArb(path) + await t.rejects(arb.buildIdealTree(), { code: 'ERESOLVE', current: { name: 'eslint', @@ -2425,62 +2428,14 @@ t.test('set the current on ERESOLVE triggered by devDeps', async t => { }) }) -t.test('shrinkwrapped dev/optional deps should not clobber flags', t => { - t.test('optional', async t => { - const path = t.testdir({ - 'package.json': JSON.stringify({ - name: 'project', - version: '1.2.3', - optionalDependencies: { - '@isaacs/test-package-with-shrinkwrap': '^1.0.0', - }, - }), - }) - const tree = await buildIdeal(path, { complete: true }) - const swName = '@isaacs/test-package-with-shrinkwrap' - const swDep = tree.children.get(swName) - const metaDep = swDep.children.get('abbrev') - t.equal(swDep.optional, true, 'shrinkwrapped dep is optional') - t.equal(metaDep.optional, true, 'shrinkwrapped metadep optional') - - // make sure we're not just somehow leaving ALL flags true - t.equal(swDep.dev, false, 'sw dep is not dev') - t.equal(metaDep.dev, false, 'meta dep is not dev') - }) - - t.test('dev', async t => { - const path = t.testdir({ - 'package.json': JSON.stringify({ - name: 'project', - version: '1.2.3', - devDependencies: { - '@isaacs/test-package-with-shrinkwrap': '^1.0.0', - }, - }), - }) - const tree = await buildIdeal(path, { complete: true }) - const swName = '@isaacs/test-package-with-shrinkwrap' - const swDep = tree.children.get(swName) - const metaDep = swDep.children.get('abbrev') - t.equal(swDep.dev, true, 'shrinkwrapped dep is dev') - t.equal(metaDep.dev, true, 'shrinkwrapped metadep dev') - - // make sure we're not just somehow leaving ALL flags true - t.equal(swDep.optional, false, 'sw dep is not optional') - t.equal(metaDep.optional, false, 'meta dep is not optional') - }) - - t.end() -}) - -t.test('do not ERESOLVE on peerOptionals that are ignored anyway', t => { +t.test('do not ERESOLVE on peerOptionals that are ignored anyway', async t => { // this simulates three cases where a conflict occurs during the peerSet // generation phase, but will not manifest in the tree building phase. const base = resolve(fixtures, 'peer-optional-eresolve') const cases = ['a', 'b', 'c', 'd', 'e', 'f'] - t.plan(cases.length) for (const c of cases) { - t.test(`case ${c}`, async t => { + await t.test(`case ${c}`, async t => { + createRegistry(t, true) const path = resolve(base, c) t.matchSnapshot(await printIdeal(path)) }) @@ -2497,8 +2452,7 @@ t.test('allow ERESOLVE to be forced when not in the source', async t => { // in these tests, the deps are both of the same type. b has a peerOptional // dep on peer, and peer is a direct dependency of the root. - t.test('both direct and peer of the same type', t => { - t.plan(types.length) + await t.test('both direct and peer of the same type', async t => { const pj = type => ({ name: '@isaacs/conflicted-peer-optional-from-dev-dep', version: '1.2.3', @@ -2509,10 +2463,11 @@ t.test('allow ERESOLVE to be forced when not in the source', async t => { }) for (const type of types) { - t.test(type, async t => { + await t.test(type, async t => { const path = t.testdir({ 'package.json': JSON.stringify(pj(type)), }) + createRegistry(t, true) t.matchSnapshot(await printIdeal(path, { force: true }), 'use the force') t.rejects(printIdeal(path), { code: 'ERESOLVE' }, 'no force') }) @@ -2520,7 +2475,7 @@ t.test('allow ERESOLVE to be forced when not in the source', async t => { }) // in these, the peer is a peer dep of the root, and b is a different type - t.test('peer is peer, b is some other type', t => { + await t.test('peer is peer, b is some other type', async t => { t.plan(types.length - 1) const pj = type => ({ name: '@isaacs/conflicted-peer-optional-from-dev-dep', @@ -2536,10 +2491,11 @@ t.test('allow ERESOLVE to be forced when not in the source', async t => { if (type === 'peerDependencies') { continue } - t.test(type, async t => { + await t.test(type, async t => { const path = t.testdir({ 'package.json': JSON.stringify(pj(type)), }) + createRegistry(t, true) t.matchSnapshot(await printIdeal(path, { force: true }), 'use the force') t.rejects(printIdeal(path), { code: 'ERESOLVE' }, 'no force') }) @@ -2547,8 +2503,7 @@ t.test('allow ERESOLVE to be forced when not in the source', async t => { }) // in these, b is a peer dep, and peer is some other type - t.test('peer is peer, b is some other type', t => { - t.plan(types.length - 1) + await t.test('peer is peer, b is some other type', async t => { const pj = type => ({ name: '@isaacs/conflicted-peer-optional-from-dev-dep', version: '1.2.3', @@ -2563,17 +2518,16 @@ t.test('allow ERESOLVE to be forced when not in the source', async t => { if (type === 'peerDependencies') { continue } - t.test(type, async t => { + await t.test(type, async t => { const path = t.testdir({ 'package.json': JSON.stringify(pj(type)), }) + createRegistry(t, true) t.matchSnapshot(await printIdeal(path, { force: true }), 'use the force') t.rejects(printIdeal(path), { code: 'ERESOLVE' }, 'no force') }) } }) - - t.end() }) t.test('allow a link dep to satisfy a peer dep', async t => { @@ -2599,6 +2553,7 @@ t.test('allow a link dep to satisfy a peer dep', async t => { }, }) + createRegistry(t, true) const add = ['@isaacs/testing-peer-dep-conflict-chain-vv@2'] // avoids if the link dep is unmet @@ -2680,22 +2635,24 @@ t.test('replace a link with a matching link when the current one is wrong', asyn }, }), }) + createRegistry(t, false) t.matchSnapshot(await printIdeal(path, { workspaces: null, // also test that a null workspaces is ignored. }), 'replace incorrect with correct') }) -t.test('cannot do workspaces in global mode', t => { +t.test('cannot do workspaces in global mode', async t => { + createRegistry(t, false) t.throws(() => printIdeal(t.testdir(), { workspaces: ['a', 'b', 'c'], global: true, }), { message: 'Cannot operate on workspaces in global mode' }) - t.end() }) t.test('add packages to workspaces, not root', async t => { const path = resolve(__dirname, '../fixtures/workspaces-not-root') + createRegistry(t, true) const addTree = await buildIdeal(path, { add: ['wrappy@1.0.1'], workspaces: ['a', 'c'], @@ -2724,6 +2681,7 @@ t.test('add one workspace to another', async t => { const path = resolve(__dirname, '../fixtures/workspaces-not-root') const packageA = resolve(path, 'packages/a') + createRegistry(t, false) const addTree = await buildIdeal(path, { add: [packageA], workspaces: ['c'], @@ -2769,23 +2727,25 @@ t.test('workspace error handling', async t => { }, }, }) - t.test('set filter, but no workspaces present', async t => { - const logs = warningTracker() + await t.test('set filter, but no workspaces present', async t => { + const warnings = warningTracker(t) + createRegistry(t, false) await buildIdeal(resolve(path, 'packages/a'), { workspaces: ['a'], }) - t.strictSame(logs(), [[ + t.strictSame(warnings, [[ 'warn', 'workspaces', 'filter set, but no workspaces present', ]], 'got warning') }) - t.test('set filter for workspace that is not present', async t => { - const logs = warningTracker() + await t.test('set filter for workspace that is not present', async t => { + const warnings = warningTracker(t) + createRegistry(t, true) await buildIdeal(path, { workspaces: ['not-here'], }) - t.strictSame(logs(), [[ + t.strictSame(warnings, [[ 'warn', 'workspaces', 'not-here in filter set, but not in workspaces', @@ -2807,6 +2767,7 @@ t.test('avoid dedupe when a dep is bundled', async t => { }), }) + createRegistry(t, true) // do our install, prior to the publishing of b@2.1.0 const startTree = await buildIdeal(path, { // date between publish times of b@2.0.0 and b@2.1.0 @@ -2820,7 +2781,7 @@ t.test('avoid dedupe when a dep is bundled', async t => { // +-- b@2.0 await startTree.meta.save() let b200 - t.test('initial tree state', t => { + await t.test('initial tree state', async t => { const a = startTree.children.get('@isaacs/testing-bundle-dupes-a') const b = startTree.children.get('@isaacs/testing-bundle-dupes-b') const bNested = a.children.get('@isaacs/testing-bundle-dupes-b') @@ -2829,21 +2790,19 @@ t.test('avoid dedupe when a dep is bundled', async t => { t.equal(bNested.version, '2.0.0') // save this to synthetically create the dupe later, so we can fix it b200 = bNested - t.end() }) // Now ensure that adding b@2 will install b@2.1.0 AND // dedupe the nested b@2.0.0 dep. const add = ['@isaacs/testing-bundle-dupes-b@2'] const newTree = await buildIdeal(path, { add }) - t.test('did not create dupe', t => { + await t.test('did not create dupe', async t => { const a = newTree.children.get('@isaacs/testing-bundle-dupes-a') const b = newTree.children.get('@isaacs/testing-bundle-dupes-b') const bNested = a.children.get('@isaacs/testing-bundle-dupes-b') t.equal(b.version, '2.1.0') t.equal(a.version, '2.0.0') t.notOk(bNested, 'should not have a nested b') - t.end() }) // now, synthetically create the bug we just verified no longer happens, @@ -2862,7 +2821,7 @@ t.test('avoid dedupe when a dep is bundled', async t => { })) // gut check that we have reproduced the error condition - t.test('gut check that dupe synthetically created', t => { + await t.test('gut check that dupe synthetically created', async t => { const a = newTree.children.get('@isaacs/testing-bundle-dupes-a') const b = newTree.children.get('@isaacs/testing-bundle-dupes-b') const bNested = a.children.get('@isaacs/testing-bundle-dupes-b') @@ -2883,24 +2842,24 @@ t.test('avoid dedupe when a dep is bundled', async t => { t.notOk(bNested, 'should not have a nested b') } - t.test('dedupe to remove dupe', async t => { + await t.test('dedupe to remove dupe', async t => { check(t, await buildIdeal(path, { update: ['@isaacs/testing-bundle-dupes-b'], preferDedupe: true, })) }) - t.test('update b to remove dupe', async t => { + await t.test('update b to remove dupe', async t => { check(t, await buildIdeal(path, { update: ['@isaacs/testing-bundle-dupes-b'], })) }) - t.test('update all to remove dupe', async t => { + await t.test('update all to remove dupe', async t => { check(t, await buildIdeal(path, { update: true })) }) - t.test('reinstall a to remove dupe', async t => { + await t.test('reinstall a to remove dupe', async t => { check(t, await buildIdeal(path, { add: ['@isaacs/testing-bundle-dupes-a@2'], })) @@ -2914,6 +2873,69 @@ t.test('avoid dedupe when a dep is bundled', async t => { }) }) +t.test('min-release-age-exclude exempts matched packages from the before filter', async t => { + // The dupes-b fixture publishes 2.0.0 at 16:23:59 and 2.1.0 at 16:25:15. + // A `before` of 16:24:00 normally filters 2.1.0 out, leaving 2.0.0. + const before = new Date('2021-04-23T16:24:00Z') + const pkg = '@isaacs/testing-bundle-dupes-b' + const mkPath = () => t.testdir({ + 'package.json': JSON.stringify({ + dependencies: { [pkg]: '2' }, + }), + }) + + await t.test('without exclude, before filters to the older version', async t => { + createRegistry(t, true) + const tree = await buildIdeal(mkPath(), { before }) + t.equal(tree.children.get(pkg).version, '2.0.0', 'before filter applied') + }) + + await t.test('exact name in exclude bypasses the before filter', async t => { + createRegistry(t, true) + const tree = await buildIdeal(mkPath(), { + before, + minReleaseAgeExclude: [pkg], + }) + t.equal(tree.children.get(pkg).version, '2.1.0', 'newest version installed') + }) + + await t.test('glob pattern in exclude bypasses the before filter', async t => { + createRegistry(t, true) + const tree = await buildIdeal(mkPath(), { + before, + minReleaseAgeExclude: ['@isaacs/*'], + }) + t.equal(tree.children.get(pkg).version, '2.1.0', 'newest version installed') + }) + + await t.test('non-matching exclude leaves the before filter in place', async t => { + createRegistry(t, true) + const tree = await buildIdeal(mkPath(), { + before, + minReleaseAgeExclude: ['some-other-pkg', '@other/*'], + }) + t.equal(tree.children.get(pkg).version, '2.0.0', 'before filter still applied') + }) + + await t.test('an npm: alias key cannot bypass the filter for its target', async t => { + // The exclude must match the resolved registry identity, not the alias key. + // Here the alias key `dupes` matches the exclude but the fetched package + // `pkg` does not, so the before filter must still apply. + createRegistry(t, true) + const aliasPath = t.testdir({ + 'package.json': JSON.stringify({ + dependencies: { dupes: `npm:${pkg}@2` }, + }), + }) + const tree = await buildIdeal(aliasPath, { + before, + minReleaseAgeExclude: ['dupes'], + }) + t.equal(tree.children.get('dupes').version, '2.0.0', + 'before filter still applied to the aliased package') + }) +}) + t.test('upgrade a partly overlapping peer set', async t => { const path = t.testdir({ 'package.json': JSON.stringify({ @@ -2923,6 +2945,7 @@ t.test('upgrade a partly overlapping peer set', async t => { }, }), }) + createRegistry(t, true) const tree = await buildIdeal(path) await tree.meta.save() t.matchSnapshot(await printIdeal(path, { @@ -2940,9 +2963,10 @@ t.test('fail to upgrade a partly overlapping peer set', async t => { }, }), }) + createRegistry(t, true) const tree = await buildIdeal(path) await tree.meta.save() - t.rejects(printIdeal(path, { + await t.rejects(printIdeal(path, { add: ['@isaacs/testing-peer-dep-conflict-chain-y@3'], }), { code: 'ERESOLVE' }, 'should not be able to upgrade dep') }) @@ -2979,6 +3003,7 @@ t.test('add deps to workspaces', async t => { const path = t.testdir(fixtureDef) t.test('no args', async t => { + createRegistry(t, true) const tree = await buildIdeal(path) t.equal(tree.children.get('mkdirp').version, '1.0.4') t.equal(tree.children.get('a').target.children.get('mkdirp').version, '0.5.5') @@ -2987,6 +3012,7 @@ t.test('add deps to workspaces', async t => { }) t.test('add mkdirp 0.5.0 to b', async t => { + createRegistry(t, true) const tree = await buildIdeal(path, { workspaces: ['b'], add: ['mkdirp@0.5.0'] }) t.equal(tree.children.get('mkdirp').version, '1.0.4') t.equal(tree.children.get('a').target.children.get('mkdirp').version, '0.5.5') @@ -2995,6 +3021,7 @@ t.test('add deps to workspaces', async t => { }) t.test('remove mkdirp from a', async t => { + createRegistry(t, true) const tree = await buildIdeal(path, { workspaces: ['a'], rm: ['mkdirp'] }) t.equal(tree.children.get('mkdirp').version, '1.0.4') t.equal(tree.children.get('a').target.children.get('mkdirp'), undefined) @@ -3003,6 +3030,7 @@ t.test('add deps to workspaces', async t => { }) t.test('upgrade mkdirp in a, dedupe on root', async t => { + createRegistry(t, true) const tree = await buildIdeal(path, { workspaces: ['a'], add: ['mkdirp@1'] }) t.equal(tree.children.get('mkdirp').version, '1.0.4') t.equal(tree.children.get('a').target.children.get('mkdirp'), undefined) @@ -3013,6 +3041,8 @@ t.test('add deps to workspaces', async t => { t.test('KEEP in the root, prune out unnecessary dupe', async t => { const path = t.testdir(fixtureDef) + const registry = createRegistry(t, true) + registry.audit() const arb = newArb(path) // reify first so that the other mkdirp is present in the tree await arb.reify() @@ -3057,6 +3087,7 @@ t.test('add deps and include workspace-root', async t => { const path = t.testdir(fixtureDef) t.test('no args', async t => { + createRegistry(t, true) const tree = await buildIdeal(path) t.equal(tree.children.get('mkdirp').version, '1.0.4') t.equal(tree.children.get('a').target.children.get('mkdirp').version, '0.5.5') @@ -3066,6 +3097,7 @@ t.test('add deps and include workspace-root', async t => { }) t.test('add mkdirp 0.5.0 to b', async t => { + createRegistry(t, true) const tree = await buildIdeal(path, { workspaces: ['b'], add: ['mkdirp@0.5.0'], includeWorkspaceRoot: true }) t.equal(tree.children.get('mkdirp').version, '0.5.0') t.ok(tree.edgesOut.has('mkdirp')) @@ -3103,6 +3135,7 @@ t.test('inflates old lockfile with hasInstallScript', async t => { }, }, }) + createRegistry(t, true) const tree = await buildIdeal(path, { add: ['esbuild@0.11.10'], @@ -3129,25 +3162,25 @@ t.test('update a global space that contains a link', async t => { once: t.fixture('symlink', '../target'), }, }) + createRegistry(t, true) const tree = await buildIdeal(path, { update: true, global: true }) t.matchSnapshot(printTree(tree)) t.equal(tree.children.get('once').isLink, true) }) -t.test('peer conflicts between peer sets in transitive deps', t => { - t.plan(4) - +t.test('peer conflicts between peer sets in transitive deps', async t => { // caused an infinite loop in https://github.com/npm/arborist/issues/325, // which is the reason for the package name. - t.test('y and j@2 at root, x and j@1 underneath a', async t => { + await t.test('y and j@2 at root, x and j@1 underneath a', async t => { const path = t.testdir({ 'package.json': '{}', }) - const warnings = warningTracker() + createRegistry(t, true) + const warnings = warningTracker(t) const tree = await buildIdeal(path, { add: ['@isaacs/peer-dep-conflict-infinite-loop-a@1'], }) - t.strictSame(warnings(), []) + t.strictSame(warnings, []) const a = tree.children.get('@isaacs/peer-dep-conflict-infinite-loop-a') const j = tree.children.get('@isaacs/peer-dep-conflict-infinite-loop-j') const x = tree.children.get('@isaacs/peer-dep-conflict-infinite-loop-x') @@ -3164,15 +3197,16 @@ t.test('peer conflicts between peer sets in transitive deps', t => { t.notOk(ay) }) - t.test('x and j@1 at root, y and j@2 underneath a', async t => { + await t.test('x and j@1 at root, y and j@2 underneath a', async t => { const path = t.testdir({ 'package.json': '{}', }) - const warnings = warningTracker() + createRegistry(t, true) + const warnings = warningTracker(t) const tree = await buildIdeal(path, { add: ['@isaacs/peer-dep-conflict-infinite-loop-a@2'], }) - t.strictSame(warnings(), []) + t.strictSame(warnings, []) const a = tree.children.get('@isaacs/peer-dep-conflict-infinite-loop-a') const j = tree.children.get('@isaacs/peer-dep-conflict-infinite-loop-j') const x = tree.children.get('@isaacs/peer-dep-conflict-infinite-loop-x') @@ -3189,15 +3223,16 @@ t.test('peer conflicts between peer sets in transitive deps', t => { t.notOk(ax) }) - t.test('get warning, x and j@1 in root, put y and j@3 in a', async t => { + await t.test('get warning, x and j@1 in root, put y and j@3 in a', async t => { const path = t.testdir({ 'package.json': '{}', }) - const warnings = warningTracker() + createRegistry(t, true) + const warnings = warningTracker(t) const tree = await buildIdeal(path, { add: ['@isaacs/peer-dep-conflict-infinite-loop-a@3'], }) - const w = warnings() + const w = warnings t.match(w, [['warn', 'ERESOLVE', 'overriding peer dependency', { code: 'ERESOLVE', }]], 'warning is an ERESOLVE') @@ -3219,15 +3254,16 @@ t.test('peer conflicts between peer sets in transitive deps', t => { t.notOk(ax) }) - t.test('x and j@1 at root, y and j@2 underneath a (no a->j dep)', async t => { + await t.test('x and j@1 at root, y and j@2 underneath a (no a->j dep)', async t => { const path = t.testdir({ 'package.json': '{}', }) - const warnings = warningTracker() + const warnings = warningTracker(t) + createRegistry(t, true) const tree = await buildIdeal(path, { add: ['@isaacs/peer-dep-conflict-infinite-loop-a@4'], }) - t.strictSame(warnings(), [], 'no warnings') + t.strictSame(warnings, [], 'no warnings') const a = tree.children.get('@isaacs/peer-dep-conflict-infinite-loop-a') const j = tree.children.get('@isaacs/peer-dep-conflict-infinite-loop-j') @@ -3244,14 +3280,11 @@ t.test('peer conflicts between peer sets in transitive deps', t => { t.equal(aj.version, '2.0.0') t.notOk(ax) }) - - t.end() }) -t.test('competing peerSets resolve in both root and workspace', t => { +t.test('competing peerSets resolve in both root and workspace', async t => { // The following trees caused an infinite loop in a workspace // https://github.com/npm/cli/issues/3933 - t.plan(2) const rootAndWs = async dependencies => { const fixt = t.testdir({ @@ -3283,7 +3316,7 @@ t.test('competing peerSets resolve in both root and workspace', t => { ] } - t.test('overlapping peerSets dont warn', async t => { + await t.test('overlapping peerSets do not warn', async t => { // This should not cause a warning because replacing `c@2` and `d@2` // with `c@1` and `d@1` is still valid. // @@ -3296,7 +3329,8 @@ t.test('competing peerSets resolve in both root and workspace', t => { // d@2 -> PEER(c@2) // ``` - const warnings = warningTracker() + createRegistry(t, true) + const warnings = warningTracker(t) const [rootTree, wsTree] = await rootAndWs({ '@lukekarrys/workspace-peer-dep-infinite-loop-a': '1', }) @@ -3320,9 +3354,9 @@ t.test('competing peerSets resolve in both root and workspace', t => { t.equal(wsC.version, '1.0.0', 'workspace c version') t.equal(wsD.version, '1.0.0', 'workspace d version') - const [rootWarnings = [], wsWarnings = []] = warnings() + const [rootWarnings = [], wsWarnings = []] = warnings // TODO: these warn for now but shouldnt - // https://github.com/npm/arborist/issues/347 + // https://github.com/npm/cli/issues/4270 t.comment('FIXME') t.match(rootWarnings, ['warn', 'ERESOLVE', 'overriding peer dependency', { code: 'ERESOLVE', @@ -3337,7 +3371,7 @@ t.test('competing peerSets resolve in both root and workspace', t => { t.matchSnapshot(printTree(wsTree), 'workspace tree') }) - t.test('conflicting peerSets do warn', async t => { + await t.test('conflicting peerSets do warn', async t => { // ``` // project -> (a@2) // a@2 -> (b), PEER(c@2), PEER(d@2) @@ -3347,7 +3381,8 @@ t.test('competing peerSets resolve in both root and workspace', t => { // d@2 -> PEER(c@2) // ``` - const warnings = warningTracker() + createRegistry(t, true) + const warnings = warningTracker(t) const [rootTree, wsTree] = await rootAndWs({ // It's 2.0.1 because I messed up publishing 2.0.0 '@lukekarrys/workspace-peer-dep-infinite-loop-a': '2.0.1', @@ -3382,12 +3417,12 @@ t.test('competing peerSets resolve in both root and workspace', t => { t.equal(wsD.version, '1.0.0', 'workspace d version') // TODO: these should not be undefined - // https://github.com/npm/arborist/issues/348 + // https://github.com/npm/cli/issues/4269 t.comment('FIXME') t.equal((wsTargetC || {}).version, undefined, 'workspace target c version') t.equal((wsTargetD || {}).version, undefined, 'workspace target d version') - const [rootWarnings, wsWarnings] = warnings() + const [rootWarnings, wsWarnings] = warnings t.match(rootWarnings, ['warn', 'ERESOLVE', 'overriding peer dependency', { code: 'ERESOLVE', }], 'root warning is an ERESOLVE') @@ -3400,12 +3435,10 @@ t.test('competing peerSets resolve in both root and workspace', t => { t.matchSnapshot(printTree(rootTree), 'root tree') t.matchSnapshot(printTree(wsTree), 'workspace tree') }) - - t.end() }) -t.test('overrides', t => { - t.test('throws when override conflicts with dependencies', async (t) => { +t.test('overrides', async t => { + await t.test('throws when override conflicts with dependencies', async (t) => { const path = t.testdir({ 'package.json': JSON.stringify({ name: 'root', @@ -3418,10 +3451,11 @@ t.test('overrides', t => { }), }) + createRegistry(t, false) await t.rejects(buildIdeal(path), { code: 'EOVERRIDE' }, 'throws EOVERRIDE') }) - t.test('throws when override conflicts with devDependencies', async (t) => { + await t.test('throws when override conflicts with devDependencies', async (t) => { const path = t.testdir({ 'package.json': JSON.stringify({ name: 'root', @@ -3434,10 +3468,11 @@ t.test('overrides', t => { }), }) + createRegistry(t, false) await t.rejects(buildIdeal(path), { code: 'EOVERRIDE' }, 'throws EOVERRIDE') }) - t.test('throws when override conflicts with peerDependencies', async (t) => { + await t.test('throws when override conflicts with peerDependencies', async (t) => { const path = t.testdir({ 'package.json': JSON.stringify({ name: 'root', @@ -3450,20 +3485,11 @@ t.test('overrides', t => { }), }) + createRegistry(t, false) await t.rejects(buildIdeal(path), { code: 'EOVERRIDE' }, 'throws EOVERRIDE') }) t.test('overrides a nested dependency', async (t) => { - generateNocks(t, { - foo: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - dependencies: ['bar'], - }, - bar: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - }, - }) - const path = t.testdir({ 'package.json': JSON.stringify({ name: 'root', @@ -3475,6 +3501,17 @@ t.test('overrides', t => { }, }), }) + const registry = createRegistry(t, false) + const fooPackuments = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + { version: '1.0.1', dependencies: { bar: '1.0.1' } }, + { version: '2.0.0', dependencies: { bar: '2.0.0' } }, + ], 'foo') + const fooManifest = registry.manifest({ name: 'foo', packuments: fooPackuments }) + const barPackuments = registry.packuments(['1.0.0', '1.0.1', '2.0.0'], 'bar') + const barManifest = registry.manifest({ name: 'bar', packuments: barPackuments }) + await registry.package({ manifest: fooManifest }) + await registry.package({ manifest: barManifest }) const tree = await buildIdeal(path) @@ -3487,15 +3524,17 @@ t.test('overrides', t => { }) t.test('overrides a nested dependency with a more specific override', async (t) => { - generateNocks(t, { - foo: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - dependencies: ['bar'], - }, - bar: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - }, - }) + const registry = createRegistry(t, false) + const fooPackuments = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + { version: '1.0.1', dependencies: { bar: '1.0.1' } }, + { version: '2.0.0', dependencies: { bar: '2.0.0' } }, + ], 'foo') + const fooManifest = registry.manifest({ name: 'foo', packuments: fooPackuments }) + const barPackuments = registry.packuments(['1.0.0', '1.0.1', '2.0.0'], 'bar') + const barManifest = registry.manifest({ name: 'bar', packuments: barPackuments }) + await registry.package({ manifest: fooManifest }) + await registry.package({ manifest: barManifest }) const path = t.testdir({ 'package.json': JSON.stringify({ @@ -3527,15 +3566,17 @@ t.test('overrides', t => { }) t.test('does not override a nested dependency when parent spec does not match', async (t) => { - generateNocks(t, { - foo: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - dependencies: ['bar'], - }, - bar: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - }, - }) + const registry = createRegistry(t, false) + const fooPackuments = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + { version: '1.0.1', dependencies: { bar: '1.0.1' } }, + { version: '2.0.0', dependencies: { bar: '2.0.0' } }, + ], 'foo') + const fooManifest = registry.manifest({ name: 'foo', packuments: fooPackuments }) + const barPackuments = registry.packuments(['1.0.0', '1.0.1', '2.0.0'], 'bar') + const barManifest = registry.manifest({ name: 'bar', packuments: barPackuments }) + await registry.package({ manifest: fooManifest }) + await registry.package({ manifest: barManifest, times: 2 }) const path = t.testdir({ 'package.json': JSON.stringify({ @@ -3567,15 +3608,17 @@ t.test('overrides', t => { }) t.test('overrides a nested dependency that also exists as a direct dependency', async (t) => { - generateNocks(t, { - foo: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - dependencies: ['bar'], - }, - bar: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - }, - }) + const registry = createRegistry(t, false) + const fooPackuments = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + { version: '1.0.1', dependencies: { bar: '1.0.1' } }, + { version: '2.0.0', dependencies: { bar: '2.0.0' } }, + ], 'foo') + const fooManifest = registry.manifest({ name: 'foo', packuments: fooPackuments }) + const barPackuments = registry.packuments(['1.0.0', '1.0.1', '2.0.0'], 'bar') + const barManifest = registry.manifest({ name: 'bar', packuments: barPackuments }) + await registry.package({ manifest: fooManifest }) + await registry.package({ manifest: barManifest }) const path = t.testdir({ 'package.json': JSON.stringify({ @@ -3610,15 +3653,17 @@ t.test('overrides', t => { }) t.test('overrides a nested dependency that also exists as a direct dependency without a top level specifier', async (t) => { - generateNocks(t, { - foo: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - dependencies: ['bar'], - }, - bar: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - }, - }) + const registry = createRegistry(t, false) + const fooPackuments = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + { version: '1.0.1', dependencies: { bar: '1.0.1' } }, + { version: '2.0.0', dependencies: { bar: '2.0.0' } }, + ], 'foo') + const fooManifest = registry.manifest({ name: 'foo', packuments: fooPackuments }) + const barPackuments = registry.packuments(['1.0.0', '1.0.1', '2.0.0'], 'bar') + const barManifest = registry.manifest({ name: 'bar', packuments: barPackuments }) + await registry.package({ manifest: fooManifest }) + await registry.package({ manifest: barManifest }) const path = t.testdir({ 'package.json': JSON.stringify({ @@ -3651,15 +3696,17 @@ t.test('overrides', t => { }) t.test('overrides a nested dependency with a reference to a direct dependency', async (t) => { - generateNocks(t, { - foo: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - dependencies: ['bar'], - }, - bar: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - }, - }) + const registry = createRegistry(t, false) + const fooPackuments = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + { version: '1.0.1', dependencies: { bar: '1.0.1' } }, + { version: '2.0.0', dependencies: { bar: '2.0.0' } }, + ], 'foo') + const fooManifest = registry.manifest({ name: 'foo', packuments: fooPackuments }) + const barPackuments = registry.packuments(['1.0.0', '1.0.1', '2.0.0'], 'bar') + const barManifest = registry.manifest({ name: 'bar', packuments: barPackuments }) + await registry.package({ manifest: fooManifest }) + await registry.package({ manifest: barManifest }) const path = t.testdir({ 'package.json': JSON.stringify({ @@ -3694,15 +3741,17 @@ t.test('overrides', t => { }) t.test('overrides a nested dependency with a reference to a direct dependency without a top level identifier', async (t) => { - generateNocks(t, { - foo: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - dependencies: ['bar'], - }, - bar: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - }, - }) + const registry = createRegistry(t, false) + const fooPackuments = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + { version: '1.0.1', dependencies: { bar: '1.0.1' } }, + { version: '2.0.0', dependencies: { bar: '2.0.0' } }, + ], 'foo') + const fooManifest = registry.manifest({ name: 'foo', packuments: fooPackuments }) + const barPackuments = registry.packuments(['1.0.0', '1.0.1', '2.0.0'], 'bar') + const barManifest = registry.manifest({ name: 'bar', packuments: barPackuments }) + await registry.package({ manifest: fooManifest }) + await registry.package({ manifest: barManifest }) const path = t.testdir({ 'package.json': JSON.stringify({ @@ -3735,15 +3784,17 @@ t.test('overrides', t => { }) t.test('overrides a peerDependency', async (t) => { - generateNocks(t, { - foo: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - peerDependencies: ['bar'], - }, - bar: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - }, - }) + const registry = createRegistry(t, false) + const fooPackuments = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + { version: '1.0.1', dependencies: { bar: '1.0.1' } }, + { version: '2.0.0', dependencies: { bar: '2.0.0' } }, + ], 'foo') + const fooManifest = registry.manifest({ name: 'foo', packuments: fooPackuments }) + const barPackuments = registry.packuments(['1.0.0', '1.0.1', '2.0.0'], 'bar') + const barManifest = registry.manifest({ name: 'bar', packuments: barPackuments }) + await registry.package({ manifest: fooManifest }) + await registry.package({ manifest: barManifest }) const path = t.testdir({ 'package.json': JSON.stringify({ @@ -3771,15 +3822,17 @@ t.test('overrides', t => { }) t.test('overrides a peerDependency without top level specifier', async (t) => { - generateNocks(t, { - foo: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - peerDependencies: ['bar'], - }, - bar: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - }, - }) + const registry = createRegistry(t, false) + const fooPackuments = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + { version: '1.0.1', dependencies: { bar: '1.0.1' } }, + { version: '2.0.0', dependencies: { bar: '2.0.0' } }, + ], 'foo') + const fooManifest = registry.manifest({ name: 'foo', packuments: fooPackuments }) + const barPackuments = registry.packuments(['1.0.0', '1.0.1', '2.0.0'], 'bar') + const barManifest = registry.manifest({ name: 'bar', packuments: barPackuments }) + await registry.package({ manifest: fooManifest }) + await registry.package({ manifest: barManifest }) // this again with no foo const path = t.testdir({ @@ -3806,20 +3859,28 @@ t.test('overrides', t => { }) t.test('can override inside a cyclical dep chain', async (t) => { - generateNocks(t, { - foo: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - dependencies: ['bar'], - }, - bar: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - dependencies: ['baz'], - }, - baz: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - dependencies: ['foo'], - }, - }) + const registry = createRegistry(t, false) + const fooPackuments = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + { version: '1.0.1', dependencies: { bar: '1.0.1' } }, + { version: '2.0.0', dependencies: { bar: '2.0.0' } }, + ], 'foo') + const fooManifest = registry.manifest({ name: 'foo', packuments: fooPackuments }) + const barPackuments = registry.packuments([ + { version: '1.0.0', dependencies: { baz: '1.0.0' } }, + { version: '1.0.1', dependencies: { baz: '1.0.1' } }, + { version: '2.0.0', dependencies: { baz: '2.0.0' } }, + ], 'bar') + const barManifest = registry.manifest({ name: 'bar', packuments: barPackuments }) + const bazPackuments = registry.packuments([ + { version: '1.0.0', dependencies: { foo: '1.0.0' } }, + { version: '1.0.1', dependencies: { foo: '1.0.1' } }, + { version: '2.0.0', dependencies: { foo: '2.0.0' } }, + ], 'baz') + const bazManifest = registry.manifest({ name: 'baz', packuments: bazPackuments }) + await registry.package({ manifest: fooManifest, times: 2 }) + await registry.package({ manifest: barManifest, times: 2 }) + await registry.package({ manifest: bazManifest, times: 2 }) const path = t.testdir({ 'package.json': JSON.stringify({ @@ -3858,23 +3919,26 @@ t.test('overrides', t => { // this tree creates an ERESOLVE due to a@1 having a peer on b@1 // and d@2 having a peer on b@2, to fix it we override the a@1 peer // to be b@2 - generateNocks(t, { - a: { - versions: ['1.0.0'], - peerDependencies: ['b'], - }, - b: { - versions: ['1.0.0', '2.0.0'], - peerDependencies: [{ '2.0.0': 'c' }], - }, - c: { - versions: ['2.0.0'], - }, - d: { - versions: ['2.0.0'], - peerDependencies: ['b'], - }, - }) + const registry = createRegistry(t, false) + const aPackuments = registry.packuments([ + { version: '1.0.0', peerDependencies: { b: '1.0.0' } }, + ], 'a') + const aManifest = registry.manifest({ name: 'a', packuments: aPackuments }) + const bPackuments = registry.packuments([ + { version: '1.0.0', peerDependencies: { c: '2.0.0' } }, + { version: '2.0.0', peerDependencies: { c: '2.0.0' } }, + ], 'b') + const bManifest = registry.manifest({ name: 'b', packuments: bPackuments }) + const cPackuments = registry.packuments(['2.0.0'], 'c') + const cManifest = registry.manifest({ name: 'c', packuments: cPackuments }) + const dPackuments = registry.packuments([ + { version: '2.0.0', peerDependencies: { b: '2.0.0' } }, + ], 'd') + const dManifest = registry.manifest({ name: 'd', packuments: dPackuments }) + await registry.package({ manifest: aManifest, times: 2 }) + await registry.package({ manifest: bManifest, times: 4 }) + await registry.package({ manifest: cManifest, times: 2 }) + await registry.package({ manifest: dManifest, times: 2 }) const pkg = { name: 'root', @@ -3921,11 +3985,10 @@ t.test('overrides', t => { }) t.test('overrides a workspace dependency', async (t) => { - generateNocks(t, { - bar: { - versions: ['1.0.0', '1.0.1', '2.0.0'], - }, - }) + const registry = createRegistry(t, false) + const packuments = registry.packuments(['1.0.0', '1.0.1', '2.0.0'], 'bar') + const manifest = registry.manifest({ name: 'bar', packuments }) + await registry.package({ manifest }) const path = t.testdir({ 'package.json': JSON.stringify({ @@ -3964,7 +4027,81 @@ t.test('overrides', t => { t.equal(fooBarEdge.to.version, '2.0.0') }) - t.end() + t.test('root overrides should be respected by workspaces on subsequent installs', async t => { + // • The root package.json declares a workspaces field, a direct dependency on "abbrev" with version constraint "^1.1.1", and an overrides field for "abbrev" also "^1.1.1". + // • The workspace "onepackage" depends on "abbrev" at "1.0.3". + const rootPkg = { + name: 'root', + version: '1.0.0', + workspaces: ['onepackage'], + dependencies: { + abbrev: '^1.1.1', + wrappy: '1.0.1', + }, + overrides: { + abbrev: '^1.1.1', + wrappy: '1.0.1', + }, + } + const workspacePkg = { + name: 'onepackage', + version: '1.0.0', + dependencies: { + abbrev: '1.0.3', + wrappy: '1.0.1', + }, + } + + createRegistry(t, true) + + const dir = t.testdir({ + 'package.json': JSON.stringify(rootPkg, null, 2), + onepackage: { + 'package.json': JSON.stringify(workspacePkg, null, 2), + }, + }) + + // fresh install + const tree1 = await buildIdeal(dir) + + // The ideal tree should resolve "abbrev" at the root to 1.1.1. + t.equal( + tree1.children.get('abbrev').package.version, + '1.1.1', + 'first install: root "abbrev" is forced to version 1.1.1' + ) + // The workspace "onepackage" should not have its own nested "abbrev". + const onepackageNode1 = tree1.children.get('onepackage').target + t.notOk( + onepackageNode1.children.has('abbrev'), + 'first install: workspace does not install "abbrev" separately' + ) + + // Write out the package-lock.json to disk to mimic a real install. + await tree1.meta.save() + + // Simulate re-running install (which reads the package-lock). + const tree2 = await buildIdeal(dir) + + // tree2 should NOT have its own abbrev dependency. + const onepackageNode2 = tree2.children.get('onepackage').target + t.notOk( + onepackageNode2.children.has('abbrev'), + 'workspace should NOT have nested "abbrev" after subsequent install' + ) + + // The root "abbrev" should still be 1.1.1. + t.equal( + tree2.children.get('abbrev').package.version, + '1.1.1', + 'second install: root "abbrev" is still forced to version 1.1.1') + + // Workspace targets inherit the root override set via their parent Link node, which is correct behavior needed for proper override propagation through the dependency tree. + t.ok( + onepackageNode2.overrides, + 'workspace target inherits root overrides via link propagation' + ) + }) }) t.test('store files with a custom indenting', async t => { @@ -3976,6 +4113,857 @@ t.test('store files with a custom indenting', async t => { const path = t.testdir({ 'package.json': tabIndentedPackageJson, }) + createRegistry(t, true) const tree = await buildIdeal(path) t.matchSnapshot(String(tree.meta)) }) + +t.test('should take devEngines in account', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'empty-update', + devEngines: { + runtime: { + name: 'node', + }, + }, + }), + }) + createRegistry(t, false) + const tree = await buildIdeal(path) + t.matchSnapshot(String(tree.meta)) +}) + +t.test('engine checking respects omit flags', async t => { + const testFixture = resolve(fixtures, 'engine-omit-test') + + t.test('fail on engine mismatch in devDependencies without omit=dev', async t => { + await t.rejects(buildIdeal(testFixture, { + nodeVersion: '12.18.4', + engineStrict: true, + }), + { code: 'EBADENGINE' }, + 'should fail with EBADENGINE when devDependencies have engine mismatch' + ) + }) + + t.test('skip engine check for devDependencies with omit=dev', async t => { + // This should NOT throw an EBADENGINE error + await buildIdeal(testFixture, { + nodeVersion: '12.18.4', + engineStrict: true, + omit: ['dev'], + }) + t.pass('should succeed when omitting dev dependencies with engine mismatches') + }) + + t.test('skip engine check for optionalDependencies with omit=optional', async t => { + const optionalFixture = resolve(fixtures, 'optional-engine-omit-test') + await buildIdeal(optionalFixture, { + nodeVersion: '12.18.4', + engineStrict: true, + omit: ['optional'], + }) + t.pass('should succeed when omitting optional dependencies with engine mismatches') + }) + + t.test('skip engine check for peerDependencies with omit=peer', async t => { + const peerFixture = resolve(fixtures, 'peer-engine-omit-test') + await buildIdeal(peerFixture, { + nodeVersion: '12.18.4', + engineStrict: true, + omit: ['peer'], + }) + t.pass('should succeed when omitting peer dependencies with engine mismatches') + }) +}) + +t.test('installLinks behavior with project-internal file dependencies', async t => { + t.test('project-internal file dependencies are always symlinked regardless of installLinks', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'test-root', + version: '1.0.0', + dependencies: { + 'local-pkg': 'file:./packages/local-pkg', + }, + }), + packages: { + 'local-pkg': { + 'package.json': JSON.stringify({ + name: 'local-pkg', + version: '1.0.0', + dependencies: { + 'local-shared': 'file:../local-shared', // Project-internal dependency + }, + }), + 'index.js': 'module.exports = "local-pkg"', + }, + 'local-shared': { + 'package.json': JSON.stringify({ + name: 'local-shared', + version: '1.0.0', + }), + 'index.js': 'module.exports = "local-shared"', + }, + }, + }) + + createRegistry(t, false) + + // Test with installLinks=true (this used to fail before our fix) + const arb = newArb(path, { installLinks: true }) + const tree = await arb.buildIdealTree() + + // Both packages should be present in the tree + t.ok(tree.children.has('local-pkg'), 'local-pkg should be in the tree') + t.ok(tree.children.has('local-shared'), 'local-shared should be in the tree') + + // Both should be Links (symlinked) because they are project-internal + const localPkg = tree.children.get('local-pkg') + const localShared = tree.children.get('local-shared') + + t.ok(localPkg.isLink, 'local-pkg should be a link') + t.ok(localShared.isLink, 'local-shared should be a link (hoisted from local-pkg)') + + // Verify the paths are correct + t.ok(localPkg.realpath.endsWith(join('packages', 'local-pkg')), 'local-pkg should link to correct path') + t.ok(localShared.realpath.endsWith(join('packages', 'local-shared')), 'local-shared should link to correct path') + }) + + t.test('external file dependencies respect installLinks setting', async t => { + // Create test structure with both project and external dependency in same testdir + const testRoot = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'test-project', + version: '1.0.0', + dependencies: { + 'external-lib': 'file:../external-lib', // External dependency (outside project) + }, + }), + }, + 'external-lib': { + 'package.json': JSON.stringify({ + name: 'external-lib', + version: '1.0.0', + }), + 'index.js': 'module.exports = "external-lib"', + }, + }) + + const projectPath = join(testRoot, 'project') + createRegistry(t, false) + + // Test with installLinks=true - external dependency should be copied (not linked) + const arbWithLinks = newArb(projectPath, { installLinks: true }) + const treeWithLinks = await arbWithLinks.buildIdealTree() + + t.ok(treeWithLinks.children.has('external-lib'), 'external-lib should be in the tree') + const externalWithLinks = treeWithLinks.children.get('external-lib') + t.notOk(externalWithLinks.isLink, 'external-lib should not be a link when installLinks=true') + + // Test with installLinks=false - external dependency should be linked + const arbNoLinks = newArb(projectPath, { installLinks: false }) + const treeNoLinks = await arbNoLinks.buildIdealTree() + + t.ok(treeNoLinks.children.has('external-lib'), 'external-lib should be in the tree') + const externalNoLinks = treeNoLinks.children.get('external-lib') + t.ok(externalNoLinks.isLink, 'external-lib should be a link when installLinks=false') + }) + + t.test('mixed internal and external file dependencies', async t => { + const testRoot = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'mixed-test', + version: '1.0.0', + dependencies: { + 'internal-pkg': 'file:./lib/internal-pkg', + 'external-dep': 'file:../external-dep', // External dependency + }, + }), + lib: { + 'internal-pkg': { + 'package.json': JSON.stringify({ + name: 'internal-pkg', + version: '1.0.0', + dependencies: { + 'internal-shared': 'file:../internal-shared', // Project-internal + }, + }), + 'index.js': 'module.exports = "internal-pkg"', + }, + 'internal-shared': { + 'package.json': JSON.stringify({ + name: 'internal-shared', + version: '1.0.0', + }), + 'index.js': 'module.exports = "internal-shared"', + }, + }, + }, + 'external-dep': { + 'package.json': JSON.stringify({ + name: 'external-dep', + version: '1.0.0', + }), + 'index.js': 'module.exports = "external-dep"', + }, + }) + + const projectPath = join(testRoot, 'project') + createRegistry(t, false) + + const arb = newArb(projectPath, { installLinks: true }) + const tree = await arb.buildIdealTree() + + // All dependencies should be present + t.ok(tree.children.has('internal-pkg'), 'internal-pkg should be in tree') + t.ok(tree.children.has('internal-shared'), 'internal-shared should be in tree') + t.ok(tree.children.has('external-dep'), 'external-dep should be in tree') + + // Internal dependencies should be links (project-internal rule) + const internalPkg = tree.children.get('internal-pkg') + const internalShared = tree.children.get('internal-shared') + t.ok(internalPkg.isLink, 'internal-pkg should be a link (project-internal)') + t.ok(internalShared.isLink, 'internal-shared should be a link (project-internal)') + + // External dependency should not be a link (respects installLinks=true) + const externalDep = tree.children.get('external-dep') + t.notOk(externalDep.isLink, 'external-dep should not be a link (respects installLinks=true)') + }) + + t.test('code coverage for project-internal file dependency edge cases', async t => { + const testRoot = t.testdir({ + 'parent-dir-external': { + 'package.json': JSON.stringify({ + name: 'parent-dir-external', + version: '1.0.0', + }), + 'index.js': 'module.exports = "parent-dir-external"', + }, + project: { + 'package.json': JSON.stringify({ + name: 'coverage-test', + version: '1.0.0', + dependencies: { + 'current-dir-dep': 'file:./current-dir-dep', // file:./ case + 'parent-dir-external': 'file:../parent-dir-external', // file:../ case outside project + }, + }), + 'current-dir-dep': { + 'package.json': JSON.stringify({ + name: 'current-dir-dep', + version: '1.0.0', + }), + 'index.js': 'module.exports = "current-dir-dep"', + }, + }, + }) + + const projectPath = join(testRoot, 'project') + createRegistry(t, false) + + // Test with installLinks=false to verify external dependencies respect setting + const arb = newArb(projectPath, { installLinks: false }) + const tree = await arb.buildIdealTree() + + t.ok(tree.children.has('current-dir-dep'), 'current-dir-dep should be in tree') + t.ok(tree.children.has('parent-dir-external'), 'parent-dir-external should be in tree') + + const currentDirDep = tree.children.get('current-dir-dep') + const parentDirExternal = tree.children.get('parent-dir-external') + + // current-dir-dep should be a link (project-internal always links) + t.ok(currentDirDep.isLink, 'current-dir-dep should be a link (file:./ within project)') + + // parent-dir-external should ALSO be a link (external, but installLinks=false means link everything) + t.ok(parentDirExternal.isLink, 'parent-dir-external should be a link (file:../ outside project, installLinks=false means link)') + + // Verify the logic branches - current-dir should resolve within project, parent-dir should not + t.match(currentDirDep.realpath, new RegExp(join(testRoot, 'project').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), + 'current-dir-dep realpath should be within project root') + }) + + t.test('installLinks=true with nested project-internal file dependencies', async t => { + // Test a more complex scenario with nested dependencies to ensure comprehensive coverage + const testRoot = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'nested-test', + version: '1.0.0', + dependencies: { + 'wrapper-pkg': 'file:./packages/wrapper-pkg', + }, + }), + packages: { + 'wrapper-pkg': { + 'package.json': JSON.stringify({ + name: 'wrapper-pkg', + version: '1.0.0', + dependencies: { + 'nested-dep': 'file:../nested-dep', + }, + }), + }, + 'nested-dep': { + 'package.json': JSON.stringify({ + name: 'nested-dep', + version: '1.0.0', + }), + }, + }, + }, + }) + + const projectPath = join(testRoot, 'project') + createRegistry(t, false) + + const arb = newArb(projectPath, { installLinks: true }) + const tree = await arb.buildIdealTree() + + const wrapperPkg = tree.children.get('wrapper-pkg') + const nestedDep = tree.children.get('nested-dep') + + t.ok(wrapperPkg, 'wrapper-pkg should be found') + t.ok(wrapperPkg.isLink, 'wrapper-pkg should be a link (project-internal)') + t.ok(nestedDep, 'nested-dep should be found') + t.ok(nestedDep.isLink, 'nested-dep should be a link (project-internal)') + }) + + t.test('installLinks=true with transitive external file dependencies', async t => { + // mainpkg installs b (external file dep) with --install-links + // b depends on a (another external file dep via file:../a) + // Both should be installed (not linked) and dependencies should resolve correctly + const testRoot = t.testdir({ + a: { + 'package.json': JSON.stringify({ + name: 'a', + main: 'index.js', + }), + 'index.js': 'export const A = "A";', + }, + b: { + 'package.json': JSON.stringify({ + name: 'b', + main: 'index.js', + dependencies: { + a: 'file:../a', + }, + }), + 'index.js': 'import {A} from "a";export const fn = () => console.log(A);', + }, + mainpkg: { + 'package.json': JSON.stringify({}), + }, + }) + + const mainpkgPath = join(testRoot, 'mainpkg') + const bPath = join(testRoot, 'b') + createRegistry(t, false) + + const arb = newArb(mainpkgPath, { installLinks: true }) + + // Add the external file dependency using the full path + await arb.buildIdealTree({ add: [`file:${bPath}`] }) + + const tree = arb.idealTree + + // Both packages should be present in the tree + const packageB = tree.children.get('b') + const packageA = tree.children.get('a') + + t.ok(packageB, 'package b should be found in tree') + t.ok(packageA, 'package a should be found in tree (transitive dependency)') + + // Both should be installed (not linked) due to installLinks=true + t.notOk(packageB.isLink, 'package b should not be a link (installLinks=true)') + t.notOk(packageA.isLink, 'package a should not be a link (transitive with installLinks=true)') + + // Verify that the resolved paths are correct + t.match(packageB.resolved, /file:.*[/\\]b$/, 'package b should have correct resolved path') + t.match(packageA.resolved, /file:.*[/\\]a$/, 'package a should have correct resolved path') + + // Verify the dependency relationship + const edgeToA = packageB.edgesOut.get('a') + t.ok(edgeToA, 'package b should have an edge to a') + t.ok(edgeToA.valid, 'the edge from b to a should be valid') + t.equal(edgeToA.to, packageA, 'the edge from b should point to package a') + }) +}) + +t.test('re-queue already-seen nodes when placed dep invalidates peerOptional (save=true, #8726)', async t => { + // Scenario: alpha has peerOptional on shared@1.0.0, beta has dep on shared@^1.0.0. + // With save=true, alpha is processed first (alphabetical order in DepsQueue), + // its peerOptional is not a problem (missing is OK for peerOptional). + // Beta is processed next, placing shared@1.1.0 (latest ^1.0.0). + // This invalidates alpha's peerOptional edge, triggering re-queue of alpha. + const registry = createRegistry(t, false) + + const alphaPack = registry.packument({ + name: 'alpha', + version: '1.0.0', + peerDependencies: { shared: '1.0.0' }, + peerDependenciesMeta: { shared: { optional: true } }, + }) + const alphaManifest = registry.manifest({ name: 'alpha', packuments: [alphaPack] }) + await registry.package({ manifest: alphaManifest }) + + const betaPack = registry.packument({ + name: 'beta', + version: '1.0.0', + dependencies: { shared: '^1.0.0' }, + }) + const betaManifest = registry.manifest({ name: 'beta', packuments: [betaPack] }) + await registry.package({ manifest: betaManifest }) + + const sharedPacks = registry.packuments(['1.0.0', '1.1.0'], 'shared') + const sharedManifest = registry.manifest({ name: 'shared', packuments: sharedPacks }) + await registry.package({ manifest: sharedManifest, times: 2 }) + + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'test-8726-install', + version: '1.0.0', + dependencies: { + alpha: '1.0.0', + beta: '1.0.0', + }, + }), + }) + + const arb = newArb(path, { save: true }) + const tree = await arb.buildIdealTree() + + t.ok(tree.children.get('alpha'), 'alpha is in the tree') + t.ok(tree.children.get('beta'), 'beta is in the tree') + t.ok(tree.children.get('shared'), 'shared is in the tree') +}) + +t.test('skip invalid peerOptional edges in problemEdges when save=false (#8726)', async t => { + // With save=false (npm ci behavior), invalid peerOptional edges should NOT be treated as problems. + // We use update.names to force alpha into #problemEdges while shared@1.1.0 (invalid for alpha's peerOptional spec of 1.0.0) is already in the tree from the lockfile. + const registry = createRegistry(t, false) + + const utilPacks = registry.packuments(['1.0.0', '1.0.1'], 'util') + const utilManifest = registry.manifest({ name: 'util', packuments: utilPacks }) + await registry.package({ manifest: utilManifest }) + + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'test-8726-ci', + version: '1.0.0', + dependencies: { + alpha: '1.0.0', + beta: '1.0.0', + }, + }), + 'package-lock.json': JSON.stringify({ + name: 'test-8726-ci', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { + name: 'test-8726-ci', + version: '1.0.0', + dependencies: { alpha: '1.0.0', beta: '1.0.0' }, + }, + 'node_modules/alpha': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/alpha/-/alpha-1.0.0.tgz', + dependencies: { util: '^1.0.0' }, + peerDependencies: { shared: '1.0.0' }, + peerDependenciesMeta: { shared: { optional: true } }, + }, + 'node_modules/beta': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/beta/-/beta-1.0.0.tgz', + dependencies: { shared: '^1.0.0' }, + }, + 'node_modules/shared': { + version: '1.1.0', + resolved: 'https://registry.npmjs.org/shared/-/shared-1.1.0.tgz', + }, + 'node_modules/util': { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/util/-/util-1.0.0.tgz', + }, + }, + }), + }) + + const arb = newArb(path, { save: false }) + const tree = await arb.buildIdealTree({ update: { names: ['util'] } }) + + t.ok(tree.children.get('alpha'), 'alpha is in the tree') + t.ok(tree.children.get('beta'), 'beta is in the tree') + t.equal(tree.children.get('shared').version, '1.1.0', + 'shared stays at 1.1.0 - peerOptional mismatch is not treated as a problem') + t.ok(tree.children.get('util'), 'util is in the tree') +}) + +t.test('peerOptional prefers existing tree node over registry fetch (#9249)', async t => { + // Reproduction: ts-jest has peerOptional jest-util@"^29||^30". + // @types/jest@28 → expect@28 → jest-util@28 placed at root first. + // jest@29 → jest-util@29 nested (root slot taken by @28). + // ts-jest re-queued, peerOptional jest-util resolves to root @28 → INVALID. + // Without fix: #nodeFromEdge fetches jest-util@30 (latest ^29||^30), blocks @29. + // With fix: #findHoistableNode finds nested @29, PlaceDep hoists it to root. + const registry = createRegistry(t, false) + + const jestPack = registry.packument({ + name: 'jest', + version: '29.0.0', + dependencies: { 'jest-util': '^29.0.0' }, + }) + const jestManifest = registry.manifest({ name: 'jest', packuments: [jestPack] }) + await registry.package({ manifest: jestManifest }) + + const tsJestPack = registry.packument({ + name: 'ts-jest', + version: '29.0.0', + peerDependencies: { jest: '^29.0.0', 'jest-util': '^29.0.0 || ^30.0.0' }, + peerDependenciesMeta: { 'jest-util': { optional: true } }, + }) + const tsJestManifest = registry.manifest({ name: 'ts-jest', packuments: [tsJestPack] }) + await registry.package({ manifest: tsJestManifest }) + + const expectPack = registry.packument({ + name: 'expect', + version: '28.0.0', + dependencies: { 'jest-util': '^28.0.0' }, + }) + const expectManifest = registry.manifest({ name: 'expect', packuments: [expectPack] }) + await registry.package({ manifest: expectManifest }) + + const atTypesPack = registry.packument({ + name: '@types/jest', + version: '28.0.0', + dependencies: { expect: '^28.0.0' }, + }) + const atTypesManifest = registry.manifest({ name: '@types/jest', packuments: [atTypesPack] }) + await registry.package({ manifest: atTypesManifest }) + + // Only publish 28, 29, and 30. + const jestUtilPacks = registry.packuments(['28.0.0', '29.0.0', '30.0.0'], 'jest-util') + const jestUtilManifest = registry.manifest({ name: 'jest-util', packuments: jestUtilPacks }) + await registry.package({ manifest: jestUtilManifest, times: 3 }) + + const path = t.testdir({ + 'package.json': JSON.stringify({ + dependencies: { + jest: '^29.0.0', + 'ts-jest': '^29.0.0', + '@types/jest': '^28.0.0', + }, + }), + }) + + const arb = newArb(path) + const tree = await arb.buildIdealTree() + + // jest-util@29 at root — found via #findHoistableNode, not fetched as @30 + t.equal(tree.children.get('jest-util').version, '29.0.0', + 'jest-util@29 hoisted to root from nested location') + + // ts-jest's peerOptional resolved to @29 from the tree, not @30 from registry + const tsJest = tree.children.get('ts-jest') + const peerOptEdge = tsJest.edgesOut.get('jest-util') + t.equal(peerOptEdge.to.version, '29.0.0', + 'ts-jest peerOptional jest-util resolved to @29') + + // jest-util@28 nested under expect (incompatible with root @29) + const expectNode = [...tree.inventory.query('name', 'expect')][0] + t.equal(expectNode?.children?.get('jest-util')?.version, '28.0.0', + 'jest-util@28 nested under expect') +}) + +t.test('peerOptional skips dedupe shortcut when update.names includes the dep', async t => { + // Same scenario as above, but with update: { names: ['jest-util'] }. + // skipExistingShortcut=true so #findHoistableNode is NOT called; + // #nodeFromEdge fetches from registry, getting jest-util@30 (latest matching ^29||^30). + const registry = createRegistry(t, false) + + const jestPack = registry.packument({ + name: 'jest', + version: '29.0.0', + dependencies: { 'jest-util': '^29.0.0' }, + }) + await registry.package({ manifest: registry.manifest({ name: 'jest', packuments: [jestPack] }) }) + + const tsJestPack = registry.packument({ + name: 'ts-jest', + version: '29.0.0', + peerDependencies: { jest: '^29.0.0', 'jest-util': '^29.0.0 || ^30.0.0' }, + peerDependenciesMeta: { 'jest-util': { optional: true } }, + }) + await registry.package({ manifest: registry.manifest({ name: 'ts-jest', packuments: [tsJestPack] }) }) + + const expectPack = registry.packument({ + name: 'expect', + version: '28.0.0', + dependencies: { 'jest-util': '^28.0.0' }, + }) + await registry.package({ manifest: registry.manifest({ name: 'expect', packuments: [expectPack] }) }) + + const atTypesPack = registry.packument({ + name: '@types/jest', + version: '28.0.0', + dependencies: { expect: '^28.0.0' }, + }) + await registry.package({ manifest: registry.manifest({ name: '@types/jest', packuments: [atTypesPack] }) }) + + const jestUtilPacks = registry.packuments(['28.0.0', '29.0.0', '30.0.0'], 'jest-util') + await registry.package({ manifest: registry.manifest({ name: 'jest-util', packuments: jestUtilPacks }), times: 3 }) + + const path = t.testdir({ + 'package.json': JSON.stringify({ + dependencies: { + jest: '^29.0.0', + 'ts-jest': '^29.0.0', + '@types/jest': '^28.0.0', + }, + }), + }) + + const arb = newArb(path) + const tree = await arb.buildIdealTree({ update: { names: ['jest-util'] } }) + + // With skipExistingShortcut=true, #nodeFromEdge fetches from registry + // so jest-util@30 (latest matching ^29||^30) is used instead of deduping @29 + const tsJest = tree.children.get('ts-jest') + const peerOptEdge = tsJest.edgesOut.get('jest-util') + t.equal(peerOptEdge.to?.version, '30.0.0', 'peerOptional jest-util refetched to @30, not deduped to @29') +}) + +t.test('overrides with bundledDependencies', async t => { + t.test('does not infinite loop with bundledDependencies and overrides', async t => { + // https://github.com/npm/cli/issues/9227 + const registry = createRegistry(t, false) + + const bPacks = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + ], 'b') + const cPacks = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + ], 'c') + const barPacks = registry.packuments(['1.0.0', '2.0.0'], 'bar') + await registry.package({ manifest: registry.manifest({ name: 'b', packuments: bPacks }) }) + await registry.package({ manifest: registry.manifest({ name: 'c', packuments: cPacks }) }) + await registry.package({ manifest: registry.manifest({ name: 'bar', packuments: barPacks }), times: 2 }) + + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + dependencies: { b: '1.0.0', c: '1.0.0' }, + bundledDependencies: true, + overrides: { bar: '2.0.0' }, + }), + }) + + const tree = await buildIdeal(path) + t.equal(tree.children.get('bar').version, '2.0.0', 'override applied') + }) + + t.test('overrides apply to deps the root will bundle and edges are valid', async t => { + const registry = createRegistry(t, false) + + const fooPacks = registry.packuments([ + { version: '1.0.0', dependencies: { bar: '1.0.0' } }, + ], 'foo') + const barPacks = registry.packuments(['1.0.0', '2.0.0'], 'bar') + await registry.package({ manifest: registry.manifest({ name: 'foo', packuments: fooPacks }) }) + await registry.package({ manifest: registry.manifest({ name: 'bar', packuments: barPacks }) }) + + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + dependencies: { foo: '1.0.0' }, + bundledDependencies: ['foo'], + overrides: { bar: '2.0.0' }, + }), + }) + + const tree = await buildIdeal(path) + t.equal(tree.children.get('bar').version, '2.0.0', 'override installed correct version') + + const fooBarEdge = tree.edgesOut.get('foo').to.edgesOut.get('bar') + t.equal(fooBarEdge.valid, true, 'overridden edge is valid') + }) + + t.test('overrides do not apply inside a dependency that bundles', async t => { + const registry = createRegistry(t, false) + + const depPacks = registry.packuments([{ + version: '1.0.0', + dependencies: { bar: '1.0.0' }, + bundleDependencies: ['bar'], + }], 'dep') + await registry.package({ manifest: registry.manifest({ name: 'dep', packuments: depPacks }) }) + + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + dependencies: { dep: '1.0.0' }, + overrides: { bar: '2.0.0' }, + }), + }) + + const tree = await buildIdeal(path) + t.equal(tree.edgesOut.get('dep').valid, true, 'dep edge is valid') + t.notOk(tree.children.get('bar'), 'bar stays inside dep bundle') + }) +}) + +t.test('allow-directory=root permits a top-level directory dependency', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root-pkg', + version: '1.0.0', + dependencies: { 'dir-dep': 'file:./dir-dep' }, + }), + 'dir-dep': { + 'package.json': JSON.stringify({ name: 'dir-dep', version: '1.0.0' }), + }, + }) + const tree = await buildIdeal(path, { allowDirectory: 'root' }) + t.ok(tree.children.get('dir-dep'), 'dir-dep is in the ideal tree') + t.equal(tree.children.get('dir-dep').isLink, true, 'dir-dep is a Link node') +}) + +t.test('allow-directory=none blocks a top-level directory dependency before the symlink branch', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root-pkg', + version: '1.0.0', + dependencies: { 'dir-dep': 'file:./dir-dep' }, + }), + 'dir-dep': { + 'package.json': JSON.stringify({ name: 'dir-dep', version: '1.0.0' }), + }, + }) + await t.rejects( + buildIdeal(path, { allowDirectory: 'none' }), + { code: 'EALLOWDIRECTORY' }, + 'arborist refuses before reaching pacote or the Link branch' + ) +}) + +t.test('allow-directory=root blocks a transitive directory dependency', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root-pkg', + version: '1.0.0', + dependencies: { parent: 'file:./parent' }, + }), + parent: { + 'package.json': JSON.stringify({ + name: 'parent', + version: '1.0.0', + dependencies: { child: 'file:./child' }, + }), + child: { + 'package.json': JSON.stringify({ name: 'child', version: '1.0.0' }), + }, + }, + }) + await t.rejects( + buildIdeal(path, { allowDirectory: 'root' }), + { code: 'EALLOWDIRECTORY' }, + 'transitive directory dep is refused because edge.from is not the project root' + ) +}) + +t.test('allow-directory=root soft-skips a transitive optional directory dependency', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root-pkg', + version: '1.0.0', + dependencies: { parent: 'file:./parent' }, + }), + parent: { + 'package.json': JSON.stringify({ + name: 'parent', + version: '1.0.0', + optionalDependencies: { 'opt-child': 'file:./opt-child' }, + }), + 'opt-child': { + 'package.json': JSON.stringify({ name: 'opt-child', version: '1.0.0' }), + }, + }, + }) + const tree = await buildIdeal(path, { allowDirectory: 'root' }) + t.ok(tree.children.get('parent'), 'parent (root-edge) is in the tree') + const optChild = [...tree.inventory.values()].find(n => n.name === 'opt-child') + t.ok(optChild, 'blocked optional transitive is recorded in the tree') + t.equal(optChild.inert, true, 'blocked optional transitive is marked inert (will not be reified)') +}) + +t.test('incomplete manifest from proxy registry prunes optional dep (#9342)', async t => { + // When a proxy/upstream registry returns an + // incomplete manifest for a platform-specific optional dep it hasn't + // cached, the version field is missing. Our fix in #nodeFromSpec + // treats this as EINCOMPLETEMANIFEST load failure so that + // #pruneFailedOptional() marks it inert instead of writing a broken + // lockfile entry like {"optional": true}. + const registry = createRegistry(t, false) + + // parent package with an optional dep + const esbuildPack = registry.packument({ + name: 'esbuild', + version: '0.27.7', + optionalDependencies: { + '@esbuild/aix-ppc64': '0.27.7', + }, + }) + const esbuildManifest = registry.manifest({ name: 'esbuild', packuments: [esbuildPack] }) + await registry.package({ manifest: esbuildManifest }) + + // simulate proxy registry returning incomplete manifest (no version field) + await registry.package({ + manifest: { + _id: '@esbuild/aix-ppc64', + _rev: '00-incomplete', + name: '@esbuild/aix-ppc64', + description: 'incomplete proxy manifest', + 'dist-tags': { latest: '0.27.7' }, + versions: { + '0.27.7': { + _id: '@esbuild/aix-ppc64@0.27.7', + name: '@esbuild/aix-ppc64', + // NO version field — this is the proxy registry bug + dependencies: {}, + dist: { + tarball: 'https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz', + }, + }, + }, + }, + }) + + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'test-incomplete-manifest', + version: '1.0.0', + devDependencies: { esbuild: '^0.27.0' }, + }), + }) + + const arb = newArb(path) + const tree = await arb.buildIdealTree() + + // esbuild itself should be in the tree + t.ok(tree.children.get('esbuild'), 'esbuild is installed') + t.equal(tree.children.get('esbuild').version, '0.27.7', 'esbuild has correct version') + + // @esbuild/aix-ppc64 should be marked inert (EINCOMPLETEMANIFEST → loadFailure) + // pruneFailedOptional marks it inert so it won't be written to lockfile + const aixNodes = [...tree.inventory.query('name', '@esbuild/aix-ppc64')] + const aixNode = aixNodes.find(n => n.root === tree) + t.ok(aixNode, 'incomplete optional dep node exists in tree') + t.equal(aixNode.inert, true, 'incomplete optional dep is marked inert') + t.equal(aixNode.errors[0].code, 'EINCOMPLETEMANIFEST', + 'node has EINCOMPLETEMANIFEST error') +}) diff --git a/workspaces/arborist/test/arborist/deduper.js b/workspaces/arborist/test/arborist/deduper.js index 92d86318fc316..b4e6076293477 100644 --- a/workspaces/arborist/test/arborist/deduper.js +++ b/workspaces/arborist/test/arborist/deduper.js @@ -1,9 +1,7 @@ const t = require('tap') -const Arborist = require('../../lib/arborist/index.js') - -const { start, stop, registry } = require('../fixtures/server.js') -t.before(start) -t.teardown(stop) +const { join } = require('node:path') +const Arborist = require('../..') +const MockRegistry = require('@npmcli/mock-registry') const { normalizePath, @@ -12,15 +10,25 @@ const { const cwd = normalizePath(process.cwd()) t.cleanSnapshot = s => s.split(cwd).join('{CWD}') - .split(registry).join('https://registry.npmjs.org/') const fixture = (t, p) => require('../fixtures/reify-cases/' + p)(t) - const cache = t.testdir() const dedupeTree = (path, opt) => - new Arborist({ registry, path, cache, save: false, ...(opt || {}) }).dedupe(opt) + new Arborist({ path, cache, save: false, ...(opt || {}) }).dedupe(opt) + +const createRegistry = t => { + const registry = new MockRegistry({ + strict: true, + tap: t, + registry: 'https://registry.npmjs.org', + }) + registry.mocks({ dir: join(__dirname, '..', 'fixtures') }) + return registry +} t.test('dedupes with actual tree', async t => { + const registry = createRegistry(t) + registry.audit({}) const path = fixture(t, 'dedupe-actual') const tree = await dedupeTree(path) const dep = tree.children.get('@isaacs/dedupe-tests-a') @@ -31,6 +39,8 @@ t.test('dedupes with actual tree', async t => { }) t.test('dedupes with lockfile', async t => { + const registry = createRegistry(t) + registry.audit({}) const path = fixture(t, 'dedupe-lockfile') const tree = await dedupeTree(path) const dep = tree.children.get('@isaacs/dedupe-tests-a') diff --git a/workspaces/arborist/test/arborist/index.js b/workspaces/arborist/test/arborist/index.js index eb4b2c760d80b..81bbd42ed7c1e 100644 --- a/workspaces/arborist/test/arborist/index.js +++ b/workspaces/arborist/test/arborist/index.js @@ -253,3 +253,74 @@ t.test('valid global/installStrategy values', t => { t.equal(new Arborist({ installStrategy: 'hoisted' }).options.installStrategy, 'hoisted') t.end() }) + +t.test('lockfileString', async t => { + const fs = require('node:fs') + const { resolve } = require('node:path') + + t.test('returns the lockfile contents as a string without writing to disk', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'lockfile-string-test', + version: '1.0.0', + }), + }) + + const arb = new Arborist({ path }) + const str = await arb.lockfileString() + + t.type(str, 'string', 'returns a string') + const parsed = JSON.parse(str) + t.equal(parsed.name, 'lockfile-string-test') + t.ok(parsed.lockfileVersion, 'has a lockfileVersion') + t.ok(parsed.packages, 'has a packages map') + t.equal( + fs.existsSync(resolve(path, 'package-lock.json')), + false, + 'no package-lock.json was written to disk' + ) + }) + + t.test('reuses an already-built ideal tree', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'lockfile-string-reuse', + version: '1.0.0', + }), + }) + + const arb = new Arborist({ path }) + const tree = await arb.buildIdealTree() + const str = await arb.lockfileString() + + t.equal(arb.idealTree, tree, 'did not rebuild the tree') + t.equal(JSON.parse(str).name, 'lockfile-string-reuse') + }) + + t.test('respects lockfileVersion option', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'lockfile-string-version', + version: '1.0.0', + }), + }) + + const arb = new Arborist({ path, lockfileVersion: 2 }) + const str = await arb.lockfileString() + + t.equal(JSON.parse(str).lockfileVersion, 2) + }) + + t.test('does not modify an existing lockfile on disk', async t => { + const fixture = resolve(__dirname, '../fixtures/workspaces-simple-virtual') + const before = fs.readFileSync(resolve(fixture, 'package-lock.json'), 'utf8') + + const arb = new Arborist({ path: fixture }) + const str = await arb.lockfileString() + + const after = fs.readFileSync(resolve(fixture, 'package-lock.json'), 'utf8') + t.equal(after, before, 'fixture lockfile is unchanged') + t.type(str, 'string') + t.equal(JSON.parse(str).name, 'workspace-simple') + }) +}) diff --git a/workspaces/arborist/test/arborist/load-actual-ctor-throw.js b/workspaces/arborist/test/arborist/load-actual-ctor-throw.js deleted file mode 100644 index 82569f1311cfa..0000000000000 --- a/workspaces/arborist/test/arborist/load-actual-ctor-throw.js +++ /dev/null @@ -1,22 +0,0 @@ -const rpj = require('read-package-json-fast') -const t = require('tap') -const rpjMock = Object.assign((...args) => rpj(...args), { - ...rpj, - normalize: () => { - throw new Error('boom') - }, -}) -const Arborist = t.mock('../../lib/arborist', { - 'read-package-json-fast': rpjMock, -}) - -const { resolve } = require('node:path') -const { fixtures } = require('../fixtures/index.js') - -t.test('blow up and catch error if Node ctor blows up', t => { - // mock rpj so that we can blow up on the 'normalize' method called - // in the Node constructor, because it's (by design) extremely hard - // to make the ctor throw. - const path = resolve(fixtures, 'root') - return t.rejects(new Arborist({ path }).loadActual(), { message: 'boom' }) -}) diff --git a/workspaces/arborist/test/arborist/load-actual.js b/workspaces/arborist/test/arborist/load-actual.js index 11f2a8cf15ace..290107eb4f3d9 100644 --- a/workspaces/arborist/test/arborist/load-actual.js +++ b/workspaces/arborist/test/arborist/load-actual.js @@ -162,14 +162,6 @@ t.test('cwd is default root', t => { t.matchSnapshot(tree, 'loaded tree')) }) -t.test('shake out Link target timing issue', t => { - process.env._TEST_ARBORIST_SLOW_LINK_TARGET_ = '1' - t.teardown(() => process.env._TEST_ARBORIST_SLOW_LINK_TARGET_ = '') - const dir = resolve(fixtures, 'selflink') - return loadActual(dir).then(tree => - t.matchSnapshot(tree, 'loaded tree')) -}) - t.test('broken json', async t => { const d = await loadActual(resolve(fixtures, 'bad')) t.ok(d.errors.length, 'Got an error object') @@ -311,7 +303,7 @@ t.test('transplant workspace targets, even if links not present', async t => { }), 'do not transplant node named "a"') }) -t.test('load workspaces when loading from hidding lockfile', async t => { +t.test('load workspaces when loading from hidden lockfile', async t => { const path = t.testdir({ 'package.json': JSON.stringify({ workspaces: ['packages/*'], @@ -460,7 +452,7 @@ t.test('no edge errors for nested deps', async t => { }, }) - // disable treeCheck since it prevents the original issue from occuring + // disable treeCheck since it prevents the original issue from occurring const ArboristNoTreeCheck = t.mock('../../lib/arborist', { '../../lib/tree-check.js': tree => tree, }) @@ -506,3 +498,50 @@ t.test('loading a workspace maintains overrides', async t => { const fooEdge = tree.edgesOut.get('foo') t.equal(tree.overrides, fooEdge.overrides, 'foo edge got the correct overrides') }) + +t.test('applies root packageExtensions to a linked actual tree', async t => { + // packageExtensions never rewrite a package's package.json, so the extension edge lives only in lockfile metadata. + // The linked store layout forces loadActual onto the filesystem-scan path, where the edge must be re-derived from the root rule set. + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { broken: '1.0.0', safe: '1.0.0' }, + packageExtensions: { 'broken@1': { dependencies: { missing: '^1.0.0' } } }, + }), + node_modules: { + broken: t.fixture('symlink', '.store/broken@1.0.0/node_modules/broken'), + // safe matches no selector, exercising the non-extended path + safe: t.fixture('symlink', '.store/safe@1.0.0/node_modules/safe'), + '.store': { + 'broken@1.0.0': { + node_modules: { + // physical manifest deliberately omits the extension-added dependency + broken: { 'package.json': JSON.stringify({ name: 'broken', version: '1.0.0' }) }, + missing: t.fixture('symlink', '../../missing@1.0.0/node_modules/missing'), + }, + }, + 'missing@1.0.0': { + node_modules: { + missing: { 'package.json': JSON.stringify({ name: 'missing', version: '1.0.0' }) }, + }, + }, + 'safe@1.0.0': { + node_modules: { + safe: { 'package.json': JSON.stringify({ name: 'safe', version: '1.0.0' }) }, + }, + }, + }, + }, + }) + + const tree = await loadActual(path) + const brokenLink = tree.children.get('broken') + const broken = brokenLink.target + const edge = broken.edgesOut.get('missing') + t.ok(edge && !edge.error, 'extension-added edge is present and resolves') + t.equal(edge.to.name, 'missing', 'edge resolves to the installed package') + const applied = { selector: 'broken@1', dependencies: ['missing'] } + t.strictSame(broken.packageExtensionsApplied, applied, 'provenance recorded on the store node') + t.strictSame(brokenLink.packageExtensionsApplied, applied, 'provenance mirrored onto the link') +}) diff --git a/workspaces/arborist/test/arborist/load-virtual.js b/workspaces/arborist/test/arborist/load-virtual.js index 3b50444c851ae..f26f1b6969628 100644 --- a/workspaces/arborist/test/arborist/load-virtual.js +++ b/workspaces/arborist/test/arborist/load-virtual.js @@ -43,7 +43,7 @@ t.test('load from fixture using filesystem root path', t => { .then(virtualTree => t.equal(virtualTree, root)) }) -t.test('load from root that already has shrinkwrap', t => +t.test('load from root with existing package-lock', t => Shrinkwrap.load({ path: tapAndFlow }).then(meta => { const root = new Node({ path: tapAndFlow, @@ -67,19 +67,21 @@ t.test('load from cwd', t => { t.test('loading without a package-lock fails', t => t.rejects(loadVirtual(badfixture), { - message: 'loadVirtual requires existing shrinkwrap file', + message: 'loadVirtual requires existing package-lock.json file', code: 'ENOLOCK', })) -t.test('load from npm-shrinkwrap.json', t => { +t.test('ignore npm-shrinkwrap.json when loading virtual tree', t => { const lock = require(fixture + '/package-lock.json') const pkg = require(fixture + '/package.json') const path = t.testdir({ 'npm-shrinkwrap.json': JSON.stringify(lock), 'package.json': JSON.stringify(pkg), }) - return loadVirtual(path).then(tree => - t.matchSnapshot(printTree(tree), 'loaded virtual tree from fixture')) + return t.rejects(loadVirtual(path), { + message: 'loadVirtual requires existing package-lock.json file', + code: 'ENOLOCK', + }) }) t.test('load without a root package.json is fine', t => { @@ -204,6 +206,12 @@ t.test('workspaces', t => { ).then(tree => t.matchSnapshot(printTree(tree), 'virtual tree ignoring nested node_modules'))) + t.test('load installed workspace with dependency overrides', t => + loadVirtual( + resolve(__dirname, '../fixtures/workspaces-with-overrides') + ).then(tree => + t.matchSnapshot(printTree(tree), 'virtual tree with overrides'))) + t.end() }) @@ -239,3 +247,44 @@ t.test('do not bundle the entire universe', async t => { 'yaml', ].sort()) }) + +t.test('error when link target is missing', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + workspaces: ['packages/*'], + }), + 'package-lock.json': JSON.stringify({ + name: 'root', + lockfileVersion: 3, + packages: { + '': { + workspaces: ['packages/*'], + }, + // This is the problematic entry - a link with no corresponding target + 'node_modules/@my-scope/my-package': { + resolved: 'packages/some-folder/my-package', + link: true, + }, + // Missing entry for 'packages/some-folder/my-package' + }, + }), + packages: { + 'some-folder': { + 'my-package': { + 'package.json': JSON.stringify({ + name: '@my-scope/my-package', + version: '1.0.0', + }), + }, + }, + }, + }) + + const arb = new Arborist({ path }) + + await t.rejects(arb.loadVirtual(), { + code: 'EMISSINGTARGET', + message: /Missing target in lock file:.*but does not exist/, + }) +}) diff --git a/workspaces/arborist/test/arborist/package-extensions.js b/workspaces/arborist/test/arborist/package-extensions.js new file mode 100644 index 0000000000000..c37455ee6fbdd --- /dev/null +++ b/workspaces/arborist/test/arborist/package-extensions.js @@ -0,0 +1,217 @@ +const { resolve } = require('node:path') +const t = require('tap') +const Arborist = require('../..') +const fixtures = resolve(__dirname, '../fixtures') +require(fixtures) +const MockRegistry = require('@npmcli/mock-registry') + +const createRegistry = (t) => new MockRegistry({ + strict: false, + tap: t, + registry: 'https://registry.npmjs.org', +}) + +const warningTracker = (t) => { + const warnings = [] + const onlog = (...msg) => msg[0] === 'warn' && warnings.push(msg) + process.on('log', onlog) + t.teardown(() => process.removeListener('log', onlog)) + return warnings +} + +const cache = t.testdir() +const newArb = (path, opt = {}) => new Arborist({ timeout: 30 * 60 * 1000, path, cache, ...opt }) +const buildIdeal = (path, opt) => newArb(path, opt).buildIdealTree(opt) + +// foo@1.0.0 imports bar but does not declare it; bar is published separately. +// withBar is false for tests that reject before bar is ever fetched. +const mockFooBar = async (t, { fooDeps, withBar = true } = {}) => { + const registry = createRegistry(t) + const fooManifest = registry.manifest({ + name: 'foo', + packuments: registry.packuments([{ version: '1.0.0', dependencies: fooDeps }], 'foo'), + }) + await registry.package({ manifest: fooManifest }) + if (withBar) { + const barManifest = registry.manifest({ + name: 'bar', + packuments: registry.packuments(['1.0.0', '1.2.3', '2.0.0'], 'bar'), + }) + await registry.package({ manifest: barManifest }) + } +} + +t.test('adds a missing dependency edge', async t => { + await mockFooBar(t) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + dependencies: { foo: '1.0.0' }, + packageExtensions: { 'foo@1': { dependencies: { bar: '^1.0.0' } } }, + }), + }) + const tree = await buildIdeal(path) + const foo = tree.edgesOut.get('foo').to + const barEdge = foo.edgesOut.get('bar') + t.ok(barEdge, 'foo has a bar edge created by the extension') + t.equal(barEdge.valid, true, 'bar edge is valid') + t.equal(barEdge.to.version, '1.2.3', 'resolved to the highest 1.x') + t.strictSame(foo.packageExtensionsApplied, { selector: 'foo@1', dependencies: ['bar'] }, + 'provenance attached to the extended node') + t.strictSame(barEdge.explain().packageExtensions, { selector: 'foo@1', field: 'dependencies' }, + 'edge explanation records the extension provenance') +}) + +t.test('edge explanation omits provenance for non-extension edges', async t => { + // foo declares baz itself; the extension only adds bar + const registry = createRegistry(t) + const fooManifest = registry.manifest({ + name: 'foo', + packuments: registry.packuments([{ version: '1.0.0', dependencies: { baz: '1.0.0' } }], 'foo'), + }) + const barManifest = registry.manifest({ name: 'bar', packuments: registry.packuments(['1.2.3'], 'bar') }) + const bazManifest = registry.manifest({ name: 'baz', packuments: registry.packuments(['1.0.0'], 'baz') }) + await registry.package({ manifest: fooManifest }) + await registry.package({ manifest: barManifest }) + await registry.package({ manifest: bazManifest }) + + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + dependencies: { foo: '1.0.0' }, + packageExtensions: { 'foo@1': { dependencies: { bar: '^1.0.0' } } }, + }), + }) + const tree = await buildIdeal(path) + const foo = tree.edgesOut.get('foo').to + t.ok(foo.edgesOut.get('bar').explain().packageExtensions, 'extension-created edge has provenance') + t.equal(foo.edgesOut.get('baz').explain().packageExtensions, undefined, + 'a self-declared edge from the same node has no provenance') +}) + +t.test('composes with overrides', async t => { + await mockFooBar(t) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + dependencies: { foo: '1.0.0' }, + packageExtensions: { 'foo@1': { dependencies: { bar: '^1.0.0' } } }, + overrides: { bar: '1.0.0' }, + }), + }) + const tree = await buildIdeal(path) + const foo = tree.edgesOut.get('foo').to + t.equal(foo.edgesOut.get('bar').to.version, '1.0.0', 'override forces the extension-created edge') +}) + +t.test('name-only selector matches every version', async t => { + await mockFooBar(t) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + dependencies: { foo: '1.0.0' }, + packageExtensions: { foo: { dependencies: { bar: '^1.0.0' } } }, + }), + }) + const tree = await buildIdeal(path) + t.ok(tree.edgesOut.get('foo').to.edgesOut.get('bar'), 'name-only selector applied') +}) + +t.test('conflicting selectors fail the install', async t => { + await mockFooBar(t, { withBar: false }) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + dependencies: { foo: '1.0.0' }, + packageExtensions: { + foo: { dependencies: { bar: '^1.0.0' } }, + 'foo@1': { dependencies: { bar: '^2.0.0' } }, + }, + }), + }) + await t.rejects(buildIdeal(path), { code: 'EEXTENSIONCONFLICT' }, 'two matching selectors reject') +}) + +t.test('invalid selector is rejected at load', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + packageExtensions: { 'foo@latest': { dependencies: { bar: '^1.0.0' } } }, + }), + }) + await t.rejects(buildIdeal(path), { code: 'EEXTENSIONSELECTOR' }, 'dist-tag selector rejected') +}) + +t.test('rejects replacing an existing dependency', async t => { + await mockFooBar(t, { fooDeps: { bar: '1.0.0' }, withBar: false }) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + dependencies: { foo: '1.0.0' }, + packageExtensions: { 'foo@1': { dependencies: { bar: '^2.0.0' } } }, + }), + }) + await t.rejects(buildIdeal(path), { code: 'EEXTENSIONDUPDEP' }, 'cannot replace existing dependency') +}) + +t.test('does not extend workspace members but warns', async t => { + const warnings = warningTracker(t) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + workspaces: ['packages/*'], + packageExtensions: { ws: { dependencies: { bar: '^1.0.0' } } }, + }), + packages: { + ws: { + 'package.json': JSON.stringify({ + name: 'ws', + version: '1.0.0', + // a non-root workspace declaring packageExtensions is ignored with a warning + packageExtensions: { other: { dependencies: { x: '^1' } } }, + }), + }, + // a second workspace that neither declares packageExtensions nor matches a selector + 'other-ws': { 'package.json': JSON.stringify({ name: 'other-ws', version: '1.0.0' }) }, + }, + }) + createRegistry(t) + const tree = await buildIdeal(path) + const ws = [...tree.inventory.values()].find(n => n.name === 'ws') + t.notOk(ws.edgesOut.get('bar'), 'workspace member is not extended') + // a workspace appears in the inventory as both a Link and its target node, so the warning must be deduped to fire once + t.equal(warnings.filter(w => /workspace package ws/.test(w[2])).length, 1, + 'warns exactly once about the workspace selector match') + t.equal(warnings.filter(w => /in workspace ws is ignored/.test(w[2])).length, 1, + 'warns exactly once about non-root workspace packageExtensions') +}) + +t.test('ignores packageExtensions from an installed dependency', async t => { + const registry = createRegistry(t) + const fooManifest = registry.manifest({ + name: 'foo', + packuments: registry.packuments([{ + version: '1.0.0', + // a published package trying to extend itself must have no effect + packageExtensions: { foo: { dependencies: { bar: '^1.0.0' } } }, + }], 'foo'), + }) + await registry.package({ manifest: fooManifest }) + const path = t.testdir({ + 'package.json': JSON.stringify({ name: 'root', dependencies: { foo: '1.0.0' } }), + }) + const tree = await buildIdeal(path) + t.notOk(tree.edgesOut.get('foo').to.edgesOut.get('bar'), + 'dependency-level packageExtensions is ignored') +}) + +t.test('records the canonical hash on the lockfile meta', async t => { + await mockFooBar(t) + const { canonicalHash } = require('../../lib/package-extensions.js') + const packageExtensions = { 'foo@1': { dependencies: { bar: '^1.0.0' } } } + const path = t.testdir({ + 'package.json': JSON.stringify({ name: 'root', dependencies: { foo: '1.0.0' }, packageExtensions }), + }) + const tree = await buildIdeal(path) + t.equal(tree.meta.packageExtensionsHash, canonicalHash(packageExtensions), 'hash stashed on meta') +}) diff --git a/workspaces/arborist/test/arborist/pruner.js b/workspaces/arborist/test/arborist/pruner.js index 7c4bec0c5e2ed..208acc1d2a05e 100644 --- a/workspaces/arborist/test/arborist/pruner.js +++ b/workspaces/arborist/test/arborist/pruner.js @@ -1,12 +1,9 @@ -const { resolve } = require('node:path') +const { resolve, join } = require('node:path') +const fs = require('node:fs') const t = require('tap') -const Arborist = require('../../lib/arborist/index.js') - -const { start, stop, registry } = require('../fixtures/server.js') - -t.before(start) -t.teardown(stop) +const Arborist = require('../..') +const MockRegistry = require('@npmcli/mock-registry') const { normalizePath, @@ -15,13 +12,15 @@ const { const cwd = normalizePath(process.cwd()) t.cleanSnapshot = s => s.split(cwd).join('{CWD}') - .split(registry).join('https://registry.npmjs.org/') const fixture = (t, p) => require('../fixtures/reify-cases/' + p)(t) +const registry = new MockRegistry({ + strict: true, + tap: t, + registry: 'https://registry.npmjs.org', +}) -const cache = t.testdir() -const pruneTree = (path, opt) => - new Arborist({ registry, path, cache, ...(opt || {}) }).prune(opt) +const pruneTree = (path, opt) => new Arborist({ path, ...(opt || {}) }).prune(opt) t.test('prune with actual tree', async t => { const path = fixture(t, 'prune-actual') @@ -39,6 +38,23 @@ t.test('prune with lockfile', async t => { t.matchSnapshot(printTree(tree)) }) +t.test('prune with lockfile with implicit optional peer dependencies', async t => { + const path = fixture(t, 'prune-lockfile-optional-peer') + const tree = await pruneTree(path, { audit: false }) + + const dep = tree.children.get('dedent') + t.ok(dep, 'required prod dep was not pruned from tree') + + const optionalPeerDep = tree.children.get('babel-plugin-macros') + t.notOk(optionalPeerDep, 'optional peer dep was pruned from tree') + + t.notMatch( + fs.readFileSync(path + '/package-lock.json'), + 'node_modules/babel-plugin-macros', + 'should remove optional peer dep from package-lock.json' + ) +}) + t.test('prune with actual tree omit dev', async t => { const path = fixture(t, 'prune-actual-omit-dev') const tree = await pruneTree(path, { omit: ['dev'] }) @@ -103,7 +119,7 @@ t.test('prune omit dev with bins', async t => { const devDep = tree.children.get('yes') t.notOk(devDep, 'all listed dev deps pruned from tree') - // should also remove ./bin/* files + // should also remove ./bin[> files const bin = resolve(path, 'node_modules/.bin/yes') if (process.platform === 'win32') { t.throws(() => statSync(bin + '.cmd').isFile(), /ENOENT/, 'should not have shim') @@ -113,8 +129,7 @@ t.test('prune omit dev with bins', async t => { }) t.test('prune workspaces', async t => { - const fs = require('node:fs') - const { join } = require('node:path') + registry.audit({}) const path = t.testdir({ 'package.json': JSON.stringify({ name: 'prune-workspaces', diff --git a/workspaces/arborist/test/arborist/rebuild.js b/workspaces/arborist/test/arborist/rebuild.js index b53b7309a4870..ab433f2f97174 100644 --- a/workspaces/arborist/test/arborist/rebuild.js +++ b/workspaces/arborist/test/arborist/rebuild.js @@ -1,30 +1,30 @@ const t = require('tap') const _trashList = Symbol.for('trashList') -const Arborist = require('../../lib/arborist/index.js') +const Arborist = require('../..') const { resolve, dirname } = require('node:path') const os = require('node:os') const fs = require('node:fs') const fixtures = resolve(__dirname, '../fixtures') const relpath = require('../../lib/relpath.js') const localeCompare = require('@isaacs/string-locale-compare')('en') +const MockRegistry = require('@npmcli/mock-registry') const fixture = (t, p) => require(`${fixtures}/reify-cases/${p}`)(t) -const isWindows = process.platform === 'win32' -const PORT = 12345 + (+process.env.TAP_CHILD_ID || 0) - -const server = require('node:http').createServer(() => { - throw new Error('rebuild should not hit the registry') +// Spin up a new mock registry with no mocks in strict mode so we ensure that no requests are made +new MockRegistry({ + strict: true, + tap: t, + registry: 'https://registry.npmjs.org', }) -t.before(() => new Promise(res => { - server.listen(PORT, () => { - t.teardown(() => server.close()) - res() - }) -})) -const registry = `http://localhost:${PORT}` -const newArb = opt => new Arborist({ ...opt, registry }) +const isWindows = process.platform === 'win32' + +// Most rebuild tests pre-date the allowScripts gate and assert that +// install scripts run. Bypass the default-deny in this suite by +// default; individual tests that want to assert the gate's behaviour +// override the option explicitly. +const newArb = opt => new Arborist({ dangerouslyAllowAllScripts: true, ...opt }) // track the logs that are emitted. returns a function that removes // the listener and provides the list of what it saw. @@ -118,6 +118,130 @@ t.test('do not run scripts if ignoreScripts=true', async t => { t.throws(() => fs.statSync(file), 'bundle build script not run') }) +t.test('allowScripts deny entry skips the build set entry for that node', async t => { + // Verifies the deny gate in #addToBuildSet: when `allowScripts` resolves + // a node's policy to `false`, that node's scripts are skipped while + // others continue to run. + const path = fixture(t, 'testing-rebuild-script-env-flags') + const arb = newArb({ + path, + allowScripts: { devdep: false, devopt: true }, + dangerouslyAllowAllScripts: false, + }) + await arb.rebuild() + // devdep is denied — its postinstall must NOT have produced the `env` + // file inside its directory. + t.throws( + () => fs.statSync(resolve(path, 'node_modules/devdep/env')), + 'devdep postinstall did not run' + ) + // devopt is not denied, so its postinstall still runs. + t.equal( + fs.statSync(resolve(path, 'node_modules/devopt/env')).isFile(), + true, + 'devopt postinstall ran' + ) +}) + +t.test('dangerouslyAllowAllScripts bypasses the deny gate', async t => { + // Same setup as above, but the escape hatch must let denied scripts run. + const path = fixture(t, 'testing-rebuild-script-env-flags') + const arb = newArb({ + path, + allowScripts: { devdep: false }, + dangerouslyAllowAllScripts: true, + }) + await arb.rebuild() + t.equal( + fs.statSync(resolve(path, 'node_modules/devdep/env')).isFile(), + true, + 'devdep postinstall ran despite deny entry' + ) +}) + +t.test('allowScripts gates local file: dep scripts (npm/cli#9498)', async t => { + const aPrepare = p => resolve(p, 'a/a-prepare') + const aPostinstall = p => resolve(p, 'a/a-post-install') + + t.test('true: scripts run when the target is allowed', async t => { + const path = fixture(t, 'link-dep-lifecycle-scripts') + const arb = newArb({ + path, + allowScripts: { 'file:../a': true }, + dangerouslyAllowAllScripts: false, + }) + await arb.rebuild() + t.equal(fs.statSync(aPrepare(path)).isFile(), true, 'prepare ran') + t.equal(fs.statSync(aPostinstall(path)).isFile(), true, 'postinstall ran') + }) + + t.test('false: deny entry blocks the scripts', async t => { + const path = fixture(t, 'link-dep-lifecycle-scripts') + const arb = newArb({ + path, + allowScripts: { 'file:../a': false }, + dangerouslyAllowAllScripts: false, + }) + await arb.rebuild() + t.throws(() => fs.statSync(aPrepare(path)), 'prepare did not run') + t.throws(() => fs.statSync(aPostinstall(path)), 'postinstall did not run') + }) + + t.test('absent: default-deny blocks the scripts', async t => { + const path = fixture(t, 'link-dep-lifecycle-scripts') + const arb = newArb({ + path, + allowScripts: {}, + dangerouslyAllowAllScripts: false, + }) + await arb.rebuild() + t.throws(() => fs.statSync(aPrepare(path)), 'prepare did not run') + t.throws(() => fs.statSync(aPostinstall(path)), 'postinstall did not run') + }) + + t.test('dangerouslyAllowAllScripts bypasses the gate for file: deps', async t => { + const path = fixture(t, 'link-dep-lifecycle-scripts') + const arb = newArb({ path, dangerouslyAllowAllScripts: true }) + await arb.rebuild() + t.equal(fs.statSync(aPrepare(path)).isFile(), true, 'prepare ran') + t.equal(fs.statSync(aPostinstall(path)).isFile(), true, 'postinstall ran') + }) +}) + +t.test('workspaces bypass the allowScripts gate (owner-managed)', async t => { + // Workspaces are owner-managed, so their scripts run regardless of the + // allowScripts policy. This must survive the #9498 fix that stopped + // bypassing all link nodes. + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'ws-root', + version: '1.0.0', + workspaces: ['ws'], + }), + node_modules: { + ws: t.fixture('symlink', '../ws'), + }, + ws: { + 'package.json': JSON.stringify({ + name: 'ws', + version: '1.0.0', + scripts: { + prepare: `node -e "require('fs').writeFileSync('ws-prepare', '')"`, + }, + }), + }, + }) + // No allowScripts entry and the escape hatch off: only the isWorkspace + // bypass can let this script through. + const arb = newArb({ path, dangerouslyAllowAllScripts: false }) + await arb.rebuild() + t.equal( + fs.statSync(resolve(path, 'ws/ws-prepare')).isFile(), + true, + 'workspace prepare ran despite no allowScripts entry' + ) +}) + t.test('do nothing if ignoreScripts=true and binLinks=false', async t => { const path = fixture(t, 'testing-rebuild-bundle-reified') const file = resolve(path, 'node_modules/@isaacs/testing-rebuild-bundle-a/node_modules/@isaacs/testing-rebuild-bundle-b/cwd') @@ -153,7 +277,7 @@ t.test('do not run scripts for nodes on trash list', async t => { t.throws(() => fs.statSync(file), 'bundle build script not run') }) -t.test('dont blow up if package.json is borked', async t => { +t.test('do not blow up if package.json is borked', async t => { const path = fixture(t, 'testing-rebuild-bundle-reified') const loc = 'node_modules/@isaacs/testing-rebuild-bundle-a/node_modules/@isaacs/testing-rebuild-bundle-b' const file = resolve(path, loc, 'cwd') @@ -225,7 +349,7 @@ t.test('run scripts in foreground if foregroundScripts set', async t => { }, }) - const arb = new Arborist({ path, registry, foregroundScripts: true }) + const arb = new Arborist({ path, foregroundScripts: true, dangerouslyAllowAllScripts: true }) await arb.rebuild() // add a sentinel to make sure we didn't get too many entries, since // t.match() will allow trailing/extra values in the test object. @@ -247,7 +371,7 @@ t.test('run scripts in foreground if foregroundScripts set', async t => { ]) }) -t.test('log failed exit codes as well, even if we dont crash', async t => { +t.test('log failed exit codes as well, even if we do not crash', async t => { const path = t.testdir({ 'package.json': JSON.stringify({ optionalDependencies: { optdep: '1' }, @@ -414,7 +538,7 @@ t.test('rebuild node-gyp dependencies lacking both preinstall and install script }, }), }) - const arb = new Arborist({ path, registry }) + const arb = new Arborist({ path, dangerouslyAllowAllScripts: true }) await arb.rebuild() t.match(RUNS, [ { @@ -460,7 +584,7 @@ t.test('do not rebuild node-gyp dependencies with gypfile:false', async t => { }, }), }) - const arb = new Arborist({ path, registry }) + const arb = new Arborist({ path, dangerouslyAllowAllScripts: true }) await arb.rebuild() }) @@ -498,7 +622,7 @@ t.test('do not run lifecycle scripts of linked deps twice', async t => { return require('@npmcli/run-script')(opts) }, }) - const arb = new Arborist({ path, registry }) + const arb = new Arborist({ path, dangerouslyAllowAllScripts: true }) await arb.rebuild() t.equal(RUNS.length, 1, 'should run postinstall script only once') t.match(RUNS, [ @@ -544,7 +668,7 @@ t.test('workspaces', async t => { return require('@npmcli/run-script')(opts) }, }) - const arb = new Arborist({ path, registry }) + const arb = new Arborist({ path, dangerouslyAllowAllScripts: true }) await arb.rebuild() t.equal(RUNS.length, 2, 'should run prepare script only once per ws') @@ -593,7 +717,7 @@ t.test('workspaces', async t => { return { code: 0, signal: null } }, }) - const arb = new Arborist({ path, registry, binLinks: false }) + const arb = new Arborist({ path, binLinks: false, dangerouslyAllowAllScripts: true }) await arb.rebuild() t.equal(RUNS.length, 1, 'should run prepare script only once') @@ -641,7 +765,7 @@ t.test('workspaces', async t => { return { code: 0, signal: null } }, }) - const arb = new Arborist({ path, registry }) + const arb = new Arborist({ path, dangerouslyAllowAllScripts: true }) await arb.rebuild() t.equal(RUNS.length, 1, 'should run prepare script only once') @@ -804,8 +928,8 @@ t.test('no workspaces', async t => { }) const arb = new Arborist({ path, - registry, workspacesEnabled: false, + dangerouslyAllowAllScripts: true, }) await arb.rebuild() @@ -817,3 +941,38 @@ t.test('no workspaces', async t => { }, ]) }) + +t.test('do not run lifecycle scripts of linked deps twice', async t => { + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'my-project', + version: '1.0.0', + dependencies: { + foo: 'file:../foo', + }, + }), + node_modules: { + foo: t.fixture('symlink', '../../foo'), + }, + }, + foo: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.0.0', + scripts: { + postinstall: 'echo "ok"', + }, + }), + }, + }) + + const path = resolve(testdir, 'project') + const Arborist = t.mock('../../lib/arborist/index.js', { + '@npmcli/run-script': () => { + throw new Error('should not run any scripts') + }, + }) + const arb = new Arborist({ path, ignoreScripts: true }) + await arb.rebuild() +}) diff --git a/workspaces/arborist/test/arborist/reify-npm-extension.js b/workspaces/arborist/test/arborist/reify-npm-extension.js new file mode 100644 index 0000000000000..851d87c08f379 --- /dev/null +++ b/workspaces/arborist/test/arborist/reify-npm-extension.js @@ -0,0 +1,280 @@ +const { join, resolve } = require('node:path') +const fs = require('node:fs') +const t = require('tap') +const Arborist = require('../..') +const fixtures = resolve(__dirname, '../fixtures') +require(fixtures) +const MockRegistry = require('@npmcli/mock-registry') +const { hashFile } = require('../../lib/npm-extension.js') + +const createRegistry = (t) => new MockRegistry({ + strict: false, + tap: t, + registry: 'https://registry.npmjs.org', +}) + +// foo@1.0.0 does not declare bar; both are served as installable tarballs from source dirs. +const register = async (t, dir, { withBar = true, withBaz = false } = {}) => { + const registry = createRegistry(t) + const fooManifest = registry.manifest({ name: 'foo', packuments: [{ version: '1.0.0' }] }) + await registry.package({ manifest: fooManifest, tarballs: { '1.0.0': join(dir, 'src/foo') } }) + if (withBar) { + const barManifest = registry.manifest({ name: 'bar', packuments: [{ version: '1.2.3' }] }) + await registry.package({ manifest: barManifest, tarballs: { '1.2.3': join(dir, 'src/bar') } }) + } + if (withBaz) { + const bazManifest = registry.manifest({ name: 'baz', packuments: [{ version: '3.0.0' }] }) + await registry.package({ manifest: bazManifest, tarballs: { '3.0.0': join(dir, 'src/baz') } }) + } +} + +// a transformManifest that adds bar to foo +const addBar = `module.exports = { + transformManifest (pkg) { + if (pkg.name === 'foo') { + pkg.dependencies = { ...pkg.dependencies, bar: '^1.0.0' } + } + return pkg + }, +} +` + +const setup = async (t, { extension = addBar, file = '.npm-extension.cjs', dependencies = { foo: '1.0.0' }, overrides, withBar = true } = {}) => { + const dir = t.testdir({ + 'package.json': JSON.stringify({ name: 'root', dependencies, overrides }), + [file]: extension, + src: { + foo: { 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }) }, + bar: { 'package.json': JSON.stringify({ name: 'bar', version: '1.2.3' }) }, + }, + }) + await register(t, dir, { withBar }) + return dir +} + +const newArb = (dir, opt = {}) => new Arborist({ + path: dir, + cache: join(dir, 'cache'), + registry: 'https://registry.npmjs.org', + audit: false, + timeout: 30 * 60 * 1000, + ...opt, +}) + +const readLock = dir => JSON.parse(fs.readFileSync(join(dir, 'package-lock.json'), 'utf8')) + +for (const installStrategy of ['hoisted', 'nested', 'shallow', 'linked']) { + t.test(`installs the transform-created edge under install-strategy=${installStrategy}`, async t => { + const dir = await setup(t) + const tree = await newArb(dir, { installStrategy }).reify() + const foo = [...tree.inventory.values()].find(n => n.name === 'foo' && !n.isLink) + const barEdge = foo.edgesOut.get('bar') + t.ok(barEdge && barEdge.valid && barEdge.to, `bar edge resolved under ${installStrategy}`) + t.equal(barEdge.to.version, '1.2.3', 'bar resolved to a real installed node') + }) +} + +t.test('lockfile records hash, provenance, effective deps, and version 4', async t => { + const dir = await setup(t) + await newArb(dir).reify() + const lock = readLock(dir) + t.equal(lock.lockfileVersion, 4, 'bumped to lockfileVersion 4') + const expectHash = hashFile('cjs', Buffer.from(addBar)) + t.equal(lock.packages[''].npmExtensionHash, expectHash, 'root entry carries the file hash') + const fooEntry = lock.packages['node_modules/foo'] + t.strictSame(fooEntry.npmExtensionApplied, { extensionPoint: 'transformManifest', dependencies: ['bar'] }, + 'foo entry carries minimal provenance') + t.strictSame(fooEntry.dependencies, { bar: '^1.0.0' }, 'foo entry carries the effective dependency metadata') +}) + +t.test('explain annotates the transform-created edge', async t => { + const dir = await setup(t) + const tree = await newArb(dir).reify() + const foo = [...tree.inventory.values()].find(n => n.name === 'foo' && !n.isLink) + const explanation = foo.edgesOut.get('bar').explain() + t.strictSame(explanation.npmExtension, { extensionPoint: 'transformManifest', field: 'dependencies' }, + 'edge explanation carries the transform provenance') +}) + +t.test('explain annotates an edge created in a non-first field', async t => { + // adds bar to optionalDependencies, so the edge explanation loop skips `dependencies` before matching + const dir = await setup(t, { + extension: `module.exports = { + transformManifest (pkg) { + if (pkg.name === 'foo') { + pkg.optionalDependencies = { ...pkg.optionalDependencies, bar: '^1.0.0' } + } + return pkg + }, + } +`, + }) + const tree = await newArb(dir).reify() + const foo = [...tree.inventory.values()].find(n => n.name === 'foo' && !n.isLink) + const explanation = foo.edgesOut.get('bar').explain() + t.strictSame(explanation.npmExtension, { extensionPoint: 'transformManifest', field: 'optionalDependencies' }, + 'edge explanation reports the optionalDependencies field') +}) + +t.test('does not rewrite the installed dependency package.json', async t => { + const dir = await setup(t) + await newArb(dir).reify() + const installed = JSON.parse(fs.readFileSync(join(dir, 'node_modules/foo/package.json'), 'utf8')) + t.notOk(installed.dependencies, 'the on-disk foo/package.json is not given a bar dependency') +}) + +t.test('composes with packageExtensions on the same package', async t => { + // .npm-extension adds bar to foo (runs first); packageExtensions adds baz to foo (runs on the transform output) + const dir = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + dependencies: { foo: '1.0.0' }, + packageExtensions: { 'foo@1': { dependencies: { baz: '^3.0.0' } } }, + }), + '.npm-extension.cjs': addBar, + src: { + foo: { 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }) }, + bar: { 'package.json': JSON.stringify({ name: 'bar', version: '1.2.3' }) }, + baz: { 'package.json': JSON.stringify({ name: 'baz', version: '3.0.0' }) }, + }, + }) + await register(t, dir, { withBaz: true }) + const tree = await newArb(dir).reify() + const foo = [...tree.inventory.values()].find(n => n.name === 'foo' && !n.isLink) + t.ok(foo.edgesOut.get('bar')?.to, 'transform-created bar edge resolved') + t.ok(foo.edgesOut.get('baz')?.to, 'packageExtensions-created baz edge resolved') + t.same(foo.npmExtensionApplied, { extensionPoint: 'transformManifest', dependencies: ['bar'] }, + 'transform provenance recorded') + t.same(foo.packageExtensionsApplied, { selector: 'foo@1', dependencies: ['baz'] }, + 'packageExtensions provenance recorded') +}) + +t.test('composes with overrides during reify', async t => { + const dir = await setup(t, { overrides: { bar: '1.2.3' } }) + const tree = await newArb(dir).reify() + const bar = [...tree.inventory.values()].find(n => n.name === 'bar') + t.equal(bar.version, '1.2.3', 'override applied to the transform-created edge') +}) + +t.test('an .mjs extension is honored', async t => { + const dir = await setup(t, { + file: '.npm-extension.mjs', + extension: `export function transformManifest (pkg) { + if (pkg.name === 'foo') pkg.dependencies = { ...pkg.dependencies, bar: '^1.0.0' } + return pkg + } +`, + }) + const tree = await newArb(dir).reify() + const foo = [...tree.inventory.values()].find(n => n.name === 'foo' && !n.isLink) + t.ok(foo.edgesOut.get('bar')?.to, 'bar edge resolved via .mjs extension') +}) + +t.test('ignore-extension disables the transform and records no state', async t => { + const dir = await setup(t, { withBar: false }) + await newArb(dir, { ignoreExtension: true }).reify() + const lock = readLock(dir) + t.notOk(lock.packages[''].npmExtensionHash, 'no extension hash recorded') + t.notOk(lock.packages['node_modules/bar'], 'bar was never added by the disabled transform') + t.notOk(lock.packages['node_modules/foo'].dependencies, 'foo has no extension-added dependency') +}) + +t.test('warns when a non-root workspace contains a .npm-extension file', async t => { + const warnings = [] + const onlog = (...m) => m[0] === 'warn' && m[1] === 'npm-extension' && warnings.push(m[2]) + process.on('log', onlog) + t.teardown(() => process.removeListener('log', onlog)) + + const dir = t.testdir({ + 'package.json': JSON.stringify({ name: 'root', workspaces: ['packages/*'] }), + packages: { + a: { + 'package.json': JSON.stringify({ name: 'a', version: '1.0.0' }), + '.npm-extension.cjs': 'module.exports = { transformManifest (p) { return p } }\n', + }, + b: { 'package.json': JSON.stringify({ name: 'b', version: '1.0.0' }) }, + }, + }) + await newArb(dir).buildIdealTree() + t.match(warnings.join('\n'), /"\.npm-extension" in workspace a is ignored/, 'warns for the workspace with the file') + t.notMatch(warnings.join('\n'), /workspace b/, 'does not warn for the workspace without one') +}) + +t.test('a project with no .npm-extension installs normally and records no state', async t => { + const dir = t.testdir({ + 'package.json': JSON.stringify({ name: 'root', dependencies: { foo: '1.0.0' } }), + src: { foo: { 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }) } }, + }) + await register(t, dir, { withBar: false }) + await newArb(dir).reify() + const lock = readLock(dir) + t.notOk(lock.packages[''].npmExtensionHash, 'no extension hash recorded') + t.notOk(lock.packages['node_modules/foo'].dependencies, 'foo unchanged') +}) + +t.test('provenance round-trips under install-strategy=linked', async t => { + const dir = await setup(t) + await newArb(dir, { installStrategy: 'linked' }).reify() + // a second linked reify rescans the store and links, re-deriving provenance on both + const tree = await newArb(dir, { installStrategy: 'linked' }).reify() + const foo = [...tree.inventory.values()].find(n => n.name === 'foo') + t.ok(foo.npmExtensionApplied || foo.target?.npmExtensionApplied, 'provenance present on the linked node or its target') +}) + +t.test('loadActual re-derives provenance only for transformed installed deps', async t => { + // a filesystem-scanned tree: foo is the transform target, qux is an unrelated installed dep + const dir = t.testdir({ + 'package.json': JSON.stringify({ name: 'root', dependencies: { foo: '^1.0.0', qux: '^1.0.0' } }), + '.npm-extension.cjs': addBar, + node_modules: { + foo: { 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }) }, + qux: { 'package.json': JSON.stringify({ name: 'qux', version: '1.0.0' }) }, + }, + }) + const actual = await newArb(dir).loadActual() + const foo = [...actual.inventory.values()].find(n => n.name === 'foo' && !n.isLink) + const qux = [...actual.inventory.values()].find(n => n.name === 'qux' && !n.isLink) + t.strictSame(foo.npmExtensionApplied, { extensionPoint: 'transformManifest', dependencies: ['bar'] }, + 'foo carries provenance from the re-derived transform') + t.equal(qux.npmExtensionApplied, null, 'qux, untouched by the transform, carries no provenance') +}) + +t.test('provenance round-trips through the lockfile', async t => { + const dir = await setup(t) + await newArb(dir).reify() + // a second reify loads the lockfile and the on-disk tree; the edge and provenance must survive + const tree = await newArb(dir).reify() + const foo = [...tree.inventory.values()].find(n => n.name === 'foo' && !n.isLink) + t.ok(foo.edgesOut.get('bar')?.to, 'bar edge still present after reinstall') + t.strictSame(foo.npmExtensionApplied, { extensionPoint: 'transformManifest', dependencies: ['bar'] }, + 'provenance preserved across reinstall') +}) + +t.test('changing the extension file re-resolves affected packages', async t => { + const dir = await setup(t) + await newArb(dir).reify() + t.equal(readLock(dir).packages['node_modules/bar']?.version, '1.2.3', 'bar installed initially') + + // rewrite the extension so it no longer adds bar, then reinstall + fs.writeFileSync(join(dir, '.npm-extension.cjs'), `module.exports = { transformManifest (pkg) { return pkg } }\n`) + await register(t, dir, { withBar: false }) + await newArb(dir).reify() + const lock = readLock(dir) + t.notOk(lock.packages['node_modules/bar'], 'bar removed after the extension stopped adding it') + t.notOk(lock.packages['node_modules/foo']?.npmExtensionApplied, 'provenance cleared') +}) + +t.test('removing the extension file reverts the locked graph', async t => { + const dir = await setup(t) + await newArb(dir).reify() + t.ok(readLock(dir).packages['node_modules/bar'], 'bar installed by the extension') + + // delete the extension file entirely, then reinstall; the transform-added edge and state must be reverted + fs.rmSync(join(dir, '.npm-extension.cjs')) + await register(t, dir, { withBar: false }) + await newArb(dir).reify() + const lock = readLock(dir) + t.notOk(lock.packages['node_modules/bar'], 'bar removed once the extension file is gone') + t.notOk(lock.packages[''].npmExtensionHash, 'root hash cleared') + t.notOk(lock.packages['node_modules/foo']?.npmExtensionApplied, 'foo provenance cleared') +}) diff --git a/workspaces/arborist/test/arborist/reify-package-extensions.js b/workspaces/arborist/test/arborist/reify-package-extensions.js new file mode 100644 index 0000000000000..3090d164d5991 --- /dev/null +++ b/workspaces/arborist/test/arborist/reify-package-extensions.js @@ -0,0 +1,177 @@ +const { join, resolve } = require('node:path') +const fs = require('node:fs') +const t = require('tap') +const Arborist = require('../..') +const fixtures = resolve(__dirname, '../fixtures') +require(fixtures) +const MockRegistry = require('@npmcli/mock-registry') +const { canonicalHash } = require('../../lib/package-extensions.js') + +const createRegistry = (t) => new MockRegistry({ + strict: false, + tap: t, + registry: 'https://registry.npmjs.org', +}) + +// Serve foo@1.0.0 and bar@1.2.3 as installable tarballs; bar is optional so a reify that does not need it leaves no unconsumed mock. +const register = async (t, dir, { withBar = true } = {}) => { + const registry = createRegistry(t) + const fooManifest = registry.manifest({ name: 'foo', packuments: [{ version: '1.0.0' }] }) + await registry.package({ manifest: fooManifest, tarballs: { '1.0.0': join(dir, 'src/foo') } }) + if (withBar) { + const barManifest = registry.manifest({ name: 'bar', packuments: [{ version: '1.2.3' }] }) + await registry.package({ manifest: barManifest, tarballs: { '1.2.3': join(dir, 'src/bar') } }) + } +} + +// foo@1.0.0 does not declare bar; both are served as installable tarballs from source dirs. +const setup = async (t, { packageExtensions, dependencies = { foo: '1.0.0' }, overrides }) => { + const dir = t.testdir({ + 'package.json': JSON.stringify({ name: 'root', dependencies, packageExtensions, overrides }), + src: { + foo: { 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }) }, + bar: { 'package.json': JSON.stringify({ name: 'bar', version: '1.2.3' }) }, + }, + }) + await register(t, dir) + return dir +} + +const newArb = (dir, opt = {}) => new Arborist({ + path: dir, + cache: join(dir, 'cache'), + registry: 'https://registry.npmjs.org', + audit: false, + timeout: 30 * 60 * 1000, + ...opt, +}) + +const readLock = dir => JSON.parse(fs.readFileSync(join(dir, 'package-lock.json'), 'utf8')) + +const ext = { 'foo@1': { dependencies: { bar: '^1.0.0' } } } + +for (const installStrategy of ['hoisted', 'nested', 'shallow', 'linked']) { + t.test(`installs the extension-created edge under install-strategy=${installStrategy}`, async t => { + const dir = await setup(t, { packageExtensions: ext }) + const tree = await newArb(dir, { installStrategy }).reify() + const foo = [...tree.inventory.values()].find(n => n.name === 'foo') + const barEdge = foo.edgesOut.get('bar') + t.ok(barEdge && barEdge.valid && barEdge.to, `bar edge resolved under ${installStrategy}`) + t.equal(barEdge.to.version, '1.2.3', 'bar resolved to a real installed node') + }) +} + +t.test('lockfile records hash, provenance, effective deps, and version 4', async t => { + const dir = await setup(t, { packageExtensions: ext }) + await newArb(dir).reify() + const lock = readLock(dir) + t.equal(lock.lockfileVersion, 4, 'bumped to lockfileVersion 4') + t.equal(lock.packages[''].packageExtensionsHash, canonicalHash(ext), 'root entry carries the canonical hash') + const fooEntry = lock.packages['node_modules/foo'] + t.strictSame(fooEntry.packageExtensionsApplied, { selector: 'foo@1', dependencies: ['bar'] }, + 'foo entry carries minimal provenance') + t.strictSame(fooEntry.dependencies, { bar: '^1.0.0' }, 'foo entry carries the effective dependency metadata') +}) + +t.test('does not rewrite the installed dependency package.json', async t => { + const dir = await setup(t, { packageExtensions: ext }) + await newArb(dir).reify() + const installed = JSON.parse(fs.readFileSync(join(dir, 'node_modules/foo/package.json'), 'utf8')) + t.notOk(installed.dependencies, 'the on-disk foo/package.json is not given a bar dependency') +}) + +t.test('composes with overrides during reify', async t => { + const dir = await setup(t, { packageExtensions: ext, overrides: { bar: '1.2.3' } }) + const tree = await newArb(dir).reify() + const bar = [...tree.inventory.values()].find(n => n.name === 'bar') + t.equal(bar.version, '1.2.3', 'override applied to the extension-created edge') +}) + +t.test('provenance round-trips through the lockfile (npm ci style)', async t => { + const dir = await setup(t, { packageExtensions: ext }) + await newArb(dir).reify() + // a fresh build loaded from the lockfile retains the provenance and hash + const virtual = await newArb(dir).loadVirtual() + const foo = [...virtual.inventory.values()].find(n => n.name === 'foo') + t.strictSame(foo.packageExtensionsApplied, { selector: 'foo@1', dependencies: ['bar'] }, + 'provenance restored from the lockfile') + t.equal(virtual.meta.packageExtensionsHash, canonicalHash(ext), 'hash restored from the lockfile') +}) + +t.test('refuses a lockfile newer than the supported version', async t => { + const dir = await setup(t, { packageExtensions: ext }) + await newArb(dir).reify() + const lock = readLock(dir) + lock.lockfileVersion = 5 + fs.writeFileSync(join(dir, 'package-lock.json'), JSON.stringify(lock)) + await t.rejects(newArb(dir).loadVirtual(), { code: 'ELOCKFILEVERSION' }, 'too-new lockfile is rejected') +}) + +t.test('removing an extension on reinstall reverts the locked graph', async t => { + const dir = await setup(t, { packageExtensions: ext }) + await newArb(dir).reify() + t.ok(readLock(dir).packages['node_modules/bar'], 'bar installed by the extension') + + // remove the extension and reinstall; the stale extended manifest must not persist + fs.writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'root', dependencies: { foo: '1.0.0' } })) + await register(t, dir, { withBar: false }) + await newArb(dir).reify() + const lock = readLock(dir) + t.notOk(lock.packages['node_modules/bar'], 'bar removed once the extension is gone') + t.notOk(lock.packages[''].packageExtensionsHash, 'root hash cleared') + t.notOk(lock.packages['node_modules/foo'].packageExtensionsApplied, 'foo provenance cleared') +}) + +t.test('adding an extension to an existing lockfile applies it on reinstall', async t => { + // first install with no extension, so the lockfile has foo but no bar + const dir = t.testdir({ + 'package.json': JSON.stringify({ name: 'root', dependencies: { foo: '1.0.0' } }), + src: { + foo: { 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }) }, + bar: { 'package.json': JSON.stringify({ name: 'bar', version: '1.2.3' }) }, + }, + }) + await register(t, dir, { withBar: false }) + await newArb(dir).reify() + t.notOk(readLock(dir).packages['node_modules/bar'], 'no bar before the extension is added') + + // add the extension and reinstall; the stale foo node must be rebuilt and gain the bar edge + fs.writeFileSync(join(dir, 'package.json'), + JSON.stringify({ name: 'root', dependencies: { foo: '1.0.0' }, packageExtensions: ext })) + await register(t, dir) + await newArb(dir).reify() + const lock = readLock(dir) + t.ok(lock.packages['node_modules/bar'], 'bar added after the extension is introduced') + t.strictSame(lock.packages['node_modules/foo'].packageExtensionsApplied, + { selector: 'foo@1', dependencies: ['bar'] }, 'provenance recorded for the newly extended node') +}) + +t.test('changing an extension range on reinstall re-resolves the edge', async t => { + const dir = t.testdir({ + 'package.json': JSON.stringify({ name: 'root', dependencies: { foo: '1.0.0' }, packageExtensions: ext }), + src: { + foo: { 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }) }, + bar: { 'package.json': JSON.stringify({ name: 'bar', version: '1.2.3' }) }, + bar2: { 'package.json': JSON.stringify({ name: 'bar', version: '2.0.0' }) }, + }, + }) + const registerBoth = async () => { + const registry = createRegistry(t) + const fooManifest = registry.manifest({ name: 'foo', packuments: [{ version: '1.0.0' }] }) + const barManifest = registry.manifest({ name: 'bar', packuments: [{ version: '1.2.3' }, { version: '2.0.0' }] }) + await registry.package({ manifest: fooManifest, tarballs: { '1.0.0': join(dir, 'src/foo') } }) + await registry.package({ + manifest: barManifest, + tarballs: { '1.2.3': join(dir, 'src/bar'), '2.0.0': join(dir, 'src/bar2') }, + }) + } + await registerBoth() + await newArb(dir).reify() + t.equal(readLock(dir).packages['node_modules/bar'].version, '1.2.3', 'bar resolved to 1.x') + + fs.writeFileSync(join(dir, 'package.json'), + JSON.stringify({ name: 'root', dependencies: { foo: '1.0.0' }, packageExtensions: { 'foo@1': { dependencies: { bar: '^2.0.0' } } } })) + await registerBoth() + await newArb(dir).reify() + t.equal(readLock(dir).packages['node_modules/bar'].version, '2.0.0', 'bar re-resolved to 2.x after the range change') +}) diff --git a/workspaces/arborist/test/arborist/reify-patch.js b/workspaces/arborist/test/arborist/reify-patch.js new file mode 100644 index 0000000000000..53ac56feb7a9e --- /dev/null +++ b/workspaces/arborist/test/arborist/reify-patch.js @@ -0,0 +1,409 @@ +const t = require('tap') +const fs = require('node:fs') +const { resolve } = require('node:path') +const { createTwoFilesPatch } = require('diff') +const MockRegistry = require('@npmcli/mock-registry') +const Arborist = require('../../lib/index.js') + +// build a git-style unified diff for a single file change +const filePatch = (file, before, after) => { + let p = createTwoFilesPatch(`a/${file}`, `b/${file}`, before, after, '', '') + .replace('===================================================================\n', '') + if (before === '') { + p = p.replace(`--- a/${file}\t`, '--- /dev/null\t') + } + if (after === '') { + p = p.replace(`+++ b/${file}\t`, '+++ /dev/null\t') + } + return p +} + +const createRegistry = (t) => new MockRegistry({ + strict: false, + tap: t, + registry: 'https://registry.npmjs.org', +}) + +const newArb = (opt) => new Arborist({ + audit: false, + cache: opt.path, + registry: 'https://registry.npmjs.org', + timeout: 30 * 60 * 1000, + ...opt, +}) + +// the registry package source we patch in these tests +const PKG_NAME = 'patch-me' +const PKG_VERSION = '1.0.0' +const ORIGINAL = 'module.exports = "original"\n' +const PATCHED = 'module.exports = "patched"\n' + +// register the package manifest + tarball on the mock registry. +// manifestTimes controls how many packument GETs are served, tarballTimes how many tarball GETs. +// nock consumes one mock per request and teardown asserts every registered mock is used, so counts must match the requests a test makes. +const mockPackage = async (t, registry, { manifestTimes = 1, tarballTimes = 1 } = {}) => { + const src = t.testdir({ + 'package.json': JSON.stringify({ name: PKG_NAME, version: PKG_VERSION }), + 'index.js': ORIGINAL, + }) + const manifest = registry.manifest({ + name: PKG_NAME, + packuments: [{ version: PKG_VERSION }], + }) + registry.nock = registry.nock + .get(registry.fullPath(`/${PKG_NAME}`)).times(manifestTimes).reply(200, manifest) + for (let i = 0; i < tarballTimes; i++) { + await registry.tarball({ manifest: manifest.versions[PKG_VERSION], tarball: src }) + } + return manifest +} + +// write a project root + on-disk patch file, return its path +const makeProject = (t, { patch, patchedDependencies, extra = {} }) => { + const tree = { + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { [PKG_NAME]: `^${PKG_VERSION}` }, + ...(patchedDependencies ? { patchedDependencies } : {}), + }), + ...extra, + } + if (patch !== undefined) { + tree.patches = { [`${PKG_NAME}@${PKG_VERSION}.patch`]: patch } + } + return t.testdir(tree) +} + +const installedFile = (path) => + resolve(path, 'node_modules', PKG_NAME, 'index.js') + +t.test('registry dep with patch is applied and recorded in lockfile', async t => { + const registry = createRegistry(t) + await mockPackage(t, registry) + + const patch = filePatch('index.js', ORIGINAL, PATCHED) + const path = makeProject(t, { + patch, + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: `patches/${PKG_NAME}@${PKG_VERSION}.patch` }, + }) + + await newArb({ path }).reify() + + t.equal(fs.readFileSync(installedFile(path), 'utf8'), PATCHED, + 'extracted package was patched') + + const lock = JSON.parse(fs.readFileSync(resolve(path, 'package-lock.json'), 'utf8')) + t.equal(lock.lockfileVersion, 4, 'lockfile bumped to version 4') + const pkgEntry = lock.packages[`node_modules/${PKG_NAME}`] + t.ok(pkgEntry.patched, 'lockfile records patched') + t.equal(pkgEntry.patched.path, `patches/${PKG_NAME}@${PKG_VERSION}.patch`, + 'patched.path is the relative patch path') + t.match(pkgEntry.patched.integrity, /^sha512-/, 'patched.integrity is an SSRI') +}) + +t.test('uninstalling a patched package drops its entry from package.json', async t => { + const registry = createRegistry(t) + // one install, then an uninstall that resolves from the lockfile so no extra fetches + await mockPackage(t, registry) + + const patch = filePatch('index.js', ORIGINAL, PATCHED) + const path = makeProject(t, { + patch, + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: `patches/${PKG_NAME}@${PKG_VERSION}.patch` }, + }) + + await newArb({ path }).reify() + t.equal(fs.readFileSync(installedFile(path), 'utf8'), PATCHED, 'package installed and patched') + + // npm uninstall : removes the dep but leaves the now-orphaned patch entry + await newArb({ path }).reify({ rm: [PKG_NAME] }) + + const rootPkg = JSON.parse(fs.readFileSync(resolve(path, 'package.json'), 'utf8')) + t.notOk(rootPkg.dependencies?.[PKG_NAME], 'dependency removed from package.json') + t.notOk(rootPkg.patchedDependencies, 'orphaned patch entry dropped from package.json') + t.notOk(fs.existsSync(resolve(path, 'node_modules', PKG_NAME)), 'package removed from node_modules') +}) + +t.test('patch is re-applied on a patch-change reify even with ignoreScripts', async t => { + const registry = createRegistry(t) + // two reifys: the second re-extracts the node due to the patch change. + // the second reify resolves the dep from the lockfile, so only one manifest GET. + await mockPackage(t, registry, { manifestTimes: 1, tarballTimes: 2 }) + + // first reify with no patch registered + const path = makeProject(t, {}) + await newArb({ path }).reify() + t.equal(fs.readFileSync(installedFile(path), 'utf8'), ORIGINAL, + 'first install is unpatched') + + // now add a patch + patchedDependencies and reify again with ignoreScripts + const patch = filePatch('index.js', ORIGINAL, PATCHED) + fs.mkdirSync(resolve(path, 'patches'), { recursive: true }) + fs.writeFileSync(resolve(path, 'patches', `${PKG_NAME}@${PKG_VERSION}.patch`), patch) + const rootPkg = JSON.parse(fs.readFileSync(resolve(path, 'package.json'), 'utf8')) + rootPkg.patchedDependencies = { + [`${PKG_NAME}@${PKG_VERSION}`]: `patches/${PKG_NAME}@${PKG_VERSION}.patch`, + } + fs.writeFileSync(resolve(path, 'package.json'), JSON.stringify(rootPkg)) + + await newArb({ path, ignoreScripts: true }).reify() + + t.equal(fs.readFileSync(installedFile(path), 'utf8'), PATCHED, + 'patch applied on patch-change reify under ignoreScripts') + const lock = JSON.parse(fs.readFileSync(resolve(path, 'package-lock.json'), 'utf8')) + t.equal(lock.lockfileVersion, 4, 'lockfile bumped to version 4 after patch added') +}) + +t.test('patch that fails to apply throws EPATCHFAILED', async t => { + const registry = createRegistry(t) + await mockPackage(t, registry) + + // a patch whose context does not match the extracted file + const patch = filePatch('index.js', 'totally different\n', 'something else\n') + const path = makeProject(t, { + patch, + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: `patches/${PKG_NAME}@${PKG_VERSION}.patch` }, + }) + + await t.rejects(newArb({ path }).reify(), { code: 'EPATCHFAILED' }, + 'hunk that does not apply hard-errors') +}) + +t.test('ignorePatchFailures downgrades EPATCHFAILED to a warning', async t => { + const registry = createRegistry(t) + await mockPackage(t, registry) + + const patch = filePatch('index.js', 'totally different\n', 'something else\n') + const path = makeProject(t, { + patch, + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: `patches/${PKG_NAME}@${PKG_VERSION}.patch` }, + }) + + const warnings = [] + const onLog = (level, prefix, msg) => level === 'warn' && warnings.push(`${prefix} ${msg}`) + process.on('log', onLog) + t.teardown(() => process.removeListener('log', onLog)) + + await t.resolves(newArb({ path, ignorePatchFailures: true }).reify(), + 'failure is downgraded and reify continues') + // file remains as extracted since the patch was skipped + t.equal(fs.readFileSync(installedFile(path), 'utf8'), ORIGINAL, + 'package left unpatched after skipped failure') + // the skipped patch must not be recorded in the lockfile + const lock = JSON.parse(fs.readFileSync(resolve(path, 'package-lock.json'), 'utf8')) + t.notOk(lock.packages[`node_modules/${PKG_NAME}`].patched, + 'unapplied patch is not written to the lockfile') + // the user is told the lockfile is now out of sync with package.json + t.match(warnings.join('\n'), /out of sync and `npm ci` will fail/, + 'warns that the lockfile no longer matches package.json') +}) + +t.test('missing patch file throws EPATCHNOTFOUND', async t => { + const registry = createRegistry(t) + // resolvePatchedDependencies fails before extract, so the tarball is never fetched + await mockPackage(t, registry, { tarballTimes: 0 }) + + // register patchedDependencies but do NOT write the patch file + const path = makeProject(t, { + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: `patches/${PKG_NAME}@${PKG_VERSION}.patch` }, + }) + + await t.rejects(newArb({ path }).reify(), { code: 'EPATCHNOTFOUND' }, + 'missing patch file on disk hard-errors') +}) + +t.test('warns when a patch upgrades the lockfile version', async t => { + const registry = createRegistry(t) + await mockPackage(t, registry) + const path = makeProject(t, { + patch: filePatch('index.js', ORIGINAL, PATCHED), + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: `patches/${PKG_NAME}@${PKG_VERSION}.patch` }, + }) + + const warnings = [] + const onLog = (level, prefix, msg) => level === 'warn' && warnings.push(`${prefix} ${msg}`) + process.on('log', onLog) + t.teardown(() => process.removeListener('log', onLog)) + + await newArb({ path }).reify() + t.match(warnings.join('\n'), /requires lockfileVersion 4/, 'warns that the lockfile was upgraded') +}) + +t.test('does not re-warn or bump the hidden lockfile once the lockfile is already v4', async t => { + const registry = createRegistry(t) + await mockPackage(t, registry) + const path = makeProject(t, { + patch: filePatch('index.js', ORIGINAL, PATCHED), + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: `patches/${PKG_NAME}@${PKG_VERSION}.patch` }, + }) + + // the first reify legitimately upgrades the real lockfile to v4 + await newArb({ path }).reify() + + const warnings = [] + const onLog = (level, prefix, msg) => level === 'warn' && warnings.push(`${prefix} ${msg}`) + process.on('log', onLog) + t.teardown(() => process.removeListener('log', onLog)) + + // the hidden lockfile is pinned to v3, so a second reify must not re-fire the upgrade warning + await newArb({ path }).reify() + t.notMatch(warnings.join('\n'), /requires lockfileVersion 4/, 'no spurious upgrade warning when already v4') + + const hidden = JSON.parse(fs.readFileSync(resolve(path, 'node_modules/.package-lock.json'), 'utf8')) + t.equal(hidden.lockfileVersion, 3, 'hidden lockfile stays at version 3') +}) + +t.test('reify revalidates the patch file when build-ideal-tree was already run', async t => { + // build-ideal-tree validates first, but reify must still guard against a file removed afterwards + const registry = createRegistry(t) + await mockPackage(t, registry) + const patchRel = `patches/${PKG_NAME}@${PKG_VERSION}.patch` + const path = makeProject(t, { + patch: filePatch('index.js', ORIGINAL, PATCHED), + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: patchRel }, + }) + + const arb = newArb({ path }) + await arb.buildIdealTree() + // delete the validated patch file; reify reuses the cached ideal tree and re-checks + fs.rmSync(resolve(path, patchRel)) + await t.rejects(arb.reify(), { code: 'EPATCHNOTFOUND' }, + 'reify re-checks the patch file even on a prebuilt ideal tree') +}) + +t.test('reify rejects a patch whose contents changed after build-ideal-tree', async t => { + const registry = createRegistry(t) + await mockPackage(t, registry) + const patchRel = `patches/${PKG_NAME}@${PKG_VERSION}.patch` + const path = makeProject(t, { + patch: filePatch('index.js', ORIGINAL, PATCHED), + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: patchRel }, + }) + + const arb = newArb({ path }) + await arb.buildIdealTree() + // change the patch contents after validation so the integrity no longer matches + fs.writeFileSync(resolve(path, patchRel), filePatch('index.js', ORIGINAL, 'module.exports = "other"\n')) + await t.rejects(arb.reify(), { code: 'EPATCHINTEGRITY' }, + 'reify rejects an integrity mismatch introduced after build-ideal-tree') +}) + +t.test('applies a patch under install-strategy=linked via the side-store', async t => { + const registry = createRegistry(t) + await mockPackage(t, registry) + const patchRel = `patches/${PKG_NAME}@${PKG_VERSION}.patch` + const path = makeProject(t, { + patch: filePatch('index.js', ORIGINAL, PATCHED), + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: patchRel }, + }) + + await newArb({ path, installStrategy: 'linked' }).reify() + + // the consumer symlink resolves to the patched contents + t.equal(fs.readFileSync(installedFile(path), 'utf8'), PATCHED, 'linked consumer sees the patch') + + // the patched package lives in a distinct +patch side-store entry + const store = fs.readdirSync(resolve(path, 'node_modules', '.store')) + const entry = store.find(e => e.startsWith(`${PKG_NAME}@${PKG_VERSION}-`) && e.endsWith('+patch')) + t.ok(entry, 'side-store key carries the +patch suffix') + t.equal( + fs.readFileSync(resolve(path, 'node_modules', '.store', entry, 'node_modules', PKG_NAME, 'index.js'), 'utf8'), + PATCHED, + 'the patch is applied in the side-store entry' + ) +}) + +t.test('removing a patch under install-strategy=linked reverts via the side-store', async t => { + const registry = createRegistry(t) + await mockPackage(t, registry, { manifestTimes: 1, tarballTimes: 2 }) + const patchRel = `patches/${PKG_NAME}@${PKG_VERSION}.patch` + const path = makeProject(t, { + patch: filePatch('index.js', ORIGINAL, PATCHED), + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: patchRel }, + }) + + // first install materializes the patched +patch side-store entry + await newArb({ path, installStrategy: 'linked' }).reify() + t.equal(fs.readFileSync(installedFile(path), 'utf8'), PATCHED, 'patched before removal') + + // remove the patch declaration and its file, then reinstall + const pkg = JSON.parse(fs.readFileSync(resolve(path, 'package.json'), 'utf8')) + delete pkg.patchedDependencies + fs.writeFileSync(resolve(path, 'package.json'), JSON.stringify(pkg)) + fs.rmSync(resolve(path, patchRel)) + + await newArb({ path, installStrategy: 'linked' }).reify() + t.equal(fs.readFileSync(installedFile(path), 'utf8'), ORIGINAL, 'consumer reverted to unpatched contents') + const store = fs.readdirSync(resolve(path, 'node_modules', '.store')) + t.notOk(store.some(e => e.endsWith('+patch')), 'the +patch side-store entry was pruned') +}) + +t.test('linked ignorePatchFailures cannot skip a failed patch', async t => { + // the content-addressed side-store cannot represent an unpatched package at a patched key, + // so a failed patch must error rather than silently leave unpatched contents that later installs trust. + const registry = createRegistry(t) + await mockPackage(t, registry) + const patch = filePatch('index.js', 'totally different\n', 'something else\n') + const path = makeProject(t, { + patch, + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: `patches/${PKG_NAME}@${PKG_VERSION}.patch` }, + }) + + await t.rejects( + newArb({ path, installStrategy: 'linked', ignorePatchFailures: true }).reify(), + { code: 'EPATCHFAILED', message: /install-strategy=linked/ }, + 'a failed patch cannot be skipped under linked mode' + ) +}) + +t.test('a patched optional dependency still fails loudly on patch problems', async t => { + // optional installs tolerate platform/env failures, but a declared patch must not be silently skipped + const registry = createRegistry(t) + await mockPackage(t, registry) + const patchRel = `patches/${PKG_NAME}@${PKG_VERSION}.patch` + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + optionalDependencies: { [PKG_NAME]: `^${PKG_VERSION}` }, + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: patchRel }, + }), + patches: { [`${PKG_NAME}@${PKG_VERSION}.patch`]: filePatch('index.js', ORIGINAL, PATCHED) }, + }) + + const arb = newArb({ path }) + await arb.buildIdealTree() + fs.rmSync(resolve(path, patchRel)) + await t.rejects(arb.reify(), { code: 'EPATCHNOTFOUND' }, + 'optional patch failure is not swallowed by optional handling') +}) + +t.test('restores node.patched from an existing v4 lockfile', async t => { + const patchRel = `patches/${PKG_NAME}@${PKG_VERSION}.patch` + const path = makeProject(t, { + patch: filePatch('index.js', ORIGINAL, PATCHED), + patchedDependencies: { [`${PKG_NAME}@${PKG_VERSION}`]: patchRel }, + extra: { + 'package-lock.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + lockfileVersion: 4, + requires: true, + packages: { + '': { name: 'root', version: '1.0.0', dependencies: { [PKG_NAME]: `^${PKG_VERSION}` } }, + [`node_modules/${PKG_NAME}`]: { + version: PKG_VERSION, + resolved: `https://registry.npmjs.org/${PKG_NAME}/-/${PKG_NAME}-${PKG_VERSION}.tgz`, + integrity: 'sha512-deadbeef', + patched: { path: patchRel, integrity: 'sha512-abc' }, + }, + }, + }), + }, + }) + const tree = await newArb({ path }).loadVirtual() + const dep = [...tree.inventory.values()].find(n => n.name === PKG_NAME) + t.strictSame(dep.patched, { path: patchRel, integrity: 'sha512-abc' }, + 'node.patched is read back from the lockfile packages entry') +}) diff --git a/workspaces/arborist/test/arborist/reify.js b/workspaces/arborist/test/arborist/reify.js index 0a7fb416040c0..e1f67033d4581 100644 --- a/workspaces/arborist/test/arborist/reify.js +++ b/workspaces/arborist/test/arborist/reify.js @@ -1,11 +1,14 @@ -const { join, resolve, basename } = require('node:path') +const { join, resolve, basename, delimiter } = require('node:path') const t = require('tap') const runScript = require('@npmcli/run-script') const localeCompare = require('@isaacs/string-locale-compare')('en') +// TODO mock registry (will require several because of differing hosts const tnock = require('../fixtures/tnock') const fs = require('node:fs') const fsp = require('node:fs/promises') const npmFs = require('@npmcli/fs') +const MockRegistry = require('@npmcli/mock-registry') +const { dirname, relative } = require('node:path') let failRm = false let failRename = null @@ -71,12 +74,14 @@ const warningTracker = () => { } } -const outputTracker = () => { +// run-script@11 emits its banners via log.notice('run', ...) rather than +// output.standard, so capture log events to assert on them. +const logTracker = () => { const list = [] - const onlog = (...msg) => msg[0] === 'standard' && list.push(msg) - process.on('output', onlog) + const onlog = (...msg) => list.push(msg) + process.on('log', onlog) return () => { - process.removeListener('output', onlog) + process.removeListener('log', onlog) return list } } @@ -91,7 +96,7 @@ const debugLogTracker = () => { } const mockDebug = Object.assign(fn => fn(), { log: () => {} }) -const Arborist = t.mock('../../lib/index.js', { +const Arborist = t.mock('../..', { ...mocks, // need to not mock this one, so we still can swap the process object '../../lib/signal-handling.js': require('../../lib/signal-handling.js'), @@ -102,18 +107,6 @@ const Arborist = t.mock('../../lib/index.js', { const { Node, Link, Shrinkwrap } = Arborist -const { - start, - stop, - registry, - advisoryBulkResponse, -} = require('../fixtures/server.js') - -t.before(start) -t.teardown(stop) - -const cache = t.testdir() - const { normalizePath, normalizePaths, @@ -122,74 +115,119 @@ const { const cwd = normalizePath(process.cwd()) t.cleanSnapshot = s => s.split(cwd).join('{CWD}') - .split(registry).join('https://registry.npmjs.org/') const fixture = (t, p) => require('../fixtures/reify-cases/' + p)(t) const printReified = (path, opt) => reify(path, opt).then(printTree) +const fixtures = join(__dirname, '..', 'fixtures') +const createRegistry = (t, mocks) => { + const registry = new MockRegistry({ + strict: true, + tap: t, + registry: 'https://registry.npmjs.org', + }) + if (mocks) { + registry.mocks({ dir: join(__dirname, '..', 'fixtures') }) + } + return registry +} const newArb = (opt) => new Arborist({ audit: false, - cache, - registry, + cache: opt.path, // give it a very long timeout so CI doesn't crash as easily timeout: 30 * 60 * 1000, ...opt, }) -const reify = (path, opt) => newArb({ path, ...(opt || {}) }).reify(opt) +const reify = (path, opt = {}) => newArb({ path, ...opt }).reify(opt) t.test('bundled file dep with same name as other dep', async t => { + const registry = createRegistry(t) + registry.mocks({ dir: fixtures }) const tree = await printReified(fixture(t, 'conflict-bundle-file-dep')) t.matchSnapshot(tree) }) -t.test('tarball deps with transitive tarball deps', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'tarball-dependencies')))) +t.test('tarball deps with transitive tarball deps', async t => { + createRegistry(t) + await t.resolveMatchSnapshot(printReified(fixture(t, 'tarball-dependencies'))) +}) t.test('update a yarn.lock file', async t => { const path = fixture(t, 'yarn-lock-mkdirp') + createRegistry(t, true) const tree = await reify(path, { add: ['abbrev'] }) t.matchSnapshot(printTree(tree), 'add abbrev') t.matchSnapshot(fs.readFileSync(path + '/yarn.lock', 'utf8'), 'updated yarn lock') }) -t.test('weirdly broken lockfile without resolved value', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'dep-missing-resolved')))) +t.test('weirdly broken lockfile without resolved value', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(fixture(t, 'dep-missing-resolved'))) +}) -t.test('testing-peer-deps package', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'testing-peer-deps')))) +t.test('testing-peer-deps package', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(fixture(t, 'testing-peer-deps'))) +}) -t.test('just the shrinkwrap', t => { - const paths = [ - 'cli-750-fresh', - 'yarn-lock-mkdirp', - ] - t.plan(paths.length) - for (const p of paths) { - t.test(p, async t => { - const path = fixture(t, p) - const arb = newArb({ path, audit: true, packageLockOnly: true }) - await arb.reify() - t.ok(arb.auditReport, 'got an audit report') - t.throws(() => fs.statSync(path + '/node_modules'), { code: 'ENOENT' }) - t.matchSnapshot(fs.readFileSync(path + '/package-lock.json', 'utf8')) - }) - } +t.test('just the lockfile', async t => { + await t.test('cli-750-fresh', async t => { + const path = fixture(t, 'cli-750-fresh') + createRegistry(t, false) + const arb = newArb({ path, audit: true, packageLockOnly: true }) + await arb.reify() + t.throws(() => fs.statSync(path + '/node_modules'), { code: 'ENOENT' }) + t.matchSnapshot(fs.readFileSync(path + '/package-lock.json', 'utf8')) + }) + await t.test('yarn-lock-mkdirp', async t => { + const path = fixture(t, 'yarn-lock-mkdirp') + const registry = createRegistry(t, true) + registry.audit({}) + const arb = newArb({ path, audit: true, packageLockOnly: true }) + await arb.reify() + t.throws(() => fs.statSync(path + '/node_modules'), { code: 'ENOENT' }) + t.matchSnapshot(fs.readFileSync(path + '/package-lock.json', 'utf8')) + }) }) t.test('packageLockOnly can add deps', async t => { const path = t.testdir({ 'package.json': '{}' }) + createRegistry(t, true) await reify(path, { add: ['abbrev'], packageLockOnly: true }) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) t.matchSnapshot(fs.readFileSync(path + '/package-lock.json', 'utf8')) t.throws(() => fs.statSync(path + '/node_modules'), { code: 'ENOENT' }) }) -t.test('malformed package.json should not be overwitten', async t => { +t.test('packageLockOnly with linked strategy in workspaces', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'repro', + private: true, + workspaces: ['packages/*'], + }), + packages: { + a: { + 'package.json': JSON.stringify({ + name: 'a', + version: '1.0.0', + }), + }, + }, + }) + createRegistry(t, false) + await reify(path, { packageLockOnly: true, installStrategy: 'linked' }) + t.ok(fs.existsSync(path + '/package-lock.json'), 'lock file created') + t.throws(() => fs.statSync(path + '/node_modules'), { code: 'ENOENT' }) +}) + +t.test('malformed package.json should not be overwritten', async t => { t.plan(2) const path = fixture(t, 'malformed-json') + createRegistry(t, false) const originalContent = fs.readFileSync(path + '/package.json', 'utf8') try { @@ -208,11 +246,13 @@ t.test('malformed package.json should not be overwitten', async t => { t.test('packageLockOnly does not work on globals', t => { const path = t.testdir({ 'package.json': '{}' }) + createRegistry(t, false) return t.rejects(() => reify(path, { global: true, packageLockOnly: true })) }) t.test('omit peer deps', t => { const path = fixture(t, 'testing-peer-deps') + createRegistry(t, true) // in this one we also snapshot the timers, mostly just as a smoke test const timers = {} const finishedTimers = [] @@ -253,20 +293,27 @@ t.test('omit peer deps', t => { }) }) -t.test('testing-peer-deps nested', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'testing-peer-deps-nested')))) +t.test('testing-peer-deps nested', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(fixture(t, 'testing-peer-deps-nested'))) +}) -t.test('a workspace with a duplicated nested conflicted dep', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'workspace4')))) +t.test('a workspace with a duplicated nested conflicted dep', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(fixture(t, 'workspace4'))) +}) -t.test('testing-peer-deps nested with update', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'testing-peer-deps-nested'), { +t.test('testing-peer-deps nested with update', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(fixture(t, 'testing-peer-deps-nested'), { update: { names: ['@isaacs/testing-peer-deps'] }, save: false, - }))) + })) +}) t.test('update a bundling node without updating all of its deps', t => { const path = fixture(t, 'tap-react15-collision-legacy-sw') + createRegistry(t, true) // check that it links the bin const bin = resolve(path, 'node_modules/.bin/tap') @@ -295,14 +342,16 @@ t.test('update a bundling node without updating all of its deps', t => { t.test('Bundles rebuilt as long as rebuildBundle not false', async t => { t.test('rebuild the bundle', async t => { const path = fixture(t, 'testing-rebuild-bundle') + createRegistry(t, true) const a = resolve(path, 'node_modules/@isaacs/testing-rebuild-bundle-a') const dir = resolve(a, 'node_modules/@isaacs/testing-rebuild-bundle-b') const file = resolve(dir, 'cwd') - await reify(path) + await reify(path, { dangerouslyAllowAllScripts: true }) t.equal(fs.readFileSync(file, 'utf8'), dir) }) t.test('do not rebuild the bundle', async t => { const path = fixture(t, 'testing-rebuild-bundle') + createRegistry(t, true) const a = resolve(path, 'node_modules/@isaacs/testing-rebuild-bundle-a') const dir = resolve(a, 'node_modules/@isaacs/testing-rebuild-bundle-b') const file = resolve(dir, 'cwd') @@ -313,6 +362,7 @@ t.test('Bundles rebuilt as long as rebuildBundle not false', async t => { t.test('transitive deps containing asymmetrical bin no lockfile', t => { const path = fixture(t, 'testing-asymmetrical-bin-no-lock') + createRegistry(t, true) // check that it links the bin const bin = resolve(path, 'node_modules/.bin/b') @@ -327,6 +377,7 @@ t.test('transitive deps containing asymmetrical bin no lockfile', t => { t.test('transitive deps containing asymmetrical bin with lockfile', t => { const path = fixture(t, 'testing-asymmetrical-bin-with-lock') + createRegistry(t, true) // check that it links the bin const bin = resolve(path, 'node_modules/.bin/b') @@ -340,9 +391,9 @@ t.test('transitive deps containing asymmetrical bin with lockfile', t => { t.test('omit optional dep', t => { const path = fixture(t, 'tap-react15-collision-legacy-sw') - const ignoreScripts = true + createRegistry(t, true) - const arb = newArb({ path, ignoreScripts }) + const arb = newArb({ path, ignoreScripts: true }) // eslint-disable-next-line promise/always-return return arb.reify({ omit: ['optional'] }).then(tree => { t.equal(tree.children.get('fsevents'), undefined, 'no fsevents in tree') @@ -359,27 +410,44 @@ t.test('dev, optional, devOptional flags and omissions', t => { const path = 'testing-dev-optional-flags' const omits = [['dev'], ['dev', 'optional'], ['optional']] t.plan(omits.length) - omits.forEach(omit => t.test(omit.join(','), t => - t.resolveMatchSnapshot(printReified(fixture(t, path), { + omits.forEach(omit => t.test(omit.join(','), async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(fixture(t, path), { omit, - })))) + })) + })) +}) + +t.test('omit reports no diff on second run', async t => { + const path = fixture(t, 'testing-dev-optional-flags') + createRegistry(t, true) + const arb = newArb({ path }) + await arb.reify({ omit: ['dev'] }) + t.equal(arb.actualTree.children.get('once'), undefined, 'no once in tree') + t.ok(arb.diff.children.length, 'first reify has changes') + await arb.reify({ omit: ['dev'] }) + t.equal(arb.actualTree.children.get('once'), undefined, 'no once in tree') + t.notOk(arb.diff.children.length, 'second reify has no changes') + await arb.reify({}) + t.ok(arb.actualTree.children.get('once'), 'once in tree') + t.ok(arb.diff.children.length, 'removing omit has changes') }) t.test('omits when both dev and optional flags are set', t => { const path = 'testing-dev-optional-flags-2' const omits = [['dev'], ['optional']] t.plan(omits.length) - omits.forEach(omit => t.test(omit.join(','), t => - t.resolveMatchSnapshot(printReified(fixture(t, path), { + omits.forEach(omit => t.test(omit.join(','), async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(fixture(t, path), { omit, - })))) + })) + })) }) -t.test('bad shrinkwrap file', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'testing-peer-deps-bad-sw')))) - t.test('multiple bundles at the same level', t => { const path = fixture(t, 'two-bundled-deps') + createRegistry(t, true) const a = newArb({ path }) return a.reify().then(tree => { const root = tree.root @@ -401,145 +469,132 @@ t.test('multiple bundles at the same level', t => { }) }) -t.test('update a node without updating its children', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'once-outdated'), - { update: { names: ['once'] }, save: false }))) - -t.test('do not add shrinkwrapped deps', t => - t.resolveMatchSnapshot(printReified( - fixture(t, 'shrinkwrapped-dep-no-lock'), { update: true }))) - -t.test('do not update shrinkwrapped deps', t => - t.resolveMatchSnapshot(printReified( - fixture(t, 'shrinkwrapped-dep-with-lock'), - { update: { names: ['abbrev'] } }))) - -t.test('tracks changes of shrinkwrapped dep correctly', async t => { - const path = t.testdir({ - 'package.json': '{}', - }) - - const install1 = await printReified(path, { add: ['@nlf/shrinkwrapped-dep-updates-a@1.0.0'] }) - t.matchSnapshot(install1, 'install added the correct tree') - - const update1 = await printReified(path, { update: true }) - t.match(install1, update1, 'update maintains the same correct tree') - - const install2 = await printReified(path, { add: ['@nlf/shrinkwrapped-dep-updates-a@2.0.0'] }) - t.matchSnapshot(install2, 'installing new version brings in the correct children') - - const update2 = await printReified(path, { update: true }) - t.match(install2, update2, 'update maintains the same correct tree') - - // delete a dependency that was installed as part of the shrinkwrap - fs.rmSync(resolve(path, 'node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-b'), { recursive: true, force: true }) - const repair = await printReified(path) - t.match(repair, install2, 'tree got repaired') +t.test('update a node without updating its children', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(fixture(t, 'once-outdated'), + { update: { names: ['once'] }, save: false })) }) -t.test('do not install optional deps with mismatched platform specifications', t => - t.resolveMatchSnapshot(printReified( - fixture(t, 'optional-platform-specification')))) +t.test('do not install optional deps with mismatched platform specifications', async t => { + createRegistry(t, true) + const path = fixture(t, 'optional-platform-specification') + const tree = await reify(path) + t.equal(tree.children.size, 0, 'does not have deps') +}) -t.test('still do not install optional deps with mismatched platform specifications even when forced', t => - t.resolveMatchSnapshot(printReified( - fixture(t, 'optional-platform-specification'), { force: true }))) +t.test('do not report failed optional deps as installed', async t => { + createRegistry(t, true) + const path = fixture(t, 'optional-platform-specification') + const arb = newArb({ path }) + await arb.reify() + t.equal(arb.diff.children.length, 0, 'no changes, nothing installed') +}) -t.test('fail to install deps with mismatched platform specifications', t => - t.rejects(printReified(fixture(t, 'platform-specification')), { code: 'EBADPLATFORM' })) +t.test('still do not install optional deps with mismatched platform specifications even when forced', async t => { + createRegistry(t, true) + const path = fixture(t, 'optional-platform-specification') + const tree = await reify(path, { force: true }) + t.equal(tree.children.size, 0, 'does not have deps') +}) -t.test('success to install optional deps with matched platform specifications with os and cpu and libc options', t => - t.resolveMatchSnapshot(printReified( - fixture(t, 'optional-platform-specification'), { os: 'not-your-os', cpu: 'not-your-cpu', libc: 'not-your-libc' }))) +t.test('fail to install deps with mismatched platform specifications', async t => { + createRegistry(t, true) + await t.rejects(reify(fixture(t, 'platform-specification')), { code: 'EBADPLATFORM' }) +}) -t.test('fail to install optional deps with matched os and mismatched cpu with os and cpu and libc options', t => - t.resolveMatchSnapshot(printReified( - fixture(t, 'optional-platform-specification'), { os: 'not-your-os', cpu: 'another-cpu', libc: 'not-your-libc' }))) +t.test('success to install optional deps with matched platform specifications with os and cpu and libc options', async t => { + createRegistry(t, true) + const path = fixture(t, 'optional-platform-specification') + const tree = await reify(path, { os: 'not-your-os', cpu: 'not-your-cpu', libc: 'not-your-libc' }) + t.equal(tree.children.size, 1, 'does have deps') +}) -t.test('fail to install optional deps with mismatched os and matched cpu with os and cpu and libc options', t => - t.resolveMatchSnapshot(printReified( - fixture(t, 'optional-platform-specification'), { os: 'another-os', cpu: 'not-your-cpu', libc: 'not-your-libc' }))) +t.test('fail to install optional deps with matched os and mismatched cpu with os and cpu and libc options', async t => { + createRegistry(t, true) + const path = fixture(t, 'optional-platform-specification') + const tree = await reify(path, { os: 'not-your-os', cpu: 'another-cpu', libc: 'not-your-libc' }) + t.equal(tree.children.size, 0, 'does not have deps') +}) -t.test('fail to install optional deps with matched os and matched cpu and mismatched libc with os and cpu and libc options', t => - t.resolveMatchSnapshot(printReified( - fixture(t, 'optional-platform-specification'), { os: 'another-os', cpu: 'not-your-cpu', libc: 'not-your-libc' }))) +t.test('fail to install optional deps with mismatched os and matched cpu with os and cpu and libc options', async t => { + createRegistry(t, true) + const path = fixture(t, 'optional-platform-specification') + const tree = await reify(path, { os: 'another-os', cpu: 'not-your-cpu', libc: 'not-your-libc' }) + t.equal(tree.children.size, 0, 'does not have deps') +}) -t.test('dry run, do not get anything wet', async t => { - const cases = [ - 'shrinkwrapped-dep-with-lock-empty', - 'shrinkwrapped-dep-no-lock-empty', - 'link-dep-empty', - 'link-meta-deps-empty', - 'testing-bundledeps-empty', - ] - t.plan(cases.length) - cases.forEach(c => t.test(c, async t => { - const path = fixture(t, c) - const arb = newArb({ path, dryRun: true }) - t.matchSnapshot(printTree(await arb.reify())) - t.throws(() => fs.statSync(resolve(path, 'node_modules'))) - t.ok(arb.diff) - })) +t.test('fail to install optional deps with matched os and matched cpu and mismatched libc with os and cpu and libc options', async t => { + createRegistry(t, true) + const path = fixture(t, 'optional-platform-specification') + const tree = await reify(path, { os: 'another-os', cpu: 'not-your-cpu', libc: 'not-your-libc' }) + t.equal(tree.children.size, 0, 'does not have deps') }) -t.test('reifying with shronk warp dep', t => { +t.test('dry run, do not get anything wet', async t => { const cases = [ - 'shrinkwrapped-dep-with-lock', - 'shrinkwrapped-dep-with-lock-empty', - 'shrinkwrapped-dep-no-lock', - 'shrinkwrapped-dep-no-lock-empty', + ['link-dep-empty', false], + ['link-meta-deps-empty', true], + ['testing-bundledeps-empty', true], ] t.plan(cases.length) - for (const c of cases) { - t.test(c, async t => { + for (const [c, mocks] of cases) { + await t.test(c, async t => { const path = fixture(t, c) - const tree = await printReified(path, { - // set update so that we don't start the idealTree - // with the actualTree, and can see that the deps - // are indeed getting set up from the shrink wrap - update: /no-lock/.test(c), - }) - t.matchSnapshot(tree) - const dep = `${path}/node_modules/@isaacs/shrinkwrapped-dependency` - t.equal(fs.statSync(`${dep}/package.json`).isFile(), true, 'has package.json') + createRegistry(t, mocks) + const arb = newArb({ path, dryRun: true }) + t.matchSnapshot(printTree(await arb.reify())) + t.throws(() => fs.statSync(resolve(path, 'node_modules'))) + t.ok(arb.diff) }) } }) -t.test('link deps already in place', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'link-dep')))) -t.test('create link deps', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'link-dep-empty')))) +t.test('link deps already in place', async t => { + createRegistry(t, false) + await t.resolveMatchSnapshot(printReified(fixture(t, 'link-dep'))) +}) + +t.test('create link deps', async t => { + createRegistry(t, false) + await t.resolveMatchSnapshot(printReified(fixture(t, 'link-dep-empty'))) +}) + +t.test('link meta deps, fresh install', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(fixture(t, 'link-meta-deps-empty'))) +}) -t.test('link meta deps, fresh install', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'link-meta-deps-empty')))) -t.test('link meta deps, update', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'link-meta-deps'), { +t.test('link meta deps, update', async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(fixture(t, 'link-meta-deps'), { // use legacy nesting so we leave the link nested legacyNesting: true, add: [ '@isaacs/testing-link-dep@2', '@isaacs/testing-link-dev-dep@2', ], - }))) + })) +}) -t.test('update a child of a node with bundled deps', t => { +t.test('update a child of a node with bundled deps', async t => { const path = fixture(t, 'testing-bundledeps-legacy-bundling') - return t.resolveMatchSnapshot(printReified(path, { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(path, { update: ['@isaacs/testing-bundledeps-c'], installStrategy: 'nested', })) }) -t.test('update a node without updating a child that has bundle deps', t => { +t.test('update a node without updating a child that has bundle deps', async t => { const path = fixture(t, 'testing-bundledeps-3') - return t.resolveMatchSnapshot(printReified(path, { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(path, { update: ['@isaacs/testing-bundledeps-parent'], save: false, })) }) -t.test('optional dependency failures', t => { +t.test('optional dependency failures', async t => { const cases = [ 'optional-dep-tgz-missing', 'optional-metadep-tgz-missing', @@ -552,22 +607,28 @@ t.test('optional dependency failures', t => { 'optional-metadep-postinstall-fail', 'optional-metadep-allinstall-fail', ] - t.plan(cases.length * 2) - let p = [...cases.map(c => t.test(`${c} save=false`, t => - t.resolveMatchSnapshot(printReified(fixture(t, c), - { update: true, save: false }))))] - - // npm update --save - p = [...cases.map(c => t.test(`${c} save=true`, t => - t.resolveMatchSnapshot(printReified(fixture(t, c), - { update: true, save: true }))))] - return p + // t.plan(cases.length * 2) + for (const c of cases) { + await t.test(`${c} save=false`, async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(fixture(t, c), + { update: true, save: false, dangerouslyAllowAllScripts: true })) + }) + // npm update --save + await t.test(`${c} save=true`, async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified(fixture(t, c), + { update: true, save: true, dangerouslyAllowAllScripts: true })) + }) + } }) -t.test('failure to fetch prod dep is failure', t => - t.rejects(printReified(fixture(t, 'prod-dep-tgz-missing')))) +t.test('failure to fetch prod dep is failure', async t => { + createRegistry(t, true) + t.rejects(printReified(fixture(t, 'prod-dep-tgz-missing'))) +}) -t.test('failing script means install failure, unless ignoreScripts', t => { +t.test('failing script means install failure, unless ignoreScripts', async t => { const cases = [ 'prod-dep-preinstall-fail', 'prod-dep-install-fail', @@ -575,28 +636,34 @@ t.test('failing script means install failure, unless ignoreScripts', t => { 'prod-dep-allinstall-fail', ] - t.plan(cases.length * 2) - - cases.forEach(c => { - t.test(c, t => - t.rejects(printReified(fixture(t, c)))) - t.test(c + ' --ignore-scripts', t => - t.resolveMatchSnapshot(printReified( - fixture(t, c), { ignoreScripts: true }))) - }) + for (const c of cases) { + await t.test(c, async t => { + createRegistry(t, true) + t.rejects(printReified(fixture(t, c), { dangerouslyAllowAllScripts: true })) + }) + await t.test(`${c} --ignore-scripts`, async t => { + createRegistry(t, true) + await t.resolveMatchSnapshot(printReified( + fixture(t, c), { ignoreScripts: true })) + }) + } }) -t.test('link metadep', t => { +t.test('link metadep', async t => { const cases = [ 'cli-750', 'cli-750-fresh', ] - t.plan(cases.length) - cases.forEach(c => t.test(c, t => - t.resolveMatchSnapshot(printReified(fixture(t, c))))) + for (const c of cases) { + createRegistry(t, false) + await t.test(c, async t => { + t.resolveMatchSnapshot(printReified(fixture(t, c))) + }) + } }) t.test('warn on reifying deprecated dependency', t => { + createRegistry(t, true) const a = newArb({ path: fixture(t, 'deprecated-dep'), lockfileVersion: 1, @@ -616,6 +683,7 @@ t.test('warn on reifying deprecated dependency', t => { t.test('rollbacks', { buffered: false }, t => { t.test('fail retiring shallow nodes', t => { const path = fixture(t, 'testing-bundledeps-3') + createRegistry(t, true) const a = newArb({ path, installStrategy: 'nested' }) const expect = new Error('rename fail') const kRenamePath = Symbol.for('renamePath') @@ -643,6 +711,7 @@ t.test('rollbacks', { buffered: false }, t => { t.test('fail retiring nodes because rm fails after eexist', t => { const path = fixture(t, 'testing-bundledeps-3') + createRegistry(t, true) const a = newArb({ path, installStrategy: 'nested' }) const eexist = new Error('rename fail') eexist.code = 'EEXIST' @@ -680,6 +749,7 @@ t.test('rollbacks', { buffered: false }, t => { t.test('fail retiring node, but then rm fixes it', async t => { const path = fixture(t, 'testing-bundledeps-3') + createRegistry(t, true) const a = newArb({ path, installStrategy: 'nested' }) const eexist = new Error('rename fail') eexist.code = 'EEXIST' @@ -705,9 +775,76 @@ t.test('rollbacks', { buffered: false }, t => { return printTree(tree) }) + t.test('fail retiring nodes because rm fails after enotempty', t => { + const path = fixture(t, 'testing-bundledeps-3') + createRegistry(t, true) + const a = newArb({ path, installStrategy: 'nested' }) + const enotempty = new Error('rename fail') + enotempty.code = 'ENOTEMPTY' + const kRenamePath = Symbol.for('renamePath') + const renamePath = a[kRenamePath] + a[kRenamePath] = (from, to) => { + a[kRenamePath] = renamePath + failRename = enotempty + failRm = true + return a[kRenamePath](from, to) + } + const kRollback = Symbol.for('rollbackRetireShallowNodes') + const rollbackRetireShallowNodes = a[kRollback] + let rolledBack = false + a[kRollback] = er => { + rolledBack = true + failRename = new Error('some other error') + failRm = false + t.match(er, new Error('rm fail')) + a[kRollback] = rollbackRetireShallowNodes + return a[kRollback](er).then(er => { + failRename = null + return er + }, er => { + failRename = null + throw er + }) + } + + return t.rejects(a.reify({ + update: ['@isaacs/testing-bundledeps-parent'], + }), new Error('rm fail')) + .then(() => t.equal(rolledBack, true, 'rolled back')) + }) + + t.test('fail retiring node with enotempty, but then rm fixes it', async t => { + const path = fixture(t, 'testing-bundledeps-3') + createRegistry(t, true) + const a = newArb({ path, installStrategy: 'nested' }) + const enotempty = new Error('rename fail') + enotempty.code = 'ENOTEMPTY' + const kRenamePath = Symbol.for('renamePath') + const renamePath = a[kRenamePath] + a[kRenamePath] = (from, to) => { + a[kRenamePath] = renamePath + failRenameOnce = enotempty + return a[kRenamePath](from, to) + } + const kRollback = Symbol.for('rollbackRetireShallowNodes') + const rollbackRetireShallowNodes = a[kRollback] + a[kRollback] = er => { + t.fail('should not roll back!') + a[kRollback] = rollbackRetireShallowNodes + return a[kRollback](er) + } + + const tree = await a.reify({ + update: ['@isaacs/testing-bundledeps-parent'], + save: false, + }) + return printTree(tree) + }) + t.test('fail creating sparse tree', t => { t.teardown(() => failMkdir = null) const path = fixture(t, 'testing-bundledeps-3') + createRegistry(t, true) const a = newArb({ path, installStrategy: 'nested' }) const kCreateST = Symbol.for('createSparseTree') const createSparseTree = a[kCreateST] @@ -733,6 +870,7 @@ t.test('rollbacks', { buffered: false }, t => { failMkdir = null failRm = null const path = fixture(t, 'testing-bundledeps-3') + createRegistry(t, true) const a = newArb({ path, installStrategy: 'nested' }) const kCreateST = Symbol.for('createSparseTree') @@ -779,34 +917,9 @@ t.test('rollbacks', { buffered: false }, t => { .then(() => failRm = false) }) - t.test('fail loading shrinkwraps and updating trees', t => { - const path = fixture(t, 'shrinkwrapped-dep-no-lock-empty') - const a = newArb({ path, installStrategy: 'nested' }) - const kLoadSW = Symbol.for('loadShrinkwrapsAndUpdateTrees') - const loadShrinkwrapsAndUpdateTrees = a[kLoadSW] - a[kLoadSW] = seen => { - a[kLoadSW] = loadShrinkwrapsAndUpdateTrees - const kDiff = Symbol.for('diffTrees') - const diffTrees = a[kDiff] - a[kDiff] = () => { - a[kDiff] = diffTrees - return Promise.reject(new Error('poop')) - } - return a[kLoadSW](seen) - } - const kRollback = Symbol.for('rollbackCreateSparseTree') - const rollbackCreateSparseTree = a[kRollback] - a[kRollback] = er => { - t.match(er, new Error('poop')) - a[kRollback] = rollbackCreateSparseTree - return a[kRollback](er) - } - - return t.rejects(a.reify(), new Error('poop')) - }) - t.test('fail loading bundles and updating trees', t => { const path = fixture(t, 'two-bundled-deps') + createRegistry(t, true) const a = newArb({ path, installStrategy: 'nested' }) const kLoadBundles = Symbol.for('loadBundlesAndUpdateTrees') const loadBundlesAndUpdateTrees = a[kLoadBundles] @@ -825,6 +938,7 @@ t.test('rollbacks', { buffered: false }, t => { t.test('fail unpacking new modules', t => { const path = fixture(t, 'two-bundled-deps') + createRegistry(t, true) const a = newArb({ path, installStrategy: 'nested' }) const kUnpack = Symbol.for('unpackNewModules') const unpackNewModules = a[kUnpack] @@ -843,6 +957,7 @@ t.test('rollbacks', { buffered: false }, t => { t.test('fail moving back retired unchanged', t => { const path = fixture(t, 'testing-bundledeps-3') + createRegistry(t, true) const a = newArb({ path, installStrategy: 'nested' }) const kMoveback = Symbol.for('moveBackRetiredUnchanged') @@ -871,6 +986,7 @@ t.test('rollbacks', { buffered: false }, t => { t.test('fail removing retired and deleted nodes', t => { const path = fixture(t, 'testing-bundledeps-3') + createRegistry(t, true) const a = newArb({ path, installStrategy: 'nested' }) const kRemove = Symbol.for('removeTrash') const removeRetiredAndDeletedNodes = a[kRemove] @@ -907,6 +1023,7 @@ t.test('rollbacks', { buffered: false }, t => { t.test('saving the ideal tree', t => { const kSaveIdealTree = Symbol.for('saveIdealTree') t.test('save=false', async t => { + createRegistry(t, false) // doesn't actually do anything, just for coverage. // if it wasn't an early exit, it'd blow up and throw // an error though. @@ -916,6 +1033,7 @@ t.test('saving the ideal tree', t => { }) t.test('save some stuff', t => { + createRegistry(t, false) const pkg = { bundleDependencies: ['a', 'b', 'c'], dependencies: { @@ -1077,7 +1195,8 @@ t.test('saving the ideal tree', t => { t.test('scoped registries', async t => { const path = t.testdir() - // this is a very artifical test that is setting a lot of internal things + // TODO + // this is a very artificial test that is setting a lot of internal things // up so that we assert that the intended behavior of sending right // resolved data for pacote.extract is working as intended, alternatively // we might prefer to replace this with a proper parallel alternative @@ -1100,8 +1219,7 @@ t.test('scoped registries', async t => { const a = new ArboristMock({ audit: false, path, - cache, - registry, + cache: path, }) const kReify = Symbol.for('reifyNode') a.addTracker('reify') @@ -1131,6 +1249,7 @@ t.test('bin links adding and removing', t => { t.test('global style', t => { const path = t.testdir() + createRegistry(t, true) const nm = resolve(path, 'node_modules') const rbinPart = '.bin/rimraf' + (process.platform === 'win32' ? '.cmd' : '') @@ -1140,7 +1259,7 @@ t.test('global style', t => { .then(() => t.strictSame(fs.readdirSync(nm).sort(), ['.bin', '.package-lock.json', 'rimraf'])) }) -t.test('global', t => { +t.test('global', async t => { const isWindows = process.platform === 'win32' const path = t.testdir({ lib: {} }) @@ -1151,43 +1270,53 @@ t.test('global', t => { const rimrafBin = resolve(binTarget, isWindows ? 'rimraf.cmd' : 'rimraf') const semverBin = resolve(binTarget, isWindows ? 'semver.cmd' : 'semver') - t.test('add rimraf', t => - reify(lib, { add: ['rimraf@2'], global: true }) + await t.test('add rimraf', async t => { + createRegistry(t, true) + await reify(lib, { add: ['rimraf@2'], global: true }) .then(() => fs.statSync(rimrafBin)) - .then(() => t.strictSame(fs.readdirSync(nm), ['rimraf']))) + .then(() => t.strictSame(fs.readdirSync(nm), ['rimraf'])) + }) - t.test('add semver', t => - reify(lib, { add: ['semver@6.3.0'], global: true }) + await t.test('add semver', async t => { + createRegistry(t, true) + await reify(lib, { add: ['semver@6.3.0'], global: true }) .then(() => fs.statSync(rimrafBin)) .then(() => fs.statSync(semverBin)) - .then(() => t.strictSame(fs.readdirSync(nm).sort(), ['rimraf', 'semver']))) + .then(() => t.strictSame(fs.readdirSync(nm).sort(), ['rimraf', 'semver'])) + }) - t.test('remove semver', t => - reify(lib, { rm: ['semver'], global: true }) + await t.test('remove semver', async t => { + createRegistry(t, false) + await reify(lib, { rm: ['semver'], global: true }) .then(() => fs.statSync(rimrafBin)) .then(() => t.throws(() => fs.statSync(semverBin))) - .then(() => t.strictSame(fs.readdirSync(nm), ['rimraf']))) + .then(() => t.strictSame(fs.readdirSync(nm), ['rimraf'])) + }) - t.test('remove rimraf', t => - reify(lib, { rm: ['rimraf'], global: true }) + await t.test('remove rimraf', async t => { + createRegistry(t, false) + await reify(lib, { rm: ['rimraf'], global: true }) .then(() => t.throws(() => fs.statSync(rimrafBin))) .then(() => t.throws(() => fs.statSync(semverBin))) - .then(() => t.strictSame(fs.readdirSync(nm), []))) + .then(() => t.strictSame(fs.readdirSync(nm), [])) + }) - t.test('add without bin links', t => - reify(lib, { add: ['rimraf@2'], global: true, binLinks: false }) + await t.test('add without bin links', async t => { + createRegistry(t, true) + await reify(lib, { add: ['rimraf@2'], global: true, binLinks: false }) .then(() => t.throws(() => fs.statSync(rimrafBin))) .then(() => t.throws(() => fs.statSync(semverBin))) - .then(() => t.strictSame(fs.readdirSync(nm), ['rimraf']))) - - t.end() + .then(() => t.strictSame(fs.readdirSync(nm), ['rimraf'])) + }) }) -t.test('workspaces', t => { - t.test('reify simple-workspaces', t => - t.resolveMatchSnapshot(printReified(fixture(t, 'workspaces-simple')), 'should reify simple workspaces')) +t.test('workspaces', async t => { + await t.test('reify simple-workspaces', async t => { + createRegistry(t, false) + await t.resolveMatchSnapshot(printReified(fixture(t, 'workspaces-simple')), 'should reify simple workspaces') + }) - t.test('reify workspaces omit dev dependencies', async t => { + await t.test('reify workspaces omit dev dependencies', async t => { const runCase = async (t, opts) => { const path = fixture(t, 'workspaces-conflicting-dev-deps') const rootAjv = resolve(path, 'node_modules/ajv/package.json') @@ -1208,6 +1337,7 @@ t.test('workspaces', t => { } await t.test('default', async t => { + createRegistry(t, false) const { root, a, b } = await runCase(t) t.equal(root.exists(), false, 'root') t.equal(a.exists(), false, 'a') @@ -1215,13 +1345,15 @@ t.test('workspaces', t => { }) await t.test('workspaces only', async t => { + createRegistry(t, false) const { root, a, b } = await runCase(t, { workspaces: ['a'] }) - t.equal(root.exists(), false, 'root') + t.equal(root.exists(), true, 'root') t.equal(a.exists(), false, 'a') t.equal(b.exists(), true, 'b') }) await t.test('workspaces + root', async t => { + createRegistry(t, false) const { root, a, b } = await runCase(t, { workspaces: ['a'], includeWorkspaceRoot: true }) t.equal(root.exists(), false, 'root') t.equal(a.exists(), false, 'a') @@ -1229,6 +1361,7 @@ t.test('workspaces', t => { }) await t.test('disable workspaces', async t => { + createRegistry(t, false) const { root, a, b } = await runCase(t, { workspacesEnabled: false }) t.equal(root.exists(), false, 'root') t.equal(a.exists(), true, 'a') @@ -1236,14 +1369,23 @@ t.test('workspaces', t => { }) }) - t.test('reify workspaces lockfile', async t => { + await t.test('reify workspaces lockfile', async t => { const path = fixture(t, 'workspaces-simple') + createRegistry(t, false) await reify(path) t.matchSnapshot(require(path + '/package-lock.json'), 'should lock workspaces config') }) - t.test('reify workspaces bin files', t => { + await t.test('reify workspaces with overrides', async t => { + const path = fixture(t, 'workspaces-with-overrides') + createRegistry(t, true) + await reify(path, { workspacesEnabled: true, workspaces: ['ws'] }) + t.matchSnapshot(require(path + '/package-lock.json'), 'should retain override version (4.1.3)') + }) + + await t.test('reify workspaces bin files', t => { const path = fixture(t, 'workspaces-link-bin') + createRegistry(t, false) const bins = [ resolve(path, 'node_modules/.bin/a'), @@ -1264,29 +1406,32 @@ t.test('workspaces', t => { .then(checkBin) }) - t.test('reify from an actual loaded workspace env', t => - t.resolveMatchSnapshot( + await t.test('reify from an actual loaded workspace env', async t => { + createRegistry(t, false) + await t.resolveMatchSnapshot( printReified(fixture(t, 'workspaces-non-simplistic')), 'should not clean up entire nm folder for no reason' - )) + ) + }) - t.test('add new workspaces dep', async t => { + await t.test('add new workspaces dep', async t => { + createRegistry(t, true) const path = fixture(t, 'workspaces-add-new-dep') await reify(path) t.matchSnapshot(require(path + '/package-lock.json'), 'should update package-lock with new added dep') }) - t.test('root as-a-workspace', async t => { + await t.test('root as-a-workspace', async t => { + createRegistry(t, true) const path = fixture(t, 'workspaces-root-linked') await reify(path) t.matchSnapshot(require(path + '/package-lock.json'), 'should produce expected package-lock file') }) - - t.end() }) t.test('reify from old package-lock with bins', async t => { const path = fixture(t, 'old-package-lock-with-bins') + createRegistry(t, true) await reify(path, {}) t.matchSnapshot( @@ -1311,6 +1456,7 @@ t.test('fail early if bins will conflict', async t => { semver: 'this is not the linked bin', }, }) + createRegistry(t, true) const arb = newArb({ global: true, path: `${path}/lib`, @@ -1321,9 +1467,10 @@ t.test('fail early if bins will conflict', async t => { await t.rejects(arb.reify({ add: ['semver'] }), { code: 'EEXIST' }) }) -t.test('add a dep present in the tree, with v1 shrinkwrap', async t => { +t.test('add a dep present in the tree, with v1 lockfile', async t => { // https://github.com/npm/arborist/issues/70 const path = fixture(t, 'old-package-lock') + createRegistry(t, true) await reify(path, { add: ['wrappy'] }) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) }) @@ -1337,6 +1484,7 @@ t.test('store files with a custom indenting', async t => { const path = t.testdir({ 'package.json': tabIndentedPackageJson, }) + createRegistry(t, true) await reify(path) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) t.matchSnapshot(fs.readFileSync(path + '/package-lock.json', 'utf8')) @@ -1344,6 +1492,7 @@ t.test('store files with a custom indenting', async t => { t.test('do not rewrite valid package.json shorthands', async t => { const path = fixture(t, 'package-json-shorthands') + createRegistry(t, false) await reify(path) const res = require(path + '/package.json') t.equal(res.bin, './index.js', 'should not rewrite bin property') @@ -1352,28 +1501,33 @@ t.test('do not rewrite valid package.json shorthands', async t => { t.test('modules bundled by the root should be installed', async t => { const path = fixture(t, 'root-bundler') + createRegistry(t, false) await reify(path) t.matchSnapshot(fs.readFileSync(path + '/node_modules/child/package.json', 'utf8')) }) t.test('add a new pkg to a prefix that needs to be mkdirpd', async t => { - const path = resolve(t.testdir(), 'missing/path/to/root') - const tree = await reify(path, { add: ['abbrev'] }) - t.matchSnapshot( - printTree(tree), - 'should output a successful tree in mkdirp folder' - ) - t.matchSnapshot( - fs.readFileSync(path + '/package.json', 'utf8'), - 'should place expected package.json file into place' - ) - t.matchSnapshot( - fs.readFileSync(path + '/package-lock.json', 'utf8'), - 'should place expected lockfile file into place' - ) + await t.test('not dry run', async t => { + const path = resolve(t.testdir(), 'missing/path/to/root') + createRegistry(t, true) + const tree = await reify(path, { add: ['abbrev'] }) + t.matchSnapshot( + printTree(tree), + 'should output a successful tree in mkdirp folder' + ) + t.matchSnapshot( + fs.readFileSync(path + '/package.json', 'utf8'), + 'should place expected package.json file into place' + ) + t.matchSnapshot( + fs.readFileSync(path + '/package-lock.json', 'utf8'), + 'should place expected lockfile file into place' + ) + }) - t.test('dry run scenarios', async t => { + await t.test('dry run scenarios', async t => { const path = resolve(t.testdir(), 'missing/path/to/root') + createRegistry(t, false) try { await reify(path, { add: ['abbrev'], dryRun: true }) @@ -1391,6 +1545,7 @@ t.test('add a new pkg to a prefix that needs to be mkdirpd', async t => { t.test('do not delete root-bundled deps in global update', async t => { const path = t.testdir() + createRegistry(t, false) const file = resolve(__dirname, '../fixtures/bundle.tgz') await reify(path, { global: true, add: [`file:${file}`] }) const depPJ = resolve(path, 'node_modules/bundle/node_modules/dep/package.json') @@ -1401,6 +1556,7 @@ t.test('do not delete root-bundled deps in global update', async t => { t.test('do not excessively duplicate bundled metadeps', async t => { const path = fixture(t, 'bundle-metadep-duplication') + createRegistry(t, true) const tree = await reify(path) const hidden = path + '/node_modules/.package-lock.json' t.matchSnapshot(fs.readFileSync(hidden, 'utf8'), 'hidden lockfile') @@ -1411,12 +1567,14 @@ t.test('do not excessively duplicate bundled metadeps', async t => { t.test('do not reify root when root matches duplicated metadep', async t => { const path = fixture(t, 'test-root-matches-metadep') + createRegistry(t, true) await reify(path) fs.statSync(path + '/do-not-delete-this-file') }) t.test('reify properly with all deps when lockfile is ancient', async t => { const path = fixture(t, 'sax') + createRegistry(t, true) const tree = await reify(path) t.matchSnapshot(printTree(tree)) fs.statSync(path + '/node_modules/tap/node_modules/.bin/nyc') @@ -1428,6 +1586,7 @@ t.test('add multiple pkgs in a specific order', async t => { name: 'multiple-pkgs', }), }) + createRegistry(t, true) await reify(path, { add: ['wrappy', 'abbrev'] }) t.matchSnapshot( fs.readFileSync(path + '/package.json', 'utf8'), @@ -1447,6 +1606,7 @@ t.test('save complete lockfile on update-all', async t => { version: '1.0.0', }), }) + createRegistry(t, true) // install the older version first const lock = () => fs.readFileSync(`${path}/package-lock.json`, 'utf8') await reify(path, { add: ['abbrev@1.0.4'] }) @@ -1455,18 +1615,36 @@ t.test('save complete lockfile on update-all', async t => { t.matchSnapshot(lock(), 'should update, but not drop root metadata') }) -t.test('save proper lockfile with bins when upgrading lockfile', t => { - const completeOpts = [true, false] - completeOpts.forEach(complete => { - t.test(`complete=${complete}`, async t => { +t.test('dry-run update does not save lockfiles', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'dry-run-update-lockfile-test', + version: '1.0.0', + }), + }) + createRegistry(t, true) + await reify(path, { add: ['abbrev@1.0.4'] }) + + const lock = filename => fs.readFileSync(resolve(path, filename), 'utf8') + const packageLock = lock('package-lock.json') + const hiddenLock = lock('node_modules/.package-lock.json') + + await reify(path, { update: true, dryRun: true, save: false }) + + t.equal(lock('package-lock.json'), packageLock, 'package-lock.json unchanged') + t.equal(lock('node_modules/.package-lock.json'), hiddenLock, 'hidden lockfile unchanged') +}) + +t.test('save proper lockfile with bins when upgrading lockfile', async t => { + for (const complete of [true, false]) { + await t.test(`complete=${complete}`, async t => { const path = fixture(t, 'semver-installed-with-old-package-lock') + createRegistry(t, true) const lock = () => fs.readFileSync(`${path}/package-lock.json`, 'utf8') await reify(path, { complete }) t.matchSnapshot(lock(), 'should upgrade, with bins in place') }) - }) - - t.end() + } }) t.test('rollback if process is terminated during reify process', async t => { @@ -1506,7 +1684,6 @@ t.test('rollback if process is terminated during reify process', async t => { const methods = [ Symbol.for('retireShallowNodes'), Symbol.for('createSparseTree'), - Symbol.for('loadShrinkwrapsAndUpdateTrees'), Symbol.for('loadBundlesAndUpdateTrees'), Symbol.for('unpackNewModules'), Symbol.for('moveBackRetiredUnchanged'), @@ -1528,6 +1705,7 @@ t.test('rollback if process is terminated during reify process', async t => { }) t.test('clean install', async t => { + createRegistry(t, true) const arb = newArb({ path }) // starting from an empty folder, ends up empty await t.rejects(arb.reify(), { @@ -1551,6 +1729,7 @@ t.test('rollback if process is terminated during reify process', async t => { name: 'abbrev', version: '0.0.0', })) + createRegistry(t, true) const arb = newArb({ path }) await t.rejects(arb.reify({ add: ['abbrev@1.1.1'] }), { message: 'process terminated', @@ -1601,8 +1780,9 @@ t.test('warn and correct if damaged data in lockfile', async t => { }), }) - t.test('first pass logs', async t => { + await t.test('first pass logs', async t => { const getLogs = warningTracker() + createRegistry(t, false) await reify(path) t.strictSame(getLogs(), [ [ @@ -1617,8 +1797,9 @@ t.test('warn and correct if damaged data in lockfile', async t => { t.matchSnapshot(fs.readFileSync(path + '/package-lock.json', 'utf8'), '"fixed" lockfile') }) - t.test('second pass just does the right thing', async t => { + await t.test('second pass just does the right thing', async t => { const getLogs = warningTracker() + createRegistry(t, true) await reify(path) t.strictSame(getLogs(), [], 'no warnings this time') t.matchSnapshot(fs.readFileSync(path + '/package-lock.json', 'utf8'), 'actually fixed lockfile') @@ -1627,6 +1808,7 @@ t.test('warn and correct if damaged data in lockfile', async t => { t.test('properly update one module when multiple are present', async t => { const path = t.testdir({}) + createRegistry(t, true) const abbrevpj = resolve(path, 'node_modules/abbrev/package.json') const oncepj = resolve(path, 'node_modules/once/package.json') @@ -1656,6 +1838,7 @@ t.test('saving should not replace file: dep with version', async t => { }, 'package.json': JSON.stringify({}), }) + createRegistry(t, false) process.chdir(path) const pj = resolve(path, 'package.json') @@ -1729,6 +1912,7 @@ t.test('filtered reification in workspaces', async t => { }, }, }) + createRegistry(t, true) const hiddenLock = resolve(path, 'node_modules/.package-lock.json') @@ -1798,46 +1982,157 @@ t.test('filtered reification in workspaces', async t => { 'hidden lockfile - foo/x linked, c, old x, removed a') }) -t.test('project with bundled deps and a link dep on itself', async t => { - const pkg = { - name: '@isaacs/testing-bundle-self-link', - version: '1.0.0', - bin: { - 'testing-bundle-self-link': 'bin.js', - }, - scripts: { - test: 'testing-bundle-self-link', - postinstall: 'testing-bundle-self-link', - }, - bundleDependencies: [ - 'abbrev', - ], - dependencies: { - '@isaacs/testing-bundle-self-link': 'file:.', - abbrev: '', - }, +// Regression for https://github.com/npm/cli/issues/5463: a workspace whose directory has been deleted should not leave behind an extraneous entry (or a lingering reference in the root's workspaces array) in package-lock.json after `npm install`. +t.test('removed workspace is pruned from package-lock.json', async t => { + const setup = () => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'remove-ws', + version: '1.0.0', + workspaces: ['packages/a', 'packages/b'], + }), + packages: { + a: { + 'package.json': JSON.stringify({ name: 'a', version: '1.0.0' }), + }, + b: { + 'package.json': JSON.stringify({ name: 'b', version: '1.0.0' }), + }, + }, + }) + return path } - const path = t.testdir({ - 'package.json': JSON.stringify(pkg), - 'bin.js': `#!/usr/bin/env node -console.log('TAP version 13') -console.log('1..1') -console.log('ok 1 - this is fine') -`, - }) - t.matchSnapshot(await printReified(path), 'result') - t.resolves(runScript({ - event: 'test', - path, - pkg, + // The lockfile's root.workspaces array mirrors package.json verbatim and is intentionally not mutated here, so we only assert that orphan package/link entries are dropped. + const assertClean = (t, path, label) => { + const lock = JSON.parse(fs.readFileSync(`${path}/package-lock.json`, 'utf8')) + t.notOk(lock.packages['packages/b'], + `${label}: packages/b entry removed from lockfile`) + t.notOk(lock.packages['node_modules/b'], + `${label}: node_modules/b link removed from lockfile`) + t.notOk(lock.dependencies && lock.dependencies.b, + `${label}: dependencies.b removed from legacy lockfile`) + } + + for (const strategy of ['hoisted', 'linked']) { + t.test(`${strategy} strategy, package.json kept stale`, async t => { + const path = setup() + createRegistry(t, false) + await reify(path, { installStrategy: strategy }) + // Remove only the directory, leave package.json's workspaces array alone. + fs.rmSync(`${path}/packages/b`, { recursive: true, force: true }) + await reify(path, { installStrategy: strategy }) + assertClean(t, path, `${strategy}/keep-pj`) + }) + + t.test(`${strategy} strategy, package.json updated`, async t => { + const path = setup(strategy) + createRegistry(t, false) + await reify(path, { installStrategy: strategy }) + fs.rmSync(`${path}/packages/b`, { recursive: true, force: true }) + fs.writeFileSync(`${path}/package.json`, JSON.stringify({ + name: 'remove-ws', + version: '1.0.0', + workspaces: ['packages/a'], + })) + await reify(path, { installStrategy: strategy }) + assertClean(t, path, `${strategy}/clean-pj`) + }) + } +}) + +// Regression for https://github.com/npm/cli/issues/9433: a file: dependency +// that itself has a file: dependency leaves a nested extraneous fsChild. That +// entry must stay in package-lock.json, otherwise `npm ci` reports the nested +// dep as missing and refuses to install. +t.test('nested file: dep keeps extraneous fsChild in package-lock.json', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'c', + version: '1.0.0', + private: true, + dependencies: { a: 'file:lib/a', b: 'file:lib/b' }, + }), + lib: { + a: { 'package.json': JSON.stringify({ name: 'a', version: '1.0.0', private: true }) }, + b: { + 'package.json': JSON.stringify({ + name: 'b', + version: '1.0.0', + private: true, + dependencies: { a: 'file:lib/a' }, + }), + lib: { + a: { 'package.json': JSON.stringify({ name: 'a', version: '1.0.0', private: true }) }, + }, + }, + }, + }) + createRegistry(t, false) + await reify(path) + + const lock = JSON.parse(fs.readFileSync(`${path}/package-lock.json`, 'utf8')) + t.match(lock.packages['lib/b/lib/a'], { version: '1.0.0', extraneous: true }, + 'nested file: dep is recorded as an extraneous entry in the lockfile') + + // Mirror the `npm ci` sync check: every node in the ideal tree built from + // package.json must be present in the virtual tree loaded from the lockfile. + const virtual = newArb({ path }) + await virtual.loadVirtual() + const virtualInventory = new Map(virtual.virtualTree.inventory) + const ideal = newArb({ path }) + await ideal.buildIdealTree() + const missing = [] + for (const [loc, node] of ideal.idealTree.inventory.entries()) { + if (!virtualInventory.has(loc)) { + missing.push(`${node.name}@${node.version}`) + } + } + t.same(missing, [], 'lockfile is in sync with package.json, so npm ci would succeed') +}) + +t.test('project with bundled deps and a link dep on itself', async t => { + const pkg = { + name: '@isaacs/testing-bundle-self-link', + version: '1.0.0', + bin: { + 'testing-bundle-self-link': 'bin.js', + }, + scripts: { + test: 'testing-bundle-self-link', + postinstall: 'testing-bundle-self-link', + }, + bundleDependencies: [ + 'abbrev', + ], + dependencies: { + '@isaacs/testing-bundle-self-link': 'file:.', + abbrev: '', + }, + } + const path = t.testdir({ + 'package.json': JSON.stringify(pkg), + 'bin.js': `#!/usr/bin/env node +console.log('TAP version 13') +console.log('1..1') +console.log('ok 1 - this is fine') +`, + }) + createRegistry(t, true) + + t.matchSnapshot(await printReified(path), 'result') + t.resolves(runScript({ + event: 'test', + path, + pkg, stdio: 'pipe', }), 'test result') }) t.test('running lifecycle scripts of unchanged link nodes on reify', async t => { const path = fixture(t, 'link-dep-lifecycle-scripts') - t.matchSnapshot(await printReified(path), 'result') + createRegistry(t, false) + t.matchSnapshot(await printReified(path, { allowScripts: { 'file:../a': true } }), 'result') t.ok(fs.lstatSync(resolve(path, 'a/a-prepare')).isFile(), 'should run prepare lifecycle scripts for links directly linked to the tree') @@ -1852,6 +2147,7 @@ t.test('save-prod, with optional', async t => { optionalDependencies: { abbrev: '*' }, }), }) + createRegistry(t, true) const arb = newArb({ path }) await arb.reify({ add: ['abbrev'], saveType: 'prod' }) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) @@ -1863,6 +2159,7 @@ t.test('saveBundle', async t => { dependencies: { abbrev: '*' }, }), }) + createRegistry(t, true) const arb = newArb({ path }) await arb.reify({ add: ['abbrev'], saveType: 'prod', saveBundle: true }) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) @@ -1875,6 +2172,7 @@ t.test('no saveType: dev w/ compatible peer', async t => { devDependencies: { abbrev: '*' }, }), }) + createRegistry(t, true) const arb = newArb({ path }) await arb.reify({ add: ['abbrev'] }) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) @@ -1887,6 +2185,7 @@ t.test('no saveType: dev w/ incompatible peer', async t => { devDependencies: { abbrev: '*' }, }), }) + createRegistry(t, true) const arb = newArb({ path }) await arb.reify({ add: ['abbrev'] }) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) @@ -1899,6 +2198,7 @@ t.test('no saveType: dev w/ compatible optional', async t => { devDependencies: { abbrev: '*' }, }), }) + createRegistry(t, true) const arb = newArb({ path }) await arb.reify({ add: ['abbrev'] }) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) @@ -1911,6 +2211,7 @@ t.test('no saveType: dev w/ incompatible optional', async t => { devDependencies: { abbrev: '*' }, }), }) + createRegistry(t, true) const arb = newArb({ path }) await arb.reify({ add: ['abbrev'] }) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) @@ -1923,6 +2224,7 @@ t.test('no saveType: prod w/ peer', async t => { dependencies: { abbrev: '*' }, }), }) + createRegistry(t, true) const arb = newArb({ path }) await arb.reify({ add: ['abbrev'] }) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) @@ -1934,6 +2236,7 @@ t.test('no saveType: peer only', async t => { peerDependencies: { abbrev: '*' }, }), }) + createRegistry(t, true) const arb = newArb({ path }) await arb.reify({ add: ['abbrev'] }) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) @@ -1945,6 +2248,7 @@ t.test('no saveType: optional only', async t => { optionalDependencies: { abbrev: '*' }, }), }) + createRegistry(t, true) const arb = newArb({ path }) await arb.reify({ add: ['abbrev'] }) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) @@ -1992,6 +2296,7 @@ t.test('do not delete linked targets when link omitted', async t => { const fooindex = resolve(path, 'foo/index.js') t.equal(fs.existsSync(barpj), true, 'bar package.json present') t.equal(fs.existsSync(fooindex), true, 'foo index.js present') + createRegistry(t, false) const tree = await reify(path, { omit: ['dev'] }) t.equal(fs.existsSync(barpj), true, 'bar package.json still present') t.equal(fs.existsSync(fooindex), true, 'foo index.js still present') @@ -2001,6 +2306,7 @@ t.test('do not delete linked targets when link omitted', async t => { t.test('add spec * with semver prefix range gets updated', async t => { const path = t.testdir({ 'package.json': '{}' }) + createRegistry(t, true) const arb = newArb({ path }) await arb.reify({ add: ['latest-is-prerelease'] }) t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8')) @@ -2037,6 +2343,7 @@ t.test('add deps to workspaces', async t => { t.test('no args', async t => { const path = t.testdir(fixture) + createRegistry(t, true) const tree = await reify(path) t.equal(tree.children.get('mkdirp').version, '1.0.4') t.equal(tree.children.get('a').target.children.get('mkdirp').version, '0.5.5') @@ -2047,6 +2354,7 @@ t.test('add deps to workspaces', async t => { t.test('add mkdirp 0.5.0 to b', async t => { const path = t.testdir(fixture) + createRegistry(t, true) await reify(path) const tree = await reify(path, { workspaces: ['b'], add: ['mkdirp@0.5.0'] }) t.equal(tree.children.get('mkdirp').version, '1.0.4') @@ -2059,6 +2367,7 @@ t.test('add deps to workspaces', async t => { t.test('remove mkdirp from a', async t => { const path = t.testdir(fixture) + createRegistry(t, true) await reify(path) const tree = await reify(path, { workspaces: ['a'], rm: ['mkdirp'] }) t.equal(tree.children.get('mkdirp').version, '1.0.4') @@ -2072,6 +2381,7 @@ t.test('add deps to workspaces', async t => { t.test('upgrade mkdirp in a, dedupe on root', async t => { const path = t.testdir(fixture) + createRegistry(t, true) await reify(path) const tree = await reify(path, { workspaces: ['a'], add: ['mkdirp@1'] }) t.equal(tree.children.get('mkdirp').version, '1.0.4') @@ -2085,6 +2395,7 @@ t.test('add deps to workspaces', async t => { t.test('add mkdirp 0.5.0 to b, empty start', async t => { const path = t.testdir(fixture) + createRegistry(t, true) const tree = await reify(path, { workspaces: ['b'], add: ['mkdirp@0.5.0'] }) t.equal(tree.children.get('mkdirp'), undefined) t.equal(tree.children.get('a'), undefined, 'did not even link workspace "a"') @@ -2096,6 +2407,7 @@ t.test('add deps to workspaces', async t => { t.test('remove mkdirp from a, empty start', async t => { const path = t.testdir(fixture) + createRegistry(t, true) const tree = await reify(path, { workspaces: ['a'], rm: ['mkdirp'] }) t.equal(tree.children.get('mkdirp'), undefined) t.equal(tree.children.get('a').target.children.get('mkdirp'), undefined) @@ -2108,6 +2420,7 @@ t.test('add deps to workspaces', async t => { t.test('upgrade mkdirp in a, dedupe on root, empty start', async t => { const path = t.testdir(fixture) + createRegistry(t, true) const tree = await reify(path, { workspaces: ['a'], add: ['mkdirp@1'] }) t.equal(tree.children.get('mkdirp').version, '1.0.4') t.equal(tree.children.get('a').target.children.get('mkdirp'), undefined) @@ -2120,6 +2433,7 @@ t.test('add deps to workspaces', async t => { t.test('add a to root', async t => { const path = t.testdir(fixture) + createRegistry(t, true) await reify(path) const tree = await reify(path, { add: ['a'], lockfileVersion: 3 }) t.matchSnapshot(printTree(tree), 'returned tree') @@ -2129,8 +2443,6 @@ t.test('add deps to workspaces', async t => { }) t.test('reify audit only workspace deps when reifying workspace', async t => { - const auditFile = resolve(__dirname, '../fixtures/audit-nyc-mkdirp/advisory-bulk.json') - t.teardown(advisoryBulkResponse(auditFile)) const path = t.testdir({ 'package.json': JSON.stringify({ workspaces: ['packages/*'], @@ -2156,6 +2468,8 @@ t.test('reify audit only workspace deps when reifying workspace', async t => { }, }, }) + const registry = createRegistry(t, true) + registry.audit({ results: require('../fixtures/audit-nyc-mkdirp/advisory-bulk.json') }) const arb = newArb({ path, audit: true, workspaces: ['a'] }) const tree = await arb.reify() const report = arb.auditReport.toJSON() @@ -2227,39 +2541,13 @@ t.test('update a dep when the lockfile is lying about it', async t => { }, }) + createRegistry(t, true) const tree = await reify(path) const abbrev = tree.children.get('abbrev') t.equal(abbrev.version, '1.1.1') t.equal(require(abbrev.path + '/package.json').version, '1.1.1') }) -t.test('shrinkwrap which lacks metadata updates deps', async t => { - const path = t.testdir({ - 'package.json': '{}', - }) - - const first = await reify(path, { - add: ['@isaacs/testing-shrinkwrap-abbrev@1.2.0'], - }) - const firstAbbrev = first.children.get('@isaacs/testing-shrinkwrap-abbrev') - .children.get('abbrev') - t.equal(firstAbbrev.version, '1.1.0') - - const abbrevPath = firstAbbrev.path - const abbrevpj = () => - JSON.parse(fs.readFileSync(abbrevPath + '/package.json', 'utf8')) - - t.equal(abbrevpj().version, firstAbbrev.version) - - const second = await reify(path, { - add: ['@isaacs/testing-shrinkwrap-abbrev@1.2.1'], - }) - const secondAbbrev = second.children.get('@isaacs/testing-shrinkwrap-abbrev') - .children.get('abbrev') - t.equal(secondAbbrev.version, '1.1.1') - t.equal(abbrevpj().version, secondAbbrev.version) -}) - t.test('move aside symlink clutter', async t => { // have to make the clutter manually, because we collide packages based // on case-insensitive names, so the ABBREV folder would be removed. @@ -2274,28 +2562,21 @@ t.test('move aside symlink clutter', async t => { file: 'do not delete me please', 'package.json': JSON.stringify({ name: 'ABBREV', version: '1.0.0' }), }, - 'sensitivity-test': t.fixture('symlink', './target'), + node_modules: { + ABBREV: t.fixture('symlink', '../target'), + }, }) // check to see if we're on a case-insensitive fs try { - const st = fs.lstatSync(path + '/SENSITIVITY-TEST') - t.equal(st.isSymbolicLink(), true, 'fs is case insensitive') + const st = fs.lstatSync(path + '/node_modules/abbrev') + t.equal(st.isSymbolicLink(), true, 'fs is case-insensitive') } catch (er) { - t.plan(0, 'case sensitive file system, test not relevant') + t.plan(0, 'case-sensitive file system, test not relevant') return } - const kReifyPackages = Symbol.for('reifyPackages') - const reifyPackages = Arborist.prototype[kReifyPackages] - t.teardown(() => Arborist.prototype[kReifyPackages] = reifyPackages) - Arborist.prototype[kReifyPackages] = async function () { - fs.mkdirSync(path + '/node_modules') - fs.symlinkSync('../target', path + '/node_modules/ABBREV') - Arborist.prototype[kReifyPackages] = reifyPackages - return this[kReifyPackages]() - } - + createRegistry(t, true) const tree = await printReified(path) const st = fs.lstatSync(path + '/node_modules/abbrev') t.equal(st.isSymbolicLink(), false) @@ -2335,6 +2616,7 @@ t.test('collide case-variant dep names', async t => { }, }) + createRegistry(t, true) const tree = await printReified(path) const st = fs.lstatSync(path + '/node_modules/abbrev') t.equal(st.isSymbolicLink(), false) @@ -2375,6 +2657,7 @@ t.test('node_modules may not be a symlink', async t => { }, }), }) + createRegistry(t, true) const warnings = warningTracker() const tree = await printReified(path) t.matchSnapshot(tree) @@ -2399,6 +2682,7 @@ t.test('never unpack into anything other than a real directory', async t => { }), }, }) + createRegistry(t, true) const arb = newArb({ path }) const logs = debugLogTracker() const wrappy = resolve(path, 'node_modules/once/node_modules/wrappy') @@ -2426,9 +2710,9 @@ t.test('adding an unresolvable optional dep is OK', async t => { }, }), }) + createRegistry(t, true) const tree = await reify(path, { add: ['abbrev'] }) - t.strictSame([...tree.children.values()], [], 'nothing actually added') - t.matchSnapshot(printTree(tree)) + t.equal(tree.children.size, 0, 'not added') }) t.test('includeWorkspaceRoot in addition to workspace', async t => { @@ -2460,6 +2744,7 @@ t.test('includeWorkspaceRoot in addition to workspace', async t => { }, }, }) + createRegistry(t, true) const tree = await reify(path, { includeWorkspaceRoot: true, workspaces: ['a'] }) t.matchSnapshot(printTree(tree)) t.equal(tree.inventory.query('name', 'semver').size, 0) @@ -2496,6 +2781,7 @@ t.test('no workspace', async t => { }, }, }) + createRegistry(t, true) const tree = await reify(path, { workspacesEnabled: false, workspaces: ['a', 'b'] }) t.matchSnapshot(printTree(tree)) t.equal(tree.inventory.query('name', 'semver').size, 0) @@ -2531,6 +2817,7 @@ t.test('add local dep with existing dev + peer/optional', async t => { t.teardown(() => process.chdir(cwd)) process.chdir(project) + createRegistry(t, false) const tree = await reify(project, { add: ['../dep'] }) t.matchSnapshot(printTree(tree), 'tree') @@ -2554,6 +2841,7 @@ t.test('runs dependencies script if tree changes', async (t) => { }), }) + createRegistry(t, true) await reify(path) for (const script of ['predependencies', 'dependencies', 'postdependencies']) { @@ -2572,12 +2860,20 @@ t.test('runs dependencies script if tree changes', async (t) => { t.not(fs.existsSync(expectedPath), `did not run ${script}`) } - const outputs = outputTracker() + const logs = logTracker() // reify again, this time adding a new dependency await reify(path, { foregroundScripts: true, add: ['once@^1.4.0'] }) - t.match(outputs(), [/predependencies/, /dependencies/, /postdependencies/], 'logged banners') + const banners = logs() + .filter(([level, title]) => level === 'notice' && title === 'run') + .map(([, , msg]) => msg) + .filter(msg => msg.startsWith('root@1.0.0 ')) + t.match( + banners, + [/predependencies/, /dependencies/, /postdependencies/], + 'logged banners' + ) // files should exist again for (const script of ['predependencies', 'dependencies', 'postdependencies']) { @@ -2591,6 +2887,7 @@ t.test('save package.json on update', t => { t.test('should save many deps in multiple package.json when using save=true', async t => { const path = fixture(t, 'workspaces-need-update') + createRegistry(t, true) await reify(path, { update: true, save: true }) t.same( @@ -2612,6 +2909,7 @@ t.test('save package.json on update', t => { t.test('should not save many deps in multiple package.json when using save=false', async t => { const path = fixture(t, 'workspaces-need-update') + createRegistry(t, true) await reify(path, { update: true, save: false }) t.same( @@ -2637,6 +2935,7 @@ t.test('save package.json on update', t => { t.test('should not save any with save=false and package-lock=false', async t => { const path = fixture(t, 'workspaces-need-update') + createRegistry(t, true) await reify(path, { update: true, save: false, packageLock: false }) t.same( @@ -2662,6 +2961,7 @@ t.test('save package.json on update', t => { t.test('should update named dep across multiple package.json using save=true', async t => { const path = fixture(t, 'workspaces-need-update') + createRegistry(t, true) await reify(path, { update: ['abbrev'], save: true }) t.same( @@ -2690,6 +2990,7 @@ t.test('save package.json on update', t => { t.test('should update single named dep across multiple package.json using save=true', async t => { const path = fixture(t, 'workspaces-need-update') + createRegistry(t, true) await reify(path, { update: ['once'], save: true }) t.same( @@ -2718,6 +3019,7 @@ t.test('save package.json on update', t => { t.test('should preserve exact ranges', async t => { const path = fixture(t, 'update-exact-version') + createRegistry(t, true) await reify(path, { update: true, save: true }) t.equal( @@ -2736,6 +3038,7 @@ t.test('save package.json on update', t => { }), }) + createRegistry(t, true) await reify(path, { update: true, save: true }) t.equal( @@ -2764,6 +3067,7 @@ t.test('save package.json on update', t => { }, }) + createRegistry(t, false) await t.resolves(reify(resolve(path, 'one'), { update: true, save: true, workspaces: [] })) t.equal( @@ -2799,6 +3103,7 @@ t.test('installLinks', (t) => { }, }) + createRegistry(t, false) await reify(resolve(path, 'a'), { installLinks: true }) const installedB = fs.lstatSync(resolve(path, 'a/node_modules/b')) @@ -2828,6 +3133,7 @@ t.test('installLinks', (t) => { }, }) + createRegistry(t, false) await reify(resolve(path, 'a'), { installLinks: false }) const installedB = fs.lstatSync(resolve(path, 'a/node_modules/b')) @@ -2857,6 +3163,7 @@ t.test('installLinks', (t) => { }, }) + createRegistry(t, false) await reify(resolve(path, 'a'), { installLinks: false, save: true }) const firstB = fs.lstatSync(resolve(path, 'a/node_modules/b')) @@ -2891,6 +3198,7 @@ t.test('installLinks', (t) => { }, }) + createRegistry(t, false) await reify(resolve(path, 'a'), { installLinks: true }) const firstB = fs.lstatSync(resolve(path, 'a/node_modules/b')) @@ -2928,6 +3236,7 @@ t.test('installLinks', (t) => { }, }) + createRegistry(t, true) await reify(resolve(path, 'a'), { installLinks: true }) const installedB = fs.lstatSync(resolve(path, 'a/node_modules/b')) @@ -2973,6 +3282,7 @@ t.test('installLinks', (t) => { }, }) + createRegistry(t, true) await reify(resolve(path, 'a'), { installLinks: true }) const installedB = fs.lstatSync(resolve(path, 'a/node_modules/b')) @@ -2988,7 +3298,76 @@ t.test('installLinks', (t) => { t.end() }) -t.only('should preserve exact ranges, missing actual tree', async (t) => { +t.test('root overrides with file: paths are visible to workspaces', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + workspaces: ['hello', 'nested/goodbye'], + dependencies: {}, + overrides: { + print: 'file:./print', + }, + }), + hello: { + 'package.json': JSON.stringify({ + name: 'hello', + version: '1.0.0', + dependencies: { + print: '../print', + }, + }), + }, + nested: { + goodbye: { + 'package.json': JSON.stringify({ + name: 'second', + version: '1.0.0', + dependencies: { + print: '../print', + }, + }), + }, + }, + print: { + 'package.json': JSON.stringify({ + name: 'print', + version: '1.0.0', + main: 'index.js', + }), + }, + }) + + createRegistry(t, false) + await reify(path) + + const printSymlink = fs.readlinkSync(resolve(path, 'node_modules/print')) + const secondSymlink = fs.readlinkSync(resolve(path, 'node_modules/second')) + + // Create a platform-agnostic way to compare symlink targets + const normalizeLinkTarget = target => { + if (process.platform === 'win32') { + // For Windows: convert absolute paths to relative and normalize slashes + const linkDir = dirname(resolve(path, 'node_modules/print')) + return relative(linkDir, target).replace(/\\/g, '/') + } + // For Unix: already a relative path + return target + } + + t.equal( + normalizeLinkTarget(printSymlink), + '../print', + 'print symlink points to ../print (normalized for platform)' + ) + + t.equal( + normalizeLinkTarget(secondSymlink), + '../nested/goodbye', + 'print symlink points to ../nested/goodbye (normalized for platform)' + ) +}) + +t.test('should preserve exact ranges, missing actual tree', async (t) => { const Pacote = require('pacote') const Arborist = t.mock('../../lib/arborist', { pacote: { @@ -3057,6 +3436,24 @@ t.only('should preserve exact ranges, missing actual tree', async (t) => { }, }) + const customGitSshPackument = JSON.stringify({ + _id: 'gitssh', + _rev: 'lkjadflkjasdf', + name: 'gitssh', + 'dist-tags': { latest: '1.1.1' }, + versions: { + '1.1.1': { + name: 'gitssh', + version: '1.1.1', + dist: { + // this is a url that `new URL()` cant parse + // https://github.com/npm/cli/issues/5278 + tarball: 'git+ssh://git@customgit.com:a/b/c.git#lkjadflkjasdf', + }, + }, + }, + }) + const notAUrlPackument = JSON.stringify({ _id: 'notaurl', _rev: 'lkjadflkjasdf', @@ -3073,7 +3470,37 @@ t.only('should preserve exact ranges, missing actual tree', async (t) => { }, }) - t.only('host should not be replaced replaceRegistryHost=never', async (t) => { + t.test('valid custom hosted git url', async (t) => { + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { + gitssh: '1.1.1', + }, + }), + }, + }) + + tnock(t, 'https://registry.github.com') + .get('/gitssh') + .reply(200, customGitSshPackument) + + const getLogs = warningTracker() + + const arb = new Arborist({ + path: resolve(testdir, 'project'), + registry: 'https://registry.github.com', + cache: resolve(testdir, 'cache'), + }) + await arb.reify() + // since it's not throwing an error on invalid url and returning undefined + // which trashes the node, so here we can only check if it has no warnings + t.strictSame(getLogs(), [], 'did not get warnings') + }) + + t.test('host should not be replaced replaceRegistryHost=never', async (t) => { const testdir = t.testdir({ project: { 'package.json': JSON.stringify({ @@ -3113,7 +3540,7 @@ t.only('should preserve exact ranges, missing actual tree', async (t) => { await arb.reify() }) - t.only('host should be replaced replaceRegistryHost=npmjs', async (t) => { + t.test('host should be replaced replaceRegistryHost=npmjs', async (t) => { const testdir = t.testdir({ project: { 'package.json': JSON.stringify({ @@ -3153,7 +3580,7 @@ t.only('should preserve exact ranges, missing actual tree', async (t) => { await arb.reify() }) - t.only('host should be always replaceRegistryHost=always', async (t) => { + t.test('host should be always replaceRegistryHost=always', async (t) => { const testdir = t.testdir({ project: { 'package.json': JSON.stringify({ @@ -3192,31 +3619,72 @@ t.only('should preserve exact ranges, missing actual tree', async (t) => { }) await arb.reify() }) -}) -t.test('install stategy linked', async (t) => { - const Arborist = require('../../lib/index.js') - const abbrev = resolve(__dirname, - '../fixtures/registry-mocks/content/abbrev/-/abbrev-1.1.1.tgz') - const abbrevTGZ = fs.readFileSync(abbrev) - - const abbrevPackument = JSON.stringify({ - _id: 'abbrev', - _rev: 'lkjadflkjasdf', - name: 'abbrev', - 'dist-tags': { latest: '1.1.1' }, - versions: { - '1.1.1': { - name: 'abbrev', - version: '1.1.1', - dist: { - tarball: 'https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz', + t.test('registry with path should only swap hostname', async (t) => { + const abbrevPackument3 = JSON.stringify({ + _id: 'abbrev', + _rev: 'lkjadflkjasdf', + name: 'abbrev', + 'dist-tags': { latest: '1.1.1' }, + versions: { + '1.1.1': { + name: 'abbrev', + version: '1.1.1', + dist: { + tarball: 'https://artifactory.example.com/api/npm/npm-all/abbrev/-/abbrev-1.1.1.tgz', + }, }, }, - }, + }) + + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { + abbrev: '1.1.1', + }, + }), + }, + }) + + tnock(t, 'https://new-host.artifactory.example.com') + .get('/api/npm/npm-all/abbrev') + .reply(200, abbrevPackument3) + + tnock(t, 'https://new-host.artifactory.example.com') + .get('/api/npm/npm-all/abbrev/-/abbrev-1.1.1.tgz') + .reply(200, abbrevTGZ) + + const arb = new Arborist({ + path: resolve(testdir, 'project'), + registry: 'https://new-host.artifactory.example.com/api/npm/npm-all', + cache: resolve(testdir, 'cache'), + replaceRegistryHost: 'always', + }) + await arb.reify() }) - t.test('should install package linked', async (t) => { + t.test('registry path prepending', async t => { + // A registry path is prepended to resolved URLs that don't already have it + const abbrevPackument4 = JSON.stringify({ + _id: 'abbrev', + _rev: 'lkjadflkjasdf', + name: 'abbrev', + 'dist-tags': { latest: '1.1.1' }, + versions: { + '1.1.1': { + name: 'abbrev', + version: '1.1.1', + dist: { + // Note: This URL has no path component that matches our registry path + tarball: 'https://external-registry.example.com/abbrev-1.1.1.tgz', + }, + }, + }, + }) + const testdir = t.testdir({ project: { 'package.json': JSON.stringify({ @@ -3229,25 +3697,816 @@ t.test('install stategy linked', async (t) => { }, }) - tnock(t, 'https://registry.npmjs.org') - .get('/abbrev') - .reply(200, abbrevPackument) + // Set up the registry with a deep path + const registryHost = 'https://registry.example.com' + const registryPath = '/custom/deep/path/registry' + const registry = `${registryHost}${registryPath}` - tnock(t, 'https://registry.npmjs.org') - .get('/abbrev/-/abbrev-1.1.1.tgz') + tnock(t, registryHost) + .get(`${registryPath}/abbrev`) + .reply(200, abbrevPackument4) + + // This is the critical test - the tarball URL in the packument doesn't have our registry path, but when replaceRegistryHost is 'always', we should get a request to this URL which includes the registry path + tnock(t, registryHost) + .get(`${registryPath}/abbrev-1.1.1.tgz`) .reply(200, abbrevTGZ) - const path = resolve(testdir, 'project') const arb = new Arborist({ - path, - registry: 'https://registry.npmjs.org', + path: resolve(testdir, 'project'), + registry, cache: resolve(testdir, 'cache'), - installStrategy: 'linked', + replaceRegistryHost: 'always', }) - await arb.reify({ installStrategy: 'linked' }) - const abbrev = fs.lstatSync(resolve(path, 'node_modules', 'abbrev')) - const store = fs.lstatSync(resolve(path, 'node_modules', '.store')) - t.ok(store.isDirectory(), 'abbrev got installed') - t.ok(abbrev.isSymbolicLink(), 'abbrev got installed') + + await t.resolves(arb.reify(), 'reify should complete successfully') }) + + t.test('registry path prepending with registry path being a package name prefix', async t => { + // A registry path is prepended to resolved URLs that don't already have it + const abbrevPackument4 = JSON.stringify({ + _id: 'abbrev', + _rev: 'lkjadflkjasdf', + name: 'abbrev', + 'dist-tags': { latest: '1.1.1' }, + versions: { + '1.1.1': { + name: 'abbrev', + version: '1.1.1', + dist: { + // Note: This URL has no path component that matches our registry path + tarball: 'https://external-registry.example.com/abbrev-1.1.1.tgz', + }, + }, + }, + }) + + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { + abbrev: '1.1.1', + }, + }), + }, + }) + + // Set up the registry with a deep path + const registryHost = 'https://registry.example.com' + // Note: This path is a prefix of the package name 'abbrev' + const registryPath = '/abb' + const registry = `${registryHost}${registryPath}` + + tnock(t, registryHost) + .get(`${registryPath}/abbrev`) + .reply(200, abbrevPackument4) + + // This is the critical test - the tarball URL in the packument doesn't have our registry path, but when replaceRegistryHost is 'always', we should get a request to this URL which includes the registry path + tnock(t, registryHost) + .get(`${registryPath}/abbrev-1.1.1.tgz`) + .reply(200, abbrevTGZ) + + const arb = new Arborist({ + path: resolve(testdir, 'project'), + registry, + cache: resolve(testdir, 'cache'), + replaceRegistryHost: 'always', + }) + + await t.resolves(arb.reify(), 'reify should complete successfully') + }) + + t.test('allowRemote=none allows registry tarball under registry path without trailing slash', async t => { + const abbrevPackument5 = JSON.stringify({ + _id: 'abbrev', + _rev: 'lkjadflkjasdf', + name: 'abbrev', + 'dist-tags': { latest: '1.1.1' }, + versions: { + '1.1.1': { + name: 'abbrev', + version: '1.1.1', + dist: { + tarball: 'https://registry.example.com/npm/abbrev/-/abbrev-1.1.1.tgz', + }, + }, + }, + }) + + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { + abbrev: '1.1.1', + }, + }), + }, + }) + + tnock(t, 'https://registry.example.com') + .get('/npm/abbrev') + .reply(200, abbrevPackument5) + + tnock(t, 'https://registry.example.com') + .get('/npm/abbrev/-/abbrev-1.1.1.tgz') + .reply(200, abbrevTGZ) + + const arb = new Arborist({ + path: resolve(testdir, 'project'), + registry: 'https://registry.example.com/npm', + cache: resolve(testdir, 'cache'), + allowRemote: 'none', + }) + + await t.resolves(arb.reify(), 'registry tarball under configured path is allowed') + }) + + t.test('allowRemote=none blocks same-origin tarball outside registry path', async t => { + const abbrevPackument5 = JSON.stringify({ + _id: 'abbrev', + _rev: 'lkjadflkjasdf', + name: 'abbrev', + 'dist-tags': { latest: '1.1.1' }, + versions: { + '1.1.1': { + name: 'abbrev', + version: '1.1.1', + dist: { + tarball: 'https://registry.example.com/evil/abbrev-1.1.1.tgz', + }, + }, + }, + }) + + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { + abbrev: '1.1.1', + }, + }), + }, + }) + + tnock(t, 'https://registry.example.com') + .get('/npm/abbrev') + .reply(200, abbrevPackument5) + + const arb = new Arborist({ + path: resolve(testdir, 'project'), + registry: 'https://registry.example.com/npm/', + cache: resolve(testdir, 'cache'), + allowRemote: 'none', + }) + + await t.rejects(arb.reify(), { code: 'EALLOWREMOTE' }, 'sibling path tarball is blocked') + }) + + t.test('allowRemote=none allows same-origin tarball for root registry path', async t => { + const abbrevPackument5 = JSON.stringify({ + _id: 'abbrev', + _rev: 'lkjadflkjasdf', + name: 'abbrev', + 'dist-tags': { latest: '1.1.1' }, + versions: { + '1.1.1': { + name: 'abbrev', + version: '1.1.1', + dist: { + tarball: 'https://registry.example.com/other/abbrev-1.1.1.tgz', + }, + }, + }, + }) + + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { + abbrev: '1.1.1', + }, + }), + }, + }) + + tnock(t, 'https://registry.example.com') + .get('/abbrev') + .reply(200, abbrevPackument5) + + tnock(t, 'https://registry.example.com') + .get('/other/abbrev-1.1.1.tgz') + .reply(200, abbrevTGZ) + + const arb = new Arborist({ + path: resolve(testdir, 'project'), + registry: 'https://registry.example.com', + cache: resolve(testdir, 'cache'), + allowRemote: 'none', + }) + + await t.resolves(arb.reify(), 'same-origin tarball is allowed for registry root') + }) + + t.test('allowRemote=none allows registry tarball whose resolved origin differs from the configured registry', async t => { + // Proxy/mirror case: a committed lockfile pins resolved to the public registry while a private mirror is configured. + // replace-registry-host rewrites the host to the configured registry at fetch time, so the effective URL is registry-mediated and must pass allow-remote=none. + const abbrevPackumentNpmjs = JSON.stringify({ + _id: 'abbrev', + _rev: 'lkjadflkjasdf', + name: 'abbrev', + 'dist-tags': { latest: '1.1.1' }, + versions: { + '1.1.1': { + name: 'abbrev', + version: '1.1.1', + dist: { + tarball: 'https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz', + }, + }, + }, + }) + + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { + abbrev: '1.1.1', + }, + }), + }, + }) + + tnock(t, 'https://registry.example.com') + .get('/abbrev') + .reply(200, abbrevPackumentNpmjs) + + // replace-registry-host (default 'npmjs') rewrites the npmjs.org tarball host to the configured mirror, so the fetch lands here. + tnock(t, 'https://registry.example.com') + .get('/abbrev/-/abbrev-1.1.1.tgz') + .reply(200, abbrevTGZ) + + const arb = new Arborist({ + path: resolve(testdir, 'project'), + registry: 'https://registry.example.com', + cache: resolve(testdir, 'cache'), + allowRemote: 'none', + }) + + await t.resolves(arb.reify(), 'mirror-fronted registry tarball is allowed under allow-remote=none') + }) + + t.test('allowRemote=none allows registry tarball with replaceRegistryHost=always', async t => { + // replace-registry-host=always routes every registry tarball fetch through the configured registry, so the effective URL is never remote and must pass allow-remote=none. + const abbrevPackumentNpmjs = JSON.stringify({ + _id: 'abbrev', + _rev: 'lkjadflkjasdf', + name: 'abbrev', + 'dist-tags': { latest: '1.1.1' }, + versions: { + '1.1.1': { + name: 'abbrev', + version: '1.1.1', + dist: { + tarball: 'https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz', + }, + }, + }, + }) + + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { + abbrev: '1.1.1', + }, + }), + }, + }) + + tnock(t, 'https://registry.example.com') + .get('/npm/abbrev') + .reply(200, abbrevPackumentNpmjs) + + // always rewrites the tarball host to the configured registry and prepends the registry path. + tnock(t, 'https://registry.example.com') + .get('/npm/abbrev/-/abbrev-1.1.1.tgz') + .reply(200, abbrevTGZ) + + const arb = new Arborist({ + path: resolve(testdir, 'project'), + registry: 'https://registry.example.com/npm', + cache: resolve(testdir, 'cache'), + allowRemote: 'none', + replaceRegistryHost: 'always', + }) + + await t.resolves(arb.reify(), 'registry tarball routed through the configured registry is allowed') + }) + + t.test('allowRemote=none allows registry tarball under linked install strategy', async t => { + // The linked strategy extracts store nodes as IsolatedNode, which has no edges to recompute isRegistryDependency from. + // The flag must be carried from the source tree node so the registry-tarball allow-remote exemption still applies. + const abbrevPackument5 = JSON.stringify({ + _id: 'abbrev', + _rev: 'lkjadflkjasdf', + name: 'abbrev', + 'dist-tags': { latest: '1.1.1' }, + versions: { + '1.1.1': { + name: 'abbrev', + version: '1.1.1', + dist: { + tarball: 'https://registry.example.com/npm/abbrev/-/abbrev-1.1.1.tgz', + }, + }, + }, + }) + + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { + abbrev: '1.1.1', + }, + }), + }, + }) + + tnock(t, 'https://registry.example.com') + .get('/npm/abbrev') + .reply(200, abbrevPackument5) + + tnock(t, 'https://registry.example.com') + .get('/npm/abbrev/-/abbrev-1.1.1.tgz') + .reply(200, abbrevTGZ) + + const arb = new Arborist({ + path: resolve(testdir, 'project'), + registry: 'https://registry.example.com/npm', + cache: resolve(testdir, 'cache'), + allowRemote: 'none', + installStrategy: 'linked', + }) + + await t.resolves(arb.reify(), 'registry tarball is allowed under linked strategy') + }) + + t.test('allowRemote=root allows root-direct remote tarball under linked install strategy', async t => { + // The linked strategy extracts store nodes as IsolatedNode, which has no edgesIn to recompute root-ness from. + // isRootDependency must be carried from the source tree node, otherwise allow-remote=root mis-fires on a genuine remote tarball that is a direct dep of the project root. + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { + abbrev: 'https://remote.example.com/abbrev-1.1.1.tgz', + }, + }), + }, + }) + + tnock(t, 'https://remote.example.com') + .get('/abbrev-1.1.1.tgz') + .reply(200, abbrevTGZ) + + const arb = new Arborist({ + path: resolve(testdir, 'project'), + registry: 'https://registry.example.com', + cache: resolve(testdir, 'cache'), + allowRemote: 'root', + installStrategy: 'linked', + }) + + await t.resolves(arb.reify(), 'root-direct remote tarball is allowed under linked strategy with allow-remote=root') + }) + + t.test('registry with different protocol should swap protocol', async (t) => { + const abbrevPackument4 = JSON.stringify({ + _id: 'abbrev', + _rev: 'lkjadflkjasdf', + name: 'abbrev', + 'dist-tags': { latest: '1.1.1' }, + versions: { + '1.1.1': { + name: 'abbrev', + version: '1.1.1', + dist: { + // Note: This URL has no path component that matches our registry path + tarball: 'https://external-registry.example.com/abbrev-1.1.1.tgz', + }, + }, + }, + }) + + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { + abbrev: '1.1.1', + }, + }), + }, + }) + + // Set up the registry with an http protocol + const registryHost = 'http://registry.example.com' + const registryPath = '/custom/deep/path/registry' + const registry = `${registryHost}${registryPath}` + + tnock(t, registryHost) + .get(`${registryPath}/abbrev`) + .reply(200, abbrevPackument4) + + tnock(t, registryHost) + .get(`${registryPath}/abbrev-1.1.1.tgz`) + .reply(200, abbrevTGZ) + + const arb = new Arborist({ + path: resolve(testdir, 'project'), + registry, + cache: resolve(testdir, 'cache'), + replaceRegistryHost: 'always', + }) + + await t.resolves(arb.reify(), 'reify should complete successfully when protocol changes from https to http') + }) +}) + +t.test('install strategy linked', async (t) => { + const Arborist = require('../../lib/index.js') + const abbrev = resolve(__dirname, + '../fixtures/registry-mocks/content/abbrev/-/abbrev-1.1.1.tgz') + const abbrevTGZ = fs.readFileSync(abbrev) + + const abbrevPackument = JSON.stringify({ + _id: 'abbrev', + _rev: 'lkjadflkjasdf', + name: 'abbrev', + 'dist-tags': { latest: '1.1.1' }, + versions: { + '1.1.1': { + name: 'abbrev', + version: '1.1.1', + dist: { + tarball: 'https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz', + }, + }, + }, + }) + + t.test('should install package linked', async (t) => { + const testdir = t.testdir({ + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { + abbrev: '1.1.1', + }, + }), + }, + }) + + tnock(t, 'https://registry.npmjs.org') + .get('/abbrev') + .reply(200, abbrevPackument) + + tnock(t, 'https://registry.npmjs.org') + .get('/abbrev/-/abbrev-1.1.1.tgz') + .reply(200, abbrevTGZ) + + const path = resolve(testdir, 'project') + const arb = new Arborist({ + path, + registry: 'https://registry.npmjs.org', + cache: resolve(testdir, 'cache'), + installStrategy: 'linked', + }) + await arb.reify({ installStrategy: 'linked' }) + const abbrev = fs.lstatSync(resolve(path, 'node_modules', 'abbrev')) + const store = fs.lstatSync(resolve(path, 'node_modules', '.store')) + t.ok(store.isDirectory(), 'abbrev got installed') + t.ok(abbrev.isSymbolicLink(), 'abbrev got installed') + }) + + t.test('does not re-create a workspace dir removed from manifest', async t => { + // Regression test for https://github.com/npm/cli/issues/9331 + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'host', + version: '1.0.0', + workspaces: ['packages/a', 'packages/b'], + }), + packages: { + a: { 'package.json': JSON.stringify({ name: 'a', version: '1.0.0' }) }, + b: { 'package.json': JSON.stringify({ name: 'b', version: '1.0.0' }) }, + }, + }) + + createRegistry(t, false) + await reify(path, { installStrategy: 'linked' }) + + // Drop workspace b: remove its directory and its entry from package.json. + fs.rmSync(resolve(path, 'packages/b'), { recursive: true, force: true }) + fs.writeFileSync(resolve(path, 'package.json'), JSON.stringify({ + name: 'host', + version: '1.0.0', + workspaces: ['packages/a'], + })) + + await reify(path, { installStrategy: 'linked' }) + + t.notOk( + fs.existsSync(resolve(path, 'packages/b')), + 'packages/b should remain absent after reinstall' + ) + }) +}) + +t.test('linked strategy exposes store node_modules via NODE_PATH for lifecycle scripts', async t => { + // Regression for #9549. In the linked strategy a store package's deps are symlinked siblings in its store node_modules. + // A separate bin invoked by the script (e.g. napi-postinstall) resolves modules from its own store realpath and cannot see them, so npm exposes them via NODE_PATH. + const Arborist = require('../../lib/index.js') + const pacote = require('pacote') + + const testdir = t.testdir({ + src: { + 'package.json': JSON.stringify({ + name: 'has-postinstall', + version: '1.0.0', + scripts: { postinstall: 'node -e ""' }, + }), + }, + project: { + 'package.json': JSON.stringify({ + name: 'myproject', + version: '1.0.0', + dependencies: { 'has-postinstall': '1.0.0' }, + }), + }, + }) + + const tgz = await pacote.tarball(resolve(testdir, 'src'), { Arborist }) + + const packument = JSON.stringify({ + _id: 'has-postinstall', + name: 'has-postinstall', + 'dist-tags': { latest: '1.0.0' }, + versions: { + '1.0.0': { + name: 'has-postinstall', + version: '1.0.0', + hasInstallScript: true, + scripts: { postinstall: 'node -e ""' }, + dist: { + tarball: 'https://registry.npmjs.org/has-postinstall/-/has-postinstall-1.0.0.tgz', + }, + }, + }, + }) + + tnock(t, 'https://registry.npmjs.org') + .get('/has-postinstall') + .reply(200, packument) + + tnock(t, 'https://registry.npmjs.org') + .get('/has-postinstall/-/has-postinstall-1.0.0.tgz') + .reply(200, tgz) + + const path = resolve(testdir, 'project') + const arb = new Arborist({ + path, + registry: 'https://registry.npmjs.org', + cache: resolve(testdir, 'cache'), + installStrategy: 'linked', + dangerouslyAllowAllScripts: true, + }) + await arb.reify() + + const run = [...arb.scriptsRun] + .find(s => s.pkg.name === 'has-postinstall' && s.event === 'postinstall') + t.ok(run, 'postinstall ran for the store package') + t.match(run.path, /[\\/]\.store[\\/]/, 'script ran on the store entry') + // Assert the leading entry: the fix prepends the store node_modules to any pre-existing NODE_PATH (e.g. the coverage harness on Windows CI). + const [firstNodePath] = run.env.NODE_PATH.split(delimiter) + t.equal(firstNodePath, resolve(run.path, '..'), + 'NODE_PATH leads with the store node_modules holding the package deps') +}) + +t.test('workspace installs retain existing versions with newer package specs', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + workspaces: [ + 'packages/*', + ], + overrides: { + 'doesnt-matter-can-be-anything': '1.2.3', + }, + }), + packages: { + 'my-cool-package': { + 'package.json': JSON.stringify({}), + }, + 'another-cool-package': { + 'package.json': JSON.stringify({}), + }, + }, + }) + + createRegistry(t, true) + + // Step 1: Install abbrev@1.0.4 in my-cool-package + await reify(path, { + add: ['abbrev@1.0.4'], + // setting savePrefix to '' is exactly what the --save-exact flag does in definitions.js + savePrefix: '', + workspaces: ['my-cool-package'], + }) + + // Verify hoisted installation + const rootNodeModules = resolve(path, 'node_modules/abbrev/package.json') + t.ok(fs.existsSync(rootNodeModules), 'abbrev should be hoisted to root node_modules') + + const hoistedPkg = JSON.parse(fs.readFileSync(rootNodeModules, 'utf8')) + t.equal(hoistedPkg.version, '1.0.4', 'hoisted version should be 1.0.4') + + // Check my-cool-package package.json + const myPackageJson = JSON.parse(fs.readFileSync( + resolve(path, 'packages/my-cool-package/package.json'), 'utf8')) + t.same(myPackageJson.dependencies, { abbrev: '1.0.4' }, + 'my-cool-package should have abbrev@1.0.4 in dependencies') + + // Step 2: Install abbrev@1.1.1 in another-cool-package + await reify(path, { + add: ['abbrev@1.1.1'], + savePrefix: '', + workspaces: ['another-cool-package'], + }) + + // Verify un-hoisted installation + const anotherNodeModules = resolve(path, 'packages/another-cool-package/node_modules/abbrev/package.json') + t.ok(fs.existsSync(anotherNodeModules), 'abbrev@1.1.1 should be installed in another-cool-package/node_modules') + + const unhoistedPkg = JSON.parse(fs.readFileSync(anotherNodeModules, 'utf8')) + t.equal(unhoistedPkg.version, '1.1.1', 'unhoisted version should be 1.1.1') + + // Check another-cool-package package.json + const anotherPackageJson = JSON.parse(fs.readFileSync( + resolve(path, 'packages/another-cool-package/package.json'), 'utf8')) + t.same(anotherPackageJson.dependencies, { abbrev: '1.1.1' }, + 'another-cool-package should have abbrev@1.1.1 in dependencies') + + // Step 3: Install abbrev@1.0.4 in another-cool-package + await reify(path, { + add: ['abbrev@1.0.4'], + savePrefix: '', + workspaces: ['another-cool-package'], + }) + + t.ok(fs.existsSync(rootNodeModules), 'abbrev@1.0.4 should still be hoisted to root node_modules') + t.notOk(fs.existsSync(anotherNodeModules), 'abbrev@1.1.1 should be removed from another-cool-package/node_modules') + + // Check another-cool-package package.json - should now be updated to 1.0.4 + const updatedPackageJson = JSON.parse(fs.readFileSync( + resolve(path, 'packages/another-cool-package/package.json'), 'utf8')) + t.same(updatedPackageJson.dependencies, { abbrev: '1.0.4' }, + 'another-cool-package package.json should be updated to abbrev@1.0.4') +}) + +for (const poisoned of ['../../../escape-target', '@evil/../../../escape-target']) { + t.test(`install strategy linked sanitizes traversal in lockfile name (${poisoned})`, async t => { + // a poisoned lockfile name field would otherwise escape node_modules/.store + const testDir = t.testdir({ + 'package.json': JSON.stringify({ + dependencies: { + abbrev: '1.1.1', + }, + }), + 'package-lock.json': JSON.stringify({ + lockfileVersion: 3, + requires: true, + packages: { + '': { + dependencies: { + abbrev: '1.1.1', + }, + }, + 'node_modules/abbrev': { + name: poisoned, + version: '1.1.1', + resolved: 'https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz', + integrity: 'sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==', + }, + }, + }), + }) + + const arb = new Arborist({ + path: testDir, + registry: 'https://registry.npmjs.org', + cache: resolve(testDir, 'cache'), + installStrategy: 'linked', + packageLockOnly: true, + }) + await arb.reify({ installStrategy: 'linked', packageLockOnly: true }) + + const external = arb.idealGraph.external + t.equal(external.length, 1, 'one external dep planned') + + const pkgName = external[0].packageName + t.notMatch(pkgName, /\.\./, 'packageName has no traversal segments') + t.ok(!pkgName.includes('/') || pkgName.startsWith('@'), + 'packageName is a single segment (or @scope/name)') + + // joining the sanitized name into the .store layout must not escape + const storePrefix = resolve(testDir, 'node_modules/.store/key/node_modules') + const projected = resolve(storePrefix, pkgName) + t.ok(projected.startsWith(storePrefix), 'projected path stays inside .store') + + // belt-and-suspenders: nothing should have been written outside testDir, + // even if a future change starts materializing paths during reify + t.notOk(fs.existsSync(resolve(testDir, '..', 'escape-target')), + 'no escape-target leaked one level above testDir') + t.notOk(fs.existsSync(resolve(testDir, '..', '..', 'escape-target')), + 'no escape-target leaked two levels above testDir') + t.notOk(fs.existsSync(resolve(testDir, '..', '..', '..', 'escape-target')), + 'no escape-target leaked three levels above testDir') + }) +} + +t.test('externalOptionalDependencies excludes inert optional node with installStrategy linked', async t => { + const testDir = t.testdir({ + 'package.json': JSON.stringify({ + optionalDependencies: { + abbrev: '1.1.1', + }, + }), + 'package-lock.json': JSON.stringify({ + lockfileVersion: 2, + requires: true, + packages: { + '': { + optionalDependencies: { + abbrev: '1.1.1', + }, + }, + 'node_modules/abbrev': { + version: '1.1.1', + resolved: 'https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz', + integrity: 'sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==', + dev: true, + cpu: ['not-your-cpu'], + }, + }, + optionalDependencies: { + abbrev: { + version: '1.1.1', + resolved: 'https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz', + integrity: 'sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==', + dev: true, + cpu: ['not-your-cpu'], + }, + }, + }), + }) + + const arb = new Arborist({ + path: testDir, + registry: 'https://registry.npmjs.org', + cache: resolve(testDir, 'cache'), + installStrategy: 'linked', + }) + await arb.reify({ installStrategy: 'linked' }) + + // Assert that the optional inert node does not appear in externalOptionalDependencies + t.notOk( + arb.idealGraph.externalOptionalDependencies && + arb.idealGraph.externalOptionalDependencies.some(n => n && n.name === 'abbrev'), + 'inert optional dependency should not appear in externalOptionalDependencies' + ) + + // And verify that it is not installed on disk + t.throws( + () => fs.lstatSync(resolve(testDir, 'node_modules', 'abbrev')), + { code: 'ENOENT' }, + 'inert optional node should not be installed' + ) + + t.end() }) diff --git a/workspaces/arborist/test/audit-report.js b/workspaces/arborist/test/audit-report.js index 6f4bcf8858f35..0322b48dbd534 100644 --- a/workspaces/arborist/test/audit-report.js +++ b/workspaces/arborist/test/audit-report.js @@ -1,27 +1,14 @@ const t = require('tap') const localeCompare = require('@isaacs/string-locale-compare')('en') const AuditReport = require('../lib/audit-report.js') -const { auditToBulk } = AuditReport const Node = require('../lib/node.js') const Arborist = require('../') +const MockRegistry = require('@npmcli/mock-registry') -const { - start, - stop, - registry, - auditResponse, - failAudit, - advisoryBulkResponse, -} = require('./fixtures/server.js') -t.before(start) -t.teardown(stop) - -const { resolve } = require('node:path') +const { join, resolve } = require('node:path') const fixtures = resolve(__dirname, 'fixtures') -const cache = t.testdir() -const newArb = (path, opts = {}) => - new Arborist({ path, registry, cache, ...opts }) +const newArb = (path, opts = {}) => new Arborist({ path, ...opts }) const sortReport = report => { const entries = Object.entries(report.vulnerabilities) @@ -41,11 +28,22 @@ const sortReport = report => { }, {}) } +const createRegistry = (t) => { + const registry = new MockRegistry({ + strict: true, + tap: t, + registry: 'https://registry.npmjs.org', + }) + return registry +} + t.test('all severity levels', async t => { const path = resolve(fixtures, 'audit-all-severities') - const auditFile = resolve(path, 'audit.json') - t.teardown(auditResponse(auditFile)) - const arb = newArb(path) + const registry = createRegistry(t) + registry.audit({ convert: true, results: require(resolve(path, 'audit.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) @@ -55,9 +53,11 @@ t.test('all severity levels', async t => { t.test('vulnerable dep not from registry', async t => { const path = resolve(fixtures, 'minimist-git-dep') - const auditFile = resolve(path, 'audit.json') - t.teardown(auditResponse(auditFile)) - const arb = newArb(path) + const registry = createRegistry(t) + registry.audit({ convert: true, results: require(resolve(path, 'audit.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) @@ -69,9 +69,11 @@ t.test('vulnerable dep not from registry', async t => { t.test('metavuln where dep is not a registry dep', async t => { const path = resolve(fixtures, 'minimist-git-metadep') - const auditFile = resolve(path, 'audit.json') - t.teardown(auditResponse(auditFile)) - const arb = newArb(path) + const registry = createRegistry(t) + registry.audit({ convert: true, results: require(resolve(path, 'audit.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) @@ -84,9 +86,11 @@ t.test('metavuln where dep is not a registry dep', async t => { t.test('metavuln where a dep is not on the registry at all', async t => { const path = resolve(fixtures, 'audit-missing-packument') - const auditFile = resolve(path, 'audit.json') - t.teardown(auditResponse(auditFile)) - const arb = newArb(path) + const registry = createRegistry(t) + registry.audit({ convert: true, results: require(resolve(path, 'audit.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) @@ -97,10 +101,11 @@ t.test('metavuln where a dep is not on the registry at all', async t => { t.test('get advisory about node not in tree', async t => { // this should never happen, but if it does, we're prepared for it const path = resolve(fixtures, 'audit-nyc-mkdirp') - const auditFile = resolve(path, 'audit.json') - t.teardown(auditResponse(auditFile)) - - const arb = newArb(path) + const registry = createRegistry(t) + registry.audit({ convert: true, results: require(resolve(path, 'audit.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = await arb.loadVirtual() tree.children.get('mkdirp').parent = null @@ -116,8 +121,6 @@ t.test('get advisory about node not in tree', async t => { } } const report = await AuditReport.load(tree, arb.options) - // just a gut-check that the registry server is actually doing stuff - t.match(report.report, auditToBulk(require(auditFile)), 'got expected response') t.equal(report.topVulns.size, 0, 'one top node found vulnerable') t.equal(report.size, 0, 'no vulns that were relevant') t.equal(report.get('nyc'), undefined) @@ -126,9 +129,11 @@ t.test('get advisory about node not in tree', async t => { t.test('unfixable, but not a semver major forced fix', async t => { const path = resolve(fixtures, 'mkdirp-pinned') - const auditFile = resolve(fixtures, 'audit-nyc-mkdirp/audit.json') - t.teardown(auditResponse(auditFile)) - const arb = newArb(path) + const registry = createRegistry(t) + registry.audit({ convert: true, results: require(resolve(fixtures, 'audit-nyc-mkdirp', 'audit.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) @@ -139,18 +144,16 @@ t.test('unfixable, but not a semver major forced fix', async t => { t.test('audit outdated nyc and mkdirp', async t => { const path = resolve(fixtures, 'audit-nyc-mkdirp') - const auditFile = resolve(path, 'audit.json') - t.teardown(auditResponse(auditFile)) - - const arb = newArb(path) + const registry = createRegistry(t) + registry.audit({ results: require(resolve(path, 'advisory-bulk.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) t.matchSnapshot(JSON.stringify(report, 0, 2), 'json version') - // just a gut-check that the registry server is actually doing stuff - t.match(report.report, auditToBulk(require(auditFile)), 'got expected response') - t.throws(() => report.set('foo', 'bar'), { message: 'do not call AuditReport.set() directly', }) @@ -160,51 +163,93 @@ t.test('audit outdated nyc and mkdirp', async t => { t.equal(report.get('mkdirp').simpleRange, '0.4.1 - 0.5.1') }) -t.test('audit outdated nyc and mkdirp with newer endpoint', async t => { +t.test('audit outdated nyc and mkdirp with before: option', async t => { const path = resolve(fixtures, 'audit-nyc-mkdirp') - const auditFile = resolve(path, 'advisory-bulk.json') - t.teardown(advisoryBulkResponse(auditFile)) + const registry = createRegistry(t) + registry.audit({ results: require(resolve(path, 'advisory-bulk.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) - const arb = newArb(path) + const cache = t.testdir() + const arb = newArb(path, { before: new Date('2020-01-01'), cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) t.matchSnapshot(JSON.stringify(report, 0, 2), 'json version') - // just a gut-check that the registry server is actually doing stuff - t.match(report.report, require(auditFile), 'got expected response') - - t.throws(() => report.set('foo', 'bar'), { - message: 'do not call AuditReport.set() directly', - }) - t.equal(report.topVulns.size, 1, 'one top node found vulnerable') t.equal(report.get('nyc').simpleRange, '6.2.0-alpha - 13.1.0') t.equal(report.get('mkdirp').simpleRange, '0.4.1 - 0.5.1') }) -t.test('audit outdated nyc and mkdirp with before: option', async t => { +t.test('min-release-age blocks an available fix', async t => { + // mkdirp's fix (0.5.5, published 2020-04) is newer than a 2020-01-01 cutoff, + // so the only versions old enough are still vulnerable and audit fix can't + // apply the fix it reported as available. const path = resolve(fixtures, 'audit-nyc-mkdirp') - const auditFile = resolve(path, 'audit.json') - t.teardown(auditResponse(auditFile)) + const registry = createRegistry(t) + registry.audit({ results: require(resolve(path, 'advisory-bulk.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { before: new Date('2020-01-01'), cache }) - const arb = newArb(path, { before: new Date('2020-01-01') }) + const tree = await arb.loadVirtual() + const report = await AuditReport.load(tree, arb.options) + t.match(report.get('mkdirp').fixBlockedByReleaseAge, { version: '0.5.5' }, + 'mkdirp fix flagged as blocked by the release-age window') +}) + +t.test('min-release-age does not block a fix that is old enough', async t => { + const path = resolve(fixtures, 'audit-nyc-mkdirp') + const registry = createRegistry(t) + registry.audit({ results: require(resolve(path, 'advisory-bulk.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + // a cutoff after mkdirp@0.5.5 was published: the fix is reachable + const arb = newArb(path, { before: new Date('2021-01-01'), cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) - t.matchSnapshot(JSON.stringify(report, 0, 2), 'json version') + t.notOk(report.get('mkdirp').fixBlockedByReleaseAge, + 'fix reachable within the window, so not flagged') +}) + +t.test('min-release-age-exclude exempts a package from the block', async t => { + const path = resolve(fixtures, 'audit-nyc-mkdirp') + const registry = createRegistry(t) + registry.audit({ results: require(resolve(path, 'advisory-bulk.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { + before: new Date('2020-01-01'), + minReleaseAgeExclude: ['mkdirp'], + cache, + }) - // just a gut-check that the registry server is actually doing stuff - t.match(report.report, auditToBulk(require(auditFile)), 'got expected response') + const tree = await arb.loadVirtual() + const report = await AuditReport.load(tree, arb.options) + t.notOk(report.get('mkdirp').fixBlockedByReleaseAge, + 'excluded package is not flagged even when its fix is too new') +}) - t.equal(report.topVulns.size, 1, 'one top node found vulnerable') - t.equal(report.get('nyc').simpleRange, '6.2.0-alpha - 13.1.0') - t.equal(report.get('mkdirp').simpleRange, '0.4.1 - 0.5.1') +t.test('min-release-age blocks when no version is old enough at all', async t => { + const path = resolve(fixtures, 'audit-nyc-mkdirp') + const registry = createRegistry(t) + registry.audit({ results: require(resolve(path, 'advisory-bulk.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + // a cutoff before any mkdirp version was published: nothing is installable + const arb = newArb(path, { before: new Date('2000-01-01'), cache }) + + const tree = await arb.loadVirtual() + const report = await AuditReport.load(tree, arb.options) + t.match(report.get('mkdirp').fixBlockedByReleaseAge, { version: '0.5.5' }, + 'flagged as blocked when nothing is installable within the window') }) t.test('audit returns an error', async t => { const path = resolve(fixtures, 'audit-nyc-mkdirp') - t.teardown(failAudit()) + const registry = createRegistry(t) + registry.audit({ responseCode: 503, results: 'no audit for you' }) const logs = [] const onlog = (...msg) => { @@ -216,7 +261,8 @@ t.test('audit returns an error', async t => { process.on('log', onlog) t.teardown(() => process.removeListener('log', onlog)) - const arb = newArb(path) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) @@ -228,11 +274,6 @@ t.test('audit returns an error', async t => { 'audit', 'bulk request', ], - [ - 'silly', - 'audit', - 'bulk request failed', - ], [ 'verbose', 'audit error', @@ -245,13 +286,15 @@ t.test('audit returns an error', async t => { t.test('audit disabled by config', async t => { const path = resolve(fixtures, 'audit-nyc-mkdirp') + createRegistry(t) const logs = [] const onlog = (...msg) => logs.push(msg) process.on('log', onlog) t.teardown(() => process.removeListener('log', onlog)) - const arb = newArb(path, { audit: false }) + const cache = t.testdir() + const arb = newArb(path, { audit: false, cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) @@ -263,13 +306,15 @@ t.test('audit disabled by config', async t => { t.test('audit disabled by offline mode', async t => { const path = resolve(fixtures, 'audit-nyc-mkdirp') + createRegistry(t) const logs = [] const onlog = (...msg) => logs.push(msg) process.on('log', onlog) t.teardown(() => process.removeListener('log', onlog)) - const arb = newArb(path, { offline: true }) + const cache = t.testdir() + const arb = newArb(path, { offline: true, cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) @@ -281,9 +326,11 @@ t.test('audit disabled by offline mode', async t => { t.test('one vulnerability', async t => { const path = resolve(fixtures, 'audit-one-vuln') - const auditFile = resolve(path, 'audit.json') - t.teardown(auditResponse(auditFile)) - const arb = newArb(path) + const registry = createRegistry(t) + registry.audit({ convert: true, results: require(resolve(path, 'audit.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) @@ -294,9 +341,11 @@ t.test('one vulnerability', async t => { t.test('a dep vuln that also has its own advisory against it', async t => { const path = resolve(fixtures, 'audit-dep-vuln-with-own-advisory') - const auditFile = resolve(path, 'audit.json') - t.teardown(auditResponse(auditFile)) - const arb = newArb(path) + const registry = createRegistry(t) + registry.audit({ convert: true, results: require(resolve(path, 'audit.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) @@ -311,33 +360,17 @@ t.test('get default opts when loaded without opts', async t => { t.strictSame(ar.options, {}) }) -t.test('error on audit response with no advisories object', async t => { - const dir = t.testdir({ - 'audit.json': JSON.stringify({ no: 'advisories', at: 'all' }), - }) - const path = resolve(fixtures, 'audit-nyc-mkdirp') - const auditFile = resolve(dir, 'audit.json') - t.teardown(auditResponse(auditFile)) - - const arb = newArb(path) - - const tree = await arb.loadVirtual() - const report = await AuditReport.load(tree, arb.options) - t.match(report.error, { - message: 'Invalid advisory report', - body: JSON.stringify({ no: 'advisories', at: 'all' }), - }) -}) - t.test('audit report with a lying v5 lockfile', async t => { // npm v5 stored the resolved dependency version in the `requires` // set, rather than the spec that is actually required. As a result, // a dep may _appear_ to be a metavuln, but when we scan the // packument, it turns out that it matches no nodes, and gets deleted. const path = resolve(fixtures, 'eslintme') - const arb = newArb(path) - const auditFile = resolve(path, 'audit.json') - t.teardown(advisoryBulkResponse(auditFile)) + const registry = createRegistry(t) + registry.audit({ results: require(resolve(path, 'audit.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = await arb.loadVirtual() const report = await AuditReport.load(tree, arb.options) // also try to delete something that just very much is not present @@ -348,9 +381,6 @@ t.test('audit report with a lying v5 lockfile', async t => { t.test('omit options', async t => { const path = resolve(fixtures, 'audit-omit') - const quick = resolve(path, 'quick.json') - // quick response doesn't change for omit args - t.teardown(auditResponse(quick)) const omits = [ [], ['dev'], @@ -360,30 +390,30 @@ t.test('omit options', async t => { ['peer', 'dev'], ['peer', 'dev', 'optional'], // empty ] - const arb = newArb(path) - const tree = await arb.loadVirtual() - for (const omit of omits) { - t.test(`omit=[${omit.join(',')}]`, async t => { + await t.test(`omit=[${omit.join(',')}]`, async t => { + const cache = t.testdir() + const arb = newArb(path, { cache }) + const tree = await arb.loadVirtual() + const registry = createRegistry(t) const s = omit.map(o => `-omit${o}`).join('') - const bulk = resolve(path, `bulk${s}.json`) - const rmBulk = advisoryBulkResponse(bulk) - const r1 = (await AuditReport.load(tree, { ...arb.options, omit })) - .toJSON() + const bulkResults = require(resolve(path, `bulk${s}.json`)) + if (Object.keys(bulkResults).length) { /// peer, dev, optional is empty + registry.audit({ convert: false, results: bulkResults }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + } + const r1 = (await AuditReport.load(tree, { ...arb.options, omit })).toJSON() sortReport(r1) - rmBulk() t.matchSnapshot(r1, 'bulk') - const r2 = (await AuditReport.load(tree, { ...arb.options, omit })) - .toJSON() + const r2 = (await AuditReport.load(tree, { ...arb.options, omit })).toJSON() sortReport(r2) t.strictSame(r1, r2, 'same results') - t.end() }) } - t.end() }) t.test('audit when tree is empty', async t => { + createRegistry(t) const tree = new Node({ path: '/path/to/tree', }) @@ -392,7 +422,8 @@ t.test('audit when tree is empty', async t => { t.strictSame(report, null) }) -t.test('audit when bulk report doenst have anything in it', async t => { +t.test('audit when bulk report does not have anything in it', async t => { + createRegistry(t) const tree = new Node({ path: '/path/to/tree', pkg: { @@ -409,47 +440,13 @@ t.test('audit when bulk report doenst have anything in it', async t => { t.strictSame(report, null) }) -t.test('default severity=high, vulnerable_versions=*', async t => { - const audit = { - actions: [], - advisories: { - 755: { - findings: [ - { - version: '1.2.3', - paths: [ - 'something', - ], - }, - ], - id: 755, - title: 'no severity or vulnerable versions', - module_name: 'something', - overview: 'should default severity=high, vulnerable_versions=*', - recommendation: "don't use this thing", - url: 'https://npmjs.com/advisories/755', - }, - }, - muted: [], - metadata: { - vulnerabilities: {}, - dependencies: 1, - devDependencies: 0, - optionalDependencies: 0, - totalDependencies: 1, - }, - runId: 'just-some-unique-identifier', - } - - const bulk = auditToBulk(audit) - t.match(bulk, { something: [{ severity: 'high', vulnerable_versions: '*' }] }) - t.end() -}) - t.test('audit supports alias deps', async t => { const path = resolve(fixtures, 'audit-nyc-mkdirp') - const auditFile = resolve(path, 'advisory-bulk.json') - t.teardown(advisoryBulkResponse(auditFile)) + const registry = createRegistry(t) + registry.audit({ results: require(resolve(path, 'advisory-bulk.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = new Node({ path, pkg: { @@ -484,17 +481,78 @@ t.test('audit supports alias deps', async t => { ], }) - const report = await AuditReport.load(tree, { path, registry, cache }) + const report = await AuditReport.load(tree, arb.options) t.matchSnapshot(JSON.stringify(report, 0, 2), 'json version') t.equal(report.get('mkdirp').simpleRange, '0.4.1 - 0.5.1') }) -t.test('audit with filterSet limiting to only mkdirp and minimist', async t => { +t.test('release-age block detection unwraps alias specs', async t => { + // An npm: alias edge must be resolved against its target, not fed to + // pickManifest as an alias spec (which it rejects). With a release-age + // window the alias fix (mkdirp@0.5.5) is too new, so it should be flagged. const path = resolve(fixtures, 'audit-nyc-mkdirp') - const auditFile = resolve(path, 'advisory-bulk.json') - t.teardown(advisoryBulkResponse(auditFile)) + const registry = createRegistry(t) + registry.audit({ results: require(resolve(path, 'advisory-bulk.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { before: new Date('2020-01-01'), cache }) + const tree = new Node({ + path, + pkg: { + name: 'mkdirp', + version: '0.5.0', + dependencies: { + novulnshereiswear: 'npm:mkdirp@^0.5.0', + }, + }, + children: [ + { + name: 'novulnshereiswear', + pkg: { + name: 'mkdirp', + version: '0.5.1', + dependencies: { minimist: '0.0.8' }, + }, + }, + { pkg: { name: 'minimist', version: '0.0.8' } }, + ], + }) - const arb = newArb(path) + const report = await AuditReport.load(tree, arb.options) + t.match(report.get('mkdirp').fixBlockedByReleaseAge, { version: '0.5.5' }, + 'alias spec is unwrapped and the blocked fix is detected') +}) + +t.test('linked local package should not be audited against the registry', async t => { + const path = resolve(fixtures, 'audit-linked-package') + // No registry.audit() mock needed — no request should be made + // because linked packages must be excluded from the bulk payload + createRegistry(t) + const cache = t.testdir() + const arb = newArb(path, { cache }) + + const tree = await arb.loadVirtual() + const report = await AuditReport.load(tree, arb.options) + + t.equal( + report.has('electron-test-app'), + false, + 'linked local package should not appear in audit report' + ) + t.equal( + report.size, + 0, + 'audit report should be empty when all dependencies are local links' + ) +}) + +t.test('audit with filterSet limiting to only mkdirp and minimist', async t => { + const path = resolve(fixtures, 'audit-nyc-mkdirp') + const registry = createRegistry(t) + registry.audit({ results: require(resolve(path, 'advisory-bulk.json')) }) + registry.mocks({ dir: join(__dirname, 'fixtures') }) + const cache = t.testdir() + const arb = newArb(path, { cache }) const tree = await arb.loadVirtual() const filterSet = new Set([ diff --git a/workspaces/arborist/test/calc-dep-flags.js b/workspaces/arborist/test/calc-dep-flags.js index ff7f320ded29d..b371ae55f6e4b 100644 --- a/workspaces/arborist/test/calc-dep-flags.js +++ b/workspaces/arborist/test/calc-dep-flags.js @@ -20,11 +20,12 @@ t.test('flag stuff', t => { dependencies: { prod: '' }, devDependencies: { dev: '' }, optionalDependencies: { optional: '' }, - peerDependencies: { peer: '' }, + peerDependencies: { peer: '', peeroptional: '' }, + peerDependenciesMeta: { peeroptional: { optional: true } }, }, }) - new Node({ + const optional = new Node({ pkg: { name: 'optional', version: '1.2.3', @@ -33,7 +34,7 @@ t.test('flag stuff', t => { parent: root, }) - new Node({ + const devoptional = new Node({ pkg: { name: 'devoptional', version: '1.2.3', @@ -41,14 +42,14 @@ t.test('flag stuff', t => { parent: root, }) - new Node({ + const extraneous = new Node({ pkg: { name: 'extraneous', }, parent: root, }) - new Node({ + const peer = new Node({ pkg: { name: 'peer', version: '1.2.3', @@ -57,7 +58,7 @@ t.test('flag stuff', t => { parent: root, }) - new Node({ + const peerdep = new Node({ pkg: { name: 'peerdep', version: '1.2.3', @@ -65,7 +66,7 @@ t.test('flag stuff', t => { parent: root, }) - new Node({ + const prod = new Node({ pkg: { name: 'prod', version: '1.2.3', @@ -75,7 +76,7 @@ t.test('flag stuff', t => { parent: root, }) - new Node({ + const metapeer = new Node({ pkg: { name: 'metapeer', version: '1.2.3', @@ -84,7 +85,7 @@ t.test('flag stuff', t => { parent: root, }) - new Node({ + const metapeerdep = new Node({ pkg: { name: 'metapeerdep', version: '1.2.3', @@ -92,7 +93,7 @@ t.test('flag stuff', t => { parent: root, }) - new Node({ + const proddep = new Node({ pkg: { name: 'proddep', version: '1.2.3', @@ -101,7 +102,7 @@ t.test('flag stuff', t => { parent: root, }) - new Node({ + const dev = new Node({ pkg: { name: 'dev', version: '1.2.3', @@ -120,7 +121,7 @@ t.test('flag stuff', t => { parent: root, }) - new Node({ + const devandoptional = new Node({ pkg: { name: 'devandoptional', version: '1.2.3', @@ -139,7 +140,7 @@ t.test('flag stuff', t => { }) // a link dep depended upon by the target of a linked dep - new Link({ + const linkylinky = new Link({ pkg: { name: 'linklink', version: '1.2.3', @@ -148,8 +149,119 @@ t.test('flag stuff', t => { parent: linky.target, }) + const peeroptional = new Node({ + pkg: { + name: 'peeroptional', + version: '1.2.3', + dependencies: { optional: '' }, + }, + parent: root, + }) + calcDepFlags(root) + t.match(optional, { + extraneous: false, + dev: false, + optional: true, + devOptional: false, + peer: false, + }) + t.match(devoptional, { + extraneous: false, + dev: false, + optional: false, + devOptional: true, + peer: false, + }) + t.match(extraneous, { + extraneous: true, + }) + t.match(peer, { + extraneous: false, + dev: false, + optional: false, + devOptional: false, + peer: true, + }) + t.match(peerdep, { + extraneous: false, + dev: false, + optional: false, + devOptional: false, + peer: true, + }) + t.match(prod, { + extraneous: false, + dev: false, + optional: false, + devOptional: false, + peer: false, + }) + t.match(metapeer, { + extraneous: false, + dev: false, + optional: false, + devOptional: false, + peer: true, + }) + t.match(metapeerdep, { + extraneous: false, + dev: false, + optional: false, + devOptional: false, + peer: true, + }) + t.match(proddep, { + extraneous: false, + dev: false, + optional: false, + devOptional: false, + peer: false, + }) + t.match(dev, { + extraneous: false, + dev: true, + optional: false, + devOptional: false, + peer: false, + }) + t.match(devdep, { + extraneous: false, + dev: true, + optional: false, + devOptional: false, + peer: false, + }) + t.match(devandoptional, { + extraneous: false, + dev: true, + optional: true, + devOptional: false, + peer: false, + }) + t.match(linky, { + extraneous: false, + dev: true, + optional: false, + devOptional: false, + peer: false, + }) + t.match(linkylinky, { + extraneous: false, + dev: true, + optional: false, + devOptional: false, + peer: false, + }) + t.match(peeroptional, { + extraneous: true, + dev: false, + optional: true, + devOptional: false, + peer: true, + }) + t.matchSnapshot(printTree(root), 'after') t.end() }) @@ -219,49 +331,15 @@ t.test('set parents to not extraneous when visiting', t => { realpath: baz.path, }) - t.matchSnapshot(printTree(root), 'before') calcDepFlags(root, true) - t.matchSnapshot(printTree(root), 'after') - - t.equal(root.extraneous, false, 'root') - t.equal(asdf.extraneous, false, 'asdf') - t.equal(bar.extraneous, false, 'bar') - t.equal(baz.extraneous, false, 'baz') - t.equal(foo.extraneous, false, 'foo') - t.equal(fooLink.extraneous, false, 'fooLink') - t.equal(bazLink.extraneous, false, 'bazLink') - - t.equal(root.dev, false, 'root not dev') - t.equal(asdf.dev, false, 'asdf not dev') - t.equal(bar.dev, false, 'bar not dev') - t.equal(baz.dev, false, 'baz not dev') - t.equal(foo.dev, false, 'foo not dev') - t.equal(fooLink.dev, false, 'fooLink not dev') - t.equal(bazLink.dev, false, 'bazLink not dev') - - t.equal(root.optional, false, 'root not optional') - t.equal(asdf.optional, false, 'asdf not optional') - t.equal(bar.optional, false, 'bar not optional') - t.equal(baz.optional, false, 'baz not optional') - t.equal(foo.optional, false, 'foo not optional') - t.equal(fooLink.optional, false, 'foolink not optional') - t.equal(bazLink.optional, false, 'bazlink not optional') - - t.equal(root.peer, false, 'root not peer') - t.equal(asdf.peer, false, 'asdf not peer') - t.equal(bar.peer, false, 'bar not peer') - t.equal(baz.peer, false, 'baz not peer') - t.equal(foo.peer, false, 'foo not peer') - t.equal(fooLink.peer, false, 'foolink not peer') - t.equal(bazLink.peer, false, 'bazlink not peer') - t.equal(root.devOptional, false, 'root not devOptional') - t.equal(asdf.devOptional, false, 'asdf not devOptional') - t.equal(bar.devOptional, false, 'bar not devOptional') - t.equal(baz.devOptional, false, 'baz not devOptional') - t.equal(foo.devOptional, false, 'foo not devOptional') - t.equal(fooLink.devOptional, false, 'foolink not devOptional') - t.equal(bazLink.devOptional, false, 'bazlink not devOptional') + t.equal(root.extraneous, false, 'root is not extraneous') + t.equal(asdf.extraneous, false, 'asdf is not extraneous') + t.equal(bar.extraneous, false, 'bar is not extraneous') + t.equal(baz.extraneous, false, 'baz is not extraneous') + t.equal(foo.extraneous, false, 'foo is not extraneous') + t.equal(fooLink.extraneous, false, 'fooLink is not extraneous') + t.equal(bazLink.extraneous, false, 'bazLink is not extraneous') t.end() }) diff --git a/workspaces/arborist/test/can-place-dep.js b/workspaces/arborist/test/can-place-dep.js index f319d973106ec..60aedb543795c 100644 --- a/workspaces/arborist/test/can-place-dep.js +++ b/workspaces/arborist/test/can-place-dep.js @@ -33,7 +33,7 @@ t.test('basic placement check tests', t => { preferDedupe, // array of nodes representing the dep's peer group peerSet, - // is this dep the thing the user is explicitly installing? + // is this dep the thing that the user is explicitly installing? explicitRequest, }) => { const target = tree.inventory.get(targetLoc) @@ -1254,7 +1254,7 @@ t.test('basic placement check tests', t => { expect: OK, }) - // same as above, but now the existing one has 3, replacment has 5 + // same as above, but now the existing one has 3, replacement has 5 // v@4 -> PEER(a@1||2) // y@1 -> PEER(d@1) // a@1 -> PEER(b@1) diff --git a/workspaces/arborist/test/case-insensitive-map.js b/workspaces/arborist/test/case-insensitive-map.js index d4a5cc7e7427e..7c63bd67b37ea 100644 --- a/workspaces/arborist/test/case-insensitive-map.js +++ b/workspaces/arborist/test/case-insensitive-map.js @@ -30,7 +30,7 @@ t.test('set values after ctor', t => { t.end() }) -t.test('dont get confused with undefined or weird values', t => { +t.test('do not get confused with undefined or weird values', t => { const cmap = new CMap() cmap.set(undefined, 'this is not defined') cmap.set(NaN, 'this is not a number') diff --git a/workspaces/arborist/test/consistent-resolve.js b/workspaces/arborist/test/consistent-resolve.js index 3792e886fb04e..5fe77bc9031e7 100644 --- a/workspaces/arborist/test/consistent-resolve.js +++ b/workspaces/arborist/test/consistent-resolve.js @@ -55,35 +55,36 @@ t.test('file and directories made consistent if toPath not set', t => { }) t.test('consistent hosted git info urls', t => { - const expect = 'git+ssh://git@github.com/a/b.git' + const expectSsh = 'git+ssh://git@github.com/a/b.git' + const expectHttps = 'git+https://github.com/a/b.git' const expectAuth = 'git+https://user:pass@github.com/a/b.git' - t.equal(cr('a/b'), expect) - t.equal(cr('github:a/b'), expect) - t.equal(cr('git+https://github.com/a/b'), expect) - t.equal(cr('git://github.com/a/b'), expect) - t.equal(cr('git+ssh://git@github.com/a/b'), expect) - t.equal(cr('git+https://github.com/a/b.git'), expect) - t.equal(cr('git://github.com/a/b.git'), expect) - t.equal(cr('git+ssh://git@github.com/a/b.git'), expect) + t.equal(cr('a/b'), expectSsh) + t.equal(cr('github:a/b'), expectSsh) + t.equal(cr('git+https://github.com/a/b'), expectHttps) + t.equal(cr('git://github.com/a/b'), expectSsh) + t.equal(cr('git+ssh://git@github.com/a/b'), expectSsh) + t.equal(cr('git+https://github.com/a/b.git'), expectHttps) + t.equal(cr('git://github.com/a/b.git'), expectSsh) + t.equal(cr('git+ssh://git@github.com/a/b.git'), expectSsh) t.equal(cr('git+https://user:pass@github.com/a/b.git'), expectAuth) const hash = '#0000000000000000000000000000000000000000' - t.equal(cr('a/b' + hash), expect + hash) - t.equal(cr('github:a/b' + hash), expect + hash) - t.equal(cr('git+https://github.com/a/b' + hash), expect + hash) - t.equal(cr('git://github.com/a/b' + hash), expect + hash) - t.equal(cr('git+ssh://git@github.com/a/b' + hash), expect + hash) - t.equal(cr('git+https://github.com/a/b.git' + hash), expect + hash) - t.equal(cr('git://github.com/a/b.git' + hash), expect + hash) - t.equal(cr('git+ssh://git@github.com/a/b.git' + hash), expect + hash) - t.equal(cr('xyz@a/b' + hash), expect + hash) - t.equal(cr('xyz@github:a/b' + hash), expect + hash) - t.equal(cr('xyz@git+https://github.com/a/b' + hash), expect + hash) - t.equal(cr('xyz@git://github.com/a/b' + hash), expect + hash) - t.equal(cr('xyz@git+ssh://git@github.com/a/b' + hash), expect + hash) - t.equal(cr('xyz@git+https://github.com/a/b.git' + hash), expect + hash) - t.equal(cr('xyz@git://github.com/a/b.git' + hash), expect + hash) - t.equal(cr('xyz@git+ssh://git@github.com/a/b.git' + hash), expect + hash) + t.equal(cr('a/b' + hash), expectSsh + hash) + t.equal(cr('github:a/b' + hash), expectSsh + hash) + t.equal(cr('git+https://github.com/a/b' + hash), expectHttps + hash) + t.equal(cr('git://github.com/a/b' + hash), expectSsh + hash) + t.equal(cr('git+ssh://git@github.com/a/b' + hash), expectSsh + hash) + t.equal(cr('git+https://github.com/a/b.git' + hash), expectHttps + hash) + t.equal(cr('git://github.com/a/b.git' + hash), expectSsh + hash) + t.equal(cr('git+ssh://git@github.com/a/b.git' + hash), expectSsh + hash) + t.equal(cr('xyz@a/b' + hash), expectSsh + hash) + t.equal(cr('xyz@github:a/b' + hash), expectSsh + hash) + t.equal(cr('xyz@git+https://github.com/a/b' + hash), expectHttps + hash) + t.equal(cr('xyz@git://github.com/a/b' + hash), expectSsh + hash) + t.equal(cr('xyz@git+ssh://git@github.com/a/b' + hash), expectSsh + hash) + t.equal(cr('xyz@git+https://github.com/a/b.git' + hash), expectHttps + hash) + t.equal(cr('xyz@git://github.com/a/b.git' + hash), expectSsh + hash) + t.equal(cr('xyz@git+ssh://git@github.com/a/b.git' + hash), expectSsh + hash) t.end() }) diff --git a/workspaces/arborist/test/dep-valid.js b/workspaces/arborist/test/dep-valid.js index ce6af25243c6c..436e2afac1222 100644 --- a/workspaces/arborist/test/dep-valid.js +++ b/workspaces/arborist/test/dep-valid.js @@ -9,133 +9,136 @@ const emptyRequestor = { edgesOut: new Map(), } -t.ok(depValid({}, '', null, emptyRequestor), '* is always ok') - -t.ok(depValid({ - package: { - version: '1.2.3', - }, - get version () { - return this.package.version - }, -}, '1.x', null, emptyRequestor), 'range that is satisfied') - -t.ok(depValid({ - package: { - version: '2.2.3', - }, - get version () { - return this.package.version - }, -}, '1.x', '2.x', emptyRequestor), 'range that is acceptable') - -t.ok(depValid({ - isLink: true, - realpath: '/some/path', -}, normalizePaths(npa('file:/some/path')), null, emptyRequestor), 'links must point at intended target') - -t.notOk(depValid({ - isLink: true, - realpath: '/some/other/path', -}, 'file:/some/path', null, emptyRequestor), 'links must point at intended target') - -t.notOk(depValid({ - realpath: '/some/path', -}, 'file:/some/path', null, emptyRequestor), 'file:// must be a link') - -t.ok(depValid({ - name: 'foo', - resolved: 'git://host/repo#somebranch', - package: { - version: '1.2.3', - }, - get version () { - return this.package.version - }, -}, 'git://host/repo#semver:1.x', null, emptyRequestor), 'git url with semver range') - -t.ok(depValid({ - name: 'foo', - package: { - name: 'bar', - version: '1.2.3', - }, - get version () { - return this.package.version - }, -}, 'npm:bar@1.2.3', null, emptyRequestor), 'alias is ok') - -t.ok(depValid({ - resolved: 'https://registry/abbrev-1.1.1.tgz', - package: {}, - get version () { - return this.package.version - }, -}, 'https://registry/abbrev-1.1.1.tgz', null, emptyRequestor), 'remote url match') - -t.ok(depValid({ - resolved: 'git+ssh://git@github.com/foo/bar', - package: {}, - get version () { - return this.package.version - }, -}, 'git+ssh://git@github.com/foo/bar.git', null, emptyRequestor), 'matching _from saveSpec') - -t.notOk(depValid({ - resolved: 'git+ssh://git@github.com/foo/bar', - package: {}, - get version () { - return this.package.version - }, -}, 'git+ssh://git@github.com/bar/foo.git', null, emptyRequestor), 'different repo') - -t.notOk(depValid({ - package: {}, - get version () { - return this.package.version - }, -}, 'git+ssh://git@github.com/bar/foo.git', null, emptyRequestor), 'missing repo') - -t.ok(depValid({ - resolved: `file:${resolve('/path/to/tarball.tgz')}`, -}, resolve('/path/to/tarball.tgz'), null, emptyRequestor), 'same tarball') - -t.notOk(depValid({ - resolved: 'file:/path/to/other/tarball.tgz', -}, '/path/to/tarball.tgz', null, emptyRequestor), 'different tarball') - -t.notOk(depValid({ - isLink: true, -}, '/path/to/tarball.tgz', null, emptyRequestor), 'links are not tarballs') - -t.ok(depValid({ - package: { - _requested: { - saveSpec: 'file:tarball.tgz', - }, - }, - get version () { - return this.package.version - }, -}, './tarball.tgz', null, emptyRequestor), 'probably the same-ish, hopefully') - -t.notOk(depValid({ - package: {}, - get version () { - return this.package.version - }, -}, './tarball.tgz', null, emptyRequestor), 'too uncertain, nope') - -t.ok(depValid({ - resolved: 'https://registry.npmjs.org/foo/foo-1.2.3.tgz', -}, 'latest', null, emptyRequestor), 'tagged registry version needs remote tarball') - -t.notOk(depValid({ - resolved: 'git+https://registry.npmjs.org/foo/foo-1.2.3.git', -}, 'latest', null, emptyRequestor), 'tagged registry version needs remote tarball, not git') - -t.notOk(depValid({}, 'latest', null, emptyRequestor), - 'tagged registry version needs remote tarball resolution') +t.test('basic', t => { + t.ok(depValid({}, '', null, emptyRequestor), '* is always ok') + + t.ok(depValid({ + package: { + version: '1.2.3', + }, + get version () { + return this.package.version + }, + }, '1.x', null, emptyRequestor), 'range that is satisfied') + + t.ok(depValid({ + package: { + version: '2.2.3', + }, + get version () { + return this.package.version + }, + }, '1.x', '2.x', emptyRequestor), 'range that is acceptable') + + t.ok(depValid({ + isLink: true, + realpath: '/some/path', + }, normalizePaths(npa('file:/some/path')), null, emptyRequestor), 'links must point at intended target') + + t.notOk(depValid({ + isLink: true, + realpath: '/some/other/path', + }, 'file:/some/path', null, emptyRequestor), 'links must point at intended target') + + t.notOk(depValid({ + realpath: '/some/path', + }, 'file:/some/path', null, emptyRequestor), 'file:// must be a link') + + t.ok(depValid({ + name: 'foo', + resolved: 'git://host/repo#somebranch', + package: { + version: '1.2.3', + }, + get version () { + return this.package.version + }, + }, 'git://host/repo#semver:1.x', null, emptyRequestor), 'git url with semver range') + + t.ok(depValid({ + name: 'foo', + package: { + name: 'bar', + version: '1.2.3', + }, + get version () { + return this.package.version + }, + }, 'npm:bar@1.2.3', null, emptyRequestor), 'alias is ok') + + t.ok(depValid({ + resolved: 'https://registry/abbrev-1.1.1.tgz', + package: {}, + get version () { + return this.package.version + }, + }, 'https://registry/abbrev-1.1.1.tgz', null, emptyRequestor), 'remote url match') + + t.ok(depValid({ + resolved: 'git+ssh://git@github.com/foo/bar', + package: {}, + get version () { + return this.package.version + }, + }, 'git+ssh://git@github.com/foo/bar.git', null, emptyRequestor), 'matching _from saveSpec') + + t.notOk(depValid({ + resolved: 'git+ssh://git@github.com/foo/bar', + package: {}, + get version () { + return this.package.version + }, + }, 'git+ssh://git@github.com/bar/foo.git', null, emptyRequestor), 'different repo') + + t.notOk(depValid({ + package: {}, + get version () { + return this.package.version + }, + }, 'git+ssh://git@github.com/bar/foo.git', null, emptyRequestor), 'missing repo') + + t.ok(depValid({ + resolved: `file:${resolve('/path/to/tarball.tgz')}`, + }, resolve('/path/to/tarball.tgz'), null, emptyRequestor), 'same tarball') + + t.notOk(depValid({ + resolved: 'file:/path/to/other/tarball.tgz', + }, '/path/to/tarball.tgz', null, emptyRequestor), 'different tarball') + + t.notOk(depValid({ + isLink: true, + }, '/path/to/tarball.tgz', null, emptyRequestor), 'links are not tarballs') + + t.ok(depValid({ + package: { + _requested: { + saveSpec: 'file:tarball.tgz', + }, + }, + get version () { + return this.package.version + }, + }, './tarball.tgz', null, emptyRequestor), 'probably the same-ish, hopefully') + + t.notOk(depValid({ + package: {}, + get version () { + return this.package.version + }, + }, './tarball.tgz', null, emptyRequestor), 'too uncertain, nope') + + t.ok(depValid({ + resolved: 'https://registry.npmjs.org/foo/foo-1.2.3.tgz', + }, 'latest', null, emptyRequestor), 'tagged registry version needs remote tarball') + + t.notOk(depValid({ + resolved: 'git+https://registry.npmjs.org/foo/foo-1.2.3.git', + }, 'latest', null, emptyRequestor), 'tagged registry version needs remote tarball, not git') + + t.notOk(depValid({}, 'latest', null, emptyRequestor), + 'tagged registry version needs remote tarball resolution') + t.end() +}) t.test('unsupported dependency type', t => { const requestor = { errors: [], edgesOut: new Map() } @@ -202,3 +205,111 @@ t.test('installLinks does not make workspace nodes invalid', t => { t.ok(depValid(child, request, null, requestor)) t.end() }) + +t.test('sha-1 and sha-256', t => { + t.ok(depValid({ + name: 'foo', + resolved: 'npm/repo#0d7bd85a85fa2571fa532d2fc842ed099b236ad2', + package: { + version: '1.2.3', + }, + get version () { + return this.package.version + }, + }, 'npm/repo#0d7bd85a85fa2571fa532d2fc842ed099b236ad2', null, emptyRequestor), 'git url with full sha-1 hash match') + + t.notOk(depValid({ + name: 'foo', + resolved: 'npm/repo#0d7bd85a85fa2571fa532d2fc842ed099b236ad2', + package: { + version: '1.2.3', + }, + get version () { + return this.package.version + }, + }, 'npm/repo#1d7bd85a85fa2571fa532d2fc842ed099b236ad2', null, emptyRequestor), 'git url with full sha-1 hash mismatch') + + t.ok(depValid({ + name: 'foo', + resolved: 'npm/repo#8e3a9b3579ab330238c06b761e7f1b5dc5b4ac6e5a96da4dd2fb3b7411009df8', + package: { + version: '1.2.3', + }, + get version () { + return this.package.version + }, + }, 'npm/repo#8e3a9b3579ab330238c06b761e7f1b5dc5b4ac6e5a96da4dd2fb3b7411009df8', null, emptyRequestor), 'git url with full sha-256 hash match') + + t.notOk(depValid({ + name: 'foo', + resolved: 'npm/repo#8e3a9b3579ab330238c06b761e7f1b5dc5b4ac6e5a96da4dd2fb3b7411009df8', + package: { + version: '1.2.3', + }, + get version () { + return this.package.version + }, + }, 'npm/repo#9e3a9b3579ab330238c06b761e7f1b5dc5b4ac6e5a96da4dd2fb3b7411009df8', null, emptyRequestor), 'git url with full sha-256 hash mismatch') + + t.end() +}) + +t.test('git tag/branch change detected via lockfile committish', t => { + // a named ref points at a commit hash, so the recorded committish tells us + // whether the spec changed + const mkRequestor = (recorded) => ({ + errors: [], + edgesOut: new Map(), + realpath: resolve('/some/path'), + location: '', + root: { + meta: { data: { packages: { '': recorded } } }, + }, + }) + + const child = { + name: 'repo', + resolved: 'git+ssh://git@github.com/npm/repo.git#0d7bd85a85fa2571fa532d2fc842ed099b236ad2', + package: { version: '1.0.0' }, + get version () { + return this.package.version + }, + } + + t.ok(depValid(child, 'npm/repo#v1.0.0', null, + mkRequestor({ dependencies: { repo: 'npm/repo#v1.0.0' } })), + 'unchanged tag is valid') + + t.notOk(depValid(child, 'npm/repo#v2.0.0', null, + mkRequestor({ dependencies: { repo: 'npm/repo#v1.0.0' } })), + 'changed tag must be re-resolved') + + t.notOk(depValid(child, 'npm/repo#other', null, + mkRequestor({ devDependencies: { repo: 'npm/repo#main' } })), + 'changed branch in devDependencies must be re-resolved') + + t.notOk(depValid(child, 'npm/repo#v2.0.0', null, + mkRequestor({ optionalDependencies: { repo: 'npm/repo#v1.0.0' } })), + 'changed tag in optionalDependencies must be re-resolved') + + t.notOk(depValid(child, 'npm/repo#other', null, + mkRequestor({ peerDependencies: { repo: 'npm/repo#main' } })), + 'changed branch in peerDependencies must be re-resolved') + + t.notOk(depValid(child, 'npm/repo#v2.0.0', null, + mkRequestor({ dependencies: { repo: 'npm/repo' } })), + 'lockfile git spec without a committish differs from a named ref') + + t.ok(depValid(child, 'npm/repo#v2.0.0', null, + mkRequestor({ dependencies: { repo: '^1.0.0' } })), + 'non-git lockfile spec is ignored, falling back to the repo-only check') + + t.ok(depValid(child, 'npm/repo#v2.0.0', null, emptyRequestor), + 'without lockfile data, fall back to the repo-only check') + + t.ok(depValid(child, 'npm/repo#v2.0.0', null, + mkRequestor({ dependencies: { repo: 'invalid spec with spaces' } })), + 'unparseable lockfile spec is ignored, falling back to the repo-only check') + + t.end() +}) diff --git a/workspaces/arborist/test/diff.js b/workspaces/arborist/test/diff.js index 219a0bb383a29..c0e6dff538ee5 100644 --- a/workspaces/arborist/test/diff.js +++ b/workspaces/arborist/test/diff.js @@ -356,74 +356,6 @@ t.test('filtered diff', async t => { t.matchSnapshot(eRemovedExtraneous, 'e is removed (extraneous)') }) -t.test('diff doesnt break unchanged shrinkwrapped deps', async t => { - const actual = new Node({ - name: 'a', - path: '/path/to/actual', - children: [{ - name: 'shrinkwrapped-dep', - hasShrinkwrap: true, - integrity: 'sha512-ddd', - children: [ - { name: 'shrinkwrap-inner-a', integrity: 'sha512-aaa' }, - { name: 'shrinkwrap-inner-b', integrity: 'sha512-bbb' }, - ], - }, { - name: 'regular-dep', - integrity: 'sha512-eee', - children: [{ - name: 'shrinkwrapped-inner', - hasShrinkwrap: true, - integrity: 'sha512-fff', - children: [{ - name: 'shrinkwrap-inner-c', - integrity: 'sha512-ccc', - }], - }], - }], - }) - - const ideal = new Node({ - name: 'a', - path: '/path/to/actual', - children: [{ - name: 'shrinkwrapped-dep', - hasShrinkwrap: true, - integrity: 'sha512-ddd', - }, { - name: 'regular-dep', - integrity: 'sha512-eee', - children: [{ - name: 'shrinkwrapped-inner', - hasShrinkwrap: true, - integrity: 'sha512-fff', - children: [{ - name: 'shrinkwrap-inner-c', - integrity: 'sha512-ccc', - }], - }], - }], - }) - - // putting the shrinkwrapped-inner node in the shrinkwrapInflated set - // allows us to fake the behavior of reifying the node and then - // running a second diff that includes that node's children. this - // is reflected by the children of the shrinkwrapped-inner node being - // marked as unchanged. - const shrinkwrappedInner = ideal.children.get('regular-dep') - .children.get('shrinkwrapped-inner') - const diff = Diff.calculate({ - actual, - ideal, - shrinkwrapInflated: new Set([shrinkwrappedInner]), - }) - t.matchSnapshot(diff, 'made no changes') - - t.equal(diff.leaves.length, 1, 'diff has exactly one leaf') - t.match(diff.leaves[0], { action: null, ideal: { name: 'shrinkwrapped-dep' } }, - 'the shrinkwrapped dep is in the leaves with a null action') -}) - t.test('extraneous pruning in workspaces', async t => { // just load the virtual tree here twice, // and then remove the extraneous ones from the 'ideal' @@ -507,6 +439,30 @@ t.test('extraneous pruning in workspaces', async t => { t.matchSnapshot(pruneWsB, 'prune in workspace B') }) +t.test('a removed patch forces a CHANGE even when other metadata matches', t => { + const integrity = 'sha512-iWml6OqIudarD/AngxZbQoeX0QoPywHRJ2rJbCcB0l9BfL1c5+Tl433R3V+AU404jppRHZGBofm97m48yKTRiA==' + const resolved = 'https://registry.npmjs.org/foo/-/foo-1.0.0.tgz' + const build = () => new Node({ + path: '/some/path', + pkg: { dependencies: { foo: '' } }, + children: [ + { name: 'foo', resolved, integrity, pkg: { name: 'foo', version: '1.0.0' } }, + ], + }) + const actual = build() + + // identical trees produce no diff entry for foo + t.equal(Diff.calculate({ actual, ideal: build() }).children.length, 0) + + // but a node marked patchRemoved must be re-extracted to revert its files + const ideal = build() + ideal.children.get('foo').patchRemoved = true + t.match(Diff.calculate({ actual, ideal }).children, [ + { ideal: ideal.children.get('foo'), action: 'CHANGE' }, + ]) + t.end() +}) + t.test('check versions (even if all other metadata is missing)', t => { const actual = new Node({ path: '/some/path', diff --git a/workspaces/arborist/test/edge.js b/workspaces/arborist/test/edge.js index bb8977897fcc0..f5ea071553195 100644 --- a/workspaces/arborist/test/edge.js +++ b/workspaces/arborist/test/edge.js @@ -57,6 +57,9 @@ const top = { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } const a = { @@ -81,6 +84,9 @@ const a = { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } const b = { @@ -104,6 +110,9 @@ const b = { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } const bb = { @@ -127,6 +136,9 @@ const bb = { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } const aa = { @@ -150,6 +162,9 @@ const aa = { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } const c = { @@ -173,6 +188,9 @@ const c = { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } t.matchSnapshot(new Edge({ @@ -180,7 +198,7 @@ t.matchSnapshot(new Edge({ type: 'peer', name: 'a', spec: '1.2.3', -}), 'peer dep at top level, nesting is ok') +}), 'peer dep at top level, nesting allowed') reset(top) reset(a) @@ -197,7 +215,7 @@ t.matchSnapshot(new Edge({ type: 'peer', name: 'aa', spec: '1.2.3', -}), 'peer dep below top level, nesting not ok') +}), 'peer dep below top level, nesting disallowed') reset(a) reset(aa) @@ -206,7 +224,7 @@ t.matchSnapshot(new Edge({ type: 'peer', name: 'b', spec: '1.2.3', -}), 'peer dep below top level, parallel ok') +}), 'peer dep below top level, parallel allowed') reset(a) reset(b) @@ -364,6 +382,9 @@ const referenceTop = { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, overrides: new OverrideSet({ overrides: { referenceGrandchild: '$referenceChild', @@ -403,6 +424,9 @@ const referenceChild = { this.overrides = edge.overrides this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } new Edge({ @@ -442,6 +466,9 @@ const referenceGrandchild = { this.overrides = edge.overrides this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } const referenceGrandchildEdge = new Edge({ @@ -490,6 +517,9 @@ const badOverride = { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, overrides: new OverrideSet({ overrides: { b: '1.x', @@ -775,6 +805,9 @@ const bundleChild = { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } const bundleParent = { @@ -797,6 +830,9 @@ const bundleParent = { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } const bundledEdge = new Edge({ @@ -858,6 +894,9 @@ t.test('override references find the correct root', (t) => { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } const foo = { @@ -885,6 +924,9 @@ t.test('override references find the correct root', (t) => { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } foo.overrides = overrides.getNodeRule(foo) @@ -915,6 +957,9 @@ t.test('override references find the correct root', (t) => { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } bar.overrides = foo.overrides.getNodeRule(bar) @@ -946,6 +991,9 @@ t.test('override references find the correct root', (t) => { addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } virtualBar.overrides = overrides @@ -961,27 +1009,133 @@ t.test('override references find the correct root', (t) => { t.end() }) -t.test('shrinkwrapped and bundled deps are not overridden and remain valid', (t) => { - const overrides = new OverrideSet({ +t.test('overrideset comparison logic', (t) => { + const overrides1 = new OverrideSet({ + overrides: { + bar: '^2.0.0', + }, + }) + + const overrides2 = new OverrideSet({ + overrides: { + bar: '^2.0.0', + }, + }) + + const overrides3 = new OverrideSet({ + overrides: { + foo: '^2.0.0', + }, + }) + + const overrides4 = new OverrideSet({ + overrides: { + foo: '^1.0.0', + }, + }) + + const overrides5 = new OverrideSet({ overrides: { bar: '^2.0.0', + foo: '^2.0.0', + }, + }) + + const overrides6 = new OverrideSet({ + overrides: { + }, + }) + + const overrides7 = new OverrideSet({ + overrides: { + bar: { + '.': '^2.0.0', + baz: '1.2.3', + }, + }, + }) + + t.ok(overrides1.isEqual(overrides1), 'overridesets are equal') + t.ok(overrides1.isEqual(overrides2), 'overridesets are equal') + t.ok(!overrides1.isEqual(overrides3), 'overridesets are different') + t.ok(!overrides1.isEqual(overrides5), 'overridesets are different') + t.ok(!overrides1.isEqual(overrides6), 'overridesets are different') + t.ok(!overrides1.isEqual(overrides7), 'overridesets are different') + t.ok(!overrides3.isEqual(overrides1), 'overridesets are different') + t.ok(!overrides3.isEqual(overrides4), 'overridesets are different') + t.ok(!overrides3.isEqual(overrides5), 'overridesets are different') + t.ok(!overrides4.isEqual(overrides5), 'overridesets are different') + t.ok(!overrides5.isEqual(overrides1), 'overridesets are different') + t.ok(!overrides5.isEqual(overrides3), 'overridesets are different') + t.ok(!overrides5.isEqual(overrides6), 'overridesets are different') + t.ok(!overrides6.isEqual(overrides1), 'overridesets are different') + t.ok(!overrides6.isEqual(overrides3), 'overridesets are different') + t.ok(overrides6.isEqual(overrides6), 'overridesets are equal') + t.ok(!overrides7.isEqual(overrides1), 'overridesets are different') + t.end() +}) + +t.test('override fallback to local when root missing dependency with from.overrides set', t => { + const localFrom = { + package: { + devDependencies: { + foo: '^1.2.3', + }, + }, + root: { + package: { + // no 'foo' defined here + }, + }, + edgesOut: new Map(), + edgesIn: new Set(), + // dummy overrides object that returns an override with isEqual defined + overrides: { + getEdgeRule (edge) { + return { + value: edge.overrides.value, + name: edge.overrides.name, + isEqual (other) { + return other && this.value === other.value && this.name === other.name + }, + } + }, + }, + addEdgeOut (edge) { + this.edgesOut.set(edge.name, edge) + }, + resolve () { + return null + }, + } + + const edge = new Edge({ + from: localFrom, + type: 'prod', + name: 'foo', + spec: '1.x', + overrides: { + value: '$foo', + name: 'foo', }, }) + t.equal(edge.spec, '^1.2.3', 'should fall back to local package version from devDependencies') + t.end() +}) + +t.test('edge with overrides should not crash when target has no overrides', t => { const root = { name: 'root', - packageName: 'root', edgesOut: new Map(), edgesIn: new Set(), - explain: () => 'root node explanation', + explain: () => 'root', package: { name: 'root', - version: '1.2.3', - dependencies: { - foo: '^1.0.0', - }, + version: '1.0.0', overrides: { - bar: '^2.0.0', + react: '^18.3.1', + 'react-dom': '^18.3.1', }, }, get version () { @@ -989,9 +1143,14 @@ t.test('shrinkwrapped and bundled deps are not overridden and remain valid', (t) }, isTop: true, parent: null, - overrides, + overrides: new OverrideSet({ + overrides: { + react: '^18.3.1', + 'react-dom': '^18.3.1', + }, + }), resolve (n) { - return n === 'foo' ? foo : null + return n === 'dep' ? dep : null }, addEdgeOut (edge) { this.edgesOut.set(edge.name, edge) @@ -999,29 +1158,29 @@ t.test('shrinkwrapped and bundled deps are not overridden and remain valid', (t) addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } - const foo = { - name: 'foo', - packageName: 'foo', - edgesOut: new Map(), + // Target node with dependencies but NO overrides + const dep = { + name: 'dep', + edgesOut: new Map([ + // Has dependencies so edgesOut.size > 0 + ['some-lib', { name: 'some-lib', peer: false }], + ]), edgesIn: new Set(), - explain: () => 'foo node explanation', - hasShrinkwrap: true, - package: { - name: 'foo', - version: '1.2.3', - dependencies: { - bar: '^1.0.0', - }, - }, + explain: () => 'dep', + package: { name: 'dep', version: '1.0.0' }, get version () { return this.package.version }, parent: root, root, - resolve (n) { - return n === 'bar' ? bar : this.parent.resolve(n) + // NO overrides property - this causes this.#to.overrides to be undefined + resolve () { + return null }, addEdgeOut (edge) { this.edgesOut.set(edge.name, edge) @@ -1029,46 +1188,92 @@ t.test('shrinkwrapped and bundled deps are not overridden and remain valid', (t) addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, } - foo.overrides = overrides.getNodeRule(foo) - const bar = { - name: 'bar', - packageName: 'bar', + // Create an edge from root to dep + // Root has overrides, dep has dependencies but no overrides + const edge = new Edge({ + from: root, + type: 'prod', + spec: '^1.0.0', + name: 'dep', + overrides: root.overrides, + }) + + t.doesNotThrow(() => { + const err = edge.error + t.equal(err, null, 'edge should be valid (no error)') + }, 'should not crash when target node has no overrides') + + t.ok(edge.valid, 'edge should be valid') + t.end() +}) + +t.test('overrides and bundled deps in satisfiedBy', t => { + const makeNode = (name, version, extras = {}) => ({ + name, + packageName: name, + version, + package: { name, version }, edgesOut: new Map(), edgesIn: new Set(), - explain: () => 'bar node explanation', - inShrinkwrap: true, - package: { - name: 'bar', - version: '1.2.3', - dependencies: {}, - }, - get version () { - return this.package.version - }, - parent: foo, - root, - resolve (n) { - return this.parent.resolve(n) - }, + explain: () => `${name}@${version}`, + isTop: false, + parent: top, + resolve: () => undefined, addEdgeOut (edge) { this.edgesOut.set(edge.name, edge) }, addEdgeIn (edge) { this.edgesIn.add(edge) }, + deleteEdgeIn (edge) { + this.edgesIn.delete(edge) + }, + inBundle: false, + inDepBundle: false, + ...extras, + }) + + const overrides = new OverrideSet({ overrides: { bar: '2.x' } }) + a.overrides = overrides + + const makeOverriddenEdge = () => { + const edge = new Edge({ + from: a, + type: 'prod', + name: 'bar', + spec: '1.x', + overrides: overrides.getEdgeRule({ name: 'bar', spec: '1.x' }), + }) + reset(a) + a.overrides = overrides + return edge } - bar.overrides = foo.overrides.getNodeRule(bar) - const edge = new Edge({ - from: foo, - type: 'prod', - spec: '^1.0.0', - name: 'bar', - overrides: overrides.getEdgeRule({ name: 'bar', spec: '^1.0.0' }), + t.test('node bundled by root uses overridden spec', t => { + const edge = makeOverriddenEdge() + const node = makeNode('bar', '2.0.0', { inBundle: true, inDepBundle: false }) + t.ok(edge.satisfiedBy(node), 'bar@2.0.0 bundled by root satisfies override 2.x') + + const nodeOld = makeNode('bar', '1.0.0', { inBundle: true, inDepBundle: false }) + t.notOk(edge.satisfiedBy(nodeOld), 'bar@1.0.0 bundled by root does not satisfy override 2.x') + t.end() }) - t.ok(edge.valid, 'edge is valid') + t.test('node bundled inside a dependency uses rawSpec', t => { + const edge = makeOverriddenEdge() + const node = makeNode('bar', '1.0.0', { inBundle: true, inDepBundle: true }) + t.ok(edge.satisfiedBy(node), 'bar@1.0.0 in dep bundle satisfies rawSpec 1.x') + + const nodeNew = makeNode('bar', '2.0.0', { inBundle: true, inDepBundle: true }) + t.notOk(edge.satisfiedBy(nodeNew), 'bar@2.0.0 in dep bundle does not satisfy rawSpec 1.x') + t.end() + }) + + delete a.overrides t.end() }) diff --git a/workspaces/arborist/test/fixtures/audit-linked-package/package-lock.json b/workspaces/arborist/test/fixtures/audit-linked-package/package-lock.json new file mode 100644 index 0000000000000..2ee513d9a81e5 --- /dev/null +++ b/workspaces/arborist/test/fixtures/audit-linked-package/package-lock.json @@ -0,0 +1,20 @@ +{ + "name": "audit-linked-package", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "audit-linked-package", + "dependencies": { + "electron-test-app": "1.0.0" + } + }, + "node_modules/electron-test-app": { + "resolved": "resolved/electron-test-app", + "link": true + }, + "resolved/electron-test-app": { + "version": "1.0.0" + } + } +} diff --git a/workspaces/arborist/test/fixtures/audit-linked-package/package.json b/workspaces/arborist/test/fixtures/audit-linked-package/package.json new file mode 100644 index 0000000000000..cbcc0a24522fb --- /dev/null +++ b/workspaces/arborist/test/fixtures/audit-linked-package/package.json @@ -0,0 +1,6 @@ +{ + "name": "audit-linked-package", + "dependencies": { + "electron-test-app": "1.0.0" + } +} diff --git a/workspaces/arborist/test/fixtures/create-reify-case.js b/workspaces/arborist/test/fixtures/create-reify-case.js index 5d2349dd33076..33bd44c185826 100644 --- a/workspaces/arborist/test/fixtures/create-reify-case.js +++ b/workspaces/arborist/test/fixtures/create-reify-case.js @@ -129,7 +129,7 @@ if (hiddenLocks.length) { } } -writeFileSync(outFile, `// generated from ${rel} +writeFileSync(outFile, `// generated from ${rel.replaceAll('\\', '/')} module.exports = t => { const path = ${output} return path diff --git a/workspaces/arborist/test/fixtures/engine-omit-test/node_modules/strict-engine-dev/package.json b/workspaces/arborist/test/fixtures/engine-omit-test/node_modules/strict-engine-dev/package.json new file mode 100644 index 0000000000000..5e7f43804b7dd --- /dev/null +++ b/workspaces/arborist/test/fixtures/engine-omit-test/node_modules/strict-engine-dev/package.json @@ -0,0 +1,8 @@ +{ + "name": "strict-engine-dev", + "version": "1.0.0", + "description": "A devDependency with strict engine requirements", + "engines": { + "node": ">=18.0.0" + } +} diff --git a/workspaces/arborist/test/fixtures/engine-omit-test/package.json b/workspaces/arborist/test/fixtures/engine-omit-test/package.json new file mode 100644 index 0000000000000..d6f46b366c420 --- /dev/null +++ b/workspaces/arborist/test/fixtures/engine-omit-test/package.json @@ -0,0 +1,7 @@ +{ + "name": "engine-omit-test", + "version": "1.0.0", + "devDependencies": { + "strict-engine-dev": "1.0.0" + } +} diff --git a/workspaces/arborist/test/fixtures/index.js b/workspaces/arborist/test/fixtures/index.js index 1ec9159a2b598..af4cb5bb5439a 100644 --- a/workspaces/arborist/test/fixtures/index.js +++ b/workspaces/arborist/test/fixtures/index.js @@ -22,7 +22,7 @@ const roots = [ 'root', // This test flakes out on Apple Silicon // https://github.com/npm/cli/pull/7411 - process.platform === 'darwin' && process.arch === 'arm64' + process.platform === 'darwin' && process.arch === 'arm64' && process.env.TAP_SNAPSHOT !== '1' ? null : 'selflink', 'symlinked-node-modules/example', diff --git a/workspaces/arborist/test/fixtures/isolated-nock.js b/workspaces/arborist/test/fixtures/isolated-nock.js index 6593c7f0d1935..61694a6dd8f0b 100644 --- a/workspaces/arborist/test/fixtures/isolated-nock.js +++ b/workspaces/arborist/test/fixtures/isolated-nock.js @@ -27,12 +27,12 @@ class StreamToBuffer extends Stream.Writable { * packPackageToStream * Uses 'tar-stream' to create the tar stream without touching the file system. */ -function packPackageToStream (manifest, reg) { +function packPackageToStream (manifest) { const { name, version, } = manifest - const { shrinkwrap, bundledDeps, ...rest } = manifest + const { bundledDeps, ...rest } = manifest const pack = tar.pack() const manifestString = JSON.stringify({ @@ -44,9 +44,6 @@ function packPackageToStream (manifest, reg) { pack.entry({ name: `${unscopedName}/package.json` }, manifestString) pack.entry({ name: `${unscopedName}/index.js` }, index) pack.entry({ name: `${unscopedName}/bin.js` }, '#!/usr/bin/env node\nconsole.log("bin")') - if (shrinkwrap) { - pack.entry({ name: `${unscopedName}/npm-shrinkwrap.json` }, shrinkwrap.replace(/##REG##/g, reg)) - } if (bundledDeps) { pack.entry({ name: `${unscopedName}/node_modules`, type: 'directory' }) bundledDeps.forEach(d => { @@ -65,8 +62,8 @@ function packPackageToStream (manifest, reg) { * Pack a package for publish. * Returns a buffer containing a tarball of the package. */ -async function packPackage (manifest, reg) { - const packStream = packPackageToStream(manifest, reg) +async function packPackage (manifest) { + const packStream = packPackageToStream(manifest) const tarBuffer = packStream.pipe(new StreamToBuffer()) @@ -86,7 +83,7 @@ async function publishPackage (registry, manifest, packuments) { name, version, } = manifest - const { shrinkwrap, bundledDeps, ...rest } = manifest + const { bundledDeps, ...rest } = manifest if (packuments.has(name)) { packuments.get(name).versions[version] = { @@ -114,7 +111,7 @@ async function publishPackage (registry, manifest, packuments) { }) } - const tarball = await packPackage(manifest, registry) + const tarball = await packPackage(manifest) nock(registry) .persist() @@ -164,9 +161,13 @@ async function getRepo (graph) { // Generate the root of the graph on disk const root = graph.root const workspaces = graph.workspaces || [] + const hasScoped = workspaces.some(w => w.name.startsWith('@')) + const workspaceGlobs = hasScoped + ? ['packages/*', 'packages/@*/*'] + : ['packages/*'] const repo = { 'package.json': JSON.stringify({ - workspaces: workspaces.length !== 0 ? ['packages/*'] : undefined, + workspaces: workspaces.length !== 0 ? workspaceGlobs : undefined, ...root, }), packages: {}, @@ -192,7 +193,7 @@ function createDir (dir, structure) { Object.entries(structure).forEach(([key, value]) => { if (typeof value === 'object') { const newDir = path.join(dir, key) - fs.mkdirSync(newDir) + fs.mkdirSync(newDir, { recursive: true }) createDir(newDir, value) } else { fs.writeFileSync(path.join(dir, key), value) diff --git a/workspaces/arborist/test/fixtures/optional-engine-omit-test/node_modules/strict-engine-optional/package.json b/workspaces/arborist/test/fixtures/optional-engine-omit-test/node_modules/strict-engine-optional/package.json new file mode 100644 index 0000000000000..3d8d97b4f35e8 --- /dev/null +++ b/workspaces/arborist/test/fixtures/optional-engine-omit-test/node_modules/strict-engine-optional/package.json @@ -0,0 +1,8 @@ +{ + "name": "strict-engine-optional", + "version": "1.0.0", + "description": "An optionalDependency with strict engine requirements", + "engines": { + "node": ">=18.0.0" + } +} diff --git a/workspaces/arborist/test/fixtures/optional-engine-omit-test/package.json b/workspaces/arborist/test/fixtures/optional-engine-omit-test/package.json new file mode 100644 index 0000000000000..f2ee2977c4b83 --- /dev/null +++ b/workspaces/arborist/test/fixtures/optional-engine-omit-test/package.json @@ -0,0 +1,7 @@ +{ + "name": "optional-engine-omit-test", + "version": "1.0.0", + "optionalDependencies": { + "strict-engine-optional": "1.0.0" + } +} diff --git a/workspaces/arborist/test/fixtures/peer-engine-omit-test/node_modules/strict-engine-peer/package.json b/workspaces/arborist/test/fixtures/peer-engine-omit-test/node_modules/strict-engine-peer/package.json new file mode 100644 index 0000000000000..97f99cdfcbde2 --- /dev/null +++ b/workspaces/arborist/test/fixtures/peer-engine-omit-test/node_modules/strict-engine-peer/package.json @@ -0,0 +1,8 @@ +{ + "name": "strict-engine-peer", + "version": "1.0.0", + "description": "A peerDependency with strict engine requirements", + "engines": { + "node": ">=18.0.0" + } +} diff --git a/workspaces/arborist/test/fixtures/peer-engine-omit-test/package.json b/workspaces/arborist/test/fixtures/peer-engine-omit-test/package.json new file mode 100644 index 0000000000000..6c1fe95fffa1c --- /dev/null +++ b/workspaces/arborist/test/fixtures/peer-engine-omit-test/package.json @@ -0,0 +1,7 @@ +{ + "name": "peer-engine-omit-test", + "version": "1.0.0", + "peerDependencies": { + "strict-engine-peer": "1.0.0" + } +} diff --git a/workspaces/arborist/test/fixtures/prune-lockfile-optional-peer/node_modules/dedent/package.json b/workspaces/arborist/test/fixtures/prune-lockfile-optional-peer/node_modules/dedent/package.json new file mode 100644 index 0000000000000..50a7c71cc90d2 --- /dev/null +++ b/workspaces/arborist/test/fixtures/prune-lockfile-optional-peer/node_modules/dedent/package.json @@ -0,0 +1,12 @@ +{ + "name": "dedent", + "version": "1.6.0", + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } +} \ No newline at end of file diff --git a/workspaces/arborist/test/fixtures/prune-lockfile-optional-peer/package-lock.json b/workspaces/arborist/test/fixtures/prune-lockfile-optional-peer/package-lock.json new file mode 100644 index 0000000000000..80b2ec4d213d9 --- /dev/null +++ b/workspaces/arborist/test/fixtures/prune-lockfile-optional-peer/package-lock.json @@ -0,0 +1,31 @@ +{ + "name": "prune-lockfile-optional-peer", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "prune-lockfile-optional-peer", + "version": "1.0.0", + "dependencies": { + "dedent": "^1.6.0" + } + }, + "node_modules/babel-plugin-macros": { + "version": "3.1.0", + "optional": true, + "peer": true + }, + "node_modules/dedent": { + "version": "1.6.0", + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } + } + } +} diff --git a/workspaces/arborist/test/fixtures/prune-lockfile-optional-peer/package.json b/workspaces/arborist/test/fixtures/prune-lockfile-optional-peer/package.json new file mode 100644 index 0000000000000..e2dd1a11a8614 --- /dev/null +++ b/workspaces/arborist/test/fixtures/prune-lockfile-optional-peer/package.json @@ -0,0 +1,7 @@ +{ + "name": "prune-lockfile-optional-peer", + "version": "1.0.0", + "dependencies": { + "dedent": "^1.6.0" + } +} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/dedent/dedent-1.6.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/dedent/dedent-1.6.0.tgz new file mode 100644 index 0000000000000..2ea7701b64861 Binary files /dev/null and b/workspaces/arborist/test/fixtures/registry-mocks/content/dedent/dedent-1.6.0.tgz differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/shrinkwrapped-dependency.json b/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/shrinkwrapped-dependency.json deleted file mode 100644 index 45bd53d41a1a1..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/shrinkwrapped-dependency.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "_id": "@isaacs/shrinkwrapped-dependency", - "name": "@isaacs/shrinkwrapped-dependency", - "dist-tags": { - "latest": "1.0.0" - }, - "versions": { - "1.0.0": { - "name": "@isaacs/shrinkwrapped-dependency", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "abbrev": "^1.0.4" - }, - "_id": "@isaacs/shrinkwrapped-dependency@1.0.0", - "_nodeVersion": "13.3.0", - "_npmVersion": "6.13.4", - "dist": { - "integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "shasum": "a22edfd12f2e796c924a36fe6cbf52eb495e93c3", - "tarball": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "fileCount": 3, - "unpackedSize": 1038, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJd+8vRCRA9TVsSAnZWagAAWsQP/AjxSgCAeCxmK01mUKva\nAtyfAXcF56Zwan9ljGCF4trC/03iO4DutZmWXYN6/0scxfAL6TJ1QYGSYxGZ\nZwpsxlNwYlmtivnLanf+pEof7Wt9jXjGDtYsnp0Kc8O2hea+MalpVAl9M8zw\nwELMt3mHIxPmB2auMHZIKi9oElJYDWwZfiKGs0rSNEoYIA6m4ebDA1NV5Dqd\np9iw986iEhKfpSyJ7kPQrXBhVSE0JPtoaKHZX99CJ58QRrbqW35H4WLktXQC\nBduX4bM3Pip5lnCXle7ZzuVWIJxNsZlvft+0ZaPbvqrbJx7rbaaGkEsb+A7A\nCJXwhHdfG8sBXIe3tswEidDYb4kj528xfiienVwNBY6KsnWeVgcKy+ZAn8vf\nCoSkd3nMAIK+9itpYtX5zzzy136pvNbXlxnZryZwFYclZcmanBK6Yn6zrF8K\n/nwlOjPKDPKag21ldDRx+m9SHvtqeG6jGeFvgrdt0IaMeGnTdrbuvUQoX9cF\nGjNMlv4MkbhbRXcNyxabtlQVCwcSI6fBjg+qLUBlxQaumBfZOhFO/yKOMwoj\nSc6HhPfYufdpXlvmcY9N2OrgJgeAD7iYZo92YmOXM47DtJc3HYP+aBzYmPru\npFI3XFMlXr93A/FXKMcYW/ORcnrhES18i/cl/NVtYFflAgX+KILkaZS78HKr\nzncR\r\n=t6l9\r\n-----END PGP SIGNATURE-----\r\n" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "directories": {}, - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/shrinkwrapped-dependency_1.0.0_1576782801049_0.38805928505087195" - }, - "_hasShrinkwrap": true - } - }, - "time": { - "created": "2019-12-19T19:13:21.019Z", - "1.0.0": "2019-12-19T19:13:21.241Z", - "modified": "2019-12-19T19:13:24.490Z" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "keywords": [], - "license": "ISC", - "readme": "ERROR: No README data found!", - "readmeFilename": "" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/shrinkwrapped-dependency.min.json b/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/shrinkwrapped-dependency.min.json deleted file mode 100644 index 11d4502fb796b..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/shrinkwrapped-dependency.min.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "@isaacs/shrinkwrapped-dependency", - "dist-tags": { - "latest": "1.0.0" - }, - "versions": { - "1.0.0": { - "name": "@isaacs/shrinkwrapped-dependency", - "version": "1.0.0", - "dependencies": { - "abbrev": "^1.0.4" - }, - "_hasShrinkwrap": true, - "dist": { - "integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "shasum": "a22edfd12f2e796c924a36fe6cbf52eb495e93c3", - "tarball": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "fileCount": 3, - "unpackedSize": 1038, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJd+8vRCRA9TVsSAnZWagAAWsQP/AjxSgCAeCxmK01mUKva\nAtyfAXcF56Zwan9ljGCF4trC/03iO4DutZmWXYN6/0scxfAL6TJ1QYGSYxGZ\nZwpsxlNwYlmtivnLanf+pEof7Wt9jXjGDtYsnp0Kc8O2hea+MalpVAl9M8zw\nwELMt3mHIxPmB2auMHZIKi9oElJYDWwZfiKGs0rSNEoYIA6m4ebDA1NV5Dqd\np9iw986iEhKfpSyJ7kPQrXBhVSE0JPtoaKHZX99CJ58QRrbqW35H4WLktXQC\nBduX4bM3Pip5lnCXle7ZzuVWIJxNsZlvft+0ZaPbvqrbJx7rbaaGkEsb+A7A\nCJXwhHdfG8sBXIe3tswEidDYb4kj528xfiienVwNBY6KsnWeVgcKy+ZAn8vf\nCoSkd3nMAIK+9itpYtX5zzzy136pvNbXlxnZryZwFYclZcmanBK6Yn6zrF8K\n/nwlOjPKDPKag21ldDRx+m9SHvtqeG6jGeFvgrdt0IaMeGnTdrbuvUQoX9cF\nGjNMlv4MkbhbRXcNyxabtlQVCwcSI6fBjg+qLUBlxQaumBfZOhFO/yKOMwoj\nSc6HhPfYufdpXlvmcY9N2OrgJgeAD7iYZo92YmOXM47DtJc3HYP+aBzYmPru\npFI3XFMlXr93A/FXKMcYW/ORcnrhES18i/cl/NVtYFflAgX+KILkaZS78HKr\nzncR\r\n=t6l9\r\n-----END PGP SIGNATURE-----\r\n" - } - } - }, - "modified": "2019-12-19T19:13:24.490Z" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz deleted file mode 100644 index 9b511d169c889..0000000000000 Binary files a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz and /dev/null differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/testing-shrinkwrap-abbrev.json b/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/testing-shrinkwrap-abbrev.json deleted file mode 100644 index a3f4b2fd79f8c..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/testing-shrinkwrap-abbrev.json +++ /dev/null @@ -1,212 +0,0 @@ -{ - "_id": "@isaacs/testing-shrinkwrap-abbrev", - "_rev": "4-74590deefb464968c8c22dbca97cbfd5", - "name": "@isaacs/testing-shrinkwrap-abbrev", - "dist-tags": { - "latest": "1.2.1" - }, - "versions": { - "1.1.0": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.0", - "dependencies": { - "abbrev": "*" - }, - "scripts": { - "test": "node test.js" - }, - "_id": "@isaacs/testing-shrinkwrap-abbrev@1.1.0", - "_nodeVersion": "16.0.0", - "_npmVersion": "7.14.0", - "dist": { - "integrity": "sha512-TYojMk588BgX1PhcpUgYcQXwH3gLt/iPfmzJ0UdR21jH5NVnmU/3GJefwmFNXlaF8OqbNcDTRv/4WGqbYYhA+w==", - "shasum": "237a8966283d2074d60778e77a3ea90d6a144412", - "tarball": "https://registry.npmjs.org/@isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.1.0.tgz", - "fileCount": 3, - "unpackedSize": 1028, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgq/LGCRA9TVsSAnZWagAAv0EP/2gjk9EdcWCXOZe49qF6\nubOfF1wAmuOqEo0aQihmufSnNshBF01hHLKanHjYPgXheQfLKUSOio0NDscW\ncgy2T2z5uV+a2IfSWBhRj+IjPqIZK2tPsN2RavsPqJ4XNmmuqipWn6t9+hKj\nHlfSWVH/PnKKqeHIkeoNoBM0JLnNAzNwyNWPIYJ9ev13xe2w542pV6VrVvvJ\nxgiIz0g8Nh64mgIERjbABLo4iQlESZrBRckT6LW5YpHQAr1r/u2ukiWV5KWR\nW3W+w9cVgSIy4nLu4hSbZ/7aHx8QKQnPz80/9AuphLTD49VzUxAXZ/X+q7+G\nbRrYkY7gQydUjWAN0hxC3Ssrb68fzKSEXIPGqIfGBK6DCSImgJoi/3Yoz4iH\n7+7wzruhYPbsRDhZIlxXviPoEvqCCKUZ0TVUmX2RnQOsA+LmGe+4KxWIgfgQ\nf9lJriWN/pu/Tpolvyys+bpd2GVdkcd0NEif447O/Asji1RBlBzseNt4NtxT\nKCTvhvYHCiSHEXjGYiNqfPnDxs0u6NuJiDq2cSP7jyaPkUKZbj2MPECRhdNZ\nicoAwOzYiroOBYMck39v9QnbGdNZmdGDKUYAEU4gCw3jsDdJ8/BCORLtXWP3\n6Dog0p7yeRPNFdAd5DuLjZTjFzfE2MdPRQ5b7KKLkE9hv0BGn0X2yD8LpAT/\nLSkS\r\n=e9hz\r\n-----END PGP SIGNATURE-----\r\n" - }, - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "directories": {}, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/testing-shrinkwrap-abbrev_1.1.0_1621881541630_0.7328421074906541" - }, - "_hasShrinkwrap": true - }, - "1.1.1": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.1", - "dependencies": { - "abbrev": "^1.1.1" - }, - "scripts": { - "test": "node test.js" - }, - "_id": "@isaacs/testing-shrinkwrap-abbrev@1.1.1", - "_nodeVersion": "16.0.0", - "_npmVersion": "7.14.0", - "dist": { - "integrity": "sha512-6PxS8ZM9rDSgqaSetq3IHVIJsSKHvQ+2xZVJwU64QzwxJl3rxa4q5nNJvuZReDsrloq3uSGkDNPtR56+V3ck5A==", - "shasum": "6c3b01872ef148948dafa87aa87e8e96264cfb9f", - "tarball": "https://registry.npmjs.org/@isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.1.1.tgz", - "fileCount": 3, - "unpackedSize": 1157, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgq/MWCRA9TVsSAnZWagAA3mEP/j4o7EH2F9bM/LLajkUZ\nF2DjXINXfXXTz17tdw3yAPSMPSzc0IPAtOO0I5Odc5av22Nu1dlcb4Rfe4uI\n0pMF9rqTUxwhnVXDOUfsiY2BrE8pEB465+AFfarm1zb9PHaI7oNXPSn+aJwZ\nfNCuCaV7+pia9KxnfRChXR/9aRZU3QjaZ0jnn+qaY8zCzcnsyMKrdVRMLxVc\nan43gbkQi4dEGx8bbMnv9kHetdfVd8HUGaH1oveOKesTlXLAZHdLXNPcNu6j\nsqm+u6+uECcogTy7TQ9Ue2sP0jRS9rDgP8PRgl3fuke8vd1+Uyk7N9Jzl1YM\n1W3irL/AGUPbgtyphUmPYp6SQscXmZj5G/HUlKBqwCvFLqgUMYE2LSB40RR2\n/+uL4xm6eXIVXnNjZZ0VC7Zbgfud2LYf36/4ICzIFeDW8g2cBUejakJuRyt/\n7hTYjTIUi96bhVrkvgn/DzD+6hSpHluyWFLgMd511Cl6hEfzl5hDu63FBM1o\nbx2oZAJ6Sh1Ju+7CF6BWQDnIeHU25ROr2h9odc/7fPlXtG08wtJ23BNo5sLw\n1t2Y8JjuAWqNmm5s/nF3mijmohaJDuLeI8PotAjcno6kLgQlKRZvOvBtEk3G\n4qd89CA471kv7/z89voPWbRmdsnCvK7apzbRAHeLhyzmmO4QX9fsZBZ1gRCx\n7cIA\r\n=nNtA\r\n-----END PGP SIGNATURE-----\r\n" - }, - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "directories": {}, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/testing-shrinkwrap-abbrev_1.1.1_1621881620405_0.5727830985048044" - }, - "_hasShrinkwrap": true - }, - "1.1.2": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.2", - "dependencies": { - "abbrev": "*" - }, - "scripts": { - "test": "node test.js" - }, - "_id": "@isaacs/testing-shrinkwrap-abbrev@1.1.2", - "_nodeVersion": "16.0.0", - "_npmVersion": "7.14.0", - "dist": { - "integrity": "sha512-r8mIu0lA0/TOS8FMzQgDIIiRZ8EW5SWobK0yTQWNLHJGdRgsjkXUx83h4sBTMQdhCl+7Ik71CTH6RrYR8IDvTg==", - "shasum": "a5645797452944c4f20055012d6645d363c5b00b", - "tarball": "https://registry.npmjs.org/@isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.1.2.tgz", - "fileCount": 3, - "unpackedSize": 1110, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgq/Q+CRA9TVsSAnZWagAABO0P/3C2uUUy9dp+dq3mFeCn\nouEgrEW3vWoGRjzqTixjGDG3C65W0Jm9nmlNT6chvovZ29PZ8ML0JFmob2PB\n5Hl6vqGtTHGmye5pdPyHSBkpBq/kajh7evSFfu3eSO12oew3x3Sdwv5JQWNt\n4+3bFWByhVJv9NB2J4ufuUC4qplF0lzZmHULl1eP8inMs8Z4rQ+B3OZpcVdM\niV6FxbSXGL+DtAk1sAq0MWw3FSDIRlPUcrj9LRKpw4ZJgCQLaBHT86ruxzmt\nHDktdA9NB9869LbigQxPKJJxesbDvLbabARcTYimEc/vKGEX5yCsV9km/9jb\nxSevgTQDh9ntfHApPzeG3nP06g7gACrquhPMuGlt6O/ZREUXvKsRgqFZnESp\nDM+NK9HWtqz5jhB7triJTh5Zbk2N9e9pQ5xJwOsiDnP0r4hBxDHIe5kOvwXn\nIdzSWmqulWKiFYV3JHWzUfDhFbFdw1adCuagPJUrJsVhpOVcfsZfKerVosBU\nyglK60k4ugT1XD10XsaSrQ3UZ/0a7yLdL546j3s2xXw/ARgoq9r/z7VoBWJN\nQm28RO6FVj1dMBda+a1FBg/bQQTZFVGscRaDpTrpldLnHyUGnN9x93nAIMNm\njaNvfskRWp8ZGtvh6k70vG/Oo5yNvaAVUA8wkv1fcF41VYSQGc28irn4j0P9\nYIoz\r\n=qWTs\r\n-----END PGP SIGNATURE-----\r\n" - }, - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "directories": {}, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/testing-shrinkwrap-abbrev_1.1.2_1621881918427_0.39865082315878" - }, - "_hasShrinkwrap": true - }, - "1.2.0": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.2.0", - "dependencies": { - "abbrev": "*" - }, - "scripts": { - "test": "node test.js" - }, - "_id": "@isaacs/testing-shrinkwrap-abbrev@1.2.0", - "_nodeVersion": "16.0.0", - "_npmVersion": "7.14.0", - "dist": { - "integrity": "sha512-C9JclYdDiJQK/bVXeO5ImV91+kpYa6UbBp0bWqX+7pTIQ8vGMBZE4Crt7+Aj7M/W0SB7Y7N7Do4qXCHcx4Vpqg==", - "shasum": "56da5ce658f3d45c0e03cea7e09cb47301bdd55d", - "tarball": "https://registry.npmjs.org/@isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.2.0.tgz", - "fileCount": 3, - "unpackedSize": 722, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgrAPDCRA9TVsSAnZWagAAg2gP/RH5J0R0HQt6isyB+oOc\nISOE9IN3kr1b+K9W4Nq2fRT9htRzb62oNk+UGj8p3mtjc6kvvHdpr6vjeQMg\nZjkY1swCDqG4EiWwS45cvmNO6LE/CgzU6vR+VeJCgu77xCaVJn6WWBEY1+po\nKA537T7SqEYF+UcejvbnJ6BGrmMymKNEIPGrZnKd41A7a21FGTTCEv5hP6bu\n+07lyLWLLqLRQMUBGCwyJghfOC2UaRTTil8++btzBhig9bfQawXFqpwKT+o3\nPZS+YlX3R1xITmOSXdQXQaXcBRyaPEwSFILPbF1oajHF/UkpgSWYIOU4SV7/\nolG3p345rjs+D06SSEEb+2E3HHsHt88SVrogL5ammk+0iRN9y7GkOovOcXL4\nLCNL7xP9dhBHN1jzl4lLyF24JrTGK+L0SogxkuuQ01jO/6uRi9Qp8jnDWqnK\nTqUovMkxMAkIwuc5Gf4lTiEFohQFH/Bk9OHelZOib6fuV48+nSS8fqryUAUe\nzqEJZJ61OwnXjG5RVXqMUfZi0FddSRAfSHpOXDnP+NmHcNMk9YtYAZ3j+3W2\n0vH2QOye3HvfLhS21DVD7Ai/QPYosJvrbZ7DBExNFDQoY3Y7jsck3dSG2t4X\nHfv3bKsbbDkQwWVPQZ/rsftBVw67sYViuJ7s2+OZgnpOieLGJOCR40Phjxha\nurE6\r\n=npZ2\r\n-----END PGP SIGNATURE-----\r\n" - }, - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "directories": {}, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/testing-shrinkwrap-abbrev_1.2.0_1621885891322_0.8362264068815064" - }, - "_hasShrinkwrap": true - }, - "1.2.1": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.2.1", - "dependencies": { - "abbrev": "*" - }, - "scripts": { - "test": "node test.js" - }, - "_id": "@isaacs/testing-shrinkwrap-abbrev@1.2.1", - "_nodeVersion": "16.0.0", - "_npmVersion": "7.14.0", - "dist": { - "integrity": "sha512-ngPpNtherFyEq59NvkvRHrVo7M8gBe9vPKBosDV5yyVhHQMSiTd/hLbgJhyoDo5Ic150VgLynkoWe6YqrDj+vw==", - "shasum": "1023e3982a109786cab10be799eea10882277f6c", - "tarball": "https://registry.npmjs.org/@isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.2.1.tgz", - "fileCount": 3, - "unpackedSize": 726, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgrAP5CRA9TVsSAnZWagAAepIQAKMTJTqMMbcX1Z8q/y2N\nRIRzwWMoDx2D/pcgxTc9SoiCCqbhwXzgnA+Pccefs1WP7N2G6fPInW6geRiA\nZ9d8nFoMseP3Kttv8v7Ne4msrM4MtELPTth6zLkIJOnnunaTq17siZ/cQAtA\nxyi8WxCFISAYctHaAkh+NE2efdR75o5f4imaSCmclJ5mu0578GK9tWOr3UE9\nf1IDvLukCmGqEjLVBXSa6mljVcCBqJkM05lRVMi8HJ6Ix72Ngiz607OHwWWe\njpNZazPUHyklBrkNspRu3Zp/3DhiWIEtE47INldUyaNTHWHIjZZvZLZq1LSV\na/svf0iCfxMIMyuBz+X3t7hjZQx4lkAHl0WMzsxfWuRnaCoCm4XXIz7c3xAO\n6X+Qn7wxzAIJTD1pMduPZy82x1j4e2cLvMebDOFq5lIpmBrATCO7kz4CcERz\nkkX1ht7Rq/ZiXDXRW3pdSAyMv2JnzsKz4EW1g4zgIlRPhAYftEzKgDS9xHgi\ne4QbutsLkFgxqVDFj2NmgcRwZteTz95Rd8ZS6jsmO89vxF1iATRzOimJfLd7\nYdXLfVVnY931OArwNqTFOK71W3YN+ON97eYJQGWDGhHeW/ldmSkHn+lXoJGP\nKj1kgrtdE7sFOAU4tZb2VNZBu68e0xLb341XVjyabrrRflN6H0y0zFq1+w4Q\ntQ3A\r\n=EzTD\r\n-----END PGP SIGNATURE-----\r\n" - }, - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "directories": {}, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/testing-shrinkwrap-abbrev_1.2.1_1621885944680_0.8275105000563601" - }, - "_hasShrinkwrap": true - } - }, - "time": { - "created": "2021-05-24T18:39:01.568Z", - "1.1.0": "2021-05-24T18:39:01.758Z", - "modified": "2021-05-24T19:52:26.926Z", - "1.1.1": "2021-05-24T18:40:20.813Z", - "1.1.2": "2021-05-24T18:45:18.624Z", - "1.2.0": "2021-05-24T19:51:31.461Z", - "1.2.1": "2021-05-24T19:52:24.825Z" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "readme": "ERROR: No README data found!", - "readmeFilename": "" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/testing-shrinkwrap-abbrev.min.json b/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/testing-shrinkwrap-abbrev.min.json deleted file mode 100644 index 43db8cb2f8ebc..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/testing-shrinkwrap-abbrev.min.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "name": "@isaacs/testing-shrinkwrap-abbrev", - "dist-tags": { - "latest": "1.2.1" - }, - "versions": { - "1.1.0": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.0", - "dependencies": { - "abbrev": "*" - }, - "_hasShrinkwrap": true, - "dist": { - "integrity": "sha512-TYojMk588BgX1PhcpUgYcQXwH3gLt/iPfmzJ0UdR21jH5NVnmU/3GJefwmFNXlaF8OqbNcDTRv/4WGqbYYhA+w==", - "shasum": "237a8966283d2074d60778e77a3ea90d6a144412", - "tarball": "https://registry.npmjs.org/@isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.1.0.tgz", - "fileCount": 3, - "unpackedSize": 1028, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgq/LGCRA9TVsSAnZWagAAv0EP/2gjk9EdcWCXOZe49qF6\nubOfF1wAmuOqEo0aQihmufSnNshBF01hHLKanHjYPgXheQfLKUSOio0NDscW\ncgy2T2z5uV+a2IfSWBhRj+IjPqIZK2tPsN2RavsPqJ4XNmmuqipWn6t9+hKj\nHlfSWVH/PnKKqeHIkeoNoBM0JLnNAzNwyNWPIYJ9ev13xe2w542pV6VrVvvJ\nxgiIz0g8Nh64mgIERjbABLo4iQlESZrBRckT6LW5YpHQAr1r/u2ukiWV5KWR\nW3W+w9cVgSIy4nLu4hSbZ/7aHx8QKQnPz80/9AuphLTD49VzUxAXZ/X+q7+G\nbRrYkY7gQydUjWAN0hxC3Ssrb68fzKSEXIPGqIfGBK6DCSImgJoi/3Yoz4iH\n7+7wzruhYPbsRDhZIlxXviPoEvqCCKUZ0TVUmX2RnQOsA+LmGe+4KxWIgfgQ\nf9lJriWN/pu/Tpolvyys+bpd2GVdkcd0NEif447O/Asji1RBlBzseNt4NtxT\nKCTvhvYHCiSHEXjGYiNqfPnDxs0u6NuJiDq2cSP7jyaPkUKZbj2MPECRhdNZ\nicoAwOzYiroOBYMck39v9QnbGdNZmdGDKUYAEU4gCw3jsDdJ8/BCORLtXWP3\n6Dog0p7yeRPNFdAd5DuLjZTjFzfE2MdPRQ5b7KKLkE9hv0BGn0X2yD8LpAT/\nLSkS\r\n=e9hz\r\n-----END PGP SIGNATURE-----\r\n" - } - }, - "1.1.1": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.1", - "dependencies": { - "abbrev": "^1.1.1" - }, - "_hasShrinkwrap": true, - "dist": { - "integrity": "sha512-6PxS8ZM9rDSgqaSetq3IHVIJsSKHvQ+2xZVJwU64QzwxJl3rxa4q5nNJvuZReDsrloq3uSGkDNPtR56+V3ck5A==", - "shasum": "6c3b01872ef148948dafa87aa87e8e96264cfb9f", - "tarball": "https://registry.npmjs.org/@isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.1.1.tgz", - "fileCount": 3, - "unpackedSize": 1157, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgq/MWCRA9TVsSAnZWagAA3mEP/j4o7EH2F9bM/LLajkUZ\nF2DjXINXfXXTz17tdw3yAPSMPSzc0IPAtOO0I5Odc5av22Nu1dlcb4Rfe4uI\n0pMF9rqTUxwhnVXDOUfsiY2BrE8pEB465+AFfarm1zb9PHaI7oNXPSn+aJwZ\nfNCuCaV7+pia9KxnfRChXR/9aRZU3QjaZ0jnn+qaY8zCzcnsyMKrdVRMLxVc\nan43gbkQi4dEGx8bbMnv9kHetdfVd8HUGaH1oveOKesTlXLAZHdLXNPcNu6j\nsqm+u6+uECcogTy7TQ9Ue2sP0jRS9rDgP8PRgl3fuke8vd1+Uyk7N9Jzl1YM\n1W3irL/AGUPbgtyphUmPYp6SQscXmZj5G/HUlKBqwCvFLqgUMYE2LSB40RR2\n/+uL4xm6eXIVXnNjZZ0VC7Zbgfud2LYf36/4ICzIFeDW8g2cBUejakJuRyt/\n7hTYjTIUi96bhVrkvgn/DzD+6hSpHluyWFLgMd511Cl6hEfzl5hDu63FBM1o\nbx2oZAJ6Sh1Ju+7CF6BWQDnIeHU25ROr2h9odc/7fPlXtG08wtJ23BNo5sLw\n1t2Y8JjuAWqNmm5s/nF3mijmohaJDuLeI8PotAjcno6kLgQlKRZvOvBtEk3G\n4qd89CA471kv7/z89voPWbRmdsnCvK7apzbRAHeLhyzmmO4QX9fsZBZ1gRCx\n7cIA\r\n=nNtA\r\n-----END PGP SIGNATURE-----\r\n" - } - }, - "1.1.2": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.2", - "dependencies": { - "abbrev": "*" - }, - "_hasShrinkwrap": true, - "dist": { - "integrity": "sha512-r8mIu0lA0/TOS8FMzQgDIIiRZ8EW5SWobK0yTQWNLHJGdRgsjkXUx83h4sBTMQdhCl+7Ik71CTH6RrYR8IDvTg==", - "shasum": "a5645797452944c4f20055012d6645d363c5b00b", - "tarball": "https://registry.npmjs.org/@isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.1.2.tgz", - "fileCount": 3, - "unpackedSize": 1110, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgq/Q+CRA9TVsSAnZWagAABO0P/3C2uUUy9dp+dq3mFeCn\nouEgrEW3vWoGRjzqTixjGDG3C65W0Jm9nmlNT6chvovZ29PZ8ML0JFmob2PB\n5Hl6vqGtTHGmye5pdPyHSBkpBq/kajh7evSFfu3eSO12oew3x3Sdwv5JQWNt\n4+3bFWByhVJv9NB2J4ufuUC4qplF0lzZmHULl1eP8inMs8Z4rQ+B3OZpcVdM\niV6FxbSXGL+DtAk1sAq0MWw3FSDIRlPUcrj9LRKpw4ZJgCQLaBHT86ruxzmt\nHDktdA9NB9869LbigQxPKJJxesbDvLbabARcTYimEc/vKGEX5yCsV9km/9jb\nxSevgTQDh9ntfHApPzeG3nP06g7gACrquhPMuGlt6O/ZREUXvKsRgqFZnESp\nDM+NK9HWtqz5jhB7triJTh5Zbk2N9e9pQ5xJwOsiDnP0r4hBxDHIe5kOvwXn\nIdzSWmqulWKiFYV3JHWzUfDhFbFdw1adCuagPJUrJsVhpOVcfsZfKerVosBU\nyglK60k4ugT1XD10XsaSrQ3UZ/0a7yLdL546j3s2xXw/ARgoq9r/z7VoBWJN\nQm28RO6FVj1dMBda+a1FBg/bQQTZFVGscRaDpTrpldLnHyUGnN9x93nAIMNm\njaNvfskRWp8ZGtvh6k70vG/Oo5yNvaAVUA8wkv1fcF41VYSQGc28irn4j0P9\nYIoz\r\n=qWTs\r\n-----END PGP SIGNATURE-----\r\n" - } - }, - "1.2.0": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.2.0", - "dependencies": { - "abbrev": "*" - }, - "_hasShrinkwrap": true, - "dist": { - "integrity": "sha512-C9JclYdDiJQK/bVXeO5ImV91+kpYa6UbBp0bWqX+7pTIQ8vGMBZE4Crt7+Aj7M/W0SB7Y7N7Do4qXCHcx4Vpqg==", - "shasum": "56da5ce658f3d45c0e03cea7e09cb47301bdd55d", - "tarball": "https://registry.npmjs.org/@isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.2.0.tgz", - "fileCount": 3, - "unpackedSize": 722, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgrAPDCRA9TVsSAnZWagAAg2gP/RH5J0R0HQt6isyB+oOc\nISOE9IN3kr1b+K9W4Nq2fRT9htRzb62oNk+UGj8p3mtjc6kvvHdpr6vjeQMg\nZjkY1swCDqG4EiWwS45cvmNO6LE/CgzU6vR+VeJCgu77xCaVJn6WWBEY1+po\nKA537T7SqEYF+UcejvbnJ6BGrmMymKNEIPGrZnKd41A7a21FGTTCEv5hP6bu\n+07lyLWLLqLRQMUBGCwyJghfOC2UaRTTil8++btzBhig9bfQawXFqpwKT+o3\nPZS+YlX3R1xITmOSXdQXQaXcBRyaPEwSFILPbF1oajHF/UkpgSWYIOU4SV7/\nolG3p345rjs+D06SSEEb+2E3HHsHt88SVrogL5ammk+0iRN9y7GkOovOcXL4\nLCNL7xP9dhBHN1jzl4lLyF24JrTGK+L0SogxkuuQ01jO/6uRi9Qp8jnDWqnK\nTqUovMkxMAkIwuc5Gf4lTiEFohQFH/Bk9OHelZOib6fuV48+nSS8fqryUAUe\nzqEJZJ61OwnXjG5RVXqMUfZi0FddSRAfSHpOXDnP+NmHcNMk9YtYAZ3j+3W2\n0vH2QOye3HvfLhS21DVD7Ai/QPYosJvrbZ7DBExNFDQoY3Y7jsck3dSG2t4X\nHfv3bKsbbDkQwWVPQZ/rsftBVw67sYViuJ7s2+OZgnpOieLGJOCR40Phjxha\nurE6\r\n=npZ2\r\n-----END PGP SIGNATURE-----\r\n" - } - }, - "1.2.1": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.2.1", - "dependencies": { - "abbrev": "*" - }, - "_hasShrinkwrap": true, - "dist": { - "integrity": "sha512-ngPpNtherFyEq59NvkvRHrVo7M8gBe9vPKBosDV5yyVhHQMSiTd/hLbgJhyoDo5Ic150VgLynkoWe6YqrDj+vw==", - "shasum": "1023e3982a109786cab10be799eea10882277f6c", - "tarball": "https://registry.npmjs.org/@isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.2.1.tgz", - "fileCount": 3, - "unpackedSize": 726, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgrAP5CRA9TVsSAnZWagAAepIQAKMTJTqMMbcX1Z8q/y2N\nRIRzwWMoDx2D/pcgxTc9SoiCCqbhwXzgnA+Pccefs1WP7N2G6fPInW6geRiA\nZ9d8nFoMseP3Kttv8v7Ne4msrM4MtELPTth6zLkIJOnnunaTq17siZ/cQAtA\nxyi8WxCFISAYctHaAkh+NE2efdR75o5f4imaSCmclJ5mu0578GK9tWOr3UE9\nf1IDvLukCmGqEjLVBXSa6mljVcCBqJkM05lRVMi8HJ6Ix72Ngiz607OHwWWe\njpNZazPUHyklBrkNspRu3Zp/3DhiWIEtE47INldUyaNTHWHIjZZvZLZq1LSV\na/svf0iCfxMIMyuBz+X3t7hjZQx4lkAHl0WMzsxfWuRnaCoCm4XXIz7c3xAO\n6X+Qn7wxzAIJTD1pMduPZy82x1j4e2cLvMebDOFq5lIpmBrATCO7kz4CcERz\nkkX1ht7Rq/ZiXDXRW3pdSAyMv2JnzsKz4EW1g4zgIlRPhAYftEzKgDS9xHgi\ne4QbutsLkFgxqVDFj2NmgcRwZteTz95Rd8ZS6jsmO89vxF1iATRzOimJfLd7\nYdXLfVVnY931OArwNqTFOK71W3YN+ON97eYJQGWDGhHeW/ldmSkHn+lXoJGP\nKj1kgrtdE7sFOAU4tZb2VNZBu68e0xLb341XVjyabrrRflN6H0y0zFq1+w4Q\ntQ3A\r\n=EzTD\r\n-----END PGP SIGNATURE-----\r\n" - } - } - }, - "modified": "2021-05-24T19:52:26.926Z" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.2.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.2.0.tgz deleted file mode 100644 index e67d4b7ca183d..0000000000000 Binary files a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.2.0.tgz and /dev/null differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.2.1.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.2.1.tgz deleted file mode 100644 index abf66248a7160..0000000000000 Binary files a/workspaces/arborist/test/fixtures/registry-mocks/content/isaacs/testing-shrinkwrap-abbrev/-/testing-shrinkwrap-abbrev-1.2.1.tgz and /dev/null differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-a.json b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-a.json deleted file mode 100644 index 6c69a5c72e521..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-a.json +++ /dev/null @@ -1,99 +0,0 @@ -{ - "_id": "@nlf/shrinkwrapped-dep-updates-a", - "_rev": "1-d805a97150d8d2daffbb2a38fb2ecf82", - "name": "@nlf/shrinkwrapped-dep-updates-a", - "dist-tags": { - "latest": "2.0.0" - }, - "versions": { - "1.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-a", - "version": "1.0.0", - "description": "a dependency with shrinkwrapped deps that change between versions", - "dependencies": { - "@nlf/shrinkwrapped-dep-updates-b": "^1.0.0", - "@nlf/shrinkwrapped-dep-updates-c": "^1.0.0", - "@nlf/shrinkwrapped-dep-updates-d": "^1.0.0" - }, - "_id": "@nlf/shrinkwrapped-dep-updates-a@1.0.0", - "_nodeVersion": "15.11.0", - "_npmVersion": "7.9.0", - "dist": { - "integrity": "sha512-pNGpUP2EJtFniSm84GAy0fXqgOvzlbDEjGj3fHcJHMxvGecrf3iu/Ad3fkzQqrwUKPQVSpBsWLgX7+oocE9LtA==", - "shasum": "eee821e72d1930a5fe7bb532f263b838aa76e98f", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-a/-/shrinkwrapped-dep-updates-a-1.0.0.tgz", - "fileCount": 2, - "unpackedSize": 2693, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfakeCRA9TVsSAnZWagAASoIP/RXlrMoeK1jPD2ckuGGf\nlMJnKRIa2XLWxy/nQ8WKkhYyj/gpbHLrmXzmYKNwr/GJKP+8ja3OdWO8J1Qe\n5q89D4Lbt/ISYVQirUYK1ER9QdwghC5sabiQYiSq33z85NniEyJ0zZau+WJh\ndByFzwHoabE8q+g5DpRakaiQbudqZtAFfDj68GlE8sMBEaARF2QR2I4liIYd\nGGpetvDbkKT3X9KjuBXLbVCVczCBIe1KfPWceEBTAxHQzqfvptL//aqrlLND\nVi9XuQTlhQvZxskzRkPv57ZompBVoBEsAmvS5zwy1vQUCZAvuKer3zAFjurK\npWAIcvEMviOOP8FhpeNQdMrk8ftOl1iOUjsNMgluLGrhM6Lidu6qSEF+pEC+\neP4+LhKIfZq2+t2NPP132Ye0mXzXbhCTKeui0AMqjSHWTmA5Q8OnhRThjQZS\nH/FHj/fNLgdSxp9hGYYR+u7BSjkodnGVbsdQRWr39UMt1I7w2eV5tC6vrhrh\n8eI4vDENGVE8+/HZYWN2C5ab5CAGDXNwBNqVx9T44QLkGxmy+7ptjYHeSOGR\ndLroSoTgDLK5EGImSuuUmZAbGzUMm/Ns333TE3fGRe8rKoqG1dfWRqmVehaP\njjnnw3IoFGKdN/dO8f8stbShjsBSJbLU3oiO5bo6radSuJ+G5kW7Clbuou/8\nHv/x\r\n=mkCk\r\n-----END PGP SIGNATURE-----\r\n" - }, - "_npmUser": { - "name": "nlf", - "email": "quitlahok@gmail.com" - }, - "directories": {}, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - } - ], - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/shrinkwrapped-dep-updates-a_1.0.0_1618848029879_0.9370532156921463" - }, - "_hasShrinkwrap": true - }, - "2.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-a", - "version": "2.0.0", - "description": "a dependency with shrinkwrapped deps that change between versions", - "dependencies": { - "@nlf/shrinkwrapped-dep-updates-b": "^2.0.0", - "@nlf/shrinkwrapped-dep-updates-c": "^1.0.0", - "@nlf/shrinkwrapped-dep-updates-e": "^1.0.0" - }, - "_id": "@nlf/shrinkwrapped-dep-updates-a@2.0.0", - "_nodeVersion": "15.11.0", - "_npmVersion": "7.9.0", - "dist": { - "integrity": "sha512-d/flPwoAL2RkRnN3jEYELUpkgjwstkk6KYL784stgi0FG7SJgJSLmyYxgtJsWlrMNyxCqlpnG+l+DGuZluG/bA==", - "shasum": "b306d24701fb53d48e674174f630c816bb061288", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-a/-/shrinkwrapped-dep-updates-a-2.0.0.tgz", - "fileCount": 2, - "unpackedSize": 2693, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfalICRA9TVsSAnZWagAAUWYP/1y6thk1Np0h+oqBB5vH\n+F70MWpCfhFy/iRGcSG18xTEoj8BFV5cXqfTiGXsYLIA6ApRK7vpz2lGclel\n1jDQjU3C7j4Z/znyrsdVHObAVJdWbFtyHeurlERtSZmIX4Ie3fRn1Y+QJV7o\nQSeey/1Wif0XuBuQFi9s8ENTI4CDIQun/lWuwi1NvlbplbiANAB+q7LbWHEr\nUW2V/3bBnCkJ1k/YNpL9kbTvOW4kBh/bXXfuIvCipoNZWnLaw6/Ih/EPmyK4\n3xwFRs6O8EXag4M8lHN0bhbAk347qDQdNI1dtABNzB/6hCz2BAmrdYTtYRz+\nUbe+BHEW2mnZxtcp9jR9otQjExnyMzMQGkMv62587NTCdhp00xb9kOE71yTa\nfQ0IVAZ0vBldrdBs9ZQ0gW//SUYFy4Q44xeF2worg6nEpgZlpM8rQkzqKDnX\n/a5dyzWAI7k5ACcAp6hXPNnR8jXa1IlR/Pb9b4ARGnGPZkHKGPb1AD75RKba\ni7y6j8oVs3nyOkCDa/H0A8OxtPi4tpQo4JLVKdL9yLg+5Qt/hVnrsFJ+Sq99\n0sled32QeU89um/WsErRPqK0yjpx15rB91mEPY4g7UmjFQeB0Ekamxzq7q7i\nNGMheVykug+ykz86VX1U83c9tb8wthKWFpT7OTzqTZeW9+BxJuu1bzBJMP5p\nXC0n\r\n=Twl4\r\n-----END PGP SIGNATURE-----\r\n" - }, - "_npmUser": { - "name": "nlf", - "email": "quitlahok@gmail.com" - }, - "directories": {}, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - } - ], - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/shrinkwrapped-dep-updates-a_2.0.0_1618848071773_0.3133555404017958" - }, - "_hasShrinkwrap": true - } - }, - "time": { - "created": "2021-04-19T16:00:29.822Z", - "1.0.0": "2021-04-19T16:00:29.984Z", - "modified": "2021-04-19T16:01:14.014Z", - "2.0.0": "2021-04-19T16:01:11.905Z" - }, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - } - ], - "description": "a dependency with shrinkwrapped deps that change between versions", - "readme": "ERROR: No README data found!", - "readmeFilename": "" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-a.min.json b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-a.min.json deleted file mode 100644 index 2f3d81143dffc..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-a.min.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-a", - "dist-tags": { - "latest": "2.0.0" - }, - "versions": { - "1.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-a", - "version": "1.0.0", - "dependencies": { - "@nlf/shrinkwrapped-dep-updates-b": "^1.0.0", - "@nlf/shrinkwrapped-dep-updates-c": "^1.0.0", - "@nlf/shrinkwrapped-dep-updates-d": "^1.0.0" - }, - "_hasShrinkwrap": true, - "dist": { - "integrity": "sha512-pNGpUP2EJtFniSm84GAy0fXqgOvzlbDEjGj3fHcJHMxvGecrf3iu/Ad3fkzQqrwUKPQVSpBsWLgX7+oocE9LtA==", - "shasum": "eee821e72d1930a5fe7bb532f263b838aa76e98f", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-a/-/shrinkwrapped-dep-updates-a-1.0.0.tgz", - "fileCount": 2, - "unpackedSize": 2693, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfakeCRA9TVsSAnZWagAASoIP/RXlrMoeK1jPD2ckuGGf\nlMJnKRIa2XLWxy/nQ8WKkhYyj/gpbHLrmXzmYKNwr/GJKP+8ja3OdWO8J1Qe\n5q89D4Lbt/ISYVQirUYK1ER9QdwghC5sabiQYiSq33z85NniEyJ0zZau+WJh\ndByFzwHoabE8q+g5DpRakaiQbudqZtAFfDj68GlE8sMBEaARF2QR2I4liIYd\nGGpetvDbkKT3X9KjuBXLbVCVczCBIe1KfPWceEBTAxHQzqfvptL//aqrlLND\nVi9XuQTlhQvZxskzRkPv57ZompBVoBEsAmvS5zwy1vQUCZAvuKer3zAFjurK\npWAIcvEMviOOP8FhpeNQdMrk8ftOl1iOUjsNMgluLGrhM6Lidu6qSEF+pEC+\neP4+LhKIfZq2+t2NPP132Ye0mXzXbhCTKeui0AMqjSHWTmA5Q8OnhRThjQZS\nH/FHj/fNLgdSxp9hGYYR+u7BSjkodnGVbsdQRWr39UMt1I7w2eV5tC6vrhrh\n8eI4vDENGVE8+/HZYWN2C5ab5CAGDXNwBNqVx9T44QLkGxmy+7ptjYHeSOGR\ndLroSoTgDLK5EGImSuuUmZAbGzUMm/Ns333TE3fGRe8rKoqG1dfWRqmVehaP\njjnnw3IoFGKdN/dO8f8stbShjsBSJbLU3oiO5bo6radSuJ+G5kW7Clbuou/8\nHv/x\r\n=mkCk\r\n-----END PGP SIGNATURE-----\r\n" - } - }, - "2.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-a", - "version": "2.0.0", - "dependencies": { - "@nlf/shrinkwrapped-dep-updates-b": "^2.0.0", - "@nlf/shrinkwrapped-dep-updates-c": "^1.0.0", - "@nlf/shrinkwrapped-dep-updates-e": "^1.0.0" - }, - "_hasShrinkwrap": true, - "dist": { - "integrity": "sha512-d/flPwoAL2RkRnN3jEYELUpkgjwstkk6KYL784stgi0FG7SJgJSLmyYxgtJsWlrMNyxCqlpnG+l+DGuZluG/bA==", - "shasum": "b306d24701fb53d48e674174f630c816bb061288", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-a/-/shrinkwrapped-dep-updates-a-2.0.0.tgz", - "fileCount": 2, - "unpackedSize": 2693, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfalICRA9TVsSAnZWagAAUWYP/1y6thk1Np0h+oqBB5vH\n+F70MWpCfhFy/iRGcSG18xTEoj8BFV5cXqfTiGXsYLIA6ApRK7vpz2lGclel\n1jDQjU3C7j4Z/znyrsdVHObAVJdWbFtyHeurlERtSZmIX4Ie3fRn1Y+QJV7o\nQSeey/1Wif0XuBuQFi9s8ENTI4CDIQun/lWuwi1NvlbplbiANAB+q7LbWHEr\nUW2V/3bBnCkJ1k/YNpL9kbTvOW4kBh/bXXfuIvCipoNZWnLaw6/Ih/EPmyK4\n3xwFRs6O8EXag4M8lHN0bhbAk347qDQdNI1dtABNzB/6hCz2BAmrdYTtYRz+\nUbe+BHEW2mnZxtcp9jR9otQjExnyMzMQGkMv62587NTCdhp00xb9kOE71yTa\nfQ0IVAZ0vBldrdBs9ZQ0gW//SUYFy4Q44xeF2worg6nEpgZlpM8rQkzqKDnX\n/a5dyzWAI7k5ACcAp6hXPNnR8jXa1IlR/Pb9b4ARGnGPZkHKGPb1AD75RKba\ni7y6j8oVs3nyOkCDa/H0A8OxtPi4tpQo4JLVKdL9yLg+5Qt/hVnrsFJ+Sq99\n0sled32QeU89um/WsErRPqK0yjpx15rB91mEPY4g7UmjFQeB0Ekamxzq7q7i\nNGMheVykug+ykz86VX1U83c9tb8wthKWFpT7OTzqTZeW9+BxJuu1bzBJMP5p\nXC0n\r\n=Twl4\r\n-----END PGP SIGNATURE-----\r\n" - } - } - }, - "modified": "2021-04-19T16:01:14.014Z" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-a/-/shrinkwrapped-dep-updates-a-1.0.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-a/-/shrinkwrapped-dep-updates-a-1.0.0.tgz deleted file mode 100644 index 1234c316a647a..0000000000000 Binary files a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-a/-/shrinkwrapped-dep-updates-a-1.0.0.tgz and /dev/null differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-a/-/shrinkwrapped-dep-updates-a-2.0.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-a/-/shrinkwrapped-dep-updates-a-2.0.0.tgz deleted file mode 100644 index 1f2015a659520..0000000000000 Binary files a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-a/-/shrinkwrapped-dep-updates-a-2.0.0.tgz and /dev/null differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-b.json b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-b.json deleted file mode 100644 index f5d1ec557adaa..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-b.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "_id": "@nlf/shrinkwrapped-dep-updates-b", - "_rev": "1-f05670713475c8f87cd84ca431001bdb", - "name": "@nlf/shrinkwrapped-dep-updates-b", - "dist-tags": { - "latest": "2.0.0" - }, - "versions": { - "1.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-b", - "version": "1.0.0", - "description": "a dependency that a shrinkwrapped dependency depends on", - "_id": "@nlf/shrinkwrapped-dep-updates-b@1.0.0", - "_nodeVersion": "15.11.0", - "_npmVersion": "7.9.0", - "dist": { - "integrity": "sha512-O8gmWJxc3W9yjGNGnEwumPQfXDTjIwkixWN8XPKvuEKwg5QldqAJfka5u7NwvM4ILP+1TT2OEMf+cNEYJ3eXUw==", - "shasum": "0f111693939e966d67c3f23c30900497076d1aa6", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-1.0.0.tgz", - "fileCount": 1, - "unpackedSize": 147, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfajPCRA9TVsSAnZWagAAfDsP/RAm3dd6uldkPJ3n/D4+\nwSrBpKQhFdwN1h9aE6dhgC8dq01r/sjezZcPDeTNAoZX8f7M0GAXNw1bB+5e\nXHp0y8lyfRXZL+EZwhZCfl0za01whvbrx79t01oeYgaeHP4ztbjygmfr7Y/D\nz+ft0/H3Fguwz76yELFYqjGY4G2mjUC93+2AhZhJ2KBSj6xsL+LUe4hdh8y/\n7HTg9j2rr+iDxS2uFWWb9DiQokfhOfyM2FrfqoCZZtPGg28I5W8zQtw9YTBj\ny2pXrhpxKzc8woHgfjlSocdj2pp6tAjiNNBVFRzKp5MBb72EAuGKAXHe8VHF\n2B6tuUYMJeOe0s9y4ptmSWg3gBZtmL/dqGn/oZy/3MdjHloz48FVUr+pyGjS\nB+JCPnal907qlfQNhXYz1I9LlfYaTgwHZEbAy4PFZA7V7MMtVWNFtwj3/Pwk\nQqHD7Su+66y//o9d3nSKWW7k5my3/T1MNbPmnisFMqpKuiMS54Bvv0ckcd4A\n593TgA7H2f0H+HSF55PH2q7BZeRkfoB2pht6XDdBSZsfWgmnksOcb0Dfy45Y\nvnHuHs/TdhrsqCxrxjNd8FrJUt2eO/R7ejRCvQhOdHLl9DWzOmhbFZqsP9El\nsTeg2OEKjDRqQCmgugcZANos9lHWFOZH0VgF2nMy3sT089sbhOf2DyWUsMmv\ne/i4\r\n=ZoBI\r\n-----END PGP SIGNATURE-----\r\n" - }, - "_npmUser": { - "name": "nlf", - "email": "quitlahok@gmail.com" - }, - "directories": {}, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - } - ], - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/shrinkwrapped-dep-updates-b_1.0.0_1618847951436_0.553392308060431" - }, - "_hasShrinkwrap": false - }, - "2.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-b", - "version": "2.0.0", - "description": "a dependency that a shrinkwrapped dependency depends on", - "_id": "@nlf/shrinkwrapped-dep-updates-b@2.0.0", - "_nodeVersion": "15.11.0", - "_npmVersion": "7.9.0", - "dist": { - "integrity": "sha512-B5arzHMzN1kp67O/tVRR+OtosYDYVdNH7dLKkVR9Ruov+M6a7mrj2bOAJd8HZMQlQ5yjMRy3UXTp2amgh9EhqA==", - "shasum": "d857895f3d09514e7efb127f9092451b34c13db7", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-2.0.0.tgz", - "fileCount": 1, - "unpackedSize": 147, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfajcCRA9TVsSAnZWagAATBkP/jMOkUYS+ehl6DKBRaLA\nrRet2hEeF8bIZQM71v+mU07oJjGWyAwKB4ZI+uEaYY4VqGZBQI5obX52Da+O\ncu+zIgbGXgTk2YgQMcyCnl2kkof2s9kPe+EflH3kHcDuK/V819ekCyNVG09W\nmDTRRx1OhT16gQnAXtfW8cLbkOS4fmbX3nUgXQIPzFqgMYtVxoJ7BXeVo0HX\nQr2ZQap9NcxQheFsSOTjCaHim2q3s0K2TOW8k2FAA1lfHmnIjMrDjiOWdBTM\nwl4M/xIyC6xKs3w/Xilyk5Ra6HIe3sxtG1KQFq/OJx3XRgV9eF61rxmo4Ru/\nrfupUlMkVluqP78CvTkulLmxSkb6flye8QskD8V93MJxFtMP7tiABINNSntT\nM33TfTBcmxUqULJTIN2oeSJyHPTAU3uFSB8Z9BKURppopyROD1+1jN/goyEy\naJWG2iXdeoXYycnmBukqOn/Jr06Bk2IWxsqKG/1x89YOY92quXbt6I6LWgHl\nP6syuZd/Fl7JgDbka5Rjki4sWGfdMVEtdymHx+GBwxuuL/0AvfrRWcqOiesD\n2DH1ir3nyP2QxtasU0AqJku79rTFfUTcxi8isKIxkYITY7lrhJ/VbPe1hZnu\n0El5WryQxjzHsbZZGRJGEzhSYXS56Tno7Z8uZa7F3YcPvqVVaS0+RGO/dWQj\nxalV\r\n=pWno\r\n-----END PGP SIGNATURE-----\r\n" - }, - "_npmUser": { - "name": "nlf", - "email": "quitlahok@gmail.com" - }, - "directories": {}, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - } - ], - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/shrinkwrapped-dep-updates-b_2.0.0_1618847964221_0.13209121545380587" - }, - "_hasShrinkwrap": false - } - }, - "time": { - "created": "2021-04-19T15:59:11.370Z", - "1.0.0": "2021-04-19T15:59:11.545Z", - "modified": "2021-04-19T15:59:26.513Z", - "2.0.0": "2021-04-19T15:59:24.340Z" - }, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - } - ], - "description": "a dependency that a shrinkwrapped dependency depends on", - "readme": "ERROR: No README data found!", - "readmeFilename": "" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-b.min.json b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-b.min.json deleted file mode 100644 index f651d38243c4b..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-b.min.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-b", - "dist-tags": { - "latest": "2.0.0" - }, - "versions": { - "1.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-b", - "version": "1.0.0", - "dist": { - "integrity": "sha512-O8gmWJxc3W9yjGNGnEwumPQfXDTjIwkixWN8XPKvuEKwg5QldqAJfka5u7NwvM4ILP+1TT2OEMf+cNEYJ3eXUw==", - "shasum": "0f111693939e966d67c3f23c30900497076d1aa6", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-1.0.0.tgz", - "fileCount": 1, - "unpackedSize": 147, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfajPCRA9TVsSAnZWagAAfDsP/RAm3dd6uldkPJ3n/D4+\nwSrBpKQhFdwN1h9aE6dhgC8dq01r/sjezZcPDeTNAoZX8f7M0GAXNw1bB+5e\nXHp0y8lyfRXZL+EZwhZCfl0za01whvbrx79t01oeYgaeHP4ztbjygmfr7Y/D\nz+ft0/H3Fguwz76yELFYqjGY4G2mjUC93+2AhZhJ2KBSj6xsL+LUe4hdh8y/\n7HTg9j2rr+iDxS2uFWWb9DiQokfhOfyM2FrfqoCZZtPGg28I5W8zQtw9YTBj\ny2pXrhpxKzc8woHgfjlSocdj2pp6tAjiNNBVFRzKp5MBb72EAuGKAXHe8VHF\n2B6tuUYMJeOe0s9y4ptmSWg3gBZtmL/dqGn/oZy/3MdjHloz48FVUr+pyGjS\nB+JCPnal907qlfQNhXYz1I9LlfYaTgwHZEbAy4PFZA7V7MMtVWNFtwj3/Pwk\nQqHD7Su+66y//o9d3nSKWW7k5my3/T1MNbPmnisFMqpKuiMS54Bvv0ckcd4A\n593TgA7H2f0H+HSF55PH2q7BZeRkfoB2pht6XDdBSZsfWgmnksOcb0Dfy45Y\nvnHuHs/TdhrsqCxrxjNd8FrJUt2eO/R7ejRCvQhOdHLl9DWzOmhbFZqsP9El\nsTeg2OEKjDRqQCmgugcZANos9lHWFOZH0VgF2nMy3sT089sbhOf2DyWUsMmv\ne/i4\r\n=ZoBI\r\n-----END PGP SIGNATURE-----\r\n" - } - }, - "2.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-b", - "version": "2.0.0", - "dist": { - "integrity": "sha512-B5arzHMzN1kp67O/tVRR+OtosYDYVdNH7dLKkVR9Ruov+M6a7mrj2bOAJd8HZMQlQ5yjMRy3UXTp2amgh9EhqA==", - "shasum": "d857895f3d09514e7efb127f9092451b34c13db7", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-2.0.0.tgz", - "fileCount": 1, - "unpackedSize": 147, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfajcCRA9TVsSAnZWagAATBkP/jMOkUYS+ehl6DKBRaLA\nrRet2hEeF8bIZQM71v+mU07oJjGWyAwKB4ZI+uEaYY4VqGZBQI5obX52Da+O\ncu+zIgbGXgTk2YgQMcyCnl2kkof2s9kPe+EflH3kHcDuK/V819ekCyNVG09W\nmDTRRx1OhT16gQnAXtfW8cLbkOS4fmbX3nUgXQIPzFqgMYtVxoJ7BXeVo0HX\nQr2ZQap9NcxQheFsSOTjCaHim2q3s0K2TOW8k2FAA1lfHmnIjMrDjiOWdBTM\nwl4M/xIyC6xKs3w/Xilyk5Ra6HIe3sxtG1KQFq/OJx3XRgV9eF61rxmo4Ru/\nrfupUlMkVluqP78CvTkulLmxSkb6flye8QskD8V93MJxFtMP7tiABINNSntT\nM33TfTBcmxUqULJTIN2oeSJyHPTAU3uFSB8Z9BKURppopyROD1+1jN/goyEy\naJWG2iXdeoXYycnmBukqOn/Jr06Bk2IWxsqKG/1x89YOY92quXbt6I6LWgHl\nP6syuZd/Fl7JgDbka5Rjki4sWGfdMVEtdymHx+GBwxuuL/0AvfrRWcqOiesD\n2DH1ir3nyP2QxtasU0AqJku79rTFfUTcxi8isKIxkYITY7lrhJ/VbPe1hZnu\n0El5WryQxjzHsbZZGRJGEzhSYXS56Tno7Z8uZa7F3YcPvqVVaS0+RGO/dWQj\nxalV\r\n=pWno\r\n-----END PGP SIGNATURE-----\r\n" - } - } - }, - "modified": "2021-04-19T15:59:26.513Z" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-1.0.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-1.0.0.tgz deleted file mode 100644 index ed45cf6739137..0000000000000 Binary files a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-1.0.0.tgz and /dev/null differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-2.0.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-2.0.0.tgz deleted file mode 100644 index 5ab93f5c4ab04..0000000000000 Binary files a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-2.0.0.tgz and /dev/null differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-c.json b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-c.json deleted file mode 100644 index 2316aef5c3c6f..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-c.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "_id": "@nlf/shrinkwrapped-dep-updates-c", - "name": "@nlf/shrinkwrapped-dep-updates-c", - "dist-tags": { - "latest": "1.0.0" - }, - "versions": { - "1.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-c", - "version": "1.0.0", - "description": "a dependency that a shrinkwrapped dependency depends on", - "_id": "@nlf/shrinkwrapped-dep-updates-c@1.0.0", - "_nodeVersion": "15.11.0", - "_npmVersion": "7.9.0", - "dist": { - "integrity": "sha512-Ny4NLloQxmjos+llolUBcc9+5FTa+JCh5/CqshFYq6d6s3RykpGuFnqPN/3vO6Uftp3lPtBOGjvlXSJtN4ZDQA==", - "shasum": "f978f8bf577c4cef0fcda2a07d804f506d1d89fc", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-c/-/shrinkwrapped-dep-updates-c-1.0.0.tgz", - "fileCount": 1, - "unpackedSize": 147, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfaizCRA9TVsSAnZWagAAfz8P/A+XjocAXkzZ7GC1FEbP\nNyQ3Hfuk6uW01IGOaylqjUvMBTcmMrQXyBBXHvuW5x2qu866FPjZp2s+vlxe\nWaH8wuL2S21uXao0sJH3rDNAJc6CzxZuL+bBP9XkgQ/K2MOJv51cCViVgxve\nc1Wm6ulezcCiywxQWoMpTVdF/dQUxh1b4slqDYHw4eJEo0kxhls2GHJVBX7z\nA7/KgSvhMdch6DJPRbcACGwHkLHhYBWbZgmA1AuwnAUwX++8gNY7+o2zFYNP\nTO/l5/af/8Wsw7mw3rcpr5ZHl0As7nHhyDd+Gtqf4lWJjg/zjP0TcZ/GzNHS\n1J93etXH0okLgd/nIkQvtcKSSdG8DKY1i5y8ajIjaVTAhxLrulqoJY8iVV2i\nmch7BpgD/P8sFUPBOUJCpIiuWppccjq28qP/ye4BSjtDIB8iL+lQD0eOAqHM\na6G1c6tZ+aDCAY1nKOTfC9HolnBJjW8BWHmWKLAu9phYuGs/3Bb7g7Lw78vf\n+HokRDmhHQFChMoHYIJjJgRZjdtk+BCG5dXVin9m4VgHsGTp1DQs9HTkghW/\nMRNYX6CDzXtXKCe6V9XErp7O08LXYgkgOM3csAR6BDrF9gzFKTcHz0ii0NNG\nU/zDwco+ZGOJ1YnkYs1Ho2EKjhacTopqZh40BDfHlDthx0+4L25xCVwenB5w\nfwqz\r\n=4/hG\r\n-----END PGP SIGNATURE-----\r\n" - }, - "_npmUser": { - "name": "nlf", - "email": "quitlahok@gmail.com" - }, - "directories": {}, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - } - ], - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/shrinkwrapped-dep-updates-c_1.0.0_1618847922911_0.8853351621660768" - }, - "_hasShrinkwrap": false - } - }, - "time": { - "created": "2021-04-19T15:58:42.849Z", - "1.0.0": "2021-04-19T15:58:43.034Z", - "modified": "2021-04-19T15:58:46.525Z" - }, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - } - ], - "description": "a dependency that a shrinkwrapped dependency depends on", - "readme": "ERROR: No README data found!", - "readmeFilename": "" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-c.min.json b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-c.min.json deleted file mode 100644 index 11107ccc74033..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-c.min.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-c", - "dist-tags": { - "latest": "1.0.0" - }, - "versions": { - "1.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-c", - "version": "1.0.0", - "dist": { - "integrity": "sha512-Ny4NLloQxmjos+llolUBcc9+5FTa+JCh5/CqshFYq6d6s3RykpGuFnqPN/3vO6Uftp3lPtBOGjvlXSJtN4ZDQA==", - "shasum": "f978f8bf577c4cef0fcda2a07d804f506d1d89fc", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-c/-/shrinkwrapped-dep-updates-c-1.0.0.tgz", - "fileCount": 1, - "unpackedSize": 147, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfaizCRA9TVsSAnZWagAAfz8P/A+XjocAXkzZ7GC1FEbP\nNyQ3Hfuk6uW01IGOaylqjUvMBTcmMrQXyBBXHvuW5x2qu866FPjZp2s+vlxe\nWaH8wuL2S21uXao0sJH3rDNAJc6CzxZuL+bBP9XkgQ/K2MOJv51cCViVgxve\nc1Wm6ulezcCiywxQWoMpTVdF/dQUxh1b4slqDYHw4eJEo0kxhls2GHJVBX7z\nA7/KgSvhMdch6DJPRbcACGwHkLHhYBWbZgmA1AuwnAUwX++8gNY7+o2zFYNP\nTO/l5/af/8Wsw7mw3rcpr5ZHl0As7nHhyDd+Gtqf4lWJjg/zjP0TcZ/GzNHS\n1J93etXH0okLgd/nIkQvtcKSSdG8DKY1i5y8ajIjaVTAhxLrulqoJY8iVV2i\nmch7BpgD/P8sFUPBOUJCpIiuWppccjq28qP/ye4BSjtDIB8iL+lQD0eOAqHM\na6G1c6tZ+aDCAY1nKOTfC9HolnBJjW8BWHmWKLAu9phYuGs/3Bb7g7Lw78vf\n+HokRDmhHQFChMoHYIJjJgRZjdtk+BCG5dXVin9m4VgHsGTp1DQs9HTkghW/\nMRNYX6CDzXtXKCe6V9XErp7O08LXYgkgOM3csAR6BDrF9gzFKTcHz0ii0NNG\nU/zDwco+ZGOJ1YnkYs1Ho2EKjhacTopqZh40BDfHlDthx0+4L25xCVwenB5w\nfwqz\r\n=4/hG\r\n-----END PGP SIGNATURE-----\r\n" - } - } - }, - "modified": "2021-04-19T15:58:46.525Z" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-c/-/shrinkwrapped-dep-updates-c-1.0.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-c/-/shrinkwrapped-dep-updates-c-1.0.0.tgz deleted file mode 100644 index 87bbaa677e0c7..0000000000000 Binary files a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-c/-/shrinkwrapped-dep-updates-c-1.0.0.tgz and /dev/null differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-d.json b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-d.json deleted file mode 100644 index c447ec25ed0ae..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-d.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "_id": "@nlf/shrinkwrapped-dep-updates-d", - "name": "@nlf/shrinkwrapped-dep-updates-d", - "dist-tags": { - "latest": "1.0.0" - }, - "versions": { - "1.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-d", - "version": "1.0.0", - "description": "a dependency that a shrinkwrapped dependency depends on", - "_id": "@nlf/shrinkwrapped-dep-updates-d@1.0.0", - "_nodeVersion": "15.11.0", - "_npmVersion": "7.9.0", - "dist": { - "integrity": "sha512-VcomTaV8pXizm8uJe//Iu7nDCyYeeIs5hdOzcO2NwmuyhFMlCGUAGb+pHx4f+Kz++sil52Zz817DUqOaVGAz1g==", - "shasum": "d283bd4e59ce7cb33a28f886a8b0a2053688870c", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-d/-/shrinkwrapped-dep-updates-d-1.0.0.tgz", - "fileCount": 1, - "unpackedSize": 147, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfaicCRA9TVsSAnZWagAAMocP/i3oC4qHlyTmZ5+Y0lEf\nbTJW7VfcFk3aDj6SAPx8/zxLbBLBDIuumTn4P0VueVWRaHvUYz98qefvpMlR\n+sjM0ucMGq47lTLuz2Qlv3wMhtO0eaOb+n1a1/dy15hD8hsy4v9bexmCpWta\nkBd098AwWpl2JgrcuVCZrbm12eOA146QzNRCYKgfimvBEf70Ogd3bY/d0UIx\nQPsLTubm9FEF9ldG8YkpV9WU8q6ChtWhdqrWBkV7iLXddxYxe7YlXzqJp3e3\n0cea0JJ67pqEwhdHEGLsrH1sr4QtzriVA1+/c/1TcVsckFSQVBsT/1K/SLTR\nrKsQzIzyXt8MG9X8Hj3lSZ0R+UPT+Prruk6fAgJlO4H7iK13+E16gjucTewD\nqXYn+jogQ6tkO4sk8qjpBfjxzwGhVTrSjioUsu5xjTJM/nerKtMf4J/hQKcJ\nLWxEp0Krn0+N0uJlqVmU2CI0SKeXN8erKgAhh3lEdxm5TGmCfBGPXv2V3CWV\nunFypb/MiaBRu/yQrbF6npgUDcXVfluxGRacXAcyhyYmy+upbR4Y/cUBbhdX\nwK2TklUjA0szA8ah20Ra8KD3b2GfHj5m+773Qortm24K4QAXpn0XfPnV1NVb\n2xE6zRpag+fUWkA6jvdRWTjRyZT/Ew8iDV4aqwkhcLe3ikJ+F97NjQgXQ05Z\nHZec\r\n=2NzU\r\n-----END PGP SIGNATURE-----\r\n" - }, - "_npmUser": { - "name": "nlf", - "email": "quitlahok@gmail.com" - }, - "directories": {}, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - } - ], - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/shrinkwrapped-dep-updates-d_1.0.0_1618847900506_0.2056089206881928" - }, - "_hasShrinkwrap": false - } - }, - "time": { - "created": "2021-04-19T15:58:20.449Z", - "1.0.0": "2021-04-19T15:58:20.605Z", - "modified": "2021-04-19T15:58:22.687Z" - }, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - } - ], - "description": "a dependency that a shrinkwrapped dependency depends on", - "readme": "ERROR: No README data found!", - "readmeFilename": "" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-d.min.json b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-d.min.json deleted file mode 100644 index 2c8e3c8c05cb5..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-d.min.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-d", - "dist-tags": { - "latest": "1.0.0" - }, - "versions": { - "1.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-d", - "version": "1.0.0", - "dist": { - "integrity": "sha512-VcomTaV8pXizm8uJe//Iu7nDCyYeeIs5hdOzcO2NwmuyhFMlCGUAGb+pHx4f+Kz++sil52Zz817DUqOaVGAz1g==", - "shasum": "d283bd4e59ce7cb33a28f886a8b0a2053688870c", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-d/-/shrinkwrapped-dep-updates-d-1.0.0.tgz", - "fileCount": 1, - "unpackedSize": 147, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfaicCRA9TVsSAnZWagAAMocP/i3oC4qHlyTmZ5+Y0lEf\nbTJW7VfcFk3aDj6SAPx8/zxLbBLBDIuumTn4P0VueVWRaHvUYz98qefvpMlR\n+sjM0ucMGq47lTLuz2Qlv3wMhtO0eaOb+n1a1/dy15hD8hsy4v9bexmCpWta\nkBd098AwWpl2JgrcuVCZrbm12eOA146QzNRCYKgfimvBEf70Ogd3bY/d0UIx\nQPsLTubm9FEF9ldG8YkpV9WU8q6ChtWhdqrWBkV7iLXddxYxe7YlXzqJp3e3\n0cea0JJ67pqEwhdHEGLsrH1sr4QtzriVA1+/c/1TcVsckFSQVBsT/1K/SLTR\nrKsQzIzyXt8MG9X8Hj3lSZ0R+UPT+Prruk6fAgJlO4H7iK13+E16gjucTewD\nqXYn+jogQ6tkO4sk8qjpBfjxzwGhVTrSjioUsu5xjTJM/nerKtMf4J/hQKcJ\nLWxEp0Krn0+N0uJlqVmU2CI0SKeXN8erKgAhh3lEdxm5TGmCfBGPXv2V3CWV\nunFypb/MiaBRu/yQrbF6npgUDcXVfluxGRacXAcyhyYmy+upbR4Y/cUBbhdX\nwK2TklUjA0szA8ah20Ra8KD3b2GfHj5m+773Qortm24K4QAXpn0XfPnV1NVb\n2xE6zRpag+fUWkA6jvdRWTjRyZT/Ew8iDV4aqwkhcLe3ikJ+F97NjQgXQ05Z\nHZec\r\n=2NzU\r\n-----END PGP SIGNATURE-----\r\n" - } - } - }, - "modified": "2021-04-19T15:58:22.687Z" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-d/-/shrinkwrapped-dep-updates-d-1.0.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-d/-/shrinkwrapped-dep-updates-d-1.0.0.tgz deleted file mode 100644 index c6e8d31bffdf4..0000000000000 Binary files a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-d/-/shrinkwrapped-dep-updates-d-1.0.0.tgz and /dev/null differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-e.json b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-e.json deleted file mode 100644 index f48fb6f480122..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-e.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "_id": "@nlf/shrinkwrapped-dep-updates-e", - "name": "@nlf/shrinkwrapped-dep-updates-e", - "dist-tags": { - "latest": "1.0.0" - }, - "versions": { - "1.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-e", - "version": "1.0.0", - "description": "a dependency that a shrinkwrapped dependency depends on", - "_id": "@nlf/shrinkwrapped-dep-updates-e@1.0.0", - "_nodeVersion": "15.11.0", - "_npmVersion": "7.9.0", - "dist": { - "integrity": "sha512-k41VmVMeLH/AgnD7Nx2TIQvt12xd0dKSrWmraYDNZIMxtuuwUjaq1lH8eo8todBU7U5aj94cH4xlLU0g3SgsBA==", - "shasum": "bad83483d08c1e134bc632cd94a146d037d266c2", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-e/-/shrinkwrapped-dep-updates-e-1.0.0.tgz", - "fileCount": 1, - "unpackedSize": 147, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfaiLCRA9TVsSAnZWagAAvPQP/3j5LZqrto1+k2kRsUwY\n4KhcD9ejg+iRsUyobh4i9AzIXHV4aDhmUXfEQPfZapZGlhPoeNHvLlH2Yc9Z\nQkUBQGpgAgHWRl0IEnlRD7XV8tbCAbwEjJVZKMqpp6+QZGbHYEmL50JNWQvo\nUlmM2hJNZfdSWGbXFfzmeTXcZzacjylOnihhuejRxc06y9nziuLRZ/xBv+1q\n0owaXlUc1x9AOfrKRxzJ3yu8GojrhHwwoB5n3sGHgS+8aiI1AO5nsV13Zy21\n1L5ZUgwMJozf1YMJQSbxKvncAfjasmrX4CYupCrnC3ci8negnJ9sjGz6kbV/\nbdCp8/HB1GzqIH3a9LE5vJ6Hhx/P6ri6WFKJQF+n+ysbBXukc+hOwoRPetrY\nt4JuVN+2HXn3ODJM/C6xZMGg6Z8MAiyGbEo6Z4JHbJAATEwLCpxXmHwWnXJz\nxCFAWfvmY9Vvx0QkkwFOmJZCaKKSg2lT6r99OTi3VaI+eGVh/agRPgQR2MGJ\n4N2enq9BXyvZNLhtqTuE301DFe4s2wdNwHVD3IHkVlPQjo0XWK1zqy5FF7Fj\nXq43ODCDR9JHqNvT+4/kmXHe28c1yyaqCI4ENUBe5qjMcVYS8w4/4rm+H1CY\nL3vvfcjOn2mj6TtmsEb22Y3/7R4ACTprfVYBFkToj5Yvo6g7vNsiKQrx/YSe\nv4O5\r\n=QXB1\r\n-----END PGP SIGNATURE-----\r\n" - }, - "_npmUser": { - "name": "nlf", - "email": "quitlahok@gmail.com" - }, - "directories": {}, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - } - ], - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/shrinkwrapped-dep-updates-e_1.0.0_1618847882817_0.9807461233557111" - }, - "_hasShrinkwrap": false - } - }, - "time": { - "created": "2021-04-19T15:58:02.723Z", - "1.0.0": "2021-04-19T15:58:02.902Z", - "modified": "2021-04-19T15:58:06.316Z" - }, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - } - ], - "description": "a dependency that a shrinkwrapped dependency depends on", - "readme": "ERROR: No README data found!", - "readmeFilename": "" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-e.min.json b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-e.min.json deleted file mode 100644 index 1641c8a68b142..0000000000000 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-e.min.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-e", - "dist-tags": { - "latest": "1.0.0" - }, - "versions": { - "1.0.0": { - "name": "@nlf/shrinkwrapped-dep-updates-e", - "version": "1.0.0", - "dist": { - "integrity": "sha512-k41VmVMeLH/AgnD7Nx2TIQvt12xd0dKSrWmraYDNZIMxtuuwUjaq1lH8eo8todBU7U5aj94cH4xlLU0g3SgsBA==", - "shasum": "bad83483d08c1e134bc632cd94a146d037d266c2", - "tarball": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-e/-/shrinkwrapped-dep-updates-e-1.0.0.tgz", - "fileCount": 1, - "unpackedSize": 147, - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgfaiLCRA9TVsSAnZWagAAvPQP/3j5LZqrto1+k2kRsUwY\n4KhcD9ejg+iRsUyobh4i9AzIXHV4aDhmUXfEQPfZapZGlhPoeNHvLlH2Yc9Z\nQkUBQGpgAgHWRl0IEnlRD7XV8tbCAbwEjJVZKMqpp6+QZGbHYEmL50JNWQvo\nUlmM2hJNZfdSWGbXFfzmeTXcZzacjylOnihhuejRxc06y9nziuLRZ/xBv+1q\n0owaXlUc1x9AOfrKRxzJ3yu8GojrhHwwoB5n3sGHgS+8aiI1AO5nsV13Zy21\n1L5ZUgwMJozf1YMJQSbxKvncAfjasmrX4CYupCrnC3ci8negnJ9sjGz6kbV/\nbdCp8/HB1GzqIH3a9LE5vJ6Hhx/P6ri6WFKJQF+n+ysbBXukc+hOwoRPetrY\nt4JuVN+2HXn3ODJM/C6xZMGg6Z8MAiyGbEo6Z4JHbJAATEwLCpxXmHwWnXJz\nxCFAWfvmY9Vvx0QkkwFOmJZCaKKSg2lT6r99OTi3VaI+eGVh/agRPgQR2MGJ\n4N2enq9BXyvZNLhtqTuE301DFe4s2wdNwHVD3IHkVlPQjo0XWK1zqy5FF7Fj\nXq43ODCDR9JHqNvT+4/kmXHe28c1yyaqCI4ENUBe5qjMcVYS8w4/4rm+H1CY\nL3vvfcjOn2mj6TtmsEb22Y3/7R4ACTprfVYBFkToj5Yvo6g7vNsiKQrx/YSe\nv4O5\r\n=QXB1\r\n-----END PGP SIGNATURE-----\r\n" - } - } - }, - "modified": "2021-04-19T15:58:06.316Z" -} diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-e/-/shrinkwrapped-dep-updates-e-1.0.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-e/-/shrinkwrapped-dep-updates-e-1.0.0.tgz deleted file mode 100644 index b13b170f07a2f..0000000000000 Binary files a/workspaces/arborist/test/fixtures/registry-mocks/content/nlf/shrinkwrapped-dep-updates-e/-/shrinkwrapped-dep-updates-e-1.0.0.tgz and /dev/null differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/test/a.json b/workspaces/arborist/test/fixtures/registry-mocks/content/test/a.json new file mode 100644 index 0000000000000..94cd8577573fb --- /dev/null +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/test/a.json @@ -0,0 +1,146 @@ +{ + "name": "@test/a", + "versions": { + "1.2.0": { + "name": "@test/a", + "version": "1.2.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "peerDependencies": { + "lodash": "^4.17.21", + "underscore": "^1.13.1", + "@test/b": "1.2.0", + "@test/c": "1.2.0" + }, + "peerDependenciesMeta": { + "@test/b": { + "optional": true + }, + "@test/c": { + "optional": true + }, + "lodash": { + "optional": true + }, + "underscore": { + "optional": true + } + }, + "_id": "@test/a@1.2.0", + "_nodeVersion": "22.14.0", + "_npmVersion": "11.4.2", + "dist": { + "integrity": "sha512-k7WYu8tdQY1aq8QV+7YEGcoSYXrdCACqnabuvNC8Tpwvpk/MF25CeX4nei6eliVaHqHxzNzAr60ne2TgsEoz2Q==", + "shasum": "b609076c847a018b144ab68c953817847195535a", + "tarball": "http://localhost:4873/@test/a/-/a-1.2.0.tgz" + }, + "contributors": [] + }, + "1.1.0": { + "name": "@test/a", + "version": "1.1.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "peerDependencies": { + "lodash": "^4.17.0", + "uniq": "^1.0.0", + "@test/b": "1.1.0", + "@test/c": "1.1.0" + }, + "peerDependenciesMeta": { + "@test/b": { + "optional": true + }, + "@test/c": { + "optional": true + }, + "lodash": { + "optional": true + }, + "uniq": { + "optional": true + } + }, + "_id": "@test/a@1.1.0", + "_nodeVersion": "22.14.0", + "_npmVersion": "11.4.2", + "dist": { + "integrity": "sha512-qlfAcmAKeohHKBVVAnwsiDs+URz5jCPYlXe+srdxX6Nzhl9W6FX9kV5Lm6XahBhB+H/c+eRi+ghAE8YcdzmFIA==", + "shasum": "0d9b53f67e05d388195ad096f61fe2c1c6f0ff8d", + "tarball": "http://localhost:4873/@test/a/-/a-1.1.0.tgz" + }, + "contributors": [] + }, + "1.0.0": { + "name": "@test/a", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "peerDependencies": { + "lodash": "^4.17.0", + "uniq": "^1.0.0", + "@test/b": "1.0.0", + "@test/c": "1.0.0" + }, + "peerDependenciesMeta": { + "@test/b": { + "optional": true + }, + "@test/c": { + "optional": true + }, + "lodash": { + "optional": true + }, + "uniq": { + "optional": true + } + }, + "_id": "@test/a@1.0.0", + "_nodeVersion": "22.14.0", + "_npmVersion": "11.4.2", + "dist": { + "integrity": "sha512-BRD01XQTy4WW2PrMdV0ZvHdqlY6v0FY3kyvEIv4v0n7apOHQwuQqjdL4iWnApfEwD0o0mVSbQs5s6DibNmDnMg==", + "shasum": "a1ec39760cf04261fff44b23582f1bafba0b14ff", + "tarball": "http://localhost:4873/@test/a/-/a-1.0.0.tgz" + }, + "contributors": [] + } + }, + "time": { + "modified": "2025-07-31T16:24:31.780Z", + "created": "2025-07-29T12:59:32.758Z", + "1.2.0": "2025-07-29T13:15:20.477Z", + "1.1.0": "2025-07-31T16:24:09.634Z", + "1.0.0": "2025-07-31T16:24:31.780Z" + }, + "users": {}, + "dist-tags": { + "latest": "1.0.0" + }, + "_rev": "44-1c1667b80cb416cc", + "_id": "@test/a", + "readme": "ERROR: No README data found!", + "_attachments": {} +} \ No newline at end of file diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/test/a/a-1.0.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/test/a/a-1.0.0.tgz new file mode 100644 index 0000000000000..00df7811e9df7 Binary files /dev/null and b/workspaces/arborist/test/fixtures/registry-mocks/content/test/a/a-1.0.0.tgz differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/test/a/a-1.1.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/test/a/a-1.1.0.tgz new file mode 100644 index 0000000000000..c1a2ba7b9b186 Binary files /dev/null and b/workspaces/arborist/test/fixtures/registry-mocks/content/test/a/a-1.1.0.tgz differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/test/b.json b/workspaces/arborist/test/fixtures/registry-mocks/content/test/b.json new file mode 100644 index 0000000000000..b32a350389ca7 --- /dev/null +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/test/b.json @@ -0,0 +1,95 @@ +{ + "name": "@test/b", + "versions": { + "1.0.0": { + "name": "@test/b", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "peerDependencies": { + "@test/a": "1.0.0" + }, + "_id": "@test/b@1.0.0", + "_nodeVersion": "22.14.0", + "_npmVersion": "11.4.2", + "dist": { + "integrity": "sha512-q2p6qVG/lIpauYmngTeuWBAhqMYOR/dAzIk/nhpIuuqueji1cuhXFkuxykRn1N/imlLKWEzXxdS72krNMAohYg==", + "shasum": "049ecb3edfce0c78d1e94718bda1e2c24d004f5c", + "tarball": "http://localhost:4873/@test/b/-/b-1.0.0.tgz" + }, + "contributors": [] + }, + "1.1.0": { + "name": "@test/b", + "version": "1.1.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "peerDependencies": { + "@test/a": "1.1.0" + }, + "_id": "@test/b@1.1.0", + "_nodeVersion": "22.14.0", + "_npmVersion": "11.4.2", + "dist": { + "integrity": "sha512-WrPD0/5vcNlm12B6XDjTiIBN0U5SfGAuPBYJi3QeV2jEaBAnXnjWnffv7Dov0KPON3zsPg11t/EB4BDVgWIJEg==", + "shasum": "33107fbfdc56efed9ae21749aae5ea84bc4a5b80", + "tarball": "http://localhost:4873/@test/b/-/b-1.1.0.tgz" + }, + "contributors": [] + }, + "1.2.0": { + "name": "@test/b", + "version": "1.2.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "peerDependencies": { + "@test/a": "1.2.0" + }, + "_id": "@test/b@1.2.0", + "_nodeVersion": "22.14.0", + "_npmVersion": "11.4.2", + "dist": { + "integrity": "sha512-X90tU1P+EZ/IyiG4ICrQgKEBcQBQugZ/0OKo9xGN8a2dWPoJ7zefIQwpoQTy2NE5w7SgGyi6v9PQSw191v524Q==", + "shasum": "b735bde9da04cbd5f1cbb31817bf64302f0db265", + "tarball": "http://localhost:4873/@test/b/-/b-1.2.0.tgz" + }, + "contributors": [] + } + }, + "time": { + "modified": "2025-07-29T13:02:09.586Z", + "created": "2025-07-29T13:01:53.128Z", + "1.0.0": "2025-07-29T13:01:53.128Z", + "1.1.0": "2025-07-29T13:02:01.228Z", + "1.2.0": "2025-07-29T13:02:09.586Z" + }, + "users": {}, + "dist-tags": { + "latest": "1.2.0" + }, + "_rev": "9-e8970996bfeb2c4f", + "_id": "@test/b", + "readme": "ERROR: No README data found!", + "_attachments": {} +} \ No newline at end of file diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/test/b/b-1.0.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/test/b/b-1.0.0.tgz new file mode 100644 index 0000000000000..0a10edf65b2e3 Binary files /dev/null and b/workspaces/arborist/test/fixtures/registry-mocks/content/test/b/b-1.0.0.tgz differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/test/b/b-1.1.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/test/b/b-1.1.0.tgz new file mode 100644 index 0000000000000..96f29aea98300 Binary files /dev/null and b/workspaces/arborist/test/fixtures/registry-mocks/content/test/b/b-1.1.0.tgz differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/test/c.json b/workspaces/arborist/test/fixtures/registry-mocks/content/test/c.json new file mode 100644 index 0000000000000..e26765f61e416 --- /dev/null +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/test/c.json @@ -0,0 +1,95 @@ +{ + "name": "@test/c", + "versions": { + "1.0.0": { + "name": "@test/c", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "peerDependencies": { + "@test/a": "1.0.0" + }, + "_id": "@test/c@1.0.0", + "_nodeVersion": "22.14.0", + "_npmVersion": "11.4.2", + "dist": { + "integrity": "sha512-ikGDvMXxzqHgCkIycVNWmpfDs6G/aA7i3AY1Or+T+hO+2G/t+rfIxnLgIc4p10K7GM2ZxcipK9Z7U6LAtTO0iw==", + "shasum": "96b5a6fa92f8713c240686e9f3dfd5c00df7497e", + "tarball": "http://localhost:4873/@test/c/-/c-1.0.0.tgz" + }, + "contributors": [] + }, + "1.1.0": { + "name": "@test/c", + "version": "1.1.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "peerDependencies": { + "@test/a": "1.1.0" + }, + "_id": "@test/c@1.1.0", + "_nodeVersion": "22.14.0", + "_npmVersion": "11.4.2", + "dist": { + "integrity": "sha512-BNxNmwGwAhVxA8RQpog/wy/NNZfa5ruskwZePlKfu1zpLVtsrjO8zGau6C/c8iIw9mwrVqBAeBuFpUwJhLTAZA==", + "shasum": "01db72391f551fd7944adbf0f54eaebc389b90c4", + "tarball": "http://localhost:4873/@test/c/-/c-1.1.0.tgz" + }, + "contributors": [] + }, + "1.2.0": { + "name": "@test/c", + "version": "1.2.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "peerDependencies": { + "@test/a": "1.2.0" + }, + "_id": "@test/c@1.2.0", + "_nodeVersion": "22.14.0", + "_npmVersion": "11.4.2", + "dist": { + "integrity": "sha512-pAHdEr8mb8mXuWPQL0mbkyHVulhzVWQ3HvpO9OBZ0azF56p9cr1+hVy/CajxPdEr/Crx6iBfjpoaNYscVPbvMg==", + "shasum": "e915f26882f8bbde7e238c02908bbc5625cf3c4e", + "tarball": "http://localhost:4873/@test/c/-/c-1.2.0.tgz" + }, + "contributors": [] + } + }, + "time": { + "modified": "2025-07-29T13:03:42.407Z", + "created": "2025-07-29T13:03:29.009Z", + "1.0.0": "2025-07-29T13:03:29.009Z", + "1.1.0": "2025-07-29T13:03:36.559Z", + "1.2.0": "2025-07-29T13:03:42.407Z" + }, + "users": {}, + "dist-tags": { + "latest": "1.2.0" + }, + "_rev": "9-19d0ff85a20ff576", + "_id": "@test/c", + "readme": "ERROR: No README data found!", + "_attachments": {} +} \ No newline at end of file diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/test/c/c-1.0.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/test/c/c-1.0.0.tgz new file mode 100644 index 0000000000000..65661f1328219 Binary files /dev/null and b/workspaces/arborist/test/fixtures/registry-mocks/content/test/c/c-1.0.0.tgz differ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/test/c/c-1.1.0.tgz b/workspaces/arborist/test/fixtures/registry-mocks/content/test/c/c-1.1.0.tgz new file mode 100644 index 0000000000000..cdbee76034001 Binary files /dev/null and b/workspaces/arborist/test/fixtures/registry-mocks/content/test/c/c-1.1.0.tgz differ diff --git a/workspaces/arborist/test/fixtures/reify-cases/prune-lockfile-optional-peer.js b/workspaces/arborist/test/fixtures/reify-cases/prune-lockfile-optional-peer.js new file mode 100644 index 0000000000000..b420709f5aa68 --- /dev/null +++ b/workspaces/arborist/test/fixtures/reify-cases/prune-lockfile-optional-peer.js @@ -0,0 +1,60 @@ +// generated from test/fixtures/prune-lockfile-optional-peer +module.exports = t => { + const path = t.testdir({ + "node_modules": { + "dedent": { + "package.json": JSON.stringify({ + "name": "dedent", + "version": "1.6.0", + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } + }) + } + }, + "package-lock.json": JSON.stringify({ + "name": "prune-lockfile-optional-peer", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "prune-lockfile-optional-peer", + "version": "1.0.0", + "dependencies": { + "dedent": "^1.6.0" + } + }, + "node_modules/babel-plugin-macros": { + "version": "3.1.0", + "optional": true, + "peer": true + }, + "node_modules/dedent": { + "version": "1.6.0", + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } + } + } + }), + "package.json": JSON.stringify({ + "name": "prune-lockfile-optional-peer", + "version": "1.0.0", + "dependencies": { + "dedent": "^1.6.0" + } + }) + }) + return path +} diff --git a/workspaces/arborist/test/fixtures/reify-cases/shrinkwrapped-dep-no-lock-empty.js b/workspaces/arborist/test/fixtures/reify-cases/shrinkwrapped-dep-no-lock-empty.js deleted file mode 100644 index c7ec4f2d4b7c5..0000000000000 --- a/workspaces/arborist/test/fixtures/reify-cases/shrinkwrapped-dep-no-lock-empty.js +++ /dev/null @@ -1,15 +0,0 @@ -// generated from test/fixtures/shrinkwrapped-dep-no-lock-empty -module.exports = t => { - const path = t.testdir({ - "README.md": "Just a module that depends on a module that ships a shrinkwrap.\n", - "package.json": JSON.stringify({ - "name": "shrinkwrap", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@isaacs/shrinkwrapped-dependency": "^1.0.0" - } - }) -}) - return path -} diff --git a/workspaces/arborist/test/fixtures/reify-cases/shrinkwrapped-dep-no-lock.js b/workspaces/arborist/test/fixtures/reify-cases/shrinkwrapped-dep-no-lock.js deleted file mode 100644 index 62345b449d221..0000000000000 --- a/workspaces/arborist/test/fixtures/reify-cases/shrinkwrapped-dep-no-lock.js +++ /dev/null @@ -1,145 +0,0 @@ -// generated from test/fixtures/shrinkwrapped-dep-no-lock -module.exports = t => { - const path = t.testdir({ - "README.md": "Just a module that depends on a module that ships a shrinkwrap.\n", - "node_modules": { - "@isaacs": { - "shrinkwrapped-dependency": { - "node_modules": { - "abbrev": { - "package.json": JSON.stringify({ - "_args": [ - [ - "abbrev@1.0.4", - "/Users/isaacs/dev/npm/arborist/test/fixtures/shrinkwrap/node_modules/@isaacs/shrinkwrapped-dependency" - ] - ], - "_from": "abbrev@1.0.4", - "_id": "abbrev@1.0.4", - "_inBundle": false, - "_integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=", - "_location": "/@isaacs/shrinkwrapped-dependency/abbrev", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "abbrev@1.0.4", - "name": "abbrev", - "escapedName": "abbrev", - "rawSpec": "1.0.4", - "saveSpec": null, - "fetchSpec": "1.0.4" - }, - "_requiredBy": [ - "/@isaacs/shrinkwrapped-dependency" - ], - "_resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "_spec": "1.0.4", - "_where": "/Users/isaacs/dev/npm/arborist/test/fixtures/shrinkwrap/node_modules/@isaacs/shrinkwrapped-dependency", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me" - }, - "bugs": { - "url": "https://github.com/isaacs/abbrev-js/issues" - }, - "description": "Like ruby's abbrev module, but in js", - "homepage": "https://github.com/isaacs/abbrev-js#readme", - "license": { - "type": "MIT", - "url": "https://github.com/isaacs/abbrev-js/raw/master/LICENSE" - }, - "main": "./lib/abbrev.js", - "name": "abbrev", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/isaacs/abbrev-js.git" - }, - "scripts": { - "test": "node lib/abbrev.js" - }, - "version": "1.0.4" - }) - } - }, - "npm-shrinkwrap.json": JSON.stringify({ - "name": "shrinkwrapped-dependency", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "abbrev": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=" - } - } - }), - "package.json": JSON.stringify({ - "_from": "@isaacs/shrinkwrapped-dependency@^1.0.0", - "_id": "@isaacs/shrinkwrapped-dependency@1.0.0", - "_inBundle": false, - "_integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "_location": "/@isaacs/shrinkwrapped-dependency", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@isaacs/shrinkwrapped-dependency@^1.0.0", - "name": "@isaacs/shrinkwrapped-dependency", - "escapedName": "@isaacs%2fshrinkwrapped-dependency", - "scope": "@isaacs", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "_shasum": "a22edfd12f2e796c924a36fe6cbf52eb495e93c3", - "_shrinkwrap": { - "name": "shrinkwrapped-dependency", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "abbrev": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=" - } - } - }, - "_spec": "@isaacs/shrinkwrapped-dependency@^1.0.0", - "_where": "/Users/isaacs/dev/npm/arborist/test/fixtures/shrinkwrap", - "author": "", - "bundleDependencies": false, - "dependencies": { - "abbrev": "^1.0.4" - }, - "deprecated": false, - "description": "", - "keywords": [], - "license": "ISC", - "main": "index.js", - "name": "@isaacs/shrinkwrapped-dependency", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "version": "1.0.0" - }) - } - } - }, - "package.json": JSON.stringify({ - "name": "shrinkwrap", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@isaacs/shrinkwrapped-dependency": "^1.0.0" - } - }) -}) - return path -} diff --git a/workspaces/arborist/test/fixtures/reify-cases/shrinkwrapped-dep-with-lock-empty.js b/workspaces/arborist/test/fixtures/reify-cases/shrinkwrapped-dep-with-lock-empty.js deleted file mode 100644 index 9045693053487..0000000000000 --- a/workspaces/arborist/test/fixtures/reify-cases/shrinkwrapped-dep-with-lock-empty.js +++ /dev/null @@ -1,66 +0,0 @@ -// generated from test/fixtures/shrinkwrapped-dep-with-lock-empty -module.exports = t => { - const path = t.testdir({ - "README.md": "Just a module that depends on a module that ships a shrinkwrap.\n", - "package-lock.json": JSON.stringify({ - "name": "shrinkwrap", - "version": "1.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "shrinkwrap", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@isaacs/shrinkwrapped-dependency": "^1.0.0" - } - }, - "node_modules/@isaacs/shrinkwrapped-dependency": { - "name": "@isaacs/shrinkwrapped-dependency", - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "hasShrinkwrap": true, - "license": "ISC", - "dependencies": { - "abbrev": "^1.0.4" - } - }, - "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev": { - "name": "abbrev", - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=", - "license": "MIT" - } - }, - "dependencies": { - "@isaacs/shrinkwrapped-dependency": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "requires": { - "abbrev": "^1.0.4" - }, - "dependencies": { - "abbrev": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=" - } - } - } - } - }), - "package.json": JSON.stringify({ - "name": "shrinkwrap", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@isaacs/shrinkwrapped-dependency": "^1.0.0" - } - }) -}) - return path -} diff --git a/workspaces/arborist/test/fixtures/reify-cases/shrinkwrapped-dep-with-lock.js b/workspaces/arborist/test/fixtures/reify-cases/shrinkwrapped-dep-with-lock.js deleted file mode 100644 index eb9b567f072a2..0000000000000 --- a/workspaces/arborist/test/fixtures/reify-cases/shrinkwrapped-dep-with-lock.js +++ /dev/null @@ -1,196 +0,0 @@ -// generated from test/fixtures/shrinkwrapped-dep-with-lock -module.exports = t => { - const path = t.testdir({ - "README.md": "Just a module that depends on a module that ships a shrinkwrap.\n", - "node_modules": { - "@isaacs": { - "shrinkwrapped-dependency": { - "node_modules": { - "abbrev": { - "package.json": JSON.stringify({ - "_args": [ - [ - "abbrev@1.0.4", - "/Users/isaacs/dev/npm/arborist/test/fixtures/shrinkwrap/node_modules/@isaacs/shrinkwrapped-dependency" - ] - ], - "_from": "abbrev@1.0.4", - "_id": "abbrev@1.0.4", - "_inBundle": false, - "_integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=", - "_location": "/@isaacs/shrinkwrapped-dependency/abbrev", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "abbrev@1.0.4", - "name": "abbrev", - "escapedName": "abbrev", - "rawSpec": "1.0.4", - "saveSpec": null, - "fetchSpec": "1.0.4" - }, - "_requiredBy": [ - "/@isaacs/shrinkwrapped-dependency" - ], - "_resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "_spec": "1.0.4", - "_where": "/Users/isaacs/dev/npm/arborist/test/fixtures/shrinkwrap/node_modules/@isaacs/shrinkwrapped-dependency", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me" - }, - "bugs": { - "url": "https://github.com/isaacs/abbrev-js/issues" - }, - "description": "Like ruby's abbrev module, but in js", - "homepage": "https://github.com/isaacs/abbrev-js#readme", - "license": { - "type": "MIT", - "url": "https://github.com/isaacs/abbrev-js/raw/master/LICENSE" - }, - "main": "./lib/abbrev.js", - "name": "abbrev", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/isaacs/abbrev-js.git" - }, - "scripts": { - "test": "node lib/abbrev.js" - }, - "version": "1.0.4" - }) - } - }, - "npm-shrinkwrap.json": JSON.stringify({ - "name": "shrinkwrapped-dependency", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "abbrev": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=" - } - } - }), - "package.json": JSON.stringify({ - "_from": "@isaacs/shrinkwrapped-dependency@^1.0.0", - "_id": "@isaacs/shrinkwrapped-dependency@1.0.0", - "_inBundle": false, - "_integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "_location": "/@isaacs/shrinkwrapped-dependency", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@isaacs/shrinkwrapped-dependency@^1.0.0", - "name": "@isaacs/shrinkwrapped-dependency", - "escapedName": "@isaacs%2fshrinkwrapped-dependency", - "scope": "@isaacs", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "_shasum": "a22edfd12f2e796c924a36fe6cbf52eb495e93c3", - "_shrinkwrap": { - "name": "shrinkwrapped-dependency", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "abbrev": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=" - } - } - }, - "_spec": "@isaacs/shrinkwrapped-dependency@^1.0.0", - "_where": "/Users/isaacs/dev/npm/arborist/test/fixtures/shrinkwrap", - "author": "", - "bundleDependencies": false, - "dependencies": { - "abbrev": "^1.0.4" - }, - "deprecated": false, - "description": "", - "keywords": [], - "license": "ISC", - "main": "index.js", - "name": "@isaacs/shrinkwrapped-dependency", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "version": "1.0.0" - }) - } - } - }, - "package-lock.json": JSON.stringify({ - "name": "shrinkwrap", - "version": "1.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "shrinkwrap", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@isaacs/shrinkwrapped-dependency": "^1.0.0" - } - }, - "node_modules/@isaacs/shrinkwrapped-dependency": { - "name": "@isaacs/shrinkwrapped-dependency", - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "hasShrinkwrap": true, - "license": "ISC", - "dependencies": { - "abbrev": "^1.0.4" - } - }, - "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev": { - "name": "abbrev", - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=", - "license": "MIT" - } - }, - "dependencies": { - "@isaacs/shrinkwrapped-dependency": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "requires": { - "abbrev": "^1.0.4" - }, - "dependencies": { - "abbrev": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=" - } - } - } - } - }), - "package.json": JSON.stringify({ - "name": "shrinkwrap", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@isaacs/shrinkwrapped-dependency": "^1.0.0" - } - }) -}) - return path -} diff --git a/workspaces/arborist/test/fixtures/reify-cases/tap-with-yarn-lock.js b/workspaces/arborist/test/fixtures/reify-cases/tap-with-yarn-lock.js index 8063de96d5f16..25f15a7aa6640 100644 --- a/workspaces/arborist/test/fixtures/reify-cases/tap-with-yarn-lock.js +++ b/workspaces/arborist/test/fixtures/reify-cases/tap-with-yarn-lock.js @@ -5773,7 +5773,7 @@ module.exports = t => { } ], "scripts": { - "test": "npm run-script lint && npm run-script unit-test", + "test": "npm run lint && npm run unit-test", "lint": "jshint lib/*.js", "unit-test": "mocha --compilers coffee:coffee-script -R spec", "generate-regex": "node tools/generate-identifier-regex.js" diff --git a/workspaces/arborist/test/fixtures/reify-cases/testing-peer-deps-bad-sw.js b/workspaces/arborist/test/fixtures/reify-cases/testing-peer-deps-bad-sw.js deleted file mode 100644 index 2f2039d06642d..0000000000000 --- a/workspaces/arborist/test/fixtures/reify-cases/testing-peer-deps-bad-sw.js +++ /dev/null @@ -1,21 +0,0 @@ -// generated from test/fixtures/testing-peer-deps-bad-sw -module.exports = t => { - const path = t.testdir({ - "package-lock.json": `this isn't a shrinkwrap file - -it isn't even json - -what is it even doing here? -`, - "package.json": JSON.stringify({ - "name": "@isaacs/testing-peer-deps", - "version": "2.0.0", - "description": "depends on b1, which has a peer dep on c1, and d, which has a regular dep on a2, which has a peer dep on b2 which has a peer dep on c2", - "dependencies": { - "@isaacs/testing-peer-deps-b": "1", - "@isaacs/testing-peer-deps-d": "2" - } - }) -}) - return path -} diff --git a/workspaces/arborist/test/fixtures/reify-cases/workspaces-with-overrides.js b/workspaces/arborist/test/fixtures/reify-cases/workspaces-with-overrides.js new file mode 100644 index 0000000000000..b20ba236d87e1 --- /dev/null +++ b/workspaces/arborist/test/fixtures/reify-cases/workspaces-with-overrides.js @@ -0,0 +1,54 @@ +// generated from test/fixtures/workspaces-with-overrides +module.exports = t => { + const path = t.testdir({ + "package-lock.json": JSON.stringify({ + "name": "workspace-with-overrides", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "workspace-with-overrides", + "workspaces": [ + "ws" + ] + }, + "node_modules/a": { + "resolved": "ws", + "link": true + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "license": "MIT" + }, + "ws": { + "name": "a", + "version": "1.0.0", + "dependencies": { + "arg": "4.1.2" + } + } + } + }), + "package.json": JSON.stringify({ + "name": "workspace-with-overrides", + "workspaces": [ + "ws" + ], + "overrides": { + "arg": "4.1.3" + } + }), + "ws": { + "package.json": JSON.stringify({ + "name": "a", + "version": "1.0.0", + "dependencies": { + "arg": "4.1.2" + } + }) + } +}) + return path +} diff --git a/workspaces/arborist/test/fixtures/server.js b/workspaces/arborist/test/fixtures/server.js deleted file mode 100644 index 61962b16c09be..0000000000000 --- a/workspaces/arborist/test/fixtures/server.js +++ /dev/null @@ -1,250 +0,0 @@ -const { join, dirname } = require('node:path') -const { promisify } = require('node:util') -const fs = require('node:fs/promises') -const http = require('node:http') -const https = require('node:https') -const zlib = require('node:zlib') -const mrm = require('minify-registry-metadata') - -const gzip = promisify(zlib.gzip) -const unzip = promisify(zlib.unzip) -const mkdirp = (p) => fs.mkdir(p, { recursive: true }) -const exists = (p) => fs.stat(p).then(() => true).catch(() => false) -const writeJson = (p, d) => fs.writeFile(p, JSON.stringify(d, null, 2) + '\n') - -const PORT = 12345 + (+process.env.TAP_CHILD_ID || 0) -const doProxy = process.env.ARBORIST_TEST_PROXY - -const missing = /\/@isaacs(\/|%2[fF])(this-does-not-exist-at-all|testing-missing-tgz\/-\/)/ -const corgiDoc = 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*' - -let advisoryBulkResponse = null -let failAdvisoryBulk = false -let auditResponse = null -let failAudit = false - -const proxyRegistry = async (req, res) => { - const upstream = await new Promise((resolve) => { - https.get({ - host: 'registry.npmjs.org', - path: req.url, - headers: { - ...req.headers, - accept: '*', - 'accept-encoding': 'identity', - host: 'registry.npmjs.org', - connection: 'close', - 'if-none-match': '', - }, - }).on('response', response => { - const { statusCode, headers } = response - const data = [] - const error = statusCode >= 300 || statusCode < 200 - const contentEncoding = headers['content-encoding'] - const contentType = headers['content-type'] - - console.error('[PROXY] START', `${req.url}: ${statusCode} ${contentType}`) - if (error) { - console.error('[PROXY] UPSTREAM ERROR', statusCode) - } - - res.statusCode = statusCode - res.setHeader('content-encoding', contentEncoding) - res.setHeader('content-type', contentType) - - response.on('end', () => { - console.error('[PROXY] END', req.url) - resolve({ error, data: Buffer.concat(data), contentType }) - }) - response.on('data', c => data.push(c)) - }).end() - }) - - return upstream -} - -const bulkAdvisoriesRoute = async (req, res) => { - if (failAdvisoryBulk) { - res.statusCode = 503 - return res.end('no advisory bulk for you') - } - - const file = advisoryBulkResponse - - if (!file) { - if (auditResponse && !failAudit) { - // simulate what the registry does when quick audits are allowed, - // but advisory bulk requests are not - res.statusCode = 405 - return res.end(JSON.stringify({ - code: 'MethodNotAllowedError', - message: 'POST is not allowed', - })) - } - res.statusCode = 404 - return res.end('not found') - } - - if (doProxy && !(await exists(file))) { - const { error, data } = await proxyRegistry(req, res) - - if (!error) { - await mkdirp(dirname(file)) - const obj = await unzip(data).then(r => JSON.parse(r.toString())) - await writeJson(file, obj) - } - - return res.end(data) - } - - res.setHeader('content-encoding', 'gzip') - const data = await fs.readFile(file).then(r => gzip(r)) - return res.end(data) -} - -const quickAuditRoute = async (req, res) => { - if (failAudit) { - res.statusCode = 503 - return res.end('no audit for you') - } - - const file = auditResponse - - if (!file) { - res.statusCode = 404 - return res.end('not found') - } - - if (doProxy && !(await exists(file))) { - const { error, data } = await proxyRegistry(req, res) - - if (!error) { - await mkdirp(dirname(file)) - const unzipped = await unzip(data).then(r => r.toString()) - const obj = JSON.parse(unzipped) - await writeJson(file, obj) - } - - return res.end(data) - } - - res.setHeader('content-encoding', 'gzip') - const data = await fs.readFile(file).then(r => gzip(r)) - return res.end(data) -} - -const onRequest = async (req, res) => { - res.setHeader('connection', 'close') - - if (req.url === '/-/npm/v1/security/advisories/bulk') { - return await bulkAdvisoriesRoute(req, res) - } - - if (req.url === '/-/npm/v1/security/audits/quick') { - return await quickAuditRoute(req, res) - } - - const f = join(__dirname, 'registry-mocks', 'content', join('/', req.url.replace(/@/g, '').replace(/%2f/gi, '/'))) - const isCorgi = req.headers.accept.includes('application/vnd.npm.install-v1+json') - - let file = f - if (isCorgi && await exists(`${f}.min.json`)) { - file += '.min.json' - } else if (await exists(`${f}.json`)) { - file += '.json' - } else if (await exists(`${f}/index.json`)) { - file += 'index.json' - } - - const { body, error } = await fs.readFile(file) - .then((body) => ({ body })) - .catch((error) => ({ error })) - - if (error) { - // testing things going missing from the registry somehow - if (missing.test(req.url)) { - res.statusCode = 404 - return res.end('{"error": "not found"}') - } - - if (doProxy) { - const { error: proxyError, contentType, data } = await proxyRegistry(req, res) - - if (!proxyError) { - await mkdirp(dirname(f)) - - if (contentType.includes('application/json')) { - const file = `${f}.json` - const obj = JSON.parse(data.toString()) - await Promise.all([ - writeJson(file, obj), - writeJson(file.replace(/\.json$/, '.min.json'), mrm(obj)), - ]) - } else { - await fs.writeFile(f, data) - } - } - - return res.end(data) - } - - res.statusCode = error.code === 'ENOENT' ? 404 : 500 - if (res.method === 'GET') { - console.error(error) - } - res.setHeader('content-type', 'text/plain') - return res.end(error.stack) - } - - res.setHeader('content-length', body.length) - res.setHeader('content-type', /\.min\.json$/.test(file) ? corgiDoc - : /\.json$/.test(file) ? 'application/json' - : 'application/octet-stream') - return res.end(body) -} - -const startServer = async () => { - const server = exports.server = http.createServer(onRequest) - await new Promise(res => server.listen(PORT, res)) -} - -exports.auditResponse = value => { - if (auditResponse && auditResponse !== value) { - throw new Error('setting audit response, but already set\n' + - '(did you forget to call the returned function on teardown?)') - } - auditResponse = value - return () => auditResponse = null -} - -exports.failAudit = () => { - failAudit = true - return () => failAudit = false -} - -exports.advisoryBulkResponse = value => { - if (advisoryBulkResponse && advisoryBulkResponse !== value) { - throw new Error('setting advisory bulk response, but already set\n' + - '(did you forget to call the returned function on teardown?)') - } - advisoryBulkResponse = value - return () => advisoryBulkResponse = null -} - -exports.failAdvisoryBulk = () => { - failAdvisoryBulk = true - return () => failAdvisoryBulk = false -} - -exports.registry = `http://localhost:${PORT}/` - -exports.start = startServer -exports.stop = () => exports.server.close() - -if (require.main === module) { - startServer() - .then(() => console.log(`Mock registry live at:\n${exports.registry}\nPress ^D to close gracefully.`)) - .catch(console.error) - process.openStdin() - process.stdin.on('end', () => exports.stop()) -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock-empty/README.md b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock-empty/README.md deleted file mode 100644 index a0f18c920410a..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock-empty/README.md +++ /dev/null @@ -1 +0,0 @@ -Just a module that depends on a module that ships a shrinkwrap. diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock-empty/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock-empty/package.json deleted file mode 100644 index 9734c113d9ae4..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock-empty/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "shrinkwrap", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@isaacs/shrinkwrapped-dependency": "^1.0.0" - } -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/README.md b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/README.md deleted file mode 100644 index a0f18c920410a..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/README.md +++ /dev/null @@ -1 +0,0 @@ -Just a module that depends on a module that ships a shrinkwrap. diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev/package.json deleted file mode 100644 index 1012219b43d18..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "_args": [ - [ - "abbrev@1.0.4", - "/Users/isaacs/dev/npm/arborist/test/fixtures/shrinkwrap/node_modules/@isaacs/shrinkwrapped-dependency" - ] - ], - "_from": "abbrev@1.0.4", - "_id": "abbrev@1.0.4", - "_inBundle": false, - "_integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=", - "_location": "/@isaacs/shrinkwrapped-dependency/abbrev", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "abbrev@1.0.4", - "name": "abbrev", - "escapedName": "abbrev", - "rawSpec": "1.0.4", - "saveSpec": null, - "fetchSpec": "1.0.4" - }, - "_requiredBy": [ - "/@isaacs/shrinkwrapped-dependency" - ], - "_resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "_spec": "1.0.4", - "_where": "/Users/isaacs/dev/npm/arborist/test/fixtures/shrinkwrap/node_modules/@isaacs/shrinkwrapped-dependency", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me" - }, - "bugs": { - "url": "https://github.com/isaacs/abbrev-js/issues" - }, - "description": "Like ruby's abbrev module, but in js", - "homepage": "https://github.com/isaacs/abbrev-js#readme", - "license": { - "type": "MIT", - "url": "https://github.com/isaacs/abbrev-js/raw/master/LICENSE" - }, - "main": "./lib/abbrev.js", - "name": "abbrev", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/isaacs/abbrev-js.git" - }, - "scripts": { - "test": "node lib/abbrev.js" - }, - "version": "1.0.4" -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency/npm-shrinkwrap.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency/npm-shrinkwrap.json deleted file mode 100644 index ab817a2435262..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency/npm-shrinkwrap.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "shrinkwrapped-dependency", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "abbrev": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=" - } - } -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency/package.json deleted file mode 100644 index 206d12cee2cfa..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/node_modules/@isaacs/shrinkwrapped-dependency/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "_from": "@isaacs/shrinkwrapped-dependency@^1.0.0", - "_id": "@isaacs/shrinkwrapped-dependency@1.0.0", - "_inBundle": false, - "_integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "_location": "/@isaacs/shrinkwrapped-dependency", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@isaacs/shrinkwrapped-dependency@^1.0.0", - "name": "@isaacs/shrinkwrapped-dependency", - "escapedName": "@isaacs%2fshrinkwrapped-dependency", - "scope": "@isaacs", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "_shasum": "a22edfd12f2e796c924a36fe6cbf52eb495e93c3", - "_shrinkwrap": { - "name": "shrinkwrapped-dependency", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "abbrev": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=" - } - } - }, - "_spec": "@isaacs/shrinkwrapped-dependency@^1.0.0", - "_where": "/Users/isaacs/dev/npm/arborist/test/fixtures/shrinkwrap", - "author": "", - "bundleDependencies": false, - "dependencies": { - "abbrev": "^1.0.4" - }, - "deprecated": false, - "description": "", - "keywords": [], - "license": "ISC", - "main": "index.js", - "name": "@isaacs/shrinkwrapped-dependency", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "version": "1.0.0" -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/package.json deleted file mode 100644 index 9734c113d9ae4..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-no-lock/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "shrinkwrap", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@isaacs/shrinkwrapped-dependency": "^1.0.0" - } -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/README.md b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/README.md deleted file mode 100644 index 9125f070e96f7..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/README.md +++ /dev/null @@ -1,17 +0,0 @@ -a package that depends on a shrinkwrapped dependency whose child dependencies -change between versions. used for a reify test, trees should look as below and -not change when updating all packages. - -z@1 depends on a@1 to provide a package with a nested shrinkwrap. - -``` -a@1 -+ -- b@1 -+ -- c@1 -+ -- d@1 - -a@2 -+ -- b@2 -+ -- c@1 -+ -- e@1 -``` diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/a/1/npm-shrinkwrap.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/a/1/npm-shrinkwrap.json deleted file mode 100644 index 37cc417aa20cb..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/a/1/npm-shrinkwrap.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-a", - "version": "1.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "@nlf/shrinkwrapped-dep-updates-a", - "version": "1.0.0", - "dependencies": { - "@nlf/shrinkwrapped-dep-updates-b": "^1.0.0", - "@nlf/shrinkwrapped-dep-updates-c": "^1.0.0", - "@nlf/shrinkwrapped-dep-updates-d": "^1.0.0" - } - }, - "node_modules/@nlf/shrinkwrapped-dep-updates-b": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-1.0.0.tgz", - "integrity": "sha512-O8gmWJxc3W9yjGNGnEwumPQfXDTjIwkixWN8XPKvuEKwg5QldqAJfka5u7NwvM4ILP+1TT2OEMf+cNEYJ3eXUw==" - }, - "node_modules/@nlf/shrinkwrapped-dep-updates-c": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-c/-/shrinkwrapped-dep-updates-c-1.0.0.tgz", - "integrity": "sha512-Ny4NLloQxmjos+llolUBcc9+5FTa+JCh5/CqshFYq6d6s3RykpGuFnqPN/3vO6Uftp3lPtBOGjvlXSJtN4ZDQA==" - }, - "node_modules/@nlf/shrinkwrapped-dep-updates-d": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-d/-/shrinkwrapped-dep-updates-d-1.0.0.tgz", - "integrity": "sha512-VcomTaV8pXizm8uJe//Iu7nDCyYeeIs5hdOzcO2NwmuyhFMlCGUAGb+pHx4f+Kz++sil52Zz817DUqOaVGAz1g==" - } - }, - "dependencies": { - "@nlf/shrinkwrapped-dep-updates-b": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-1.0.0.tgz", - "integrity": "sha512-O8gmWJxc3W9yjGNGnEwumPQfXDTjIwkixWN8XPKvuEKwg5QldqAJfka5u7NwvM4ILP+1TT2OEMf+cNEYJ3eXUw==" - }, - "@nlf/shrinkwrapped-dep-updates-c": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-c/-/shrinkwrapped-dep-updates-c-1.0.0.tgz", - "integrity": "sha512-Ny4NLloQxmjos+llolUBcc9+5FTa+JCh5/CqshFYq6d6s3RykpGuFnqPN/3vO6Uftp3lPtBOGjvlXSJtN4ZDQA==" - }, - "@nlf/shrinkwrapped-dep-updates-d": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-d/-/shrinkwrapped-dep-updates-d-1.0.0.tgz", - "integrity": "sha512-VcomTaV8pXizm8uJe//Iu7nDCyYeeIs5hdOzcO2NwmuyhFMlCGUAGb+pHx4f+Kz++sil52Zz817DUqOaVGAz1g==" - } - } -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/a/1/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/a/1/package.json deleted file mode 100644 index e15a0c215036b..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/a/1/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-a", - "version": "1.0.0", - "description": "a dependency with shrinkwrapped deps that change between versions", - "dependencies": { - "@nlf/shrinkwrapped-dep-updates-b": "^1.0.0", - "@nlf/shrinkwrapped-dep-updates-c": "^1.0.0", - "@nlf/shrinkwrapped-dep-updates-d": "^1.0.0" - } -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/a/2/npm-shrinkwrap.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/a/2/npm-shrinkwrap.json deleted file mode 100644 index d4bd764686298..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/a/2/npm-shrinkwrap.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-a", - "version": "2.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "@nlf/shrinkwrapped-dep-updates-a", - "version": "2.0.0", - "dependencies": { - "@nlf/shrinkwrapped-dep-updates-b": "^2.0.0", - "@nlf/shrinkwrapped-dep-updates-c": "^1.0.0", - "@nlf/shrinkwrapped-dep-updates-e": "^1.0.0" - } - }, - "node_modules/@nlf/shrinkwrapped-dep-updates-b": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-2.0.0.tgz", - "integrity": "sha512-B5arzHMzN1kp67O/tVRR+OtosYDYVdNH7dLKkVR9Ruov+M6a7mrj2bOAJd8HZMQlQ5yjMRy3UXTp2amgh9EhqA==" - }, - "node_modules/@nlf/shrinkwrapped-dep-updates-c": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-c/-/shrinkwrapped-dep-updates-c-1.0.0.tgz", - "integrity": "sha512-Ny4NLloQxmjos+llolUBcc9+5FTa+JCh5/CqshFYq6d6s3RykpGuFnqPN/3vO6Uftp3lPtBOGjvlXSJtN4ZDQA==" - }, - "node_modules/@nlf/shrinkwrapped-dep-updates-e": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-e/-/shrinkwrapped-dep-updates-e-1.0.0.tgz", - "integrity": "sha512-k41VmVMeLH/AgnD7Nx2TIQvt12xd0dKSrWmraYDNZIMxtuuwUjaq1lH8eo8todBU7U5aj94cH4xlLU0g3SgsBA==" - } - }, - "dependencies": { - "@nlf/shrinkwrapped-dep-updates-b": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-b/-/shrinkwrapped-dep-updates-b-2.0.0.tgz", - "integrity": "sha512-B5arzHMzN1kp67O/tVRR+OtosYDYVdNH7dLKkVR9Ruov+M6a7mrj2bOAJd8HZMQlQ5yjMRy3UXTp2amgh9EhqA==" - }, - "@nlf/shrinkwrapped-dep-updates-c": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-c/-/shrinkwrapped-dep-updates-c-1.0.0.tgz", - "integrity": "sha512-Ny4NLloQxmjos+llolUBcc9+5FTa+JCh5/CqshFYq6d6s3RykpGuFnqPN/3vO6Uftp3lPtBOGjvlXSJtN4ZDQA==" - }, - "@nlf/shrinkwrapped-dep-updates-e": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@nlf/shrinkwrapped-dep-updates-e/-/shrinkwrapped-dep-updates-e-1.0.0.tgz", - "integrity": "sha512-k41VmVMeLH/AgnD7Nx2TIQvt12xd0dKSrWmraYDNZIMxtuuwUjaq1lH8eo8todBU7U5aj94cH4xlLU0g3SgsBA==" - } - } -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/a/2/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/a/2/package.json deleted file mode 100644 index 11cf85b3d9134..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/a/2/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-a", - "version": "2.0.0", - "description": "a dependency with shrinkwrapped deps that change between versions", - "dependencies": { - "@nlf/shrinkwrapped-dep-updates-b": "^2.0.0", - "@nlf/shrinkwrapped-dep-updates-c": "^1.0.0", - "@nlf/shrinkwrapped-dep-updates-e": "^1.0.0" - } -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/b/1/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/b/1/package.json deleted file mode 100644 index 14d4765905cb8..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/b/1/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-b", - "version": "1.0.0", - "description": "a dependency that a shrinkwrapped dependency depends on" -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/b/2/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/b/2/package.json deleted file mode 100644 index ae0789254c483..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/b/2/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-b", - "version": "2.0.0", - "description": "a dependency that a shrinkwrapped dependency depends on" -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/c/1/package-lock.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/c/1/package-lock.json deleted file mode 100644 index b160c22020b89..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/c/1/package-lock.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-c", - "version": "1.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "@nlf/shrinkwrapped-dep-updates-c", - "version": "1.0.0" - } - } -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/c/1/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/c/1/package.json deleted file mode 100644 index 2221428631c23..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/c/1/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-c", - "version": "1.0.0", - "description": "a dependency that a shrinkwrapped dependency depends on" -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/d/1/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/d/1/package.json deleted file mode 100644 index 9844e61f72483..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/d/1/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-d", - "version": "1.0.0", - "description": "a dependency that a shrinkwrapped dependency depends on" -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/e/1/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/e/1/package.json deleted file mode 100644 index 753319068e717..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-updates/e/1/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "@nlf/shrinkwrapped-dep-updates-e", - "version": "1.0.0", - "description": "a dependency that a shrinkwrapped dependency depends on" -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock-empty/README.md b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock-empty/README.md deleted file mode 100644 index a0f18c920410a..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock-empty/README.md +++ /dev/null @@ -1 +0,0 @@ -Just a module that depends on a module that ships a shrinkwrap. diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock-empty/package-lock.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock-empty/package-lock.json deleted file mode 100644 index b32817828e437..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock-empty/package-lock.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "shrinkwrap", - "version": "1.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "shrinkwrap", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@isaacs/shrinkwrapped-dependency": "^1.0.0" - } - }, - "node_modules/@isaacs/shrinkwrapped-dependency": { - "name": "@isaacs/shrinkwrapped-dependency", - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "hasShrinkwrap": true, - "license": "ISC", - "dependencies": { - "abbrev": "^1.0.4" - } - }, - "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev": { - "name": "abbrev", - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=", - "license": "MIT" - } - }, - "dependencies": { - "@isaacs/shrinkwrapped-dependency": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "requires": { - "abbrev": "^1.0.4" - }, - "dependencies": { - "abbrev": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=" - } - } - } - } -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock-empty/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock-empty/package.json deleted file mode 100644 index 9734c113d9ae4..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock-empty/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "shrinkwrap", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@isaacs/shrinkwrapped-dependency": "^1.0.0" - } -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/README.md b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/README.md deleted file mode 100644 index a0f18c920410a..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/README.md +++ /dev/null @@ -1 +0,0 @@ -Just a module that depends on a module that ships a shrinkwrap. diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev/package.json deleted file mode 100644 index 1012219b43d18..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "_args": [ - [ - "abbrev@1.0.4", - "/Users/isaacs/dev/npm/arborist/test/fixtures/shrinkwrap/node_modules/@isaacs/shrinkwrapped-dependency" - ] - ], - "_from": "abbrev@1.0.4", - "_id": "abbrev@1.0.4", - "_inBundle": false, - "_integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=", - "_location": "/@isaacs/shrinkwrapped-dependency/abbrev", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "abbrev@1.0.4", - "name": "abbrev", - "escapedName": "abbrev", - "rawSpec": "1.0.4", - "saveSpec": null, - "fetchSpec": "1.0.4" - }, - "_requiredBy": [ - "/@isaacs/shrinkwrapped-dependency" - ], - "_resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "_spec": "1.0.4", - "_where": "/Users/isaacs/dev/npm/arborist/test/fixtures/shrinkwrap/node_modules/@isaacs/shrinkwrapped-dependency", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me" - }, - "bugs": { - "url": "https://github.com/isaacs/abbrev-js/issues" - }, - "description": "Like ruby's abbrev module, but in js", - "homepage": "https://github.com/isaacs/abbrev-js#readme", - "license": { - "type": "MIT", - "url": "https://github.com/isaacs/abbrev-js/raw/master/LICENSE" - }, - "main": "./lib/abbrev.js", - "name": "abbrev", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/isaacs/abbrev-js.git" - }, - "scripts": { - "test": "node lib/abbrev.js" - }, - "version": "1.0.4" -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency/npm-shrinkwrap.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency/npm-shrinkwrap.json deleted file mode 100644 index ab817a2435262..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency/npm-shrinkwrap.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "shrinkwrapped-dependency", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "abbrev": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=" - } - } -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency/package.json deleted file mode 100644 index 206d12cee2cfa..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/node_modules/@isaacs/shrinkwrapped-dependency/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "_from": "@isaacs/shrinkwrapped-dependency@^1.0.0", - "_id": "@isaacs/shrinkwrapped-dependency@1.0.0", - "_inBundle": false, - "_integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "_location": "/@isaacs/shrinkwrapped-dependency", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@isaacs/shrinkwrapped-dependency@^1.0.0", - "name": "@isaacs/shrinkwrapped-dependency", - "escapedName": "@isaacs%2fshrinkwrapped-dependency", - "scope": "@isaacs", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "_shasum": "a22edfd12f2e796c924a36fe6cbf52eb495e93c3", - "_shrinkwrap": { - "name": "shrinkwrapped-dependency", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "abbrev": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=" - } - } - }, - "_spec": "@isaacs/shrinkwrapped-dependency@^1.0.0", - "_where": "/Users/isaacs/dev/npm/arborist/test/fixtures/shrinkwrap", - "author": "", - "bundleDependencies": false, - "dependencies": { - "abbrev": "^1.0.4" - }, - "deprecated": false, - "description": "", - "keywords": [], - "license": "ISC", - "main": "index.js", - "name": "@isaacs/shrinkwrapped-dependency", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "version": "1.0.0" -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/package-lock.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/package-lock.json deleted file mode 100644 index b32817828e437..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/package-lock.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "shrinkwrap", - "version": "1.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "shrinkwrap", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@isaacs/shrinkwrapped-dependency": "^1.0.0" - } - }, - "node_modules/@isaacs/shrinkwrapped-dependency": { - "name": "@isaacs/shrinkwrapped-dependency", - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "hasShrinkwrap": true, - "license": "ISC", - "dependencies": { - "abbrev": "^1.0.4" - } - }, - "node_modules/@isaacs/shrinkwrapped-dependency/node_modules/abbrev": { - "name": "abbrev", - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=", - "license": "MIT" - } - }, - "dependencies": { - "@isaacs/shrinkwrapped-dependency": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@isaacs/shrinkwrapped-dependency/-/shrinkwrapped-dependency-1.0.0.tgz", - "integrity": "sha512-9OAp7wVNnaxbqHi6n+AALGvSmZ/nJPGWKBNUr/RuGpVitaT54KCbwIHPA1sOwowUFaooDggoB8Jtk/aBOWwKoQ==", - "requires": { - "abbrev": "^1.0.4" - }, - "dependencies": { - "abbrev": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz", - "integrity": "sha1-vVWuXkE7oXIu5Mq6H26hBBSlns0=" - } - } - } - } -} diff --git a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/package.json b/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/package.json deleted file mode 100644 index 9734c113d9ae4..0000000000000 --- a/workspaces/arborist/test/fixtures/shrinkwrapped-dep-with-lock/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "shrinkwrap", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@isaacs/shrinkwrapped-dependency": "^1.0.0" - } -} diff --git a/workspaces/arborist/test/fixtures/test-package-with-shrinkwrap/npm-shrinkwrap.json b/workspaces/arborist/test/fixtures/test-package-with-shrinkwrap/package-lock.json similarity index 100% rename from workspaces/arborist/test/fixtures/test-package-with-shrinkwrap/npm-shrinkwrap.json rename to workspaces/arborist/test/fixtures/test-package-with-shrinkwrap/package-lock.json diff --git a/workspaces/arborist/test/fixtures/testing-peer-deps-bad-sw/package-lock.json b/workspaces/arborist/test/fixtures/testing-peer-deps-bad-sw/package-lock.json deleted file mode 100644 index 28861ddd66b2a..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-peer-deps-bad-sw/package-lock.json +++ /dev/null @@ -1,5 +0,0 @@ -this isn't a shrinkwrap file - -it isn't even json - -what is it even doing here? diff --git a/workspaces/arborist/test/fixtures/testing-peer-deps-bad-sw/package.json b/workspaces/arborist/test/fixtures/testing-peer-deps-bad-sw/package.json deleted file mode 100644 index e874021bc6a97..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-peer-deps-bad-sw/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "@isaacs/testing-peer-deps", - "version": "2.0.0", - "description": "depends on b1, which has a peer dep on c1, and d, which has a regular dep on a2, which has a peer dep on b2 which has a peer dep on c2", - "dependencies": { - "@isaacs/testing-peer-deps-b": "1", - "@isaacs/testing-peer-deps-d": "2" - } -} diff --git a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.0/npm-shrinkwrap.json b/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.0/npm-shrinkwrap.json deleted file mode 100644 index 3c01095433627..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.0/npm-shrinkwrap.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.0", - "dependencies": { - "abbrev": "*" - } - }, - "node_modules/abbrev": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.0.tgz", - "integrity": "sha1-0FVMIlZjbi9W58LlrRg/hZQo2B8=" - } - }, - "dependencies": { - "abbrev": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.0.tgz", - "integrity": "sha1-0FVMIlZjbi9W58LlrRg/hZQo2B8=" - } - } -} diff --git a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.0/package.json b/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.0/package.json deleted file mode 100644 index 5bd252f84b33e..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.0/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.0", - "dependencies": { - "abbrev": "*" - }, - "scripts": { - "test": "node test.js" - } -} diff --git a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.0/test.js b/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.0/test.js deleted file mode 100644 index d18ad4a45007f..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.0/test.js +++ /dev/null @@ -1,3 +0,0 @@ -const { version } = require('./package.json') -const { version: abbrev } = require('./node_modules/abbrev/package.json') -require('assert').equal(version, abbrev, 'should have same version') diff --git a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.1/npm-shrinkwrap.json b/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.1/npm-shrinkwrap.json deleted file mode 100644 index 7c57cef8c1eee..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.1/npm-shrinkwrap.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.2", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.1", - "dependencies": { - "abbrev": "*" - } - }, - "node_modules/abbrev": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", - "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" - } - }, - "dependencies": { - "abbrev": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", - "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" - } - } -} diff --git a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.1/package.json b/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.1/package.json deleted file mode 100644 index 0d8ea306cae74..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.1/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.2", - "dependencies": { - "abbrev": "*" - }, - "scripts": { - "test": "node test.js" - } -} diff --git a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.1/test.js b/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.1/test.js deleted file mode 100644 index f8575f8111c36..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.1.1/test.js +++ /dev/null @@ -1,2 +0,0 @@ -const { version: abbrev } = require('./node_modules/abbrev/package.json') -require('assert').equal(abbrev, '1.1.1', 'should have expected version') diff --git a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.0/npm-shrinkwrap.json b/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.0/npm-shrinkwrap.json deleted file mode 100644 index c3e8822252a08..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.0/npm-shrinkwrap.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.2.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.2.0", - "dependencies": { - "abbrev": "*" - } - }, - "node_modules/abbrev": { - "version": "1.1.0" - } - }, - "dependencies": { - "abbrev": { - "version": "1.1.0" - } - } -} diff --git a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.0/package.json b/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.0/package.json deleted file mode 100644 index 4ae9addf0d7fc..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.0/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.2.0", - "dependencies": { - "abbrev": "*" - }, - "scripts": { - "test": "node test.js" - } -} diff --git a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.0/test.js b/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.0/test.js deleted file mode 100644 index 5c6adad2a246d..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.0/test.js +++ /dev/null @@ -1,2 +0,0 @@ -const { version: abbrev } = require('./node_modules/abbrev/package.json') -require('assert').equal(abbrev, '1.1.0', 'should have same version') diff --git a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.1/npm-shrinkwrap.json b/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.1/npm-shrinkwrap.json deleted file mode 100644 index d25bd00c925af..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.1/npm-shrinkwrap.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.2", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.1.1", - "dependencies": { - "abbrev": "*" - } - }, - "node_modules/abbrev": { - "version": "1.1.1" - } - }, - "dependencies": { - "abbrev": { - "version": "1.1.1" - } - } -} diff --git a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.1/package.json b/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.1/package.json deleted file mode 100644 index 11df5022ea827..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.1/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@isaacs/testing-shrinkwrap-abbrev", - "version": "1.2.1", - "dependencies": { - "abbrev": "*" - }, - "scripts": { - "test": "node test.js" - } -} diff --git a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.1/test.js b/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.1/test.js deleted file mode 100644 index f8575f8111c36..0000000000000 --- a/workspaces/arborist/test/fixtures/testing-shrinkwrap-abbrev/1.2.1/test.js +++ /dev/null @@ -1,2 +0,0 @@ -const { version: abbrev } = require('./node_modules/abbrev/package.json') -require('assert').equal(abbrev, '1.1.1', 'should have expected version') diff --git a/workspaces/arborist/test/fixtures/workspaces-with-overrides/package-lock.json b/workspaces/arborist/test/fixtures/workspaces-with-overrides/package-lock.json new file mode 100644 index 0000000000000..a7bbd20bbcb93 --- /dev/null +++ b/workspaces/arborist/test/fixtures/workspaces-with-overrides/package-lock.json @@ -0,0 +1,29 @@ +{ + "name": "workspace-with-overrides", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "workspace-with-overrides", + "workspaces": [ + "ws" + ] + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "license": "MIT" + }, + "node_modules/ws": { + "resolved": "ws", + "link": true + }, + "ws": { + "version": "1.0.0", + "dependencies": { + "arg": "4.1.2" + } + } + } +} diff --git a/workspaces/arborist/test/fixtures/workspaces-with-overrides/package.json b/workspaces/arborist/test/fixtures/workspaces-with-overrides/package.json new file mode 100644 index 0000000000000..9f35f2abd82fc --- /dev/null +++ b/workspaces/arborist/test/fixtures/workspaces-with-overrides/package.json @@ -0,0 +1,9 @@ +{ + "name": "workspace-with-overrides", + "workspaces": [ + "ws" + ], + "overrides": { + "arg": "4.1.3" + } +} diff --git a/workspaces/arborist/test/fixtures/workspaces-with-overrides/ws/package.json b/workspaces/arborist/test/fixtures/workspaces-with-overrides/ws/package.json new file mode 100644 index 0000000000000..b44d12e431fbe --- /dev/null +++ b/workspaces/arborist/test/fixtures/workspaces-with-overrides/ws/package.json @@ -0,0 +1,7 @@ +{ + "name": "ws", + "version": "1.0.0", + "dependencies": { + "arg": "4.1.2" + } +} diff --git a/workspaces/arborist/test/install-scripts.js b/workspaces/arborist/test/install-scripts.js new file mode 100644 index 0000000000000..342e8e7d891d4 --- /dev/null +++ b/workspaces/arborist/test/install-scripts.js @@ -0,0 +1,383 @@ +const t = require('tap') + +const mockGetInstallScripts = (t, isNodeGypResult = () => false) => + t.mock('../lib/install-scripts.js', { + '@npmcli/node-gyp': { + isNodeGypPackage: async (path) => { + if (typeof isNodeGypResult === 'function') { + return isNodeGypResult(path) + } + return !!isNodeGypResult + }, + }, + }) + +const node = ({ + scripts = {}, + gypfile, + resolved = 'https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz', + path = '/fake', +} = {}) => ({ + resolved, + path, + package: { scripts, ...(gypfile !== undefined ? { gypfile } : {}) }, +}) + +t.test('collects preinstall, install, postinstall', async t => { + const getInstallScripts = mockGetInstallScripts(t) + t.strictSame( + await getInstallScripts(node({ scripts: { preinstall: 'pre' } })), + { preinstall: 'pre' } + ) + t.strictSame( + await getInstallScripts(node({ scripts: { install: 'inst' } })), + { install: 'inst' } + ) + t.strictSame( + await getInstallScripts(node({ scripts: { postinstall: 'post' } })), + { postinstall: 'post' } + ) + t.strictSame( + await getInstallScripts(node({ scripts: {} })), + {} + ) +}) + +t.test('ignores unrelated scripts', async t => { + const getInstallScripts = mockGetInstallScripts(t) + t.strictSame( + await getInstallScripts(node({ scripts: { test: 'x', build: 'y' } })), + {} + ) +}) + +t.test('prepare only counts for non-registry sources', async t => { + const getInstallScripts = mockGetInstallScripts(t) + // registry: prepare ignored + t.strictSame( + await getInstallScripts(node({ + scripts: { prepare: 'do' }, + resolved: 'https://registry.npmjs.org/x/-/x-1.0.0.tgz', + })), + {} + ) + // git: prepare counts + t.strictSame( + await getInstallScripts(node({ + scripts: { prepare: 'do' }, + resolved: 'git+ssh://git@github.com/foo/bar.git#abc', + })), + { prepare: 'do' } + ) + // file: prepare counts + t.strictSame( + await getInstallScripts(node({ + scripts: { prepare: 'do' }, + resolved: 'file:../local', + })), + { prepare: 'do' } + ) +}) + +t.test('synthetic node-gyp install detected via binding.gyp', async t => { + const getInstallScripts = mockGetInstallScripts(t, () => true) + t.strictSame( + await getInstallScripts(node()), + { install: 'node-gyp rebuild' } + ) +}) + +t.test('synthetic node-gyp suppressed when gypfile: false', async t => { + const getInstallScripts = mockGetInstallScripts(t, () => true) + t.strictSame( + await getInstallScripts(node({ gypfile: false })), + {} + ) +}) + +t.test('synthetic node-gyp suppressed when explicit install is present', async t => { + const getInstallScripts = mockGetInstallScripts(t, () => true) + t.strictSame( + await getInstallScripts(node({ scripts: { install: 'real-install' } })), + { install: 'real-install' } + ) +}) + +t.test('synthetic node-gyp suppressed when explicit preinstall is present', async t => { + const getInstallScripts = mockGetInstallScripts(t, () => true) + t.strictSame( + await getInstallScripts(node({ scripts: { preinstall: 'real-pre' } })), + { preinstall: 'real-pre' } + ) +}) + +t.test('node-gyp detection error is treated as not-gyp', async t => { + const getInstallScripts = t.mock('../lib/install-scripts.js', { + '@npmcli/node-gyp': { + isNodeGypPackage: async () => { + throw new Error('fs blew up') + }, + }, + }) + t.strictSame(await getInstallScripts(node()), {}) +}) + +t.test('missing resolved treated as registry (prepare ignored)', async t => { + const getInstallScripts = mockGetInstallScripts(t) + // Construct the node directly so the destructuring default in the test + // helper does not substitute a registry URL for the missing resolved + // field. Exercises the fallback path in isRegistrySource. + const missingResolved = { + path: '/fake', + package: { scripts: { prepare: 'do' } }, + } + t.strictSame(await getInstallScripts(missingResolved), {}) +}) + +t.test('prepare counts for non-registry deps even when resolved URL looks registry-like', async t => { + const getInstallScripts = mockGetInstallScripts(t) + // A fork hosted at a URL that happens to follow the npm registry tarball + // shape. Arborist's edge-based check (isRegistryDependency=false) is + // authoritative — prepare must NOT be skipped just because the URL pattern + // matches. + const nonRegistry = { + resolved: 'https://corp.example.com/mirror/sharp/-/sharp-1.0.0.tgz', + path: '/fake', + isRegistryDependency: false, + package: { scripts: { prepare: 'do' } }, + } + t.strictSame(await getInstallScripts(nonRegistry), { prepare: 'do' }) +}) + +t.test('prepare is skipped for registry deps regardless of resolved URL shape', async t => { + const getInstallScripts = mockGetInstallScripts(t) + const registryNode = { + resolved: 'https://internal.corp/private-registry/sharp/-/sharp-1.0.0.tgz', + path: '/fake', + isRegistryDependency: true, + package: { scripts: { prepare: 'do' } }, + } + t.strictSame(await getInstallScripts(registryNode), {}) +}) + +t.test('lockfile-only node with hasInstallScript=true emits a sentinel', async t => { + // Loaded from a lockfile (e.g. `npm ci` virtualTree, or strict mode's + // preflight against the idealTree before reify has fetched manifests): + // the lockfile records `hasInstallScript: true` but does not inline + // the script bodies. Without a sentinel the preflight would miss this + // node entirely and let install scripts run. + const getInstallScripts = mockGetInstallScripts(t) + const lockfileNode = { + resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz', + path: '/fake', + isRegistryDependency: true, + hasInstallScript: true, + package: { name: 'pkg', version: '1.0.0' }, + } + t.strictSame( + await getInstallScripts(lockfileNode), + { install: '(install scripts present)' } + ) +}) + +t.test('sentinel is not emitted when scripts are already enumerated', async t => { + // If `hasInstallScript: true` coexists with a real `scripts` map, we + // surface the real names, and the sentinel must not overwrite them. + const getInstallScripts = mockGetInstallScripts(t) + const node = { + resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz', + path: '/fake', + isRegistryDependency: true, + hasInstallScript: true, + package: { scripts: { postinstall: 'echo hi' } }, + } + t.strictSame(await getInstallScripts(node), { postinstall: 'echo hi' }) +}) + +t.test('sentinel is not emitted when hasInstallScript is absent', async t => { + // Defensive: a lockfile entry without `hasInstallScript` (the common + // case) still returns {} so we don't false-positive every dep. + const getInstallScripts = mockGetInstallScripts(t) + const node = { + resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz', + path: '/fake', + isRegistryDependency: true, + package: { name: 'pkg', version: '1.0.0' }, + } + t.strictSame(await getInstallScripts(node), {}) +}) + +t.test('lockfile-only node hydrates real scripts from package.json on disk', async t => { + // The common lockfile-driven case (`npm ci`, a repeat `npm install`): + // `node.package.scripts` is empty but the package is unpacked on disk. + // We must read the installed package.json and surface the real script + // body instead of the sentinel. + const getInstallScripts = mockGetInstallScripts(t) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'pkg', + version: '1.0.0', + scripts: { postinstall: 'node -e "console.log(1)"' }, + }), + }) + const lockfileNode = { + resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz', + path, + isRegistryDependency: true, + hasInstallScript: true, + package: { name: 'pkg', version: '1.0.0' }, + } + t.strictSame( + await getInstallScripts(lockfileNode), + { postinstall: 'node -e "console.log(1)"' } + ) +}) + +t.test('lockfile-only node hydrates an explicit install script from disk', async t => { + // A native package such as fsevents that ships a prebuilt binary (no + // binding.gyp, so synthetic gyp detection finds nothing) but declares an + // explicit `install: node-gyp rebuild`. The disk read must recover it + // rather than emitting the sentinel. + const getInstallScripts = mockGetInstallScripts(t) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'fsevents', + version: '2.3.3', + scripts: { install: 'node-gyp rebuild' }, + }), + }) + const lockfileNode = { + resolved: 'https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz', + path, + isRegistryDependency: true, + hasInstallScript: true, + package: { name: 'fsevents', version: '2.3.3' }, + } + t.strictSame( + await getInstallScripts(lockfileNode), + { install: 'node-gyp rebuild' } + ) +}) + +t.test('lockfile-only node hydrates a preinstall script from disk', async t => { + // Cover the disk `preinstall` recovery path. + const getInstallScripts = mockGetInstallScripts(t) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'pkg', + version: '1.0.0', + scripts: { preinstall: 'node pre.js' }, + }), + }) + const lockfileNode = { + resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz', + path, + isRegistryDependency: true, + hasInstallScript: true, + package: { name: 'pkg', version: '1.0.0' }, + } + t.strictSame( + await getInstallScripts(lockfileNode), + { preinstall: 'node pre.js' } + ) +}) + +t.test('lockfile-only non-registry node hydrates prepare from disk', async t => { + // A git/file dependency installed from a lockfile: `prepare` runs for + // non-registry sources, so the disk read must recover it. + const getInstallScripts = mockGetInstallScripts(t) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'pkg', + version: '1.0.0', + scripts: { prepare: 'node build.js' }, + }), + }) + const lockfileNode = { + resolved: 'git+ssh://git@github.com/foo/bar.git#abc', + path, + isRegistryDependency: false, + hasInstallScript: true, + package: { name: 'pkg', version: '1.0.0' }, + } + t.strictSame( + await getInstallScripts(lockfileNode), + { prepare: 'node build.js' } + ) +}) + +t.test('hydrated prepare is ignored for registry deps', async t => { + // Hydration reuses the same registry/non-registry boundary as the + // in-memory path: a registry dep whose on-disk package.json only has a + // `prepare` script falls through to the sentinel, since `prepare` never + // runs for registry installs. + const getInstallScripts = mockGetInstallScripts(t) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'pkg', + version: '1.0.0', + scripts: { prepare: 'build' }, + }), + }) + const lockfileNode = { + resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz', + path, + isRegistryDependency: true, + hasInstallScript: true, + package: { name: 'pkg', version: '1.0.0' }, + } + t.strictSame( + await getInstallScripts(lockfileNode), + { install: '(install scripts present)' } + ) +}) + +t.test('falls back to sentinel when on-disk package.json has no install scripts', async t => { + // The lockfile flagged install scripts but the on-disk package.json has + // none we recognise (e.g. only lifecycle scripts like `test`). Keep the + // sentinel so the advisory still surfaces that something was flagged. + const getInstallScripts = mockGetInstallScripts(t) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'pkg', + version: '1.0.0', + scripts: { test: 'tap' }, + }), + }) + const lockfileNode = { + resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz', + path, + isRegistryDependency: true, + hasInstallScript: true, + package: { name: 'pkg', version: '1.0.0' }, + } + t.strictSame( + await getInstallScripts(lockfileNode), + { install: '(install scripts present)' } + ) +}) + +t.test('disk hydration does not mutate node.package', async t => { + // The enumeration helper is read-only: recovering scripts from disk must + // not write them back onto the node (unlike Builder#addToBuildSet, which + // owns the node and hydrates it deliberately). + const getInstallScripts = mockGetInstallScripts(t) + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'pkg', + version: '1.0.0', + scripts: { postinstall: 'echo hi' }, + }), + }) + const pkg = { name: 'pkg', version: '1.0.0' } + const lockfileNode = { + resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz', + path, + isRegistryDependency: true, + hasInstallScript: true, + package: pkg, + } + await getInstallScripts(lockfileNode) + t.strictSame(pkg, { name: 'pkg', version: '1.0.0' }, 'node.package untouched') + t.notOk(pkg.scripts, 'no scripts written back onto node.package') +}) diff --git a/workspaces/arborist/test/inventory.js b/workspaces/arborist/test/inventory.js index 1b087fe70eb35..24c690a6e4511 100644 --- a/workspaces/arborist/test/inventory.js +++ b/workspaces/arborist/test/inventory.js @@ -113,7 +113,7 @@ t.test('basic operations', t => { t.end() }) -t.test('dont allow external nodes to be added to inventory', t => { +t.test('do not allow external nodes to be added to inventory', t => { const i = new Inventory() const root = { location: '', path: 'rootpath' } i.add(root) diff --git a/workspaces/arborist/test/isolated-mode.js b/workspaces/arborist/test/isolated-mode.js index dcc293b82dc77..f80235721fb67 100644 --- a/workspaces/arborist/test/isolated-mode.js +++ b/workspaces/arborist/test/isolated-mode.js @@ -20,7 +20,7 @@ const { getRepo } = require('./fixtures/isolated-nock') /** * The testing framework here is work in progress, in particular it does not have nice ergonomics. - * The syntactic suggar for this framework will be introduced over time as we add more features. + * The syntactic sugar for this framework will be introduced over time as we add more features. * * The framework has two parts: * - Mocking: The tool generates a test repo based on a declarative list of packages. @@ -42,7 +42,8 @@ const rule1 = { apply: (t, dir, resolvedGraph, alreadyAsserted) => { const graph = parseGraph(resolvedGraph) const allPackages = getAllPackages(withRequireChain(graph)) - allPackages.filter(p => p.chain.length !== 0).forEach(p => { + // Workspaces are excluded: linked-strategy workspaces have no self-symlink, so self-referencing requires an `exports` field (matching pnpm). + allPackages.filter(p => p.chain.length !== 0 && !p.workspace).forEach(p => { const resolveChain = [...p.chain, p.name] const key = p.initialDir + ' => ' + resolveChain.join(' => ') if (alreadyAsserted.has(key)) { @@ -309,6 +310,110 @@ tap.test('simple peer dependencies scenarios', async t => { rule7.apply(t, dir, resolved, asserted) }) +tap.test('peer dependencies with legacyPeerDeps', async t => { + /* + * With legacyPeerDeps, peer dep edges are not created on the node. + * The linked strategy should still place peer deps alongside the + * package in the store so require() works from the real path. + * + * root -> phpegjs + * phpegjs -> pegjs (peer dep, no edge with legacyPeerDeps) + * root -> pegjs + */ + + const graph = { + registry: [ + { name: 'phpegjs', version: '1.0.0', peerDependencies: { pegjs: '*', missing: '*' } }, + { name: 'pegjs', version: '2.0.0' }, + { + name: 'adapter', + version: '1.0.0', + dependencies: { pegjs: '*' }, + peerDependencies: { pegjs: '*' }, + }, + ], + root: { + name: 'foo', + version: '1.2.3', + dependencies: { phpegjs: '1.0.0', pegjs: '2.0.0', adapter: '1.0.0' }, + }, + } + + const resolved = { + 'foo@1.2.3 (root)': { + 'phpegjs@1.0.0': { + 'pegjs@2.0.0 (peer)': {}, + }, + 'pegjs@2.0.0': {}, + 'adapter@1.0.0': { + 'pegjs@2.0.0': {}, + }, + }, + } + + const { dir, registry } = await getRepo(graph) + + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache, legacyPeerDeps: true }) + await arborist.reify({ installStrategy: 'linked' }) + + // phpegjs should be able to require its peer dep pegjs + t.ok(setupRequire(dir)('phpegjs', 'pegjs'), + 'phpegjs can require peer dep pegjs with legacyPeerDeps') + + const asserted = new Set() + rule1.apply(t, dir, resolved, asserted) + rule2.apply(t, dir, resolved, asserted) + rule3.apply(t, dir, resolved, asserted) + rule5.apply(t, dir, resolved, asserted) + rule7.apply(t, dir, resolved, asserted) +}) + +tap.test('idempotent install with legacyPeerDeps and workspace peer deps', async t => { + // Regression: when legacyPeerDeps is enabled and a workspace has a peer dependency on another workspace, node.resolve() returns the Link node (not its target). This caused workspaceProxy to be called with the Link, producing store links under node_modules//node_modules/ that race with the workspace symlink at node_modules/, hitting EEXIST on the second install. + // Use many workspaces with cross-peer-deps to increase concurrency and make the race window large enough to trigger reliably. + const workspaces = [] + for (let i = 0; i < 20; i++) { + workspaces.push({ + name: `ws-${i}`, + version: '1.0.0', + dependencies: { abbrev: '1.0.0' }, + peerDependencies: { [`ws-${(i + 1) % 20}`]: '*' }, + }) + } + + const graph = { + registry: [ + { name: 'abbrev', version: '1.0.0' }, + ], + root: { + name: 'myroot', version: '1.0.0', + }, + workspaces, + } + + const { dir, registry } = await getRepo(graph) + + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const opts = { path: dir, registry, packumentCache: new Map(), cache, legacyPeerDeps: true } + + // First install + const arb1 = new Arborist(opts) + await arb1.reify({ installStrategy: 'linked' }) + + // Second install must not throw EEXIST + const arb2 = new Arborist({ ...opts, packumentCache: new Map() }) + await arb2.reify({ installStrategy: 'linked' }) + + // Workspace peer dep symlinks should still be present after second install + for (let i = 0; i < 20; i++) { + const peerTarget = `ws-${(i + 1) % 20}` + const peerLink = path.join(dir, 'packages', `ws-${i}`, 'node_modules', peerTarget) + t.ok(fs.lstatSync(peerLink).isSymbolicLink(), + `ws-${i} peer dep on ${peerTarget} is still a symlink after second install`) + } +}) + tap.test('Lock file is same in hoisted and in isolated mode', async t => { const graph = { registry: [ @@ -334,7 +439,7 @@ tap.test('Lock file is same in hoisted and in isolated mode', async t => { fs.promises.readFile(path.join(isolatedModeDir, 'package-lock.json'), { encoding: 'utf8' }), ]) - t.same(hoistedModeLockFile, isolatedModeLockFile, 'hoited mode and isolated mode produce the same lockfile') + t.same(hoistedModeLockFile, isolatedModeLockFile, 'hoisted mode and isolated mode produce the same lockfile') }) tap.test('Basic workspaces setup', async t => { @@ -363,32 +468,36 @@ tap.test('Basic workspaces setup', async t => { 'isexe@1.0.0': {}, }, }, - 'baz@1.0.0 (workspace)': { - 'bar@1.0.0 (workspace)': { - 'which@2.0.0': { - 'isexe@1.0.0': {}, - }, - }, + }, + 'bar@1.0.0 (workspace)': { + 'which@2.0.0': { + 'isexe@1.0.0': {}, + }, + }, + 'baz@1.0.0 (workspace)': { + 'bar@1.0.0 (workspace)': { 'which@2.0.0': { 'isexe@1.0.0': {}, }, }, + 'which@2.0.0': { + 'isexe@1.0.0': {}, + }, + }, + 'cat@1.0.0 (workspace)': { + 'which@1.0.0': { + 'isexe@1.0.0': {}, + }, + }, + 'fish@1.0.0 (workspace)': { 'cat@1.0.0 (workspace)': { 'which@1.0.0': { 'isexe@1.0.0': {}, }, }, - 'fish@1.0.0 (workspace)': { - 'cat@1.0.0 (workspace)': { - 'which@1.0.0': { - 'isexe@1.0.0': {}, - }, - }, - 'which@1.0.0': { - 'isexe@1.0.0': {}, - }, + 'which@1.0.0': { + 'isexe@1.0.0': {}, }, - 'catfish@1.0.0': {}, }, } @@ -581,240 +690,6 @@ tap.test('Optional deps are installed when possible', async t => { t.ok(fs.existsSync(path.join(dir, 'node_modules', '.bin', 'which'))) }) -tap.test('shrinkwrap', async t => { - const shrinkwrap = JSON.stringify({ - name: 'which', - version: '1.0.0', - lockfileVersion: 2, - requires: true, - packages: { - '': { - name: 'which', - version: '1.0.0', - dependencies: { - isexe: '^1.0.0', - }, - }, - 'node_modules/isexe': { - version: '1.0.0', - resolved: '##REG##/isexe/1.0.0.tar', - }, - }, - dependencies: { - isexe: { - version: '1.0.0', - resolved: '##REG##/isexe/1.0.0.tar', - }, - }, - }) - - // Input of arborist - const graph = { - registry: [ - { name: 'which', version: '1.0.0', dependencies: { isexe: '^1.0.0' }, shrinkwrap, _hasShrinkwrap: true }, - { name: 'isexe', version: '1.1.0' }, - { name: 'isexe', version: '1.0.0' }, - ], - root: { - name: 'foo', version: '1.2.3', dependencies: { which: '1.0.0', isexe: '^1.0.0' }, - }, - } - - // expected output - const resolved = { - 'foo@1.2.3 (root)': { - 'which@1.0.0': { - 'isexe@1.0.0': {}, - }, - 'isexe@1.1.0': {}, - }, - } - - const { dir, registry } = await getRepo(graph) - - // Note that we override this cache to prevent interference from other tests - const cache = fs.mkdtempSync(`${getTempDir()}/test-`) - const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) - await arborist.reify({ installStrategy: 'linked' }) - - const asserted = new Set() - rule1.apply(t, dir, resolved, asserted) - rule2.apply(t, dir, resolved, asserted) - rule3.apply(t, dir, resolved, asserted) - rule4.apply(t, dir, resolved, asserted) - rule5.apply(t, dir, resolved, asserted) - rule6.apply(t, dir, resolved, asserted) - rule7.apply(t, dir, resolved, asserted) -}) - -tap.test('shrinkwrap install dev deps (like hoisting does)', async t => { - const shrinkwrap = JSON.stringify({ - name: 'which', - version: '1.0.0', - lockfileVersion: 2, - requires: true, - packages: { - '': { - name: 'which', - version: '1.0.0', - devDependencies: { - isexe: '^1.0.0', - }, - }, - 'node_modules/isexe': { - version: '1.0.0', - dev: true, - resolved: '##REG##/isexe/1.0.0.tar', - }, - }, - dependencies: { - isexe: { - version: '1.0.0', - dev: true, - resolved: '##REG##/isexe/1.0.0.tar', - }, - }, - }) - - // Input of arborist - const graph = { - registry: [ - { name: 'which', version: '1.0.0', devDependencies: { isexe: '^1.0.0' }, shrinkwrap, _hasShrinkwrap: true }, - { name: 'isexe', version: '1.1.0' }, - { name: 'isexe', version: '1.0.0' }, - ], - root: { - name: 'foo', version: '1.2.3', dependencies: { which: '1.0.0', isexe: '^1.0.0' }, - }, - } - - // expected output - const resolved = { - 'foo@1.2.3 (root)': { - 'which@1.0.0': { - 'isexe@1.0.0': {}, - }, - 'isexe@1.1.0': {}, - }, - } - - const { dir, registry } = await getRepo(graph) - - // Note that we override this cache to prevent interference from other tests - const cache = fs.mkdtempSync(`${getTempDir()}/test-`) - const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) - await arborist.reify({ installStrategy: 'linked' }) - - const asserted = new Set() - rule1.apply(t, dir, resolved, asserted) - rule2.apply(t, dir, resolved, asserted) - rule3.apply(t, dir, resolved, asserted) - rule4.apply(t, dir, resolved, asserted) - rule5.apply(t, dir, resolved, asserted) - rule6.apply(t, dir, resolved, asserted) - rule7.apply(t, dir, resolved, asserted) -}) - -tap.test('shrinkwrap with peer dependencies', async t => { - const shrinkwrap = JSON.stringify({ - name: 'which', - version: '1.0.0', - lockfileVersion: 2, - requires: true, - packages: { - '': { - name: 'which', - version: '1.0.0', - dependencies: { - isexe: '^1.0.0', - }, - devDependencies: { - bar: '1.0.0', - }, - peerDependencies: { - bar: '*', - }, - }, - 'node_modules/bar': { - version: '1.0.0', - resolved: '##REG##/bar/1.0.0.tar', - dev: true, - bin: { - bar: 'bin.js', - }, - }, - 'node_modules/isexe': { - version: '1.0.0', - resolved: '##REG##/isexe/1.0.0.tar', - bin: { - isexe: 'bin.js', - }, - }, - }, - dependencies: { - bar: { - version: '1.0.0', - resolved: '##REG##/bar/1.0.0.tar', - dev: true, - }, - isexe: { - version: '1.0.0', - resolved: '##REG##/isexe/1.0.0.tar', - }, - }, - }) - // expected output - const resolved = { - 'foo@1.0.0 (root)': { - 'which@1.0.0': { - 'isexe@1.0.0': {}, - 'bar@1.0.0': {}, - }, - 'isexe@1.1.0': {}, - 'bar@1.1.0': {}, - }, - } - - // Input of arborist - const graph = { - registry: [ - { - name: 'which', - version: '1.0.0', - dependencies: { isexe: '^1.0.0' }, - peerDependencies: { bar: '*' }, - devDependencies: { bar: '1.0.0' }, - shrinkwrap, - _hasShrinkwrap: true, - }, - { name: 'isexe', version: '1.1.0' }, - { name: 'isexe', version: '1.0.0' }, - { name: 'bar', version: '1.1.0' }, - { name: 'bar', version: '1.0.0' }, - ], - root: { - name: 'foo', - version: '1.0.0', - dependencies: { isexe: '^1.0.0', bar: '^1.0.0', which: '1.0.0' }, - }, - } - - const { dir, registry } = await getRepo(graph) - const cache = fs.mkdtempSync(`${getTempDir()}/test-`) - const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) - await arborist.reify({ installStrategy: 'linked' }) - - // TODO: greate the resolved object - const asserted = new Set() - rule1.apply(t, dir, resolved, asserted) - rule2.apply(t, dir, resolved, asserted) - rule3.apply(t, dir, resolved, asserted) - rule4.apply(t, dir, resolved, asserted) - rule5.apply(t, dir, resolved, asserted) - rule6.apply(t, dir, resolved, asserted) - rule7.apply(t, dir, resolved, asserted) -}) - tap.test('bundled dependencies of external packages', async t => { // Input of arborist const graph = { @@ -973,7 +848,10 @@ tap.test('nested bundled dependencies of workspaces', async t => { const resolved = { 'dog@1.2.3 (root)': { - 'bar@1.0.0 (workspace)': {}, + 'which@2.0.0': {}, + 'isexe@1.0.0': {}, + }, + 'bar@1.0.0 (workspace)': { 'which@2.0.0': {}, 'isexe@1.0.0': {}, }, @@ -991,12 +869,14 @@ tap.test('nested bundled dependencies of workspaces', async t => { rule1.apply(t, dir, resolved, asserted) rule2.apply(t, dir, resolved, asserted) rule3.apply(t, dir, resolved, asserted) - rule4.apply(t, dir, resolved, asserted) + // Workspace link at packages/bar/node_modules/bar and bundled deps (which, isexe) are co-located in the same node_modules/, making them mutually accessible regardless of declared dependencies. + // rule4.apply(t, dir, resolved, asserted) rule5.apply(t, dir, resolved, asserted) // I think that duplicated versions are okay in the case of bundled deps // rule6.apply(t, dir, resolved, asserted) rule7.apply(t, dir, resolved, asserted) + // Bundled deps are hoisted to root node_modules as real directories const isexePath = path.join(dir, 'node_modules', 'isexe') t.equal(isexePath, fs.realpathSync(isexePath)) const whichPath = path.join(dir, 'node_modules', 'which') @@ -1020,24 +900,24 @@ tap.test('nested bundled dependencies of workspaces with conflicting isolated de } // the isexe that is bundled is hoisted - // the 'which' that is bundled is not hoisted due to a conflaict + // the 'which' that is bundled is not hoisted due to a conflict const resolved = { 'dog@1.2.3 (root)': { - 'bar@1.0.0 (workspace)': { - 'which@2.0.0': { - 'isexe@1.0.0': {}, - }, - 'isexe@1.0.0': {}, - }, 'which@3.0.0': { 'isexe@2.0.0': {}, }, }, - } - - const { dir, registry } = await getRepo(graph) - - // Note that we override this cache to prevent interference from other tests + 'bar@1.0.0 (workspace)': { + 'which@2.0.0': { + 'isexe@1.0.0': {}, + }, + 'isexe@1.0.0': {}, + }, + } + + const { dir, registry } = await getRepo(graph) + + // Note that we override this cache to prevent interference from other tests const cache = fs.mkdtempSync(`${getTempDir()}/test-`) const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) @@ -1047,7 +927,8 @@ tap.test('nested bundled dependencies of workspaces with conflicting isolated de rule1.apply(t, dir, resolved, asserted) rule2.apply(t, dir, resolved, asserted) rule3.apply(t, dir, resolved, asserted) - rule4.apply(t, dir, resolved, asserted) + // Workspace link at packages/bar/node_modules/bar and bundled deps (which, isexe) share the same node_modules/, making them mutually accessible regardless of declared dependencies. + // rule4.apply(t, dir, resolved, asserted) rule5.apply(t, dir, resolved, asserted) // I think that duplicated versions are okay in the case of bundled deps // rule6.apply(t, dir, resolved, asserted) @@ -1300,6 +1181,113 @@ tap.test('scoped package', async t => { rule7.apply(t, dir, resolved, asserted) }) +tap.test('scoped workspace packages', async t => { + /* + * Dependency graph: + * + * root -> @scope/package-b (workspace) + * @scope/package-b -> @scope/package-a (workspace) + * root -> @scope/package-a (workspace) + */ + + const graph = { + registry: [ + { name: 'which', version: '1.0.0' }, + ], + root: { + name: 'myproject', version: '1.0.0', dependencies: { '@scope/package-a': '*', '@scope/package-b': '*' }, + }, + workspaces: [ + { name: '@scope/package-a', version: '1.0.0', dependencies: { which: '1.0.0' } }, + { name: '@scope/package-b', version: '1.0.0', dependencies: { '@scope/package-a': '*' } }, + ], + } + + const resolved = { + 'myproject@1.0.0 (root)': { + '@scope/package-a@1.0.0 (workspace)': { + 'which@1.0.0': {}, + }, + '@scope/package-b@1.0.0 (workspace)': { + '@scope/package-a@1.0.0 (workspace)': { + 'which@1.0.0': {}, + }, + }, + }, + } + + const { dir, registry } = await getRepo(graph) + + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arborist.reify({ installStrategy: 'linked' }) + + const asserted = new Set() + rule1.apply(t, dir, resolved, asserted) + rule2.apply(t, dir, resolved, asserted) + rule3.apply(t, dir, resolved, asserted) + rule4.apply(t, dir, resolved, asserted) + rule7.apply(t, dir, resolved, asserted) +}) + +tap.test('aliased packages in workspace', async t => { + /* + * Dependency graph: + * + * root -> prettier (alias for npm:custom-prettier@3.0.3) + * custom-prettier -> isexe + * root -> my-pkg (workspace) + * my-pkg -> prettier (alias for npm:custom-prettier@3.0.3) + */ + + const graph = { + registry: [ + { name: 'custom-prettier', version: '3.0.3', dependencies: { isexe: '1.0.0' } }, + { name: 'isexe', version: '1.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { prettier: 'npm:custom-prettier@3.0.3' }, + }, + workspaces: [ + { name: 'my-pkg', version: '1.0.0', dependencies: { prettier: 'npm:custom-prettier@3.0.3' } }, + ], + } + + const resolved = { + 'myproject@1.0.0 (root)': { + 'prettier@3.0.3': { + 'isexe@1.0.0': {}, + }, + }, + 'my-pkg@1.0.0 (workspace)': { + 'prettier@3.0.3': { + 'isexe@1.0.0': {}, + }, + }, + } + + const { dir, registry } = await getRepo(graph) + + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arborist.reify({ installStrategy: 'linked' }) + + // Verify symlink uses alias name, not real package name + t.ok(setupRequire(dir)('prettier'), 'root can require via alias "prettier"') + t.notOk( + pathExists(path.join(dir, 'node_modules', 'custom-prettier')), + 'no custom-prettier symlink at root node_modules' + ) + + const asserted = new Set() + rule1.apply(t, dir, resolved, asserted) + rule2.apply(t, dir, resolved, asserted) + rule3.apply(t, dir, resolved, asserted) + rule7.apply(t, dir, resolved, asserted) +}) + tap.test('failing optional peer deps are not installed', async t => { // Input of arborist const graph = { @@ -1322,6 +1310,56 @@ tap.test('failing optional peer deps are not installed', async t => { t.notOk(setupRequire(dir)('bar', 'which'), 'Failing optional peer deps should not be installed') }) +tap.test('optional peer declared only in peerDependenciesMeta is materialized when provided', async t => { + // Regression for npm/cli#9460. + // `bar` declares `which` as an optional peer via peerDependenciesMeta only, with no peerDependencies entry, so no edge is created for it. + // The workspace provides `which`, so under the linked strategy `which` should be linked into `bar`'s store node_modules (matching pnpm). + // `which` is not a root dependency, so it is not hoisted to the top-level node_modules where parent-dir lookup would mask the result. + const graph = { + registry: [ + { name: 'which', version: '1.0.0' }, + { name: 'bar', version: '1.0.0', peerDependenciesMeta: { which: { optional: true } } }, + ], + root: { name: 'foo', version: '1.2.3' }, + workspaces: [ + { name: 'app', version: '1.0.0', dependencies: { bar: '*', which: '1.0.0' } }, + ], + } + + const { dir, registry } = await getRepo(graph) + + // Note that we override this cache to prevent interference from other tests + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arborist.reify({ installStrategy: 'linked' }) + + t.ok(setupRequire(path.join(dir, 'packages', 'app'))('bar', 'which'), + 'optional peer provided by the workspace is materialized into bar store node_modules') +}) + +tap.test('optional peer declared only in peerDependenciesMeta is omitted when not provided', async t => { + // Counterpart to the regression above: when nobody provides the optional peer it must stay omitted, preserving "optional" semantics. + const graph = { + registry: [ + { name: 'bar', version: '1.0.0', peerDependenciesMeta: { which: { optional: true } } }, + ], + root: { name: 'foo', version: '1.2.3' }, + workspaces: [ + { name: 'app', version: '1.0.0', dependencies: { bar: '*' } }, + ], + } + + const { dir, registry } = await getRepo(graph) + + // Note that we override this cache to prevent interference from other tests + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arborist.reify({ installStrategy: 'linked' }) + + t.notOk(setupRequire(path.join(dir, 'packages', 'app'))('bar', 'which'), + 'optional peer that nobody provides is not materialized') +}) + // Virtual packages are 2 packages that have the same version but are // duplicated on disk to solve peer-dependency conflict. tap.test('virtual packages', async t => { @@ -1395,16 +1433,102 @@ tap.test('postinstall scripts are run', async t => { // Note that we override this cache to prevent interference from other tests const cache = fs.mkdtempSync(`${getTempDir()}/test-`) - const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache, dangerouslyAllowAllScripts: true }) await arborist.reify({ installStrategy: 'linked' }) const postInstallRanWhich = pathExists(`${setupRequire(dir)('which')}/postInstallRanWhich`) t.ok(postInstallRanWhich) - const postInstallRanBar = pathExists(`${setupRequire(dir)('bar')}/postInstallRanBar`) + const postInstallRanBar = pathExists(`${path.join(dir, 'packages', 'bar')}/postInstallRanBar`) t.ok(postInstallRanBar) }) +tap.test('postinstall scripts run once for store packages', async t => { + // Regression test: store links should not cause scripts to run twice. + // The store entry and its symlink both end up in the build queue, but + // only the store entry should run scripts. + const graph = { + registry: [ + { + name: 'which', + version: '1.0.0', + scripts: { + postinstall: 'node -e "var c=0;try{c=+fs.readFileSync(\'postinstall-count\',\'utf8\')}catch(e){};fs.writeFileSync(\'postinstall-count\',String(c+1))"', + }, + }, + ], + root: { + name: 'foo', version: '1.2.3', dependencies: { which: '1.0.0' }, + }, + } + + const { dir, registry } = await getRepo(graph) + + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache, dangerouslyAllowAllScripts: true }) + await arborist.reify({ installStrategy: 'linked' }) + + const whichDir = setupRequire(dir)('which') + const count = Number(fs.readFileSync(`${whichDir}/postinstall-count`, 'utf8')) + t.equal(count, 1, 'postinstall ran exactly once') +}) + +tap.test('workspace-filtered install with linked strategy', async t => { + // Two workspaces sharing the same dependency must not crash when installing with --workspace + --install-strategy=linked. + const graph = { + registry: [ + { name: 'abbrev', version: '2.0.0' }, + ], + root: { + name: 'myroot', version: '1.0.0', + }, + workspaces: [ + { name: 'ws-a', version: '1.0.0', dependencies: { abbrev: '2.0.0' } }, + { name: 'ws-b', version: '1.0.0', dependencies: { abbrev: '2.0.0' } }, + ], + } + + const { dir, registry } = await getRepo(graph) + + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + + // Full install first + await arborist.reify({ installStrategy: 'linked' }) + + // Verify store entry exists + const storeDir = path.join(dir, 'node_modules', '.store') + const storeEntries = fs.readdirSync(storeDir) + t.ok(storeEntries.some(e => e.startsWith('abbrev@')), 'store has abbrev entry after full install') + + // Workspace-filtered install must not crash + const arborist2 = new Arborist({ + path: dir, + registry, + packumentCache: new Map(), + cache, + workspaces: ['ws-a'], + }) + await arborist2.reify({ + installStrategy: 'linked', + workspaces: ['ws-a'], + }) + + // Verify workspace filtering was actually applied (not silently skipped) + t.ok(arborist2.diff.filterSet.size > 0, 'workspace filter was applied to diff') + + // Store entries still intact + const storeEntries2 = fs.readdirSync(storeDir) + t.ok(storeEntries2.some(e => e.startsWith('abbrev@')), 'store entries preserved after ws install') + + // Workspace symlinks preserved + const wsALink = fs.readlinkSync(path.join(dir, 'packages', 'ws-a', 'node_modules', 'abbrev')) + t.ok(wsALink.includes('.store'), 'workspace a abbrev symlink points to store') + + const wsBLink = fs.readlinkSync(path.join(dir, 'packages', 'ws-b', 'node_modules', 'abbrev')) + t.ok(wsBLink.includes('.store'), 'workspace b abbrev symlink preserved') +}) + tap.test('bins are installed', async t => { // Input of arborist const graph = { @@ -1434,93 +1558,987 @@ tap.test('bins are installed', async t => { const binFromRootToWhich = pathExists(`${dir}/node_modules/.bin/which`) t.ok(binFromRootToWhich) - const binFromRootToBar = pathExists(`${dir}/node_modules/.bin/bar`) - t.ok(binFromRootToBar) - - const binFromBarToWhich = pathExists(`${setupRequire(dir)('bar')}/node_modules/.bin/which`) + // bar is not a root dep, so its bin should be in the workspace's own node_modules + const binFromBarToWhich = pathExists(`${path.join(dir, 'packages', 'bar')}/node_modules/.bin/which`) t.ok(binFromBarToWhich) }) -function setupRequire (cwd) { - return function requireChain (...chain) { - return chain.reduce((path, name) => { - if (path === undefined) { - return undefined - } - return resolvePackage(name, path) - }, cwd) +tap.test('file: dependency with linked strategy', async t => { + /* + * Regression test for https://github.com/npm/cli/issues/7549 + * + * A relative file: dependency (file:./project2) was incorrectly resolved as file:../project2, causing ENOENT errors because the path was resolved one level above the project root. + */ + const graph = { + registry: [], + root: { + name: 'project1', + version: '1.0.0', + dependencies: { project2: 'file:./project2' }, + }, } -} -function pathExists (path) { - try { - fs.statSync(path) - return true - } catch (_) { - return false - } -} + const { dir, registry } = await getRepo(graph) -/** - * We reimplement a lightweight version of require.resolve because the - * one that is implemented in nodejs memoizes the resolution which - * asserts interfering with each others - **/ -function resolvePackage (name, from) { - try { - const loc = `${from}/node_modules/${name}` - fs.statSync(loc) - return fs.realpathSync(loc) - } catch (_) { - const next = path.dirname(from) - if (next === from) { - return undefined - } else { - return resolvePackage(name, next) - } - } -} + // Create the local file: dependency on disk + const depDir = path.join(dir, 'project2') + fs.mkdirSync(depDir, { recursive: true }) + fs.writeFileSync(path.join(depDir, 'package.json'), JSON.stringify({ + name: 'project2', + version: '1.0.0', + })) + fs.writeFileSync(path.join(depDir, 'index.js'), "module.exports = 'project2'") -function getAllPackages (resolvedGraph) { - return [...getAllPackagesRecursive(resolvedGraph.root), - ...(resolvedGraph.workspaces?.map(w => getAllPackagesRecursive(w)) || []).reduce((a, n) => ([...a, ...n]), [])] -} + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arborist.reify({ installStrategy: 'linked' }) -function getAllPackagesRecursive (resolvedGraph) { - return [ - resolvedGraph, - ...(resolvedGraph.dependencies - ?.filter(d => !isLoopToken(d)) - .map(d => getAllPackagesRecursive(d)) || []) - .reduce((a, n) => ([...a, ...n]), []), - ] -} + // The file dep should be symlinked in node_modules + const linkPath = path.join(dir, 'node_modules', 'project2') + const stat = fs.lstatSync(linkPath) + t.ok(stat.isSymbolicLink(), 'project2 is a symlink in node_modules') -function withRequireChain (resolvedGraph) { - return { + // The symlink should resolve to the actual local directory + const realpath = fs.realpathSync(linkPath) + t.equal(realpath, depDir, 'symlink points to the correct local directory') + + // The package should be requireable + t.ok(setupRequire(dir)('project2'), 'project2 can be required from root') +}) + +tap.test('npm link (external file: dep) with linked strategy', async t => { + // Regression test: `npm link` creates a file: dependency pointing outside the project root. + // The linked strategy should symlink it directly instead of trying to extract it into .store/. + const graph = { + registry: [ + { name: 'abbrev', version: '2.0.0' }, + ], root: { - ...resolvedGraph.root, - chain: [], - initialDir: '.', - dependencies: resolvedGraph.root.dependencies?.map(d => - withRequireChainRecursive(d, [], '.')), + name: 'my-app', + version: '1.0.0', + dependencies: { abbrev: '2.0.0' }, }, - workspaces: resolvedGraph.workspaces?.map(w => { - const initialDir = `packages/${w.name}` - return { - ...w, - chain: [], - initialDir, - dependencies: w.dependencies?.map(d => withRequireChainRecursive(d, [], initialDir)), - } - }), } -} -function withRequireChainRecursive (resolvedGraph, chain, initialDir) { - if (isLoopToken(resolvedGraph)) { - return resolvedGraph - } + const { dir, registry } = await getRepo(graph) + + // Create an external package OUTSIDE the project root (simulates npm link target) + const externalPkgDir = path.join(path.dirname(dir), 'external-pkg') + fs.mkdirSync(externalPkgDir, { recursive: true }) + fs.writeFileSync(path.join(externalPkgDir, 'package.json'), JSON.stringify({ + name: 'external-pkg', + version: '1.0.0', + })) + fs.writeFileSync(path.join(externalPkgDir, 'index.js'), "module.exports = 'external'") + + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + // First install without the linked package + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + // Now simulate `npm link external-pkg` by adding a file: dep and reifying + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked', add: [`file:${externalPkgDir}`] }) + + // The external package should be symlinked in node_modules + const linkPath = path.join(dir, 'node_modules', 'external-pkg') + const stat = fs.lstatSync(linkPath) + t.ok(stat.isSymbolicLink(), 'external-pkg is a symlink in node_modules') + + // The symlink should resolve to the actual external directory + const realpath = fs.realpathSync(linkPath) + t.equal(realpath, externalPkgDir, 'symlink points to the correct external directory') + + // The existing store packages should still be intact + const storePath = path.join(dir, 'node_modules', '.store') + const storeEntries = fs.readdirSync(storePath) + t.ok(storeEntries.some(e => e.startsWith('abbrev@')), 'abbrev is still in the store') + t.notOk(storeEntries.some(e => e.startsWith('external-pkg@')), 'external-pkg is NOT in the store') +}) + +tap.test('workspace file: dependency on a non-workspace local package with linked strategy', async t => { + // Regression test for https://github.com/npm/cli/issues/9589 + // A workspace declaring a file: dep on a local package that is NOT itself a workspace was silently skipped: no symlink, no error. + const graph = { + registry: [], + root: { + name: 'mono', + version: '1.0.0', + }, + workspaces: [ + { name: 'ws-a', version: '1.0.0', dependencies: { 'local-dep': 'file:../../local-dep' } }, + ], + } + + const { dir, registry } = await getRepo(graph) + + // Create the non-workspace local package on disk, outside the workspaces globs + const depDir = path.join(dir, 'local-dep') + fs.mkdirSync(depDir, { recursive: true }) + fs.writeFileSync(path.join(depDir, 'package.json'), JSON.stringify({ + name: 'local-dep', + version: '1.0.0', + })) + fs.writeFileSync(path.join(depDir, 'index.js'), "module.exports = 'local-dep'") + + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arborist.reify({ installStrategy: 'linked' }) + + // The file dep should be symlinked into the workspace's node_modules + const linkPath = path.join(dir, 'packages', 'ws-a', 'node_modules', 'local-dep') + const stat = fs.lstatSync(linkPath) + t.ok(stat.isSymbolicLink(), 'local-dep is a symlink in the workspace node_modules') + + // The symlink should resolve to the actual local directory + t.equal(fs.realpathSync(linkPath), fs.realpathSync(depDir), 'symlink points to the correct local directory') + + // It must be symlinked directly, not extracted into the store + const storePath = path.join(dir, 'node_modules', '.store') + if (fs.existsSync(storePath)) { + t.notOk(fs.readdirSync(storePath).some(e => e.startsWith('local-dep@')), 'local-dep is NOT in the store') + } + + // The package should be requireable from inside the workspace + t.ok(setupRequire(path.join(dir, 'packages', 'ws-a'))('local-dep'), 'local-dep can be required from the workspace') +}) + +tap.test('workspace file: dependency on a package outside the repo root with linked strategy', async t => { + // Regression test for the out-of-repo variant of https://github.com/npm/cli/issues/9589 (the real `npm --workspace link ` case, https://github.com/npm/cli/issues/9115). + // A workspace file: dep whose target resolves OUTSIDE the repo root was silently skipped. + // The target is not in idealTree.fsChildren, so the fix must detect it from the file: link edge. + const graph = { + registry: [], + root: { + name: 'mono', + version: '1.0.0', + }, + workspaces: [ + { name: 'ws-a', version: '1.0.0', dependencies: { 'ext-pkg': 'file:../../../ext-pkg' } }, + ], + } + + const { dir, registry } = await getRepo(graph) + + // Create the external package OUTSIDE the repo root + const extDir = path.join(path.dirname(dir), 'ext-pkg') + fs.mkdirSync(extDir, { recursive: true }) + fs.writeFileSync(path.join(extDir, 'package.json'), JSON.stringify({ + name: 'ext-pkg', + version: '1.0.0', + })) + fs.writeFileSync(path.join(extDir, 'index.js'), "module.exports = 'ext-pkg'") + + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arborist.reify({ installStrategy: 'linked' }) + + // The file dep should be symlinked into the workspace's node_modules + const linkPath = path.join(dir, 'packages', 'ws-a', 'node_modules', 'ext-pkg') + const stat = fs.lstatSync(linkPath) + t.ok(stat.isSymbolicLink(), 'ext-pkg is a symlink in the workspace node_modules') + + // The symlink should resolve to the actual external directory + t.equal(fs.realpathSync(linkPath), fs.realpathSync(extDir), 'symlink points to the correct external directory') + + // It must be symlinked directly, not extracted into the store + const storePath = path.join(dir, 'node_modules', '.store') + if (fs.existsSync(storePath)) { + t.notOk(fs.readdirSync(storePath).some(e => e.startsWith('ext-pkg@')), 'ext-pkg is NOT in the store') + } + + // The package should be requireable from inside the workspace + t.ok(setupRequire(path.join(dir, 'packages', 'ws-a'))('ext-pkg'), 'ext-pkg can be required from the workspace') +}) + +tap.test('subsequent linked install is a no-op', async t => { + const graph = { + registry: [ + { name: 'which', version: '1.0.0', bin: './bin.js', dependencies: { isexe: '^1.0.0' } }, + { name: 'isexe', version: '1.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { which: '1.0.0' }, + }, + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + // First install + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + // Verify packages are installed + t.ok(fs.lstatSync(path.join(dir, 'node_modules', 'which')).isSymbolicLink(), + 'which is a symlink after first install') + + // Second install — should detect everything is up-to-date + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + // Verify the diff has zero actionable leaves + const leaves = arb2.diff?.leaves || [] + const actions = leaves.filter(l => l.action) + t.equal(actions.length, 0, 'second install should have no diff actions') + + // Verify unchanged nodes were detected + t.ok(arb2.diff.unchanged.length > 0, 'second install should have unchanged nodes') + + // Verify packages are still correctly installed + t.ok(fs.lstatSync(path.join(dir, 'node_modules', 'which')).isSymbolicLink(), + 'which is still a symlink after second install') + t.ok(setupRequire(dir)('which'), 'which is requireable after second install') +}) + +tap.test('workspace links are not affected by store resolved fix', async t => { + const graph = { + registry: [ + { name: 'abbrev', version: '1.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { abbrev: '1.0.0' }, + }, + workspaces: [ + { name: 'mypkg', version: '1.0.0', dependencies: { abbrev: '1.0.0' } }, + ], + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + // First install + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + // Second install + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + // Verify the workspace's own deps still resolve from inside the workspace after the second install + t.ok(setupRequire(path.join(dir, 'packages', 'mypkg'))('abbrev'), 'workspace dep is requireable from inside workspace after second install') + t.ok(setupRequire(dir)('abbrev'), 'registry dep is requireable after second install') + + // Verify the diff has unchanged nodes (store entries are correctly matched) + t.ok(arb2.diff.unchanged.length > 0, 'second install should have unchanged nodes') +}) + +tap.test('idempotent install with cross-workspace deps (diamond pattern)', async t => { + // Regression: when workspace-x depends on workspace-y (and both share a registry dep), the second install would report "changed N packages" because (1) workspace link resolved values didn't match between ideal and actual trees, and (2) actual fsChildren overwrote synthetic store entries in the diff proxy. + const graph = { + registry: [ + { name: 'abbrev', version: '2.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { 'workspace-x': '*', 'workspace-y': '*' }, + }, + workspaces: [ + { name: 'workspace-x', version: '1.0.0', dependencies: { abbrev: '2.0.0', 'workspace-y': '*' } }, + { name: 'workspace-y', version: '1.0.0', dependencies: { abbrev: '2.0.0' } }, + ], + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + // First install + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + // Second install — should detect everything is up-to-date + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + const leaves = arb2.diff?.leaves || [] + const actions = leaves.filter(l => l.action) + t.equal(actions.length, 0, 'second install should have no diff actions') + t.ok(arb2.diff.unchanged.length > 0, 'second install should have unchanged nodes') + + // Verify packages are still correctly installed (abbrev is a workspace dep, not root) + t.ok(setupRequire(path.join(dir, 'packages', 'workspace-y'))('abbrev'), + 'abbrev is requireable from workspace after second install') +}) + +tap.test('orphaned store entries are cleaned up on dependency update', async t => { + const graph = { + registry: [ + { name: 'which', version: '1.0.0', dependencies: { isexe: '^1.0.0' } }, + { name: 'which', version: '2.0.0', dependencies: { isexe: '^1.0.0' } }, + { name: 'isexe', version: '1.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { which: '1.0.0' }, + }, + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const storeDir = path.join(dir, 'node_modules', '.store') + + // First install — which@1.0.0 + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + const entriesAfterV1 = fs.readdirSync(storeDir) + t.ok(entriesAfterV1.some(e => e.startsWith('which@1.0.0-')), + 'store has which@1.0.0 entry after first install') + + // Update package.json to depend on which@2.0.0 + const pkgPath = path.join(dir, 'package.json') + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) + pkg.dependencies.which = '2.0.0' + fs.writeFileSync(pkgPath, JSON.stringify(pkg)) + + // Second install — which@2.0.0 + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + const entriesAfterV2 = fs.readdirSync(storeDir) + t.ok(entriesAfterV2.some(e => e.startsWith('which@2.0.0-')), + 'store has which@2.0.0 entry after update') + t.notOk(entriesAfterV2.some(e => e.startsWith('which@1.0.0-')), + 'old which@1.0.0 store entry is removed after update') +}) + +tap.test('orphaned scoped store entries are cleaned up on dependency update', async t => { + // https://github.com/npm/cli/issues/9440 — a scoped store key spans two path segments (.store/@scope/pkg@version-hash), so the single-segment orphan cleanup never swept the stale entry. + const graph = { + registry: [ + { name: '@scope/which', version: '1.0.0', dependencies: { isexe: '^1.0.0' } }, + { name: '@scope/which', version: '2.0.0', dependencies: { isexe: '^1.0.0' } }, + { name: 'isexe', version: '1.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { '@scope/which': '1.0.0' }, + }, + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const storeDir = path.join(dir, 'node_modules', '.store') + const scopeDir = path.join(storeDir, '@scope') + + // First install — @scope/which@1.0.0 + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + const entriesAfterV1 = fs.readdirSync(scopeDir) + t.ok(entriesAfterV1.some(e => e.startsWith('which@1.0.0-')), + 'store has @scope/which@1.0.0 entry after first install') + + // Update package.json to depend on @scope/which@2.0.0 + const pkgPath = path.join(dir, 'package.json') + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) + pkg.dependencies['@scope/which'] = '2.0.0' + fs.writeFileSync(pkgPath, JSON.stringify(pkg)) + + // Second install — @scope/which@2.0.0 + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + const entriesAfterV2 = fs.readdirSync(scopeDir) + t.ok(entriesAfterV2.some(e => e.startsWith('which@2.0.0-')), + 'store has @scope/which@2.0.0 entry after update') + t.notOk(entriesAfterV2.some(e => e.startsWith('which@1.0.0-')), + 'old @scope/which@1.0.0 store entry is removed after update') +}) + +tap.test('orphaned scoped store entries leave no empty scope directory when last dep is removed', async t => { + // https://github.com/npm/cli/issues/9440 — when the last package under a scope is orphaned, the now-empty @scope directory should also be pruned. + const graph = { + registry: [ + { name: '@scope/which', version: '1.0.0', dependencies: { isexe: '^1.0.0' } }, + { name: 'isexe', version: '1.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { '@scope/which': '1.0.0' }, + }, + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const storeDir = path.join(dir, 'node_modules', '.store') + + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + t.ok(fs.existsSync(path.join(storeDir, '@scope')), 'store has @scope directory after install') + + // Remove the dependency + const pkgPath = path.join(dir, 'package.json') + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) + delete pkg.dependencies + fs.writeFileSync(pkgPath, JSON.stringify(pkg)) + + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + t.notOk(fs.existsSync(path.join(storeDir, '@scope')), + 'empty @scope directory is pruned after the last scoped dep is removed') +}) + +tap.test('orphaned store entries are cleaned up on dependency removal', async t => { + const graph = { + registry: [ + { name: 'which', version: '1.0.0', dependencies: { isexe: '^1.0.0' } }, + { name: 'isexe', version: '1.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { which: '1.0.0' }, + }, + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const storeDir = path.join(dir, 'node_modules', '.store') + + // First install + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + t.ok(fs.readdirSync(storeDir).length > 0, 'store has entries after install') + + // Remove the dependency + const pkgPath = path.join(dir, 'package.json') + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) + delete pkg.dependencies + fs.writeFileSync(pkgPath, JSON.stringify(pkg)) + + // Reinstall + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + const entriesAfterRemoval = fs.readdirSync(storeDir) + t.equal(entriesAfterRemoval.length, 0, + 'all store entries are removed when dependencies are removed') + + // https://github.com/npm/cli/issues/9308 — the top-level node_modules symlink for the removed dep was left behind, dangling into the just-cleaned store. + t.notOk(fs.existsSync(path.join(dir, 'node_modules', 'which')), + 'top-level symlink for removed dependency is also cleaned up') +}) + +tap.test('orphaned link inside workspace node_modules is cleaned up on dependency removal', async t => { + const graph = { + registry: [ + { name: 'abbrev', version: '4.0.0' }, + ], + root: { + name: 'root', + version: '1.0.0', + }, + workspaces: [ + { name: 'a', version: '1.0.0', dependencies: { abbrev: '^4.0.0' } }, + ], + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + const wsLink = path.join(dir, 'packages', 'a', 'node_modules', 'abbrev') + t.ok(fs.existsSync(wsLink), 'abbrev is linked into workspace node_modules') + + // Drop abbrev from the workspace package.json + const wsPkgPath = path.join(dir, 'packages', 'a', 'package.json') + const wsPkg = JSON.parse(fs.readFileSync(wsPkgPath, 'utf8')) + delete wsPkg.dependencies + fs.writeFileSync(wsPkgPath, JSON.stringify(wsPkg)) + + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + t.notOk(fs.existsSync(wsLink), 'abbrev symlink target no longer resolves') + t.notOk(fs.lstatSync(wsLink, { throwIfNoEntry: false }), + 'abbrev symlink itself is removed from workspace node_modules') +}) + +tap.test('orphaned link in declared-workspace node_modules is cleaned up when last dep is removed', async t => { + // Reproduces the case where the workspace is also a root dependency, so its self-link sits at the ROOT node_modules and the workspace's own node_modules has no surviving links after removing its only dep. + // Without explicitly seeding each workspace's node_modules into the sweep map, that directory would never be visited and the orphan symlink would remain. + const graph = { + registry: [ + { name: 'abbrev', version: '4.0.0' }, + ], + root: { + name: 'root', + version: '1.0.0', + dependencies: { a: '*' }, + }, + workspaces: [ + { name: 'a', version: '1.0.0', dependencies: { abbrev: '^4.0.0' } }, + ], + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + const wsLink = path.join(dir, 'packages', 'a', 'node_modules', 'abbrev') + t.ok(fs.lstatSync(wsLink, { throwIfNoEntry: false }), 'abbrev is linked into workspace node_modules') + + const wsPkgPath = path.join(dir, 'packages', 'a', 'package.json') + const wsPkg = JSON.parse(fs.readFileSync(wsPkgPath, 'utf8')) + delete wsPkg.dependencies + fs.writeFileSync(wsPkgPath, JSON.stringify(wsPkg)) + + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + t.notOk(fs.lstatSync(wsLink, { throwIfNoEntry: false }), + 'abbrev symlink is removed even though the workspace itself is the only declared root dep') +}) + +tap.test('orphan sweep is skipped on dryRun and packageLockOnly linked installs', async t => { + // The sweep mutates node_modules; dry-run and package-lock-only installs must not touch the filesystem. + const graph = { + registry: [ + { name: 'abbrev', version: '4.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { abbrev: '^4.0.0' }, + }, + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + const linkPath = path.join(dir, 'node_modules', 'abbrev') + t.ok(fs.lstatSync(linkPath, { throwIfNoEntry: false }), 'abbrev link present after first install') + + // Drop the dep, then run dryRun and packageLockOnly — neither should remove the orphan + const pkgPath = path.join(dir, 'package.json') + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) + delete pkg.dependencies + fs.writeFileSync(pkgPath, JSON.stringify(pkg)) + + const arbDry = new Arborist({ path: dir, registry, packumentCache: new Map(), cache, dryRun: true }) + await arbDry.reify({ installStrategy: 'linked', dryRun: true }) + t.ok(fs.lstatSync(linkPath, { throwIfNoEntry: false }), + 'dryRun does not remove orphan symlink') + + const arbLockOnly = new Arborist({ path: dir, registry, packumentCache: new Map(), cache, packageLockOnly: true }) + await arbLockOnly.reify({ installStrategy: 'linked', packageLockOnly: true }) + t.ok(fs.lstatSync(linkPath, { throwIfNoEntry: false }), + 'packageLockOnly does not remove orphan symlink') + + // A real install does perform the cleanup + const arbReal = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arbReal.reify({ installStrategy: 'linked' }) + t.notOk(fs.lstatSync(linkPath, { throwIfNoEntry: false }), + 'real install cleans up the orphan symlink') +}) + +tap.test('orphan sweep is scoped to in-filter workspaces during workspace-filtered linked install', async t => { + // Filtered installs should clean up dependencies removed from the targeted workspace, but leave out-of-scope workspaces alone. + // ws-a is the in-filter workspace: it keeps one dep (which) and drops one (abbrev) so both the surviving-link and orphan-sweep paths are exercised inside an in-scope workspace. + // ws-c is also in the filter but starts with one dep (abbrev) and drops it entirely, exercising the case where the in-filter workspace's node_modules dir is not populated by any surviving links. + // ws-b is out of filter and gets a stale link planted to verify it is preserved. + const graph = { + registry: [ + { name: 'abbrev', version: '4.0.0' }, + { name: 'which', version: '4.0.0' }, + ], + root: { + name: 'myroot', + version: '1.0.0', + // ws-c is declared as a root dep so its self-link lives at root node_modules — that means ws-c's own node_modules has no self-link, and dropping its only dep leaves the dir empty. + dependencies: { 'ws-c': '*' }, + }, + workspaces: [ + { name: 'ws-a', version: '1.0.0', dependencies: { abbrev: '4.0.0', which: '4.0.0' } }, + { name: 'ws-b', version: '1.0.0', dependencies: { abbrev: '4.0.0' } }, + { name: 'ws-c', version: '1.0.0', dependencies: { abbrev: '4.0.0' } }, + ], + } + + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + // Plant a stale orphan link inside ws-b (out-of-filter): the sweep must NOT touch it. + const stalePath = path.join(dir, 'packages', 'ws-b', 'node_modules', 'stale-pkg') + fs.symlinkSync('../../../node_modules/.store/nonexistent/node_modules/stale-pkg', stalePath) + + // Drop abbrev from ws-a's package.json so that ws-a/node_modules/abbrev becomes orphan; which stays as a surviving link. + const wsAPkgPath = path.join(dir, 'packages', 'ws-a', 'package.json') + const wsAPkg = JSON.parse(fs.readFileSync(wsAPkgPath, 'utf8')) + wsAPkg.dependencies = { which: '4.0.0' } + fs.writeFileSync(wsAPkgPath, JSON.stringify(wsAPkg)) + + // Drop all deps from ws-c so its node_modules has no surviving links — exercises the in-filter empty-dir seeding path. + const wsCPkgPath = path.join(dir, 'packages', 'ws-c', 'package.json') + const wsCPkg = JSON.parse(fs.readFileSync(wsCPkgPath, 'utf8')) + delete wsCPkg.dependencies + fs.writeFileSync(wsCPkgPath, JSON.stringify(wsCPkg)) + + const arb2 = new Arborist({ + path: dir, + registry, + packumentCache: new Map(), + cache, + workspaces: ['ws-a', 'ws-c'], + }) + await arb2.reify({ + installStrategy: 'linked', + workspaces: ['ws-a', 'ws-c'], + }) + + t.ok(arb2.diff.filterSet.size > 0, 'filterSet is populated for filtered install') + t.notOk(fs.lstatSync(path.join(dir, 'packages', 'ws-a', 'node_modules', 'abbrev'), { throwIfNoEntry: false }), + 'orphan link in in-filter workspace with surviving deps is removed') + t.ok(fs.lstatSync(path.join(dir, 'packages', 'ws-a', 'node_modules', 'which'), { throwIfNoEntry: false }), + 'surviving link in in-filter workspace is preserved') + t.notOk(fs.lstatSync(path.join(dir, 'packages', 'ws-c', 'node_modules', 'abbrev'), { throwIfNoEntry: false }), + 'orphan link in in-filter workspace with no surviving deps is removed') + t.ok(fs.lstatSync(stalePath, { throwIfNoEntry: false }), + 'stale link in out-of-filter workspace is preserved') +}) + +tap.test('orphan sweep includes root node_modules when --include-workspace-root is set', async t => { + // With --include-workspace-root, the filter scope pulls root deps in too, so dropped root deps must be cleaned up alongside the in-filter workspaces. + const graph = { + registry: [ + { name: 'abbrev', version: '4.0.0' }, + { name: 'which', version: '4.0.0' }, + ], + root: { + name: 'myroot', + version: '1.0.0', + dependencies: { which: '4.0.0' }, + }, + workspaces: [ + { name: 'ws-a', version: '1.0.0', dependencies: { abbrev: '4.0.0' } }, + ], + } + + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + t.ok(fs.lstatSync(path.join(dir, 'node_modules', 'which'), { throwIfNoEntry: false }), 'which is installed at root') + + // Drop the root dep so node_modules/which becomes orphan. + const pkgPath = path.join(dir, 'package.json') + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) + delete pkg.dependencies + fs.writeFileSync(pkgPath, JSON.stringify(pkg)) + + const arb2 = new Arborist({ + path: dir, + registry, + packumentCache: new Map(), + cache, + workspaces: ['ws-a'], + includeWorkspaceRoot: true, + }) + await arb2.reify({ + installStrategy: 'linked', + workspaces: ['ws-a'], + includeWorkspaceRoot: true, + }) + + t.notOk(fs.lstatSync(path.join(dir, 'node_modules', 'which'), { throwIfNoEntry: false }), + 'orphan root dep is removed when --include-workspace-root scope covers it') +}) + +tap.test('hand-made symlink inside the project root is intentionally swept by linked install', async t => { + // Documents an explicit trade-off: a hand-made symlink whose target lives inside the project (e.g. node_modules/local-tool -> ../tools/local-tool) is indistinguishable from a workspace self-link or store link by target alone. + // The linked sweep treats it as orphaned and removes it on the next reify, matching how the default install strategy already behaves with intra-project symlinks. + // External targets (outside the project root) remain preserved — see the sibling test 'unmanaged symlinks (e.g. npm link) in node_modules are preserved across reify'. + const graph = { + registry: [ + { name: 'abbrev', version: '4.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { abbrev: '^4.0.0' }, + }, + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + // Create a target folder inside the project root and link to it from node_modules. + const localToolDir = path.join(dir, 'tools', 'local-tool') + fs.mkdirSync(localToolDir, { recursive: true }) + fs.writeFileSync(path.join(localToolDir, 'package.json'), + JSON.stringify({ name: 'local-tool', version: '0.0.0' })) + const intraLink = path.join(dir, 'node_modules', 'local-tool') + fs.symlinkSync(path.join('..', 'tools', 'local-tool'), intraLink) + + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + t.notOk(fs.lstatSync(intraLink, { throwIfNoEntry: false }), + 'intra-project hand-made symlink is removed by the sweep (intentional trade-off)') + t.ok(fs.existsSync(localToolDir), + 'the target directory itself is left intact — only the symlink is removed') +}) + +tap.test('orphaned workspace self-link in root node_modules is cleaned up when workspace is undeclared', async t => { + // When root declares a workspace as a dependency, the workspace gets a self-link at root node_modules (e.g. node_modules/a -> ../packages/a). + // If the workspace is later removed from root's dependencies, that self-link must be cleaned up. + // It is a symlink npm itself created, but its target lives outside .store/, so the sweep must accept any orphan whose target resolves inside the project root. + const graph = { + registry: [], + root: { + name: 'root', + version: '1.0.0', + dependencies: { a: '*', b: '*' }, + }, + workspaces: [ + { name: 'a', version: '1.0.0' }, + { name: 'b', version: '1.0.0' }, + ], + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + t.ok(fs.lstatSync(path.join(dir, 'node_modules', 'a'), { throwIfNoEntry: false }), 'a self-link present') + t.ok(fs.lstatSync(path.join(dir, 'node_modules', 'b'), { throwIfNoEntry: false }), 'b self-link present') + + // Drop workspace a from both root deps and the workspaces glob + const pkgPath = path.join(dir, 'package.json') + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) + pkg.workspaces = ['packages/b'] + pkg.dependencies = { b: '*' } + fs.writeFileSync(pkgPath, JSON.stringify(pkg)) + + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + t.notOk(fs.lstatSync(path.join(dir, 'node_modules', 'a'), { throwIfNoEntry: false }), + 'orphan workspace self-link is removed') + t.ok(fs.lstatSync(path.join(dir, 'node_modules', 'b'), { throwIfNoEntry: false }), + 'still-declared workspace self-link is preserved') +}) + +tap.test('unmanaged symlinks (e.g. npm link) in node_modules are preserved across reify', async t => { + // The orphan sweep should only touch links the linked strategy itself created (those resolving into the project's node_modules/.store/). + // A symlink pointing outside .store/ — e.g. one created by `npm link foo` without --save or by hand — must be left alone. + const graph = { + registry: [ + { name: 'abbrev', version: '4.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { abbrev: '^4.0.0' }, + }, + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + // Drop a hand-made symlink to a target outside the project's .store/ + const externalDir = fs.mkdtempSync(`${getTempDir()}/external-`) + fs.writeFileSync(path.join(externalDir, 'package.json'), + JSON.stringify({ name: 'external-pkg', version: '1.0.0' })) + const externalLink = path.join(dir, 'node_modules', 'external-pkg') + fs.symlinkSync(externalDir, externalLink) + + // Remove abbrev so the sweep runs and would otherwise consider external-pkg orphaned + const pkgPath = path.join(dir, 'package.json') + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) + delete pkg.dependencies + fs.writeFileSync(pkgPath, JSON.stringify(pkg)) + + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + t.notOk(fs.existsSync(path.join(dir, 'node_modules', 'abbrev')), + 'orphan link into our .store/ is removed') + t.ok(fs.lstatSync(externalLink, { throwIfNoEntry: false }), + 'unmanaged symlink pointing outside .store/ is preserved') +}) + +tap.test('orphaned scoped top-level link is cleaned up when only one of two scoped deps is removed', async t => { + const graph = { + registry: [ + { name: '@scope/a', version: '1.0.0' }, + { name: '@scope/b', version: '1.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { '@scope/a': '1.0.0', '@scope/b': '1.0.0' }, + }, + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + t.ok(fs.existsSync(path.join(dir, 'node_modules', '@scope', 'a')), '@scope/a installed') + t.ok(fs.existsSync(path.join(dir, 'node_modules', '@scope', 'b')), '@scope/b installed') + + // Drop @scope/a from package.json + const pkgPath = path.join(dir, 'package.json') + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) + delete pkg.dependencies['@scope/a'] + fs.writeFileSync(pkgPath, JSON.stringify(pkg)) + + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + t.notOk(fs.existsSync(path.join(dir, 'node_modules', '@scope', 'a')), + '@scope/a top-level symlink is removed') + t.ok(fs.existsSync(path.join(dir, 'node_modules', '@scope', 'b')), + '@scope/b top-level symlink is preserved') +}) + +tap.test('store symlinks are updated when hash changes after adding a dep', async t => { + const graph = { + registry: [ + { name: 'which', version: '1.0.0', dependencies: { isexe: '^1.0.0' } }, + { name: 'isexe', version: '1.0.0' }, + { name: 'abbrev', version: '2.0.0' }, + ], + root: { + name: 'myproject', + version: '1.0.0', + dependencies: { which: '1.0.0' }, + }, + } + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + + // First install — only which + const arb1 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb1.reify({ installStrategy: 'linked' }) + + const whichLink = path.join(dir, 'node_modules', 'which') + t.ok(fs.lstatSync(whichLink).isSymbolicLink(), 'which is a symlink after first install') + const hashBefore = fs.readlinkSync(whichLink) + + // Add abbrev — changes the dep graph, causing store hash recalculation + const pkgPath = path.join(dir, 'package.json') + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) + pkg.dependencies.abbrev = '2.0.0' + fs.writeFileSync(pkgPath, JSON.stringify(pkg)) + + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + // The symlink target should still be valid (not dangling) + t.ok(fs.existsSync(whichLink), 'which symlink target exists after adding abbrev') + t.ok(setupRequire(dir)('which'), 'which is requireable after adding abbrev') + + // Verify the symlink was updated if the hash changed + const hashAfter = fs.readlinkSync(whichLink) + if (hashBefore !== hashAfter) { + const storeDir = path.join(dir, 'node_modules', '.store') + const storeEntries = fs.readdirSync(storeDir) + const oldKey = hashBefore.split('/')[0].replace('.store/', '') + t.notOk(storeEntries.includes(oldKey), 'old store entry was cleaned up') + } +}) + +function setupRequire (cwd) { + return function requireChain (...chain) { + return chain.reduce((path, name) => { + if (path === undefined) { + return undefined + } + return resolvePackage(name, path) + }, cwd) + } +} + +function pathExists (path) { + try { + fs.statSync(path) + return true + } catch (_) { + return false + } +} + +/** + * We reimplement a lightweight version of require.resolve because the + * one that is implemented in nodejs memoizes the resolution which + * asserts interfering with each others + **/ +function resolvePackage (name, from) { + try { + const loc = `${from}/node_modules/${name}` + fs.statSync(loc) + return fs.realpathSync(loc) + } catch (_) { + const next = path.dirname(from) + if (next === from) { + return undefined + } else { + return resolvePackage(name, next) + } + } +} + +function getAllPackages (resolvedGraph) { + return [...getAllPackagesRecursive(resolvedGraph.root), + ...(resolvedGraph.workspaces?.map(w => getAllPackagesRecursive(w)) || []).reduce((a, n) => ([...a, ...n]), [])] +} + +function getAllPackagesRecursive (resolvedGraph) { + return [ + resolvedGraph, + ...(resolvedGraph.dependencies + ?.filter(d => !isLoopToken(d)) + .map(d => getAllPackagesRecursive(d)) || []) + .reduce((a, n) => ([...a, ...n]), []), + ] +} + +function withRequireChain (resolvedGraph) { + return { + root: { + ...resolvedGraph.root, + chain: [], + initialDir: '.', + dependencies: resolvedGraph.root.dependencies?.map(d => + withRequireChainRecursive(d, [], '.')), + }, + workspaces: resolvedGraph.workspaces?.map(w => { + const initialDir = `packages/${w.name}` + return { + ...w, + chain: [], + initialDir, + dependencies: w.dependencies?.map(d => withRequireChainRecursive(d, [], initialDir)), + } + }), + } +} + +function withRequireChainRecursive (resolvedGraph, chain, initialDir) { + if (isLoopToken(resolvedGraph)) { + return resolvedGraph + } const newChain = [...chain, resolvedGraph.name] return { @@ -1564,6 +2582,273 @@ function parseGraphRecursive (key, deps) { return { name, version, workspace, peer, dependencies } } +tap.test('undeclared workspaces are not hoisted to root node_modules', async t => { + // Regression test: all workspace packages were unconditionally symlinked into root node_modules/. + // Only workspaces that root explicitly depends on should appear at root node_modules/. + const graph = { + registry: [ + { name: 'which', version: '1.0.0', dependencies: { isexe: '^1.0.0' } }, + { name: 'isexe', version: '1.0.0' }, + ], + root: { + name: 'myapp', + version: '1.0.0', + dependencies: { 'ws-a': '*' }, + }, + workspaces: [ + { name: 'ws-a', version: '1.0.0', dependencies: { 'ws-b': '*', which: '1.0.0' } }, + { name: 'ws-b', version: '1.0.0' }, + { name: 'ws-c', version: '1.0.0' }, + ], + } + + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arborist.reify({ installStrategy: 'linked' }) + + // ws-a is declared as a root dependency — should be at root node_modules + t.ok(pathExists(path.join(dir, 'node_modules', 'ws-a')), + 'declared workspace ws-a is symlinked at root node_modules') + t.ok(fs.lstatSync(path.join(dir, 'node_modules', 'ws-a')).isSymbolicLink(), + 'ws-a at root is a symlink') + + // ws-b is NOT a root dependency — should NOT be at root node_modules + t.notOk(pathExists(path.join(dir, 'node_modules', 'ws-b')), + 'undeclared workspace ws-b is NOT at root node_modules') + + // ws-c is NOT a root dependency — should NOT be at root node_modules + t.notOk(pathExists(path.join(dir, 'node_modules', 'ws-c')), + 'undeclared workspace ws-c is NOT at root node_modules') + + // ws-b should be resolvable from ws-a (ws-a depends on ws-b) + t.ok(pathExists(path.join(dir, 'packages', 'ws-a', 'node_modules', 'ws-b')), + 'ws-b is linked in ws-a/node_modules (declared dep)') + + // ws-c has no dependencies and is not depended on — should not be able to access ws-b + t.notOk(pathExists(path.join(dir, 'packages', 'ws-c', 'node_modules', 'ws-b')), + 'ws-c cannot access ws-b (no dependency declared)') +}) + +tap.test('undeclared workspaces do not get a self-link in their own node_modules', async t => { + // Undeclared workspaces used to be self-symlinked into their own node_modules/. + // Cross-workspace dep links remain unaffected, and stale self-links from older npm versions are swept on the next install. + const graph = { + registry: [ + { name: 'abbrev', version: '1.0.0' }, + ], + root: { + name: 'myapp', + version: '1.0.0', + dependencies: { '@scope/a': '*' }, + }, + workspaces: [ + { name: '@scope/a', version: '1.0.0', dependencies: { '@scope/test': '*', abbrev: '1.0.0' } }, + { name: '@scope/test', version: '1.0.0' }, + ], + } + + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arborist.reify({ installStrategy: 'linked' }) + + // No self-link inside the undeclared workspace's own node_modules + t.notOk(fs.lstatSync(path.join(dir, 'packages', '@scope', 'test', 'node_modules', '@scope', 'test'), { throwIfNoEntry: false }), + 'undeclared workspace has no self-link in its own node_modules') + + // Cross-workspace dep link still works: @scope/a depends on @scope/test + t.ok(fs.lstatSync(path.join(dir, 'packages', '@scope', 'a', 'node_modules', '@scope', 'test'), { throwIfNoEntry: false })?.isSymbolicLink(), + '@scope/a still has a symlink to @scope/test in its node_modules') + + // Stale self-link from an older npm version must be swept on a subsequent install + fs.mkdirSync(path.join(dir, 'packages', '@scope', 'test', 'node_modules', '@scope'), { recursive: true }) + fs.symlinkSync('../../..', path.join(dir, 'packages', '@scope', 'test', 'node_modules', '@scope', 'test')) + t.ok(fs.lstatSync(path.join(dir, 'packages', '@scope', 'test', 'node_modules', '@scope', 'test'), { throwIfNoEntry: false }), + 'stale self-link planted') + + const arb2 = new Arborist({ path: dir, registry, packumentCache: new Map(), cache }) + await arb2.reify({ installStrategy: 'linked' }) + + t.notOk(fs.lstatSync(path.join(dir, 'packages', '@scope', 'test', 'node_modules', '@scope', 'test'), { throwIfNoEntry: false }), + 'stale self-link is removed by the orphan sweep on the next install') +}) + +tap.test('omit dev dependencies with linked strategy', async t => { + const graph = { + registry: [ + { name: 'which', version: '1.0.0', dependencies: { isexe: '^1.0.0' } }, + { name: 'isexe', version: '1.0.0' }, + { name: 'eslint', version: '1.0.0' }, + ], + root: { + name: 'myapp', + version: '1.0.0', + dependencies: { which: '1.0.0' }, + devDependencies: { eslint: '1.0.0' }, + }, + workspaces: [ + { + name: 'mylib', + version: '1.0.0', + dependencies: { isexe: '1.0.0' }, + devDependencies: { eslint: '1.0.0' }, + }, + ], + } + + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ + path: dir, + registry, + packumentCache: new Map(), + cache, + omit: ['dev'], + }) + await arborist.reify({ installStrategy: 'linked' }) + + const storeDir = path.join(dir, 'node_modules', '.store') + const storeEntries = fs.readdirSync(storeDir) + + t.ok(storeEntries.some(e => e.startsWith('which@')), 'prod dep which is in store') + t.ok(storeEntries.some(e => e.startsWith('isexe@')), 'prod dep isexe is in store') + t.notOk(storeEntries.some(e => e.startsWith('eslint@')), 'dev dep eslint is not in store') +}) + +tap.test('omit dev deps from root even when shared with workspace prod deps', async t => { + // In a monorepo, a root devDependency may also be a workspace prod dependency. + // With --omit=dev, root should NOT link to it, but the workspace still should. + // Also covers the case where a workspace itself is a root devDependency. + const graph = { + registry: [ + { name: 'typescript', version: '5.0.0' }, + { name: 'which', version: '1.0.0', dependencies: { isexe: '^1.0.0' } }, + { name: 'isexe', version: '1.0.0' }, + ], + root: { + name: 'myapp', + version: '1.0.0', + dependencies: { which: '1.0.0', mylib: '1.0.0' }, + devDependencies: { typescript: '5.0.0', devtool: '1.0.0' }, + }, + workspaces: [ + { + name: 'mylib', + version: '1.0.0', + dependencies: { typescript: '5.0.0' }, + }, + { + name: 'devtool', + version: '1.0.0', + }, + ], + } + + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ + path: dir, + registry, + packumentCache: new Map(), + cache, + omit: ['dev'], + }) + await arborist.reify({ installStrategy: 'linked' }) + + const storeDir = path.join(dir, 'node_modules', '.store') + const storeEntries = fs.readdirSync(storeDir) + + // typescript should still be in the store because mylib needs it as a prod dep + t.ok(storeEntries.some(e => e.startsWith('typescript@')), 'typescript is in store (workspace prod dep)') + t.ok(storeEntries.some(e => e.startsWith('which@')), 'which is in store') + + // root should NOT have a symlink to typescript (it's a dev dep of root) + const rootNmEntries = fs.readdirSync(path.join(dir, 'node_modules')) + t.ok(rootNmEntries.includes('which'), 'root has symlink to prod dep which') + t.ok(rootNmEntries.includes('mylib'), 'root has symlink to prod workspace mylib') + t.notOk(rootNmEntries.includes('typescript'), 'root does not have symlink to dev dep typescript') + t.notOk(rootNmEntries.includes('devtool'), 'root does not have symlink to dev workspace devtool') + + // workspace should have a symlink to typescript (it's a prod dep of mylib) + const wsNmEntries = fs.readdirSync(path.join(dir, 'packages', 'mylib', 'node_modules')) + t.ok(wsNmEntries.includes('typescript'), 'workspace has symlink to prod dep typescript') +}) + +tap.test('omit optional dependencies with linked strategy', async t => { + const graph = { + registry: [ + { name: 'which', version: '1.0.0' }, + { name: 'fsevents', version: '1.0.0' }, + ], + root: { + name: 'myapp', + version: '1.0.0', + dependencies: { which: '1.0.0' }, + optionalDependencies: { fsevents: '1.0.0' }, + }, + workspaces: [ + { + name: 'mylib', + version: '1.0.0', + dependencies: { fsevents: '1.0.0' }, + }, + ], + } + + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ + path: dir, + registry, + packumentCache: new Map(), + cache, + omit: ['optional'], + }) + await arborist.reify({ installStrategy: 'linked' }) + + const rootNmEntries = fs.readdirSync(path.join(dir, 'node_modules')) + t.ok(rootNmEntries.includes('which'), 'root has prod dep which') + t.notOk(rootNmEntries.includes('fsevents'), 'root does not have optional dep fsevents') +}) + +tap.test('omit peer dependencies with linked strategy', async t => { + const graph = { + registry: [ + { name: 'which', version: '1.0.0' }, + { name: 'react', version: '18.0.0' }, + ], + root: { + name: 'myapp', + version: '1.0.0', + dependencies: { which: '1.0.0' }, + peerDependencies: { react: '18.0.0' }, + }, + workspaces: [ + { + name: 'mylib', + version: '1.0.0', + dependencies: { react: '18.0.0' }, + }, + ], + } + + const { dir, registry } = await getRepo(graph) + const cache = fs.mkdtempSync(`${getTempDir()}/test-`) + const arborist = new Arborist({ + path: dir, + registry, + packumentCache: new Map(), + cache, + omit: ['peer'], + }) + await arborist.reify({ installStrategy: 'linked' }) + + const rootNmEntries = fs.readdirSync(path.join(dir, 'node_modules')) + t.ok(rootNmEntries.includes('which'), 'root has prod dep which') + t.notOk(rootNmEntries.includes('react'), 'root does not have peer dep react') +}) + /* * TO TEST: * -------------------------------------- diff --git a/workspaces/arborist/test/link.js b/workspaces/arborist/test/link.js index 685ace11046d3..472f33c2f4535 100644 --- a/workspaces/arborist/test/link.js +++ b/workspaces/arborist/test/link.js @@ -43,7 +43,7 @@ t.matchSnapshot(normalizePaths(l1), 'instantiate without providing target') t.equal(l1.isLink, true, 'link is a link') t.same(l1.children.size, 0, 'children is empty') l1.children = new Map([[1, 2], [3, 4]]) -t.same(l1.children.size, 0, 'children still empty after being sasigned') +t.same(l1.children.size, 0, 'children still empty after being assigned') l1.children.set('asdf', 'foo') t.same(l1.children.size, 0, 'children still empty after setting value') @@ -207,6 +207,100 @@ t.test('link gets version from target', t => { t.end() }) +t.test('recalculateOutEdgesOverrides forwards overrides to target', t => { + const root = new Node({ + path: '/path/to/root', + pkg: { + name: 'root', + dependencies: { foo: '1.0.0' }, + overrides: { bar: '2.0.0' }, + }, + loadOverrides: true, + }) + + const target = new Node({ + path: '/path/to/store/foo', + pkg: { + name: 'foo', + version: '1.0.0', + dependencies: { bar: '1.0.0' }, + }, + root, + }) + + const link = new Link({ + pkg: { name: 'foo', version: '1.0.0' }, + path: '/path/to/root/node_modules/foo', + realpath: '/path/to/store/foo', + target, + parent: root, + }) + + // The root has overrides, and the edge from root -> link should propagate them + t.ok(root.overrides, 'root has overrides') + t.ok(link.overrides, 'link received overrides from root edge') + t.ok(link.target.overrides, 'target received overrides forwarded from link') + + // The target's edge to "bar" should have the override applied + const barEdge = link.target.edgesOut.get('bar') + t.ok(barEdge, 'target has edge to bar') + t.ok(barEdge.overrides, 'bar edge has overrides') + t.equal(barEdge.spec, '2.0.0', 'bar edge spec is overridden to 2.0.0') + t.equal(barEdge.rawSpec, '1.0.0', 'bar edge rawSpec is original 1.0.0') + + // recalculateOutEdgesOverrides is a no-op when target is null + link.target = null + t.doesNotThrow(() => link.recalculateOutEdgesOverrides(), + 'no-op when target is null') + + t.end() +}) + +t.test('recalculateOutEdgesOverrides does not forward when no rule matches a target dep — npm/cli#9357', t => { + // Regression: prior to the fix, Link.recalculateOutEdgesOverrides forwarded the link's full OverrideSet to the target unconditionally. + // For a target whose edges are NOT named in any override rule, that flipped target.overrides from undefined to the root's OverrideSet. + // Downstream, that "has overrides" state changed canPlaceDep's KEEP-vs-REPLACE decision and made `npm ci` re-resolve lockfile-pinned edges from the registry. + // After the fix, propagation is gated on at least one rule whose name matches an edge in target.edgesOut. + const root = new Node({ + path: '/path/to/root', + pkg: { + name: 'root', + dependencies: { foo: '1.0.0' }, + // override is for "bar", but the linked target only depends on "baz" + overrides: { bar: '2.0.0' }, + }, + loadOverrides: true, + }) + + const target = new Node({ + path: '/path/to/store/foo', + pkg: { + name: 'foo', + version: '1.0.0', + dependencies: { baz: '1.0.0' }, + }, + root, + }) + + // eslint-disable-next-line no-new + new Link({ + pkg: { name: 'foo', version: '1.0.0' }, + path: '/path/to/root/node_modules/foo', + realpath: '/path/to/store/foo', + target, + parent: root, + }) + + t.ok(root.overrides, 'root has overrides') + t.notOk(target.overrides, + 'target.overrides stays undefined when no rule matches a target dep') + const bazEdge = target.edgesOut.get('baz') + t.notOk(bazEdge.overrides, + 'unrelated edge keeps edge.overrides undefined') + t.equal(bazEdge.spec, '1.0.0', 'unrelated edge spec is unchanged') + t.end() +}) + t.test('link to root path gets root as target', t => { const root = new Node({ path: '/project/root', diff --git a/workspaces/arborist/test/node.js b/workspaces/arborist/test/node.js index f5090dc2def5a..ec474e0b7d75e 100644 --- a/workspaces/arborist/test/node.js +++ b/workspaces/arborist/test/node.js @@ -1016,43 +1016,6 @@ t.test('setting package refreshes deps', t => { t.end() }) -t.test('nodes in shrinkwraps', t => { - const root = new Node({ - pkg: { dependencies: { a: '' } }, - path: '/path/to/root', - children: [ - { - name: 'a', - pkg: { - name: 'a', - version: '1.2.3', - dependencies: { b: '' }, - _hasShrinkwrap: true, - }, - children: [ - { - name: 'b', - pkg: { - version: '1.2.3', - name: 'b', - dependencies: { c: '' }, - }, - children: [{ name: 'c', pkg: { name: 'c', version: '1.2.3' } }], - }, - ], - }, - ], - }) - const a = root.children.get('a') - const b = a.children.get('b') - const c = b.children.get('c') - - t.equal(a.hasShrinkwrap, true, 'a has a shrinkwrap') - t.equal(b.inShrinkwrap, true, 'b is in shrinkwrap') - t.equal(c.inShrinkwrap, true, 'c is in shrinkwrap') - t.end() -}) - t.test('bin paths', t => { const root = new Node({ path: '/a/b/c', @@ -1322,7 +1285,7 @@ t.test('replace workspaces keeping existing edges out', t => { t.end() }) -t.test('dont rely on legacy _resolved for file: nodes', async t => { +t.test('do not rely on legacy _resolved for file: nodes', async t => { const old = new Node({ pkg: { _resolved: 'file:/x/y/z/blorg.tgz', @@ -2242,7 +2205,7 @@ t.test('virtual references to root node has devDep edges', async t => { t.equal(virtualRoot.edgesOut.get('a').type, 'dev') }) -t.test('globaTop set for children of global link root target', async t => { +t.test('globalTop set for children of global link root target', async t => { const root = new Link({ path: '/usr/local/lib', realpath: '/data/lib', @@ -2365,7 +2328,7 @@ t.test('canDedupe()', t => { | +-- a 1.2.3 (removable, matches) +-- extraneous 1.2.3 +-- wrapper - +-- a 1.2.3 (not removable, in shrinkwrap) + +-- a 1.2.3 (removable, matches root a) */ const root = new Node({ @@ -2405,9 +2368,7 @@ t.test('canDedupe()', t => { dependencies: { a: '1', }, - _hasShrinkwrap: true, }, - hasShrinkwrap: true, children: [ { pkg: { name: 'a', version: '1.2.3' }, @@ -2480,6 +2441,7 @@ t.test('canDedupe()', t => { const canDedupeLocs = [...root.inventory.filter(n => n.canDedupe())] .map(n => n.location) t.match(canDedupeLocs, [ + 'node_modules/wrapper/node_modules/a', 'node_modules/c/node_modules/a', 'node_modules/b/node_modules/e', 'node_modules/b/node_modules/c/node_modules/a/node_modules/e', @@ -2488,6 +2450,7 @@ t.test('canDedupe()', t => { const canDedupeTrueLocs = [...root.inventory.filter(n => n.canDedupe(true))] .map(n => n.location) t.match(canDedupeTrueLocs, [ + 'node_modules/wrapper/node_modules/a', 'node_modules/c/node_modules/a', // this is the one that's only deduped if we preferDedupe 'node_modules/b/node_modules/a', @@ -2522,6 +2485,43 @@ t.test('canDedupe()', t => { t.end() }) +t.test('canDedupe returns true when explicitRequest is true regardless of other conditions', t => { + // Create a minimal tree with a valid resolveParent + const root = new Node({ + pkg: { name: 'root', version: '1.0.0' }, + path: '/root', + realpath: '/root', + }) + + // Create a duplicate candidate node in the tree + const duplicate = new Node({ + pkg: { name: 'dup', version: '1.0.0' }, + parent: root, + }) + + // Create a node with the same name but a higher version so that normally dedupe would not occur + const node = new Node({ + pkg: { name: 'dup', version: '2.0.0' }, + parent: duplicate, + }) + + // Manually add an incoming edge so that node.edgesIn is non-empty + node.edgesIn.add({ + from: duplicate, + satisfiedBy () { + return true + }, + }) + + const preferDedupe = false + let explicitRequest = false + t.notOk(node.canDedupe(preferDedupe, explicitRequest), 'without explicit request, dedupe is not allowed') + + explicitRequest = true + t.ok(node.canDedupe(preferDedupe, explicitRequest), 'explicit request forces dedupe to return true') + t.end() +}) + t.test('packageName getter', t => { const node = new Node({ pkg: { name: 'foo' }, @@ -2753,6 +2753,7 @@ t.test('overrides', (t) => { name: 'baz', version: '1.0.0', pkg: { + version: '1.0.0', dependencies: { buzz: '1.0.0', }, @@ -2774,6 +2775,90 @@ t.test('overrides', (t) => { t.not(buzz.overridden, 'buzz was not overridden') }) + t.test('node.overridden is false when an override does not match the node version', async (t) => { + const tree = new Node({ + loadOverrides: true, + path: '/some/path', + pkg: { + name: 'foo', + dependencies: { + bar: '^1', + }, + overrides: { + baz: '1.0.0', // Override specifies "1.0.0" + }, + }, + children: [{ + name: 'bar', + version: '1.0.0', + pkg: { + dependencies: { + baz: '2.0.0', + }, + }, + children: [{ + name: 'baz', + version: '3.0.0', + pkg: { + version: '3.0.0', // This does NOT match the override! + dependencies: { + buzz: '1.0.0', + }, + }, + children: [{ + name: 'buzz', + version: '1.0.0', + pkg: {}, + }], + }], + }], + }) + + const bar = tree.edgesOut.get('bar').to + t.not(bar.overridden, 'bar was not overridden') + + const baz = bar.edgesOut.get('baz').to + t.not(baz.overridden, 'baz was not overridden because version mismatch') + + const buzz = baz.edgesOut.get('buzz').to + t.not(buzz.overridden, 'buzz was not overridden') + }) + + t.test('node.overridden returns false when an incoming edge override equals its source override', t => { + const baseOverride = new OverrideSet({ + overrides: { + foo: 'bar', + }, + }) + baseOverride.name = 'test-package' + baseOverride.value = '1.0.0' + + const node = new Node({ + pkg: { name: 'test-package', version: '1.0.0' }, + path: '/some/path/test-package', + realpath: '/some/path/test-package', + overrides: baseOverride, + }) + + const equalOverride = new OverrideSet({ + overrides: { + foo: 'bar', + }, + }) + equalOverride.name = 'test-package' + equalOverride.value = '1.0.0' + + const fakeEdge = { + overrides: equalOverride, + from: { overrides: baseOverride }, + } + + node.edgesIn.add(fakeEdge) + + t.equal(node.overridden, false, 'node.overridden returns false when edge.override equals edge.from.override') + t.end() + }) + t.test('assertRootOverrides throws when a dependency and override conflict', async (t) => { const conflictingTree = new Node({ loadOverrides: true, @@ -2882,18 +2967,17 @@ t.test('overrides', (t) => { t.notOk(root.edgesOut.get('foo').valid, 'foo edge is not valid') t.notOk(foo.edgesOut.get('bar').valid, 'bar edge is not valid') - // we add bar to the root first, this is deliberate so that we don't have a simple - // linear inheritance. we'll add foo later and make sure that both edges and nodes - // become valid after that - + // Attach bar to root. This does not trigger override propagation because + // bar is not connected via a dependency edge. bar.root = root - t.ok(bar.overrides, 'bar now has overrides') + t.notOk(bar.overrides, 'bar still does not have overrides until connected by a dependency edge') t.notOk(foo.edgesOut.get('bar').valid, 'bar edge is not valid yet') + // Now attach foo to root so that it is connected as a dependency. foo.root = root t.ok(foo.overrides, 'foo now has overrides') t.ok(root.edgesOut.get('foo').valid, 'foo edge is now valid') - t.ok(bar.overrides, 'bar still has overrides') + t.ok(bar.overrides, 'bar now has overrides after foo is attached') t.ok(foo.edgesOut.get('bar').valid, 'bar edge is now valid') }) @@ -2915,7 +2999,7 @@ t.test('overrides', (t) => { ], }) - const badReplacement = new Node({ + const equivalentReplacement = new Node({ loadOverrides: true, path: '/some/path', pkg: { @@ -2932,7 +3016,7 @@ t.test('overrides', (t) => { ], }) - t.equal(original.canReplaceWith(badReplacement), false, 'different overrides fails') + t.equal(original.canReplaceWith(equivalentReplacement), true, 'different overrides passes') const goodReplacement = new Node({ path: '/some/path', @@ -2981,3 +3065,461 @@ t.test('node with only registry edges in a registry dep', async t => { t.equal(node.isRegistryDependency, true) }) + +t.test('canReplaceWith returns false when overrides differ', t => { + const override1 = new OverrideSet({ + overrides: { foo: '1.0.0' }, + }) + const override2 = new OverrideSet({ + overrides: { foo: '2.0.0' }, + }) + + // Create two nodes with a dependency to force creation of an outgoing edge + const node1 = new Node({ + pkg: { name: 'foo', dependencies: { bar: '^1' } }, + path: '/some/path/foo', + realpath: '/some/path/foo', + overrides: override1, + }) + const node2 = new Node({ + pkg: { name: 'foo', dependencies: { bar: '^1' } }, + path: '/some/path/foo', + realpath: '/some/path/foo', + overrides: override2, + }) + + t.ok(node1.edgesOut.size > 0, 'node1 has outgoing edges') + t.equal(node1.canReplaceWith(node2, new Set()), false, 'cannot replace when overrides differ') + t.end() +}) + +t.test('updateOverridesEdgeInRemoved uses findSpecificOverrideSet for multiple edgesIn', t => { + const commonOverrides = new OverrideSet({ + overrides: { + foo: '1.0.0', + }, + }) + const specificOverrides = new OverrideSet({ + overrides: { + foo: '1.0.0', + bar: '2.0.0', + }, + }) + // Create a node with initial overrides set to commonOverrides + const node = new Node({ + pkg: { name: 'nodeA' }, + path: '/some/path/nodeA', + realpath: '/some/path/nodeA', + overrides: commonOverrides, + }) + // Simulate incoming edges with overrides + node.edgesIn.add({ + overrides: commonOverrides, + }) + node.edgesIn.add({ + overrides: specificOverrides, + }) + // Call updateOverridesEdgeInRemoved passing an override set equal to node.overrides + const result = node.updateOverridesEdgeInRemoved(commonOverrides) + t.equal(result, true, 'updateOverridesEdgeInRemoved returns true when newOverrideSet differs') + t.notOk(commonOverrides.isEqual(node.overrides), 'node.overrides is updated to a more specific override set') + t.end() +}) + +t.test('updateOverridesEdgeInAdded conflicts on conflicting override set', t => { + const overrides8 = new OverrideSet({ + overrides: { + bat: '1.2.0', + }, + }) + const overrides9 = new OverrideSet({ + overrides: { + 'bat@3.0.0': '1.2.0', + }, + }) + + // Create a node with an existing override set + const node = new Node({ + pkg: { name: 'conflict-node' }, + path: '/some/path/conflict-node', + realpath: '/some/path/conflict-node', + overrides: overrides8, + }) + + // Call updateOverridesEdgeInAdded with a conflicting override set + const result = node.updateOverridesEdgeInAdded(overrides9) + t.equal(result, undefined, 'returns undefined on conflict') + + t.end() +}) + +t.test('updateOverridesEdgeInRemoved calls recalculateOutEdgesOverrides when new override set exists', t => { + const originalOverrides = new OverrideSet({ + overrides: { + foo: '1.0.0', + }, + }) + const specificOverrides = new OverrideSet({ + overrides: { + foo: '1.0.0', + bar: '2.0.0', + }, + }) + + // Create a node with original overrides and simulate an incoming edge + // whose override is more specific, so that the computed newOverrideSet + // differs from the original, triggering recalculateOutEdgesOverrides + const node = new Node({ + pkg: { name: 'test-node' }, + path: '/some/path/test-node', + realpath: '/some/path/test-node', + overrides: originalOverrides, + }) + + node.edgesIn.add({ + overrides: specificOverrides, + }) + + // Spy on recalculateOutEdgesOverrides to verify it's called + let recalcCalled = false + node.recalculateOutEdgesOverrides = () => { + recalcCalled = true + } + + const result = node.updateOverridesEdgeInRemoved(originalOverrides) + t.equal(result, true, 'returns true when override set changes') + t.ok(recalcCalled, 'recalculateOutEdgesOverrides was called') + t.ok(specificOverrides.isEqual(node.overrides), 'node.overrides updated to the specific override set') + t.end() +}) + +t.test('should propagate the new override set to the target node', t => { + const tree = new Node({ + loadOverrides: true, + path: '/root', + pkg: { + name: 'root', + version: '1.0.0', + dependencies: { + mockDep: '1.x', + }, + overrides: { + mockDep: '2.x', + }, + }, + children: [{ + name: 'mockDep', + version: '2.0.0', + pkg: { + dependencies: { + subDep: '1.0.0', + }, + }, + children: [{ + name: 'subDep', + version: '1.0.0', + pkg: {}, + }], + }], + }) + + // Force edge.override to a conflicting object so that it will differ from + // the computed override coming from the parent's override set. + const conflictingOverride = new OverrideSet({ + overrides: { mockDep: '1.x' }, + }) + const edge = tree.edgesOut.get('mockDep') + edge.overrides = conflictingOverride + + // Calls updateOverridesEdgeInRemoved and updateOverridesEdgeInAdded + edge.reload() + + // Validate that the override's value property has been updated + t.equal(edge.overrides.value, '2.x', 'Edge override propagates the correct override value from the parent') + + t.end() +}) + +t.test('override conflict detection with semantic comparison', t => { + t.test('non-conflicting different override sets should be valid', t => { + // Regression test for issue #8688 + // This validates that the improved semantic conflict detection allows + // structurally different override sets that don't actually conflict. + + // Create two different override sets (simulating Vaadin's structure) + // These override different packages, so they don't conflict + const overridesComponents = new OverrideSet({ + overrides: { + '@vaadin/react-components': '24.9.2', + }, + }) + + const overridesComponentsPro = new OverrideSet({ + overrides: { + '@vaadin/react-components-pro': '24.9.2', + }, + }) + + const tree = new Node({ + loadOverrides: true, + path: '/root', + pkg: { + name: 'root', + version: '1.0.0', + dependencies: { + mockDep: '1.x', + }, + overrides: { + mockDep: '2.x', + }, + }, + children: [{ + name: 'mockDep', + version: '2.0.0', + pkg: { + dependencies: { + subDep: '1.0.0', + }, + }, + children: [{ + name: 'subDep', + version: '1.0.0', + pkg: {}, + }], + }], + }) + + const edge = tree.edgesOut.get('mockDep') + + // Manually set an override to the edge + edge.overrides = overridesComponents + + // Override satisfiedBy so it returns true, ensuring the conflict branch is reached + edge.satisfiedBy = () => true + + // Set different but non-conflicting override on the target node + const mockDep = tree.children.get('mockDep') + mockDep.overrides = overridesComponentsPro + + // Force edge to recalculate + edge.reload(true) + + // The edge should be valid despite different override contexts + // because they don't have conflicting version requirements + t.equal(edge.error, null, 'Edge should be valid with non-conflicting override contexts') + t.ok(edge.valid, 'Edge.valid should be true') + + t.end() + }) + + t.test('conflicting override sets should be detected as invalid', t => { + // This validates that actual conflicts ARE still caught by the semantic detection + + // Create two override sets with conflicting version requirements for the same package + const overridesV1 = new OverrideSet({ + overrides: { + lodash: '1.x', + }, + }) + + const overridesV4 = new OverrideSet({ + overrides: { + lodash: '4.x', + }, + }) + + const tree = new Node({ + loadOverrides: true, + path: '/root', + pkg: { + name: 'root', + version: '1.0.0', + dependencies: { + mockDep: '1.x', + }, + overrides: { + mockDep: '2.x', + }, + }, + children: [{ + name: 'mockDep', + version: '2.0.0', + pkg: { + dependencies: { + lodash: '1.0.0', + }, + }, + children: [{ + name: 'lodash', + version: '1.0.0', + pkg: {}, + }], + }], + }) + + const edge = tree.edgesOut.get('mockDep') + const mockDep = tree.children.get('mockDep') + + // Manually set conflicting overrides + edge.overrides = overridesV1 + mockDep.overrides = overridesV4 + + // Override satisfiedBy so it returns true, ensuring the conflict branch is reached + edge.satisfiedBy = () => true + + // Clear the cached error by calling reload(true) + edge.reload(true) + + // Re-set the overrides after reload (since reload may have changed them) + edge.overrides = overridesV1 + mockDep.overrides = overridesV4 + + // The edge should be INVALID due to conflicting override requirements + t.equal(edge.error, 'INVALID', 'Edge should be invalid with conflicting override versions') + t.notOk(edge.valid, 'Edge.valid should be false') + + t.end() + }) + + t.test('reference overrides should not cause false positives', t => { + // This validates that reference overrides ($syntax) don't trigger false positives + + const overridesRef1 = new OverrideSet({ + overrides: { + lodash: '$some-reference', + }, + }) + + const overridesRef2 = new OverrideSet({ + overrides: { + lodash: '$another-reference', + }, + }) + + const tree = new Node({ + loadOverrides: true, + path: '/root', + pkg: { + name: 'root', + version: '1.0.0', + dependencies: { + mockDep: '1.x', + }, + overrides: { + mockDep: '2.x', + }, + }, + children: [{ + name: 'mockDep', + version: '2.0.0', + pkg: { + dependencies: { + lodash: '4.0.0', + }, + }, + children: [{ + name: 'lodash', + version: '4.0.0', + pkg: {}, + }], + }], + }) + + const edge = tree.edgesOut.get('mockDep') + + // Set reference overrides + edge.overrides = overridesRef1 + + // Override satisfiedBy so it returns true, ensuring the conflict branch is reached + edge.satisfiedBy = () => true + + const mockDep = tree.children.get('mockDep') + mockDep.overrides = overridesRef2 + + // Force edge to recalculate + edge.reload(true) + + // Reference overrides should not cause conflicts because we can't determine + // their compatibility at this stage - they might resolve to the same version + t.equal(edge.error, null, 'Edge should be valid with reference overrides') + t.ok(edge.valid, 'Edge.valid should be true with reference overrides') + + t.end() + }) + + t.end() +}) + +t.test('shouldOmit method', t => { + t.test('dev dependency with dev omit', t => { + const node = new Node({ + pkg: { name: 'test' }, + path: '/test', + dummy: true, + }) + node.dev = true + t.equal(node.shouldOmit(new Set(['dev'])), true, 'should omit dev dependency when dev is omitted') + t.equal(node.shouldOmit(new Set(['optional'])), false, 'should not omit dev dependency when only optional is omitted') + t.end() + }) + + t.test('optional dependency with optional omit', t => { + const node = new Node({ + pkg: { name: 'test' }, + path: '/test', + dummy: true, + }) + node.optional = true + t.equal(node.shouldOmit(new Set(['optional'])), true, 'should omit optional dependency when optional is omitted') + t.equal(node.shouldOmit(new Set(['dev'])), false, 'should not omit optional dependency when only dev is omitted') + t.end() + }) + + t.test('peer dependency with peer omit', t => { + const node = new Node({ + pkg: { name: 'test' }, + path: '/test', + dummy: true, + }) + node.peer = true + t.equal(node.shouldOmit(new Set(['peer'])), true, 'should omit peer dependency when peer is omitted') + t.equal(node.shouldOmit(new Set(['dev'])), false, 'should not omit peer dependency when only dev is omitted') + t.end() + }) + + t.test('devOptional dependency', t => { + const node = new Node({ + pkg: { name: 'test' }, + path: '/test', + dummy: true, + }) + node.devOptional = true + t.equal(node.shouldOmit(new Set(['dev', 'optional'])), true, 'should omit devOptional when both dev and optional are omitted') + t.equal(node.shouldOmit(new Set(['dev'])), false, 'should not omit devOptional when only dev is omitted') + t.equal(node.shouldOmit(new Set(['optional'])), false, 'should not omit devOptional when only optional is omitted') + t.end() + }) + + t.test('regular dependency', t => { + const node = new Node({ + pkg: { name: 'test' }, + path: '/test', + dummy: true, + }) + t.equal(node.shouldOmit(new Set(['dev', 'optional', 'peer'])), false, 'should never omit regular dependencies') + t.end() + }) + + t.test('empty omit set', t => { + const node = new Node({ + pkg: { name: 'test' }, + path: '/test', + dummy: true, + }) + node.dev = true + t.equal(node.shouldOmit(new Set()), false, 'should not omit anything when omit set is empty') + t.end() + }) + + t.end() +}) diff --git a/workspaces/arborist/test/npm-extension.js b/workspaces/arborist/test/npm-extension.js new file mode 100644 index 0000000000000..774f19c9f2ea9 --- /dev/null +++ b/workspaces/arborist/test/npm-extension.js @@ -0,0 +1,206 @@ +const t = require('tap') +const { resolve } = require('node:path') +const NpmExtension = require('../lib/npm-extension.js') +const { discover, hashFile, EXTENSION_POINT } = require('../lib/npm-extension.js') + +// write a transformManifest module body as a .mjs or .cjs file in a fresh dir +const mjs = body => `export function transformManifest (pkg, context) {\n${body}\n}\n` +const cjs = body => `module.exports = { transformManifest (pkg, context) {\n${body}\n} }\n` + +t.test('discover', async t => { + t.equal(discover(t.testdir({}), null), null, 'nothing present') + + const mjsDir = t.testdir({ '.npm-extension.mjs': mjs('return pkg') }) + t.match(discover(mjsDir, null), { format: 'mjs', path: resolve(mjsDir, '.npm-extension.mjs') }, 'finds .mjs') + + const cjsDir = t.testdir({ '.npm-extension.cjs': cjs('return pkg') }) + t.match(discover(cjsDir, null), { format: 'cjs' }, 'finds .cjs') + + const bothDir = t.testdir({ '.npm-extension.mjs': mjs('return pkg'), '.npm-extension.cjs': cjs('return pkg') }) + t.throws(() => discover(bothDir, null), { code: 'ENPMEXTENSIONDUP' }, 'rejects both files present') + + // extension-file + const cfgDir = t.testdir({ tools: { 'ext.mjs': mjs('return pkg') } }) + t.match(discover(cfgDir, 'tools/ext.mjs'), { format: 'mjs' }, 'loads configured file') + t.throws(() => discover(cfgDir, '../escape.mjs'), { code: 'ENPMEXTENSIONPATH' }, 'rejects path outside root') + t.throws(() => discover(cfgDir, 'tools/ext.js'), { code: 'ENPMEXTENSIONPATH' }, 'rejects non mjs/cjs extension') + t.throws(() => discover(cfgDir, 'tools/missing.mjs'), { code: 'ENPMEXTENSIONPATH' }, 'rejects missing configured file') + + // a non-ENOENT read error (here a directory in the file's place) propagates + const dirNamed = t.testdir({ '.npm-extension.mjs': {} }) + t.throws(() => discover(dirNamed, null), { code: 'EISDIR' }, 'propagates non-ENOENT read errors') +}) + +t.test('hashFile is deterministic and format-tagged', async t => { + const bytes = Buffer.from('export function transformManifest (p) { return p }') + t.equal(hashFile('mjs', bytes), hashFile('mjs', bytes), 'stable for same bytes') + t.not(hashFile('mjs', bytes), hashFile('cjs', bytes), 'mjs and cjs differ for identical bytes') + t.match(hashFile('mjs', bytes), /^sha512-/, 'sha512 ssri string') +}) + +t.test('constructor without root is absent', async t => { + const ext = new NpmExtension() + t.equal(ext.present, false) + t.equal(ext.hash, null) +}) + +t.test('load: honors an ESM default export', async t => { + const dir = t.testdir({ + '.npm-extension.mjs': `export default { transformManifest (pkg) { pkg.dependencies = { d: '1' }; return pkg } }\n`, + }) + const ext = new NpmExtension({ root: dir }) + await ext.load() + t.same(ext.apply({ name: 'foo', version: '1.0.0' }).applied.dependencies, ['d'], 'default export used') +}) + +t.test('apply: keys the cache by resolved source when integrity is absent', async t => { + const dir = t.testdir({ '.npm-extension.cjs': cjs(`pkg.dependencies = { d: '1' }; return pkg`) }) + const ext = new NpmExtension({ root: dir }) + await ext.load() + // a git-style manifest: no _integrity, no version, only a resolved source + const res = ext.apply({ name: 'g', _resolved: 'git+ssh://host/a.git#abc' }) + t.same(res.applied.dependencies, ['d'], 'transform applied to a non-registry manifest') +}) + +t.test('apply: a manifest without a name is skipped', async t => { + const dir = t.testdir({ '.npm-extension.mjs': mjs('pkg.dependencies = { d: "1" }; return pkg') }) + const ext = new NpmExtension({ root: dir }) + await ext.load() + t.equal(ext.apply({ version: '1.0.0' }), null, 'no name means nothing to match') +}) + +t.test('load: rejects a bad export shape', async t => { + const dir = t.testdir({ '.npm-extension.mjs': 'export const transformManifest = 5\n' }) + const ext = new NpmExtension({ root: dir }) + t.ok(ext.present) + t.ok(ext.hash, 'hash computed without executing the module') + await t.rejects(ext.load(), { code: 'ENPMEXTENSIONSHAPE' }, 'non-function export rejected') +}) + +t.test('load: absent extension is a no-op', async t => { + const ext = new NpmExtension({ root: t.testdir({}) }) + await ext.load() + t.equal(ext.apply({ name: 'x', version: '1.0.0' }), null, 'apply is a no-op when absent') +}) + +t.test('apply: cjs adds a dependency', async t => { + const dir = t.testdir({ + '.npm-extension.cjs': cjs(`if (pkg.name === 'foo') { pkg.dependencies = { ...pkg.dependencies, bar: '^2.0.0' }; context.log('added bar') } return pkg`), + }) + const ext = new NpmExtension({ root: dir }) + await ext.load() + const res = ext.apply({ name: 'foo', version: '1.0.0', _integrity: 'sha512-foo' }) + t.same(res.pkg.dependencies, { bar: '^2.0.0' }, 'dependency added') + t.same(res.applied, { extensionPoint: EXTENSION_POINT, dependencies: ['bar'] }, 'provenance recorded') + t.equal(ext.apply({ name: 'other', version: '1.0.0' }), null, 'non-matching package unchanged') +}) + +t.test('apply: mjs adds optional peer and meta, sorted provenance', async t => { + const dir = t.testdir({ + '.npm-extension.mjs': mjs(` + if (pkg.name !== 'widget') return pkg + pkg.peerDependencies = { ...pkg.peerDependencies, '@types/react': '*', react: '>=18' } + pkg.peerDependenciesMeta = { ...pkg.peerDependenciesMeta, '@types/react': { optional: true } } + return pkg`), + }) + const ext = new NpmExtension({ root: dir }) + await ext.load() + const res = ext.apply({ name: 'widget', version: '2.0.0', _integrity: 'sha512-w' }) + t.same(res.applied, { + extensionPoint: EXTENSION_POINT, + peerDependencies: ['@types/react', 'react'], + peerDependenciesMeta: ['@types/react'], + }, 'affected names sorted per field') +}) + +t.test('apply: can replace a range and delete an entry', async t => { + const dir = t.testdir({ + '.npm-extension.cjs': cjs(` + if (pkg.name === 'rep') pkg.dependencies = { ...pkg.dependencies, dep: '^9.0.0' } + if (pkg.name === 'del') delete pkg.dependencies.gone + return pkg`), + }) + const ext = new NpmExtension({ root: dir }) + await ext.load() + const rep = ext.apply({ name: 'rep', version: '1.0.0', dependencies: { dep: '^1.0.0' } }) + t.equal(rep.pkg.dependencies.dep, '^9.0.0', 'range replaced') + t.same(rep.applied.dependencies, ['dep']) + + const del = ext.apply({ name: 'del', version: '1.0.0', dependencies: { gone: '1', keep: '2' } }) + t.same(del.pkg.dependencies, { keep: '2' }, 'entry deleted') + t.same(del.applied.dependencies, ['gone'], 'deleted name recorded in provenance') +}) + +t.test('apply: no-op transform returns null', async t => { + const dir = t.testdir({ '.npm-extension.mjs': mjs('return pkg') }) + const ext = new NpmExtension({ root: dir }) + await ext.load() + t.equal(ext.apply({ name: 'foo', version: '1.0.0' }), null, 'unchanged manifest yields no provenance') +}) + +t.test('apply: caches per identity and isolates consumers', async t => { + const dir = t.testdir({ + '.npm-extension.cjs': cjs(`pkg.dependencies = { ...pkg.dependencies, added: '1.0.0' }; return pkg`), + }) + const ext = new NpmExtension({ root: dir }) + await ext.load() + // two consumers of the same cached identity must each get a distinct, deeply isolated object + const a = ext.apply({ name: 'foo', version: '1.0.0', _integrity: 'sha512-shared' }) + const b = ext.apply({ name: 'foo', version: '1.0.0', _integrity: 'sha512-shared' }) + t.not(a.pkg, b.pkg, 'each consumer gets a distinct object') + a.pkg.dependencies.added = 'mutated' + t.equal(b.pkg.dependencies.added, '1.0.0', 'mutating one copy does not affect another') +}) + +t.test('apply: rejects invalid transform output', async t => { + const cases = [ + ['return null', 'ENPMEXTENSIONRETURN'], + ['return 5', 'ENPMEXTENSIONRETURN'], + ['return []', 'ENPMEXTENSIONRETURN'], + ['return Promise.resolve(pkg)', 'ENPMEXTENSIONRETURN'], + [`pkg.scripts = { build: 'x' }; return pkg`, 'ENPMEXTENSIONFIELD'], + [`return { name: pkg.name, version: pkg.version, scripts: { build: 'x' } }`, 'ENPMEXTENSIONFIELD'], + [`pkg.dependencies = 'nope'; return pkg`, 'ENPMEXTENSIONVALUE'], + [`pkg.dependencies = null; return pkg`, 'ENPMEXTENSIONVALUE'], + [`pkg.dependencies = { x: null }; return pkg`, 'ENPMEXTENSIONVALUE'], + [`pkg.peerDependencies = { p: '*' }; pkg.peerDependenciesMeta = { p: null }; return pkg`, 'ENPMEXTENSIONVALUE'], + [`throw new Error('boom')`, 'ENPMEXTENSIONTHROW'], + ] + // a unique dir per case so require/import cache never serves a previous module + for (const [i, [body, code]] of cases.entries()) { + const dir = t.testdir({ [`c${i}`]: { '.npm-extension.cjs': cjs(body) } }) + const ext = new NpmExtension({ root: resolve(dir, `c${i}`) }) + await ext.load() + t.throws(() => ext.apply({ name: 'foo', version: '1.0.0', scripts: {} }), { code }, `${code}: ${body}`) + } +}) + +t.test('apply: a handler may return a new object with only repaired fields', async t => { + const dir = t.testdir({ + '.npm-extension.cjs': cjs(`return { name: pkg.name, version: pkg.version, dependencies: { ...pkg.dependencies, bar: '^2.0.0' } }`), + }) + const ext = new NpmExtension({ root: dir }) + await ext.load() + const res = ext.apply({ name: 'foo', version: '1.0.0', dependencies: { keep: '1' }, scripts: { build: 'x' }, _integrity: 'sha512-z' }) + t.same(res.pkg.dependencies, { keep: '1', bar: '^2.0.0' }, 'returned dependencies overlaid on the baseline') + t.same(res.pkg.scripts, { build: 'x' }, 'omitted non-allowlisted field preserved from the baseline') +}) + +t.test('apply: isolates cached provenance between consumers', async t => { + const dir = t.testdir({ '.npm-extension.cjs': cjs(`pkg.dependencies = { ...pkg.dependencies, bar: '1' }; return pkg`) }) + const ext = new NpmExtension({ root: dir }) + await ext.load() + const a = ext.apply({ name: 'foo', version: '1.0.0', _integrity: 'sha512-prov' }) + const b = ext.apply({ name: 'foo', version: '1.0.0', _integrity: 'sha512-prov' }) + a.applied.dependencies.push('mutated') + t.same(b.applied.dependencies, ['bar'], 'mutating one consumer\'s provenance does not affect another') +}) + +t.test('apply: does not mutate the input manifest', async t => { + const dir = t.testdir({ '.npm-extension.cjs': cjs(`pkg.dependencies = { bar: '1' }; return pkg`) }) + const ext = new NpmExtension({ root: dir }) + await ext.load() + const input = { name: 'foo', version: '1.0.0', dependencies: { keep: '2' } } + ext.apply(input) + t.same(input.dependencies, { keep: '2' }, 'caller manifest untouched') +}) diff --git a/workspaces/arborist/test/optional-set.js b/workspaces/arborist/test/optional-set.js index e639ea1450ef6..27719254eae06 100644 --- a/workspaces/arborist/test/optional-set.js +++ b/workspaces/arborist/test/optional-set.js @@ -9,17 +9,18 @@ tree (PROD a, PROD c, OPT i) +-- a (OPT o) +-- b (PROD c) +-- c (OPT b) -+-- o (PROD m) -+-- m (PROD n) ++-- o (PROD m, OPT i) ++-- m (OPT n) +-- n () +-- OPT i (PROD j) +-- j () Gathering the optional set from: -j: [i], +j: [j, i], a: [], -o: [m, n], -b: [] +o: [o, m, n], +m: [o, m, n], +b: [b], */ const tree = new Node({ @@ -38,8 +39,8 @@ const tree = new Node({ ['a', [], ['o']], ['b', ['c'], []], ['c', [], ['b']], - ['o', ['m'], []], - ['m', ['n'], []], + ['o', ['m'], ['i']], + ['m', [], ['n']], ['n', [], []], ['i', ['j'], []], ['j', [], []], @@ -63,7 +64,6 @@ calcDepFlags(tree) const nodeJ = tree.children.get('j') const nodeI = tree.children.get('i') -const nodeA = tree.children.get('a') const nodeO = tree.children.get('o') const nodeM = tree.children.get('m') const nodeN = tree.children.get('n') @@ -74,21 +74,59 @@ t.equal(setJ.has(nodeJ), true, 'gathering from j includes j') t.equal(setJ.has(nodeI), true, 'gathering from j includes i') t.equal(setJ.size, 2, 'two nodes in j set') -const setA = optionalSet(nodeA) -t.equal(setA.size, 0, 'gathering from a is empty set') - const setO = optionalSet(nodeO) t.equal(setO.size, 3, 'three nodes in o set') t.equal(setO.has(nodeO), true, 'set o includes o') t.equal(setO.has(nodeM), true, 'set o includes m') t.equal(setO.has(nodeN), true, 'set o includes n') -const setN = optionalSet(nodeO) -t.equal(setN.size, 3, 'three nodes in n set') -t.equal(setN.has(nodeO), true, 'set n includes o') -t.equal(setN.has(nodeM), true, 'set n includes m') -t.equal(setN.has(nodeN), true, 'set n includes n') +const setM = optionalSet(nodeM) +t.equal(setM.size, 3, 'three nodes in m set') +t.equal(setM.has(nodeO), true, 'set m includes o') +t.equal(setM.has(nodeM), true, 'set m includes m') +t.equal(setM.has(nodeN), true, 'set m includes n') const setB = optionalSet(nodeB) t.equal(setB.size, 1, 'gathering from b is only b') t.equal(setB.has(nodeB), true, 'set b includes b') + +// tree (OPT opt-p, OPT opt-q) +// +-- OPT opt-p (PROD shared-dep) +// +-- OPT opt-q (PROD shared-dep) +// +-- shared-dep () +const sharedTree = new Node({ + path: '/path/to/shared-tree', + pkg: { + optionalDependencies: { + 'opt-p': '', + 'opt-q': '', + }, + }, + children: [ + { pkg: { name: 'opt-p', version: '1.0.0', dependencies: { 'shared-dep': '' } } }, + { pkg: { name: 'opt-q', version: '1.0.0', dependencies: { 'shared-dep': '' } } }, + { pkg: { name: 'shared-dep', version: '1.0.0' } }, + ], +}) + +calcDepFlags(sharedTree) + +const nodeOptP = sharedTree.children.get('opt-p') +const nodeOptQ = sharedTree.children.get('opt-q') +const nodeSharedDep = sharedTree.children.get('shared-dep') + +// Simulate opt-p failing platform check and being marked inert first +const setOptP = optionalSet(nodeOptP) +// shared-dep is excluded because opt-q (not yet inert) also depends on it +t.equal(setOptP.has(nodeOptP), true, 'set opt-p includes opt-p') +t.equal(setOptP.has(nodeSharedDep), false, 'set opt-p excludes shared-dep (opt-q is not inert)') +for (const n of setOptP) { + n.inert = true +} + +// Simulate opt-q failing platform check second (opt-p is already inert) +const setOptQ = optionalSet(nodeOptQ) +// shared-dep now has no active external dependents and is included +t.equal(setOptQ.has(nodeOptQ), true, 'set opt-q includes opt-q') +t.equal(setOptQ.has(nodeSharedDep), true, 'set opt-q includes shared-dep (opt-p is inert)') +t.equal(setOptQ.size, 2, 'set opt-q has two nodes: opt-q and shared-dep') diff --git a/workspaces/arborist/test/override-set.js b/workspaces/arborist/test/override-set.js index 705996b443b22..b892c02c7cc85 100644 --- a/workspaces/arborist/test/override-set.js +++ b/workspaces/arborist/test/override-set.js @@ -1,5 +1,4 @@ const t = require('tap') - const OverrideSet = require('../lib/override-set.js') t.test('constructor', async (t) => { @@ -271,4 +270,364 @@ t.test('constructor', async (t) => { const outOfRangeRule = bazEdgeRule.getEdgeRule({ name: 'buzz', spec: 'github:baz/buzz#semver:^2.0.0' }) t.equal(outOfRangeRule.name, 'baz', 'no match - returned parent') }) + + t.test('isequal and findspecificoverrideset tests', async (t) => { + const overrides1 = new OverrideSet({ + overrides: { + foo: { + bar: { + '.': '2.0.0', + baz: '3.0.0', + }, + baz: '2.0.0', + }, + bar: '1.0.0', + baz: '1.0.0', + }, + }) + const overrides2 = new OverrideSet({ + overrides: { + foo: { + bar: { + '.': '2.0.0', + baz: '3.0.0', + }, + baz: '2.0.0', + }, + bar: '1.0.0', + baz: '1.0.0', + }, + }) + const overrides3 = new OverrideSet({ + overrides: { + foo: { + bar: { + '.': '2.0.0', + baz: '3.1.0', + }, + baz: '2.0.0', + }, + bar: '1.0.0', + baz: '1.0.0', + }, + }) + const overrides4 = new OverrideSet({ + overrides: { + foo: { + bar: { + '.': '2.0.0', + }, + baz: '2.0.0', + }, + bar: '1.0.0', + baz: '1.0.0', + }, + }) + const overrides5 = new OverrideSet({ + overrides: { + foo: { + bar: { + '.': '2.0.0', + }, + bat: '2.0.0', + }, + bar: '1.0.0', + baz: '1.0.0', + }, + }) + const overrides6 = new OverrideSet({ + overrides: { + bar: { + '.': '2.0.0', + }, + bat: '2.0.0', + }, + }) + overrides6.parent = overrides5 + const overrides7 = new OverrideSet({ + overrides: { + bat: '2.0.0', + }, + }) + const overrides8 = new OverrideSet({ + overrides: { + bat: '1.2.0', + }, + }) + const overrides9 = new OverrideSet({ + overrides: { + 'bat@3.0.0': '1.2.0', + }, + }) + + t.ok(overrides1.isEqual(overrides1), 'override set is equal to itself') + t.ok(overrides1.isEqual(overrides2), 'two identical override sets are equal') + t.ok(!overrides1.isEqual(overrides3), 'two different override sets are not equal') + t.ok(!overrides2.isEqual(overrides3), 'two different override sets are not equal') + t.ok(!overrides3.isEqual(overrides1), 'two different override sets are not equal') + t.ok(!overrides3.isEqual(overrides2), 'two different override sets are not equal') + t.ok(!overrides4.isEqual(overrides1), 'two different override sets are not equal') + t.ok(!overrides4.isEqual(overrides2), 'two different override sets are not equal') + t.ok(!overrides4.isEqual(overrides3), 'two different override sets are not equal') + t.ok(!overrides4.isEqual(overrides5), 'two override sets that differ only by package name are not equal') + t.ok(!overrides5.isEqual(overrides4), 'two override sets that differ only by package name are not equal') + t.equal(OverrideSet.findSpecificOverrideSet(overrides5, overrides5), overrides5, 'find more specific override set when the sets are identical') + t.equal(OverrideSet.findSpecificOverrideSet(overrides5, overrides6), overrides6, "find more specific override set when it's the second") + t.equal(OverrideSet.findSpecificOverrideSet(overrides6, overrides5), overrides6, "find more specific override set when it's the first") + t.ok(!OverrideSet.doOverrideSetsConflict(overrides1, overrides2), 'override sets are equal') + t.ok(!OverrideSet.doOverrideSetsConflict(overrides5, overrides5), 'override sets are the same object') + t.ok(!OverrideSet.doOverrideSetsConflict(overrides5, overrides6), 'one override set is the specific version of the other') + t.ok(!OverrideSet.doOverrideSetsConflict(overrides6, overrides5), 'one override set is the specific version of the other') + // With semantic conflict detection, overrides5 and overrides7 don't conflict because + // they have the same value for 'bat' (2.0.0). Structurally they're incomparable, + // but semantically they're compatible. + t.ok(!OverrideSet.doOverrideSetsConflict(overrides5, overrides7), 'structurally incomparable but semantically compatible') + t.ok(!OverrideSet.doOverrideSetsConflict(overrides7, overrides5), 'structurally incomparable but semantically compatible') + t.ok(!overrides7.isEqual(overrides8), 'two override sets that differ in the version are not equal') + t.ok(!overrides8.isEqual(overrides9), 'two override sets that differ in the range are not equal') + t.ok(!overrides7.isEqual(overrides9), 'two override sets that differ in both version and range are not equal') + // overrides7 (bat: 2.0.0) and overrides8 (bat: 1.2.0) have conflicting versions for the same package + t.ok(OverrideSet.doOverrideSetsConflict(overrides7, overrides8), 'override sets have conflicting versions for bat') + // overrides7 (bat: 2.0.0) and overrides9 (bat@3.0.0: 1.2.0) don't directly conflict because + // overrides9 only applies to bat@3.x, not bat@2.x + t.ok(!OverrideSet.doOverrideSetsConflict(overrides7, overrides9), 'override sets apply to different version ranges') + // overrides8 (bat: 1.2.0) and overrides9 (bat@3.0.0: 1.2.0) have same target version + t.ok(!OverrideSet.doOverrideSetsConflict(overrides8, overrides9), 'override sets have compatible target versions') + }) + + t.test('semantic conflict detection (haveConflictingRules)', async (t) => { + t.test('no conflict when packages are different', async (t) => { + const overrides1 = new OverrideSet({ + overrides: { + foo: '1.0.0', + }, + }) + const overrides2 = new OverrideSet({ + overrides: { + bar: '1.0.0', + }, + }) + t.ok(!OverrideSet.haveConflictingRules(overrides1, overrides2), 'different packages should not conflict') + }) + + t.test('no conflict when version ranges intersect', async (t) => { + const overrides1 = new OverrideSet({ + overrides: { + lodash: '^4.0.0', + }, + }) + const overrides2 = new OverrideSet({ + overrides: { + lodash: '4.17.0', + }, + }) + t.ok(!OverrideSet.haveConflictingRules(overrides1, overrides2), 'intersecting ranges should not conflict') + }) + + t.test('conflict when version ranges do not intersect', async (t) => { + const overrides1 = new OverrideSet({ + overrides: { + lodash: '1.x', + }, + }) + const overrides2 = new OverrideSet({ + overrides: { + lodash: '4.x', + }, + }) + t.ok(OverrideSet.haveConflictingRules(overrides1, overrides2), 'non-intersecting ranges should conflict') + }) + + t.test('no conflict when using reference overrides', async (t) => { + const overrides1 = new OverrideSet({ + overrides: { + lodash: '$ref1', + }, + }) + const overrides2 = new OverrideSet({ + overrides: { + lodash: '$ref2', + }, + }) + t.ok(!OverrideSet.haveConflictingRules(overrides1, overrides2), 'reference overrides should not conflict') + }) + + t.test('no conflict when one is a reference override', async (t) => { + const overrides1 = new OverrideSet({ + overrides: { + lodash: '$ref1', + }, + }) + const overrides2 = new OverrideSet({ + overrides: { + lodash: '4.17.21', + }, + }) + t.ok(!OverrideSet.haveConflictingRules(overrides1, overrides2), 'reference override with version should not conflict') + }) + + t.test('no conflict when rules are equal', async (t) => { + const overrides1 = new OverrideSet({ + overrides: { + lodash: '4.17.21', + }, + }) + const overrides2 = new OverrideSet({ + overrides: { + lodash: '4.17.21', + }, + }) + t.ok(!OverrideSet.haveConflictingRules(overrides1, overrides2), 'equal rules should not conflict') + }) + + t.test('handles non-semver spec types gracefully', async (t) => { + const overrides1 = new OverrideSet({ + overrides: { + foo: 'github:user/repo', + }, + }) + const overrides2 = new OverrideSet({ + overrides: { + foo: 'file:./local', + }, + }) + // Non-semver types should not be considered conflicting + t.ok(!OverrideSet.haveConflictingRules(overrides1, overrides2), 'non-semver specs should not conflict') + }) + + t.test('regression test for issue #8688 - Vaadin case', async (t) => { + const overridesComponents = new OverrideSet({ + overrides: { + '@vaadin/react-components': '24.9.2', + }, + }) + const overridesComponentsPro = new OverrideSet({ + overrides: { + '@vaadin/react-components-pro': '24.9.2', + }, + }) + t.ok(!OverrideSet.doOverrideSetsConflict(overridesComponents, overridesComponentsPro), 'Vaadin components should not conflict') + }) + }) +}) + +t.test('findSpecificOverrideSet returns common ancestor for compatible siblings', async (t) => { + // Regression test for https://github.com/npm/cli/issues/9109 + // When two top-level overrides (e.g. react + react-dom) share a transitive dep (e.g. loose-envify), the dep's node gets override sets from both siblings. findSpecificOverrideSet must return their common ancestor instead of undefined. + const root = new OverrideSet({ + overrides: { + react: '18.3.1', + 'react-dom': '18.3.1', + }, + }) + + const reactChild = root.children.get('react') + const reactDomChild = root.children.get('react-dom') + + t.ok(reactChild, 'react child exists') + t.ok(reactDomChild, 'react-dom child exists') + + // These are siblings - neither is an ancestor of the other + const result = OverrideSet.findSpecificOverrideSet(reactChild, reactDomChild) + t.ok(result, 'findSpecificOverrideSet should not return undefined for compatible siblings') + t.ok(result.isEqual(root), 'should return the common ancestor (root)') + + const reverse = OverrideSet.findSpecificOverrideSet(reactDomChild, reactChild) + t.ok(reverse, 'reverse order should also return a result') + t.ok(reverse.isEqual(root), 'reverse order should also return the root') +}) + +t.test('findCommonAncestor', async (t) => { + const root = new OverrideSet({ + overrides: { + foo: '1.0.0', + bar: '2.0.0', + }, + }) + + const fooChild = root.children.get('foo') + const barChild = root.children.get('bar') + + const ancestor = OverrideSet.findCommonAncestor(fooChild, barChild) + t.ok(ancestor, 'should find a common ancestor') + t.ok(ancestor.isEqual(root), 'common ancestor should be the root') + + // Two unrelated roots have no common ancestor + const other = new OverrideSet({ overrides: { baz: '3.0.0' } }) + const noAncestor = OverrideSet.findCommonAncestor(fooChild, other) + t.equal(noAncestor, null, 'unrelated sets have no common ancestor') +}) + +t.test('findSpecificOverrideSet returns undefined for truly conflicting siblings', async (t) => { + // Siblings with conflicting rules should still return undefined + const root = new OverrideSet({ + overrides: { + foo: { + '.': '1.0.0', + shared: '1.0.0', + }, + bar: { + '.': '2.0.0', + shared: '99.0.0', + }, + }, + }) + + const fooChild = root.children.get('foo') + const barChild = root.children.get('bar') + + t.ok(fooChild, 'foo child exists') + t.ok(barChild, 'bar child exists') + + const result = OverrideSet.findSpecificOverrideSet(fooChild, barChild) + t.equal(result, undefined, 'truly conflicting siblings should return undefined') +}) + +t.test('coverage for isEqual edge cases', async t => { + t.test('isEqual with null/undefined other', async t => { + const overrides = new OverrideSet({ overrides: { foo: '1.0.0' } }) + t.ok(!overrides.isEqual(null), 'override set is not equal to null') + t.ok(!overrides.isEqual(undefined), 'override set is not equal to undefined') + }) + + t.test('isEqual when parent != null', async t => { + // Both parents have the SAME config -> parent.isEqual(...) will return TRUE + const parentA = new OverrideSet({ overrides: { foo: '1.0.0' } }) + const parentB = new OverrideSet({ overrides: { foo: '1.0.0' } }) + + // Child override sets with the same parent config => should be equal + const childA = new OverrideSet({ + overrides: { bar: '2.0.0' }, + key: 'bar', + parent: parentA, + }) + const childB = new OverrideSet({ + overrides: { bar: '2.0.0' }, + key: 'bar', + parent: parentB, + }) + + // This specifically covers the code path where parent != null + // AND parent.isEqual(...) returns true + t.ok(childA.isEqual(childB), 'two children with equivalent parents are equal') + + // Different parent configs -> parent.isEqual(...) will return FALSE + const parentC = new OverrideSet({ overrides: { foo: '1.0.0' } }) + const parentD = new OverrideSet({ overrides: { foo: '1.0.1' } }) + + const childC = new OverrideSet({ + overrides: { bar: '2.0.0' }, + key: 'bar', + parent: parentC, + }) + const childD = new OverrideSet({ + overrides: { bar: '2.0.0' }, + key: 'bar', + parent: parentD, + }) + + // This specifically covers the code path where parent != null + // AND parent.isEqual(...) returns false + t.notOk(childC.isEqual(childD), 'two children with different parents are not equal') + }) }) diff --git a/workspaces/arborist/test/package-extensions.js b/workspaces/arborist/test/package-extensions.js new file mode 100644 index 0000000000000..72046b3ad1d31 --- /dev/null +++ b/workspaces/arborist/test/package-extensions.js @@ -0,0 +1,214 @@ +const t = require('tap') +const PackageExtensions = require('../lib/package-extensions.js') +const { + parseSelector, + rangeMatches, + canonicalHash, + canonicalStringify, +} = require('../lib/package-extensions.js') + +t.test('parseSelector', async t => { + t.strictSame(parseSelector('foo'), { name: 'foo', range: null }, 'name only') + t.strictSame(parseSelector('foo@1'), { name: 'foo', range: '1' }, 'name with range') + t.strictSame(parseSelector('@scope/foo'), { name: '@scope/foo', range: null }, 'scoped name only') + t.strictSame(parseSelector('@scope/foo@^2.3.0'), { name: '@scope/foo', range: '^2.3.0' }, 'scoped with range') + + for (const bad of ['', null, undefined, 5]) { + t.throws(() => parseSelector(bad), { code: 'EEXTENSIONSELECTOR' }, `rejects ${JSON.stringify(bad)}`) + } + // dist-tags, git, file, url, alias specs are not valid selectors + for (const bad of ['foo@latest', 'foo@next', 'foo@git+https://x.com/a.git', 'foo@file:../x', 'foo@npm:bar@1', 'foo@https://x.com/a.tgz']) { + t.throws(() => parseSelector(bad), { code: 'EEXTENSIONSELECTOR' }, `rejects spec selector ${bad}`) + } + // a blank range is malformed; use the name-only form to match every version + for (const bad of ['foo@', 'foo@ ', '@scope/foo@']) { + t.throws(() => parseSelector(bad), { code: 'EEXTENSIONSELECTOR' }, `rejects blank range ${JSON.stringify(bad)}`) + } + // invalid package names + for (const bad of [' @1', ' space ', '.hidden']) { + t.throws(() => parseSelector(bad), { code: 'EEXTENSIONSELECTOR' }, `rejects invalid name ${bad}`) + } +}) + +t.test('rangeMatches', async t => { + t.ok(rangeMatches(null, '1.2.3'), 'name-only matches semver version') + t.ok(rangeMatches(null, 'not-semver'), 'name-only matches non-semver version') + t.ok(rangeMatches('1', '1.2.3'), 'range matches satisfying version') + t.notOk(rangeMatches('1', '2.0.0'), 'range rejects non-satisfying version') + t.notOk(rangeMatches('1', 'not-semver'), 'versioned selector rejects non-semver version') +}) + +t.test('constructor validation', async t => { + t.equal(new PackageExtensions(undefined).present, false, 'absent field is allowed and not present') + t.equal(new PackageExtensions(undefined).hash, null, 'absent field has no hash') + + const empty = new PackageExtensions({}) + t.equal(empty.present, true, 'empty object is present') + t.ok(empty.hash, 'empty object still hashes') + + for (const bad of [null, [], 'x', 5]) { + t.throws(() => new PackageExtensions(bad), { code: 'EEXTENSIONROOT' }, `rejects root ${JSON.stringify(bad)}`) + } + + t.throws(() => new PackageExtensions({ foo: { devDependencies: { a: '1' } } }), + { code: 'EEXTENSIONFIELD' }, 'rejects unsupported field') + t.throws(() => new PackageExtensions({ foo: { dependencies: [] } }), + { code: 'EEXTENSIONVALUE' }, 'rejects non-object field value') + t.throws(() => new PackageExtensions({ foo: 'bar' }), + { code: 'EEXTENSIONVALUE' }, 'rejects non-object extension') + + for (const del of [null, false, '-']) { + t.throws(() => new PackageExtensions({ foo: { dependencies: { bar: del } } }), + { code: 'EEXTENSIONDELETE' }, `rejects deletion value ${JSON.stringify(del)}`) + } + + for (const bad of [null, false, '-', 'x', 5]) { + t.throws(() => new PackageExtensions({ foo: { peerDependenciesMeta: { bar: bad } } }), + { code: 'EEXTENSIONVALUE' }, `rejects non-object peerDependenciesMeta value ${JSON.stringify(bad)}`) + } +}) + +t.test('match', async t => { + const pe = new PackageExtensions({ + foo: { dependencies: { a: '1' } }, + 'bar@^2': { dependencies: { b: '1' } }, + }) + t.equal(pe.match('foo', '9.9.9').key, 'foo', 'name-only matches any version') + t.equal(pe.match('bar', '2.5.0').key, 'bar@^2', 'range matches satisfying version') + t.equal(pe.match('bar', '1.0.0'), null, 'range misses non-satisfying version') + t.equal(pe.match('nope', '1.0.0'), null, 'unknown name misses') + + const conflict = new PackageExtensions({ + foo: { dependencies: { a: '1' } }, + 'foo@1': { dependencies: { b: '1' } }, + }) + t.throws(() => conflict.match('foo', '1.2.3'), { code: 'EEXTENSIONCONFLICT' }, 'two matching selectors conflict') + t.equal(conflict.match('foo', '2.0.0').key, 'foo', 'only one matches at 2.0.0, no conflict') +}) + +t.test('apply: add missing dependencies and optionalDependencies', async t => { + const pe = new PackageExtensions({ + foo: { + dependencies: { 'missing-dep': '^2.0.0' }, + optionalDependencies: { 'opt-dep': '^1.0.0' }, + }, + }) + const { pkg, applied } = pe.apply({ name: 'foo', version: '1.0.0', dependencies: { existing: '^1' } }) + t.strictSame(pkg.dependencies, { existing: '^1', 'missing-dep': '^2.0.0' }, 'added to dependencies, kept existing') + t.strictSame(pkg.optionalDependencies, { 'opt-dep': '^1.0.0' }, 'created optionalDependencies') + t.strictSame(applied, { + selector: 'foo', + dependencies: ['missing-dep'], + optionalDependencies: ['opt-dep'], + }, 'provenance records selector and changed names') +}) + +t.test('apply: does not mutate the input manifest', async t => { + const pe = new PackageExtensions({ foo: { dependencies: { bar: '^1' } } }) + const input = { name: 'foo', version: '1.0.0', dependencies: { a: '1' } } + const inputDeps = input.dependencies + const { pkg } = pe.apply(input) + t.strictSame(input.dependencies, { a: '1' }, 'input dependencies unchanged') + t.equal(input.dependencies, inputDeps, 'input dependencies object identity unchanged') + t.not(pkg.dependencies, input.dependencies, 'output has a fresh dependencies object') +}) + +t.test('apply: rejects replacing an existing normal dependency', async t => { + const pe = new PackageExtensions({ foo: { dependencies: { bar: '^2' } } }) + t.throws(() => pe.apply({ name: 'foo', version: '1.0.0', dependencies: { bar: '^1' } }), + { code: 'EEXTENSIONDUPDEP' }, 'cannot replace existing dependency') + + const peOpt = new PackageExtensions({ foo: { dependencies: { bar: '^2' } } }) + t.throws(() => peOpt.apply({ name: 'foo', version: '1.0.0', optionalDependencies: { bar: '^1' } }), + { code: 'EEXTENSIONDUPDEP' }, 'cannot add a dependency already in optionalDependencies (no field move)') + + const peMove = new PackageExtensions({ foo: { optionalDependencies: { bar: '^2' } } }) + t.throws(() => peMove.apply({ name: 'foo', version: '1.0.0', dependencies: { bar: '^1' } }), + { code: 'EEXTENSIONDUPDEP' }, 'cannot add an optionalDependency already in dependencies (no field move)') +}) + +t.test('apply: peerDependencies merge and replace', async t => { + const pe = new PackageExtensions({ + foo: { + peerDependencies: { typescript: '>=5', react: '^18' }, + }, + }) + const { pkg, applied } = pe.apply({ + name: 'foo', + version: '1.0.0', + peerDependencies: { typescript: '>=4', vue: '^3' }, + }) + t.strictSame(pkg.peerDependencies, { typescript: '>=5', vue: '^3', react: '^18' }, + 'replaced existing range, added new, kept unrelated') + t.strictSame(applied.peerDependencies.sort(), ['react', 'typescript'], 'provenance lists changed peers') +}) + +t.test('apply: peerDependenciesMeta merge by key', async t => { + const pe = new PackageExtensions({ + foo: { + peerDependenciesMeta: { typescript: { optional: true } }, + }, + }) + const { pkg } = pe.apply({ + name: 'foo', + version: '1.0.0', + peerDependencies: { typescript: '>=5' }, + peerDependenciesMeta: { typescript: { somethingElse: true } }, + }) + t.strictSame(pkg.peerDependenciesMeta.typescript, { somethingElse: true, optional: true }, + 'shallow-merged meta object without dropping existing keys') +}) + +t.test('apply: peerDependenciesMeta with same extension adding the peer', async t => { + const pe = new PackageExtensions({ + foo: { + peerDependencies: { typescript: '>=5' }, + peerDependenciesMeta: { typescript: { optional: true } }, + }, + }) + const { pkg } = pe.apply({ name: 'foo', version: '1.0.0' }) + t.strictSame(pkg.peerDependencies, { typescript: '>=5' }, 'peer added') + t.strictSame(pkg.peerDependenciesMeta, { typescript: { optional: true } }, 'meta added') +}) + +t.test('apply: orphan peerDependenciesMeta is an error', async t => { + const pe = new PackageExtensions({ + foo: { peerDependenciesMeta: { typescript: { optional: true } } }, + }) + t.throws(() => pe.apply({ name: 'foo', version: '1.0.0' }), + { code: 'EEXTENSIONORPHANMETA' }, 'meta without corresponding peer fails') +}) + +t.test('apply: peer may overlap with dependencies', async t => { + const pe = new PackageExtensions({ + foo: { peerDependencies: { bar: '^1' } }, + }) + const { pkg } = pe.apply({ name: 'foo', version: '1.0.0', dependencies: { bar: '^1' } }) + t.strictSame(pkg.dependencies, { bar: '^1' }, 'dependency kept') + t.strictSame(pkg.peerDependencies, { bar: '^1' }, 'peer added alongside dependency') +}) + +t.test('apply: returns null when nothing matches', async t => { + const pe = new PackageExtensions({ foo: { dependencies: { a: '1' } } }) + t.equal(pe.apply({ name: 'other', version: '1.0.0' }), null, 'no match returns null') + t.equal(new PackageExtensions(undefined).apply({ name: 'foo', version: '1' }), null, 'absent returns null') + t.equal(pe.apply(null), null, 'no manifest returns null') +}) + +t.test('canonical hash is order-independent and value-sensitive', async t => { + const a = canonicalHash({ foo: { dependencies: { a: '1', b: '2' } }, bar: { dependencies: { c: '3' } } }) + const b = canonicalHash({ bar: { dependencies: { c: '3' } }, foo: { dependencies: { b: '2', a: '1' } } }) + t.equal(a, b, 'key order does not change the hash') + + const c = canonicalHash({ foo: { dependencies: { a: '1.0.0' } } }) + t.not(a, c, 'value changes change the hash') + t.match(a, /^sha512-/, 'uses sha512 digest encoding') + + t.equal(canonicalStringify({ b: 1, a: 2 }), '{"a":2,"b":1}', 'sorts keys') + t.equal(canonicalStringify({ a: [3, 1] }), '{"a":[3,1]}', 'preserves array order') +}) + +t.test('constructor stores hash of present field', async t => { + const raw = { foo: { dependencies: { bar: '^1' } } } + t.equal(new PackageExtensions(raw).hash, canonicalHash(raw), 'instance hash matches canonicalHash') +}) diff --git a/workspaces/arborist/test/patch.js b/workspaces/arborist/test/patch.js new file mode 100644 index 0000000000000..652d7252f00a1 --- /dev/null +++ b/workspaces/arborist/test/patch.js @@ -0,0 +1,143 @@ +const t = require('tap') +const { readFileSync, existsSync } = require('node:fs') +const { resolve } = require('node:path') +const { createTwoFilesPatch } = require('diff') +const { applyPatchToDir, patchIntegrity } = require('../lib/patch.js') + +// build a git-style unified diff for a single file change +const filePatch = (file, before, after) => { + let p = createTwoFilesPatch(`a/${file}`, `b/${file}`, before, after, '', '') + .replace('===================================================================\n', '') + if (before === '') { + p = p.replace(`--- a/${file}\t`, '--- /dev/null\t') + } + if (after === '') { + p = p.replace(`+++ b/${file}\t`, '+++ /dev/null\t') + } + return p +} + +t.test('modifies an existing file', async t => { + const dir = t.testdir({ 'index.js': 'const v = 1\n' }) + await applyPatchToDir({ patch: filePatch('index.js', 'const v = 1\n', 'const v = 2\n'), cwd: dir }) + t.equal(readFileSync(resolve(dir, 'index.js'), 'utf8'), 'const v = 2\n') +}) + +t.test('creates a new file', async t => { + const dir = t.testdir({ 'index.js': 'x\n' }) + await applyPatchToDir({ patch: filePatch('added.js', '', 'new\n'), cwd: dir }) + t.equal(readFileSync(resolve(dir, 'added.js'), 'utf8'), 'new\n') +}) + +t.test('deletes a file', async t => { + const dir = t.testdir({ 'gone.js': 'bye\n' }) + await applyPatchToDir({ patch: filePatch('gone.js', 'bye\n', ''), cwd: dir }) + t.notOk(existsSync(resolve(dir, 'gone.js')), 'file removed') +}) + +t.test('creates nested directories for new files', async t => { + const dir = t.testdir({}) + await applyPatchToDir({ patch: filePatch('lib/deep/x.js', '', 'deep\n'), cwd: dir }) + t.equal(readFileSync(resolve(dir, 'lib/deep/x.js'), 'utf8'), 'deep\n') +}) + +t.test('empty patch content is a no-op', async t => { + const dir = t.testdir({ 'index.js': 'unchanged\n' }) + await applyPatchToDir({ patch: '', cwd: dir }) + t.equal(readFileSync(resolve(dir, 'index.js'), 'utf8'), 'unchanged\n') +}) + +t.test('throws on context drift (fuzz 0)', async t => { + const dir = t.testdir({ 'index.js': 'totally different content\n' }) + await t.rejects( + applyPatchToDir({ patch: filePatch('index.js', 'const v = 1\n', 'const v = 2\n'), cwd: dir }), + { code: 'EPATCHFAILED' } + ) +}) + +t.test('refuses to write outside the package directory', async t => { + const dir = t.testdir({ 'index.js': 'x\n' }) + await t.rejects( + applyPatchToDir({ patch: filePatch('../escape.js', '', 'pwned\n'), cwd: dir }), + { code: 'EPATCHUNSAFE' } + ) +}) + +t.test('refuses an absolute-path target', async t => { + const dir = t.testdir({ 'index.js': 'x\n' }) + await t.rejects( + applyPatchToDir({ patch: filePatch('/tmp/escape.js', '', 'pwned\n'), cwd: dir }), + { code: 'EPATCHUNSAFE' } + ) +}) + +t.test('refuses to delete outside the package directory', async t => { + const dir = t.testdir({ 'index.js': 'x\n' }) + await t.rejects( + applyPatchToDir({ patch: filePatch('../escape.js', 'secret\n', ''), cwd: dir }), + { code: 'EPATCHUNSAFE' } + ) +}) + +t.test('delete fails when the file drifted from the diff', async t => { + const dir = t.testdir({ 'gone.js': 'different content\n' }) + await t.rejects( + applyPatchToDir({ patch: filePatch('gone.js', 'original\n', ''), cwd: dir }), + { code: 'EPATCHFAILED' } + ) +}) + +t.test('delete fails when the target is missing', async t => { + const dir = t.testdir({}) + await t.rejects( + applyPatchToDir({ patch: filePatch('gone.js', 'original\n', ''), cwd: dir }), + { code: 'EPATCHFAILED' } + ) +}) + +t.test('add fails when the file already exists', async t => { + const dir = t.testdir({ 'added.js': 'already here\n' }) + await t.rejects( + applyPatchToDir({ patch: filePatch('added.js', '', 'new\n'), cwd: dir }), + { code: 'EPATCHFAILED' } + ) +}) + +t.test('modify fails when the target is missing', async t => { + const dir = t.testdir({}) + await t.rejects( + applyPatchToDir({ patch: filePatch('index.js', 'a\n', 'b\n'), cwd: dir }), + { code: 'EPATCHFAILED' } + ) +}) + +t.test('re-codes a raw filesystem error as EPATCHFAILED', async t => { + // "foo" exists as a file, so creating "foo/bar.js" makes mkdir throw a raw FS error + const dir = t.testdir({ foo: 'i am a file, not a directory\n' }) + await t.rejects( + applyPatchToDir({ patch: filePatch('foo/bar.js', '', 'new\n'), cwd: dir }), + { code: 'EPATCHFAILED' } + ) +}) + +t.test('patchIntegrity is stable and content-addressed', t => { + const a = patchIntegrity('hello') + const b = patchIntegrity(Buffer.from('hello')) + const c = patchIntegrity('world') + t.equal(a, b, 'string and buffer match') + t.match(a, /^sha512-/, 'is a sha512 SSRI') + t.not(a, c, 'different content -> different hash') + t.end() +}) + +t.test('round-trips a multi-file diff', async t => { + const dir = t.testdir({ 'a.js': 'aaa\n', 'del.js': 'd\n' }) + const patch = + filePatch('a.js', 'aaa\n', 'AAA\n') + + filePatch('b.js', '', 'bbb\n') + + filePatch('del.js', 'd\n', '') + await applyPatchToDir({ patch, cwd: dir }) + t.equal(readFileSync(resolve(dir, 'a.js'), 'utf8'), 'AAA\n') + t.equal(readFileSync(resolve(dir, 'b.js'), 'utf8'), 'bbb\n') + t.notOk(existsSync(resolve(dir, 'del.js'))) +}) diff --git a/workspaces/arborist/test/patched-dependencies-resolve.js b/workspaces/arborist/test/patched-dependencies-resolve.js new file mode 100644 index 0000000000000..d213b3cf87019 --- /dev/null +++ b/workspaces/arborist/test/patched-dependencies-resolve.js @@ -0,0 +1,431 @@ +// Exercises resolvePatchedDependencies, which is not exported, so it must be driven through Arborist. +// We build a real ideal tree against a t.testdir fixture and assert that node.patched is set on matches and that the documented error codes throw. +const t = require('tap') +const Arborist = require('../lib/arborist') + +// a trivial but valid unified diff used as the on-disk patch contents +const PATCH = '--- a/index.js\n+++ b/index.js\n@@ -1 +1 @@\n-old\n+new\n' + +// build a lockfileVersion 3 entry for a registry dependency +const lockEntry = (name, version) => ({ + version, + resolved: `https://registry.npmjs.org/${name}/-/${name}-${version}.tgz`, + integrity: 'sha512-deadbeef', +}) + +// build an offline ideal tree for a fixture directory, so registry deps need no network +const buildIdeal = (path, opts = {}) => + new Arborist({ path, offline: true, ...opts }).buildIdealTree() + +t.test('attaches node.patched on an exact match', async t => { + const path = t.testdir({ + 'fix.patch': PATCH, + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { dep: '^1.0.0' }, + patchedDependencies: { 'dep@1.0.0': 'fix.patch' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'root', version: '1.0.0', dependencies: { dep: '^1.0.0' } }, + 'node_modules/dep': lockEntry('dep', '1.0.0'), + }, + }), + node_modules: { + dep: { 'package.json': JSON.stringify({ name: 'dep', version: '1.0.0' }) }, + }, + }) + + const tree = await buildIdeal(path) + const dep = tree.inventory.query('name', 'dep').values().next().value + t.ok(dep, 'dep node exists') + t.ok(dep.patched, 'node.patched is set') + t.equal(dep.patched.path, 'fix.patch', 'records the relative patch path') + t.match(dep.patched.integrity, /^sha512-/, 'records the sha512 integrity') +}) + +t.test('no patchedDependencies is a no-op', async t => { + // empty patchedDependencies hits the early return guard + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + patchedDependencies: {}, + }), + }) + const tree = await buildIdeal(path) + for (const node of tree.inventory.values()) { + t.notOk(node.patched, `${node.name} is not patched`) + } +}) + +t.test('marks patchRemoved when a lockfile-patched node loses its selector', async t => { + // the lockfile records a patch but package.json declares none, so the node must be re-extracted + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { dep: '^1.0.0' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + lockfileVersion: 4, + requires: true, + packages: { + '': { name: 'root', version: '1.0.0', dependencies: { dep: '^1.0.0' } }, + 'node_modules/dep': { + ...lockEntry('dep', '1.0.0'), + patched: { path: 'patches/dep@1.0.0.patch', integrity: 'sha512-old' }, + }, + }, + }), + node_modules: { + dep: { 'package.json': JSON.stringify({ name: 'dep', version: '1.0.0' }) }, + }, + }) + + const tree = await buildIdeal(path) + const dep = tree.inventory.query('name', 'dep').values().next().value + t.notOk(dep.patched, 'the stale patch record is cleared') + t.ok(dep.patchRemoved, 'the node is marked for re-extraction') +}) + +t.test('shares integrity cache across selectors pointing at one file', async t => { + // two selectors reference the same patch path, so the file is read once and both matched nodes get the identical integrity value + const path = t.testdir({ + 'shared.patch': PATCH, + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { a: '^1.0.0', b: '^1.0.0' }, + patchedDependencies: { 'a@1.0.0': 'shared.patch', 'b@1.0.0': 'shared.patch' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'root', version: '1.0.0', dependencies: { a: '^1.0.0', b: '^1.0.0' } }, + 'node_modules/a': lockEntry('a', '1.0.0'), + 'node_modules/b': lockEntry('b', '1.0.0'), + }, + }), + node_modules: { + a: { 'package.json': JSON.stringify({ name: 'a', version: '1.0.0' }) }, + b: { 'package.json': JSON.stringify({ name: 'b', version: '1.0.0' }) }, + }, + }) + + const tree = await buildIdeal(path) + const a = tree.inventory.query('name', 'a').values().next().value + const b = tree.inventory.query('name', 'b').values().next().value + t.ok(a.patched && b.patched, 'both nodes are patched') + t.equal(a.patched.integrity, b.patched.integrity, 'integrity is shared from the cache') + t.equal(a.patched.path, 'shared.patch') + t.equal(b.patched.path, 'shared.patch') +}) + +t.test('EPATCHWORKSPACE when a workspace member declares patchedDependencies', async t => { + const path = t.testdir({ + 'fix.patch': PATCH, + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + workspaces: ['workspace-a'], + // a root entry is needed so the function does not early-return + patchedDependencies: { 'x@1.0.0': 'fix.patch' }, + }), + 'workspace-a': { + 'package.json': JSON.stringify({ + name: 'workspace-a', + version: '1.0.0', + patchedDependencies: { 'x@1.0.0': 'fix.patch' }, + }), + }, + }) + + await t.rejects(buildIdeal(path), { code: 'EPATCHWORKSPACE', workspace: 'workspace-a' }) +}) + +t.test('skips a clean workspace member and patches a root dep', async t => { + const path = t.testdir({ + 'fix.patch': PATCH, + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + workspaces: ['workspace-a'], + dependencies: { dep: '^1.0.0' }, + patchedDependencies: { 'dep@1.0.0': 'fix.patch' }, + }), + 'workspace-a': { + 'package.json': JSON.stringify({ name: 'workspace-a', version: '1.0.0' }), + }, + 'package-lock.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'root', version: '1.0.0', dependencies: { dep: '^1.0.0' }, workspaces: ['workspace-a'] }, + 'workspace-a': { name: 'workspace-a', version: '1.0.0' }, + 'node_modules/workspace-a': { link: true, resolved: 'workspace-a' }, + 'node_modules/dep': lockEntry('dep', '1.0.0'), + }, + }), + node_modules: { + 'workspace-a': t.fixture('symlink', '../workspace-a'), + dep: { 'package.json': JSON.stringify({ name: 'dep', version: '1.0.0' }) }, + }, + }) + + const tree = await buildIdeal(path) + const dep = tree.inventory.query('name', 'dep').values().next().value + t.ok(dep.patched, 'root dep is patched even though a workspace member exists') +}) + +t.test('EPATCHNONREGISTRY when the matched node is not a registry dependency', async t => { + // a file: dependency resolves to a Link/non-registry node and cannot be patched + const path = t.testdir({ + 'fix.patch': PATCH, + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { dep: 'file:./localdep' }, + patchedDependencies: { 'dep@1.0.0': 'fix.patch' }, + }), + localdep: { + 'package.json': JSON.stringify({ name: 'dep', version: '1.0.0' }), + }, + node_modules: { + dep: { 'package.json': JSON.stringify({ name: 'dep', version: '1.0.0' }) }, + }, + }) + + await t.rejects(buildIdeal(path), { code: 'EPATCHNONREGISTRY', node: 'dep' }) +}) + +t.test('EPATCHUNUSED when a registered patch matches no node', async t => { + const path = t.testdir({ + 'fix.patch': PATCH, + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { dep: '^1.0.0' }, + // ghost has no installed node so it is unused + patchedDependencies: { 'ghost@1.0.0': 'fix.patch' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'root', version: '1.0.0', dependencies: { dep: '^1.0.0' } }, + 'node_modules/dep': lockEntry('dep', '1.0.0'), + }, + }), + node_modules: { + dep: { 'package.json': JSON.stringify({ name: 'dep', version: '1.0.0' }) }, + }, + }) + + await t.rejects(buildIdeal(path), { code: 'EPATCHUNUSED', unused: ['ghost@1.0.0'] }) +}) + +t.test('uninstalling a patched package drops its orphaned patch entry', async t => { + // npm uninstall removes the node but leaves the patchedDependencies entry, which would otherwise be EPATCHUNUSED + const path = t.testdir({ + 'fix.patch': PATCH, + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { dep: '^1.0.0' }, + patchedDependencies: { 'dep@1.0.0': 'fix.patch' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'root', version: '1.0.0', dependencies: { dep: '^1.0.0' } }, + 'node_modules/dep': lockEntry('dep', '1.0.0'), + }, + }), + node_modules: { + dep: { 'package.json': JSON.stringify({ name: 'dep', version: '1.0.0' }) }, + }, + }) + + const tree = await buildIdeal(path, { rm: ['dep'] }) + t.notOk(tree.inventory.query('name', 'dep').size, 'dep node is removed') + t.notOk(tree.package.patchedDependencies, 'the orphaned patch entry is dropped') +}) + +t.test('uninstall keeps patch entries for packages that remain', async t => { + // removing one package must not drop another package's still-used patch + const path = t.testdir({ + 'a.patch': PATCH, + 'b.patch': PATCH, + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { a: '^1.0.0', b: '^1.0.0' }, + patchedDependencies: { 'a@1.0.0': 'a.patch', 'b@1.0.0': 'b.patch' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'root', version: '1.0.0', dependencies: { a: '^1.0.0', b: '^1.0.0' } }, + 'node_modules/a': lockEntry('a', '1.0.0'), + 'node_modules/b': lockEntry('b', '1.0.0'), + }, + }), + node_modules: { + a: { 'package.json': JSON.stringify({ name: 'a', version: '1.0.0' }) }, + b: { 'package.json': JSON.stringify({ name: 'b', version: '1.0.0' }) }, + }, + }) + + const tree = await buildIdeal(path, { rm: ['a'] }) + t.notOk(tree.inventory.query('name', 'a').size, 'a node is removed') + t.same(tree.package.patchedDependencies, { 'b@1.0.0': 'b.patch' }, 'b patch entry survives') + const b = tree.inventory.query('name', 'b').values().next().value + t.ok(b.patched, 'b is still patched') +}) + +t.test('uninstall does not drop a patch when the package survives as a transitive dep', async t => { + // dep is a direct dep being removed but stays in the tree under parent, so its patch is still used + const path = t.testdir({ + 'fix.patch': PATCH, + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { dep: '^1.0.0', parent: '^1.0.0' }, + patchedDependencies: { 'dep@1.0.0': 'fix.patch' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'root', version: '1.0.0', dependencies: { dep: '^1.0.0', parent: '^1.0.0' } }, + 'node_modules/dep': lockEntry('dep', '1.0.0'), + 'node_modules/parent': { + ...lockEntry('parent', '1.0.0'), + dependencies: { dep: '^1.0.0' }, + }, + }, + }), + node_modules: { + dep: { 'package.json': JSON.stringify({ name: 'dep', version: '1.0.0' }) }, + parent: { + 'package.json': JSON.stringify({ + name: 'parent', + version: '1.0.0', + dependencies: { dep: '^1.0.0' }, + }), + }, + }, + }) + + const tree = await buildIdeal(path, { rm: ['dep'] }) + const dep = tree.inventory.query('name', 'dep').values().next().value + t.ok(dep, 'dep node survives as a transitive dependency') + t.ok(dep.patched, 'dep is still patched') + t.same(tree.package.patchedDependencies, { 'dep@1.0.0': 'fix.patch' }, 'patch entry is kept') +}) + +t.test('allowUnusedPatches:true suppresses EPATCHUNUSED', async t => { + const path = t.testdir({ + 'fix.patch': PATCH, + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { dep: '^1.0.0' }, + patchedDependencies: { 'ghost@1.0.0': 'fix.patch' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'root', version: '1.0.0', dependencies: { dep: '^1.0.0' } }, + 'node_modules/dep': lockEntry('dep', '1.0.0'), + }, + }), + node_modules: { + dep: { 'package.json': JSON.stringify({ name: 'dep', version: '1.0.0' }) }, + }, + }) + + const tree = await buildIdeal(path, { allowUnusedPatches: true }) + for (const node of tree.inventory.values()) { + t.notOk(node.patched, `${node.name} is not patched`) + } +}) + +t.test('EPATCHNOTFOUND when the patch file is missing on disk', async t => { + // selector matches an installed node but the referenced patch file is absent + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { dep: '^1.0.0' }, + patchedDependencies: { 'dep@1.0.0': 'missing.patch' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'root', version: '1.0.0', dependencies: { dep: '^1.0.0' } }, + 'node_modules/dep': lockEntry('dep', '1.0.0'), + }, + }), + node_modules: { + dep: { 'package.json': JSON.stringify({ name: 'dep', version: '1.0.0' }) }, + }, + }) + + await t.rejects(buildIdeal(path), { code: 'EPATCHNOTFOUND', path: 'missing.patch' }) +}) + +t.test('EPATCHUNSAFE when the patch path escapes the project', async t => { + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + dependencies: { dep: '^1.0.0' }, + patchedDependencies: { 'dep@1.0.0': '../outside.patch' }, + }), + 'package-lock.json': JSON.stringify({ + name: 'root', + version: '1.0.0', + lockfileVersion: 3, + requires: true, + packages: { + '': { name: 'root', version: '1.0.0', dependencies: { dep: '^1.0.0' } }, + 'node_modules/dep': lockEntry('dep', '1.0.0'), + }, + }), + node_modules: { + dep: { 'package.json': JSON.stringify({ name: 'dep', version: '1.0.0' }) }, + }, + }) + + await t.rejects(buildIdeal(path), { code: 'EPATCHUNSAFE' }) +}) diff --git a/workspaces/arborist/test/patched-dependencies.js b/workspaces/arborist/test/patched-dependencies.js new file mode 100644 index 0000000000000..ea7d95211cbe1 --- /dev/null +++ b/workspaces/arborist/test/patched-dependencies.js @@ -0,0 +1,52 @@ +const t = require('tap') +const { parseSelector, matchSelector } = require('../lib/patched-dependencies.js') + +t.test('parseSelector', t => { + t.strictSame(parseSelector('lodash'), { name: 'lodash', spec: null }) + t.strictSame(parseSelector('lodash@4.17.21'), { name: 'lodash', spec: '4.17.21' }) + t.strictSame(parseSelector('lodash@^4.0.0'), { name: 'lodash', spec: '^4.0.0' }) + t.strictSame(parseSelector('@babel/core@7.23.0'), { name: '@babel/core', spec: '7.23.0' }) + t.strictSame(parseSelector('@babel/core'), { name: '@babel/core', spec: null }) + t.end() +}) + +const sel = (name, spec) => ({ name, spec, key: spec ? `${name}@${spec}` : name }) + +t.test('exact wins over range and name-only', t => { + const selectors = [sel('lodash', '4.17.21'), sel('lodash', '^4.0.0'), sel('lodash', null)] + t.equal(matchSelector(selectors, { name: 'lodash', version: '4.17.21' }).key, 'lodash@4.17.21') + t.end() +}) + +t.test('range wins over name-only', t => { + const selectors = [sel('lodash', '^4.0.0'), sel('lodash', null)] + t.equal(matchSelector(selectors, { name: 'lodash', version: '4.5.0' }).key, 'lodash@^4.0.0') + t.end() +}) + +t.test('name-only is the fallback', t => { + const selectors = [sel('lodash', null)] + t.equal(matchSelector(selectors, { name: 'lodash', version: '3.0.0' }).key, 'lodash') + t.end() +}) + +t.test('most specific (subset) range wins regardless of order', t => { + const wideFirst = [sel('x', '>=1.0.0 <3.0.0'), sel('x', '>=1.5.0 <2.0.0')] + t.equal(matchSelector(wideFirst, { name: 'x', version: '1.7.0' }).key, 'x@>=1.5.0 <2.0.0') + const narrowFirst = [sel('x', '>=1.5.0 <2.0.0'), sel('x', '>=1.0.0 <3.0.0')] + t.equal(matchSelector(narrowFirst, { name: 'x', version: '1.7.0' }).key, 'x@>=1.5.0 <2.0.0') + t.end() +}) + +t.test('ambiguous overlapping ranges throw', t => { + const selectors = [sel('x', '>=1.0.0 <2.0.0'), sel('x', '>=1.5.0 <3.0.0')] + t.throws(() => matchSelector(selectors, { name: 'x', version: '1.7.0' }), { code: 'EPATCHAMBIGUOUS' }) + t.end() +}) + +t.test('no match returns null', t => { + const selectors = [sel('lodash', '4.17.21')] + t.equal(matchSelector(selectors, { name: 'lodash', version: '5.0.0' }), null) + t.equal(matchSelector(selectors, { name: 'other', version: '1.0.0' }), null) + t.end() +}) diff --git a/workspaces/arborist/test/place-dep.js b/workspaces/arborist/test/place-dep.js index be98835fcc1f5..14bb4bfc24dbf 100644 --- a/workspaces/arborist/test/place-dep.js +++ b/workspaces/arborist/test/place-dep.js @@ -33,7 +33,7 @@ t.test('placement tests', t => { preferDedupe = false, // --force set? force = false, - // is this the thing the user is explicitly installing? + // is this the thing that the user is explicitly installing? explicitRequest, // the names passed to `npm update foo bar baz` for example. updateNames = [], @@ -1516,7 +1516,7 @@ t.test('placement tests', t => { nodeLoc: '', }) - // same as above, but now the existing one has 3, replacment has 5 + // same as above, but now the existing one has 3, replacement has 5 // v@4 -> PEER(a@1||2) // y@1 -> PEER(d@1) // a@1 -> PEER(b@1) diff --git a/workspaces/arborist/test/printable.js b/workspaces/arborist/test/printable.js index cbdbbbfcaaa07..7729d93cc4d2b 100644 --- a/workspaces/arborist/test/printable.js +++ b/workspaces/arborist/test/printable.js @@ -229,7 +229,7 @@ t.test('virtual roots are shown with their sourceReference', t => { t.end() }) -t.test('broken links dont break the printing', t => { +t.test('broken links do not break the printing', t => { const tree = new Node({ path: '/home/user/projects/root', }) @@ -290,7 +290,7 @@ t.test('show workspaces in printable node output', t => { t.end() }) -t.test('show bundle/shrinkwrap info', t => { +t.test('show bundle info', t => { const tree = new Node({ path: '/path/to/root', pkg: { @@ -298,7 +298,6 @@ t.test('show bundle/shrinkwrap info', t => { version: '1.2.3', dependencies: { bundler: '', - wrapper: '', a: '1', b: '2', c: '3', @@ -321,23 +320,6 @@ t.test('show bundle/shrinkwrap info', t => { }, ], }, - { - pkg: { - name: 'wrapper', - version: '1.2.3', - dependencies: { - a: '1', - }, - _hasShrinkwrap: true, - }, - hasShrinkwrap: true, - children: [ - { - pkg: { name: 'a', version: '1.2.3' }, - integrity: 'a123', - }, - ], - }, { pkg: { name: 'a', version: '1.2.3' }, integrity: 'a123', diff --git a/workspaces/arborist/test/query-selector-all.js b/workspaces/arborist/test/query-selector-all.js index d1b9b9acb4674..3886efc334d0c 100644 --- a/workspaces/arborist/test/query-selector-all.js +++ b/workspaces/arborist/test/query-selector-all.js @@ -472,7 +472,7 @@ t.test('query-selector-all', async t => { ['#a > :root', []], ['#a ~ :root', []], - // pseudo miscelaneous + // pseudo miscellaneous [':empty', [ '@npmcli/abbrev@2.0.0-beta.45', 'a@1.0.0', @@ -569,6 +569,7 @@ t.test('query-selector-all', async t => { 'a@1.0.0', 'b@1.0.0', 'c@1.0.0', + // TODO this should show up in the other :type tests, see lib/query-selector-all.js '@npmcli/abbrev@2.0.0-beta.45', 'abbrev@1.1.1', 'bar@2.0.0', @@ -596,6 +597,22 @@ t.test('query-selector-all', async t => { 'bar@1.4.0', 'moo@3.0.0', ]], + [':type(registry)', [ + 'a@1.0.0', + 'abbrev@1.1.1', + 'b@1.0.0', + 'bar@2.0.0', + 'baz@1.0.0', + 'dash-separated-pkg@1.0.0', + 'dasher@2.0.0', + 'foo@2.2.2', + 'bar@1.4.0', + 'ipsum@npm:sit@1.0.0', + 'lorem@1.0.0', + 'moo@3.0.0', + 'recur@1.0.0', + 'sive@1.0.0', + ]], [':type(git)', []], // path pseudo @@ -1018,4 +1035,119 @@ t.test('query-selector-all', async t => { ['#a, #bar:semver(2), #foo:semver(2.2.2)', ['a@1.0.0', 'bar@2.0.0', 'foo@2.2.2']], ['#b *', ['a@1.0.0', 'bar@2.0.0', 'baz@1.0.0', 'lorem@1.0.0', 'moo@3.0.0']], ]) + + // :outdated combined with --before and min-release-age-exclude. + // bar's 2.0.0 was published today, so `before: yesterday` normally filters it + // out and bar drops off the outdated list. Excluding bar bypasses the filter + // for that package so its newer version is considered again. + await t.test(':outdated honors min-release-age-exclude (exact name)', async t => { + const res = await querySelectorAll(tree, ':outdated', { + before: yesterday, + minReleaseAgeExclude: ['bar'], + }) + t.same(res, [ + 'abbrev@1.1.1', + 'baz@1.0.0', + 'dash-separated-pkg@1.0.0', + 'bar@1.4.0', // not filtered by before because bar is excluded + ], 'excluded package is not filtered by before') + }) + + await t.test(':outdated honors min-release-age-exclude (glob)', async t => { + const res = await querySelectorAll(tree, ':outdated', { + before: yesterday, + minReleaseAgeExclude: ['b*'], + }) + t.same(res, [ + 'abbrev@1.1.1', + 'baz@1.0.0', + 'dash-separated-pkg@1.0.0', + 'bar@1.4.0', // glob matches bar, bypassing the before filter + ], 'glob pattern excludes bar from the before filter') + }) +}) +t.test('linked strategy: :root > * excludes transitive deps and store nodes', async t => { + /* + fixture tree (linked strategy layout): + + linked-test@1.0.0 + ├── nopt@7.2.1 (symlink -> .store/nopt-hash/node_modules/nopt) + ├── ini@4.1.3 (symlink -> .store/ini-hash/node_modules/ini) + └── .store/ + ├── nopt-hash/ + │ └── node_modules/ + │ ├── nopt@7.2.1 (actual) + │ └── abbrev (symlink -> ../../abbrev-hash/node_modules/abbrev) + ├── ini-hash/ + │ └── node_modules/ + │ └── ini@4.1.3 (actual) + └── abbrev-hash/ + └── node_modules/ + └── abbrev@2.0.0 (actual) + */ + + const path = t.testdir({ + node_modules: { + nopt: t.fixture('symlink', '.store/nopt-hash/node_modules/nopt'), + ini: t.fixture('symlink', '.store/ini-hash/node_modules/ini'), + '.store': { + 'nopt-hash': { + node_modules: { + nopt: { + 'package.json': JSON.stringify({ + name: 'nopt', + version: '7.2.1', + dependencies: { abbrev: '^2.0.0' }, + }), + }, + abbrev: t.fixture('symlink', '../../abbrev-hash/node_modules/abbrev'), + }, + }, + 'ini-hash': { + node_modules: { + ini: { + 'package.json': JSON.stringify({ + name: 'ini', + version: '4.1.3', + }), + }, + }, + }, + 'abbrev-hash': { + node_modules: { + abbrev: { + 'package.json': JSON.stringify({ + name: 'abbrev', + version: '2.0.0', + }), + }, + }, + }, + }, + }, + 'package.json': JSON.stringify({ + name: 'linked-test', + version: '1.0.0', + dependencies: { + nopt: '^7.0.0', + ini: '^4.0.0', + }, + }), + }) + + const arb = new Arborist({ path }) + const tree = await arb.loadActual() + + const rootChildren = await querySelectorAll(tree, ':root > *') + t.same(rootChildren, [ + 'ini@4.1.3', + 'nopt@7.2.1', + ], ':root > * should only return direct dependencies, not transitive deps or store nodes') + + const rootDescendants = await querySelectorAll(tree, ':root *') + t.same(rootDescendants, [ + 'abbrev@2.0.0', + 'ini@4.1.3', + 'nopt@7.2.1', + ], ':root * should return all descendants including transitive deps') }) diff --git a/workspaces/arborist/test/release-age-exclude.js b/workspaces/arborist/test/release-age-exclude.js new file mode 100644 index 0000000000000..71b15a1ab7997 --- /dev/null +++ b/workspaces/arborist/test/release-age-exclude.js @@ -0,0 +1,71 @@ +const t = require('tap') +const npa = require('npm-package-arg') +const { isReleaseAgeExcluded, trustedSpecName } = require('../lib/release-age-exclude.js') + +t.test('returns false when there are no patterns', t => { + t.equal(isReleaseAgeExcluded('lodash', []), false, 'empty array') + t.equal(isReleaseAgeExcluded('lodash', undefined), false, 'undefined') + t.equal(isReleaseAgeExcluded('lodash', null), false, 'null') + t.end() +}) + +t.test('returns false when the name is missing', t => { + t.equal(isReleaseAgeExcluded(undefined, ['*']), false, 'undefined name') + t.equal(isReleaseAgeExcluded('', ['*']), false, 'empty name') + t.end() +}) + +t.test('matches exact package names', t => { + t.equal(isReleaseAgeExcluded('lodash', ['lodash']), true, 'unscoped exact') + t.equal(isReleaseAgeExcluded('@myorg/utils', ['@myorg/utils']), true, 'scoped exact') + t.equal(isReleaseAgeExcluded('react', ['lodash', 'react', 'vue']), true, 'one of many') + t.equal(isReleaseAgeExcluded('react-dom', ['react']), false, 'no partial match') + t.end() +}) + +t.test('matches glob patterns', t => { + t.equal(isReleaseAgeExcluded('@myorg/utils', ['@myorg/*']), true, 'scope wildcard') + t.equal(isReleaseAgeExcluded('@myorg/shared-utils', ['@myorg/*']), true, 'scope wildcard 2') + t.equal(isReleaseAgeExcluded('@other/utils', ['@myorg/*']), false, 'different scope') + t.equal(isReleaseAgeExcluded('lodash', ['lo*']), true, 'prefix wildcard') + t.equal(isReleaseAgeExcluded('react', ['@myorg/*', 'lodash']), false, 'no pattern matches') + t.end() +}) + +t.test('negation and comment patterns cannot invert into a match-all', t => { + // A leading `!` must be treated literally (no package name can contain `!`), + // so it exempts nothing rather than everything-but-the-listed-name. Likewise + // a leading `#` must not be swallowed as a comment. + t.equal(isReleaseAgeExcluded('lodash', ['!react']), false, 'negation does not match others') + t.equal(isReleaseAgeExcluded('react', ['!react']), false, 'negation does not match itself') + t.equal(isReleaseAgeExcluded('lodash', ['#lodash']), false, 'comment matches nothing') + t.end() +}) + +t.test('trustedSpecName unwraps npm: aliases to the resolved package', t => { + t.equal(trustedSpecName(npa.resolve('lodash', '^4.17.0')), 'lodash', 'plain registry range') + t.equal(trustedSpecName(npa.resolve('@scope/pkg', '^1.0.0')), '@scope/pkg', 'scoped registry range') + // For an alias the fetched package is the alias target, not the alias key. + t.equal( + trustedSpecName(npa.resolve('@myorg/x', 'npm:attacker-pkg@1.0.0')), + 'attacker-pkg', + 'alias resolves to the underlying package name' + ) + t.equal(trustedSpecName(undefined), undefined, 'missing spec') + t.end() +}) + +t.test('an alias key cannot match an exclude pattern for its target', t => { + // Victim excludes their own scope; a malicious dep aliases an attacker package + // under a name in that scope (`"@myorg/x": "npm:attacker-pkg@1"`). The exempt + // decision must be keyed on the resolved target, not the alias key, so the + // age filter is NOT disabled for attacker-pkg. + const spec = npa.resolve('@myorg/x', 'npm:attacker-pkg@1.0.0') + t.equal(isReleaseAgeExcluded(spec.name, ['@myorg/*']), true, + 'the raw alias key would wrongly match') + t.equal(isReleaseAgeExcluded(trustedSpecName(spec), ['@myorg/*']), false, + 'the trusted target name does not match') + t.end() +}) + +t.end() diff --git a/workspaces/arborist/test/reset-dep-flags.js b/workspaces/arborist/test/reset-dep-flags.js deleted file mode 100644 index 6755c743c4a62..0000000000000 --- a/workspaces/arborist/test/reset-dep-flags.js +++ /dev/null @@ -1,17 +0,0 @@ -const t = require('tap') -const resetDepFlags = require('../lib/reset-dep-flags.js') - -const tree = { - inventory: new Map([ - ['x', {}], - ['y', { extraneous: false, dev: false, devOptional: false, peer: false, optional: false }], - ]), -} - -resetDepFlags(tree) -t.match(tree, { - inventory: new Map([ - ['x', { extraneous: true, dev: true, devOptional: true, peer: true, optional: true }], - ['y', { extraneous: true, dev: true, devOptional: true, peer: true, optional: true }], - ]), -}) diff --git a/workspaces/arborist/test/script-allowed.js b/workspaces/arborist/test/script-allowed.js new file mode 100644 index 0000000000000..615ffaba7140e --- /dev/null +++ b/workspaces/arborist/test/script-allowed.js @@ -0,0 +1,721 @@ +const t = require('tap') +const isScriptAllowed = require('../lib/script-allowed.js') +const { trustedDisplay } = isScriptAllowed + +// Test nodes default to a consistent registry-tarball shape: the resolved +// URL's name+version match the supplied name+version. Tests that need to +// simulate manifest confusion (mismatched URL) can override `resolved` +// independently. +const node = (overrides = {}) => { + const name = overrides.name ?? overrides.packageName ?? 'pkg' + const packageName = overrides.packageName ?? name + const version = overrides.version ?? '1.0.0' + // For real aliased installs, the URL is the TARGET package's URL, so + // build the default URL from packageName, not name. + const urlPkg = packageName + return { + name, + packageName, + version, + resolved: overrides.resolved + ?? `https://registry.npmjs.org/${urlPkg}/-/${urlPkg}-${version}.tgz`, + location: overrides.location ?? `node_modules/${name}`, + ...overrides, + } +} + +t.test('returns null when no policy is set', t => { + t.equal(isScriptAllowed(node(), null), null) + t.equal(isScriptAllowed(node(), undefined), null) + t.equal(isScriptAllowed(node(), {}), null) + t.end() +}) + +t.test('registry — name-only allow', t => { + t.equal(isScriptAllowed(node({ name: 'canvas', version: '2.11.0' }), { canvas: true }), true) + t.equal(isScriptAllowed(node({ name: 'other', version: '1.0.0' }), { canvas: true }), null) + t.end() +}) + +t.test('registry — exact version match', t => { + const policy = { 'canvas@2.11.0': true } + t.equal(isScriptAllowed(node({ name: 'canvas', version: '2.11.0' }), policy), true) + t.equal(isScriptAllowed(node({ name: 'canvas', version: '2.11.1' }), policy), null) + t.end() +}) + +t.test('registry — semver range', t => { + const policy = { 'sharp@0.33.2 || 0.34.0': true } + t.equal(isScriptAllowed(node({ name: 'sharp', version: '0.33.2' }), policy), true) + t.equal(isScriptAllowed(node({ name: 'sharp', version: '0.34.0' }), policy), true) + t.equal(isScriptAllowed(node({ name: 'sharp', version: '0.33.3' }), policy), null) + t.end() +}) + +t.test('registry — version mismatch returns null', t => { + const policy = { 'canvas@2.11.0': true } + t.equal(isScriptAllowed(node({ name: 'canvas', version: '3.0.0' }), policy), null) + t.end() +}) + +t.test('alias must not match the alias name', t => { + // install: `trusted@npm:naughty@1.0.0` + // node.name === 'trusted', node.packageName === 'naughty' + const aliased = node({ name: 'trusted', packageName: 'naughty', version: '1.0.0' }) + // Key matching the alias name must NOT match. + t.equal(isScriptAllowed(aliased, { trusted: true }), null) + // Key matching the real package name DOES match. + t.equal(isScriptAllowed(aliased, { naughty: true }), true) + t.equal(isScriptAllowed(aliased, { 'naughty@1.0.0': true }), true) + t.end() +}) + +t.test('registry-style key does not match a tarball or git node', t => { + const gitNode = node({ + name: 'pkg', + version: '1.0.0', + resolved: 'git+ssh://git@github.com/foo/bar.git#deadbeefcafebabe1234567890abcdef12345678', + }) + t.equal(isScriptAllowed(gitNode, { pkg: true }), null) + t.end() +}) + +t.test('git — repo-only match by canonical ssh URL', t => { + const gitNode = node({ + name: 'bar', + packageName: 'bar', + version: '1.0.0', + resolved: 'git+ssh://git@github.com/foo/bar.git#deadbeefcafebabe1234567890abcdef12345678', + }) + // Key by repo only — name-only allow for the git source. + t.equal(isScriptAllowed(gitNode, { 'github:foo/bar': true }), true) + t.equal(isScriptAllowed(gitNode, { 'github:foo/other': true }), null) + t.end() +}) + +t.test('git — short SHA prefix matches full SHA', t => { + const gitNode = node({ + name: 'bar', + packageName: 'bar', + version: '1.0.0', + resolved: 'git+ssh://git@github.com/foo/bar.git#deadbeefcafebabe1234567890abcdef12345678', + }) + t.equal(isScriptAllowed(gitNode, { 'github:foo/bar#deadbeef': true }), true) + t.equal(isScriptAllowed(gitNode, { 'github:foo/bar#deadbee': true }), true) + t.equal(isScriptAllowed(gitNode, { 'github:foo/bar#abcdef0': true }), null) + t.end() +}) + +t.test('file path — exact resolved match', t => { + const fileNode = node({ + name: 'local-pkg', + packageName: 'local-pkg', + version: '1.0.0', + resolved: 'file:../local-pkg', + }) + t.equal(isScriptAllowed(fileNode, { 'file:../local-pkg': true }), true) + t.equal(isScriptAllowed(fileNode, { 'file:../other': true }), null) + t.end() +}) + +t.test('file path — link target matches incoming link source', t => { + const targetPath = require('node:path').resolve('local-pkg') + const target = node({ + name: 'local-pkg', + packageName: 'local-pkg', + version: '1.0.0', + }) + target.resolved = null + target.path = targetPath + target.realpath = targetPath + target.linksIn = new Set([{ resolved: 'file:../local-pkg' }]) + + t.equal(isScriptAllowed(target, { 'file:../local-pkg': true }), true) + t.equal(isScriptAllowed(target, { 'file:local-pkg': true }), true) + t.equal(isScriptAllowed(target, { 'file:../local-pkg': false }), false) + t.equal(isScriptAllowed(target, { 'file:../other': true }), null) + t.end() +}) + +t.test('file path — registry nodes do not match by install path', t => { + const reg = node({ + name: 'sharp', + packageName: 'sharp', + version: '0.33.0', + path: 'node_modules/sharp', + realpath: require('node:path').resolve('node_modules/sharp'), + linksIn: new Set(), + }) + + t.equal(isScriptAllowed(reg, { 'file:node_modules/sharp': true }), null) + t.end() +}) + +t.test('file path — empty link sets do not add install paths', t => { + const targetPath = require('node:path').resolve('local-pkg') + const target = node({ + name: 'local-pkg', + packageName: 'local-pkg', + version: '1.0.0', + }) + target.resolved = null + target.path = targetPath + target.realpath = targetPath + target.linksIn = new Set() + + t.equal(isScriptAllowed(target, { 'file:local-pkg': true }), null) + t.equal(isScriptAllowed(target, { [targetPath]: true }), null) + t.end() +}) + +t.test('directory key — npa parses absolute paths as type=directory', t => { + // npa treats absolute paths as { type: 'directory' }, which the + // matcher shares with the 'file' case. path.resolve produces a + // platform-correct absolute path so this works on Windows. + const absDir = require('node:path').resolve('local-pkg') + const dirNode = node({ + name: 'local-pkg', + packageName: 'local-pkg', + version: '1.0.0', + resolved: absDir, + }) + t.equal(isScriptAllowed(dirNode, { [absDir]: true }), true) + t.end() +}) + +t.test('local tarball key — npa parses *.tgz paths as type=file', t => { + // npa treats `*.tgz` paths as { type: 'file' }, separate from + // 'directory'. Both share the matchFileOrDir body. + const tgzNode = node({ + name: 'local-pkg', + packageName: 'local-pkg', + version: '1.0.0', + resolved: 'file:../local-pkg.tgz', + }) + t.equal(isScriptAllowed(tgzNode, { 'file:../local-pkg.tgz': true }), true) + t.end() +}) + +t.test('remote tarball — exact resolved match', t => { + const remoteNode = node({ + name: 'pkg', + packageName: 'pkg', + version: '1.0.0', + resolved: 'https://example.com/pkg.tgz', + }) + t.equal(isScriptAllowed(remoteNode, { 'https://example.com/pkg.tgz': true }), true) + t.equal(isScriptAllowed(remoteNode, { 'https://example.com/other.tgz': true }), null) + t.end() +}) + +t.test('omitLockfileRegistryResolved: name-only match via edges; version-pinned does not', t => { + // Without a resolved URL, the trusted name comes from an incoming + // dependency edge (consumer-written), not from node.location (which + // for aliases would expose the alias name and let a malicious publisher + // bypass the policy). Version isn't trustable in this case, so + // version-pinned policy entries cannot match. + const omitted = { + name: 'canvas', + packageName: 'canvas', + version: '2.11.0', + resolved: undefined, + location: 'node_modules/canvas', + edgesIn: new Set([{ name: 'canvas', spec: '^2.0.0' }]), + } + t.equal(isScriptAllowed(omitted, { canvas: true }), true) + t.equal(isScriptAllowed(omitted, { 'canvas@2.11.0': true }), null, + 'version-pinned match requires the trusted URL-derived version') + t.equal(isScriptAllowed(omitted, { 'canvas@3': true }), null) + t.end() +}) + +t.test('omitLockfileRegistryResolved + alias: location is ignored; underlying name wins', t => { + // Consumer's package.json has `"trusted": "npm:naughty@1.0.0"`. With + // omitLockfileRegistryResolved, the resolved URL is absent. The install + // location is `node_modules/trusted` (alias path). The matcher MUST + // derive the underlying name from the edge's alias subSpec, not from + // the location. + const aliasOmitted = { + name: 'trusted', + packageName: 'naughty', + version: '1.0.0', + resolved: undefined, + location: 'node_modules/trusted', + edgesIn: new Set([{ name: 'trusted', spec: 'npm:naughty@1.0.0' }]), + } + // Alias name MUST NOT match. + t.equal(isScriptAllowed(aliasOmitted, { trusted: true }), null, + 'alias name does not authorize the underlying package') + // Underlying name DOES match. + t.equal(isScriptAllowed(aliasOmitted, { naughty: true }), true, + 'underlying package name authorizes scripts') + t.end() +}) + +t.test('omit-lockfile with no edges returns null (no trusted identity)', t => { + const orphan = { + name: 'canvas', + packageName: 'canvas', + version: '1.0.0', + resolved: undefined, + location: 'node_modules/canvas', + // No edgesIn at all. + } + t.equal(isScriptAllowed(orphan, { canvas: true }), null, + 'cannot match without a trusted name source') + t.end() +}) + +t.test('deny wins on conflict', t => { + const n = node({ name: 'pkg', version: '2.0.0' }) + t.equal(isScriptAllowed(n, { 'pkg@1.0.0 || 2.0.0': true, 'pkg@2.0.0 || 3.0.0': false }), false) + t.equal(isScriptAllowed(n, { pkg: true, 'pkg@2.0.0': false }), false) + t.end() +}) + +t.test('name-only deny without overlap returns false', t => { + t.equal(isScriptAllowed(node({ name: 'core-js', version: '3.0.0' }), { 'core-js': false }), false) + t.end() +}) + +t.test('skips unparseable policy keys', t => { + t.equal( + isScriptAllowed(node({ name: 'pkg', version: '1.0.0' }), { '@@@invalid': true, pkg: true }), + true + ) + t.end() +}) + +t.test('registry — forbidden semver ranges are rejected', async t => { + const n = node({ name: 'sharp', version: '0.33.5' }) + // Caret range that DOES match version, but RFC forbids — must return null + t.equal(isScriptAllowed(n, { 'sharp@^0.33.0': true }), null) + t.equal(isScriptAllowed(n, { 'sharp@~0.33.0': true }), null) + t.equal(isScriptAllowed(n, { 'sharp@>=0.33.0': true }), null) + t.equal(isScriptAllowed(n, { 'sharp@<1.0.0': true }), null) + // Partial versions like `0.33` are ranges in semver — also rejected + t.equal(isScriptAllowed(n, { 'sharp@0.33': true }), null) + t.equal(isScriptAllowed(n, { 'sharp@0': true }), null) +}) + +t.test('registry — wildcard versions are allowed (treated as name-only)', async t => { + const n = node({ name: 'sharp', version: '0.33.5' }) + t.equal(isScriptAllowed(n, { 'sharp@*': true }), true) +}) + +t.test('registry — exact disjunction with full semver is allowed', async t => { + const n = node({ name: 'sharp', version: '0.33.2' }) + t.equal(isScriptAllowed(n, { 'sharp@0.33.2 || 0.34.0': true }), true) +}) + +t.test('registry — exact disjunction where version is not listed returns null', async t => { + const n = node({ name: 'sharp', version: '0.33.5' }) + t.equal(isScriptAllowed(n, { 'sharp@0.33.2 || 0.34.0': true }), null) +}) + +t.test('forbidden range deny does NOT win (would silently allow new versions otherwise)', async t => { + // A user wrote `sharp@^0.33.0: false` thinking they're denying all 0.33.x. + // The matcher rejects the range, so the entry is effectively absent — + // deny does not match the node, returns null (unreviewed). + const n = node({ name: 'sharp', version: '0.33.5' }) + t.equal(isScriptAllowed(n, { 'sharp@^0.33.0': false }), null) +}) + +t.test('isRegistryNode — spoofed tarball URL is NOT treated as registry', async t => { + // An attacker-controlled URL that happens to contain /-/- + // must not match a registry-style allow entry. + const spoofed = node({ + name: 'trusted', + version: '1.0.0', + resolved: 'https://evil.com/-/trusted-1.0.0.tgz', + }) + // Without a path segment before /-/, the URL is not a registry tarball + // pattern. The 'trusted@1.0.0' allow must not match. + t.equal(isScriptAllowed(spoofed, { 'trusted@1.0.0': true }), null) + t.equal(isScriptAllowed(spoofed, { trusted: true }), null) + // The user can still allow this specific URL via an exact resolved match. + t.equal( + isScriptAllowed(spoofed, { 'https://evil.com/-/trusted-1.0.0.tgz': true }), + true + ) +}) + +t.test('isRegistryNode — arborist isRegistryDependency overrides URL guessing', async t => { + // A real arborist Node has isRegistryDependency. When false, the URL + // pattern is ignored entirely. + const arboristNode = { + name: 'trusted', + packageName: 'trusted', + version: '1.0.0', + resolved: 'https://registry.npmjs.org/trusted/-/trusted-1.0.0.tgz', + isRegistryDependency: false, // edges say it came from a non-registry source + } + t.equal(isScriptAllowed(arboristNode, { 'trusted@1.0.0': true }), null) +}) + +t.test('isRegistryNode — arborist isRegistryDependency true accepts even unusual URLs', async t => { + const arboristNode = { + name: 'trusted', + packageName: 'trusted', + version: '1.0.0', + resolved: 'https://internal.corp/private-registry/trusted/-/trusted-1.0.0.tgz', + isRegistryDependency: true, // edges say it came from a configured registry + } + t.equal(isScriptAllowed(arboristNode, { 'trusted@1.0.0': true }), true) +}) + +t.test('bundled deps cannot be allowlisted (never run)', async t => { + // Bundled dependencies have inBundle=true and no independent resolved + // URL. They can never be allowlisted because matching by name@version + // from the bundled tarball would reintroduce manifest confusion. They + // always return null, and their install scripts never run. + + const bundled = { + name: 'bundled-pkg', + packageName: 'bundled-pkg', + version: '1.0.0', + resolved: undefined, + inBundle: true, + } + + // Name-only allow: must NOT match a bundled dep. + t.equal(isScriptAllowed(bundled, { 'bundled-pkg': true }), null) + // Versioned allow: must NOT match a bundled dep. + t.equal(isScriptAllowed(bundled, { 'bundled-pkg@1.0.0': true }), null) + // Disjunction allow: must NOT match a bundled dep. + t.equal(isScriptAllowed(bundled, { 'bundled-pkg@1.0.0 || 2.0.0': true }), null) + // No policy: still null (no policy = nothing to evaluate against). + t.equal(isScriptAllowed(bundled, {}), null) + t.equal(isScriptAllowed(bundled, null), null) +}) + +t.test('bundled deps: deny entry does not match either (returns null, not false)', async t => { + // A deny entry doesn't apply to bundled deps because they're outside + // the policy scope entirely. They're blocked because they never run, + // not via a policy entry. + const bundled = { + name: 'bundled-pkg', + packageName: 'bundled-pkg', + version: '1.0.0', + resolved: undefined, + inBundle: true, + } + t.equal(isScriptAllowed(bundled, { 'bundled-pkg': false }), null) +}) + +t.test('bundled dep with resolved field is still rejected', async t => { + // Defensive: even if a bundled dep somehow has a resolved URL, the + // inBundle flag wins over identity matching. + const bundledWithResolved = { + name: 'pkg', + packageName: 'pkg', + version: '1.0.0', + resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz', + inBundle: true, + } + t.equal(isScriptAllowed(bundledWithResolved, { 'pkg@1.0.0': true }), null) +}) + +t.test('inBundle: false does not affect normal matching', async t => { + // Sanity check: explicit inBundle: false behaves identically to absent. + const normal = { + name: 'pkg', + packageName: 'pkg', + version: '1.0.0', + resolved: 'https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz', + inBundle: false, + } + t.equal(isScriptAllowed(normal, { 'pkg@1.0.0': true }), true) +}) + +t.test('isolated mode (linked): bundled IsolatedNode is blocked', async t => { + // Regression guard: in isolated/linked mode the gate runs against + // IsolatedNode instances, not real Nodes. A bundled IsolatedNode must + // report inBundle so the gate blocks it even when its resolved URL + // looks like a registry identity that a name entry would otherwise + // match. Without inBundle on IsolatedNode the guard is silently + // skipped and the bundled install script runs. + const { IsolatedNode } = require('../lib/isolated-classes.js') + + const bundled = new IsolatedNode({ + inBundle: true, + location: 'node_modules/bundled-pkg', + name: 'bundled-pkg', + package: { name: 'bundled-pkg', version: '1.0.0' }, + path: '/project/node_modules/bundled-pkg', + resolved: 'https://registry.npmjs.org/bundled-pkg/-/bundled-pkg-1.0.0.tgz', + }) + + t.equal(bundled.inBundle, true, 'bundled IsolatedNode reports inBundle') + t.equal(isScriptAllowed(bundled, { 'bundled-pkg': true }), null) + t.equal(isScriptAllowed(bundled, { 'bundled-pkg@1.0.0': true }), null) + + const store = new IsolatedNode({ + isInStore: true, + isRegistryDependency: true, // carried from the source node by #externalProxy + location: 'node_modules/.store/store-pkg@1.0.0/node_modules/store-pkg', + name: 'store-pkg', + package: { name: 'store-pkg', version: '1.0.0' }, + path: '/project/node_modules/.store/store-pkg@1.0.0/node_modules/store-pkg', + resolved: 'https://registry.npmjs.org/store-pkg/-/store-pkg-1.0.0.tgz', + }) + + t.equal(store.inBundle, false, 'external store IsolatedNode is not bundled') + t.equal(isScriptAllowed(store, { 'store-pkg@1.0.0': true }), true) +}) + +t.test('manifest confusion: malicious tarball self-name cannot bypass allow entry', async t => { + // A package author publishes 'naughty' to the registry but inside the + // tarball claims `package.json#name = "trusted"` and the matching + // version. The lockfile records the registry URL for 'naughty'. + // node.packageName / node.version return the tarball's claims; the + // matcher MUST ignore both and consult only the URL. + const malicious = { + name: 'naughty', // dependency edge name (consumer's deps) + packageName: 'trusted', // tarball's self-claimed name (LIE) + version: '1.0.0', // tarball's self-claimed version + resolved: 'https://registry.npmjs.org/naughty/-/naughty-1.0.0.tgz', + location: 'node_modules/naughty', + isRegistryDependency: true, + } + + // The 'trusted' allowlist entry must NOT match this node. + t.equal(isScriptAllowed(malicious, { trusted: true }), null) + t.equal(isScriptAllowed(malicious, { 'trusted@1.0.0': true }), null) + // A 'naughty' entry (the URL-derived name) DOES match. + t.equal(isScriptAllowed(malicious, { naughty: true }), true) + t.equal(isScriptAllowed(malicious, { 'naughty@1.0.0': true }), true) +}) + +t.test('manifest confusion: malicious version claim cannot satisfy version pin', async t => { + // The tarball claims version 1.0.0 but the URL records 2.0.0. The + // matcher must trust the URL. + const malicious = { + name: 'pkg', + packageName: 'pkg', + version: '1.0.0', // tarball lie + resolved: 'https://registry.npmjs.org/pkg/-/pkg-2.0.0.tgz', + location: 'node_modules/pkg', + isRegistryDependency: true, + } + // Pin for the URL version matches. + t.equal(isScriptAllowed(malicious, { 'pkg@2.0.0': true }), true) + // Pin for the tarball's lie does NOT match. + t.equal(isScriptAllowed(malicious, { 'pkg@1.0.0': true }), null) +}) + +t.test('manifest confusion: scoped registry tarball', async t => { + const node = { + name: 'pkg', + packageName: 'totally-different', + version: '9.9.9', + resolved: 'https://registry.npmjs.org/@scope/real/-/real-1.0.0.tgz', + location: 'node_modules/@scope/real', + isRegistryDependency: true, + } + t.equal(isScriptAllowed(node, { '@scope/real': true }), true) + t.equal(isScriptAllowed(node, { '@scope/real@1.0.0': true }), true) + t.equal(isScriptAllowed(node, { 'totally-different': true }), null) +}) + +t.test('git committish: matching is one-directional (key is prefix of resolved SHA)', async t => { + // The lockfile records a 40-char SHA; the policy key has a (typically + // shorter) SHA. The trusted check is `nodeFullSha.startsWith(keyShortSha)`. + // The reverse direction must NOT match — a malformed lockfile that + // happens to record only a short committish must not let a longer key + // authorize it. + const shortNode = node({ + name: 'bar', + packageName: 'bar', + version: '1.0.0', + // Node committish is 8 chars; key committish below is longer. + resolved: 'git+ssh://git@github.com/foo/bar.git#deadbeef', + }) + // Key SHA strictly longer than the node committish: must not match. + t.equal( + isScriptAllowed(shortNode, { 'github:foo/bar#deadbeefcafebabe1234567890abcdef12345678': true }), + null + ) + // Node fully starts with key — matches normally. + const fullNode = node({ + name: 'bar', + packageName: 'bar', + version: '1.0.0', + resolved: 'git+ssh://git@github.com/foo/bar.git#deadbeefcafebabe1234567890abcdef12345678', + }) + t.equal(isScriptAllowed(fullNode, { 'github:foo/bar#deadbeef': true }), true) +}) + +t.test('git policy key against a non-git node does not match', t => { + // matchGit fast-exits when the node has no resolved or its resolved + // does not begin with `git`. + const registryNode = node({ + name: 'bar', + packageName: 'bar', + version: '1.0.0', + resolved: 'https://registry.npmjs.org/bar/-/bar-1.0.0.tgz', + }) + t.equal(isScriptAllowed(registryNode, { 'github:foo/bar': true }), null) + + const noResolved = { + name: 'bar', + packageName: 'bar', + version: '1.0.0', + resolved: undefined, + edgesIn: new Set([{ name: 'bar', spec: 'github:foo/bar' }]), + } + t.equal(isScriptAllowed(noResolved, { 'github:foo/bar': true }), null) + t.end() +}) + +t.test('git — non-hosted git URL matches via fetchSpec', t => { + // Self-hosted git server: not on GitHub/GitLab/etc, so `hosted` is + // undefined and the matcher falls back to comparing fetchSpec. + const gitNode = node({ + name: 'bar', + packageName: 'bar', + version: '1.0.0', + resolved: 'git+ssh://git.example.com/foo/bar.git#deadbeefcafebabe1234567890abcdef12345678', + }) + t.equal( + isScriptAllowed(gitNode, { 'git+ssh://git.example.com/foo/bar.git': true }), + true + ) + t.equal( + isScriptAllowed(gitNode, { 'git+ssh://git.example.com/foo/other.git': true }), + null + ) + t.end() +}) + +t.test('git — hosted key against non-hosted node falls through', t => { + // A GitHub-style key cannot match a self-hosted git node: one side + // produces a hosted.ssh URL, the other does not, so neither the + // hosted branch nor the fetchSpec branch applies. + const gitNode = node({ + name: 'bar', + packageName: 'bar', + version: '1.0.0', + resolved: 'git+ssh://git.example.com/foo/bar.git#deadbeefcafebabe1234567890abcdef12345678', + }) + t.equal(isScriptAllowed(gitNode, { 'github:foo/bar': true }), null) + t.end() +}) + +t.test('git — resolved URL without a committish does not match keys with one', t => { + // The lockfile somehow recorded the git URL without a #SHA suffix. + // Any policy key that pins a specific committish must NOT match. + const gitNode = node({ + name: 'bar', + packageName: 'bar', + version: '1.0.0', + resolved: 'git+ssh://git@github.com/foo/bar.git', + }) + t.equal(isScriptAllowed(gitNode, { 'github:foo/bar#deadbeef': true }), null) + // Repo-only key still matches. + t.equal(isScriptAllowed(gitNode, { 'github:foo/bar': true }), true) + t.end() +}) + +t.test('file/directory key against a node with no resolved does not match', t => { + const noResolved = { + name: 'local-pkg', + packageName: 'local-pkg', + version: '1.0.0', + resolved: undefined, + edgesIn: new Set([{ name: 'local-pkg', spec: 'file:../local-pkg' }]), + } + t.equal(isScriptAllowed(noResolved, { 'file:../local-pkg': true }), null) + t.end() +}) + +t.test('remote key against a node with no resolved does not match', t => { + const noResolved = { + name: 'pkg', + packageName: 'pkg', + version: '1.0.0', + resolved: undefined, + edgesIn: new Set([{ name: 'pkg', spec: 'https://example.com/pkg.tgz' }]), + } + t.equal(isScriptAllowed(noResolved, { 'https://example.com/pkg.tgz': true }), null) + t.end() +}) + +t.test('alias-typed policy key never matches anything', t => { + // Policy key parsed as type 'alias' (e.g. `foo@npm:bar@1.0.0`) is + // explicitly disallowed. The user must address the real package name. + const aliased = node({ name: 'foo', packageName: 'bar', version: '1.0.0' }) + t.equal(isScriptAllowed(aliased, { 'foo@npm:bar@1.0.0': true }), null) + t.end() +}) + +t.test('registry — `pkg@latest` tag spec does not match (rejected up front)', t => { + // npa parses `canvas@latest` as { type: 'tag' }. Validated out by + // resolve-allow-scripts.js#validatePolicy; defense-in-depth here. + const n = node({ name: 'canvas', version: '2.11.0' }) + t.equal(isScriptAllowed(n, { 'canvas@latest': true }), null) + t.equal(isScriptAllowed(n, { 'other@latest': true }), null) + t.end() +}) + +t.test('omit-lockfile: unparseable edge specs are skipped', t => { + // An edge whose spec npa.resolve cannot parse is ignored; the matcher + // continues to the next edge to find a trusted name. + const omitted = { + name: 'canvas', + packageName: 'canvas', + version: '2.11.0', + resolved: undefined, + location: 'node_modules/canvas', + edgesIn: new Set([ + { name: 'canvas', spec: '\u0000not a real spec' }, + { name: 'canvas', spec: '^2.0.0' }, + ]), + } + t.equal(isScriptAllowed(omitted, { canvas: true }), true) + t.end() +}) + +t.test('omit-lockfile: edges with only non-registry specs yield no trusted name', t => { + // Every incoming edge is a git/file/remote spec, so nameFromEdges + // walks them all and returns null at the end. + const omitted = { + name: 'canvas', + packageName: 'canvas', + version: '2.11.0', + resolved: undefined, + location: 'node_modules/canvas', + edgesIn: new Set([ + { name: 'canvas', spec: 'github:foo/canvas' }, + { name: 'canvas', spec: 'file:../canvas' }, + ]), + } + t.equal(isScriptAllowed(omitted, { canvas: true }), null) + t.end() +}) + +t.test('trustedDisplay returns URL-derived identity when available', t => { + // Registry tarball URL carries name and version — those are trusted and + // must override the tarball-self-claimed package fields. + const n = node({ + name: 'pkg', + packageName: 'lying-name', + version: '9.9.9', + resolved: 'https://registry.npmjs.org/canvas/-/canvas-2.11.0.tgz', + }) + t.strictSame(trustedDisplay(n), { name: 'canvas', version: '2.11.0' }) + t.end() +}) + +t.test('trustedDisplay falls back to node.name/version when URL has no identity', t => { + // Git source: matchGit handles it for matching, but trustedDisplay + // accepts the node's self-reported name/version for human-facing output. + const n = node({ + name: 'bar', + packageName: 'bar', + version: '1.2.3', + resolved: 'git+ssh://git@github.com/foo/bar.git#deadbeefcafebabe1234567890abcdef12345678', + }) + t.strictSame(trustedDisplay(n), { name: 'bar', version: '1.2.3' }) + t.end() +}) diff --git a/workspaces/arborist/test/shrinkwrap.js b/workspaces/arborist/test/shrinkwrap.js index 5a52a44dfa860..d4f9756e8c7c3 100644 --- a/workspaces/arborist/test/shrinkwrap.js +++ b/workspaces/arborist/test/shrinkwrap.js @@ -17,7 +17,6 @@ const YarnLock = require('../lib/yarn-lock.js') const yarnFixture = resolve(__dirname, 'fixtures/yarn-stuff') const emptyFixture = resolve(__dirname, 'fixtures/empty') const depTypesFixture = resolve(__dirname, 'fixtures/dev-deps') -const badJsonFixture = resolve(__dirname, 'fixtures/testing-peer-deps-bad-sw') const hiddenLockfileFixture = resolve(__dirname, 'fixtures/hidden-lockfile') const hidden = 'node_modules/.package-lock.json' const saxFixture = resolve(__dirname, 'fixtures/sax') @@ -79,6 +78,20 @@ t.test('starting out with a reset lockfile is an empty lockfile', async t => { t.equal(sw.filename, resolve(fixture, 'package-lock.json')) }) +t.test('errors on a lockfileVersion newer than supported', async t => { + const dir = t.testdir({ + 'package-lock.json': JSON.stringify({ + name: 'x', + version: '1.0.0', + lockfileVersion: 5, + requires: true, + packages: {}, + }), + }) + await t.rejects(Shrinkwrap.load({ path: dir }), { code: 'ELOCKFILEVERSION' }, + 'a lockfile newer than the supported version is refused') +}) + t.test('reset in a bad dir gets an empty lockfile with no lockfile version', async t => { const nullLockDir = t.testdir({ 'package-lock.json': JSON.stringify(null), @@ -120,7 +133,8 @@ t.test('loading in bad dir gets empty lockfile', async t => { }) t.test('failure to parse json gets empty lockfile', async t => { - const sw = await Shrinkwrap.load({ path: badJsonFixture }) + const path = t.testdir({ 'package-lock.json': 'this is not valid json {' }) + const sw = await Shrinkwrap.load({ path }) t.strictSame(sw.data, { lockfileVersion: 3, requires: true, @@ -393,6 +407,7 @@ t.test('construct metadata from node and package data', t => { }, os: ['any', '!win32'], cpu: ['x64'], + libc: ['glibc'], }, resolved: '/home/user/projects/root/archives/tarball.tgz', parent: root, @@ -577,7 +592,7 @@ t.test('saving dependency-free shrinkwrap object', t => { resolve(`${dir}/node_modules/.package-lock.json`), 'correct filepath on shrinkwrap instance' ) - // save does not throw, but doens't write the file + // save does not throw, but doesn't write the file await sw.save() t.throws(() => fs.statSync(sw.filename)) }) @@ -676,7 +691,7 @@ t.test('write the shrinkwrap back to disk', t => { t.end() }) -t.test('load shrinkwrap if no package-lock.json present', async t => { +t.test('ignore npm-shrinkwrap.json at the project root', async t => { const dir = t.testdir({ 'npm-shrinkwrap.json': JSON.stringify({ lockfileVersion: 1, @@ -685,14 +700,12 @@ t.test('load shrinkwrap if no package-lock.json present', async t => { }), }) let s - s = await Shrinkwrap.load({ path: dir, shrinkwrapOnly: true }) - t.equal(s.type, 'npm-shrinkwrap.json', 'loaded with swonly') - s = await Shrinkwrap.reset({ path: dir, shrinkwrapOnly: true }) - t.equal(s.type, 'npm-shrinkwrap.json', 'loaded fresh') s = await Shrinkwrap.load({ path: dir }) - t.equal(s.type, 'npm-shrinkwrap.json', 'loaded without swonly') + t.equal(s.loadedFromDisk, false, 'shrinkwrap is not loaded from disk') + t.notOk(s.filename.endsWith('npm-shrinkwrap.json'), 'filename is package-lock.json') s = await Shrinkwrap.reset({ path: dir }) - t.equal(s.type, 'npm-shrinkwrap.json', 'loaded fresh without swonly') + t.equal(s.loadedFromDisk, false, 'reset does not find shrinkwrap') + t.notOk(s.filename.endsWith('npm-shrinkwrap.json'), 'reset filename is package-lock.json') }) t.test('load yarn.lock file if present', async t => { @@ -719,7 +732,7 @@ t.test('ignore yarn lock file parse errors', async t => { t.equal(s.yarnLock.entries.size, 0, 'did not get any entries out of it') }) -t.test('load a resolution from yarn.lock if we dont have our own', async t => { +t.test('load a resolution from yarn.lock if we do not have our own', async t => { const path = t.testdir({ 'yarn.lock': ` # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. @@ -864,6 +877,141 @@ t.test('load a hidden lockfile', async t => { t.equal(data.dependencies, undefined, 'deleted legacy metadata') }) +t.test('skip inert nodes in commit', async t => { + // When a proxy registry returns 404 or incomplete manifests for + // platform-specific optional deps, #pruneFailedOptional marks them + // inert. commit() must skip inert nodes — otherwise the lockfile + // gets entries like {"optional": true} without version/resolved/integrity + // that cause "Invalid Version:" errors on subsequent npm ci. + const path = t.testdir({ + 'package.json': JSON.stringify({ + name: 'proxy-registry-repro', + version: '1.0.0', + devDependencies: { esbuild: '^0.27.0' }, + }), + }) + const meta = new Shrinkwrap({ path }) + meta.data = { + lockfileVersion: 3, + packages: {}, + } + + const root = new Node({ + pkg: { + name: 'proxy-registry-repro', + version: '1.0.0', + devDependencies: { esbuild: '^0.27.0' }, + }, + path, + realpath: path, + }) + + // esbuild with full metadata (valid) + const esbuild = new Node({ + pkg: { + name: 'esbuild', + version: '0.27.7', + optionalDependencies: { + '@esbuild/linux-x64': '0.27.7', + '@esbuild/aix-ppc64': '0.27.7', + }, + }, + name: 'esbuild', + parent: root, + }) + esbuild.dev = true + + // platform dep with full metadata (current platform — valid, NOT inert) + const validDep = new Node({ + pkg: { + name: '@esbuild/linux-x64', + version: '0.27.7', + os: ['linux'], + cpu: ['x64'], + }, + name: '@esbuild/linux-x64', + parent: root, + }) + validDep.optional = true + validDep.dev = true + + // platform dep marked inert (proxy registry 404'd or returned incomplete manifest) + // #pruneFailedOptional sets inert=true on these nodes + const brokenDep = new Node({ + pkg: { + name: '@esbuild/aix-ppc64', + // no version — proxy registry returned 404 or incomplete manifest + }, + name: '@esbuild/aix-ppc64', + parent: esbuild, + }) + brokenDep.optional = true + brokenDep.dev = true + brokenDep.extraneous = false + brokenDep.inert = true + + // file: optional dep WITHOUT version (legitimate — NOT inert, should be kept) + const fileDep = new Node({ + pkg: { + name: 'my-local-optional', + // no version — but this is a file: dep, so it's legitimate + }, + name: 'my-local-optional', + parent: root, + resolved: 'file:../my-local-optional', + }) + fileDep.optional = true + fileDep.extraneous = false + + // local optional dep WITHOUT version or resolved (NOT inert, should be kept) + const localDep = new Node({ + pkg: { + name: 'my-disk-optional', + // no version, no resolved — loaded from local node_modules + }, + name: 'my-disk-optional', + parent: root, + }) + localDep.optional = true + localDep.extraneous = false + + meta.tree = root + const committed = meta.commit() + + // The valid platform dep should be in the lockfile + const validLoc = 'node_modules/@esbuild/linux-x64' + t.ok( + committed.packages[validLoc], + 'valid optional dep is included' + ) + t.equal( + committed.packages[validLoc].version, + '0.27.7', + 'valid optional dep has version' + ) + + // The inert dep should NOT be in the lockfile + const brokenLoc = 'node_modules/esbuild/node_modules/@esbuild/aix-ppc64' + t.notOk( + committed.packages[brokenLoc], + 'inert optional dep is excluded from lockfile' + ) + + // The file: optional dep WITHOUT version SHOULD be kept (not inert) + const fileLoc = 'node_modules/my-local-optional' + t.ok( + committed.packages[fileLoc], + 'file: optional dep without version is preserved in lockfile' + ) + + // The local (resolved=null) optional dep WITHOUT version SHOULD be kept (not inert) + const localLoc = 'node_modules/my-disk-optional' + t.ok( + committed.packages[localLoc], + 'local optional dep without version is preserved in lockfile' + ) +}) + t.test('load a fresh hidden lockfile', async t => { const sw = await Shrinkwrap.reset({ path: hiddenLockfileFixture, @@ -1599,14 +1747,15 @@ t.test('shrinkwrap where root is a link node', async t => { }) }) -t.test('prioritize npm-shrinkwrap.json over package-lock.json', async t => { +t.test('ignore npm-shrinkwrap.json even when package-lock.json is also present', async t => { const path = t.testdir({ - 'npm-shrinkwrap.json': '{}', - 'package-lock.json': '{}', + 'npm-shrinkwrap.json': '{"name":"from-shrinkwrap"}', + 'package-lock.json': '{"name":"from-package-lock"}', 'package.json': '{}', }) const sw = await Shrinkwrap.load({ path }) - t.equal(sw.type, 'npm-shrinkwrap.json') + t.equal(sw.type, 'package-lock.json') + t.equal(sw.data.name, 'from-package-lock', 'read package-lock.json, not npm-shrinkwrap.json') }) t.test('do not add metadata if versions mismatch', async t => { diff --git a/workspaces/arborist/test/unreviewed-scripts.js b/workspaces/arborist/test/unreviewed-scripts.js new file mode 100644 index 0000000000000..7f26f56db6875 --- /dev/null +++ b/workspaces/arborist/test/unreviewed-scripts.js @@ -0,0 +1,188 @@ +const t = require('tap') +const { + collectUnreviewedScripts, + strictAllowScriptsError, +} = require('../lib/unreviewed-scripts.js') + +// Loads a fresh copy of the shared module with `install-scripts.js` mocked, +// so script detection (including the synthetic node-gyp `binding.gyp` path) +// can be controlled without touching the filesystem. +const mockCollect = (t, getInstallScripts) => + t.mock('../lib/unreviewed-scripts.js', { + '../lib/install-scripts.js': getInstallScripts, + }).collectUnreviewedScripts + +// Minimal tree fixture for the walk. +const tree = (nodes) => ({ + inventory: new Map(nodes.map((n, i) => [`node_modules/${n.name || `n${i}`}`, n])), +}) + +// Registry-shaped node so the real script-allowed/install-scripts helpers +// behave deterministically (registry tarballs skip `prepare`, and the +// identity matcher keys off the resolved URL). +const node = ({ + name = 'pkg', + version = '1.0.0', + scripts = {}, + isProjectRoot = false, + isWorkspace = false, + isLink = false, + inBundle = false, + resolved, +} = {}) => ({ + name, + packageName: name, + version, + resolved: resolved ?? `https://registry.npmjs.org/${name}/-/${name}-${version}.tgz`, + location: `node_modules/${name}`, + isProjectRoot, + isWorkspace, + isLink, + inBundle, + isRegistryDependency: true, + package: { name, version, scripts }, +}) + +t.test('collectUnreviewedScripts', async t => { + t.test('returns [] when ignoreScripts is set', async t => { + const result = await collectUnreviewedScripts({ + tree: tree([node({ scripts: { install: 'x' } })]), + policy: null, + ignoreScripts: true, + }) + t.strictSame(result, []) + }) + + t.test('returns [] when dangerouslyAllowAllScripts is set', async t => { + const result = await collectUnreviewedScripts({ + tree: tree([node({ scripts: { install: 'x' } })]), + policy: null, + dangerouslyAllowAllScripts: true, + }) + t.strictSame(result, []) + }) + + t.test('returns [] when tree has no inventory', async t => { + t.strictSame(await collectUnreviewedScripts({ tree: undefined }), []) + t.strictSame(await collectUnreviewedScripts({ tree: {} }), []) + t.strictSame(await collectUnreviewedScripts({}), []) + t.strictSame(await collectUnreviewedScripts(), []) + }) + + t.test('skips project root, workspace, linked, and bundled nodes', async t => { + const result = await collectUnreviewedScripts({ + tree: tree([ + node({ name: 'root', scripts: { install: 'x' }, isProjectRoot: true }), + node({ name: 'ws', scripts: { install: 'x' }, isWorkspace: true }), + node({ name: 'linked', scripts: { install: 'x' }, isLink: true }), + node({ name: 'bundled', scripts: { install: 'x' }, inBundle: true }), + ]), + policy: null, + }) + t.strictSame(result, []) + }) + + t.test('skips nodes with no install-relevant scripts', async t => { + const result = await collectUnreviewedScripts({ + tree: tree([node({ scripts: { test: 'jest' } })]), + policy: null, + }) + t.strictSame(result, []) + }) + + t.test('collects unreviewed install scripts', async t => { + const result = await collectUnreviewedScripts({ + tree: tree([ + node({ name: 'a', scripts: { preinstall: 'pre' } }), + node({ name: 'b', scripts: { install: 'inst' } }), + node({ name: 'c', scripts: { postinstall: 'post' } }), + ]), + policy: null, + }) + t.equal(result.length, 3) + t.strictSame(result[0].scripts, { preinstall: 'pre' }) + t.strictSame(result[1].scripts, { install: 'inst' }) + t.strictSame(result[2].scripts, { postinstall: 'post' }) + }) + + t.test('skips nodes the policy allows or denies', async t => { + const result = await collectUnreviewedScripts({ + tree: tree([ + node({ name: 'allowed', version: '1.0.0', scripts: { install: 'x' } }), + node({ name: 'denied', version: '1.0.0', scripts: { install: 'x' } }), + node({ name: 'pending', version: '1.0.0', scripts: { install: 'x' } }), + ]), + policy: { allowed: true, denied: false }, + }) + t.equal(result.length, 1) + t.equal(result[0].node.name, 'pending') + }) + + t.test('skips reviewed local directory link targets', async t => { + const target = node({ name: 'local', scripts: { install: 'x' } }) + target.resolved = null + target.isRegistryDependency = false + target.path = require('node:path').resolve('local') + target.realpath = target.path + target.linksIn = new Set([{ resolved: 'file:../local' }]) + + t.strictSame(await collectUnreviewedScripts({ + tree: tree([target]), + policy: { 'file:../local': false }, + }), []) + + t.strictSame(await collectUnreviewedScripts({ + tree: tree([target]), + policy: { 'file:local': true }, + }), []) + }) + + t.test('detects synthetic node-gyp via binding.gyp runtime check', async t => { + const collect = mockCollect(t, async (n) => { + if (n.path === '/has-bindings') { + return { install: 'node-gyp rebuild' } + } + return {} + }) + const result = await collect({ + tree: tree([ + { ...node({ name: 'native' }), path: '/has-bindings' }, + { ...node({ name: 'pure-js' }), path: '/no-bindings' }, + ]), + policy: null, + }) + t.equal(result.length, 1) + t.equal(result[0].node.name, 'native') + t.strictSame(result[0].scripts, { install: 'node-gyp rebuild' }) + }) +}) + +t.test('strictAllowScriptsError', async t => { + const unreviewed = [ + { node: { package: { name: 'a', version: '1.0.0' } }, scripts: { install: 'do-a' } }, + { node: { package: { name: 'b', version: '2.0.0' } }, scripts: { preinstall: 'pre', postinstall: 'post' } }, + ] + + const err = strictAllowScriptsError(unreviewed, { remediation: 'FIX IT.' }) + t.equal(err.code, 'ESTRICTALLOWSCRIPTS') + t.match(err.message, /2 package\(s\) have install scripts not covered by allowScripts:/) + t.match(err.message, /a@1\.0\.0 \(install: do-a\)/) + t.match(err.message, /b@2\.0\.0 \(preinstall: pre; postinstall: post\)/) + t.match(err.message, /FIX IT\.$/) +}) + +t.test('strictAllowScriptsError falls back to node.name when no package', async t => { + const err = strictAllowScriptsError( + [{ node: { name: 'c' }, scripts: { install: 'x' } }], + { remediation: 'go.' } + ) + t.match(err.message, /\n {2}c \(install: x\)\n/) +}) + +t.test('strictAllowScriptsError defaults options when called without them', async t => { + const err = strictAllowScriptsError( + [{ node: { name: 'c' }, scripts: { install: 'x' } }] + ) + t.equal(err.code, 'ESTRICTALLOWSCRIPTS') + t.match(err.message, /\n {2}c \(install: x\)\n/) +}) diff --git a/workspaces/arborist/test/yarn-lock.js b/workspaces/arborist/test/yarn-lock.js index e1ed29701be0a..8b02fc96bd6b8 100644 --- a/workspaces/arborist/test/yarn-lock.js +++ b/workspaces/arborist/test/yarn-lock.js @@ -118,7 +118,7 @@ t.test('yarn lock with dedupes yarn wouldnt do', async t => { t.matchSnapshot(y.toString(), 'yarn.lock from deduped tree') }) -t.test('deduped prior entries that dont match one another', async t => { +t.test('deduped prior entries that do not match one another', async t => { const tree = new Node({ path: '/my/project', pkg: { dependencies: { a: '', b: '' } }, diff --git a/workspaces/config/.gitignore b/workspaces/config/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/workspaces/config/.gitignore +++ b/workspaces/config/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/workspaces/config/CHANGELOG.md b/workspaces/config/CHANGELOG.md index 58e3def1c765c..2ca50d59b1cc4 100644 --- a/workspaces/config/CHANGELOG.md +++ b/workspaces/config/CHANGELOG.md @@ -1,5 +1,198 @@ # Changelog +## [11.0.0-pre.1](https://github.com/npm/cli/compare/config-v11.0.0-pre.0...config-v11.0.0-pre.1) (2026-06-19) +### ⚠️ BREAKING CHANGES +* The default license for `npm init` has been changed from "ISC" to an empty string. If not set, the license field will be omitted from new packages. +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +* allow-git and allow-remote now default to "none"; set them to "all" (or "root") to install git or user-supplied tarball-URL dependencies. +* unknown configs in .npmrc, unknown CLI flags, abbreviated flags, and single-hyphen multi-char shorthands now throw instead of warning. +### Features +* [`1db885c`](https://github.com/npm/cli/commit/1db885c84b2dfc5126ab663abb12262b533922c1) [#9439](https://github.com/npm/cli/pull/9439) native dependency patching (npm patch add/commit/update/ls/rm) (#9439) (@manzoorwanijk) +* [`fc80bb3`](https://github.com/npm/cli/commit/fc80bb359502699bb0a055157e01eaedd5bd73c8) [#9234](https://github.com/npm/cli/pull/9234) remove default license for npm init (@owlstronaut) +* [`be8053c`](https://github.com/npm/cli/commit/be8053c390a2be3902b9382d3c7d4ad9012fa1c2) [#9544](https://github.com/npm/cli/pull/9544) warn when min-release-age blocks an audit fix (#9544) (@JamieMagee) +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +* [`c3e1a71`](https://github.com/npm/cli/commit/c3e1a7175c6475553e212e2f7671bd31bfe07aba) [#9532](https://github.com/npm/cli/pull/9532) add min-release-age-exclude config (@JamieMagee, @caseyjhol) +* [`f6a9aad`](https://github.com/npm/cli/commit/f6a9aad3c5b47d6fd8dba3a604e63b0000901c9d) [#9517](https://github.com/npm/cli/pull/9517) differentiate GitHub Actions environments in user-agent (#9517) (@reggi, @Copilot) +* [`5cd5150`](https://github.com/npm/cli/commit/5cd5150d3e85dcf5d246e7e5c9de216c2ff849db) [#9424](https://github.com/npm/cli/pull/9424) default-deny install scripts (allowScripts opt-in) [v12] (@JamieMagee) +* [`caa3295`](https://github.com/npm/cli/commit/caa329568d32587e53f6e098f43b550dd2685034) [#9466](https://github.com/npm/cli/pull/9466) default allow-git and allow-remote to none (@owlstronaut) +* [`f2e4a28`](https://github.com/npm/cli/commit/f2e4a285ec5ed43055462a47db6d330758a16e64) [#9351](https://github.com/npm/cli/pull/9351) add a global npmignore file (#9351) (@ljharb) +* [`c9be2d1`](https://github.com/npm/cli/commit/c9be2d1efadd353e743bcebd52faaa5aa64e2fc0) [#9153](https://github.com/npm/cli/pull/9153) publish --access=private alias for restricted (#9153) (@reggi, @Copilot) +* [`7068d42`](https://github.com/npm/cli/commit/7068d4286eb446fdb0ded08d15d7b5c3883d80f5) [#9360](https://github.com/npm/cli/pull/9360) Phase 1 of `allowScripts` opt-in install-script policy (#9360) (@JamieMagee) +* [`979518d`](https://github.com/npm/cli/commit/979518dd198b9f2beb788c6c3cdcd1e055b03d22) [#9276](https://github.com/npm/cli/pull/9276) error on unknown configs, flags, and abbreviations (#9276) (@owlstronaut) +### Bug Fixes +* [`9b5c7b0`](https://github.com/npm/cli/commit/9b5c7b0c8ea47823156111d27800aa6e741c7a2c) [#9521](https://github.com/npm/cli/pull/9521) config: strict-allow-scripts default blocks with a warning, not silently (@JamieMagee) +* [`6efac6e`](https://github.com/npm/cli/commit/6efac6ead98af50c5a40fc45cb657bbee496a584) [#9453](https://github.com/npm/cli/pull/9453) config: clarify --all help so it's accurate for approve-scripts and deny-scripts (@JamieMagee) +* [`c5292fa`](https://github.com/npm/cli/commit/c5292fa8a09a56b25394d393faf21e47ffb096c0) [#9422](https://github.com/npm/cli/pull/9422) use prerelease strategy without a bug (@owlstronaut) +### Dependencies +* [`21df0ab`](https://github.com/npm/cli/commit/21df0ab3c629496511a3c481ee721b0e62c16e92) [#9559](https://github.com/npm/cli/pull/9559) `proc-log@7.0.0` +* [`471309f`](https://github.com/npm/cli/commit/471309f580efdf7f8055020ac0a08610f692a4f4) [#9559](https://github.com/npm/cli/pull/9559) `nopt@10.0.1` +* [`406820a`](https://github.com/npm/cli/commit/406820a15bc2c19543c7457a4331ea40ae8d0cf6) [#9559](https://github.com/npm/cli/pull/9559) `ini@7.0.0` +* [`0be6ae2`](https://github.com/npm/cli/commit/0be6ae21c79eb3986a76d5d769d5dd5ef00283c2) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/package-json@8.0.0` +* [`4d234b2`](https://github.com/npm/cli/commit/4d234b22e59416f6307eb75bef52ac9b43ee6628) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/map-workspaces@6.0.0` +### Chores +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) + +## [11.0.0-pre.0.0](https://github.com/npm/cli/compare/config-v10.8.1...config-v11.0.0-pre.0.0) (2026-05-20) +### ⚠️ BREAKING CHANGES +* `npm shrinkwrap` is removed, the `shrinkwrap` config alias is removed, and `npm-shrinkwrap.json` is no longer loaded or honored at the project root or from inside dependency tarballs. Rename project-root `npm-shrinkwrap.json` to `package-lock.json`; use `bundleDependencies` if you need to ship a locked dependency tree. +### Features +* [`916cb4b`](https://github.com/npm/cli/commit/916cb4b262df1d188ce7644e916b138fbc78c4e7) [#9287](https://github.com/npm/cli/pull/9287) add allow-directory, allow-file, and allow-remote (#9287) (@wraithgar) +* [`2e5dcad`](https://github.com/npm/cli/commit/2e5dcad17a59ee9f69eeec27fc5b087b5b032df7) [#9262](https://github.com/npm/cli/pull/9262) drop npm-shrinkwrap.json support (@owlstronaut) +### Bug Fixes +* [`18ebb0f`](https://github.com/npm/cli/commit/18ebb0f8b2370d9a4fd3df0a5b89ec6a8036bb81) [#9368](https://github.com/npm/cli/pull/9368) min-release-age=0 doesn't filter, honor cross-source precedence (@owlstronaut) +* [`ca585c8`](https://github.com/npm/cli/commit/ca585c80dee759fedb85c5c20f9dd3ea8d017be4) [#9368](https://github.com/npm/cli/pull/9368) allow min-release-age in npmrc to coexist with --before (@raazkhnl) +* [`6628d05`](https://github.com/npm/cli/commit/6628d0524b460c26cefc93b1ec3e901abdcb86f4) [#9285](https://github.com/npm/cli/pull/9285) config: preserve min-release-age after flattening (@lawrence3699) + +## [10.8.1](https://github.com/npm/cli/compare/config-v10.8.0...config-v10.8.1) (2026-03-24) +### Bug Fixes +* [`596706a`](https://github.com/npm/cli/commit/596706a3d10100587e3751d860b4cfcc59342d2f) [#9148](https://github.com/npm/cli/pull/9148) revert prefer-offline/prefer-online exclusivity (#9129) (@owlstronaut) + +## [10.8.0](https://github.com/npm/cli/compare/config-v10.7.1...config-v10.8.0) (2026-03-18) +### Features +* [`8eff5fb`](https://github.com/npm/cli/commit/8eff5fb31afc996c71c8f159defa324cb86dfc5a) [#9049](https://github.com/npm/cli/pull/9049) audit: add --include-attestations flag to output sigstore bundles (#9049) (@mitchdenny) +### Bug Fixes +* [`d273380`](https://github.com/npm/cli/commit/d2733809b820a9a9dc3a5453b55f2690afee6066) [#9129](https://github.com/npm/cli/pull/9129) config: make prefer-offline and prefer-online exclusive (#9129) (@mvanhorn) +* [`e839b07`](https://github.com/npm/cli/commit/e839b07b1a512a98e2266ff85ff79774d9385d9d) [#9023](https://github.com/npm/cli/pull/9023) clear exclusive param siblings when setting from CLI (#9023) (@umeshmore45) + +## [10.7.1](https://github.com/npm/cli/compare/config-v10.7.0...config-v10.7.1) (2026-02-19) +### Bug Fixes +* [`9fac412`](https://github.com/npm/cli/commit/9fac412105c4bbd116cffb6e27dda54a2adecf33) [#8995](https://github.com/npm/cli/pull/8995) improve unknown config warning with .npmrc section hint (#8995) (@umeshmore45) +### Chores +* [`40fcab4`](https://github.com/npm/cli/commit/40fcab45d356545f8db7f34df3e5630116d0dd40) [#8991](https://github.com/npm/cli/pull/8991) `@npmcli/template-oss@4.29.0` (@wraithgar) + +## [10.7.0](https://github.com/npm/cli/compare/config-v10.6.0...config-v10.7.0) (2026-02-11) +### Features +* [`cf56a1e`](https://github.com/npm/cli/commit/cf56a1e4df9c8ae7b7e9752437d827a183e4040e) [#8899](https://github.com/npm/cli/pull/8899) npm trust, per-command config (@reggi) +* [`cf56a1e`](https://github.com/npm/cli/commit/cf56a1e4df9c8ae7b7e9752437d827a183e4040e) [#8899](https://github.com/npm/cli/pull/8899) npm trust (@reggi) +* [`66d6e11`](https://github.com/npm/cli/commit/66d6e11f3ecdbc823ede24ef83257f3bb6e69d46) [#8965](https://github.com/npm/cli/pull/8965) add min-release-age (#8965) (@wraithgar) + +## [10.6.0](https://github.com/npm/cli/compare/config-v10.5.0...config-v10.6.0) (2026-02-04) +### Features +* [`f5f6cf7`](https://github.com/npm/cli/commit/f5f6cf7c9fc9315b96eb29c5c7d5ab63ad3a9122) [#8943](https://github.com/npm/cli/pull/8943) config: add --allow-git (@wraithgar) + +## [10.5.0](https://github.com/npm/cli/compare/config-v10.4.5...config-v10.5.0) (2026-01-21) +### Features +* [`5a444d5`](https://github.com/npm/cli/commit/5a444d57f1068efddc71ddfd131a949632524e00) [#8828](https://github.com/npm/cli/pull/8828) export environment config variable names (Max Black) + +## [10.4.5](https://github.com/npm/cli/compare/config-v10.4.4...config-v10.4.5) (2025-12-09) +### Bug Fixes +* [`4ebb831`](https://github.com/npm/cli/commit/4ebb831d93f13cc0b980754bf36abb2982b131f7) [#8839](https://github.com/npm/cli/pull/8839) updates hints to use cli paradigm (@owlstronaut) + +## [10.4.4](https://github.com/npm/cli/compare/config-v10.4.3...config-v10.4.4) (2025-11-25) +### Bug Fixes +* [`958b10e`](https://github.com/npm/cli/commit/958b10e52f442f73796a92c7bbb7d2808bb5bbe5) [#8761](https://github.com/npm/cli/pull/8761) move config.list to a getter (#8761) (@wraithgar) +### Dependencies +* [`f51e4aa`](https://github.com/npm/cli/commit/f51e4aaf06ac6703abe053a95fe25b8efca3c527) [#8770](https://github.com/npm/cli/pull/8770) `nopt@9.0.0` + +## [10.4.3](https://github.com/npm/cli/compare/config-v10.4.2...config-v10.4.3) (2025-11-19) +### Bug Fixes +* [`c6242d9`](https://github.com/npm/cli/commit/c6242d92e5227e0a772d9cfe474ea57776af79e0) [#8706](https://github.com/npm/cli/pull/8706) change npm profile to create tokens with GAT support (#8706) (@owlstronaut, @wraithgar) +### Dependencies +* [`e49286e`](https://github.com/npm/cli/commit/e49286e2189dfe1604d957ccc415038957a64d19) [#8723](https://github.com/npm/cli/pull/8723) `ini@5.0.0` +* [`05ac7a7`](https://github.com/npm/cli/commit/05ac7a7ea2a4d258658537a19ba350e07df34fda) [#8723](https://github.com/npm/cli/pull/8723) `proc-log@6.0.0` + +## [10.4.2](https://github.com/npm/cli/compare/config-v10.4.1...config-v10.4.2) (2025-10-08) +### Bug Fixes +* [`5b4a7fc`](https://github.com/npm/cli/commit/5b4a7fc594e23dbdd5acab8df7bd195992383d5f) [#8650](https://github.com/npm/cli/pull/8650) handle missing node-gyp gracefully in @npmcli/config definitions (@owlstronaut) +* [`9197995`](https://github.com/npm/cli/commit/9197995ef0b760738454f2d255c0683d0731b24c) [#8619](https://github.com/npm/cli/pull/8619) spelling (#8619) (@jsoref) +### Documentation +* [`1fde042`](https://github.com/npm/cli/commit/1fde04261c899fd03753e2a90698774e41943887) [#8640](https://github.com/npm/cli/pull/8640) rewrap markdown (#8640) (@jsoref) +### Chores +* [`8e5d204`](https://github.com/npm/cli/commit/8e5d2042b041d637db14670f22cb7e866dd00479) [#8626](https://github.com/npm/cli/pull/8626) fix spelling: different (#8626) (@jsoref) +* [`7455fc0`](https://github.com/npm/cli/commit/7455fc01fffa8419dda0f01e2480ab860b81b56f) [#8608](https://github.com/npm/cli/pull/8608) Fix spelling in workspaces/config (#8608) (@jsoref) + +## [10.4.1](https://github.com/npm/cli/compare/config-v10.4.0...config-v10.4.1) (2025-09-23) +### Documentation +* [`7a09902`](https://github.com/npm/cli/commit/7a099029dbeeeab821498b9b462abce1269461f4) [#8582](https://github.com/npm/cli/pull/8582) bring back certfile (#8582) (@jenseng) +### Dependencies +* [`1b4433f`](https://github.com/npm/cli/commit/1b4433fdb85623e019a6194cb01ff85c7f64ccad) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/map-workspaces@5.0.0` +* [`ceae674`](https://github.com/npm/cli/commit/ceae674c32a080b81e62d79003c2d537d7ca93d2) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/package-json@7.0.1` +### Chores +* [`402a0ab`](https://github.com/npm/cli/commit/402a0ab1b4e5d1a8414dd063d0cbde0c0bc5a192) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/template-oss@4.25.1` (@wraithgar) + +## [10.4.0](https://github.com/npm/cli/compare/config-v10.3.1...config-v10.4.0) (2025-09-03) +### Features +* [`bdcc10d`](https://github.com/npm/cli/commit/bdcc10d9f848940987b3d326ccd4673fab2bcfef) [#8359](https://github.com/npm/cli/pull/8359) add support for optional env var replacements in .npmrc (#8359) (@aczekajski, @owlstronaut) + +## [10.3.1](https://github.com/npm/cli/compare/config-v10.3.0...config-v10.3.1) (2025-07-24) +### Bug Fixes +* [`7f66f0a`](https://github.com/npm/cli/commit/7f66f0ae8fb84f567fe83a9a5738d06c7fe8fb54) [#8447](https://github.com/npm/cli/pull/8447) add better hint for `before` and clean up description (@wraithgar) +* [`5b858c6`](https://github.com/npm/cli/commit/5b858c6b2c275f0e670e09c52de5b931936d6e07) [#8411](https://github.com/npm/cli/pull/8411) ensure progress bars display consistently across all environments (#8411) (@owlstronaut) +### Documentation +* [`4673e9c`](https://github.com/npm/cli/commit/4673e9c165b39563e16409f3b1ca06fdc32e7d44) [#8371](https://github.com/npm/cli/pull/8371) rebrand OS X references to macOS (@MikeMcC399) +### Chores +* [`3f60b5f`](https://github.com/npm/cli/commit/3f60b5f9621b43ae0b8796d3a7160a603748f756) [#8383](https://github.com/npm/cli/pull/8383) `@npmcli/template-oss@4.24.4` (#8383) (@wraithgar) +* [`01f8cc6`](https://github.com/npm/cli/commit/01f8cc6f001e3211135fa0563f7129aed09dc46c) [#8381](https://github.com/npm/cli/pull/8381) `@npmcli/template-oss@4.24.3` (#8381) (@wraithgar) + +## [10.3.0](https://github.com/npm/cli/compare/config-v10.2.0...config-v10.3.0) (2025-05-15) +### Features +* [`a0e60fb`](https://github.com/npm/cli/commit/a0e60fb1893ac77a78380d9a9faaaaa54da1fe85) [#8246](https://github.com/npm/cli/pull/8246) added init-private option (@owlstronaut) +* [`57aa89f`](https://github.com/npm/cli/commit/57aa89ff70e0c6186a43888b944b5799b25c7bc8) [#8265](https://github.com/npm/cli/pull/8265) use run by default and run-script as the alias (#8265) (@owlstronaut) +### Bug Fixes +* [`ed1a28e`](https://github.com/npm/cli/commit/ed1a28ed51d1cf1ed2421293c830201da4ce1fb6) [#8238](https://github.com/npm/cli/pull/8238) config: use exclusive for save types (@owlstronaut) + +## [10.2.0](https://github.com/npm/cli/compare/config-v10.1.0...config-v10.2.0) (2025-04-08) +### Features +* [`b306d25`](https://github.com/npm/cli/commit/b306d25df2f2e6ae75fd4f6657e0858b6dd71c43) [#8129](https://github.com/npm/cli/pull/8129) add `node-gyp` as actual config (@wraithgar) +### Bug Fixes +* [`9e73338`](https://github.com/npm/cli/commit/9e733383ba8183da0ee18ae1d6694a679168e18b) [#8129](https://github.com/npm/cli/pull/8129) warn on non-default npm-version (@wraithgar) +* [`1814b45`](https://github.com/npm/cli/commit/1814b451d4b14c04cd8cb61f934277fa4d0d4723) [#8145](https://github.com/npm/cli/pull/8145) re-add positional arg and abbrev warnings (#8145) (@wraithgar) + +## [10.1.0](https://github.com/npm/cli/compare/config-v10.0.1...config-v10.1.0) (2025-03-05) +### Features +* [`3a80a7b`](https://github.com/npm/cli/commit/3a80a7b7d168c23b5e297cba7b47ba5b9875934d) [#8081](https://github.com/npm/cli/pull/8081) add --init-type flag (#8081) (@reggi) +* [`63f2fd7`](https://github.com/npm/cli/commit/63f2fd78eaf056248a7568aef2877fe859010709) [#8071](https://github.com/npm/cli/pull/8071) warn on unknown configs (@wraithgar) +* [`2a1e11f`](https://github.com/npm/cli/commit/2a1e11f1f6e4a4c948b8ac52b9cda8f370d8674b) [#8071](https://github.com/npm/cli/pull/8071) move nerfDart list into @npmcli/config (@wraithgar) +### Bug Fixes +* [`879303c`](https://github.com/npm/cli/commit/879303cd7c529a04d855f47d14dce433118ac626) [#8078](https://github.com/npm/cli/pull/8078) warn on invalid publishConfig (#8078) (@wraithgar) +* [`593c849`](https://github.com/npm/cli/commit/593c84921b0df963cef2ca7b13e44acc20cbd558) [#8076](https://github.com/npm/cli/pull/8076) warn on invalid single-hyphen cli flags (#8076) (@wraithgar) +* [`5e35fde`](https://github.com/npm/cli/commit/5e35fde12275d81b311787de4a52850a9ac90f2b) [#8071](https://github.com/npm/cli/pull/8071) remove -ws shorthand from config suggestions (@wraithgar) +### Dependencies +* [`f0f6265`](https://github.com/npm/cli/commit/f0f626526b86bb54862bb4c0e3c24adfc0f1c8ce) [#8071](https://github.com/npm/cli/pull/8071) `nopt@8.1.0` +### Chores +* [`ed85b01`](https://github.com/npm/cli/commit/ed85b014bfb050ae4ae04827133d49b0f78c5df0) [#8071](https://github.com/npm/cli/pull/8071) tests for config warnings/changes (@wraithgar) + +## [10.0.1](https://github.com/npm/cli/compare/config-v10.0.0...config-v10.0.1) (2025-01-29) +### Documentation +* [`e90c6fe`](https://github.com/npm/cli/commit/e90c6feeacdf9ad010d4d73b65d7dd7d3b86efe2) [#8051](https://github.com/npm/cli/pull/8051) depth flag default value (#8051) (@milaninfy) + +## [10.0.0](https://github.com/npm/cli/compare/config-v10.0.0-pre.1...config-v10.0.0) (2024-12-16) +### Features +* [`a7bfc6d`](https://github.com/npm/cli/commit/a7bfc6df76882996ebb834dbca785fdf33b8c50d) [#7972](https://github.com/npm/cli/pull/7972) trigger release process (#7972) (@wraithgar) +### Chores +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) + +## [10.0.0-pre.1](https://github.com/npm/cli/compare/config-v10.0.0-pre.0...config-v10.0.0-pre.1) (2024-12-06) +### Documentation +* [`2af31dd`](https://github.com/npm/cli/commit/2af31dd30f4c226f43ce7295cd0b5fbb3f3cb2a6) [#7947](https://github.com/npm/cli/pull/7947) change certfile to cafile (#7947) (@wraithgar) +### Dependencies +* [`c0bcc2a`](https://github.com/npm/cli/commit/c0bcc2a860fec5c86234dec44f5474364c25aefc) [#7955](https://github.com/npm/cli/pull/7955) `walk-up-path@4.0.0` + +## [10.0.0-pre.0](https://github.com/npm/cli/compare/config-v9.0.0...config-v10.0.0-pre.0) (2024-11-26) +### ⚠️ BREAKING CHANGES +* @npmcli/config now supports node `^20.17.0 || >=22.9.0` +### Bug Fixes +* [`6e11eb2`](https://github.com/npm/cli/commit/6e11eb2cf663b6566f4fcf10b2b9d4fbce615b5d) [#7831](https://github.com/npm/cli/pull/7831) for @npmcli/config sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +### Chores +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) + +## [9.0.0](https://github.com/npm/cli/compare/config-v8.3.4...config-v9.0.0) (2024-10-03) +### ⚠️ BREAKING CHANGES +* `@npmcli/config` now supports node `^18.17.0 || >=20.5.0` +### Bug Fixes +* [`f846ad3`](https://github.com/npm/cli/commit/f846ad3e5e2a930c89cc8c4daa7752ba6fd52598) [#7803](https://github.com/npm/cli/pull/7803) align @npmcli/config to npm 10 node engine range (@reggi) +### Dependencies +* [`f6909a0`](https://github.com/npm/cli/commit/f6909a022c9373c85d980c96a30f47a3a65aa4a9) [#7803](https://github.com/npm/cli/pull/7803) update `proc-log@5.0.0` +* [`105fa2b`](https://github.com/npm/cli/commit/105fa2bdb2bbb0502bb8e0c5ccec3dadcff3c2d6) [#7803](https://github.com/npm/cli/pull/7803) update `nopt@8.0.0` +* [`f54b155`](https://github.com/npm/cli/commit/f54b155d0cbc251c7159cc42ba3b6154563f9e49) [#7803](https://github.com/npm/cli/pull/7803) update `ini@5.0.0` +* [`2076368`](https://github.com/npm/cli/commit/207636897aa5544ec28cad5b75fe2e685028dafd) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/package-json@6.0.1` +* [`feac87c`](https://github.com/npm/cli/commit/feac87c7ed6113665bc144ee677017bc66138b70) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/map-workspaces@4.0.1` +### Chores +* [`2072705`](https://github.com/npm/cli/commit/2072705aa80d009dc077639adc305692f4a6c0b9) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/eslint-config@5.0.1` (@reggi) +* [`8035725`](https://github.com/npm/cli/commit/80357253ecd8483463cd66c783c4464c330d72df) [#7756](https://github.com/npm/cli/pull/7756) `@npmcli/template-oss@4.23.3` (@wraithgar) + ## [8.3.4](https://github.com/npm/cli/compare/config-v8.3.3...config-v8.3.4) (2024-07-09) ### Bug Fixes @@ -49,7 +242,7 @@ ### Features -* [`9123de4`](https://github.com/npm/cli/commit/9123de4d282bfd19ea17ad613f5a2acab0e0e162) [#7373](https://github.com/npm/cli/pull/7373) do all ouput over proc-log events (@lukekarrys) +* [`9123de4`](https://github.com/npm/cli/commit/9123de4d282bfd19ea17ad613f5a2acab0e0e162) [#7373](https://github.com/npm/cli/pull/7373) do all output over proc-log events (@lukekarrys) ### Bug Fixes @@ -283,7 +476,10 @@ ### ⚠️ BREAKING CHANGES -* unscoped auth configuration is no longer automatically scoped to a registry. the `validate` method is no longer called automatically. the `_auth` configuration key is no longer split into `username` and `_password`. errors will be thrown by `validate()` if problems are found. +* unscoped auth configuration is no longer automatically scoped to a registry. +the `validate` method is no longer called automatically. +the `_auth` configuration key is no longer split into `username` and `_password`. +errors will be thrown by `validate()` if problems are found. * `@npmcli/config` is now compatible with the following semver range for node: `^14.17.0 || ^16.13.0 || >=18.0.0` ### Features diff --git a/workspaces/config/README.md b/workspaces/config/README.md index 12a5e23331d3a..6a948d9b11a91 100644 --- a/workspaces/config/README.md +++ b/workspaces/config/README.md @@ -2,53 +2,42 @@ 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 +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. +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 `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. + `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`. +- 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. +- 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 @@ -65,7 +54,7 @@ const conf = new Config({ flatten, // optional, defaults to process.argv // argv: [] <- if you are using this package in your own cli - // and dont want to have colliding argv + // and don't want to have colliding argv argv: process.argv, // optional, defaults to process.env env: process.env, @@ -103,57 +92,50 @@ const Config = require('@npmcli/config') ### static `Config.typeDefs` -The type definitions passed to `nopt` for CLI option parsing and known -configuration validation. +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. +- `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. +- `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 +- `platform` Optional, defaults to `process.platform`. +Used when inferring the `globalPrefix` from the `execPath`, since this is done differently 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. +- `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 +- `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. +- `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, + - `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 @@ -166,21 +148,17 @@ Fields: - `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()`. +- `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. + 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. +Returns a `Promise` that resolves when configuration is loaded, and fails if a fatal error is encountered. ### `config.find(key)` @@ -196,8 +174,7 @@ 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. +Set the key to the specified value, at the specified level in the config stack. ### `config.delete(key, where = 'cli')` @@ -205,12 +182,9 @@ 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. +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. +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. @@ -222,30 +196,24 @@ Note that it's usually enough (and more efficient) to just check ### `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. +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`. +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: +> 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: +> 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') @@ -253,5 +221,6 @@ This method can be used for avoiding or tweaking default values, e.g: ### `config.save(where)` -Save the config file specified by the `where` param. Must be one of +Save the config file specified by the `where` param. +Must be one of `project`, `user`, `global`, `builtin`. diff --git a/workspaces/config/lib/definitions/definition.js b/workspaces/config/lib/definitions/definition.js index 333a91928526e..c151506b24476 100644 --- a/workspaces/config/lib/definitions/definition.js +++ b/workspaces/config/lib/definitions/definition.js @@ -22,6 +22,8 @@ const allowed = [ 'typeDescription', 'usage', 'envExport', + 'alias', + 'required', ] const { @@ -34,7 +36,7 @@ const { class Definition { constructor (key, def) { this.key = key - // if it's set falsey, don't export it, otherwise we do by default + // if it's set falsey, don't export it; otherwise, we do by default this.envExport = true Object.assign(this, def) this.validate() @@ -83,7 +85,7 @@ 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('`, `')}\`` + const exclusive = !this.exclusive ? '' : `\nThis config cannot be used with: \`${this.exclusive.join('`, `')}\`` return wrapAll(`#### \`${this.key}\` * Default: ${unindent(this.defaultDescription)} diff --git a/workspaces/config/lib/definitions/definitions.js b/workspaces/config/lib/definitions/definitions.js index 7c58b11cf6eec..ecb491cb32f62 100644 --- a/workspaces/config/lib/definitions/definitions.js +++ b/workspaces/config/lib/definitions/definitions.js @@ -1,4 +1,5 @@ const Definition = require('./definition.js') +const parseAllowScriptsList = require('../parse-allow-scripts-list.js') const ciInfo = require('ci-info') const querystring = require('node:querystring') @@ -153,28 +154,34 @@ const definitions = { defaultDescription: ` 'public' for new packages, existing packages it will not change the current level `, - type: [null, 'restricted', 'public'], + type: [null, 'restricted', 'public', 'private'], 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\`. + Unscoped packages cannot 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. + + The value \`private\` is an alias for \`restricted\`. `, - flatten, + flatten (key, obj, flatOptions) { + const value = obj[key] + flatOptions.access = value === 'private' ? 'restricted' : value + }, }), 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. + Show or act on all packages, not just the ones your project directly + depends on. For \`npm outdated\` and \`npm ls\` this lists every outdated + or installed package. For \`npm approve-scripts\` and \`npm deny-scripts\` + it selects every package with pending install scripts. `, flatten, }), @@ -187,6 +194,104 @@ const definitions = { `, flatten, }), + 'allow-directory': new Definition('allow-directory', { + default: 'all', + type: ['all', 'none', 'root'], + description: ` + Limits the ability for npm to install dependencies from directories. + That is, dependencies that point to a directory instead of a version or semver range. + Please note that this could leave your tree incomplete and some packages may not function as intended or designed. + Changing this setting will not remove dependencies that are already installed. + + \`all\` allows any directories to be installed. + \`none\` prevents any directories from being installed. + \`root\` only allows directories defined in your project's package.json to be installed. Also allows directory dependencies to be used for other commands like \`npm view\` + `, + flatten, + }), + 'allow-file': new Definition('allow-file', { + default: 'all', + type: ['all', 'none', 'root'], + description: ` + Limits the ability for npm to install dependencies from tarball files. + That is, dependencies that point to a local tarball file instead of a version or semver range. + Please note that this could leave your tree incomplete and some packages may not function as intended or designed. + Changing this setting will not remove dependencies that are already installed. + + \`all\` allows any tarball file to be installed. + \`none\` prevents any tarball file from being installed. + \`root\` only allows tarball files defined in your project's package.json to be installed. Also allows tarball file dependencies to be used for other commands like \`npm view\` + `, + flatten, + }), + 'allow-git': new Definition('allow-git', { + default: 'none', + type: ['all', 'none', 'root'], + description: ` + Limits the ability for npm to fetch dependencies from git references. + That is, dependencies that point to a git repo instead of a version or semver range. + Please note that this could leave your tree incomplete and some packages may not function as intended or designed. + Changing this setting will not remove dependencies that are already installed. + + As of npm 12 the default is \`none\`. Git dependencies run \`git\` + against a remote repo and may install configuration the project does + not control. Opt in explicitly per project (in \`.npmrc\`) or per + command (on the CLI) when you need git deps. + + \`all\` allows any git dependencies to be fetched and installed. + \`none\` prevents any git dependencies from being fetched and installed. + \`root\` only allows git dependencies defined in your project's package.json to be fetched and installed. Also allows git dependencies to be fetched for other commands like \`npm view\` + `, + flatten, + }), + 'allow-remote': new Definition('allow-remote', { + default: 'none', + type: ['all', 'none', 'root'], + description: ` + Limits the ability for npm to fetch dependencies from urls. + That is, dependencies that point to a tarball url instead of a version or semver range. + Please note that this could leave your tree incomplete and some packages may not function as intended or designed. + Changing this setting will not remove dependencies that are already installed. + + As of npm 12 the default is \`none\`. Tarballs that share a hostname + with the configured registry (the typical case for the npm registry, + GitHub Packages, and most private registries) are still installed + normally. If your registry serves tarballs from a different host, + set \`replace-registry-host\` or override this setting. Opt in + explicitly per project (in \`.npmrc\`) or per command (on the CLI) + when you intentionally install from a URL. + + \`all\` allows any url to be installed. + \`none\` prevents any url from being installed. + \`root\` only allows urls defined in your project's package.json to be installed. Also allows url dependencies to be used for other commands like \`npm view\` + `, + flatten, + }), + 'allow-scripts': new Definition('allow-scripts', { + default: '', + type: [String, Array], + hint: '', + description: ` + Comma-separated list of packages whose install-time lifecycle scripts + (\`preinstall\`, \`install\`, \`postinstall\`, and \`prepare\` for + non-registry dependencies) are allowed to run. + + This setting is intended for one-off and global contexts: \`npm exec\`, + \`npx\`, and \`npm install -g\`, where no project \`package.json\` is + involved. For team-wide policy in a project, use the \`allowScripts\` + field in \`package.json\` (which also supports explicit denials), or + configure it in \`.npmrc\`. Passing \`--allow-scripts\` on the command + line during a project-scoped \`npm install\`, \`ci\`, \`update\`, or + \`rebuild\` is an error. + + Each name is matched against a dependency's resolved identity, not + against the package's self-reported name. \`--ignore-scripts\` and + \`--dangerously-allow-all-scripts\` both override this setting. + `, + flatten (key, obj, flatOptions) { + flatOptions.allowScripts = parseAllowScriptsList(obj[key]) + }, + }), also: new Definition('also', { default: null, type: [null, 'dev', 'development'], @@ -230,17 +335,31 @@ const definitions = { }), before: new Definition('before', { default: null, + hint: '', 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. + versions that were available **on or before** the given date are + installed. If there are no versions available for the current set of + 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\`. + + If \`before\` and \`min-release-age\` are both set in the same source, + \`before\` wins (an explicit absolute date overrides a relative window). + Across sources, the standard precedence applies (cli > env > project > + user > global), so a higher-priority source can always relax or + override a lower-priority one. + + As with \`min-release-age\`, when this cutoff blocks a fix that + \`npm audit fix\` would install, npm keeps the vulnerable version, warns, + and exits with a non-zero code. + + Packages whose names match \`min-release-age-exclude\` are exempt from + this filter. `, flatten, }), @@ -260,7 +379,7 @@ const definitions = { browser: new Definition('browser', { default: null, defaultDescription: ` - OS X: \`"open"\`, Windows: \`"start"\`, Others: \`"xdg-open"\` + macOS: \`"open"\`, Windows: \`"start"\`, Others: \`"xdg-open"\` `, type: [null, Boolean, String], description: ` @@ -273,6 +392,16 @@ const definitions = { `, flatten, }), + 'bypass-2fa': new Definition('bypass-2fa', { + default: false, + type: Boolean, + description: ` + When creating a Granular Access Token with \`npm token create\`, + setting this to true will allow the token to bypass two-factor + authentication. This is useful for automation and CI/CD workflows. + `, + flatten, + }), ca: new Definition('ca', { default: null, type: [null, String, Array], @@ -458,10 +587,22 @@ const definitions = { `, flatten, }), + 'dangerously-allow-all-scripts': new Definition('dangerously-allow-all-scripts', { + default: false, + type: Boolean, + description: ` + If \`true\`, bypass the \`allowScripts\` policy entirely and run every + dependency install script regardless of whether it was approved or + denied. Intended as a migration escape hatch only; its use is strongly + discouraged. \`--ignore-scripts\` still takes precedence over this + setting. + `, + flatten, + }), depth: new Definition('depth', { default: null, defaultDescription: ` - \`Infinity\` if \`--all\` is set, otherwise \`1\` + \`Infinity\` if \`--all\` is set; otherwise, \`0\` `, type: [null, Number], description: ` @@ -623,6 +764,28 @@ const definitions = { Can be either true (expect some results) or false (expect no results). `, }), + expires: new Definition('expires', { + default: null, + type: [null, Number], + description: ` + When creating a Granular Access Token with \`npm token create\`, + this sets the expiration in days. If not specified, the server + will determine the default expiration. + `, + flatten, + }), + 'extension-file': new Definition('extension-file', { + default: null, + type: [null, path], + description: ` + Path to a project-local npm extension file to load instead of + discovering \`.npm-extension.mjs\` / \`.npm-extension.cjs\` at the + project root. Must resolve inside the project root and use a \`.mjs\` + or \`.cjs\` extension. Only honored from project config or the command + line, never from user, global, or builtin config. + `, + flatten, + }), 'fetch-retries': new Definition('fetch-retries', { default: 2, type: Number, @@ -736,7 +899,7 @@ const definitions = { default: true, type: Boolean, description: ` - Format \`package-lock.json\` or \`npm-shrinkwrap.json\` as a human + Format \`package-lock.json\` as a human readable file. `, flatten, @@ -805,6 +968,29 @@ const definitions = { `, flatten, }), + // the global-ignore-file has its default defined outside of this module + 'global-ignore-file': new Definition('global-ignore-file', { + type: path, + default: '', + defaultDescription: ` + The global --prefix setting plus 'etc/npmignore'. For example, + '/usr/local/etc/npmignore' + `, + description: ` + An additional ignore file applied during \`npm pack\` and \`npm + publish\`, owned by the current user rather than the package. Patterns + follow the same syntax as a package's local \`.npmignore\` file. + Useful for keeping editor metadata (such as \`.idea/\` or \`*.iml\`) + and scratch directories out of every package you publish, without + adding them to each package's own ignore rules. + + The global rules apply in addition to a package's local \`.npmignore\`. + When a package uses a \`files\` field in its \`package.json\`, an entry + in \`files\` that contradicts a global rule (i.e., explicitly includes + a path the global rule would exclude) still wins. + `, + flatten, + }), 'global-style': new Definition('global-style', { default: false, type: Boolean, @@ -847,7 +1033,7 @@ const definitions = { type: Boolean, envExport: false, description: ` - If true, npm will not exit with an error code when \`run-script\` is + If true, npm will not exit with an error code when \`run\` 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. @@ -856,6 +1042,17 @@ const definitions = { `, flatten, }), + 'ignore-extension': new Definition('ignore-extension', { + default: false, + type: Boolean, + description: ` + If true, npm does not import or execute a root \`.npm-extension.mjs\` / + \`.npm-extension.cjs\` file (or one selected via \`extension-file\`). + \`ignore-scripts\` implies \`ignore-extension\`, since both disable + root-owned install-time code. + `, + flatten, + }), 'ignore-scripts': new Definition('ignore-scripts', { default: false, type: Boolean, @@ -864,10 +1061,19 @@ const definitions = { 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 + run\` will still run their intended script if \`ignore-scripts\` is set, but they will *not* run any pre- or post-scripts. + + Setting \`ignore-scripts\` also disables \`.npm-extension\` execution, + as if \`ignore-extension\` were set. `, - flatten, + // ignore-scripts implies ignore-extension: both disable root install-time code + flatten (key, obj, flatOptions) { + flatOptions.ignoreScripts = obj['ignore-scripts'] + if (obj['ignore-scripts']) { + flatOptions.ignoreExtension = true + } + }, }), include: new Definition('include', { default: [], @@ -910,6 +1116,17 @@ const definitions = { `, flatten, }), + 'include-attestations': new Definition('include-attestations', { + default: false, + type: Boolean, + description: ` + When used with \`npm audit signatures --json\`, includes the full + sigstore attestation bundles in the JSON output for each verified + package. The bundles contain DSSE envelopes, verification material, + and transparency log entries. + `, + flatten, + }), 'init-author-email': new Definition('init-author-email', { default: '', hint: '', @@ -936,11 +1153,12 @@ const definitions = { `, }), 'init-license': new Definition('init-license', { - default: 'ISC', + default: '', hint: '', type: String, description: ` The value \`npm init\` should use by default for the package license. + If not set, the license field will be omitted from new packages. `, }), 'init-module': new Definition('init-module', { @@ -954,6 +1172,14 @@ const definitions = { more information, or [npm init](/commands/npm-init). `, }), + 'init-type': new Definition('init-type', { + default: 'commonjs', + type: String, + hint: '', + description: ` + The value that \`npm init\` should use by default for the package.json type field. + `, + }), 'init-version': new Definition('init-version', { default: '1.0.0', type: Semver, @@ -963,6 +1189,14 @@ const definitions = { version number, if not already set in package.json. `, }), + 'init-private': new Definition('init-private', { + default: false, + type: Boolean, + description: ` + The value \`npm init\` should use by default for the package's private flag. + `, + flatten, + }), // 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', { @@ -995,7 +1229,7 @@ const definitions = { `, }), 'init.license': new Definition('init.license', { - default: 'ISC', + default: '', type: String, deprecated: ` Use \`--init-license\` instead. @@ -1188,11 +1422,11 @@ const definitions = { default: null, type: [null, 1, 2, 3, '1', '2', '3'], defaultDescription: ` - Version 3 if no lockfile, auto-converting v1 lockfiles to v3, otherwise + 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: + Set the lockfile format version to be used in package-lock.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 @@ -1264,6 +1498,16 @@ const definitions = { Show extended information in \`ls\`, \`search\`, and \`help-search\`. `, }), + name: new Definition('name', { + default: null, + type: [null, String], + hint: '', + description: ` + When creating a Granular Access Token with \`npm token create\`, + this sets the name/description for the token. + `, + flatten, + }), maxsockets: new Definition('maxsockets', { default: 15, type: Number, @@ -1286,6 +1530,100 @@ const definitions = { `, flatten, }), + 'min-release-age': new Definition('min-release-age', { + default: null, + hint: '', + type: [null, Number], + envExport: false, + description: ` + If set, npm will build the npm tree such that only versions that were + available more than the given number of days ago will be installed. If + there are no versions available for the current set of dependencies, the + command will error. + + This flag is a complement to \`before\`, which accepts an exact date + instead of a relative number of days. The two may coexist (e.g. + \`min-release-age\` in your \`.npmrc\` is preserved when npm internally + spawns a sub-process with \`--before\` while preparing a \`git:\` or + \`github:\` dependency); when both apply, \`before\` wins within a + single source and across sources the standard precedence rules apply. + + When this window stops \`npm audit fix\` from installing a patched + version (because the fix was published too recently), npm keeps the + package at its vulnerable version, warns that the fix was blocked, and + exits with a non-zero code. To install the fix, add the package to + \`min-release-age-exclude\`, or relax \`min-release-age\` or \`before\`. + + Packages whose names match \`min-release-age-exclude\` are exempt from + this filter. + `, + flatten: (key, obj, flatOptions) => { + const age = obj['min-release-age'] + // `hasOwn` so a `before` inherited via ConfigData's prototype chain (lib/index.js) from a lower-priority source doesn't silently win. + // The `: null` clear depends on `Config#flat` iterating sources low → high. + if (age != null && !Object.hasOwn(obj, 'before')) { + flatOptions.before = age ? new Date(Date.now() - (86400000 * age)) : null + } + }, + }), + 'min-release-age-exclude': new Definition('min-release-age-exclude', { + default: [], + hint: '', + type: [Array, String], + envExport: false, + description: ` + A list of package names or \`minimatch\` glob patterns that are exempt + from the \`min-release-age\` (and \`before\`) filter. A matching package + can always resolve to its newest version, even when a release-age window + is set. + + For example, to apply a release-age window to third-party dependencies + while letting internally maintained packages update immediately: + + \`\`\` + min-release-age=7 + min-release-age-exclude[]=@myorg/* + min-release-age-exclude[]=my-internal-pkg + \`\`\` + + Only the named package is exempt; its own dependencies still follow the + release-age policy unless they also match a pattern. Patterns match + against the package name, so \`@myorg/*\` matches \`@myorg/shared-utils\`. + + Excluding a package does not change which registry it is fetched from. You + should own your private scope on the public registry so that nobody else + can publish a package with the same name. + `, + flatten: (key, obj, flatOptions) => { + // The config layer always resolves this to an array (nopt and .npmrc both + // coerce `[Array, String]` to a list, default `[]`), so treat it as one. + // A single value may still pack multiple names as a comma string. + const list = obj[key] + .flatMap(v => String(v).split(',')) + .map(v => v.trim()) + .filter(Boolean) + flatOptions.minReleaseAgeExclude = [...new Set(list)] + }, + }), + 'node-gyp': new Definition('node-gyp', { + default: (() => { + try { + return require.resolve('node-gyp/bin/node-gyp.js') + } catch { + return '' + } + })(), + defaultDescription: ` + The path to the node-gyp bin that ships with npm + `, + type: path, + description: ` + This is the location of the "node-gyp" bin. By default it uses one that ships with npm itself. + + You can use this config to specify your own "node-gyp" to run when it is required to build a package. + `, + flatten, + }), 'node-options': new Definition('node-options', { default: null, type: [null, String], @@ -1326,15 +1664,15 @@ const definitions = { 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. + '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 + \`package-lock.json\` file. They are just not physically installed on disk. If a package type appears in both the \`--include\` and \`--omit\` @@ -1373,6 +1711,15 @@ const definitions = { definitions.omit.flatten('omit', obj, flatOptions) }, }), + orgs: new Definition('orgs', { + default: null, + type: [null, String, Array], + description: ` + When creating a Granular Access Token with \`npm token create\`, + this limits the token access to specific organizations. + `, + flatten, + }), optional: new Definition('optional', { default: null, type: [null, Boolean], @@ -1469,6 +1816,72 @@ const definitions = { `, flatten, }), + packages: new Definition('packages', { + default: [], + type: [null, String, Array], + description: ` + When creating a Granular Access Token with \`npm token create\`, + this limits the token access to specific packages. + `, + flatten, + }), + 'patches-dir': new Definition('patches-dir', { + default: 'patches', + type: String, + description: ` + The directory, relative to the project root, where \`npm patch commit\` + writes patch files for \`patchedDependencies\`. + `, + flatten, + }), + // CLI-only: deliberately no flatten, so a value in .npmrc/env never reaches the install pipeline. + // npm install reads it from the cli layer only, and npm ci rejects it. + 'allow-unused-patches': new Definition('allow-unused-patches', { + default: false, + type: Boolean, + description: ` + Install even when a registered patch in \`patchedDependencies\` matches no + installed package. Does not silence patch apply failures. + + This flag is only honored when passed on the command line; it is ignored + in \`.npmrc\` and environment variables, and rejected by \`npm ci\`. + `, + }), + 'ignore-patch-failures': new Definition('ignore-patch-failures', { + default: false, + type: Boolean, + description: ` + Install even when a registered patch fails to apply, with a warning per + failure. Intended for incident response only. + + This flag is only honored when passed on the command line; it is ignored + in \`.npmrc\` and environment variables, and rejected by \`npm ci\`. + `, + }), + 'edit-dir': new Definition('edit-dir', { + default: null, + type: [null, path], + description: ` + Override the temporary directory used by \`npm patch add\` to prepare a + package for editing. + `, + }), + 'ignore-existing': new Definition('ignore-existing', { + default: false, + type: Boolean, + description: ` + With \`npm patch add\`, discard a previous unfinished edit directory and + start fresh. + `, + }), + 'keep-edit-dir': new Definition('keep-edit-dir', { + default: false, + type: Boolean, + description: ` + With \`npm patch commit\`, do not remove the edit directory after + committing the patch. + `, + }), parseable: new Definition('parseable', { default: false, type: Boolean, @@ -1479,6 +1892,27 @@ const definitions = { `, flatten, }), + 'allow-scripts-pending': new Definition('allow-scripts-pending', { + default: false, + type: Boolean, + description: ` + List packages with install scripts that are not yet covered by the + \`allowScripts\` policy, without modifying \`package.json\`. Only + meaningful for \`npm approve-scripts\`. + `, + flatten, + }), + 'allow-scripts-pin': new Definition('allow-scripts-pin', { + default: true, + type: Boolean, + description: ` + Write pinned (\`pkg@version\`) entries when approving install scripts. + Set to \`false\` to write name-only entries that allow any version. + Has no effect on \`npm deny-scripts\`, which always writes name-only + entries regardless of this setting. + `, + flatten, + }), 'prefer-dedupe': new Definition('prefer-dedupe', { default: false, type: Boolean, @@ -1542,9 +1976,9 @@ const definitions = { }, }), progress: new Definition('progress', { - default: !ciInfo.isCI, + default: !(ciInfo.isCI || !process.stderr.isTTY || !process.stdout.isTTY || process.env.TERM === 'dumb'), defaultDescription: ` - \`true\` unless running in a known CI system + \`true\` when not in CI and both stderr and stdout are TTYs and not in a dumb terminal `, type: Boolean, description: ` @@ -1554,11 +1988,8 @@ const definitions = { 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' + // Only show progress if explicitly enabled AND we have proper TTY environment + flatOptions.progress = !!obj.progress && !!process.stderr.isTTY && !!process.stdout.isTTY && process.env.TERM !== 'dumb' }, }), provenance: new Definition('provenance', { @@ -1674,6 +2105,7 @@ const definitions = { default: false, type: Boolean, short: 'D', + exclusive: ['save-optional', 'save-peer', 'save-prod'], description: ` Save installed packages to a package.json file as \`devDependencies\`. `, @@ -1705,6 +2137,7 @@ const definitions = { default: false, type: Boolean, short: 'O', + exclusive: ['save-dev', 'save-peer', 'save-prod'], description: ` Save installed packages to a package.json file as \`optionalDependencies\`. @@ -1733,6 +2166,7 @@ const definitions = { 'save-peer': new Definition('save-peer', { default: false, type: Boolean, + exclusive: ['save-dev', 'save-optional', 'save-prod'], description: ` Save installed packages to a package.json file as \`peerDependencies\` `, @@ -1778,6 +2212,7 @@ const definitions = { default: false, type: Boolean, short: 'P', + exclusive: ['save-dev', 'save-optional', 'save-peer'], description: ` Save installed packages into \`dependencies\` specifically. This is useful if a package already exists in \`devDependencies\` or @@ -1863,6 +2298,63 @@ const definitions = { flatOptions.projectScope = scope }, }), + scopes: new Definition('scopes', { + default: null, + type: [null, String, Array], + description: ` + When creating a Granular Access Token with \`npm token create\`, + this limits the token access to specific scopes. Provide + a scope name (with or without @ prefix). + `, + flatten, + }), + 'packages-all': new Definition('packages-all', { + default: false, + type: Boolean, + description: ` + When creating a Granular Access Token with \`npm token create\`, + grants the token access to all packages instead of limiting to + specific packages. + `, + flatten, + }), + 'packages-and-scopes-permission': new Definition('packages-and-scopes-permission', { + default: null, + type: [null, 'read-only', 'read-write', 'no-access'], + description: ` + When creating a Granular Access Token with \`npm token create\`, + sets the permission level for packages and scopes. Options are + "read-only", "read-write", or "no-access". + `, + flatten, + }), + 'orgs-permission': new Definition('orgs-permission', { + default: null, + type: [null, 'read-only', 'read-write', 'no-access'], + description: ` + When creating a Granular Access Token with \`npm token create\`, + sets the permission level for organizations. Options are + "read-only", "read-write", or "no-access". + `, + flatten, + }), + password: new Definition('password', { + default: null, + type: [null, String], + description: ` + Password for authentication. Can be provided via command line when + creating tokens, though it's generally safer to be prompted for it. + `, + flatten, + }), + 'token-description': new Definition('token-description', { + default: null, + type: [null, String], + description: ` + Description text for the token when using \`npm token create\`. + `, + flatten, + }), 'script-shell': new Definition('script-shell', { default: null, defaultDescription: ` @@ -1934,20 +2426,6 @@ const definitions = { `, 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, @@ -1992,6 +2470,23 @@ const definitions = { `, flatten, }), + 'strict-allow-scripts': new Definition('strict-allow-scripts', { + default: false, + type: Boolean, + description: ` + If \`true\`, turn the install-script policy from a warning into a hard + error: any dependency with install scripts that is not covered by + \`allowScripts\` will fail the install instead of being blocked with a + warning. + + Dependencies explicitly denied with \`false\` in \`allowScripts\` are + always silently skipped; this setting only affects unreviewed entries + (packages with install scripts that are neither approved nor denied). + \`--ignore-scripts\` and \`--dangerously-allow-all-scripts\` both + override this setting. + `, + flatten, + }), 'strict-ssl': new Definition('strict-ssl', { default: true, type: Boolean, @@ -2012,13 +2507,13 @@ const definitions = { 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 + 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 + + 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) { @@ -2053,6 +2548,16 @@ const definitions = { while still writing the timing file, use \`--silent\`. `, }), + to: new Definition('to', { + default: null, + hint: '', + type: [null, String], + description: ` + Used by \`npm patch update\` to set the version to rebase a patch onto + when it cannot be read from \`package-lock.json\` — for example an + exact-version selector, or a version that has not been installed yet. + `, + }), umask: new Definition('umask', { default: 0, type: Umask, @@ -2127,6 +2632,36 @@ const definitions = { flatten (key, obj, flatOptions) { const value = obj[key] const ciName = ciInfo.name?.toLowerCase().split(' ').join('-') || null + // A more specific sub-category for the detected CI, appended to the + // ci token as `ci/{ci-name}/{sub-ci-name}` when present. + let subCiName = null + if (ciInfo.GITHUB_ACTIONS) { + // Env vars can be absent, empty, or whitespace; normalize before use. + const serverUrl = (process.env.GITHUB_SERVER_URL || '').trim() + const runnerEnv = (process.env.RUNNER_ENVIRONMENT || '').trim() + let serverHost = '' + try { + serverHost = new URL(serverUrl).hostname.toLowerCase() + } catch { + serverHost = '' + } + if (serverHost === 'github.com') { + if (runnerEnv === 'github-hosted') { + subCiName = 'dotcom-hosted' + } else if (runnerEnv === 'self-hosted') { + subCiName = 'dotcom-selfhosted' + } else { + subCiName = 'dotcom' + } + } else if (serverHost === 'ghe.com' || serverHost.endsWith('.ghe.com')) { + subCiName = 'ghecom' + } else if (serverHost) { + subCiName = 'ghes' + } + } + const ci = ciName + ? `ci/${ciName}${subCiName ? `/${subCiName}` : ''}` + : '' let inWorkspaces = false if (obj.workspaces || obj.workspace && obj.workspace.length) { inWorkspaces = true @@ -2137,7 +2672,7 @@ const definitions = { .replace(/\{platform\}/gi, process.platform) .replace(/\{arch\}/gi, process.arch) .replace(/\{workspaces\}/gi, inWorkspaces) - .replace(/\{ci\}/gi, ciName ? `ci/${ciName}` : '') + .replace(/\{ci\}/gi, ci) .trim() // We can't clobber the original or else subsequent flattening will fail @@ -2231,7 +2766,6 @@ const definitions = { 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 diff --git a/workspaces/config/lib/definitions/index.js b/workspaces/config/lib/definitions/index.js index 8255a90442391..b5b63bf2fce12 100644 --- a/workspaces/config/lib/definitions/index.js +++ b/workspaces/config/lib/definitions/index.js @@ -55,12 +55,34 @@ const shorthands = { readonly: ['--read-only'], reg: ['--registry'], iwr: ['--include-workspace-root'], + ws: ['--workspaces'], ...definitionProps.shorthands, } +// These are the configs that we can nerf-dart. Only _auth even has a config definition so we have to explicitly validate them here. +// This is used to validate during "npm config set" and to not warn on loading unknown configs when we see these. +const nerfDarts = [ + '_auth', // Has a config + '_authToken', // Does not have a config + '_password', // Does not have a config + 'certfile', // Does not have a config + 'email', // Does not have a config + 'keyfile', // Does not have a config + 'username', // Does not have a config +] + +const proxyEnv = [ + 'http_proxy', + 'https_proxy', + 'proxy', + 'no_proxy', +] + module.exports = { defaults: definitionProps.defaults, definitions, flatten, + nerfDarts, + proxyEnv, shorthands, } diff --git a/workspaces/config/lib/env-replace.js b/workspaces/config/lib/env-replace.js index c851f6e4d1501..c347be480ed68 100644 --- a/workspaces/config/lib/env-replace.js +++ b/workspaces/config/lib/env-replace.js @@ -1,9 +1,11 @@ // replace any ${ENV} values with the appropriate environ. +// optional "?" modifier can be used like this: ${ENV?} so in case of the variable being not defined, it evaluates into empty string. -const envExpr = /(? f.replace(envExpr, (orig, esc, name) => { - const val = env[name] !== undefined ? env[name] : `$\{${name}}` +module.exports = (f, env) => f.replace(envExpr, (orig, esc, name, modifier) => { + const fallback = modifier === '?' ? '' : `$\{${name}}` + const val = env[name] !== undefined ? env[name] : fallback // consume the escape chars that are relevant. if (esc.length % 2) { diff --git a/workspaces/config/lib/index.js b/workspaces/config/lib/index.js index 4aa76d8e2d9a2..4121c2a7a3840 100644 --- a/workspaces/config/lib/index.js +++ b/workspaces/config/lib/index.js @@ -15,6 +15,13 @@ const { mkdir, } = require('node:fs/promises') +// TODO global-prefix and local-prefix are set by lib/set-envs.js. This may not be the best way to persist those, if we even want to persist them (see set-envs.js) +const internalEnv = [ + 'npm-version', + 'global-prefix', + 'local-prefix', +] + const fileExists = (...p) => stat(resolve(...p)) .then((st) => st.isFile()) .catch(() => false) @@ -52,6 +59,11 @@ class Config { #flatten // populated the first time we flatten the object #flatOptions = null + #warnings = [] + // Unknown configs collected during load(), aggregated and thrown by `BaseCommand.validateCli` once command-specific definitions are known. + // Entries: { where, key, baseKey, source }. `baseKey` is non-null only for scoped keys (e.g. `:foo`) and holds the trailing segment. + // `env` and `publishConfig` entries warn instead of error. + #unknownConfigs = [] static get typeDefs () { return typeDefs @@ -61,6 +73,7 @@ class Config { definitions, shorthands, flatten, + nerfDarts = [], npmPath, // options just to override in tests, mostly @@ -70,19 +83,13 @@ class Config { execPath = process.execPath, cwd = process.cwd(), excludeNpmCwd = false, + warn = true, }) { - // turn the definitions into nopt's weirdo syntax + this.nerfDarts = nerfDarts 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') - } - } + // turn the definitions into nopt's weirdo syntax + const { types, defaults, deprecated } = getTypesFromDefinitions(definitions) + this.deprecated = deprecated this.#flatten = flatten this.types = types @@ -123,13 +130,20 @@ class Config { this.sources = new Map([]) - this.list = [] for (const { data } of this.data.values()) { this.list.unshift(data) } - Object.freeze(this.list) this.#loaded = false + this.warn = warn + } + + get list () { + const list = [] + for (const { data } of this.data.values()) { + list.unshift(data) + } + return list } get loaded () { @@ -272,6 +286,7 @@ class Config { } try { + // This does not have an actual definition because this is not user definable 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 @@ -302,6 +317,24 @@ class Config { configurable: true, enumerable: true, }) + + // like globalconfig, the global-ignore-file default is computed from + // the current prefix. since prefix may be overridden after defaults + // load (via cli, env, or userconfig), expose a getter and only freeze + // to a value once explicitly set. + Object.defineProperty(data, 'global-ignore-file', { + get: () => resolve(this.#get('prefix'), 'etc/npmignore'), + set (value) { + Object.defineProperty(data, 'global-ignore-file', { + value, + configurable: true, + writable: true, + enumerable: true, + }) + }, + configurable: true, + enumerable: true, + }) } loadHome () { @@ -346,10 +379,21 @@ class Config { } loadCLI () { + for (const s of Object.keys(this.shorthands)) { + if (s.length > 1 && this.argv.includes(`-${s}`)) { + throw Object.assign( + new Error(`-${s} is not a valid single-hyphen cli flag. Did you mean --${s}?`), + { code: 'EUNKNOWNCONFIG' } + ) + } + } nopt.invalidHandler = (k, val, type) => this.invalidHandler(k, val, type, 'command line options', 'cli') + nopt.unknownHandler = (k, next) => this.unknownHandler(k, next) + nopt.abbrevHandler = this.abbrevHandler const conf = nopt(this.types, this.shorthands, this.argv) nopt.invalidHandler = null + nopt.unknownHandler = null this.parsedArgv = conf.argv delete conf.argv this.#loadObject(conf, 'cli', 'command line options') @@ -412,6 +456,32 @@ class Config { } } } + + // Top-level `email`, `certfile`, and `keyfile` must be in nerfdart form. + // certfile/keyfile are an mTLS pair: drop a lone one rather than migrating it. + if (this.get('email', entryWhere)) { + authProblems.push({ + action: 'rename', + from: 'email', + to: `${nerfedReg}:email`, + where: entryWhere, + }) + } + for (const key of ['certfile', 'keyfile']) { + if (this.get(key, entryWhere)) { + const pair = key === 'certfile' ? 'keyfile' : 'certfile' + if (!this.get(pair, entryWhere)) { + authProblems.push({ action: 'delete', key, where: entryWhere }) + } else { + authProblems.push({ + action: 'rename', + from: key, + to: `${nerfedReg}:${key}`, + where: entryWhere, + }) + } + } + } } } @@ -462,10 +532,15 @@ class Config { 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) + // If the destination already exists, drop the source rather than clobber. + if (this.find(problem.to) !== null) { + this.delete(problem.from, problem.where) + } else { + 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) + } } } } @@ -515,6 +590,19 @@ class Config { log.warn('invalid config', msg, desc) } + abbrevHandler (short, long) { + throw Object.assign( + new Error(`Invalid abbreviated flag "--${short}". Did you mean "--${long}"?`), + { code: 'EUNKNOWNCONFIG' } + ) + } + + unknownHandler (key, next) { + if (next) { + this.queueWarning(`unknown:${next}`, `"${next}" is being parsed as a normal command line argument.`) + } + } + #getOneOfKeywords (mustBe, typeDesc) { let keyword if (mustBe.length === 1 && typeDesc.includes(Array)) { @@ -553,7 +641,7 @@ class Config { } } else { conf.raw = obj - for (const [key, value] of Object.entries(obj)) { + outer: for (const [key, value] of Object.entries(obj)) { const k = envReplace(key, this.env) const v = this.parseField(value, k) if (where !== 'default') { @@ -561,18 +649,80 @@ class Config { 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}`) + // when loading from env, skip only if sibling was explicitly set via CLI + if (where === 'env') { + const cliData = this.data.get('cli').data + if (Object.hasOwn(cliData, exclusive)) { + continue outer + } + } + throw new TypeError(`--${key} cannot be provided when using --${exclusive}`) } } } } + if (where !== 'default' || key === 'npm-version') { + this.checkUnknown(where, key, source) + } conf.data[k] = v } } } + checkUnknown (where, key, source = null) { + if (this.definitions[key]) { + return + } + if (internalEnv.includes(key)) { + return + } + const scoped = key.includes(':') + let baseKey = null + if (scoped) { + baseKey = key.split(':').pop() + if (this.definitions[baseKey] || this.nerfDarts.includes(baseKey)) { + return + } + } + + const entry = { where, key, baseKey, source: source ?? this.data.get(where)?.source ?? null } + this.#unknownConfigs.push(entry) + + // publishConfig is handled by publish/unpublish/config commands and is out of scope for the npm 12 breaking change (tracked separately). + // Keep it as a queued warning so existing behavior is preserved. + if (where === 'publishConfig') { + const hint = ' See `npm help npmrc` for supported config options.' + const msg = scoped + ? `Unknown ${where} config "${baseKey}" (${key}). This will stop working in the next major version of npm.${hint}` + : `Unknown ${where} config "${key}". This will stop working in the next major version of npm.${hint}` + this.queueWarning(scoped ? baseKey : key, msg) + return + } + + // env unknowns are an explicit carve-out for npm 12. + // setEnvs() exports npm_config_* for child processes and loadEnv() re-ingests them; erroring here would break npm-invoked-npm and many CI setups. + // Keep as warning. Planned to error in npm 13. + if (where === 'env') { + const hint = ' See `npm help npmrc` for supported config options.' + const msg = scoped + ? `Unknown ${where} config "${baseKey}" (${key}). This will error in a future major version of npm.${hint}` + : `Unknown ${where} config "${key}". This will error in a future major version of npm.${hint}` + this.queueWarning(scoped ? baseKey : key, msg) + } + + // cli + file sources (builtin/project/user/global): collected only. + // Aggregated and thrown by `BaseCommand.validateCli` after subcommand flag resolution so command-specific flags can be allow-listed first. + } + + // Returns unknown-config entries for a given source ('cli', 'builtin', 'project', 'user', 'global') or all entries except `env` and `publishConfig` when omitted. + getUnknownConfigs (where) { + if (where) { + return this.#unknownConfigs.filter(u => u.where === where) + } + return this.#unknownConfigs.filter(u => u.where !== 'env' && u.where !== 'publishConfig') + } + #checkDeprecated (key) { - // XXX(npm9+) make this throw an error if (this.deprecated[key]) { log.warn('config', key, this.deprecated[key]) } @@ -626,7 +776,7 @@ class Config { // 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 + // which causes some calamities. 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') @@ -725,13 +875,8 @@ class Config { 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') - } + // Historically, save('user') would "de-nerf" email — move a scoped `:email` into a top-level `email` key — because npm used to warn on nerfed email. + // In npm 12 the top-level `email` key is a hard error, so we keep email in its scoped form. } // We need the actual raw data before we called parseField so that we are @@ -759,11 +904,7 @@ class Config { 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) - } + // In npm 12, top-level `email` is a hard error — don't de-nerf it here either. } this.delete(`${nerfed}:_authToken`, level) this.delete(`${nerfed}:_auth`, level) @@ -782,7 +923,9 @@ class Config { // 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') + // NOTE: we intentionally do NOT delete `${nerfed}:email` here anymore. + // In npm 11 and earlier, top-level `email` was the canonical form (with getCredentialsByURI copying scoped email up to top-level on read), and setCredentialsByURI cleared the scoped copy to enforce that invariant. + // In npm 12 top-level `email` is a hard error and the scoped nerfdart form is canonical, so preserve any existing scoped email across login. if (certfile && keyfile) { this.set(`${nerfed}:certfile`, certfile, 'user') this.set(`${nerfed}:keyfile`, keyfile, 'user') @@ -813,17 +956,13 @@ class Config { // 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 + // email is handled differently, it used to always be nerfed and now it never should be. + // In npm 12 the top-level `email` key is a hard error, so we stop copying scoped email back to the top-level here. // 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 } @@ -871,6 +1010,35 @@ class Config { setEnvs () { setEnvs(this) } + + removeWarning (key) { + this.#warnings = this.#warnings.filter(w => w.type !== key) + } + + getUnknownPositionals () { + return this.#warnings + .filter(w => w.type.startsWith('unknown:')) + .map(w => w.type.slice('unknown:'.length)) + } + + removeUnknownPositional (value) { + this.removeWarning(`unknown:${value}`) + } + + queueWarning (type, ...args) { + if (!this.warn) { + this.#warnings.push({ type, args }) + } else { + log.warn(...args) + } + } + + logWarnings () { + for (const warning of this.#warnings) { + log.warn(...warning.args) + } + this.#warnings = [] + } } const _loadError = Symbol('loadError') @@ -928,4 +1096,21 @@ class ConfigData { } } +const getTypesFromDefinitions = (definitions) => { + const types = {} + const defaults = {} + const deprecated = {} + + for (const [key, def] of Object.entries(definitions)) { + defaults[key] = def.default + types[key] = def.type + if (def.deprecated) { + deprecated[key] = def.deprecated.trim().replace(/\n +/, '\n') + } + } + + return { types, defaults, deprecated } +} + module.exports = Config +module.exports.getTypesFromDefinitions = getTypesFromDefinitions diff --git a/workspaces/config/lib/parse-allow-scripts-list.js b/workspaces/config/lib/parse-allow-scripts-list.js new file mode 100644 index 0000000000000..0f13d4a75b634 --- /dev/null +++ b/workspaces/config/lib/parse-allow-scripts-list.js @@ -0,0 +1,23 @@ +// Parse an `allow-scripts` raw config value (string or array of strings) +// into a flat array of trimmed package-spec entries. Shared between the +// CLI/env layer (via the `allow-scripts` definition's `flatten`) and the +// package.json / .npmrc layer (in lib/utils/resolve-allow-scripts.js) so +// both paths agree on quoting, whitespace, and duplicate handling. +const parseAllowScriptsList = (raw) => { + const parts = [] + const entries = Array.isArray(raw) ? raw : (typeof raw === 'string' ? [raw] : []) + for (const entry of entries) { + if (typeof entry !== 'string') { + continue + } + for (const part of entry.split(',')) { + const trimmed = part.trim() + if (trimmed) { + parts.push(trimmed) + } + } + } + return parts +} + +module.exports = parseAllowScriptsList diff --git a/workspaces/config/lib/set-envs.js b/workspaces/config/lib/set-envs.js index b6f5a30562ab1..12719b5647836 100644 --- a/workspaces/config/lib/set-envs.js +++ b/workspaces/config/lib/set-envs.js @@ -90,17 +90,22 @@ const setEnvs = (config) => { // also set some other common nice envs that we want to rely on env.HOME = config.home + // TODO this may not be the best away to persist these 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 + // note: this doesn't affect 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'] } + // the node-gyp bin uses this so we always set it + env.npm_config_node_gyp = cliConf['node-gyp'] + // this doesn't have a full definition so we manually export it here + env.npm_config_npm_version = cliConf['npm-version'] || 'unknown' env.npm_execpath = config.npmBin env.NODE = env.npm_node_execpath = config.execPath } diff --git a/workspaces/config/package.json b/workspaces/config/package.json index 04e6e55c3efa9..09bad8c20829d 100644 --- a/workspaces/config/package.json +++ b/workspaces/config/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/config", - "version": "8.3.4", + "version": "11.0.0-pre.1", "files": [ "bin/", "lib/" @@ -17,11 +17,12 @@ "scripts": { "test": "tap", "snap": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "nyc-arg": [ @@ -30,27 +31,27 @@ ] }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", + "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-globals": "^1.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/template-oss": "5.1.1", "tap": "^16.3.8" }, "dependencies": { - "@npmcli/map-workspaces": "^3.0.2", - "@npmcli/package-json": "^5.1.1", + "@npmcli/map-workspaces": "^6.0.0", + "@npmcli/package-json": "^8.0.0", "ci-info": "^4.0.0", - "ini": "^4.1.2", - "nopt": "^7.2.1", - "proc-log": "^4.2.0", + "ini": "^7.0.0", + "nopt": "^10.0.1", + "proc-log": "^7.0.0", "semver": "^7.3.5", - "walk-up-path": "^3.0.1" + "walk-up-path": "^4.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../../scripts/template-oss/index.js" } } diff --git a/workspaces/config/tap-snapshots/test/definitions/definition.js.test.cjs b/workspaces/config/tap-snapshots/test/definitions/definition.js.test.cjs index e405d599029ec..11c48bd946a01 100644 --- a/workspaces/config/tap-snapshots/test/definitions/definition.js.test.cjs +++ b/workspaces/config/tap-snapshots/test/definitions/definition.js.test.cjs @@ -27,7 +27,7 @@ exports[`test/definitions/definition.js TAP basic definition > description of de a number -This config can not be used with: \`x\` +This config cannot be used with: \`x\` ` exports[`test/definitions/definition.js TAP basic definition > human-readable description 1`] = ` diff --git a/workspaces/config/tap-snapshots/test/index.js.test.cjs b/workspaces/config/tap-snapshots/test/index.js.test.cjs index eccdbee3abced..935f328ae5659 100644 --- a/workspaces/config/tap-snapshots/test/index.js.test.cjs +++ b/workspaces/config/tap-snapshots/test/index.js.test.cjs @@ -5,26 +5,6 @@ * Make sure to inspect the output below. Do not ignore changes! */ 'use strict' -exports[`test/index.js TAP credentials management def_auth > default registry 1`] = ` -Object { - "auth": "aGVsbG86d29ybGQ=", - "password": "world", - "username": "hello", -} -` - -exports[`test/index.js TAP credentials management def_auth > default registry after set 1`] = ` -Object { - "auth": "aGVsbG86d29ybGQ=", - "password": "world", - "username": "hello", -} -` - -exports[`test/index.js TAP credentials management def_auth > other registry 1`] = ` -Object {} -` - exports[`test/index.js TAP credentials management def_authEnv > default registry 1`] = ` Object { "auth": "\${PATH}", @@ -37,54 +17,6 @@ exports[`test/index.js TAP credentials management def_authEnv > other registry 1 Object {} ` -exports[`test/index.js TAP credentials management def_passNoUser > default registry 1`] = ` -Object { - "email": "i@izs.me", -} -` - -exports[`test/index.js TAP credentials management def_passNoUser > other registry 1`] = ` -Object { - "email": "i@izs.me", -} -` - -exports[`test/index.js TAP credentials management def_userNoPass > default registry 1`] = ` -Object { - "email": "i@izs.me", -} -` - -exports[`test/index.js TAP credentials management def_userNoPass > other registry 1`] = ` -Object { - "email": "i@izs.me", -} -` - -exports[`test/index.js TAP credentials management def_userpass > default registry 1`] = ` -Object { - "auth": "aGVsbG86d29ybGQ=", - "email": "i@izs.me", - "password": "world", - "username": "hello", -} -` - -exports[`test/index.js TAP credentials management def_userpass > default registry after set 1`] = ` -Object { - "auth": "aGVsbG86d29ybGQ=", - "email": "i@izs.me", - "password": "world", - "username": "hello", -} -` - -exports[`test/index.js TAP credentials management def_userpass > other registry 1`] = ` -Object { - "email": "i@izs.me", -} -` - exports[`test/index.js TAP credentials management nerfed_auth > default registry 1`] = ` Object { "auth": "aGVsbG86d29ybGQ=", @@ -174,7 +106,6 @@ exports[`test/index.js TAP credentials management nerfed_mtlsUserPass > default Object { "auth": "aGVsbG86d29ybGQ=", "certfile": "/path/to/cert", - "email": "i@izs.me", "keyfile": "/path/to/key", "password": "world", "username": "hello", @@ -182,9 +113,7 @@ Object { ` exports[`test/index.js TAP credentials management nerfed_mtlsUserPass > other registry 1`] = ` -Object { - "email": "i@izs.me", -} +Object {} ` exports[`test/index.js TAP credentials management nerfed_userpass > default registry 1`] = ` @@ -199,31 +128,12 @@ Object { exports[`test/index.js TAP credentials management nerfed_userpass > default registry after set 1`] = ` Object { "auth": "aGVsbG86d29ybGQ=", - "email": "i@izs.me", "password": "world", "username": "hello", } ` exports[`test/index.js TAP credentials management nerfed_userpass > other registry 1`] = ` -Object { - "email": "i@izs.me", -} -` - -exports[`test/index.js TAP credentials management none_authToken > default registry 1`] = ` -Object { - "token": "0bad1de4", -} -` - -exports[`test/index.js TAP credentials management none_authToken > default registry after set 1`] = ` -Object { - "token": "0bad1de4", -} -` - -exports[`test/index.js TAP credentials management none_authToken > other registry 1`] = ` Object {} ` @@ -235,14 +145,6 @@ exports[`test/index.js TAP credentials management none_emptyConfig > other regis Object {} ` -exports[`test/index.js TAP credentials management none_lcAuthToken > default registry 1`] = ` -Object {} -` - -exports[`test/index.js TAP credentials management none_lcAuthToken > other registry 1`] = ` -Object {} -` - exports[`test/index.js TAP credentials management none_noConfig > default registry 1`] = ` Object {} ` diff --git a/workspaces/config/tap-snapshots/test/type-description.js.test.cjs b/workspaces/config/tap-snapshots/test/type-description.js.test.cjs index a78afd3d4ba75..0e3a63289772e 100644 --- a/workspaces/config/tap-snapshots/test/type-description.js.test.cjs +++ b/workspaces/config/tap-snapshots/test/type-description.js.test.cjs @@ -15,13 +15,47 @@ Object { null, "restricted", "public", + "private", ], "all": Array [ "boolean value (true or false)", ], + "allow-directory": Array [ + "all", + "none", + "root", + ], + "allow-file": Array [ + "all", + "none", + "root", + ], + "allow-git": Array [ + "all", + "none", + "root", + ], + "allow-remote": Array [ + "all", + "none", + "root", + ], "allow-same-version": Array [ "boolean value (true or false)", ], + "allow-scripts": Array [ + Function String(), + Function Array(), + ], + "allow-scripts-pending": Array [ + "boolean value (true or false)", + ], + "allow-scripts-pin": Array [ + "boolean value (true or false)", + ], + "allow-unused-patches": Array [ + "boolean value (true or false)", + ], "also": Array [ null, "dev", @@ -55,6 +89,9 @@ Object { "boolean value (true or false)", Function String(), ], + "bypass-2fa": Array [ + "boolean value (true or false)", + ], "ca": Array [ null, Function String(), @@ -95,6 +132,9 @@ Object { null, Function String(), ], + "dangerously-allow-all-scripts": Array [ + "boolean value (true or false)", + ], "depth": Array [ null, "numeric value", @@ -133,6 +173,10 @@ Object { "dry-run": Array [ "boolean value (true or false)", ], + "edit-dir": Array [ + null, + "valid filesystem path", + ], "editor": Array [ Function String(), ], @@ -147,6 +191,14 @@ Object { null, "boolean value (true or false)", ], + "expires": Array [ + null, + "numeric value", + ], + "extension-file": Array [ + null, + "valid filesystem path", + ], "fetch-retries": Array [ "numeric value", ], @@ -183,6 +235,9 @@ Object { "global": Array [ "boolean value (true or false)", ], + "global-ignore-file": Array [ + "valid filesystem path", + ], "global-style": Array [ "boolean value (true or false)", ], @@ -199,6 +254,15 @@ Object { "if-present": Array [ "boolean value (true or false)", ], + "ignore-existing": Array [ + "boolean value (true or false)", + ], + "ignore-extension": Array [ + "boolean value (true or false)", + ], + "ignore-patch-failures": Array [ + "boolean value (true or false)", + ], "ignore-scripts": Array [ "boolean value (true or false)", ], @@ -209,6 +273,9 @@ Object { "optional", "peer", ], + "include-attestations": Array [ + "boolean value (true or false)", + ], "include-staged": Array [ "boolean value (true or false)", ], @@ -231,6 +298,12 @@ Object { "init-module": Array [ "valid filesystem path", ], + "init-private": Array [ + "boolean value (true or false)", + ], + "init-type": Array [ + Function String(), + ], "init-version": Array [ "full valid SemVer string", ], @@ -265,6 +338,9 @@ Object { "json": Array [ "boolean value (true or false)", ], + "keep-edit-dir": Array [ + "boolean value (true or false)", + ], "key": Array [ null, Function String(), @@ -322,6 +398,21 @@ Object { "message": Array [ Function String(), ], + "min-release-age": Array [ + null, + "numeric value", + ], + "min-release-age-exclude": Array [ + Function Array(), + Function String(), + ], + "name": Array [ + null, + Function String(), + ], + "node-gyp": Array [ + "valid filesystem path", + ], "node-options": Array [ null, Function String(), @@ -351,6 +442,17 @@ Object { null, "boolean value (true or false)", ], + "orgs": Array [ + null, + Function String(), + Function Array(), + ], + "orgs-permission": Array [ + null, + "read-only", + "read-write", + "no-access", + ], "os": Array [ null, Function String(), @@ -372,9 +474,30 @@ Object { "package-lock-only": Array [ "boolean value (true or false)", ], + "packages": Array [ + null, + Function String(), + Function Array(), + ], + "packages-all": Array [ + "boolean value (true or false)", + ], + "packages-and-scopes-permission": Array [ + null, + "read-only", + "read-write", + "no-access", + ], "parseable": Array [ "boolean value (true or false)", ], + "password": Array [ + null, + Function String(), + ], + "patches-dir": Array [ + Function String(), + ], "prefer-dedupe": Array [ "boolean value (true or false)", ], @@ -459,6 +582,11 @@ Object { "scope": Array [ Function String(), ], + "scopes": Array [ + null, + Function String(), + Function Array(), + ], "script-shell": Array [ null, Function String(), @@ -478,15 +606,15 @@ Object { "shell": Array [ Function String(), ], - "shrinkwrap": Array [ - "boolean value (true or false)", - ], "sign-git-commit": Array [ "boolean value (true or false)", ], "sign-git-tag": Array [ "boolean value (true or false)", ], + "strict-allow-scripts": Array [ + "boolean value (true or false)", + ], "strict-peer-deps": Array [ "boolean value (true or false)", ], @@ -502,6 +630,14 @@ Object { "timing": Array [ "boolean value (true or false)", ], + "to": Array [ + null, + Function String(), + ], + "token-description": Array [ + null, + Function String(), + ], "umask": Array [ "octal number in range 0o000..0o777 (0..511)", ], diff --git a/workspaces/config/test/definitions/definitions.js b/workspaces/config/test/definitions/definitions.js index 2090e0dd32008..3f89aef92dc19 100644 --- a/workspaces/config/test/definitions/definitions.js +++ b/workspaces/config/test/definitions/definitions.js @@ -1,6 +1,7 @@ const t = require('tap') const { resolve } = require('node:path') const mockGlobals = require('@npmcli/mock-globals') +const Module = require('node:module') // have to fake the node version, or else it'll only pass on this one mockGlobals(t, { 'process.version': 'v14.8.0', 'process.env.NODE_ENV': undefined }) @@ -32,6 +33,23 @@ t.test('basic flattening function camelCases from css-case', t => { t.end() }) +t.test('access flattening maps private to restricted', t => { + const definitions = mockDefs() + const flatPrivate = {} + definitions.access.flatten('access', { access: 'private' }, flatPrivate) + t.equal(flatPrivate.access, 'restricted', 'private is mapped to restricted') + const flatRestricted = {} + definitions.access.flatten('access', { access: 'restricted' }, flatRestricted) + t.equal(flatRestricted.access, 'restricted', 'restricted is passed through') + const flatPublic = {} + definitions.access.flatten('access', { access: 'public' }, flatPublic) + t.equal(flatPublic.access, 'public', 'public is passed through') + const flatNull = {} + definitions.access.flatten('access', { access: null }, flatNull) + t.equal(flatNull.access, null, 'null is passed through') + t.end() +}) + t.test('editor', t => { t.test('has EDITOR and VISUAL, use EDITOR', t => { mockGlobals(t, { 'process.env': { EDITOR: 'vim', VISUAL: 'mate' } }) @@ -402,6 +420,7 @@ t.test('progress', t => { const flat = {} + // Test flatten function behavior mockDefs().progress.flatten('progress', {}, flat) t.strictSame(flat, { progress: false }) @@ -417,6 +436,59 @@ t.test('progress', t => { mockDefs().progress.flatten('progress', { progress: true }, flat) t.strictSame(flat, { progress: false }) + // Ensures consistency between default and flatOptions behavior + t.test('default value consistency', t => { + // Test case 1: Both TTYs, normal terminal, not CI + setEnv({ tty: true, term: 'xterm' }) + const def1 = mockDefs({ 'ci-info': { isCI: false, name: null } }).progress + t.equal(def1.default, true, 'default should be true when both TTYs, normal terminal, and not CI') + + // Test case 2: No TTYs, not CI + setEnv({ tty: false, term: 'xterm' }) + const def2 = mockDefs({ 'ci-info': { isCI: false, name: null } }).progress + t.equal(def2.default, false, 'default should be false when no TTYs') + + // Test case 3: Both TTYs but dumb terminal, not CI + setEnv({ tty: true, term: 'dumb' }) + const def3 = mockDefs({ 'ci-info': { isCI: false, name: null } }).progress + t.equal(def3.default, false, 'default should be false in dumb terminal') + + // Test case 4: Mixed TTY states, not CI + mockGlobals(t, { + 'process.stderr.isTTY': true, + 'process.stdout.isTTY': false, + 'process.env.TERM': 'xterm', + }) + const def4 = mockDefs({ 'ci-info': { isCI: false, name: null } }).progress + t.equal(def4.default, false, 'default should be false when only one TTY') + + // Test case 5: Good TTY environment but in CI + setEnv({ tty: true, term: 'xterm' }) + const def5 = mockDefs({ 'ci-info': { isCI: true, name: 'github-actions' } }).progress + t.equal(def5.default, false, 'default should be false in CI even with good TTY environment') + + t.end() + }) + + // Test that flatten behavior is independent of CI detection + t.test('flatten function ignores CI detection', t => { + const flatObj = {} + + // Test that CI doesn't affect flatten behavior when user explicitly enables + setEnv({ tty: true, term: 'xterm' }) + const defsCI = mockDefs({ 'ci-info': { isCI: true, name: 'github-actions' } }) + defsCI.progress.flatten('progress', { progress: true }, flatObj) + t.equal(flatObj.progress, true, 'flatten should enable progress in CI if user explicitly sets true and TTY is available') + + // Test that non-CI doesn't guarantee flatten success if TTY is bad + setEnv({ tty: false, term: 'xterm' }) + const defsNoCI = mockDefs({ 'ci-info': { isCI: false, name: null } }) + defsNoCI.progress.flatten('progress', { progress: true }, flatObj) + t.equal(flatObj.progress, false, 'flatten should disable progress outside CI if TTY is not available') + + t.end() + }) + t.end() }) @@ -445,7 +517,7 @@ t.test('search options', t => { description: 'test description', exclude: 'test search exclude', limit: 99, - staleneess: 99, + staleness: 99, } const obj = {} @@ -531,16 +603,10 @@ t.test('strictSSL', t => { t.end() }) -t.test('shrinkwrap/package-lock', t => { - const obj = { shrinkwrap: false } +t.test('package-lock', t => { + const obj = {} const flat = {} - mockDefs().shrinkwrap.flatten('shrinkwrap', obj, flat) - t.strictSame(flat, { packageLock: false }) - obj.shrinkwrap = true - mockDefs().shrinkwrap.flatten('shrinkwrap', obj, flat) - t.strictSame(flat, { packageLock: true }) - delete obj.shrinkwrap obj['package-lock'] = false mockDefs()['package-lock'].flatten('package-lock', obj, flat) t.strictSame(flat, { packageLock: false }) @@ -794,6 +860,102 @@ t.test('user-agent', t => { t.end() }) +t.test('user-agent github actions ci variants', t => { + const npmVersion = '1.2.3' + const base = `npm/${npmVersion} node/${process.version} ` + + `${process.platform} ${process.arch} workspaces/false` + + const cases = [ + { + name: 'dotcom + github-hosted runner', + env: { GITHUB_SERVER_URL: 'https://github.com', RUNNER_ENVIRONMENT: 'github-hosted' }, + expect: `${base} ci/github-actions/dotcom-hosted`, + }, + { + name: 'dotcom + self-hosted runner', + env: { GITHUB_SERVER_URL: 'https://github.com', RUNNER_ENVIRONMENT: 'self-hosted' }, + expect: `${base} ci/github-actions/dotcom-selfhosted`, + }, + { + name: 'dotcom + missing runner environment', + env: { GITHUB_SERVER_URL: 'https://github.com', RUNNER_ENVIRONMENT: undefined }, + expect: `${base} ci/github-actions/dotcom`, + }, + { + name: 'dotcom + whitespace runner environment', + env: { GITHUB_SERVER_URL: 'https://github.com', RUNNER_ENVIRONMENT: ' ' }, + expect: `${base} ci/github-actions/dotcom`, + }, + { + name: 'ghe.com tenant', + env: { GITHUB_SERVER_URL: 'https://octocorp.ghe.com', RUNNER_ENVIRONMENT: 'github-hosted' }, + expect: `${base} ci/github-actions/ghecom`, + }, + { + name: 'bare ghe.com host', + env: { GITHUB_SERVER_URL: 'https://ghe.com', RUNNER_ENVIRONMENT: 'github-hosted' }, + expect: `${base} ci/github-actions/ghecom`, + }, + { + name: 'ghe.com only in path is treated as ghes', + env: { GITHUB_SERVER_URL: 'https://evil.example/x.ghe.com', RUNNER_ENVIRONMENT: 'self-hosted' }, + expect: `${base} ci/github-actions/ghes`, + }, + { + name: 'ghes (non-empty, non github.com, non ghe.com)', + env: { GITHUB_SERVER_URL: 'https://github.example.com', RUNNER_ENVIRONMENT: 'self-hosted' }, + expect: `${base} ci/github-actions/ghes`, + }, + { + name: 'missing server url stays generic', + env: { GITHUB_SERVER_URL: undefined, RUNNER_ENVIRONMENT: undefined }, + expect: `${base} ci/github-actions`, + }, + { + name: 'whitespace server url stays generic', + env: { GITHUB_SERVER_URL: ' ', RUNNER_ENVIRONMENT: 'github-hosted' }, + expect: `${base} ci/github-actions`, + }, + ] + + for (const { name, env, expect } of cases) { + t.test(name, t => { + mockGlobals(t, { 'process.env': env }) + const defs = mockDefs({ + 'ci-info': { isCi: true, name: 'GitHub Actions', GITHUB_ACTIONS: true }, + }) + const obj = { + 'npm-version': npmVersion, + 'user-agent': defs['user-agent'].default, + } + const flat = {} + defs['user-agent'].flatten('user-agent', obj, flat) + t.equal(flat.userAgent, expect) + t.equal(process.env.npm_config_user_agent, flat.userAgent, 'npm_user_config environment is set') + t.end() + }) + } + + t.test('non github-actions ci is unchanged', t => { + mockGlobals(t, { + 'process.env': { GITHUB_SERVER_URL: 'https://github.com', RUNNER_ENVIRONMENT: 'github-hosted' }, + }) + const defs = mockDefs({ + 'ci-info': { isCi: true, name: 'Travis CI', GITHUB_ACTIONS: false }, + }) + const obj = { + 'npm-version': npmVersion, + 'user-agent': defs['user-agent'].default, + } + const flat = {} + defs['user-agent'].flatten('user-agent', obj, flat) + t.equal(flat.userAgent, `${base} ci/travis-ci`) + t.end() + }) + + t.end() +}) + t.test('save-prefix', t => { const obj = { 'save-exact': true, @@ -966,3 +1128,188 @@ t.test('otp changes auth-type', t => { t.strictSame(obj, { 'auth-type': 'legacy', otp: 123456 }) t.end() }) + +t.test('node-gyp', t => { + t.test('when node-gyp is available', t => { + const defs = mockDefs() + t.type(defs['node-gyp'].default, 'string') + t.ok(defs['node-gyp'].default.length > 0, 'has a default path') + t.ok(defs['node-gyp'].default.includes('node-gyp'), 'path contains node-gyp') + t.end() + }) + + t.test('when node-gyp is not available', t => { + const origResolve = Module._resolveFilename + + Module._resolveFilename = function (request, parent, isMain, options) { + if (request === 'node-gyp/bin/node-gyp.js') { + const err = new Error(`Cannot find module '${request}'`) + err.code = 'MODULE_NOT_FOUND' + throw err + } + return origResolve.call(this, request, parent, isMain, options) + } + + try { + const defs = require('../../lib/definitions/definitions.js') + t.equal(defs['node-gyp'].default, '', 'returns empty string when node-gyp not found') + } finally { + // Restore the original resolve + Module._resolveFilename = origResolve + } + + t.end() + }) + + t.end() +}) + +t.test('allow-git defaults to none and flattens to allowGit', t => { + const defs = mockDefs() + t.equal(defs['allow-git'].default, 'none') + t.strictSame(defs['allow-git'].type, ['all', 'none', 'root']) + const flat = {} + defs['allow-git'].flatten('allow-git', { 'allow-git': 'root' }, flat) + t.strictSame(flat, { allowGit: 'root' }) + t.end() +}) + +t.test('allow-remote defaults to none and flattens to allowRemote', t => { + const defs = mockDefs() + t.equal(defs['allow-remote'].default, 'none') + t.strictSame(defs['allow-remote'].type, ['all', 'none', 'root']) + const flat = {} + defs['allow-remote'].flatten('allow-remote', { 'allow-remote': 'all' }, flat) + t.strictSame(flat, { allowRemote: 'all' }) + t.end() +}) + +t.test('allow-file and allow-directory still default to all', t => { + const defs = mockDefs() + t.equal(defs['allow-file'].default, 'all', 'allow-file unchanged') + t.equal(defs['allow-directory'].default, 'all', 'allow-directory unchanged') + t.end() +}) + +t.test('allow-scripts', t => { + t.test('defaults to empty string and flattens to []', t => { + const defs = mockDefs() + t.equal(defs['allow-scripts'].default, '') + const flat = {} + defs['allow-scripts'].flatten('allow-scripts', { 'allow-scripts': '' }, flat) + t.strictSame(flat, { allowScripts: [] }) + t.end() + }) + + t.test('parses comma-separated string into trimmed array', t => { + const flat = {} + mockDefs()['allow-scripts'].flatten( + 'allow-scripts', + { 'allow-scripts': 'canvas, sharp ,sqlite3' }, + flat + ) + t.strictSame(flat, { allowScripts: ['canvas', 'sharp', 'sqlite3'] }) + t.end() + }) + + t.test('drops empty entries', t => { + const flat = {} + mockDefs()['allow-scripts'].flatten( + 'allow-scripts', + { 'allow-scripts': ' canvas , , sharp ' }, + flat + ) + t.strictSame(flat, { allowScripts: ['canvas', 'sharp'] }) + t.end() + }) + + t.test('passes array values through (multiple --allow-scripts flags)', t => { + const flat = {} + mockDefs()['allow-scripts'].flatten( + 'allow-scripts', + { 'allow-scripts': ['canvas', 'sharp'] }, + flat + ) + t.strictSame(flat, { allowScripts: ['canvas', 'sharp'] }) + t.end() + }) + + t.test('ignores non-string entries in array values', t => { + const flat = {} + mockDefs()['allow-scripts'].flatten( + 'allow-scripts', + { 'allow-scripts': ['canvas', 42, null, { name: 'sharp' }, 'sqlite3'] }, + flat + ) + t.strictSame(flat, { allowScripts: ['canvas', 'sqlite3'] }) + t.end() + }) + + t.test('splits commas within each array entry (CLI single value)', t => { + const flat = {} + mockDefs()['allow-scripts'].flatten( + 'allow-scripts', + { 'allow-scripts': ['canvas,sharp', 'sqlite3'] }, + flat + ) + t.strictSame(flat, { allowScripts: ['canvas', 'sharp', 'sqlite3'] }) + t.end() + }) + + t.test('non-string non-array values flatten to empty list', t => { + const flat = {} + mockDefs()['allow-scripts'].flatten( + 'allow-scripts', + { 'allow-scripts': null }, + flat + ) + t.strictSame(flat, { allowScripts: [] }) + t.end() + }) + + t.end() +}) + +t.test('strict-allow-scripts', t => { + const defs = mockDefs() + t.equal(defs['strict-allow-scripts'].default, false) + t.equal(defs['strict-allow-scripts'].type, Boolean) + const flat = {} + defs['strict-allow-scripts'].flatten( + 'strict-allow-scripts', + { 'strict-allow-scripts': true }, + flat + ) + t.strictSame(flat, { strictAllowScripts: true }) + t.end() +}) + +t.test('dangerously-allow-all-scripts', t => { + const defs = mockDefs() + t.equal(defs['dangerously-allow-all-scripts'].default, false) + t.equal(defs['dangerously-allow-all-scripts'].type, Boolean) + const flat = {} + defs['dangerously-allow-all-scripts'].flatten( + 'dangerously-allow-all-scripts', + { 'dangerously-allow-all-scripts': true }, + flat + ) + t.strictSame(flat, { dangerouslyAllowAllScripts: true }) + t.end() +}) + +t.test('global-ignore-file', t => { + const defs = mockDefs() + const def = defs['global-ignore-file'] + + t.ok(def, 'global-ignore-file definition is exported') + t.equal(def.type, require('../../lib/type-defs.js').path.type, 'is a path typed config') + t.equal(def.default, '', 'default value is empty (computed at load time)') + t.ok(/ignore/i.test(def.description), 'has a descriptive entry') + + const flat = {} + def.flatten('global-ignore-file', { 'global-ignore-file': '/path/to/npmignore' }, flat) + t.strictSame(flat, { globalIgnoreFile: '/path/to/npmignore' }, 'flattens to camelCase') + + t.end() +}) diff --git a/workspaces/config/test/env-replace.js b/workspaces/config/test/env-replace.js index c2b570364de87..c6b40266d30e5 100644 --- a/workspaces/config/test/env-replace.js +++ b/workspaces/config/test/env-replace.js @@ -6,8 +6,18 @@ const env = { bar: 'baz', } -t.equal(envReplace('\\${foo}', env), '${foo}') -t.equal(envReplace('\\\\${foo}', env), '\\bar') -t.equal(envReplace('${baz}', env), '${baz}') -t.equal(envReplace('\\${baz}', env), '${baz}') -t.equal(envReplace('\\\\${baz}', env), '\\${baz}') +t.equal(envReplace('${foo}', env), 'bar', 'replaces defined variable') +t.equal(envReplace('${foo?}', env), 'bar', 'replaces defined variable with ? modifier') +t.equal(envReplace('${foo}${bar}', env), 'barbaz', 'replaces multiple defined variables') +t.equal(envReplace('${foo?}${baz?}', env), 'bar', 'replaces mixed defined/undefined variables with ? modifier') +t.equal(envReplace('\\${foo}', env), '${foo}', 'escapes normal variable') +t.equal(envReplace('\\\\${foo}', env), '\\bar', 'double escape allows replacement') +t.equal(envReplace('\\\\\\${foo}', env), '\\${foo}', 'triple escape prevents replacement') +t.equal(envReplace('${baz}', env), '${baz}', 'leaves undefined variable unreplaced') +t.equal(envReplace('\\${baz}', env), '${baz}', 'escapes undefined variable') +t.equal(envReplace('\\\\${baz}', env), '\\${baz}', 'double escape with undefined variable') +t.equal(envReplace('\\${foo?}', env), '${foo?}', 'escapes optional variable') +t.equal(envReplace('\\\\${foo?}', env), '\\bar', 'double escape allows optional replacement') +t.equal(envReplace('${baz?}', env), '', 'replaces undefined variable with empty string when using ? modifier') +t.equal(envReplace('\\${baz?}', env), '${baz?}', 'escapes undefined optional variable') +t.equal(envReplace('\\\\${baz?}', env), '\\', 'double escape with undefined optional variable results in empty replacement') diff --git a/workspaces/config/test/extension-file.js b/workspaces/config/test/extension-file.js new file mode 100644 index 0000000000000..d32c7e519b19d --- /dev/null +++ b/workspaces/config/test/extension-file.js @@ -0,0 +1,62 @@ +const t = require('tap') +const { join, resolve } = require('node:path') +const Config = require('../lib/index.js') +const { definitions, shorthands, flatten, nerfDarts } = require('../lib/definitions') + +const npmPath = resolve(__dirname, '..') + +// build a Config whose project (local prefix) is the testdir root, with optional npmrc per source +// --prefix forces the local prefix to the testdir, so the project .npmrc lives there +const loadConfig = async (t, { project, user, argv = [] } = {}) => { + const dir = t.testdir({ + '.npmrc': project ?? '', + 'package.json': '{"name":"proj","version":"1.0.0"}', + home: { '.npmrc': user ?? '' }, + }) + const config = new Config({ + npmPath, + shorthands, + definitions, + flatten, + nerfDarts, + env: { HOME: join(dir, 'home') }, + argv: [process.execPath, __filename, '--prefix', dir, '--userconfig', join(dir, 'home/.npmrc'), ...argv], + cwd: dir, + }) + await config.load() + return config +} + +t.test('extension-file is accepted from project config', async t => { + const config = await loadConfig(t, { project: 'extension-file=tools/ext.mjs' }) + t.equal(config.find('extension-file'), 'project', 'sourced from project') + t.match(config.get('extension-file'), /tools[/\\]ext\.mjs$/, 'value resolved') +}) + +t.test('extension-file is accepted from the command line', async t => { + const config = await loadConfig(t, { argv: ['--extension-file', 'tools/ext.cjs'] }) + t.equal(config.find('extension-file'), 'cli', 'sourced from cli') +}) + +t.test('extension-file from user config exposes its source for the consumer to reject', async t => { + // the config layer loads it and records the source; the npm CLI enforces the source restriction + const config = await loadConfig(t, { user: 'extension-file=tools/ext.mjs' }) + t.equal(config.find('extension-file'), 'user', 'source reported as user') +}) + +t.test('extension-file unset loads cleanly', async t => { + const config = await loadConfig(t, {}) + t.equal(config.get('extension-file'), null, 'default null') +}) + +t.test('ignore-scripts implies ignoreExtension in flatOptions', async t => { + const onlyScripts = await loadConfig(t, { project: 'ignore-scripts=true' }) + t.equal(onlyScripts.flat.ignoreExtension, true, 'ignore-scripts turns on ignoreExtension') + t.equal(onlyScripts.flat.ignoreScripts, true, 'ignore-scripts still flattens itself') + + const neither = await loadConfig(t, {}) + t.equal(neither.flat.ignoreExtension, false, 'off by default') + + const onlyExt = await loadConfig(t, { project: 'ignore-extension=true' }) + t.equal(onlyExt.flat.ignoreExtension, true, 'ignore-extension alone works') +}) diff --git a/workspaces/config/test/index.js b/workspaces/config/test/index.js index 67d49b28751dc..60941c7760985 100644 --- a/workspaces/config/test/index.js +++ b/workspaces/config/test/index.js @@ -45,7 +45,26 @@ const fsMocks = { 'node:fs': mockFs, } -const { definitions, shorthands, flatten } = t.mock('../lib/definitions/index.js', fsMocks) +const { definitions: realDefinitions, shorthands, nerfDarts, flatten } = + t.mock('../lib/definitions/index.js', fsMocks) + +// Extend the real definitions with stub entries for fake config keys used +// in the shared fixture below. Treating them as known lets merge-order, +// env-override, and similar tests exercise Config.load() without tripping +// the npm 12 unknown-config throw. Tests that want to exercise unknown +// behavior use keys NOT in this stub list (e.g. "totally-unknown-key"). +const stubDef = (key) => ({ key, type: [String, Boolean] }) +const definitions = { + ...realDefinitions, + 'builtin-config': stubDef('builtin-config'), + 'global-config': stubDef('global-config'), + 'user-config-from-builtin': stubDef('user-config-from-builtin'), + 'default-user-config-in-home': stubDef('default-user-config-in-home'), + 'project-config': stubDef('project-config'), + 'cli-config': stubDef('cli-config'), + foo: stubDef('foo'), + bAr: stubDef('bAr'), +} const Config = t.mock('../', fsMocks) // because we used t.mock above, the require cache gets blown and we lose our direct equality @@ -138,6 +157,7 @@ prefix = ${path}/global `, '.npmrc-from-builtin': ` user-config-from-builtin = true +default-user-config-in-home = true foo = from-custom-userconfig globalconfig = ${path}/global/etc/npmrc `, @@ -186,6 +206,7 @@ loglevel = yolo cwd: join(`${path}/project`), shorthands, definitions, + nerfDarts, }) await t.rejects(() => config.load(), { message: `double-loading config "${resolve(path, 'npm/npmrc')}" as "user",` + @@ -201,6 +222,7 @@ loglevel = yolo cwd: join(`${path}/project`), shorthands, definitions, + nerfDarts, }) await config.load() @@ -217,6 +239,7 @@ loglevel = yolo cwd: join(`${path}/project`), shorthands, definitions, + nerfDarts, }) await config.load() @@ -238,6 +261,7 @@ loglevel = yolo cwd: path, shorthands, definitions, + nerfDarts, }) logs.length = 0 await config.load() @@ -288,10 +312,10 @@ loglevel = yolo t.equal(config.get('global', 'env'), undefined, 'empty env is missing') t.equal(config.get('global'), false, 'empty env is missing') - config.set('asdf', 'quux', 'global') + config.set('foo', 'quux', 'global') await config.save('global') const gres = readFileSync(`${path}/global/etc/npmrc`, 'utf8') - t.match(gres, 'asdf=quux') + t.match(gres, 'foo=quux') const cliData = config.data.get('cli') t.throws(() => cliData.loadError = true, { @@ -388,7 +412,7 @@ loglevel = yolo ['warn', 'invalid config', 'omit="cucumber"', 'set in command line options'], ['warn', 'invalid config', 'Must be one or more of:', 'dev, optional, peer'], ['warn', 'invalid config', 'access="blueberry"', 'set in command line options'], - ['warn', 'invalid config', 'Must be one of:', 'null, restricted, public'], + ['warn', 'invalid config', 'Must be one of:', 'null, restricted, public, private'], ['warn', 'invalid config', 'multiple-numbers="what kind of fruit is not a number"', 'set in command line options'], ['warn', 'invalid config', 'Must be one or more', 'numeric value'], @@ -413,7 +437,7 @@ loglevel = yolo t.notOk(config.isDefault('cli-config'), 'should return false for a cli-defined value') t.notOk(config.isDefault('foo'), - 'should return false for a env-defined value') + 'should return false for an env-defined value') t.notOk(config.isDefault('project-config'), 'should return false for a project-defined value') t.notOk(config.isDefault('default-user-config-in-home'), @@ -424,7 +448,7 @@ loglevel = yolo 'should return false for a builtin-defined value') // make sure isDefault still works as intended after - // setting and deleting values in differente sources + // setting and deleting values in different sources config.set('methane', 'H2O', 'cli') t.notOk(config.isDefault('methane'), 'should no longer return true now that a cli value was defined') @@ -449,6 +473,7 @@ loglevel = yolo shorthands, definitions, + nerfDarts, }) await config.load() @@ -482,6 +507,7 @@ loglevel = yolo shorthands, definitions, + nerfDarts, }) await config.load() @@ -582,7 +608,7 @@ loglevel = yolo ['warn', 'invalid config', 'omit="cucumber"', 'set in command line options'], ['warn', 'invalid config', 'Must be one or more of:', 'dev, optional, peer'], ['warn', 'invalid config', 'access="blueberry"', 'set in command line options'], - ['warn', 'invalid config', 'Must be one of:', 'null, restricted, public'], + ['warn', 'invalid config', 'Must be one of:', 'null, restricted, public, private'], ['warn', 'invalid config', 'multiple-numbers="what kind of fruit is not a number"', 'set in command line options'], ['warn', 'invalid config', 'Must be one or more', 'numeric value'], @@ -612,6 +638,7 @@ t.test('cafile loads as ca (and some saving tests)', async t => { const config = new Config({ shorthands, definitions, + nerfDarts, npmPath: __dirname, env: { HOME: dir, PREFIX: dir }, flatten, @@ -650,6 +677,7 @@ fakey mc fakerson const config = new Config({ shorthands, definitions, + nerfDarts, npmPath: __dirname, env: { HOME: dir, @@ -671,6 +699,7 @@ t.test('ignore cafile if it does not load', async t => { const config = new Config({ shorthands, definitions, + nerfDarts, npmPath: __dirname, env: { HOME: dir }, }) @@ -689,6 +718,7 @@ t.test('raise error if reading ca file error other than ENOENT', async t => { const config = new Config({ shorthands, definitions, + nerfDarts, npmPath: __dirname, env: { HOME: dir }, flatten, @@ -703,8 +733,7 @@ t.test('credentials management', async t => { nerfed_userpass: { '.npmrc': `//registry.example/:username = hello //registry.example/:_password = ${Buffer.from('world').toString('base64')} -//registry.example/:email = i@izs.me -//registry.example/:always-auth = "false"`, +//registry.example/:email = i@izs.me`, }, nerfed_auth: { // note: does not load, because we don't do _auth per reg '.npmrc': `//registry.example/:_auth = ${Buffer.from('hello:world').toString('base64')}`, @@ -719,7 +748,6 @@ t.test('credentials management', async t => { nerfed_mtlsUserPass: { '.npmrc': `//registry.example/:username = hello //registry.example/:_password = ${Buffer.from('world').toString('base64')} //registry.example/:email = i@izs.me -//registry.example/:always-auth = "false" //registry.example/:certfile = /path/to/cert //registry.example/:keyfile = /path/to/key`, }, @@ -758,17 +786,40 @@ always-auth = true`, const defReg = 'https://registry.example/' const otherReg = 'https://other.registry/' + // Cases whose fixtures include top-level legacy auth keys that are no + // longer tolerated in npm 12 — Config collects them as unknowns; the + // error is raised by base-cmd.validateCli when the command runs. + const mustCollect = new Set([ + 'def_userpass', + 'def_userNoPass', + 'def_passNoUser', + 'def_auth', + 'none_authToken', + 'none_lcAuthToken', + ]) for (const testCase of Object.keys(fixtures)) { t.test(testCase, async t => { const c = new Config({ npmPath: path, shorthands, definitions, + nerfDarts, env: { HOME: resolve(path, testCase) }, argv: ['node', 'file', '--registry', defReg], }) + await c.load() + if (mustCollect.has(testCase)) { + const unknowns = [ + ...c.getUnknownConfigs('user'), + ...c.getUnknownConfigs('project'), + ...c.getUnknownConfigs('global'), + ] + t.ok(unknowns.length > 0, 'unknown top-level legacy auth keys collected') + return + } + // only have to do this the first time, it's redundant otherwise if (testCase === 'none_noConfig') { t.throws(() => c.setCredentialsByURI('http://x.com', { @@ -786,25 +837,20 @@ always-auth = true`, }) } - // the def_ and none_ prefixed cases have unscoped auth values and should throw - if (testCase.startsWith('def_') || - testCase === 'none_authToken' || - testCase === 'none_lcAuthToken') { + // def_authEnv still needs validate+repair (uses defined `_auth` at top + // level, which loads fine but validate flags as incomplete auth). + if (testCase === 'def_authEnv') { try { c.validate() - // validate should throw, fail the test here if it doesn't t.fail('validate should have thrown') } catch (err) { if (err.code !== 'ERR_INVALID_AUTH') { throw err } - - // we got our expected invalid auth error, so now repair it c.repair(err.problems) t.ok(c.valid, 'config is valid') } } else { - // validate won't throw for these ones, so let's prove it and repair are no-ops c.validate() c.repair() } @@ -863,6 +909,7 @@ t.test('finding the global prefix', t => { }, shorthands, definitions, + nerfDarts, npmPath, }) c.loadGlobalPrefix() @@ -878,6 +925,7 @@ t.test('finding the global prefix', t => { execPath: '/path/to/nodejs/node.exe', shorthands, definitions, + nerfDarts, npmPath, }) c.loadGlobalPrefix() @@ -890,6 +938,7 @@ t.test('finding the global prefix', t => { execPath: '/path/to/nodejs/bin/node', shorthands, definitions, + nerfDarts, npmPath, }) c.loadGlobalPrefix() @@ -903,6 +952,7 @@ t.test('finding the global prefix', t => { env: { DESTDIR: '/some/dest/dir' }, shorthands, definitions, + nerfDarts, npmPath, }) c.loadGlobalPrefix() @@ -928,6 +978,7 @@ t.test('finding the local prefix', t => { argv: [process.execPath, __filename, '-C', path], shorthands, definitions, + nerfDarts, npmPath: path, }) await c.load() @@ -938,6 +989,7 @@ t.test('finding the local prefix', t => { cwd: join(`${path}/hasNM/x/y/z`), shorthands, definitions, + nerfDarts, npmPath: path, }) await c.load() @@ -948,6 +1000,7 @@ t.test('finding the local prefix', t => { cwd: join(`${path}/hasPJ/x/y/z`), shorthands, definitions, + nerfDarts, npmPath: path, }) await c.load() @@ -958,6 +1011,7 @@ t.test('finding the local prefix', t => { cwd: join('/this/path/does/not/exist/x/y/z'), shorthands, definitions, + nerfDarts, npmPath: path, }) await c.load() @@ -973,29 +1027,33 @@ t.test('setting basic auth creds and email', async t => { const opts = { shorthands: {}, argv: ['node', __filename, `--userconfig=${path}/.npmrc`], + env: {}, definitions: { registry: { default: registry }, }, - npmPath: process.cwd(), + nerfDarts, + cwd: path, + excludeNpmCwd: true, + npmPath: path, } const c = new Config(opts) await c.load() - c.set('email', 'name@example.com', 'user') - t.equal(c.get('email', 'user'), 'name@example.com', 'email was set') + c.setCredentialsByURI(registry, { + username: 'admin', + password: 'admin', + }) + c.set('//registry.npmjs.org/:email', 'name@example.com', 'user') await c.save('user') - t.equal(c.get('email', 'user'), 'name@example.com', 'email still top level') - t.strictSame(c.getCredentialsByURI(registry), { email: 'name@example.com' }) + t.strictSame(c.getCredentialsByURI(registry), { + email: 'name@example.com', + username: 'admin', + password: 'admin', + auth: _auth, + }) const d = new Config(opts) await d.load() - t.strictSame(d.getCredentialsByURI(registry), { email: 'name@example.com' }) - d.set('_auth', _auth, 'user') - t.equal(d.get('_auth', 'user'), _auth, '_auth was set') - d.repair() - await d.save('user') - const e = new Config(opts) - await e.load() - t.equal(e.get('_auth', 'user'), undefined, 'un-nerfed _auth deleted') - t.strictSame(e.getCredentialsByURI(registry), { + t.equal(d.get('_auth', 'user'), undefined, 'un-nerfed _auth not present') + t.strictSame(d.getCredentialsByURI(registry), { email: 'name@example.com', username: 'admin', password: 'admin', @@ -1009,29 +1067,29 @@ t.test('setting username/password/email individually', async t => { const opts = { shorthands: {}, argv: ['node', __filename, `--userconfig=${path}/.npmrc`], + env: {}, definitions: { registry: { default: registry }, }, - npmPath: process.cwd(), + nerfDarts, + cwd: path, + excludeNpmCwd: true, + npmPath: path, } const c = new Config(opts) await c.load() - c.set('email', 'name@example.com', 'user') - t.equal(c.get('email'), 'name@example.com') - c.set('username', 'admin', 'user') - t.equal(c.get('username'), 'admin') - c.set('_password', Buffer.from('admin').toString('base64'), 'user') - t.equal(c.get('_password'), Buffer.from('admin').toString('base64')) + c.setCredentialsByURI(registry, { + username: 'admin', + password: 'admin', + }) + c.set('//registry.npmjs.org/:email', 'name@example.com', 'user') + t.equal(c.get('//registry.npmjs.org/:email'), 'name@example.com') + t.equal(c.get('//registry.npmjs.org/:username'), 'admin') t.equal(c.get('_auth'), undefined) - c.repair() await c.save('user') const d = new Config(opts) await d.load() - t.equal(d.get('email'), 'name@example.com') - t.equal(d.get('username'), undefined) - t.equal(d.get('_password'), undefined) - t.equal(d.get('_auth'), undefined) t.strictSame(d.getCredentialsByURI(registry), { email: 'name@example.com', username: 'admin', @@ -1040,7 +1098,7 @@ t.test('setting username/password/email individually', async t => { }) }) -t.test('nerfdart auths set at the top level into the registry', async t => { +t.test('nerfdart auths set at the top level now throw in npm 12', async t => { const registry = 'https://registry.npmjs.org/' const _auth = Buffer.from('admin:admin').toString('base64') const username = 'admin' @@ -1048,90 +1106,301 @@ t.test('nerfdart auths set at the top level into the registry', async t => { const email = 'i@izs.me' const _authToken = 'deadbeefblahblah' - // name: [ini, expect, wontThrow] - const cases = { - '_auth only, no email': [`_auth=${_auth}`, { - '//registry.npmjs.org/:_auth': _auth, - }], - '_auth with email': [`_auth=${_auth}\nemail=${email}`, { - '//registry.npmjs.org/:_auth': _auth, - email, - }], - '_authToken alone': [`_authToken=${_authToken}`, { - '//registry.npmjs.org/:_authToken': _authToken, - }], - '_authToken and email': [`_authToken=${_authToken}\nemail=${email}`, { - '//registry.npmjs.org/:_authToken': _authToken, - email, - }], - 'username and _password': [`username=${username}\n_password=${_password}`, { - '//registry.npmjs.org/:username': username, - '//registry.npmjs.org/:_password': _password, - }], - 'username, password, email': [`username=${username}\n_password=${_password}\nemail=${email}`, { - '//registry.npmjs.org/:username': username, - '//registry.npmjs.org/:_password': _password, - email, - }], - // handled invalid/legacy cases - 'username, no _password': [`username=${username}`, {}], - '_password, no username': [`_password=${_password}`, {}], - '_authtoken instead of _authToken': [`_authtoken=${_authToken}`, {}], - '-authtoken instead of _authToken': [`-authtoken=${_authToken}`, {}], - // de-nerfdart the email, if present in that way - 'nerf-darted email': [`//registry.npmjs.org/:email=${email}`, { - email, - }, true], + // All these legacy fixtures place auth-like keys at the top level of an + // .npmrc. In npm 11 these produced warnings and `repair()` migrated them + // into a nerfdart section. In npm 12 they are collected as unknown + // configs; base-cmd.validateCli throws on them when the command runs. + const throwingCases = { + '_auth only, no email': `_auth=${_auth}`, + '_auth with email': `_auth=${_auth}\nemail=${email}`, + '_authToken alone': `_authToken=${_authToken}`, + '_authToken and email': `_authToken=${_authToken}\nemail=${email}`, + 'username and _password': `username=${username}\n_password=${_password}`, + 'username, password, email': + `username=${username}\n_password=${_password}\nemail=${email}`, + 'username, no _password': `username=${username}`, + '_password, no username': `_password=${_password}`, + '_authtoken instead of _authToken': `_authtoken=${_authToken}`, + '-authtoken instead of _authToken': `-authtoken=${_authToken}`, } - const logs = [] - const logHandler = (...args) => logs.push(args) - process.on('log', logHandler) - t.teardown(() => { - process.removeListener('log', logHandler) - }) - const cwd = process.cwd() - for (const [name, [ini, expect, wontThrow]] of Object.entries(cases)) { + for (const [name, ini] of Object.entries(throwingCases)) { t.test(name, async t => { - t.teardown(() => { - process.chdir(cwd) - logs.length = 0 - }) const path = t.testdir({ '.npmrc': ini, 'package.json': JSON.stringify({}), }) - process.chdir(path) - const argv = [ - 'node', - __filename, - `--prefix=${path}`, - `--userconfig=${path}/.npmrc`, - `--globalconfig=${path}/etc/npmrc`, - ] const opts = { shorthands: {}, - argv, + argv: [ + 'node', + __filename, + `--prefix=${path}`, + `--userconfig=${path}/.npmrc`, + `--globalconfig=${path}/etc/npmrc`, + ], env: {}, definitions: { registry: { default: registry }, }, - npmPath: process.cwd(), + cwd: path, + excludeNpmCwd: true, + npmPath: path, } - const c = new Config(opts) await c.load() + const unknowns = [ + ...c.getUnknownConfigs('user'), + ...c.getUnknownConfigs('project'), + ...c.getUnknownConfigs('global'), + ...c.getUnknownConfigs('builtin'), + ] + t.ok(unknowns.length > 0, 'legacy top-level auth keys collected as unknown') + t.throws( + () => c.validate(), + { code: 'ERR_INVALID_AUTH' }, + 'validate() throws ErrInvalidAuth with a message describing each problem' + ) + }) + } - if (!wontThrow) { - t.throws(() => c.validate(), { code: 'ERR_INVALID_AUTH' }) - } + t.test('nerf-darted email still loads', async t => { + const path = t.testdir({ + '.npmrc': `//registry.npmjs.org/:email=${email}`, + 'package.json': JSON.stringify({}), + }) + const opts = { + shorthands: {}, + argv: [ + 'node', + __filename, + `--prefix=${path}`, + `--userconfig=${path}/.npmrc`, + `--globalconfig=${path}/etc/npmrc`, + ], + env: {}, + definitions: { + registry: { default: registry }, + }, + nerfDarts, + cwd: path, + excludeNpmCwd: true, + npmPath: path, + } + const c = new Config(opts) + await c.load() + c.repair() + await c.save('user') + t.same(c.data.get('user').data, { '//registry.npmjs.org/:email': email }) + }) +}) + +t.test('checkUnknown and repair carve-outs', async t => { + const registry = 'https://registry.npmjs.org/' + const _authToken = 'deadbeef' - // now we go ahead and do the repair, and save - c.repair() - await c.save('user') - t.same(c.list[3], expect) + t.test('repair() with no args validates and fixes auth problems', async t => { + const path = t.testdir({ + '.npmrc': `_authtoken=${_authToken}`, + 'package.json': JSON.stringify({}), }) - } + const c = new Config({ + shorthands: {}, + argv: [ + 'node', + __filename, + `--prefix=${path}`, + `--userconfig=${path}/.npmrc`, + `--globalconfig=${path}/etc/npmrc`, + ], + env: {}, + definitions: { registry: { default: registry } }, + cwd: path, + excludeNpmCwd: true, + npmPath: path, + }) + await c.load() + t.throws(() => c.validate(), { code: 'ERR_INVALID_AUTH' }, 'pre-repair validate throws') + c.repair() + t.equal(c.get('_authtoken', 'user'), undefined, 'deleted from user config') + t.doesNotThrow(() => c.validate(), 'post-repair validate passes') + }) + + t.test('repair() migrates top-level email to nerfdart form', async t => { + const email = 'me@example.com' + const path = t.testdir({ + '.npmrc': `email=${email}`, + 'package.json': JSON.stringify({}), + }) + const c = new Config({ + shorthands: {}, + argv: [ + 'node', + __filename, + `--prefix=${path}`, + `--userconfig=${path}/.npmrc`, + `--globalconfig=${path}/etc/npmrc`, + ], + env: {}, + definitions: { registry: { default: registry } }, + cwd: path, + excludeNpmCwd: true, + npmPath: path, + }) + await c.load() + t.throws(() => c.validate(), { code: 'ERR_INVALID_AUTH' }, + 'pre-repair validate flags top-level email') + c.repair() + t.equal(c.get('email', 'user'), undefined, 'top-level email deleted') + t.equal(c.get('//registry.npmjs.org/:email', 'user'), email, + 'email moved to nerfdart form') + t.doesNotThrow(() => c.validate(), 'post-repair validate passes') + }) + + t.test('repair() migrates certfile+keyfile pair to nerfdart form', async t => { + const path = t.testdir({ + '.npmrc': 'certfile=/path/to/cert\nkeyfile=/path/to/key', + 'package.json': JSON.stringify({}), + }) + const c = new Config({ + shorthands: {}, + argv: [ + 'node', + __filename, + `--prefix=${path}`, + `--userconfig=${path}/.npmrc`, + `--globalconfig=${path}/etc/npmrc`, + ], + env: {}, + definitions: { registry: { default: registry } }, + cwd: path, + excludeNpmCwd: true, + npmPath: path, + }) + await c.load() + t.throws(() => c.validate(), { code: 'ERR_INVALID_AUTH' }, + 'pre-repair validate flags top-level certfile/keyfile') + c.repair() + t.equal(c.get('certfile', 'user'), undefined, 'top-level certfile deleted') + t.equal(c.get('keyfile', 'user'), undefined, 'top-level keyfile deleted') + t.equal(c.get('//registry.npmjs.org/:certfile', 'user'), '/path/to/cert', + 'certfile moved to nerfdart form') + t.equal(c.get('//registry.npmjs.org/:keyfile', 'user'), '/path/to/key', + 'keyfile moved to nerfdart form') + t.doesNotThrow(() => c.validate(), 'post-repair validate passes') + }) + + t.test('repair() drops orphan certfile (no matching keyfile)', async t => { + const path = t.testdir({ + '.npmrc': 'certfile=/path/to/cert', + 'package.json': JSON.stringify({}), + }) + const c = new Config({ + shorthands: {}, + argv: [ + 'node', + __filename, + `--prefix=${path}`, + `--userconfig=${path}/.npmrc`, + `--globalconfig=${path}/etc/npmrc`, + ], + env: {}, + definitions: { registry: { default: registry } }, + cwd: path, + excludeNpmCwd: true, + npmPath: path, + }) + await c.load() + c.repair() + t.equal(c.get('certfile', 'user'), undefined, 'orphan certfile deleted') + t.equal(c.get('//registry.npmjs.org/:certfile', 'user'), undefined, + 'orphan certfile NOT moved (useless without keyfile)') + }) + + t.test('repair() preserves existing scoped destination on collision', async t => { + // Stale top-level + current scoped should keep the scoped value. + const stale = 'old@example.com' + const current = 'new@example.com' + const path = t.testdir({ + '.npmrc': `email=${stale}\n//registry.npmjs.org/:email=${current}`, + 'package.json': JSON.stringify({}), + }) + const c = new Config({ + shorthands: {}, + argv: [ + 'node', + __filename, + `--prefix=${path}`, + `--userconfig=${path}/.npmrc`, + `--globalconfig=${path}/etc/npmrc`, + ], + env: {}, + definitions: { registry: { default: registry } }, + cwd: path, + excludeNpmCwd: true, + npmPath: path, + }) + await c.load() + c.repair() + t.equal(c.get('email', 'user'), undefined, 'stale top-level email deleted') + t.equal(c.get('//registry.npmjs.org/:email', 'user'), current, + 'existing scoped email preserved (not clobbered)') + }) + + t.test('publishConfig unknown warns but does not error', async t => { + const path = t.testdir({ 'package.json': JSON.stringify({}) }) + const c = new Config({ + shorthands: {}, + argv: ['node', __filename, `--prefix=${path}`], + env: {}, + definitions: { registry: { default: registry } }, + cwd: path, + excludeNpmCwd: true, + npmPath: path, + warn: false, + }) + await c.load() + c.checkUnknown('publishConfig', 'bogus-pub-key') + c.checkUnknown('publishConfig', '@scope:bogus-scoped-pub') + const pubUnknowns = c.getUnknownConfigs('publishConfig') + t.equal(pubUnknowns.length, 2, 'publishConfig unknowns collected') + t.notOk( + c.getUnknownConfigs().some(u => u.where === 'publishConfig'), + 'publishConfig unknowns excluded from default getUnknownConfigs()' + ) + }) + + t.test('getUnknownConfigs() returns all file + cli entries', async t => { + const path = t.testdir({ + '.npmrc': 'bogus-user-key=yes', + 'package.json': JSON.stringify({}), + }) + const c = new Config({ + shorthands: {}, + argv: [ + 'node', + __filename, + `--prefix=${path}`, + `--userconfig=${path}/.npmrc`, + `--globalconfig=${path}/etc/npmrc`, + ], + env: { + npm_config_bogus_env_key: 'x', + 'npm_config_@scope:bogus-scoped-env': 'y', + }, + definitions: { registry: { default: registry } }, + cwd: path, + excludeNpmCwd: true, + npmPath: path, + }) + await c.load() + const all = c.getUnknownConfigs() + t.ok(all.some(u => u.key === 'bogus-user-key' && u.where === 'user'), 'includes user file key') + t.notOk(all.some(u => u.where === 'env'), 'excludes env entries') + const envUnknowns = c.getUnknownConfigs('env') + t.ok(envUnknowns.some(u => !u.baseKey), 'plain env unknown collected') + t.ok(envUnknowns.some(u => u.baseKey), 'scoped env unknown collected') + }) }) t.test('workspaces', async (t) => { @@ -1182,6 +1451,7 @@ t.test('workspaces', async (t) => { cwd: join(`${path}/workspaces/one`), shorthands, definitions, + nerfDarts, }) await config.load() @@ -1205,6 +1475,7 @@ t.test('workspaces', async (t) => { cwd: join(`${path}/workspaces/one`), shorthands, definitions, + nerfDarts, }) await config.load() @@ -1228,6 +1499,7 @@ t.test('workspaces', async (t) => { cwd: join(`${path}/workspaces/three`), shorthands, definitions, + nerfDarts, }) await config.load() @@ -1253,6 +1525,7 @@ t.test('workspaces', async (t) => { cwd: join(`${path}/workspaces/one`), shorthands, definitions, + nerfDarts, }) await config.load() @@ -1274,6 +1547,7 @@ t.test('workspaces', async (t) => { cwd: join(`${path}/workspaces/one`), shorthands, definitions, + nerfDarts, }) await config.load() @@ -1295,6 +1569,7 @@ t.test('workspaces', async (t) => { cwd: join(`${path}/workspaces/one`), shorthands, definitions, + nerfDarts, }) await config.load() @@ -1316,6 +1591,7 @@ t.test('workspaces', async (t) => { cwd: join(`${path}/workspaces/one`), shorthands, definitions, + nerfDarts, }) await config.load() @@ -1337,6 +1613,7 @@ t.test('workspaces', async (t) => { cwd: join(`${path}/workspaces/one`), shorthands, definitions, + nerfDarts, excludeNpmCwd: true, }) @@ -1365,6 +1642,7 @@ t.test('workspaces', async (t) => { cwd: join(`${path}/workspaces/one`), shorthands, definitions, + nerfDarts, }) await config.load() @@ -1409,8 +1687,85 @@ t.test('exclusive options conflict', async t => { }) await t.rejects(config.load(), { name: 'TypeError', - message: '--lie can not be provided when using --truth', + message: '--lie cannot be provided when using --truth', + }) +}) + +t.test('exclusive options both from env still conflict', async t => { + const path = t.testdir() + const config = new Config({ + env: { + npm_config_aaa: 'true', + npm_config_zzz: 'true', + }, + npmPath: __dirname, + argv: [ + process.execPath, + __filename, + ], + cwd: join(`${path}/project`), + shorthands, + definitions: { + ...definitions, + ...createDef('aaa', { + default: false, + type: Boolean, + description: 'aaa', + exclusive: ['zzz'], + }), + ...createDef('zzz', { + default: false, + type: Boolean, + description: 'zzz', + exclusive: ['aaa'], + }), + }, + flatten, + }) + await t.rejects(config.load(), { + name: 'TypeError', + message: '--zzz cannot be provided when using --aaa', + }) +}) + +t.test('exclusive env option is skipped when sibling is set via CLI', async t => { + const path = t.testdir() + const config = new Config({ + env: { + HOME: path, + npm_config_truth: 'true', + }, + npmPath: __dirname, + argv: [ + process.execPath, + __filename, + '--lie=true', + ], + cwd: join(`${path}/project`), + excludeNpmCwd: true, + shorthands, + definitions: { + ...definitions, + ...createDef('truth', { + default: false, + type: Boolean, + description: 'The Truth', + exclusive: ['lie'], + }), + ...createDef('lie', { + default: false, + type: Boolean, + description: 'A Lie', + exclusive: ['truth'], + }), + }, + nerfDarts, + flatten, }) + // should not throw — env `truth` is skipped because `lie` was set via CLI + await t.resolves(config.load()) + t.equal(config.get('lie'), true, 'CLI lie is set') + t.equal(config.get('truth'), false, 'env truth is skipped, remains default') }) t.test('env-replaced config from files is not clobbered when saving', async (t) => { @@ -1421,8 +1776,12 @@ t.test('env-replaced config from files is not clobbered when saving', async (t) env: { TEST: 'test value' }, definitions: { registry: { default: 'https://registry.npmjs.org/' }, + test: { default: '' }, + other: { default: '' }, }, - npmPath: process.cwd(), + cwd: path, + excludeNpmCwd: true, + npmPath: path, } const c = new Config(opts) await c.load() @@ -1450,6 +1809,7 @@ t.test('umask', async t => { cwd: join(`${path}/project`), shorthands, definitions, + nerfDarts, flatten, }) await config.load() @@ -1480,10 +1840,11 @@ t.test('catch project config prefix error', async t => { }) const config = new Config({ npmPath: `${path}/npm`, - argv: [process.execPath, __filename, '--projectconfig', `${path}/project/.npmrc`], + argv: [process.execPath, __filename], cwd: join(`${path}/project`), shorthands, definitions, + nerfDarts, }) const logs = [] const logHandler = (...args) => logs.push(args) @@ -1492,8 +1853,577 @@ t.test('catch project config prefix error', async t => { logs.length = 0 // config.load() triggers the error to be logged await config.load() - const filtered = logs.filter(l => l[0] !== 'silly') + const filtered = logs.filter(l => l[0] === 'error') t.match(filtered, [[ 'error', 'config', `prefix cannot be changed from project config: ${path}`, ]], 'Expected error logged') }) + +t.test('invalid single hyphen errors', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [process.execPath, __filename, '-ws', '-iwr'], + cwd: path, + shorthands, + definitions, + nerfDarts, + }) + await t.rejects(config.load(), { + code: 'EUNKNOWNCONFIG', + message: /single-hyphen/, + }, 'Throws on invalid single-hyphen flag') +}) + +t.test('positional arg is collected as unknown cli config', async t => { + const path = t.testdir() + const logs = [] + const logHandler = (...args) => logs.push(args) + process.on('log', logHandler) + t.teardown(() => process.off('log', logHandler)) + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [process.execPath, __filename, '--something', 'extra'], + cwd: path, + shorthands, + definitions, + nerfDarts, + }) + // Unknown CLI flags are collected silently during load(); base-cmd throws + // later once command-scoped definitions are known. + await config.load() + const filtered = logs.filter(l => l[0] === 'warn') + t.match(filtered, [ + ['warn', '"extra" is being parsed as a normal command line argument.'], + ], 'Still warns about positional cli arg being parsed as positional') + const unknowns = config.getUnknownConfigs('cli') + t.ok(unknowns.some(u => u.key === 'something'), + 'unknown cli flag collected for later validation') +}) + +t.test('abbreviation expansion errors', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [process.execPath, __filename, '--bef', '2020-01-01'], + cwd: path, + shorthands, + definitions, + nerfDarts, + }) + await t.rejects(config.load(), { + code: 'EUNKNOWNCONFIG', + message: /--bef.*--before/, + }, 'Throws on abbreviation expansion') +}) + +t.test('warning suppression and logging', async t => { + const path = t.testdir() + const logs = [] + const logHandler = (...args) => logs.push(args) + process.on('log', logHandler) + t.teardown(() => process.off('log', logHandler)) + + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [process.execPath, __filename, '--unknown-key', 'value'], + cwd: path, + shorthands, + definitions, + nerfDarts, + }) + + // Load first to collect warnings + await config.load() + + // Now disable warnings and trigger more + config.warn = false + config.queueWarning('test-type', 'test warning 1') + config.queueWarning('test-type2', 'test warning 2') + + // Should have warnings collected but not logged + const initialWarnings = logs.filter(l => l[0] === 'warn') + const beforeCount = initialWarnings.length + + // Now log the warnings + config.warn = true + config.logWarnings() + const afterLogging = logs.filter(l => l[0] === 'warn') + t.ok(afterLogging.length > beforeCount, 'warnings logged after logWarnings()') + + // Calling logWarnings again should not add more warnings + const warningCount = afterLogging.length + config.logWarnings() + const finalWarnings = logs.filter(l => l[0] === 'warn') + t.equal(finalWarnings.length, warningCount, 'no duplicate warnings after second logWarnings()') +}) + +t.test('warn false with unknown env flag and warning removal', async t => { + const path = t.testdir() + const logs = [] + const logHandler = (...args) => logs.push(args) + process.on('log', logHandler) + t.teardown(() => process.off('log', logHandler)) + + const config = new Config({ + npmPath: `${path}/npm`, + env: { npm_config_invalid_flag: 'value' }, + argv: [process.execPath, __filename], + cwd: path, + shorthands, + definitions, + nerfDarts, + }) + + config.warn = false + await config.load() + + // First logWarnings call - should log the queued env-unknown warning + const logsBeforeFirst = logs.filter(l => l[0] === 'warn').length + config.logWarnings() + const logsAfterFirst = logs.filter(l => l[0] === 'warn') + + t.ok(logsAfterFirst.length > logsBeforeFirst, 'warnings were logged') + const invalidFlagWarnings = logsAfterFirst.filter(w => w[1] && w[1].includes('invalid-flag')) + t.ok(invalidFlagWarnings.length > 0, 'invalid-flag warning present') + + // Trigger the same warning again + config.checkUnknown('env', 'invalid-flag') + + // Remove the warning + config.removeWarning('invalid-flag') + + // Call logWarnings again - should not add the invalid-flag warning since we removed it + const beforeSecondLog = logs.filter(l => l[0] === 'warn').length + config.logWarnings() + const afterSecondLog = logs.filter(l => l[0] === 'warn') + t.equal(afterSecondLog.length, beforeSecondLog, 'no new warnings after removal and logWarnings') +}) + +t.test('prefix getter when global is true', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [process.execPath, __filename, '--global'], + cwd: path, + shorthands, + definitions, + nerfDarts, + }) + + await config.load() + t.equal(config.prefix, config.globalPrefix, 'prefix returns globalPrefix when global=true') +}) + +t.test('prefix getter when global is false', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [process.execPath, __filename], + cwd: path, + shorthands, + definitions, + nerfDarts, + }) + + await config.load() + t.equal(config.prefix, config.localPrefix, 'prefix returns localPrefix when global=false') +}) + +t.test('find throws when config not loaded', async t => { + const config = new Config({ + npmPath: t.testdir(), + env: {}, + argv: [process.execPath, __filename], + cwd: process.cwd(), + shorthands, + definitions, + nerfDarts, + }) + + t.throws( + () => config.find('registry'), + /call config\.load\(\) before reading values/, + 'find throws before load' + ) +}) + +t.test('valid getter with invalid config', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [process.execPath, __filename, '--maxsockets', 'not-a-number'], + cwd: path, + shorthands, + definitions, + nerfDarts, + }) + + await config.load() + const isValid = config.valid + t.notOk(isValid, 'config is invalid when it has invalid values') +}) + +t.test('getUnknownPositionals and removeUnknownPositional', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + // Pass unknown flags with values - the values become "unknown positionals" + argv: [process.execPath, __filename, '--unknown-flag1', 'positional1', '--unknown-flag2', 'positional2'], + cwd: path, + shorthands, + definitions, + nerfDarts, + warn: false, // Queue warnings instead of logging them + }) + + await config.load() + + // Get the unknown positionals (values after unknown flags) + const unknownPositionals = config.getUnknownPositionals() + t.ok(unknownPositionals.includes('positional1'), 'positional1 is in unknown positionals') + t.ok(unknownPositionals.includes('positional2'), 'positional2 is in unknown positionals') + + // Remove one positional + config.removeUnknownPositional('positional1') + + // Verify it was removed + const afterRemoval = config.getUnknownPositionals() + t.notOk(afterRemoval.includes('positional1'), 'positional1 was removed') + t.ok(afterRemoval.includes('positional2'), 'positional2 still exists') + + // Remove the second positional + config.removeUnknownPositional('positional2') + + // Verify all are removed + const afterSecondRemoval = config.getUnknownPositionals() + t.equal(afterSecondRemoval.length, 0, 'no unknown positionals remain') +}) + +t.test('before and min-release-age', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [process.execPath, __filename, '--min-release-age', '30'], + cwd: path, + definitions, + nerfDarts, + shorthands, + flatten, + }) + await config.load() + // Simple gut check to make sure we didn't do + instead of - + t.ok(config.flat.before < Date.now(), 'before date is in the past not the future') + t.equal(config.get('min-release-age'), 30, 'min-release-age config remains readable after flattening') +}) + +// Regression test for https://github.com/npm/cli/issues/9291 +// pacote spawns child npm processes with `--before=` whenever it has a +// `before` option (which includes the case where the parent derived `before` +// from `min-release-age`). The child process then loads the user's npmrc, which +// still contains `min-release-age=N`. Previously this combination crashed +// because the two options were declared mutually exclusive. +t.test('min-release-age in npmrc coexists with --before from CLI (pacote spawn)', async t => { + const dir = t.testdir({ + '.npmrc': 'min-release-age=7', + }) + const cliBefore = new Date('2024-01-15T00:00:00.000Z') + const config = new Config({ + npmPath: __dirname, + env: { HOME: dir }, + argv: [process.execPath, __filename, `--before=${cliBefore.toISOString()}`], + cwd: dir, + definitions, + shorthands, + flatten, + }) + await t.resolves(config.load(), 'loads without crashing on previously exclusive options') + // CLI is the highest-priority source, so its `before` overrides whatever + // `min-release-age` in the npmrc would have produced. + t.equal( + config.flat.before.toISOString(), + cliBefore.toISOString(), + 'CLI --before overrides npmrc min-release-age' + ) +}) + +// A higher-priority source must be able to relax (or override) a stricter +// lower-priority `min-release-age`. Previously this would have thrown via +// the `exclusive` check; now it follows normal cli > npmrc precedence. +t.test('CLI --min-release-age=0 relaxes a stricter npmrc min-release-age', async t => { + const dir = t.testdir({ + '.npmrc': 'min-release-age=30', + }) + const config = new Config({ + npmPath: __dirname, + env: { HOME: dir }, + argv: [process.execPath, __filename, '--min-release-age=0'], + cwd: dir, + definitions, + shorthands, + flatten, + }) + await config.load() + // CLI=0 explicitly asserts "no minimum age", clearing the before filter + // derived from the lower-priority npmrc value. (Setting `before = now` + // here would still filter out brand-new versions due to clock skew.) + t.equal(config.flat.before, null, 'CLI 0 clears the npmrc-derived before filter') +}) + +// Within a single source, an explicit `before` wins over a relative +// `min-release-age` so the resolution is deterministic regardless of the +// argv parser's key-iteration order. +t.test('within a single source, before wins over min-release-age', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [ + process.execPath, + __filename, + '--min-release-age=1', + '--before=2020-01-01T00:00:00.000Z', + ], + cwd: path, + definitions, + shorthands, + flatten, + }) + await config.load() + t.equal( + config.flat.before.toISOString(), + '2020-01-01T00:00:00.000Z', + 'explicit --before wins over --min-release-age in the same source' + ) +}) + +t.test('min-release-age=0 does not set a before filter', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [process.execPath, __filename, '--min-release-age', '0'], + cwd: path, + definitions, + shorthands, + flatten, + }) + await config.load() + t.equal(config.flat.before, null, 'flat.before remains null when min-release-age=0') + t.equal(config.get('min-release-age'), 0, 'min-release-age=0 is preserved') +}) + +t.test('higher-priority min-release-age overrides a lower-priority before', async t => { + const dir = t.testdir({ + '.npmrc': 'before=2020-01-01T00:00:00.000Z', + }) + const config = new Config({ + npmPath: __dirname, + env: { HOME: dir }, + argv: [process.execPath, __filename, '--min-release-age=7'], + cwd: dir, + definitions, + shorthands, + flatten, + }) + await config.load() + const expected = Date.now() - (7 * 86400000) + t.ok( + Math.abs(config.flat.before.getTime() - expected) < 60_000, + 'flat.before reflects CLI --min-release-age, not npmrc before' + ) +}) + +t.test('CLI --min-release-age=0 clears a lower-priority npmrc before', async t => { + const dir = t.testdir({ + '.npmrc': 'before=2020-01-01T00:00:00.000Z', + }) + const config = new Config({ + npmPath: __dirname, + env: { HOME: dir }, + argv: [process.execPath, __filename, '--min-release-age=0'], + cwd: dir, + definitions, + shorthands, + flatten, + }) + await config.load() + t.equal(config.flat.before, null, 'CLI 0 clears the npmrc-set before') +}) + +// Env source (`npm_config_*`) routes through the same flatten path as cli and npmrc; lock down its precedence behavior too. +t.test('env npm_config_min_release_age applies as a relative window', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: { npm_config_min_release_age: '7' }, + argv: [process.execPath, __filename], + cwd: path, + definitions, + shorthands, + flatten, + }) + await config.load() + const expected = Date.now() - (7 * 86400000) + t.ok( + Math.abs(config.flat.before.getTime() - expected) < 60_000, + 'flat.before reflects env-source min-release-age' + ) +}) + +t.test('env npm_config_min_release_age=0 clears a lower-priority npmrc before', async t => { + const dir = t.testdir({ + '.npmrc': 'before=2020-01-01T00:00:00.000Z', + }) + const config = new Config({ + npmPath: __dirname, + env: { HOME: dir, npm_config_min_release_age: '0' }, + argv: [process.execPath, __filename], + cwd: dir, + definitions, + shorthands, + flatten, + }) + await config.load() + t.equal(config.flat.before, null, 'env 0 clears the npmrc-set before') +}) + +t.test('CLI --min-release-age beats env npm_config_min_release_age', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: { npm_config_min_release_age: '30' }, + argv: [process.execPath, __filename, '--min-release-age=3'], + cwd: path, + definitions, + shorthands, + flatten, + }) + await config.load() + const expected = Date.now() - (3 * 86400000) + t.ok( + Math.abs(config.flat.before.getTime() - expected) < 60_000, + 'CLI --min-release-age=3 overrides env npm_config_min_release_age=30' + ) +}) + +t.test('min-release-age-exclude', async t => { + t.test('defaults to an empty array', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [process.execPath, __filename], + cwd: path, + definitions, + shorthands, + flatten, + }) + await config.load() + t.same(config.flat.minReleaseAgeExclude, [], 'flattens to []') + }) + + t.test('a single value flattens to a one-element array', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [process.execPath, __filename, '--min-release-age-exclude=@myorg/*'], + cwd: path, + definitions, + shorthands, + flatten, + }) + await config.load() + t.same(config.flat.minReleaseAgeExclude, ['@myorg/*'], 'single pattern') + }) + + t.test('repeated flags accumulate into an array', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [ + process.execPath, + __filename, + '--min-release-age-exclude=@myorg/*', + '--min-release-age-exclude=lodash', + ], + cwd: path, + definitions, + shorthands, + flatten, + }) + await config.load() + t.same(config.flat.minReleaseAgeExclude, ['@myorg/*', 'lodash'], 'two patterns') + }) + + t.test('a comma-delimited string is split, trimmed, and deduped', async t => { + const dir = t.testdir({ + '.npmrc': 'min-release-age-exclude = @myorg/* , lodash ,@myorg/*', + }) + const config = new Config({ + npmPath: __dirname, + env: { HOME: dir }, + argv: [process.execPath, __filename], + cwd: dir, + definitions, + shorthands, + flatten, + }) + await config.load() + t.same(config.flat.minReleaseAgeExclude, ['@myorg/*', 'lodash'], 'normalized list') + }) +}) + +t.test('global-ignore-file defaults to ${prefix}/etc/npmignore', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [process.execPath, __filename, '--prefix', `${path}/global`], + cwd: path, + definitions, + shorthands, + flatten, + }) + await config.load() + t.equal( + config.get('global-ignore-file'), + resolve(`${path}/global/etc/npmignore`), + 'computed from --prefix, mirrors globalconfig' + ) + t.equal(config.flat.globalIgnoreFile, resolve(`${path}/global/etc/npmignore`), 'flattens to camelCase') +}) + +t.test('global-ignore-file follows an explicit override', async t => { + const path = t.testdir() + const config = new Config({ + npmPath: `${path}/npm`, + env: {}, + argv: [ + process.execPath, __filename, + '--prefix', `${path}/global`, + '--global-ignore-file', `${path}/custom/.npmignore`, + ], + cwd: path, + definitions, + shorthands, + flatten, + }) + await config.load() + t.equal( + config.get('global-ignore-file'), + resolve(`${path}/custom/.npmignore`), + 'cli override wins over computed default' + ) +}) diff --git a/workspaces/config/test/set-envs.js b/workspaces/config/test/set-envs.js index b62ab60955521..c7af0faca33c0 100644 --- a/workspaces/config/test/set-envs.js +++ b/workspaces/config/test/set-envs.js @@ -11,6 +11,7 @@ const NODE = execPath const npmPath = '{path}' const npmBin = join(npmPath, 'bin/npm-cli.js') +const nodeGypPath = require.resolve('node-gyp/bin/node-gyp.js') const mockDefinitions = (t) => { mockGlobals(t, { 'process.env': { EDITOR: 'vim' } }) @@ -27,6 +28,8 @@ t.test('set envs that are not defaults and not already in env', t => { INIT_CWD: cwd, EDITOR: 'vim', HOME: undefined, + npm_config_node_gyp: nodeGypPath, + npm_config_npm_version: 'unknown', npm_execpath: npmBin, npm_node_execpath: execPath, npm_config_global_prefix: globalPrefix, @@ -80,6 +83,8 @@ t.test('set envs that are not defaults and not already in env, array style', t = INIT_CWD: cwd, EDITOR: 'vim', HOME: undefined, + npm_config_node_gyp: nodeGypPath, + npm_config_npm_version: 'unknown', npm_execpath: npmBin, npm_node_execpath: execPath, npm_config_global_prefix: globalPrefix, @@ -130,6 +135,8 @@ t.test('set envs that are not defaults and not already in env, boolean edition', INIT_CWD: cwd, EDITOR: 'vim', HOME: undefined, + npm_config_node_gyp: nodeGypPath, + npm_config_npm_version: 'unknown', npm_execpath: npmBin, npm_node_execpath: execPath, npm_config_global_prefix: globalPrefix, @@ -207,6 +214,8 @@ t.test('dont set configs marked as envExport:false', t => { INIT_CWD: cwd, EDITOR: 'vim', HOME: undefined, + npm_config_node_gyp: nodeGypPath, + npm_config_npm_version: 'unknown', npm_execpath: npmBin, npm_node_execpath: execPath, npm_config_global_prefix: globalPrefix, diff --git a/workspaces/libnpmaccess/.gitignore b/workspaces/libnpmaccess/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/workspaces/libnpmaccess/.gitignore +++ b/workspaces/libnpmaccess/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/workspaces/libnpmaccess/CHANGELOG.md b/workspaces/libnpmaccess/CHANGELOG.md index 6be8f008db45c..45e19e9d8cf0d 100644 --- a/workspaces/libnpmaccess/CHANGELOG.md +++ b/workspaces/libnpmaccess/CHANGELOG.md @@ -1,5 +1,67 @@ # Changelog +## [11.0.0-pre.0](https://github.com/npm/cli/compare/libnpmaccess-v10.0.3...libnpmaccess-v11.0.0-pre.0) (2026-06-19) +### ⚠️ BREAKING CHANGES +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +### Features +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +### Dependencies +* [`1f9c567`](https://github.com/npm/cli/commit/1f9c56792493f80fb3b3d61710086ed748312f2a) [#9559](https://github.com/npm/cli/pull/9559) `npm-registry-fetch@20.0.1` +* [`d80859a`](https://github.com/npm/cli/commit/d80859a2dd97376e4ea621812b3bc7de6a218d21) [#9559](https://github.com/npm/cli/pull/9559) `npm-package-arg@14.0.0` +### Chores +* [`1453954`](https://github.com/npm/cli/commit/1453954f9328a6b2480c183f9d1903ac93764915) [#9559](https://github.com/npm/cli/pull/9559) `nock@14.0.0` (@owlstronaut) +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`40fcab4`](https://github.com/npm/cli/commit/40fcab45d356545f8db7f34df3e5630116d0dd40) [#8991](https://github.com/npm/cli/pull/8991) `@npmcli/template-oss@4.29.0` (@wraithgar) + +## [10.0.3](https://github.com/npm/cli/compare/libnpmaccess-v10.0.2...libnpmaccess-v10.0.3) (2025-10-08) +### Bug Fixes +* [`f367507`](https://github.com/npm/cli/commit/f367507b2a8156c00687426034d0a76188e90b4c) [#8624](https://github.com/npm/cli/pull/8624) spelling (#8624) (@jsoref) +### Chores +* [`7f1c3a3`](https://github.com/npm/cli/commit/7f1c3a37316b42e652b61ea4919e40305c8de06f) [#8606](https://github.com/npm/cli/pull/8606) fix spelling - permissions (#8606) (@jsoref) + +## [10.0.2](https://github.com/npm/cli/compare/libnpmaccess-v10.0.1...libnpmaccess-v10.0.2) (2025-09-23) +### Dependencies +* [`bf6b686`](https://github.com/npm/cli/commit/bf6b6862731e03002cc6fa3b86b6f090df46b009) [#8576](https://github.com/npm/cli/pull/8576) `npm-package-arg@13.0.0` +* [`1149971`](https://github.com/npm/cli/commit/11499711e4c10e4ddb97bf3e1ef1652d151894fb) [#8576](https://github.com/npm/cli/pull/8576) `npm-registry-fetch@19.0.0` +### Chores +* [`402a0ab`](https://github.com/npm/cli/commit/402a0ab1b4e5d1a8414dd063d0cbde0c0bc5a192) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/template-oss@4.25.1` (@wraithgar) +* [`3f60b5f`](https://github.com/npm/cli/commit/3f60b5f9621b43ae0b8796d3a7160a603748f756) [#8383](https://github.com/npm/cli/pull/8383) `@npmcli/template-oss@4.24.4` (#8383) (@wraithgar) +* [`01f8cc6`](https://github.com/npm/cli/commit/01f8cc6f001e3211135fa0563f7129aed09dc46c) [#8381](https://github.com/npm/cli/pull/8381) `@npmcli/template-oss@4.24.3` (#8381) (@wraithgar) + +## [10.0.1](https://github.com/npm/cli/compare/libnpmaccess-v10.0.0...libnpmaccess-v10.0.1) (2025-05-15) +### Bug Fixes +* [`5b5e886`](https://github.com/npm/cli/commit/5b5e886edadf77ee48368695e6bc52ad6c4f06c3) [#8289](https://github.com/npm/cli/pull/8289) libnpmaccess: formatting of options in README (#8289) (@mbtools) + +## [10.0.0](https://github.com/npm/cli/compare/libnpmaccess-v10.0.0-pre.0...libnpmaccess-v10.0.0) (2024-12-16) +### Features +* [`a7bfc6d`](https://github.com/npm/cli/commit/a7bfc6df76882996ebb834dbca785fdf33b8c50d) [#7972](https://github.com/npm/cli/pull/7972) trigger release process (#7972) (@wraithgar) +### Chores +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) + +## [10.0.0-pre.0](https://github.com/npm/cli/compare/libnpmaccess-v9.0.0...libnpmaccess-v10.0.0-pre.0) (2024-11-26) +### ⚠️ BREAKING CHANGES +* libnpmaccess now supports node `^20.17.0 || >=22.9.0` +### Bug Fixes +* [`687cfaf`](https://github.com/npm/cli/commit/687cfafa91af13048037c5f544c15c00cf52921e) [#7831](https://github.com/npm/cli/pull/7831) for libnpmaccess sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +### Dependencies +* [`75a3f12`](https://github.com/npm/cli/commit/75a3f1228865f426d8790be27f1258e501f2c450) [#7859](https://github.com/npm/cli/pull/7859) remove unused deps (#7859) +### Chores +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) + +## [9.0.0](https://github.com/npm/cli/compare/libnpmaccess-v8.0.6...libnpmaccess-v9.0.0) (2024-10-03) +### ⚠️ BREAKING CHANGES +* `libnpmaccess` now supports node `^18.17.0 || >=20.5.0` +### Bug Fixes +* [`73068d6`](https://github.com/npm/cli/commit/73068d60ded17de3ff6a3d38ff2b83b136316ffc) [#7803](https://github.com/npm/cli/pull/7803) align libnpmaccess to npm 10 node engine range (@reggi) +### Dependencies +* [`d13a20b`](https://github.com/npm/cli/commit/d13a20bebef1b9932f86c44741ea6d214ad6842b) [#7803](https://github.com/npm/cli/pull/7803) update `npm-registry-fetch@18.0.1` +* [`50a7bc8`](https://github.com/npm/cli/commit/50a7bc8737bb4e0a8fbc5f00b8f580512153a5bc) [#7803](https://github.com/npm/cli/pull/7803) update `npm-package-arg@12.0.0` +### Chores +* [`2072705`](https://github.com/npm/cli/commit/2072705aa80d009dc077639adc305692f4a6c0b9) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/eslint-config@5.0.1` (@reggi) +* [`8035725`](https://github.com/npm/cli/commit/80357253ecd8483463cd66c783c4464c330d72df) [#7756](https://github.com/npm/cli/pull/7756) `@npmcli/template-oss@4.23.3` (@wraithgar) + ## [8.0.6](https://github.com/npm/cli/compare/libnpmaccess-v8.0.5...libnpmaccess-v8.0.6) (2024-05-15) ### Dependencies @@ -188,7 +250,7 @@ - `2668386` deps: npm-registry-fetch@8.0.0 ([@mikemimik](https://github.com/mikemimik)) - `ef093e2` deps: tap@14.10.6 ([@mikemimik](https://github.com/mikemimik)) -### Miscellanieous +### Miscellaneous - `8e33902` chore: basic project updates ([@claudiahdz](https://github.com/claudiahdz)) - `50e1433` fix: update return value; add tests ([@mikemimik](https://github.com/mikemimik)) - `36d5c80` chore: updated gitignore; includes coverage folder ([@mikemimik](https://github.com/mikemimik)) diff --git a/workspaces/libnpmaccess/README.md b/workspaces/libnpmaccess/README.md index 060016bc2a0b6..233b61e65ea1a 100644 --- a/workspaces/libnpmaccess/README.md +++ b/workspaces/libnpmaccess/README.md @@ -64,8 +64,8 @@ Sets access level for package described by `spec`. The npm registry accepts the following `access` levels: -`public`: package is public -`private`: package is private +- `public`: package is public +- `private`: package is private The npm registry also only allows scoped packages to have their access level set. @@ -73,15 +73,15 @@ level set. #### access.setMfa(spec, level, opts) -> Promise` Sets the publishing mfa requirements for a given package. Level must be one of the -following +following: -`none`: mfa is not required to publish this package. -`publish`: mfa is required to publish this package, automation tokens +- `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 +- `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` +#### access.setPermissions(team, spec, permissions, opts) -> Promise` Sets permissions levels for a given team to a package. @@ -89,5 +89,5 @@ 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 +- `read-only`: Read only permissions +- `read-write`: Read and write (aka publish) permissions diff --git a/workspaces/libnpmaccess/lib/index.js b/workspaces/libnpmaccess/lib/index.js index fca0e47279bfb..71ba6ea352acd 100644 --- a/workspaces/libnpmaccess/lib/index.js +++ b/workspaces/libnpmaccess/lib/index.js @@ -73,7 +73,7 @@ const setMfa = async (pkg, level, opts) => { body.publish_requires_tfa = false break case 'publish': - // tfa is required, automation tokens can not override tfa + // tfa is required, automation tokens cannot override tfa body.publish_requires_tfa = true body.automation_token_overrides_tfa = false break diff --git a/workspaces/libnpmaccess/package.json b/workspaces/libnpmaccess/package.json index 64a4af0bee153..35549dbb848cf 100644 --- a/workspaces/libnpmaccess/package.json +++ b/workspaces/libnpmaccess/package.json @@ -1,24 +1,24 @@ { "name": "libnpmaccess", - "version": "8.0.6", + "version": "11.0.0-pre.0", "description": "programmatic library for `npm access` commands", "author": "GitHub Inc.", "license": "ISC", "main": "lib/index.js", "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "test": "tap", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", + "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-registry": "^1.0.0", - "@npmcli/template-oss": "4.22.0", - "nock": "^13.3.3", + "@npmcli/template-oss": "5.1.1", "tap": "^16.3.8" }, "repository": { @@ -29,11 +29,11 @@ "bugs": "https://github.com/npm/libnpmaccess/issues", "homepage": "https://npmjs.com/package/libnpmaccess", "dependencies": { - "npm-package-arg": "^11.0.2", - "npm-registry-fetch": "^17.0.1" + "npm-package-arg": "^14.0.0", + "npm-registry-fetch": "^20.0.1" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "files": [ "bin/", @@ -41,10 +41,14 @@ ], "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../../scripts/template-oss/index.js" }, "tap": { + "node-arg": [ + "--require", + "../../scripts/disable-agent-for-tests.js" + ], "nyc-arg": [ "--exclude", "tap-snapshots/**" diff --git a/workspaces/libnpmdiff/.gitignore b/workspaces/libnpmdiff/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/workspaces/libnpmdiff/.gitignore +++ b/workspaces/libnpmdiff/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/workspaces/libnpmdiff/CHANGELOG.md b/workspaces/libnpmdiff/CHANGELOG.md index 32cb0435a275b..37b9f37b73cad 100644 --- a/workspaces/libnpmdiff/CHANGELOG.md +++ b/workspaces/libnpmdiff/CHANGELOG.md @@ -4,6 +4,170 @@ * [workspace](https://github.com/npm/cli/releases/tag/arborist-v7.5.4): `@npmcli/arborist@7.5.4` +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.1): `@npmcli/arborist@9.0.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.2): `@npmcli/arborist@9.0.2` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.0): `@npmcli/arborist@9.1.0` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.1): `@npmcli/arborist@9.1.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.2): `@npmcli/arborist@9.1.2` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.3): `@npmcli/arborist@9.1.3` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.4): `@npmcli/arborist@9.1.4` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.7): `@npmcli/arborist@9.1.7` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.9): `@npmcli/arborist@9.1.9` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.10): `@npmcli/arborist@9.1.10` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.3.0): `@npmcli/arborist@9.3.0` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.3.1): `@npmcli/arborist@9.3.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.0): `@npmcli/arborist@9.4.0` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.1): `@npmcli/arborist@9.4.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.2): `@npmcli/arborist@9.4.2` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v10.0.0-pre.0.0): `@npmcli/arborist@10.0.0-pre.0.0` + +## [9.0.0-pre.0](https://github.com/npm/cli/compare/libnpmdiff-v8.1.6-pre.0...libnpmdiff-v9.0.0-pre.0) (2026-06-19) +### ⚠️ BREAKING CHANGES +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +* allow-git and allow-remote now default to "none"; set them to "all" (or "root") to install git or user-supplied tarball-URL dependencies. +### Features +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +* [`caa3295`](https://github.com/npm/cli/commit/caa329568d32587e53f6e098f43b550dd2685034) [#9466](https://github.com/npm/cli/pull/9466) default allow-git and allow-remote to none (@owlstronaut) +### Bug Fixes +* [`c5292fa`](https://github.com/npm/cli/commit/c5292fa8a09a56b25394d393faf21e47ffb096c0) [#9422](https://github.com/npm/cli/pull/9422) use prerelease strategy without a bug (@owlstronaut) +### Dependencies +* [`cc96d57`](https://github.com/npm/cli/commit/cc96d57246df7cbcaedca6c2540d4e45190d9bb8) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/installed-package-contents@5.0.0` +* [`a44c1cf`](https://github.com/npm/cli/commit/a44c1cf1635de5ecda02ed80af70f5d7360111b6) [#9559](https://github.com/npm/cli/pull/9559) `pacote@22.0.0` +* [`d80859a`](https://github.com/npm/cli/commit/d80859a2dd97376e4ea621812b3bc7de6a218d21) [#9559](https://github.com/npm/cli/pull/9559) `npm-package-arg@14.0.0` +### Chores +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v10.0.0-pre.1): `@npmcli/arborist@10.0.0-pre.1` + +## [8.1.0](https://github.com/npm/cli/compare/libnpmdiff-v8.0.13...libnpmdiff-v8.1.0) (2026-02-04) +### Features +* [`f5f6cf7`](https://github.com/npm/cli/commit/f5f6cf7c9fc9315b96eb29c5c7d5ab63ad3a9122) [#8943](https://github.com/npm/cli/pull/8943) config: add --allow-git (@wraithgar) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.2.0): `@npmcli/arborist@9.2.0` + +## [8.0.11](https://github.com/npm/cli/compare/libnpmdiff-v8.0.10...libnpmdiff-v8.0.11) (2025-11-25) +### Dependencies +* [`9d77b84`](https://github.com/npm/cli/commit/9d77b84ce961a28941af8b1a597a03e308828cd4) [#8770](https://github.com/npm/cli/pull/8770) `@npmcli/installed-package-contents@4.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.8): `@npmcli/arborist@9.1.8` + +## [8.0.9](https://github.com/npm/cli/compare/libnpmdiff-v8.0.8...libnpmdiff-v8.0.9) (2025-10-08) +### Documentation +* [`268e4f8`](https://github.com/npm/cli/commit/268e4f8ae9845991e15cccd7bcaf2545af766898) [#8642](https://github.com/npm/cli/pull/8642) rewrap markdown (#8642) (@jsoref) +### Chores +* [`6c4c387`](https://github.com/npm/cli/commit/6c4c387ea9f8900a1e1e70e661be1ec54b073aea) [#8609](https://github.com/npm/cli/pull/8609) Fix spelling in workspaces/libnpmdiff (#8609) (@jsoref) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.6): `@npmcli/arborist@9.1.6` + +## [8.0.8](https://github.com/npm/cli/compare/libnpmdiff-v8.0.7...libnpmdiff-v8.0.8) (2025-09-23) +### Dependencies +* [`849dcb6`](https://github.com/npm/cli/commit/849dcb6dc22a16f01869ba9c6bf9146143000b25) [#8589](https://github.com/npm/cli/pull/8589) `tar@7.5.1` (#8589) +* [`ef87ec6`](https://github.com/npm/cli/commit/ef87ec6612fe5924d3466967aa7e104f3f98bf15) [#8576](https://github.com/npm/cli/pull/8576) `diff@8.0.2` +* [`566f1b7`](https://github.com/npm/cli/commit/566f1b7b487ad80604c61162ddde769d5ac2b241) [#8576](https://github.com/npm/cli/pull/8576) `minimatch@10.0.3` +* [`bf6b686`](https://github.com/npm/cli/commit/bf6b6862731e03002cc6fa3b86b6f090df46b009) [#8576](https://github.com/npm/cli/pull/8576) `npm-package-arg@13.0.0` +* [`b6bb9ae`](https://github.com/npm/cli/commit/b6bb9aea4134c47f0593c111a734eda12ec3c20d) [#8576](https://github.com/npm/cli/pull/8576) `pacote@21.0.3` +### Chores +* [`402a0ab`](https://github.com/npm/cli/commit/402a0ab1b4e5d1a8414dd063d0cbde0c0bc5a192) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/template-oss@4.25.1` (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.5): `@npmcli/arborist@9.1.5` + +## [8.0.0](https://github.com/npm/cli/compare/libnpmdiff-v8.0.0-pre.1...libnpmdiff-v8.0.0) (2024-12-16) +### Features +* [`a7bfc6d`](https://github.com/npm/cli/commit/a7bfc6df76882996ebb834dbca785fdf33b8c50d) [#7972](https://github.com/npm/cli/pull/7972) trigger release process (#7972) (@wraithgar) +### Chores +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0): `@npmcli/arborist@9.0.0` + +## [8.0.0-pre.1](https://github.com/npm/cli/compare/libnpmdiff-v8.0.0-pre.0...libnpmdiff-v8.0.0-pre.1) (2024-12-06) +### ⚠️ BREAKING CHANGES +* `bun.lockb` files are now included in the strict ignore list during packing +### Dependencies +* [`ac8eb39`](https://github.com/npm/cli/commit/ac8eb390b0e0a21346fcdc5476ee0b884278b3a9) [#7955](https://github.com/npm/cli/pull/7955) `diff@7.0.0` +* [`c0bcc2a`](https://github.com/npm/cli/commit/c0bcc2a860fec5c86234dec44f5474364c25aefc) [#7955](https://github.com/npm/cli/pull/7955) `walk-up-path@4.0.0` +* [`ca84b22`](https://github.com/npm/cli/commit/ca84b22a18806495c37ef6ee2aecd42a1c7bb7f6) [#7945](https://github.com/npm/cli/pull/7945) `pacote@21.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0-pre.1): `@npmcli/arborist@9.0.0-pre.1` + +## [8.0.0-pre.0](https://github.com/npm/cli/compare/libnpmdiff-v7.0.0...libnpmdiff-v8.0.0-pre.0) (2024-11-26) +### ⚠️ BREAKING CHANGES +* libnpmdiff now supports node `^20.17.0 || >=22.9.0` +### Bug Fixes +* [`dab3042`](https://github.com/npm/cli/commit/dab304274805ac64a0cb063eb21fa7d26fb5c1ce) [#7831](https://github.com/npm/cli/pull/7831) for libnpmdiff sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +### Dependencies +* [`7dbef6f`](https://github.com/npm/cli/commit/7dbef6f3a3ead089b1b8b9fe6b2fa25e24309000) [#7850](https://github.com/npm/cli/pull/7850) `pacote@20.0.0` +### Chores +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0-pre.0): `@npmcli/arborist@9.0.0-pre.0` + +## [7.0.0](https://github.com/npm/cli/compare/libnpmdiff-v6.1.4...libnpmdiff-v7.0.0) (2024-10-03) +### ⚠️ BREAKING CHANGES +* `libnpmdiff` now supports node `^18.17.0 || >=20.5.0` +### Bug Fixes +* [`340a330`](https://github.com/npm/cli/commit/340a330a312ec784c100637fb3ff064a3fd68c56) [#7803](https://github.com/npm/cli/pull/7803) align libnpmdiff to npm 10 node engine range (@reggi) +### Dependencies +* [`820e983`](https://github.com/npm/cli/commit/820e983b1d5a82d6c9c10895487c2e43b423d6ef) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/installed-package-contents@3.0.0` +* [`e7ab206`](https://github.com/npm/cli/commit/e7ab206370e5fc62fefe6916e5dcc40b3e577d22) [#7803](https://github.com/npm/cli/pull/7803) update `pacote@19.0.0` +* [`50a7bc8`](https://github.com/npm/cli/commit/50a7bc8737bb4e0a8fbc5f00b8f580512153a5bc) [#7803](https://github.com/npm/cli/pull/7803) update `npm-package-arg@12.0.0` +### Chores +* [`2072705`](https://github.com/npm/cli/commit/2072705aa80d009dc077639adc305692f4a6c0b9) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/eslint-config@5.0.1` (@reggi) +* [`8035725`](https://github.com/npm/cli/commit/80357253ecd8483463cd66c783c4464c330d72df) [#7756](https://github.com/npm/cli/pull/7756) `@npmcli/template-oss@4.23.3` (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v8.0.0): `@npmcli/arborist@8.0.0` + ## [6.1.3](https://github.com/npm/cli/compare/libnpmdiff-v6.1.2...libnpmdiff-v6.1.3) (2024-05-29) ### Bug Fixes @@ -325,7 +489,8 @@ ### ⚠️ BREAKING CHANGES -* `npm pack` now follows a strict order of operations when applying ignore rules. If a files array is present in the package.json, then rules in .gitignore and .npmignore files from the root will be ignored. +* `npm pack` now follows a strict order of operations when applying ignore rules. +If a files array is present in the package.json, then rules in .gitignore and .npmignore files from the root will be ignored. ### Features diff --git a/workspaces/libnpmdiff/README.md b/workspaces/libnpmdiff/README.md index b8eb083bdded7..0b329df0a2bad 100644 --- a/workspaces/libnpmdiff/README.md +++ b/workspaces/libnpmdiff/README.md @@ -52,15 +52,11 @@ index v1.1.0..v1.1.1 100644 ### 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. +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. +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. @@ -70,23 +66,34 @@ Happy hacking! #### `> 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). +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 also 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`. +- `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. +Returns a `Promise` that fulfills 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. diff --git a/workspaces/libnpmdiff/lib/format-diff.js b/workspaces/libnpmdiff/lib/format-diff.js index a6606d94b8b30..f50738207c854 100644 --- a/workspaces/libnpmdiff/lib/format-diff.js +++ b/workspaces/libnpmdiff/lib/format-diff.js @@ -19,7 +19,7 @@ const color = (colorStr, colorId) => { return colorStr.replace(/[^\n\r]+/g, open + '$&' + close) } -const formatDiff = ({ files, opts = {}, refs, versions }) => { +const formatDiff = async ({ files, opts = {}, refs, versions }) => { let res = '' const srcPrefix = opts.diffNoPrefix ? '' : opts.diffSrcPrefix || 'a/' const dstPrefix = opts.diffNoPrefix ? '' : opts.diffDstPrefix || 'b/' @@ -77,7 +77,7 @@ const formatDiff = ({ files, opts = {}, refs, versions }) => { /* eslint-disable-next-line max-len */ header(`index ${opts.tagVersionPrefix || 'v'}${versions.a}..${opts.tagVersionPrefix || 'v'}${versions.b} ${fileMode}`) - if (shouldPrintPatch(filename)) { + if (await shouldPrintPatch(filename)) { patch += jsDiff.createTwoFilesPatch( names.a, names.b, diff --git a/workspaces/libnpmdiff/lib/index.js b/workspaces/libnpmdiff/lib/index.js index 10532c1990dc4..3b3ce90408606 100644 --- a/workspaces/libnpmdiff/lib/index.js +++ b/workspaces/libnpmdiff/lib/index.js @@ -22,7 +22,10 @@ const diff = async (specs, opts = {}) => { aManifest, bManifest, ] = - await Promise.all(specs.map(spec => pacote.manifest(spec, opts))) + await Promise.all(specs.map(spec => pacote.manifest(spec, { + ...opts, + _isRoot: true, + }))) const versions = { a: aManifest.version, diff --git a/workspaces/libnpmdiff/lib/should-print-patch.js b/workspaces/libnpmdiff/lib/should-print-patch.js index 8000fc5e6afc1..c63cdee87c1fa 100644 --- a/workspaces/libnpmdiff/lib/should-print-patch.js +++ b/workspaces/libnpmdiff/lib/should-print-patch.js @@ -1,14 +1,14 @@ const { basename, extname } = require('node:path') -const binaryExtensions = require('binary-extensions') - // we should try to print patches as long as the // extension is not identified as binary files -const shouldPrintPatch = (path, opts = {}) => { +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('.') diff --git a/workspaces/libnpmdiff/lib/tarball.js b/workspaces/libnpmdiff/lib/tarball.js index e2738b58f11bc..a78b3e18ee8b5 100644 --- a/workspaces/libnpmdiff/lib/tarball.js +++ b/workspaces/libnpmdiff/lib/tarball.js @@ -29,10 +29,21 @@ const tarball = (manifest, opts) => { return nodeModulesTarball(manifest, opts) } - return pacote.tarball(manifest._resolved, { - ...opts, - Arborist, - }) + // pacote re-parses manifest._resolved as type=remote, so allow-remote=none + // would mis-fire on the tarball URL the registry just handed us. mirror + // arborist reify's carve-out: trust resolved tarballs for registry-typed specs. + const tarballOpts = { ...opts, Arborist } + let fromSpec + try { + fromSpec = manifest._from ? npa(manifest._from) : null + } catch { + fromSpec = null + } + if (fromSpec?.registry) { + tarballOpts.allowRemote = 'all' + } + + return pacote.tarball(manifest._resolved, tarballOpts) } module.exports = tarball diff --git a/workspaces/libnpmdiff/lib/untar.js b/workspaces/libnpmdiff/lib/untar.js index 341ae27d1e826..6bbecd8a59ce0 100644 --- a/workspaces/libnpmdiff/lib/untar.js +++ b/workspaces/libnpmdiff/lib/untar.js @@ -37,7 +37,6 @@ const untar = ({ files, refs }, { filterFiles, item, prefix }) => { // should skip reading file when using --name-only option let content try { - entry.setEncoding('utf8') content = entry.concat() } catch (e) { /* istanbul ignore next */ @@ -80,11 +79,12 @@ const readTarballs = async (tarballs, opts = {}) => { } // await to read all content from included files + // TODO this feels like it could be one in one pass instead of three (values, map, forEach) const allRefs = [...refs.values()] const contents = await Promise.all(allRefs.map(async ref => ref.content)) contents.forEach((content, index) => { - allRefs[index].content = content + allRefs[index].content = content.toString('utf8') }) return { diff --git a/workspaces/libnpmdiff/package.json b/workspaces/libnpmdiff/package.json index f1c28fd1735a2..9ddd23fffef19 100644 --- a/workspaces/libnpmdiff/package.json +++ b/workspaces/libnpmdiff/package.json @@ -1,6 +1,6 @@ { "name": "libnpmdiff", - "version": "6.1.4", + "version": "9.0.0-pre.0", "description": "The registry diff", "repository": { "type": "git", @@ -13,7 +13,7 @@ "lib/" ], "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "keywords": [ "npm", @@ -32,32 +32,33 @@ ], "license": "ISC", "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "tap": "^16.3.8" }, "dependencies": { - "@npmcli/arborist": "^7.5.4", - "@npmcli/installed-package-contents": "^2.1.0", - "binary-extensions": "^2.3.0", - "diff": "^5.1.0", - "minimatch": "^9.0.4", - "npm-package-arg": "^11.0.2", - "pacote": "^18.0.6", - "tar": "^6.2.1" + "@npmcli/arborist": "^10.0.0-pre.1", + "@npmcli/installed-package-contents": "^5.0.0", + "binary-extensions": "^3.0.0", + "diff": "^8.0.2", + "minimatch": "^10.0.3", + "npm-package-arg": "^14.0.0", + "pacote": "^22.0.0", + "tar": "^7.5.1" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../../scripts/template-oss/index.js" }, "tap": { diff --git a/workspaces/libnpmdiff/tap-snapshots/test/format-diff.js.test.cjs b/workspaces/libnpmdiff/tap-snapshots/test/format-diff.js.test.cjs index a35d1f1ce55a8..fe27264cc2c2d 100644 --- a/workspaces/libnpmdiff/tap-snapshots/test/format-diff.js.test.cjs +++ b/workspaces/libnpmdiff/tap-snapshots/test/format-diff.js.test.cjs @@ -49,8 +49,8 @@ index v1.0.0..v2.0.0 100644 --- before/foo.js +++ after/foo.js @@ -4,4 +4,6 @@ - const c = "c" -+const d = "d" + const c = "c" ++ const d = "d" module.exports = () => a+ b+ -c @@ -105,7 +105,6 @@ index v1.0.0..v2.0.0 @@ -1,2 +0,0 @@ -"use strict" -module.exports = "foo" -/ No newline at end of file ` exports[`test/format-diff.js TAP format simple diff > should output expected diff result 1`] = ` diff --git a/workspaces/libnpmdiff/test/format-diff.js b/workspaces/libnpmdiff/test/format-diff.js index f2fc7c77d7f11..911961792a2b6 100644 --- a/workspaces/libnpmdiff/test/format-diff.js +++ b/workspaces/libnpmdiff/test/format-diff.js @@ -8,7 +8,7 @@ const normalizeWin = (str) => str t.cleanSnapshot = (str) => normalizeWin(str) -t.test('format simple diff', t => { +t.test('format simple diff', async t => { const files = new Set([ 'foo.js', ]) @@ -27,7 +27,7 @@ t.test('format simple diff', t => { b: '2.0.0', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -35,10 +35,9 @@ t.test('format simple diff', t => { }), 'should output expected diff result' ) - t.end() }) -t.test('nothing to diff', t => { +t.test('nothing to diff', async t => { const files = new Set([ 'foo.js', ]) @@ -57,7 +56,7 @@ t.test('nothing to diff', t => { b: '1.0.0', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -65,10 +64,9 @@ t.test('nothing to diff', t => { }), 'should output empty result' ) - t.end() }) -t.test('format removed file', t => { +t.test('format removed file', async t => { const files = new Set([ 'foo.js', ]) @@ -83,7 +81,7 @@ t.test('format removed file', t => { b: '2.0.0', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -91,10 +89,9 @@ t.test('format removed file', t => { }), 'should output expected removed file diff result' ) - t.end() }) -t.test('changed file mode', t => { +t.test('changed file mode', async t => { const files = new Set([ 'foo.js', ]) @@ -113,7 +110,7 @@ t.test('changed file mode', t => { b: '2.0.0', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -121,10 +118,9 @@ t.test('changed file mode', t => { }), 'should output expected changed file mode diff result' ) - t.end() }) -t.test('added file', t => { +t.test('added file', async t => { const files = new Set([ 'foo.js', ]) @@ -139,7 +135,7 @@ t.test('added file', t => { b: '2.0.0', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -147,10 +143,9 @@ t.test('added file', t => { }), 'should output expected added file diff result' ) - t.end() }) -t.test('binary file', t => { +t.test('binary file', async t => { const files = new Set([ 'foo.jpg', ]) @@ -169,7 +164,7 @@ t.test('binary file', t => { b: '2.0.0', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -177,10 +172,9 @@ t.test('binary file', t => { }), 'should output expected bin file diff result' ) - t.end() }) -t.test('nothing to compare', t => { +t.test('nothing to compare', async t => { const files = new Set([ 'foo.jpg', ]) @@ -193,7 +187,7 @@ t.test('nothing to compare', t => { b: '2.0.0', } - t.equal( + await t.resolveMatch( formatDiff({ files, refs, @@ -202,10 +196,9 @@ t.test('nothing to compare', t => { '', 'should have no output' ) - t.end() }) -t.test('colored output', t => { +t.test('colored output', async t => { const files = new Set([ 'foo.js', ]) @@ -224,7 +217,7 @@ t.test('colored output', t => { b: '2.0.0', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -235,10 +228,9 @@ t.test('colored output', t => { }), 'should output expected colored diff result' ) - t.end() }) -t.test('using --name-only option', t => { +t.test('using --name-only option', async t => { const files = new Set([ 'foo.js', 'lib/bar.js', @@ -277,7 +269,7 @@ t.test('using --name-only option', t => { b: '2.0.0', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -288,10 +280,9 @@ t.test('using --name-only option', t => { }), 'should output expected diff result' ) - t.end() }) -t.test('respect --tag-version-prefix option', t => { +t.test('respect --tag-version-prefix option', async t => { const files = new Set([ 'foo.js', ]) @@ -310,7 +301,7 @@ t.test('respect --tag-version-prefix option', t => { b: '2.0.0', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -321,10 +312,9 @@ t.test('respect --tag-version-prefix option', t => { }), 'should output expected diff result' ) - t.end() }) -t.test('diff options', t => { +t.test('diff options', async t => { const files = new Set([ 'foo.js', ]) @@ -346,7 +336,7 @@ t.test('diff options', t => { b: '2.0.0', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -360,10 +350,9 @@ t.test('diff options', t => { }), 'should output expected diff result' ) - t.end() }) -t.test('diffUnified=0', t => { +t.test('diffUnified=0', async t => { const files = new Set([ 'foo.js', ]) @@ -385,7 +374,7 @@ t.test('diffUnified=0', t => { b: '2.0.0', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -396,10 +385,9 @@ t.test('diffUnified=0', t => { }), 'should output no context lines in output' ) - t.end() }) -t.test('noPrefix', t => { +t.test('noPrefix', async t => { const files = new Set([ 'foo.js', ]) @@ -418,7 +406,7 @@ t.test('noPrefix', t => { b: '2.0.0', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -429,10 +417,9 @@ t.test('noPrefix', t => { }), 'should output result with no prefixes' ) - t.end() }) -t.test('format multiple files patch', t => { +t.test('format multiple files patch', async t => { const files = new Set([ 'foo.js', 'lib/bar.js', @@ -471,7 +458,7 @@ t.test('format multiple files patch', t => { b: '1.1.1', } - t.matchSnapshot( + await t.resolveMatchSnapshot( formatDiff({ files, refs, @@ -479,5 +466,4 @@ t.test('format multiple files patch', t => { }), 'should output expected result for multiple files' ) - t.end() }) diff --git a/workspaces/libnpmdiff/test/should-print-patch.js b/workspaces/libnpmdiff/test/should-print-patch.js index 97b15787d3933..ad841a5808af1 100644 --- a/workspaces/libnpmdiff/test/should-print-patch.js +++ b/workspaces/libnpmdiff/test/should-print-patch.js @@ -1,28 +1,25 @@ const t = require('tap') const shouldPrintPatch = require('../lib/should-print-patch.js') -t.test('valid filenames', t => { - t.ok(shouldPrintPatch('LICENSE')) - t.ok(shouldPrintPatch('.gitignore')) - t.ok(shouldPrintPatch('foo.md')) - t.ok(shouldPrintPatch('./bar.txt')) - t.ok(shouldPrintPatch('/a/b/c/bar.html')) - t.end() +t.test('valid filenames', async t => { + await t.resolves(shouldPrintPatch('LICENSE'), true) + await t.resolves(shouldPrintPatch('.gitignore'), true) + await t.resolves(shouldPrintPatch('foo.md'), true) + await t.resolves(shouldPrintPatch('./bar.txt'), true) + await t.resolves(shouldPrintPatch('/a/b/c/bar.html'), true) }) -t.test('invalid filenames', t => { - t.notOk(shouldPrintPatch('foo.exe')) - t.notOk(shouldPrintPatch('./foo.jpg')) - t.notOk(shouldPrintPatch('/a/b/c/bar.bin')) - t.end() +t.test('invalid filenames', async t => { + await t.resolves(shouldPrintPatch('foo.exe'), false) + await t.resolves(shouldPrintPatch('./foo.jpg'), false) + await t.resolves(shouldPrintPatch('/a/b/c/bar.bin'), false) }) -t.test('using --text/-a option', t => { +t.test('using --text/-a option', async t => { const opts = { diffText: true, } - t.ok(shouldPrintPatch('foo.exe', opts)) - t.ok(shouldPrintPatch('./foo.jpg', opts)) - t.ok(shouldPrintPatch('/a/b/c/bar.bin', opts)) - t.end() + await t.resolves(shouldPrintPatch('foo.exe', opts), true) + await t.resolves(shouldPrintPatch('./foo.jpg', opts), true) + await t.resolves(shouldPrintPatch('/a/b/c/bar.bin', opts), true) }) diff --git a/workspaces/libnpmdiff/test/tarball.js b/workspaces/libnpmdiff/test/tarball.js index e182c159bc541..e5ababd3c2036 100644 --- a/workspaces/libnpmdiff/test/tarball.js +++ b/workspaces/libnpmdiff/test/tarball.js @@ -93,3 +93,51 @@ t.test('pkg not in a node_modules folder', async t => { 'should call regular pacote.tarball method instead' ) }) + +t.test('allowRemote carve-out for registry-mediated tarballs', async t => { + const originalTarball = pacote.tarball + let captured + pacote.tarball = async (resolved, opts) => { + captured = { resolved, opts } + return Buffer.alloc(0) + } + t.teardown(() => { + pacote.tarball = originalTarball + }) + + t.beforeEach(() => { + captured = undefined + }) + + t.test('registry-typed _from sets allowRemote=all', async t => { + await tarball({ + _from: 'abbrev@1.0.0', + _resolved: 'https://registry.npmjs.org/abbrev/-/abbrev-1.0.0.tgz', + }, {}) + t.equal(captured.opts.allowRemote, 'all') + }) + + t.test('non-registry _from leaves allowRemote untouched', async t => { + await tarball({ + _from: 'https://example.com/foo.tgz', + _resolved: 'https://example.com/foo.tgz', + }, {}) + t.notOk(captured.opts.allowRemote) + }) + + t.test('missing _from leaves allowRemote untouched', async t => { + await tarball({ + _resolved: 'https://example.com/foo.tgz', + }, {}) + t.notOk(captured.opts.allowRemote) + }) + + t.test('unparseable _from leaves allowRemote untouched', async t => { + // npa throws on tags with reserved characters, exercising the catch branch + await tarball({ + _from: '@', + _resolved: 'https://example.com/foo.tgz', + }, {}) + t.notOk(captured.opts.allowRemote) + }) +}) diff --git a/workspaces/libnpmexec/.gitignore b/workspaces/libnpmexec/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/workspaces/libnpmexec/.gitignore +++ b/workspaces/libnpmexec/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/workspaces/libnpmexec/CHANGELOG.md b/workspaces/libnpmexec/CHANGELOG.md index ebec7bb175264..78934681287e4 100644 --- a/workspaces/libnpmexec/CHANGELOG.md +++ b/workspaces/libnpmexec/CHANGELOG.md @@ -1,5 +1,218 @@ # Changelog +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.1): `@npmcli/arborist@9.1.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.2): `@npmcli/arborist@9.1.2` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.3): `@npmcli/arborist@9.1.3` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.4): `@npmcli/arborist@9.1.4` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.9): `@npmcli/arborist@9.1.9` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.10): `@npmcli/arborist@9.1.10` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.3.0): `@npmcli/arborist@9.3.0` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.3.1): `@npmcli/arborist@9.3.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.1): `@npmcli/arborist@9.4.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.2): `@npmcli/arborist@9.4.2` + +## [11.0.0-pre.0](https://github.com/npm/cli/compare/libnpmexec-v10.2.6-pre.0...libnpmexec-v11.0.0-pre.0) (2026-06-19) +### ⚠️ BREAKING CHANGES +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +### Features +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +* [`64e3f79`](https://github.com/npm/cli/commit/64e3f798344e66f4c500636cb8aec5c8111a1fe9) [#9480](https://github.com/npm/cli/pull/9480) allowScripts tooling and inBundle hardening (#9480) (@JamieMagee) +### Bug Fixes +* [`6901bb1`](https://github.com/npm/cli/commit/6901bb185a5ca323d6d76561136a906a5023ea6d) [#9436](https://github.com/npm/cli/pull/9436) escape executable name in libnpmexec run-script (#9436) (@rootvector2) +* [`c5292fa`](https://github.com/npm/cli/commit/c5292fa8a09a56b25394d393faf21e47ffb096c0) [#9422](https://github.com/npm/cli/pull/9422) use prerelease strategy without a bug (@owlstronaut) +* [`6237783`](https://github.com/npm/cli/commit/62377832db5f91ae50856ef871c16e3d07c074e2) [#9408](https://github.com/npm/cli/pull/9408) exempt local project introspection from allow-directory (@owlstronaut) +### Dependencies +* [`b62db95`](https://github.com/npm/cli/commit/b62db95b7768049f58a0aca0d7266cba6ed17757) [#9559](https://github.com/npm/cli/pull/9559) `bin-links@7.0.0` +* [`3484d7f`](https://github.com/npm/cli/commit/3484d7f1cdb7595353562129e6ab6ef83204f227) [#9559](https://github.com/npm/cli/pull/9559) `read@6.0.0` +* [`21df0ab`](https://github.com/npm/cli/commit/21df0ab3c629496511a3c481ee721b0e62c16e92) [#9559](https://github.com/npm/cli/pull/9559) `proc-log@7.0.0` +* [`a44c1cf`](https://github.com/npm/cli/commit/a44c1cf1635de5ecda02ed80af70f5d7360111b6) [#9559](https://github.com/npm/cli/pull/9559) `pacote@22.0.0` +* [`d80859a`](https://github.com/npm/cli/commit/d80859a2dd97376e4ea621812b3bc7de6a218d21) [#9559](https://github.com/npm/cli/pull/9559) `npm-package-arg@14.0.0` +* [`9d13ebf`](https://github.com/npm/cli/commit/9d13ebfc2adca5543e4797632039adaa7a318985) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/run-script@11.0.0` +* [`0be6ae2`](https://github.com/npm/cli/commit/0be6ae21c79eb3986a76d5d769d5dd5ef00283c2) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/package-json@8.0.0` +### Chores +* [`1453954`](https://github.com/npm/cli/commit/1453954f9328a6b2480c183f9d1903ac93764915) [#9559](https://github.com/npm/cli/pull/9559) `nock@14.0.0` (@owlstronaut) +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v10.0.0-pre.1): `@npmcli/arborist@10.0.0-pre.1` + +## [10.2.6-pre.0.0](https://github.com/npm/cli/compare/libnpmexec-v10.2.5...libnpmexec-v10.2.6-pre.0.0) (2026-05-20) +### Bug Fixes +* [`e9b0157`](https://github.com/npm/cli/commit/e9b0157b367aef184e7c4e99b90d9fcb8f0bff54) [#9255](https://github.com/npm/cli/pull/9255) libnpmexec: skip redundant reify for cached directory specs (#9255) (@manzoorwanijk) +### Chores +* [`2ca36c4`](https://github.com/npm/cli/commit/2ca36c4b37f50419303db41cf482d05f5ec69023) [#9261](https://github.com/npm/cli/pull/9261) fixed non-functional typos throughout the codebase (@opensourcezeal) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v10.0.0-pre.0.0): `@npmcli/arborist@10.0.0-pre.0.0` + +## [10.2.3](https://github.com/npm/cli/compare/libnpmexec-v10.2.2...libnpmexec-v10.2.3) (2026-02-25) +### Bug Fixes +* [`cf88236`](https://github.com/npm/cli/commit/cf8823608afe4229cb05f8b6c29890a6bda64502) [#9008](https://github.com/npm/cli/pull/9008) use @gar/promise-retry instead of promise-retry (@wraithgar) +### Dependencies +* [`60f332c`](https://github.com/npm/cli/commit/60f332c9df28e736f510ef8ac1f207175687dcad) [#9008](https://github.com/npm/cli/pull/9008) remove promise-retry +* [`cb8b9c7`](https://github.com/npm/cli/commit/cb8b9c7a45d81883ada7891f492afbf998574d10) [#9008](https://github.com/npm/cli/pull/9008) add `@gar/promise-retry@1.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.0): `@npmcli/arborist@9.4.0` + +## [10.2.0](https://github.com/npm/cli/compare/libnpmexec-v10.1.12...libnpmexec-v10.2.0) (2026-02-04) +### Features +* [`f5f6cf7`](https://github.com/npm/cli/commit/f5f6cf7c9fc9315b96eb29c5c7d5ab63ad3a9122) [#8943](https://github.com/npm/cli/pull/8943) config: add --allow-git (@wraithgar) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.2.0): `@npmcli/arborist@9.2.0` + +## [10.1.10](https://github.com/npm/cli/compare/libnpmexec-v10.1.9...libnpmexec-v10.1.10) (2025-11-25) +### Dependencies +* [`e2ac092`](https://github.com/npm/cli/commit/e2ac092fdab0ccbf3b20abbac7ff1ebb7cda9a88) [#8770](https://github.com/npm/cli/pull/8770) `read@5.0.1` +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.8): `@npmcli/arborist@9.1.8` + +## [10.1.9](https://github.com/npm/cli/compare/libnpmexec-v10.1.8...libnpmexec-v10.1.9) (2025-11-19) +### Bug Fixes +* [`3439a89`](https://github.com/npm/cli/commit/3439a89d58a25deac08650da53157595e8b8edfb) [#8733](https://github.com/npm/cli/pull/8733) libnpmexec: fix lock compromise logic (#8733) (@jenseng) +### Dependencies +* [`05ac7a7`](https://github.com/npm/cli/commit/05ac7a7ea2a4d258658537a19ba350e07df34fda) [#8723](https://github.com/npm/cli/pull/8723) `proc-log@6.0.0` +* [`0a74f6d`](https://github.com/npm/cli/commit/0a74f6d1d8643f3a089f6e63502df77e6e3038ff) [#8723](https://github.com/npm/cli/pull/8723) `bin-links@6.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.7): `@npmcli/arborist@9.1.7` + +## [10.1.8](https://github.com/npm/cli/compare/libnpmexec-v10.1.7...libnpmexec-v10.1.8) (2025-10-08) +### Bug Fixes +* [`d62c5fe`](https://github.com/npm/cli/commit/d62c5fe9a7c6b180019cd4d62e7963f232038ebb) [#8625](https://github.com/npm/cli/pull/8625) spelling in workspaces/libnpmexec (#8625) (@jsoref) +### Chores +* [`91393de`](https://github.com/npm/cli/commit/91393deaf71bad084bb1d2aa868d5f895cc5f103) [#8599](https://github.com/npm/cli/pull/8599) Update references for arborist to cli (#8599) (@jsoref) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.6): `@npmcli/arborist@9.1.6` + +## [10.1.7](https://github.com/npm/cli/compare/libnpmexec-v10.1.6...libnpmexec-v10.1.7) (2025-09-23) +### Bug Fixes +* [`1eedf82`](https://github.com/npm/cli/commit/1eedf82f2a36df193a51dca2c07fdc82dcb18a68) [#8576](https://github.com/npm/cli/pull/8576) use @npmcli/package-json to parse package.json (@wraithgar) +* [`7949cff`](https://github.com/npm/cli/commit/7949cff04d28e2344461a18ef30bf36fc76a091d) [#8577](https://github.com/npm/cli/pull/8577) libnpmexec: improve withLock stability (#8577) (@jenseng) +* [`5db81c3`](https://github.com/npm/cli/commit/5db81c350654dbbe2e1442d623efada9a24e04f1) [#8512](https://github.com/npm/cli/pull/8512) allow concurrent non-local npx calls (#8512) (@jenseng, @wraithgar) +### Dependencies +* [`bf6b686`](https://github.com/npm/cli/commit/bf6b6862731e03002cc6fa3b86b6f090df46b009) [#8576](https://github.com/npm/cli/pull/8576) `npm-package-arg@13.0.0` +* [`6b4c5f9`](https://github.com/npm/cli/commit/6b4c5f92865230ed9a260cd3e8486bf3991120eb) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/run-script@10.0.0` +* [`b6bb9ae`](https://github.com/npm/cli/commit/b6bb9aea4134c47f0593c111a734eda12ec3c20d) [#8576](https://github.com/npm/cli/pull/8576) `pacote@21.0.3` +* [`ceae674`](https://github.com/npm/cli/commit/ceae674c32a080b81e62d79003c2d537d7ca93d2) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/package-json@7.0.1` +* [`4f37534`](https://github.com/npm/cli/commit/4f37534300553e9ddfbc413c14d1ef15b02b46f2) [#8576](https://github.com/npm/cli/pull/8576) remove read-package-json-fast +### Chores +* [`402a0ab`](https://github.com/npm/cli/commit/402a0ab1b4e5d1a8414dd063d0cbde0c0bc5a192) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/template-oss@4.25.1` (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.5): `@npmcli/arborist@9.1.5` + +## [10.1.2](https://github.com/npm/cli/compare/libnpmexec-v10.1.1...libnpmexec-v10.1.2) (2025-05-15) +### Bug Fixes +* [`fdc3413`](https://github.com/npm/cli/commit/fdc3413019c2f34f1fde35449e5f3a6b0fb51ba2) [#8221](https://github.com/npm/cli/pull/8221) exec: Fails to Execute Binaries Named After Shell Keywords (#8221) (@13sfaith) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.0): `@npmcli/arborist@9.1.0` + +## [10.1.1](https://github.com/npm/cli/compare/libnpmexec-v10.1.0...libnpmexec-v10.1.1) (2025-04-08) +### Bug Fixes +* [`386f328`](https://github.com/npm/cli/commit/386f32898067d8ae17a160271bf1bc1832e6ebb4) [#8154](https://github.com/npm/cli/pull/8154) npx: always save true when installing to npx cache (#8154) (@milaninfy) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.2): `@npmcli/arborist@9.0.2` + +## [10.1.0](https://github.com/npm/cli/compare/libnpmexec-v10.0.0...libnpmexec-v10.1.0) (2025-03-05) +### Features +* [`d18d422`](https://github.com/npm/cli/commit/d18d422e081fbf33a0671cbd83a64531c485f940) [#8100](https://github.com/npm/cli/pull/8100) add context to npx cache package.json (@wraithgar) +### Bug Fixes +* [`8461186`](https://github.com/npm/cli/commit/846118686849f821b084775f7891038013f7ba97) [#8100](https://github.com/npm/cli/pull/8100) update npx cache if possible when spec is a range (@wraithgar) +### Dependencies +* [`3d8b257`](https://github.com/npm/cli/commit/3d8b257bd667e76e74236c756aaa2dceaa6d6e5e) [#8100](https://github.com/npm/cli/pull/8100) `@npmcli/package-json@6.1.1` +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.1): `@npmcli/arborist@9.0.1` + +## [10.0.0](https://github.com/npm/cli/compare/libnpmexec-v10.0.0-pre.1...libnpmexec-v10.0.0) (2024-12-16) +### Features +* [`a7bfc6d`](https://github.com/npm/cli/commit/a7bfc6df76882996ebb834dbca785fdf33b8c50d) [#7972](https://github.com/npm/cli/pull/7972) trigger release process (#7972) (@wraithgar) +### Chores +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0): `@npmcli/arborist@9.0.0` + +## [10.0.0-pre.1](https://github.com/npm/cli/compare/libnpmexec-v10.0.0-pre.0...libnpmexec-v10.0.0-pre.1) (2024-12-06) +### ⚠️ BREAKING CHANGES +* `bun.lockb` files are now included in the strict ignore list during packing +### Dependencies +* [`c0bcc2a`](https://github.com/npm/cli/commit/c0bcc2a860fec5c86234dec44f5474364c25aefc) [#7955](https://github.com/npm/cli/pull/7955) `walk-up-path@4.0.0` +* [`ca84b22`](https://github.com/npm/cli/commit/ca84b22a18806495c37ef6ee2aecd42a1c7bb7f6) [#7945](https://github.com/npm/cli/pull/7945) `pacote@21.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0-pre.1): `@npmcli/arborist@9.0.0-pre.1` + +## [10.0.0-pre.0](https://github.com/npm/cli/compare/libnpmexec-v9.0.0...libnpmexec-v10.0.0-pre.0) (2024-11-26) +### ⚠️ BREAKING CHANGES +* libnpmexec now supports node `^20.17.0 || >=22.9.0` +### Bug Fixes +* [`7f541e8`](https://github.com/npm/cli/commit/7f541e82a0b2908cc0cfef9a36b714eeab40c029) [#7815](https://github.com/npm/cli/pull/7815) make pack and exec work with git hash refs (#7815) (@milaninfy) +* [`2902d4c`](https://github.com/npm/cli/commit/2902d4cfd363eac1dd011e90bd9a1b156852155c) [#7831](https://github.com/npm/cli/pull/7831) for libnpmexec sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +### Dependencies +* [`7dbef6f`](https://github.com/npm/cli/commit/7dbef6f3a3ead089b1b8b9fe6b2fa25e24309000) [#7850](https://github.com/npm/cli/pull/7850) `pacote@20.0.0` +### Chores +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0-pre.0): `@npmcli/arborist@9.0.0-pre.0` + +## [9.0.0](https://github.com/npm/cli/compare/libnpmexec-v8.1.4...libnpmexec-v9.0.0) (2024-10-03) +### ⚠️ BREAKING CHANGES +* `libnpmexec` now supports node `^18.17.0 || >=20.5.0` +### Bug Fixes +* [`a2c8016`](https://github.com/npm/cli/commit/a2c80166e02a79402fb7bbb629f8ecc14ff8b546) [#7803](https://github.com/npm/cli/pull/7803) align libnpmexec to npm 10 node engine range (@reggi) +### Dependencies +* [`99ccae3`](https://github.com/npm/cli/commit/99ccae3ded6f7013b26ed268a208c24473cdeb8f) [#7803](https://github.com/npm/cli/pull/7803) update `bin-links@5.0.0` +* [`9cd6603`](https://github.com/npm/cli/commit/9cd66031ebd2e9a0d6fdee3a7b4d7779694306ff) [#7803](https://github.com/npm/cli/pull/7803) update `read-package-json-fast@4.0.0` +* [`8b7dbc8`](https://github.com/npm/cli/commit/8b7dbc8234914352b2649f56c6a11765f1904e30) [#7803](https://github.com/npm/cli/pull/7803) update `read@4.0.0` +* [`f6909a0`](https://github.com/npm/cli/commit/f6909a022c9373c85d980c96a30f47a3a65aa4a9) [#7803](https://github.com/npm/cli/pull/7803) update `proc-log@5.0.0` +* [`e7ab206`](https://github.com/npm/cli/commit/e7ab206370e5fc62fefe6916e5dcc40b3e577d22) [#7803](https://github.com/npm/cli/pull/7803) update `pacote@19.0.0` +* [`50a7bc8`](https://github.com/npm/cli/commit/50a7bc8737bb4e0a8fbc5f00b8f580512153a5bc) [#7803](https://github.com/npm/cli/pull/7803) update `npm-package-arg@12.0.0` +* [`538a4cc`](https://github.com/npm/cli/commit/538a4cc1dd731a3643ab4477fe545db39997bcdf) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/run-script@9.0.1` +### Chores +* [`2072705`](https://github.com/npm/cli/commit/2072705aa80d009dc077639adc305692f4a6c0b9) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/eslint-config@5.0.1` (@reggi) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v8.0.0): `@npmcli/arborist@8.0.0` + +## [8.1.4](https://github.com/npm/cli/compare/libnpmexec-v8.1.3...libnpmexec-v8.1.4) (2024-08-28) +### Bug Fixes +* [`9214be9`](https://github.com/npm/cli/commit/9214be9ed8779493e00d193e36a930918a30be64) [#7640](https://github.com/npm/cli/pull/7640) gracefully handle nonexistent global installation directory (#7640) (@milaninfy) +### Chores +* [`8035725`](https://github.com/npm/cli/commit/80357253ecd8483463cd66c783c4464c330d72df) [#7756](https://github.com/npm/cli/pull/7756) `@npmcli/template-oss@4.23.3` (@wraithgar) + ## [8.1.3](https://github.com/npm/cli/compare/libnpmexec-v8.1.2...libnpmexec-v8.1.3) (2024-07-09) ### Bug Fixes diff --git a/workspaces/libnpmexec/README.md b/workspaces/libnpmexec/README.md index acd037c110b4b..84512ac590498 100644 --- a/workspaces/libnpmexec/README.md +++ b/workspaces/libnpmexec/README.md @@ -40,7 +40,7 @@ await libexec({ - `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** + - `registry`, `cache`, and more options that are forwarded to [@npmcli/arborist](https://github.com/npm/cli/blob/latest/workspaces/arborist/README.md) and [pacote](https://github.com/npm/pacote/#options) **Object** ## LICENSE diff --git a/workspaces/libnpmexec/lib/get-bin-from-manifest.js b/workspaces/libnpmexec/lib/get-bin-from-manifest.js index 8ebc0e7a18bd2..cede563c96a0d 100644 --- a/workspaces/libnpmexec/lib/get-bin-from-manifest.js +++ b/workspaces/libnpmexec/lib/get-bin-from-manifest.js @@ -1,7 +1,7 @@ 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 + // that; otherwise, fail const bin = mani.bin || {} if (new Set(Object.values(bin)).size === 1) { return Object.keys(bin)[0] diff --git a/workspaces/libnpmexec/lib/index.js b/workspaces/libnpmexec/lib/index.js index 8344471696e25..35452f796246b 100644 --- a/workspaces/libnpmexec/lib/index.js +++ b/workspaces/libnpmexec/lib/index.js @@ -1,20 +1,23 @@ 'use strict' +const { dirname, join, resolve } = require('node:path') +const crypto = require('node:crypto') const { mkdir } = require('node:fs/promises') const Arborist = require('@npmcli/arborist') +const strictAllowScriptsPreflight = require('./strict-allow-scripts-preflight.js') 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 PackageJson = require('@npmcli/package-json') 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 withLock = require('./with-lock.js') const binPaths = [] @@ -24,7 +27,12 @@ const manifests = new Map() const getManifest = async (spec, flatOptions) => { if (!manifests.has(spec.raw)) { - const manifest = await pacote.manifest(spec, { ...flatOptions, preferOnline: true }) + const manifest = await pacote.manifest(spec, { + ...flatOptions, + preferOnline: true, + Arborist, + _isRoot: true, + }) manifests.set(spec.raw, manifest) } return manifests.get(spec.raw) @@ -37,6 +45,7 @@ const missingFromTree = async ({ spec, tree, flatOptions, isNpxTree, shallow }) // - 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 they gave a range and not a tag we still need to check if it's outdated. if (spec.registry && spec.type !== 'tag' && !npxByNameOnly) { // registry spec that is not a specific tag. const nodesBySpec = tree.inventory.query('packageName', spec.name) @@ -53,7 +62,8 @@ const missingFromTree = async ({ spec, tree, flatOptions, isNpxTree, shallow }) return { node } } // package requested by version range, only remaining registry type - if (semver.satisfies(node.package.version, spec.rawSpec)) { + // the npx tree shouldn't be ok w/ an outdated version + if (!isNpxTree && semver.satisfies(node.package.version, spec.rawSpec)) { return { node } } } @@ -63,12 +73,12 @@ const missingFromTree = async ({ spec, tree, flatOptions, isNpxTree, shallow }) // 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') { + if (spec.type === 'directory' && !isNpxTree) { return { manifest } } const nodesByManifest = tree.inventory.query('packageName', manifest.name) for (const node of nodesByManifest) { - if (node.package.resolved === manifest._resolved) { + if (node.package.resolved === manifest._resolved || node.realpath === manifest._resolved) { // we have a package by the same name and the same resolved destination, nothing to add. return { node } } @@ -77,9 +87,14 @@ const missingFromTree = async ({ spec, tree, flatOptions, isNpxTree, shallow }) } } +// Strict-mode pre-flight for `npm exec` / `npx` lives in +// ./strict-allow-scripts-preflight.js + // see if the package.json at `path` has an entry that matches `cmd` +// the path is a known-local directory, not a user-supplied dep, so +// allow-directory must not gate this introspection const hasPkgBin = (path, cmd, flatOptions) => - pacote.manifest(path, flatOptions) + pacote.manifest(path, { ...flatOptions, allowDirectory: 'all' }) .then(manifest => manifest?.bin?.[cmd]).catch(() => null) const exec = async (opts) => { @@ -138,6 +153,8 @@ const exec = async (opts) => { // we have to install the local package into the npx cache so that its // bin links get set up flatOptions.installLinks = false + // self-execution of a local bin, not a directory dep install + flatOptions.allowDirectory = 'all' // args[0] will exist when the package is installed packages.push(p) yes = true @@ -244,7 +261,8 @@ const exec = async (opts) => { ...flatOptions, path: installDir, }) - const npxTree = await npxArb.loadActual() + const lockPath = join(installDir, 'concurrency.lock') + const npxTree = await withLock(lockPath, () => npxArb.loadActual()) await Promise.all(needInstall.map(async ({ spec }) => { const { manifest } = await missingFromTree({ spec, @@ -287,12 +305,21 @@ const exec = async (opts) => { } } } - await npxArb.reify({ - ...flatOptions, - add, + await withLock(lockPath, async () => { + // Hard-fail before reify if --strict-allow-scripts is set and + // any node has install scripts not covered by allowScripts. + await strictAllowScriptsPreflight(npxArb, { ...flatOptions, add }) + await npxArb.reify({ + ...flatOptions, + save: true, + add, + }) }) } binPaths.push(resolve(installDir, 'node_modules/.bin')) + const pkgJson = await PackageJson.load(installDir) + pkgJson.update({ _npx: { packages } }) + await pkgJson.save() } return await run() diff --git a/workspaces/libnpmexec/lib/run-script.js b/workspaces/libnpmexec/lib/run-script.js index 1f621edcbc9aa..2de40454f9dcf 100644 --- a/workspaces/libnpmexec/lib/run-script.js +++ b/workspaces/libnpmexec/lib/run-script.js @@ -1,8 +1,9 @@ const ciInfo = require('ci-info') const runScript = require('@npmcli/run-script') -const readPackageJson = require('read-package-json-fast') +const pkgJson = require('@npmcli/package-json') const { log, output } = require('proc-log') const noTTY = require('./no-tty.js') +const isWindowsShell = require('./is-windows.js') const run = async ({ args, @@ -14,12 +15,25 @@ const run = async ({ runPath, scriptShell, }) => { + // escape executable path + // necessary for preventing bash/cmd keywords from overriding + if (!isWindowsShell) { + if (args.length > 0) { + // single-quote so shell metacharacters in the executable name are taken + // literally; double quotes still expand $(), backticks, $var and " + args[0] = `'${args[0].replace(/'/g, `'\\''`)}'` + } + } + // 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 { content: realPkg } = await pkgJson.normalize(path, { steps: [ + 'binDir', + ...pkgJson.normalizeSteps, + ] }).catch(() => ({ content: {} })) const pkg = { ...realPkg, scripts: { diff --git a/workspaces/libnpmexec/lib/strict-allow-scripts-preflight.js b/workspaces/libnpmexec/lib/strict-allow-scripts-preflight.js new file mode 100644 index 0000000000000..579fd0c0fddf2 --- /dev/null +++ b/workspaces/libnpmexec/lib/strict-allow-scripts-preflight.js @@ -0,0 +1,40 @@ +const { collectUnreviewedScripts, strictAllowScriptsError } = require('@npmcli/arborist/lib/unreviewed-scripts.js') + +// Strict-mode pre-flight for `npm exec` / `npx`. When +// `--strict-allow-scripts` is set, build the npx-cache ideal tree and +// throw before reify if any node has install scripts not covered by +// the resolved `allowScripts` policy. The arborist gate already +// silently skips those scripts; this turns the silent skip into a +// hard failure for CI. Bypassed by `--ignore-scripts` and +// `--dangerously-allow-all-scripts`. +const strictAllowScriptsPreflight = async (arb, opts) => { + if (!opts.strictAllowScripts) { + return + } + if (opts.ignoreScripts || opts.dangerouslyAllowAllScripts) { + return + } + + if (!arb.idealTree) { + await arb.buildIdealTree(opts) + } + + const unreviewed = await collectUnreviewedScripts({ + tree: arb.idealTree, + policy: opts.allowScripts || null, + ignoreScripts: opts.ignoreScripts, + dangerouslyAllowAllScripts: opts.dangerouslyAllowAllScripts, + }) + + if (unreviewed.length === 0) { + return + } + + throw strictAllowScriptsError(unreviewed, { + remediation: + 'Pass --allow-scripts= for one-off approval, or bypass this ' + + 'check with --dangerously-allow-all-scripts.', + }) +} + +module.exports = strictAllowScriptsPreflight diff --git a/workspaces/libnpmexec/lib/with-lock.js b/workspaces/libnpmexec/lib/with-lock.js new file mode 100644 index 0000000000000..f6cc381c14602 --- /dev/null +++ b/workspaces/libnpmexec/lib/with-lock.js @@ -0,0 +1,177 @@ +const fs = require('node:fs/promises') +const { rmdirSync } = require('node:fs') +const { promiseRetry } = require('@gar/promise-retry') +const { onExit } = require('signal-exit') + +// a lockfile implementation inspired by the unmaintained proper-lockfile library +// +// similarities: +// - based on mkdir's atomicity +// - works across processes and even machines (via NFS) +// - cleans up after itself +// - detects compromised locks +// +// differences: +// - higher-level API (just a withLock function) +// - written in async/await style +// - uses mtime + inode for more reliable compromised lock detection +// - more ergonomic compromised lock handling (i.e. withLock will reject, and callbacks have access to an AbortSignal) +// - uses a more recent version of signal-exit + +// mtime precision is platform dependent, so deal in seconds +const touchInterval = 1_000 +// use a reasonably large threshold, in case stat calls take a while +const staleThreshold = 60_000 + +// track current locks and their cleanup functions +const currentLocks = new Map() + +function cleanupLocks () { + for (const [, cleanup] of currentLocks) { + try { + cleanup() + } catch (err) { + // + } + } +} + +// clean up any locks that were not released normally +onExit(cleanupLocks) + +/** + * Acquire an advisory lock for the given path and hold it for the duration of the callback. + * + * The lock will be released automatically when the callback resolves or rejects. + * Concurrent calls to withLock() for the same path will wait until the lock is released. + */ +async function withLock (lockPath, cb) { + try { + const signal = await acquireLock(lockPath) + return await new Promise((resolve, reject) => { + signal.addEventListener('abort', () => { + reject(Object.assign(new Error('Lock compromised'), { code: 'ECOMPROMISED' })) + }); + + (async () => { + try { + resolve(await cb(signal)) + } catch (err) { + reject(err) + } + })() + }) + } finally { + releaseLock(lockPath) + } +} + +function acquireLock (lockPath) { + return promiseRetry(async (retry) => { + try { + await fs.mkdir(lockPath) + } catch (err) { + if (err.code !== 'EEXIST' && err.code !== 'EBUSY' && err.code !== 'EPERM') { + throw err + } + + const status = await getLockStatus(lockPath) + + if (status === 'locked') { + // let's see if we can acquire it on the next attempt 🤞 + return retry(err) + } + if (status === 'stale') { + try { + // there is a very tiny window where another process could also release the stale lock and acquire it before we release it here; the lock compromise checker should detect this and throw an error + deleteLock(lockPath) + } catch (e) { + // on windows, EBUSY/EPERM can happen if another process is (re)creating the lock; maybe we can acquire it on a subsequent attempt 🤞 + if (e.code === 'EBUSY' || e.code === 'EPERM') { + return retry(e) + } + throw e + } + } + // immediately attempt to acquire the lock (no backoff) + return await acquireLock(lockPath) + } + try { + const signal = await maintainLock(lockPath) + return signal + } catch (err) { + throw Object.assign(new Error('Lock compromised'), { code: 'ECOMPROMISED' }) + } + }, { + minTimeout: 100, + maxTimeout: 5_000, + // if another process legitimately holds the lock, wait for it to release; if it dies abnormally and the lock becomes stale, we'll acquire it automatically + forever: true, + }) +} + +function deleteLock (lockPath) { + try { + // synchronous, so we can call in an exit handler + rmdirSync(lockPath) + } catch (err) { + if (err.code !== 'ENOENT') { + throw err + } + } +} + +function releaseLock (lockPath) { + currentLocks.get(lockPath)?.() + currentLocks.delete(lockPath) +} + +async function getLockStatus (lockPath) { + try { + const stat = await fs.stat(lockPath) + return (Date.now() - stat.mtimeMs > staleThreshold) ? 'stale' : 'locked' + } catch (err) { + if (err.code === 'ENOENT') { + return 'unlocked' + } + throw err + } +} + +async function maintainLock (lockPath) { + const controller = new AbortController() + const stats = await fs.stat(lockPath) + // fs.utimes operates on floating points seconds (directly, or via strings/Date objects), which may not match the underlying filesystem's mtime precision, meaning that we might read a slightly different mtime than we write. always round to the nearest second, since all filesystems support at least second precision + let mtime = Math.round(stats.mtimeMs / 1000) + const signal = controller.signal + + let timeout + async function touchLock () { + try { + const currentStats = (await fs.stat(lockPath)) + const currentMtime = Math.round(currentStats.mtimeMs / 1000) + if (currentStats.ino !== stats.ino || currentMtime !== mtime) { + throw new Error('Lock compromised') + } + mtime = Math.round(Date.now() / 1000) + // touch the lock, unless we just released it during this iteration + if (currentLocks.has(lockPath)) { + await fs.utimes(lockPath, mtime, mtime) + } + timeout = setTimeout(touchLock, touchInterval).unref() + } catch (err) { + // stats mismatch or other fs error means the lock was compromised + controller.abort() + } + } + + timeout = setTimeout(touchLock, touchInterval).unref() + function cleanup () { + clearTimeout(timeout) + deleteLock(lockPath) + } + currentLocks.set(lockPath, cleanup) + return signal +} + +module.exports = withLock diff --git a/workspaces/libnpmexec/package.json b/workspaces/libnpmexec/package.json index 159501266386a..ceb27812f6206 100644 --- a/workspaces/libnpmexec/package.json +++ b/workspaces/libnpmexec/package.json @@ -1,13 +1,13 @@ { "name": "libnpmexec", - "version": "8.1.3", + "version": "11.0.0-pre.0", "files": [ "bin/", "lib/" ], "main": "lib/index.js", "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "description": "npm exec (npx) programmatic API", "repository": { @@ -33,46 +33,53 @@ ], "license": "ISC", "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "posttest": "npm run lint", "test": "tap", "snap": "tap", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "template-oss-apply": "template-oss-apply --force" + "lintfix": "npm run eslint -- --fix", + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "files": "test/*.js", + "node-arg": [ + "--require", + "../../scripts/disable-agent-for-tests.js" + ], "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", + "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-registry": "^1.0.0", - "@npmcli/template-oss": "4.22.0", - "bin-links": "^4.0.4", + "@npmcli/template-oss": "5.1.1", + "bin-links": "^7.0.0", "chalk": "^5.2.0", "just-extend": "^6.2.0", "just-safe-set": "^4.2.1", "tap": "^16.3.8" }, "dependencies": { - "@npmcli/arborist": "^7.5.4", - "@npmcli/run-script": "^8.1.0", + "@gar/promise-retry": "^1.0.0", + "@npmcli/arborist": "^10.0.0-pre.1", + "@npmcli/package-json": "^8.0.0", + "@npmcli/run-script": "^11.0.0", "ci-info": "^4.0.0", - "npm-package-arg": "^11.0.2", - "pacote": "^18.0.6", - "proc-log": "^4.2.0", - "read": "^3.0.1", - "read-package-json-fast": "^3.0.2", + "npm-package-arg": "^14.0.0", + "pacote": "^22.0.0", + "proc-log": "^7.0.0", + "read": "^6.0.0", "semver": "^7.3.7", - "walk-up-path": "^3.0.1" + "signal-exit": "^4.1.0", + "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.22.0", + "version": "5.1.1", "content": "../../scripts/template-oss/index.js" } } diff --git a/workspaces/libnpmexec/test/get-bin-from-manifest.js b/workspaces/libnpmexec/test/get-bin-from-manifest.js index 24e7dc8e2c6b3..1110d7d080cd0 100644 --- a/workspaces/libnpmexec/test/get-bin-from-manifest.js +++ b/workspaces/libnpmexec/test/get-bin-from-manifest.js @@ -15,7 +15,7 @@ t.test('extract scope from manifest name with multiple bins', t => { t.end() }) -t.test('can not figure out what executable to run', t => { +t.test('cannot figure out what executable to run', t => { t.throws( () => getBinFromManifest({ name: 'lorem', diff --git a/workspaces/libnpmexec/test/local.js b/workspaces/libnpmexec/test/local.js index 5828ab4fa9f9c..2423440c9d82c 100644 --- a/workspaces/libnpmexec/test/local.js +++ b/workspaces/libnpmexec/test/local.js @@ -58,7 +58,7 @@ t.test('bin in local pkg', async t => { await chmod('node_modules/pkg-with-conflicting-bin/index.js') // Note that we have to resetSeenLinks after each exec since otherwise - // our non-existent file will fail when it gets attempted to get chmod'ed + // our nonexistent file will fail when it gets attempted to get chmod'ed // in a real world situation these would happen during different // processes where these is no shared cache const exec = async (...args) => { @@ -278,6 +278,59 @@ t.test('no npxCache', async t => { }), /Must provide a valid npxCache path/) }) +t.test('local file system path - skips reify on subsequent runs', async t => { + let reifyCount = 0 + const Arborist = require('@npmcli/arborist') + const { exec, chmod, readOutput, rmOutput, path } = setup(t, { + mocks: { + 'ci-info': { isCI: true }, + '@npmcli/arborist': class extends Arborist { + async reify (...args) { + reifyCount++ + return super.reify(...args) + } + }, + }, + testdir: { + a: { + 'package.json': { + name: 'a', + bin: { + a: './index.js', + }, + }, + 'index.js': { key: 'a', value: 'LOCAL PKG' }, + }, + }, + }) + + await chmod('a/index.js') + + // First run should reify (cold cache) + await exec({ + args: [`file:${resolve(path, 'a')}`, 'resfile'], + }) + + t.match(await readOutput('a'), { + value: 'LOCAL PKG', + args: ['resfile'], + }) + t.equal(reifyCount, 1, 'first run should reify') + + await rmOutput('a') + + // Second run should skip reify (cached) + await exec({ + args: [`file:${resolve(path, 'a')}`, 'resfile'], + }) + + t.match(await readOutput('a'), { + value: 'LOCAL PKG', + args: ['resfile'], + }) + t.equal(reifyCount, 1, 'second run should not reify') +}) + t.test('local file system path', async t => { const { exec, chmod, readOutput, path } = setup(t, { mocks: { @@ -370,3 +423,49 @@ t.test('global scoped pkg', async t => { created: 'global/node_modules/@npmcli/create-test/bin-file.js', }) }) + +// Regression: local bin lookup must not be gated by allow-directory, +// even when the policy is `none` or `root`. +for (const allowDirectory of ['none', 'root']) { + t.test(`local bin still resolves with allow-directory=${allowDirectory}`, async t => { + const { pkg, fixtures } = createPkg({ + version: '1.0.0', + name: '@npmcli/local-pkg-allow-directory-test', + bin: { + a: 'local-bin-test.js', + }, + files: { + 'local-bin-test.js': { key: 'local-bin', value: 'LOCAL PKG' }, + }, + }) + + const { exec, chmod, readOutput, path } = setup(t, { + pkg, + testdir: merge( + fixtures.packages[`@npmcli-local-pkg-allow-directory-test-1.0.0`], + { + node_modules: { + '@npmcli': { + 'some-other-pkg-with-same-scope': {}, + }, + }, + } + ), + }) + + const localBin = resolve(path, 'node_modules', '.bin') + + await chmod('local-bin-test.js') + + await exec({ + localBin, + args: ['a', 'argument-a'], + allowDirectory, + }) + + t.match(await readOutput('local-bin'), { + value: 'LOCAL PKG', + args: ['argument-a'], + }) + }) +} diff --git a/workspaces/libnpmexec/test/registry.js b/workspaces/libnpmexec/test/registry.js index a9ae2cb8a597e..adbf4116107b4 100644 --- a/workspaces/libnpmexec/test/registry.js +++ b/workspaces/libnpmexec/test/registry.js @@ -1,6 +1,8 @@ const { resolve } = require('node:path') const t = require('tap') const { setup, createPkg, merge } = require('./fixtures/setup.js') +const crypto = require('node:crypto') +const { existsSync } = require('node:fs') t.test('run from registry - no local packages', async t => { const { fixtures, package } = createPkg({ versions: ['2.0.0'] }) @@ -227,7 +229,7 @@ t.test('packages with different versions in the global tree', async t => { }) }) -t.test('run from registry - non existant global path', async t => { +t.test('run from registry - non existent global path', async t => { const { fixtures, package } = createPkg({ versions: ['2.0.0'] }) const { exec, path, registry, readOutput } = setup(t, { @@ -238,10 +240,91 @@ t.test('run from registry - non existant global path', async t => { await exec({ args: ['@npmcli/create-index'], - globalPath: resolve(path, 'non-existant'), + globalPath: resolve(path, 'non-existent'), }) t.match(await readOutput('@npmcli-create-index'), { value: 'packages-2.0.0', }) }) + +t.test('npx tree triggers manifest fetch when local version does satisfy range using real npx cache inventory', async t => { + // The local installation is version 1.0.0, which does NOT satisfy the spec ^2.0.0. + const pkgData = createPkg({ + localVersion: '1.0.0', + versions: ['1.0.0', '2.0.0', '2.0.1'], + name: '@npmcli/create-index', + }) + const { fixtures, package: pkg } = pkgData + + const hash = crypto.createHash('sha512') + .update('@npmcli/create-index@^2.0.0') + .digest('hex') + .slice(0, 16) + + const npxCacheFixture = { + [hash]: { + 'package.json': { + name: '@npmcli/create-index', + version: '2.0.0', + }, + }, + } + + const { exec: execFn, path, registry, readOutput, binLinks } = setup(t, { + pkg: [pkg], + testdir: { + ...fixtures, + npxCache: npxCacheFixture, + }, + }) + + // Set up the registry package so that a manifest fetch returns version 2.0.1. + await pkg({ + registry, + path, + tarballs: ['2.0.1'], + }) + await binLinks() + + // Execute in NPX mode with the spec ^2.0.0. + // The local tree (version 1.0.0) does not satisfy ^2.0.0, so the system will find the cached package (version 2.0.0) in npxCache and then update from the registry to 2.0.1. + await execFn({ + args: ['create-index'], + packages: ['@npmcli/create-index@^2.0.0'], + }) + + t.match(await readOutput('@npmcli-create-index'), { + value: 'packages-2.0.1', + }) +}) + +t.test('override save to true when installing to npx cache', async t => { + const { fixtures, package } = createPkg({ versions: ['2.0.0'] }) + + const hash = crypto.createHash('sha512') + .update('@npmcli/create-index') + .digest('hex') + .slice(0, 16) + + const { exec, path, registry, readOutput } = setup(t, { + testdir: merge(fixtures, { + global: {}, + }), + }) + + await package({ registry, path }) + + await exec({ + args: ['@npmcli/create-index'], + globalPath: resolve(path, 'global'), + save: false, + }) + + const packageJsonPath = resolve(path, 'npxCache', hash, 'package.json') + t.ok(existsSync(packageJsonPath), 'package.json should exist at npmCache') + + t.match(await readOutput('@npmcli-create-index'), { + value: 'packages-2.0.0', + }) +}) diff --git a/workspaces/libnpmexec/test/run-script.js b/workspaces/libnpmexec/test/run-script.js index 01e3f35594906..5c92ce19397f6 100644 --- a/workspaces/libnpmexec/test/run-script.js +++ b/workspaces/libnpmexec/test/run-script.js @@ -115,3 +115,45 @@ t.test('ci env', async t => { t.equal(logs[0], 'warn exec Interactive mode disabled in CI environment') }) + +t.test('isWindows', async t => { + const { runScript } = await mockRunScript(t, { + 'ci-info': { isCI: true }, + '@npmcli/run-script': async () => { + t.ok('should call run-script') + }, + '../lib/is-windows.js': true, + }) + + await runScript({ args: ['test'] }) + // need both arguments and no arguments for code coverage + await runScript() +}) + +t.test('escapes executable name to neutralize shell metacharacters', async t => { + let pkg + const { runScript } = await mockRunScript(t, { + 'ci-info': { isCI: true }, + '@npmcli/run-script': async (opts) => { + pkg = opts.pkg + }, + '../lib/is-windows.js': false, + }) + + await runScript({ args: [`evil'; touch pwned #`] }) + t.equal(pkg.scripts.npx, `'evil'\\''; touch pwned #'`) +}) + +t.test('isNotWindows', async t => { + const { runScript } = await mockRunScript(t, { + 'ci-info': { isCI: true }, + '@npmcli/run-script': async () => { + t.ok('should call run-script') + }, + '../lib/is-windows.js': false, + }) + + await runScript({ args: ['test'] }) + // need both arguments and no arguments for code coverage + await runScript() +}) diff --git a/workspaces/libnpmexec/test/strict-allow-scripts-preflight.js b/workspaces/libnpmexec/test/strict-allow-scripts-preflight.js new file mode 100644 index 0000000000000..1d6795703ed31 --- /dev/null +++ b/workspaces/libnpmexec/test/strict-allow-scripts-preflight.js @@ -0,0 +1,82 @@ +const t = require('tap') + +const strictAllowScriptsPreflight = require('../lib/strict-allow-scripts-preflight.js') + +// a node carrying install scripts that the policy has not reviewed +const unreviewedTree = { + inventory: new Map([ + ['node_modules/has-scripts', { + name: 'has-scripts', + location: 'node_modules/has-scripts', + package: { scripts: { install: 'node-gyp rebuild' } }, + }], + ]), +} + +const fakeArb = (idealTree) => { + const arb = { + idealTree, + buildIdealTreeCalled: false, + async buildIdealTree () { + arb.buildIdealTreeCalled = true + arb.idealTree = unreviewedTree + }, + } + return arb +} + +t.test('no-op when strictAllowScripts is not set', async t => { + const arb = fakeArb(unreviewedTree) + await t.resolves(strictAllowScriptsPreflight(arb, {})) + t.notOk(arb.buildIdealTreeCalled, 'does not build the ideal tree') +}) + +t.test('bypassed by ignoreScripts', async t => { + const arb = fakeArb(unreviewedTree) + await t.resolves(strictAllowScriptsPreflight(arb, + { strictAllowScripts: true, ignoreScripts: true })) + t.notOk(arb.buildIdealTreeCalled, 'does not build the ideal tree') +}) + +t.test('bypassed by dangerouslyAllowAllScripts', async t => { + const arb = fakeArb(unreviewedTree) + await t.resolves(strictAllowScriptsPreflight(arb, + { strictAllowScripts: true, dangerouslyAllowAllScripts: true })) + t.notOk(arb.buildIdealTreeCalled, 'does not build the ideal tree') +}) + +t.test('builds the ideal tree when missing', async t => { + const arb = fakeArb(null) + await t.rejects( + strictAllowScriptsPreflight(arb, { strictAllowScripts: true }), + /install scripts/i, + 'throws on unreviewed scripts' + ) + t.ok(arb.buildIdealTreeCalled, 'builds the ideal tree') +}) + +t.test('throws when unreviewed scripts are present', async t => { + const arb = fakeArb(unreviewedTree) + await t.rejects( + strictAllowScriptsPreflight(arb, { strictAllowScripts: true }), + { code: 'ESTRICTALLOWSCRIPTS' }, + 'throws with the strict-allow-scripts error' + ) +}) + +t.test('resolves when no unreviewed scripts are present', async t => { + const cleanTree = { + inventory: new Map([ + ['node_modules/no-scripts', { + name: 'no-scripts', + location: 'node_modules/no-scripts', + package: {}, + }], + ]), + } + const arb = fakeArb(cleanTree) + await t.resolves( + strictAllowScriptsPreflight(arb, { strictAllowScripts: true }), + 'no error when nothing is unreviewed' + ) +}) diff --git a/workspaces/libnpmexec/test/with-lock.js b/workspaces/libnpmexec/test/with-lock.js new file mode 100644 index 0000000000000..5d37c59d50038 --- /dev/null +++ b/workspaces/libnpmexec/test/with-lock.js @@ -0,0 +1,358 @@ +const fs = require('node:fs') +const path = require('node:path') +const os = require('node:os') +const setTimeout = require('node:timers/promises').setTimeout + +const getTempDir = () => fs.realpathSync(os.tmpdir()) + +const t = require('tap') + +let mockMkdir +let mockStat +let mockUtimes +let mockRmdirSync +let onExitHandler +const withLock = t.mock('../lib/with-lock.js', { + // make various fs things mockable, but default to the real implementation + 'node:fs/promises': { + mkdir: async (...args) => { + return await (mockMkdir?.(...args) ?? fs.promises.mkdir(...args)) + }, + stat: async (...args) => { + return await (mockStat?.(...args) ?? fs.promises.stat(...args)) + }, + utimes: async (...args) => { + return await (mockUtimes?.(...args) ?? fs.promises.utimes(...args)) + }, + }, + 'node:fs': { + rmdirSync: (...args) => { + return (mockRmdirSync?.(...args) ?? fs.rmdirSync(...args)) + }, + }, + 'signal-exit': { + onExit: (handler) => { + onExitHandler = handler + }, + }, +}) + +t.beforeEach(() => { + mockMkdir = undefined + mockStat = undefined + mockUtimes = undefined + mockRmdirSync = undefined +}) + +t.test('concurrent locking', async (t) => { + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + const events = [] + const lockPromise1 = withLock(lockPath, async () => { + events.push('lock1 acquired') + await setTimeout(100) + events.push('lock1 released') + }) + await setTimeout(50) // ensure lock1 is acquired before lock2 + const lockPromise2 = withLock(lockPath, async () => { + events.push('lock2 acquired') + await setTimeout(100) + events.push('lock2 released') + return 'lock2' + }) + await Promise.all([lockPromise1, lockPromise2]) + t.same(events, [ + 'lock1 acquired', + 'lock1 released', + 'lock2 acquired', + 'lock2 released', + ], 'should acquire locks in order and release them correctly') +}) + +t.test('unrelated locks', async (t) => { + const lockPath1 = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-1-')), 'concurrency.lock') + const lockPath2 = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-2-')), 'concurrency.lock') + const lockPromise1 = withLock(lockPath1, async () => { + await setTimeout(100) + return 'lock1' + }) + const lockPromise2 = withLock(lockPath2, async () => 'lock2') + t.equal(await lockPromise2, 'lock2', 'lock2 should not be blocked by lock1') + t.equal(await lockPromise1, 'lock1', 'lock1 should complete after lock2') +}) + +t.test('resolved value', async (t) => { + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + const result = await withLock(lockPath, async () => 'test value') + t.equal(result, 'test value', 'should resolve to the same value as the callback') +}) + +t.test('rejection', async (t) => { + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + await t.rejects(withLock(lockPath, async () => { + throw new Error('test error') + }), new Error('test error')) + t.equal(await withLock(lockPath, async () => 'test'), 'test', 'should allow subsequent locks after rejection') +}) + +t.test('stale lock takeover', async (t) => { + let mkdirCalls = 0 + mockMkdir = async () => { + if (++mkdirCalls === 1) { + throw Object.assign(new Error(), { code: 'EEXIST' }) + } + } + let statCalls = 0 + const mtimeMs = Math.round(Date.now() / 1000) * 1000 + mockStat = async () => { + if (++statCalls === 1) { + return { mtimeMs: mtimeMs - 120_000 } + } else { + return { mtimeMs, ino: 1 } + } + } + mockUtimes = async () => {} + mockRmdirSync = () => {} + + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + const lockPromise = withLock(lockPath, async () => { + await setTimeout(100) + return 'test value' + }) + t.equal(await lockPromise, 'test value', 'should take over the lock') + t.equal(mkdirCalls, 2, 'should make two mkdir calls') +}) + +t.test('EBUSY during lock acquisition', async (t) => { + let mkdirCalls = 0 + mockMkdir = async (...args) => { + if (++mkdirCalls === 1) { + throw Object.assign(new Error(), { code: 'EBUSY' }) + } + return fs.promises.mkdir(...args) + } + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + t.ok(await withLock(lockPath, async () => true)) + t.equal(mkdirCalls, 2, 'should make two mkdir calls') +}) + +t.test('EBUSY during stale lock takeover', async (t) => { + let mkdirCalls = 0 + mockMkdir = async () => { + if (++mkdirCalls === 1) { + throw Object.assign(new Error(), { code: 'EEXIST' }) + } + } + let statCalls = 0 + const mtimeMs = Math.round(Date.now() / 1000) * 1000 + mockStat = async () => { + if (++statCalls === 1) { + return { mtimeMs: mtimeMs - 120_000 } + } else { + return { mtimeMs, ino: 1 } + } + } + let rmdirSyncCalls = 0 + mockRmdirSync = () => { + if (++rmdirSyncCalls === 1) { + throw Object.assign(new Error(), { code: 'EBUSY' }) + } + } + + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + const lockPromise = withLock(lockPath, async () => 'test value') + t.equal(await lockPromise, 'test value', 'should take over the lock') + t.equal(mkdirCalls, 2, 'should make two mkdir calls') +}) + +t.test('concurrent stale lock takeover', async (t) => { + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + // make a stale lock + await fs.promises.mkdir(lockPath) + await fs.promises.utimes(lockPath, new Date(Date.now() - 120_000), new Date(Date.now() - 120_000)) + + const results = await Promise.allSettled([ + withLock(lockPath, () => 'lock1'), + withLock(lockPath, () => 'lock2'), + withLock(lockPath, () => 'lock3'), + ]) + // all locks should either be successfully acquired or get compromised (expected occasional race condition) + t.ok(results.every(result => result.status === 'fulfilled' || result.status === 'rejected' && result.reason.code === 'ECOMPROMISED')) +}) + +t.test('mkdir -> getLockStatus race', async (t) => { + // validate that we can acquire a lock when mkdir fails (due to the lock existing) + // but status indicates it's unlocked (i.e. lock was released after the mkdir call) + let mkdirCalls = 0 + mockMkdir = async () => { + if (++mkdirCalls === 1) { + throw Object.assign(new Error(), { code: 'EEXIST' }) + } + } + let statCalls = 0 + const mtimeMs = Math.round(Date.now() / 1000) * 1000 + mockStat = async () => { + if (++statCalls === 1) { + throw Object.assign(new Error(), { code: 'ENOENT' }) + } else { + return { mtimeMs, ino: 1 } + } + } + mockUtimes = async () => {} + mockRmdirSync = () => {} + + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + const lockPromise = withLock(lockPath, async () => { + await setTimeout(100) + return 'test value' + }) + t.equal(await lockPromise, 'test value', 'should acquire the lock') + t.equal(mkdirCalls, 2, 'should make two mkdir calls') +}) + +t.test('mtime floating point mismatch', async (t) => { + let mtimeMs = Math.round(Date.now() / 1000) * 1000 + mockStat = async () => { + return { mtimeMs, ino: 1 } + } + mockUtimes = async (_, nextMtimeSeconds) => { + mtimeMs = nextMtimeSeconds * 1000 - 0.001 + } + + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + t.ok(await withLock(lockPath, async () => { + await setTimeout(2000) + return true + }), 'should handle mtime floating point mismatches') +}) + +t.test('slow fs.stat calls shouldn\'t cause a lock compromise false positive', async (t) => { + let mtimeMs = Math.round(Date.now() / 1000) * 1000 + let statCalls = 0 + mockStat = async () => { + const result = mtimeMs + if (++statCalls === 2) { // make it slow in the first touchLock callback + await setTimeout(2000) + } + return { mtimeMs: result, ino: 1 } + } + mockUtimes = async (_, nextMtimeSeconds) => { + mtimeMs = nextMtimeSeconds * 1000 + } + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + t.ok(await withLock(lockPath, async () => { + await setTimeout(4000) + return true + }), 'should handle slow fs.stat calls') +}) + +t.test('unexpected errors', async (t) => { + t.test('can\'t create lock', async (t) => { + const lockPath = '/these/parent/directories/do/not/exist/so/it/should/fail.lock' + await t.rejects(withLock(lockPath, async () => {}), { code: 'ENOENT' }) + }) + + t.test('can\'t release lock', async (t) => { + mockRmdirSync = () => { + throw Object.assign(new Error(), { code: 'ENOTDIR' }) + } + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + await t.rejects(withLock(lockPath, async () => {}), { code: 'ENOTDIR' }) + }) + + t.test('existing lock becomes unreadable right before we check its status', async (t) => { + // someone else has the lock + mockMkdir = async () => { + throw Object.assign(new Error(), { code: 'EEXIST' }) + } + // we can't stat the lock file + mockStat = async () => { + throw Object.assign(new Error(), { code: 'EACCES' }) + } + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + await t.rejects(withLock(lockPath, async () => {}), { code: 'EACCES' }) + }) + + t.test('can\'t take over stale lock', async (t) => { + // someone else has the lock + mockMkdir = async () => { + throw Object.assign(new Error(), { code: 'EEXIST' }) + } + // it's stale + mockStat = async () => { + return { mtimeMs: Date.now() - 120_000 } + } + // but we can't release it + mockRmdirSync = () => { + throw Object.assign(new Error(), { code: 'ENOTDIR' }) + } + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + await t.rejects(withLock(lockPath, async () => {}), { code: 'ENOTDIR' }) + }) + + t.test('lock compromised (recreated)', async (t) => { + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + + mockStat = async () => { + return { mtimeMs: Date.now(), ino: Math.floor(Math.random() * 1000000) } + } + await t.rejects(withLock(lockPath, () => setTimeout(2000)), { code: 'ECOMPROMISED' }) + }) + + t.test('lock compromised (deleted)', async (t) => { + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + + mockStat = async () => { + throw Object.assign(new Error(), { code: 'ENOENT' }) + } + await t.rejects(withLock(lockPath, () => setTimeout(2000)), { code: 'ECOMPROMISED' }) + }) +}) + +t.test('lock released during maintenance', async (t) => { + // this test validates that if we release the lock while touchLock is running, it doesn't interfere with subsequent locks + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + + let releaseLock + const releaseLockPromise = new Promise((resolve) => { + releaseLock = resolve + }) + + let statCalls = 0 + mockStat = async (...args) => { + const value = await fs.promises.stat(...args) + if (++statCalls > 1) { + // this runs during the setTimeout callback; release the lock so that we no longer hold it + await releaseLock('test value') + await setTimeout() + } + return value + } + + let utimesCalls = 0 + mockUtimes = async () => { + utimesCalls++ + } + + const lockPromise = withLock(lockPath, () => releaseLockPromise) + // since we unref the timeout, we need to wait to ensure it actually runs + await setTimeout(2000) + t.equal(await lockPromise, 'test value', 'should acquire the lock') + t.equal(utimesCalls, 0, 'should never call utimes') +}) + +t.test('onExit handler', async (t) => { + t.ok(onExitHandler, 'should be registered') + let rmdirSyncCalls = 0 + + mockRmdirSync = () => { + rmdirSyncCalls++ + } + + const lockPath = path.join(fs.mkdtempSync(path.join(getTempDir(), 'test-')), 'concurrency.lock') + // don't await it since the promise never resolves + withLock(lockPath, () => new Promise(() => {})).catch(() => {}) + // since we unref the interval timeout, we need to wait to ensure it actually runs + await setTimeout(2000) + onExitHandler() + t.ok(rmdirSyncCalls > 0, 'should have removed outstanding locks') +}) diff --git a/workspaces/libnpmfund/.gitignore b/workspaces/libnpmfund/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/workspaces/libnpmfund/.gitignore +++ b/workspaces/libnpmfund/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/workspaces/libnpmfund/CHANGELOG.md b/workspaces/libnpmfund/CHANGELOG.md index f3401fce9c6f6..3ba4172608193 100644 --- a/workspaces/libnpmfund/CHANGELOG.md +++ b/workspaces/libnpmfund/CHANGELOG.md @@ -8,6 +8,145 @@ * [workspace](https://github.com/npm/cli/releases/tag/arborist-v7.5.4): `@npmcli/arborist@7.5.4` +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0-pre.1): `@npmcli/arborist@9.0.0-pre.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.1): `@npmcli/arborist@9.0.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.2): `@npmcli/arborist@9.0.2` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.0): `@npmcli/arborist@9.1.0` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.1): `@npmcli/arborist@9.1.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.2): `@npmcli/arborist@9.1.2` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.3): `@npmcli/arborist@9.1.3` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.4): `@npmcli/arborist@9.1.4` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.5): `@npmcli/arborist@9.1.5` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.6): `@npmcli/arborist@9.1.6` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.7): `@npmcli/arborist@9.1.7` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.8): `@npmcli/arborist@9.1.8` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.9): `@npmcli/arborist@9.1.9` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.10): `@npmcli/arborist@9.1.10` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.2.0): `@npmcli/arborist@9.2.0` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.3.0): `@npmcli/arborist@9.3.0` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.3.1): `@npmcli/arborist@9.3.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.0): `@npmcli/arborist@9.4.0` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.1): `@npmcli/arborist@9.4.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.2): `@npmcli/arborist@9.4.2` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v10.0.0-pre.0.0): `@npmcli/arborist@10.0.0-pre.0.0` + +## [8.0.0-pre.0](https://github.com/npm/cli/compare/libnpmfund-v7.0.20-pre.0...libnpmfund-v8.0.0-pre.0) (2026-06-19) +### ⚠️ BREAKING CHANGES +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +### Features +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +### Bug Fixes +* [`c5292fa`](https://github.com/npm/cli/commit/c5292fa8a09a56b25394d393faf21e47ffb096c0) [#9422](https://github.com/npm/cli/pull/9422) use prerelease strategy without a bug (@owlstronaut) +### Chores +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v10.0.0-pre.1): `@npmcli/arborist@10.0.0-pre.1` + +## [7.0.0](https://github.com/npm/cli/compare/libnpmfund-v7.0.0-pre.1...libnpmfund-v7.0.0) (2024-12-16) +### Features +* [`a7bfc6d`](https://github.com/npm/cli/commit/a7bfc6df76882996ebb834dbca785fdf33b8c50d) [#7972](https://github.com/npm/cli/pull/7972) trigger release process (#7972) (@wraithgar) +### Chores +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0): `@npmcli/arborist@9.0.0` + +## [7.0.0-pre.0](https://github.com/npm/cli/compare/libnpmfund-v6.0.0...libnpmfund-v7.0.0-pre.0) (2024-11-26) +### ⚠️ BREAKING CHANGES +* libnpmfund now supports node `^20.17.0 || >=22.9.0` +### Bug Fixes +* [`44be07c`](https://github.com/npm/cli/commit/44be07cdb6d4e12a41569405e1a13b2d15fc103d) [#7831](https://github.com/npm/cli/pull/7831) for libnpmfund sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +### Chores +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0-pre.0): `@npmcli/arborist@9.0.0-pre.0` + +## [6.0.0](https://github.com/npm/cli/compare/libnpmfund-v5.0.12...libnpmfund-v6.0.0) (2024-10-03) +### ⚠️ BREAKING CHANGES +* `libnpmfund` now supports node `^18.17.0 || >=20.5.0` +### Bug Fixes +* [`e7298de`](https://github.com/npm/cli/commit/e7298de7026b960ad163cc2a137e27739b91876c) [#7803](https://github.com/npm/cli/pull/7803) align libnpmfund to npm 10 node engine range (@reggi) +### Chores +* [`2072705`](https://github.com/npm/cli/commit/2072705aa80d009dc077639adc305692f4a6c0b9) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/eslint-config@5.0.1` (@reggi) +* [`8035725`](https://github.com/npm/cli/commit/80357253ecd8483463cd66c783c4464c330d72df) [#7756](https://github.com/npm/cli/pull/7756) `@npmcli/template-oss@4.23.3` (@wraithgar) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v8.0.0): `@npmcli/arborist@8.0.0` + ## [5.0.11](https://github.com/npm/cli/compare/libnpmfund-v5.0.10...libnpmfund-v5.0.11) (2024-05-29) ### Bug Fixes diff --git a/workspaces/libnpmfund/README.md b/workspaces/libnpmfund/README.md index 6072b11d9dee7..2b5b283014c86 100644 --- a/workspaces/libnpmfund/README.md +++ b/workspaces/libnpmfund/README.md @@ -75,14 +75,14 @@ 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. +- `path`, `registry` and more [Arborist options](https://github.com/npm/cli/blob/latest/workspaces/arborist/README.md#usage). ##### `> 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: +- `tree`: An [`arborist`](https://github.com/npm/cli/blob/latest/workspaces/arborist/README.md) tree to be used, e.g: ```js const Arborist = require('@npmcli/arborist') diff --git a/workspaces/libnpmfund/package.json b/workspaces/libnpmfund/package.json index 3ce8a899ccbea..d4cebb47745a1 100644 --- a/workspaces/libnpmfund/package.json +++ b/workspaces/libnpmfund/package.json @@ -1,6 +1,6 @@ { "name": "libnpmfund", - "version": "5.0.12", + "version": "8.0.0-pre.0", "main": "lib/index.js", "files": [ "bin/", @@ -31,28 +31,29 @@ ], "license": "ISC", "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "tap": "^16.3.8" }, "dependencies": { - "@npmcli/arborist": "^7.5.4" + "@npmcli/arborist": "^10.0.0-pre.1" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../../scripts/template-oss/index.js" }, "tap": { diff --git a/workspaces/libnpmhook/.eslintrc.js b/workspaces/libnpmhook/.eslintrc.js deleted file mode 100644 index f21d26eccec7d..0000000000000 --- a/workspaces/libnpmhook/.eslintrc.js +++ /dev/null @@ -1,20 +0,0 @@ -/* This file is automatically added by @npmcli/template-oss. Do not edit. */ - -'use strict' - -const { readdirSync: readdir } = require('fs') - -const localConfigs = readdir(__dirname) - .filter((file) => file.startsWith('.eslintrc.local.')) - .map((file) => `./${file}`) - -module.exports = { - root: true, - ignorePatterns: [ - 'tap-testdir*/', - ], - extends: [ - '@npmcli', - ...localConfigs, - ], -} diff --git a/workspaces/libnpmhook/.gitignore b/workspaces/libnpmhook/.gitignore deleted file mode 100644 index a96d056a7064e..0000000000000 --- a/workspaces/libnpmhook/.gitignore +++ /dev/null @@ -1,23 +0,0 @@ -# This file is automatically added by @npmcli/template-oss. Do not edit. - -# ignore everything in the root -/* -# transient test directories -tap-testdir*/ - -# keep these -!**/.gitignore -!/.eslintrc.js -!/.eslintrc.local.* -!/.gitignore -!/bin/ -!/CHANGELOG* -!/docs/ -!/lib/ -!/LICENSE* -!/map.js -!/package.json -!/README* -!/scripts/ -!/tap-snapshots/ -!/test/ diff --git a/workspaces/libnpmhook/CHANGELOG.md b/workspaces/libnpmhook/CHANGELOG.md deleted file mode 100644 index cef8e53fd2bc8..0000000000000 --- a/workspaces/libnpmhook/CHANGELOG.md +++ /dev/null @@ -1,251 +0,0 @@ -# Changelog - -## [10.0.5](https://github.com/npm/cli/compare/libnpmhook-v10.0.4...libnpmhook-v10.0.5) (2024-05-15) - -### Dependencies - -* [`63ef498`](https://github.com/npm/cli/commit/63ef498bf2916a882a92c0b9fe6de6728584694a) [#7457](https://github.com/npm/cli/pull/7457) `npm-registry-fetch@17.0.1` - -### Chores - -* [`9c4d3c4`](https://github.com/npm/cli/commit/9c4d3c402c77bd7aaa514ee9e02d7fd87223343e) [#7467](https://github.com/npm/cli/pull/7467) template-oss-apply (@lukekarrys) -* [`2b7ec54`](https://github.com/npm/cli/commit/2b7ec54f52f9e8aee568ccb4e34ce4a5733af21a) [#7467](https://github.com/npm/cli/pull/7467) `template-oss@4.22.0` (@lukekarrys) - -## [10.0.4](https://github.com/npm/cli/compare/libnpmhook-v10.0.3...libnpmhook-v10.0.4) (2024-04-30) - -### Bug Fixes - -* [`57ebebf`](https://github.com/npm/cli/commit/57ebebf03d55d4eda2b6439149a97b595a191aaf) [#7418](https://github.com/npm/cli/pull/7418) update repository.url in package.json (#7418) (@wraithgar) - -### Dependencies - -* [`a7145d4`](https://github.com/npm/cli/commit/a7145d422485fcbcb9427efa775c15180c7ee1c2) [#7453](https://github.com/npm/cli/pull/7453) `npm-registry-fetch@17.0.0` - -## [10.0.3](https://github.com/npm/cli/compare/libnpmhook-v10.0.2...libnpmhook-v10.0.3) (2024-04-25) - -### Dependencies - -* [`ee4b3e0`](https://github.com/npm/cli/commit/ee4b3e0e741545045dc03741c7147560961d867d) [#7373](https://github.com/npm/cli/pull/7373) `npm-registry-fetch@16.2.1` - -## [10.0.2](https://github.com/npm/cli/compare/libnpmhook-v10.0.1...libnpmhook-v10.0.2) (2024-04-03) - -### Dependencies - -* [`87a61fc`](https://github.com/npm/cli/commit/87a61fc8bb65c950cda389ab3d14ae250ab2345d) [#7334](https://github.com/npm/cli/pull/7334) `npm-registry-fetch@16.2.0` - -## [10.0.1](https://github.com/npm/cli/compare/libnpmhook-v10.0.0...libnpmhook-v10.0.1) (2023-12-06) - -### Chores - -* [`f656b66`](https://github.com/npm/cli/commit/f656b669e549286844f2071b9b62cf23f7958034) [#7062](https://github.com/npm/cli/pull/7062) `@npmcli/template-oss@4.21.3` (#7062) (@lukekarrys) -* [`9754b17`](https://github.com/npm/cli/commit/9754b173de26f3173e7f41eab34733fe9ba50f1d) [#7051](https://github.com/npm/cli/pull/7051) use global npm for workspace tests (@lukekarrys) -* [`3891757`](https://github.com/npm/cli/commit/3891757f54d6d960cbf5f0d93d183d6424e8bed6) [#7051](https://github.com/npm/cli/pull/7051) `@npmcli/template-oss@4.21.2` (@lukekarrys) -* [`0270a7d`](https://github.com/npm/cli/commit/0270a7d42984210fd388f3d9a70aaa01887d29f6) [#6807](https://github.com/npm/cli/pull/6807) set workspace engines (@lukekarrys) -* [`fec08ad`](https://github.com/npm/cli/commit/fec08ade0fed990b838b781867adf03253907e91) [#6807](https://github.com/npm/cli/pull/6807) `@npmcli/template-oss@4.19.0` (@lukekarrys) - -## [10.0.0](https://github.com/npm/cli/compare/libnpmhook-v10.0.0-pre.0...libnpmhook-v10.0.0) (2023-08-31) - -### Features - -* [`fb31c7e`](https://github.com/npm/cli/commit/fb31c7e5f00ae39e67f9a5d6b6860c1d839c704b) trigger release process (@lukekarrys) - -## [10.0.0-pre.0](https://github.com/npm/cli/compare/libnpmhook-v9.0.3...libnpmhook-v10.0.0-pre.0) (2023-08-31) - -### ⚠️ BREAKING CHANGES - -* support for node <=16.13 has been removed -* support for node 14 has been removed - -### Bug Fixes - -* [`6b251b1`](https://github.com/npm/cli/commit/6b251b1009648b36d49b83a2cc407c348fa225e0) [#6706](https://github.com/npm/cli/pull/6706) drop node 16.13.x support (@lukekarrys) -* [`4caedd0`](https://github.com/npm/cli/commit/4caedd0e49641e9f1757f5622e5845b5b49c56c1) [#6706](https://github.com/npm/cli/pull/6706) drop node14 support (@lukekarrys) - -### Dependencies - -* [`2ee0fb3`](https://github.com/npm/cli/commit/2ee0fb3ac0c5e49f9eba545d6b05e20be1352414) [#6706](https://github.com/npm/cli/pull/6706) `npm-registry-fetch@16.0.0` -* [`5d0d859`](https://github.com/npm/cli/commit/5d0d8592cbf3b816d9fe44c36d390200ec15e87a) [#6706](https://github.com/npm/cli/pull/6706) `npm-registry-fetch@15.0.0` - -## [9.0.3](https://github.com/npm/cli/compare/libnpmhook-v9.0.2...libnpmhook-v9.0.3) (2023-02-07) - -### Bug Fixes - -* [`12ec7ee`](https://github.com/npm/cli/commit/12ec7ee1983876565445ae7967e2f14f3d95e356) remove unused package.json scripts (@lukekarrys) - -## [9.0.2](https://github.com/npm/cli/compare/libnpmhook-v9.0.1...libnpmhook-v9.0.2) (2023-02-01) - -### Dependencies - -* [`721fe3f`](https://github.com/npm/cli/commit/721fe3fac383d714aa7fd7285b4392619903b1e7) [#6118](https://github.com/npm/cli/pull/6118) `read-package-json-fast@3.0.2` -* [`a39556f`](https://github.com/npm/cli/commit/a39556f1cff4526dcbcb7b65cdd86a1ba092e13e) `@npmcli/template-oss@4.11.3` - -## [9.0.1](https://github.com/npm/cli/compare/libnpmhook-v9.0.0...libnpmhook-v9.0.1) (2022-12-07) - -### Dependencies - -* [`0a3fe00`](https://github.com/npm/cli/commit/0a3fe000e2723ae6fdb8b1d3154fd3835057c992) [#5933](https://github.com/npm/cli/pull/5933) `minipass@4.0.0` -* [`fee9b66`](https://github.com/npm/cli/commit/fee9b6686892a1c7f976c36ddd5d89b70c416817) `npm-registry-fetch@14.0.3` - -## [9.0.0](https://github.com/npm/cli/compare/libnpmhook-v9.0.0-pre.1...libnpmhook-v9.0.0) (2022-10-19) - -### Features - -* [`586e78d`](https://github.com/npm/cli/commit/586e78d59c3dad29e8e886a4764d2eb8021d11d1) empty commit to trigger all workspace releases (@lukekarrys) - -## [9.0.0-pre.1](https://github.com/npm/cli/compare/libnpmhook-v9.0.0-pre.0...libnpmhook-v9.0.0-pre.1) (2022-10-19) - -### Dependencies - -* [`aa01072`](https://github.com/npm/cli/commit/aa010722996ef6de46e1bb937c6f8a94dc2844fa) [#5707](https://github.com/npm/cli/pull/5707) update the following dependencies - -## [9.0.0-pre.0](https://github.com/npm/cli/compare/libnpmhook-v8.0.4...libnpmhook-v9.0.0-pre.0) (2022-09-08) - -### ⚠ BREAKING CHANGES - -* **workspaces:** all workspace packages are now compatible with the following semver range for node: `^14.17.0 || ^16.13.0 || >=18.0.0` - -### Features - - * [`e95017a`](https://github.com/npm/cli/commit/e95017a07b041cbb3293e659dad853f76462c108) [#5485](https://github.com/npm/cli/pull/5485) feat(workspaces): update supported node engines in package.json (@lukekarrys) - -## [8.0.4](https://github.com/npm/cli/compare/libnpmhook-v8.0.3...libnpmhook-v8.0.4) (2022-08-31) - -### Dependencies - - * [`8ab12dc`](https://github.com/npm/cli/commit/8ab12dc32b26db770b868cf694cedab38f4e7460) [#5323](https://github.com/npm/cli/pull/5323) deps: `@npmcli/eslint-config@3.1.0` - -### [8.0.3](https://github.com/npm/cli/compare/libnpmhook-v8.0.2...libnpmhook-v8.0.3) (2022-04-06) - - -### Bug Fixes - -* replace deprecated String.prototype.substr() ([#4667](https://github.com/npm/cli/issues/4667)) ([e3da5df](https://github.com/npm/cli/commit/e3da5df4152fbe547f7871547165328e1bf06262)) -* update readme badges ([#4658](https://github.com/npm/cli/issues/4658)) ([2829cb2](https://github.com/npm/cli/commit/2829cb28a432b5ff7beeeb3bf3e7e2e174c1121d)) - - -### Dependencies - -* @npmcli/template-oss@3.2.1 ([aac01b8](https://github.com/npm/cli/commit/aac01b89caf6336a2eb34d696296303cdadd5c08)) -* @npmcli/template-oss@3.2.2 ([#4639](https://github.com/npm/cli/issues/4639)) ([a59fd2c](https://github.com/npm/cli/commit/a59fd2cb863245fce56f96c90ac854e62c5c4d6f)) - -### [8.0.2](https://www.github.com/npm/cli/compare/libnpmhook-v8.0.1...libnpmhook-v8.0.2) (2022-03-10) - - -### Documentation - -* standardize changelog heading ([#4510](https://www.github.com/npm/cli/issues/4510)) ([91f03ee](https://www.github.com/npm/cli/commit/91f03ee618bc635f9cfbded735fe98bbfa9d643f)) - -## [6.0.0](https://github.com/npm/libnpmhook/compare/v5.0.2...v6.0.0) (2020-02-26) - -### Breaking Changes - -* [`aa629b4`](https://github.com/npm/libnpmhook/commit/aa629b4) fix: remove figgy-pudding ([@claudiahdz](https://github.com/claudiahdz)) - -### Miscellaneuous - -* [`ea795fb`](https://github.com/npm/libnpmhook/commit/ea795fb) chore: basic project updates ([@claudiahdz](https://github.com/claudiahdz)) -* [`a0fdf7e`](https://github.com/npm/libnpmhook/commit/a0fdf7e) chore: cleanup badges, contrib, readme ([@ruyadorno](https://github.com/ruyadorno)) - ---- - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - - -### [8.0.1](https://www.github.com/npm/cli/compare/libnpmhook-vlibnpmhook@8.0.0...libnpmhook-v8.0.1) (2022-03-03) - - -### Bug Fixes - -* set proper workspace repo urls in package.json ([#4476](https://www.github.com/npm/cli/issues/4476)) ([0cfc155](https://www.github.com/npm/cli/commit/0cfc155db5f11ce23419e440111d99a63bf39754)) - -## [5.0.2](https://github.com/npm/libnpmhook/compare/v5.0.1...v5.0.2) (2018-08-24) - - - - -## [5.0.1](https://github.com/npm/libnpmhook/compare/v5.0.0...v5.0.1) (2018-08-23) - - -### Bug Fixes - -* **deps:** move JSONStream to prod deps ([bb63594](https://github.com/npm/libnpmhook/commit/bb63594)) - - - - -# [5.0.0](https://github.com/npm/libnpmhook/compare/v4.0.1...v5.0.0) (2018-08-21) - - -### Features - -* **api:** overhauled API ([46b271b](https://github.com/npm/libnpmhook/commit/46b271b)) - - -### BREAKING CHANGES - -* **api:** the API for ls() has changed, and rm() no longer errors on 404 - - - - -## [4.0.1](https://github.com/npm/libnpmhook/compare/v4.0.0...v4.0.1) (2018-04-09) - - - - -# [4.0.0](https://github.com/npm/libnpmhook/compare/v3.0.1...v4.0.0) (2018-04-08) - - -### meta - -* drop support for node 4 and 7 ([f2a301e](https://github.com/npm/libnpmhook/commit/f2a301e)) - - -### BREAKING CHANGES - -* node@4 and node@7 are no longer supported - - - - -## [3.0.1](https://github.com/npm/libnpmhook/compare/v3.0.0...v3.0.1) (2018-04-08) - - - - -# [3.0.0](https://github.com/npm/libnpmhook/compare/v2.0.1...v3.0.0) (2018-04-04) - - -### add - -* guess type based on name ([9418224](https://github.com/npm/libnpmhook/commit/9418224)) - - -### BREAKING CHANGES - -* hook type is now based on name prefix - - - - -## [2.0.1](https://github.com/npm/libnpmhook/compare/v2.0.0...v2.0.1) (2018-03-16) - - -### Bug Fixes - -* **urls:** was hitting the wrong URL endpoints ([10171a9](https://github.com/npm/libnpmhook/commit/10171a9)) - - - - -# [2.0.0](https://github.com/npm/libnpmhook/compare/v1.0.0...v2.0.0) (2018-03-16) - - - - -# 1.0.0 (2018-03-16) - - -### Features - -* **api:** baseline working api ([122658e](https://github.com/npm/npm-hooks/commit/122658e)) diff --git a/workspaces/libnpmhook/LICENSE.md b/workspaces/libnpmhook/LICENSE.md deleted file mode 100644 index 8d28acf866d93..0000000000000 --- a/workspaces/libnpmhook/LICENSE.md +++ /dev/null @@ -1,16 +0,0 @@ -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. diff --git a/workspaces/libnpmhook/README.md b/workspaces/libnpmhook/README.md deleted file mode 100644 index 309f8041da08b..0000000000000 --- a/workspaces/libnpmhook/README.md +++ /dev/null @@ -1,271 +0,0 @@ -# libnpmhook - -[![npm version](https://img.shields.io/npm/v/libnpmhook.svg)](https://npm.im/libnpmhook) -[![license](https://img.shields.io/npm/l/libnpmhook.svg)](https://npm.im/libnpmhook) -[![CI - libnpmhook](https://github.com/npm/cli/actions/workflows/ci-libnpmhook.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmhook.yml) - -[`libnpmhook`](https://github.com/npm/libnpmhook) is a Node.js library for -programmatically managing the npm registry's server-side hooks. - -For a more general introduction to managing hooks, see [the introductory blog -post](https://blog.npmjs.org/post/145260155635/introducing-hooks-get-notifications-of-npm). - -## Table of Contents - -* [Example](#example) -* [Install](#install) -* [Contributing](#contributing) -* [API](#api) - * [hook opts](#opts) - * [`add()`](#add) - * [`rm()`](#rm) - * [`ls()`](#ls) - * [`ls.stream()`](#ls-stream) - * [`update()`](#update) - -## Example - -```js -const hooks = require('libnpmhook') - -console.log(await hooks.ls('mypkg', {token: 'deadbeef'})) -// array of hook objects on `mypkg`. -``` - -## Install - -`$ npm install libnpmhook` - -### API - -#### `opts` for `libnpmhook` commands - -`libnpmhook` 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 `libnpmhook` command fails with `err.code === EOTP`, please retry the request with `{otp: <2fa token>}` - -#### `> hooks.add(name, endpoint, secret, [opts]) -> Promise` - -`name` is the name of the package, org, or user/org scope to watch. The type is -determined by the name syntax: `'@foo/bar'` and `'foo'` are treated as packages, -`@foo` is treated as a scope, and `~user` is treated as an org name or scope. -Each type will attach to different events. - -The `endpoint` should be a fully-qualified http URL for the endpoint the hook -will send its payload to when it fires. `secret` is a shared secret that the -hook will send to that endpoint to verify that it's actually coming from the -registry hook. - -The returned Promise resolves to the full hook object that was created, -including its generated `id`. - -See also: [`POST -/v1/hooks/hook`](https://github.com/npm/registry/blob/master/docs/hooks/endpoints.md#post-v1hookshook) - -##### Example - -```javascript -await hooks.add('~zkat', 'https://example.com/api/added', 'supersekrit', { - token: 'myregistrytoken', - otp: '694207' -}) - -=> - -{ id: '16f7xoal', - username: 'zkat', - name: 'zkat', - endpoint: 'https://example.com/api/added', - secret: 'supersekrit', - type: 'owner', - created: '2018-08-21T20:05:25.125Z', - updated: '2018-08-21T20:05:25.125Z', - deleted: false, - delivered: false, - last_delivery: null, - response_code: 0, - status: 'active' } -``` - -#### `> hooks.find(id, [opts]) -> Promise` - -Returns the hook identified by `id`. - -The returned Promise resolves to the full hook object that was found, or error -with `err.code` of `'E404'` if it didn't exist. - -See also: [`GET -/v1/hooks/hook/:id`](https://github.com/npm/registry/blob/master/docs/hooks/endpoints.md#get-v1hookshookid) - -##### Example - -```javascript -await hooks.find('16f7xoal', {token: 'myregistrytoken'}) - -=> - -{ id: '16f7xoal', - username: 'zkat', - name: 'zkat', - endpoint: 'https://example.com/api/added', - secret: 'supersekrit', - type: 'owner', - created: '2018-08-21T20:05:25.125Z', - updated: '2018-08-21T20:05:25.125Z', - deleted: false, - delivered: false, - last_delivery: null, - response_code: 0, - status: 'active' } -``` - -#### `> hooks.rm(id, [opts]) -> Promise` - -Removes the hook identified by `id`. - -The returned Promise resolves to the full hook object that was removed, if it -existed, or `null` if no such hook was there (instead of erroring). - -See also: [`DELETE -/v1/hooks/hook/:id`](https://github.com/npm/registry/blob/master/docs/hooks/endpoints.md#delete-v1hookshookid) - -##### Example - -```javascript -await hooks.rm('16f7xoal', { - token: 'myregistrytoken', - otp: '694207' -}) - -=> - -{ id: '16f7xoal', - username: 'zkat', - name: 'zkat', - endpoint: 'https://example.com/api/added', - secret: 'supersekrit', - type: 'owner', - created: '2018-08-21T20:05:25.125Z', - updated: '2018-08-21T20:05:25.125Z', - deleted: true, - delivered: false, - last_delivery: null, - response_code: 0, - status: 'active' } - -// Repeat it... -await hooks.rm('16f7xoal', { - token: 'myregistrytoken', - otp: '694207' -}) - -=> null -``` - -#### `> hooks.update(id, endpoint, secret, [opts]) -> Promise` - -The `id` should be a hook ID from a previously-created hook. - -The `endpoint` should be a fully-qualified http URL for the endpoint the hook -will send its payload to when it fires. `secret` is a shared secret that the -hook will send to that endpoint to verify that it's actually coming from the -registry hook. - -The returned Promise resolves to the full hook object that was updated, if it -existed. Otherwise, it will error with an `'E404'` error code. - -See also: [`PUT -/v1/hooks/hook/:id`](https://github.com/npm/registry/blob/master/docs/hooks/endpoints.md#put-v1hookshookid) - -##### Example - -```javascript -await hooks.update('16fxoal', 'https://example.com/api/other', 'newsekrit', { - token: 'myregistrytoken', - otp: '694207' -}) - -=> - -{ id: '16f7xoal', - username: 'zkat', - name: 'zkat', - endpoint: 'https://example.com/api/other', - secret: 'newsekrit', - type: 'owner', - created: '2018-08-21T20:05:25.125Z', - updated: '2018-08-21T20:14:41.964Z', - deleted: false, - delivered: false, - last_delivery: null, - response_code: 0, - status: 'active' } -``` - -#### `> hooks.ls([opts]) -> Promise` - -Resolves to an array of hook objects associated with the account you're -authenticated as. - -Results can be further filtered with three values that can be passed in through -`opts`: - -* `opts.package` - filter results by package name -* `opts.limit` - maximum number of hooks to return -* `opts.offset` - pagination offset for results (use with `opts.limit`) - -See also: - * [`hooks.ls.stream()`](#ls-stream) - * [`GET -/v1/hooks`](https://github.com/npm/registry/blob/master/docs/hooks/endpoints.md#get-v1hooks) - -##### Example - -```javascript -await hooks.ls({token: 'myregistrytoken'}) - -=> -[ - { id: '16f7xoal', ... }, - { id: 'wnyf98a1', ... }, - ... -] -``` - -#### `> hooks.ls.stream([opts]) -> Stream` - -Returns a stream of hook objects associated with the account you're -authenticated as. The returned stream is a valid `Symbol.asyncIterator` on -`node@>=10`. - -Results can be further filtered with three values that can be passed in through -`opts`: - -* `opts.package` - filter results by package name -* `opts.limit` - maximum number of hooks to return -* `opts.offset` - pagination offset for results (use with `opts.limit`) - -See also: - * [`hooks.ls()`](#ls) - * [`GET -/v1/hooks`](https://github.com/npm/registry/blob/master/docs/hooks/endpoints.md#get-v1hooks) - -##### Example - -```javascript -for await (let hook of hooks.ls.stream({token: 'myregistrytoken'})) { - console.log('found hook:', hook.id) -} - -=> -// outputs: -// found hook: 16f7xoal -// found hook: wnyf98a1 -``` diff --git a/workspaces/libnpmhook/lib/index.js b/workspaces/libnpmhook/lib/index.js deleted file mode 100644 index 091cdc49a80d1..0000000000000 --- a/workspaces/libnpmhook/lib/index.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict' - -const fetch = require('npm-registry-fetch') -const validate = require('aproba') - -const eu = encodeURIComponent -const cmd = module.exports = {} -cmd.add = (name, endpoint, secret, opts = {}) => { - validate('SSSO', [name, endpoint, secret, opts]) - let type = 'package' - if (name.match(/^@[^/]+$/)) { - type = 'scope' - } - if (name[0] === '~') { - type = 'owner' - name = name.slice(1) - } - return fetch.json('/-/npm/v1/hooks/hook', { - ...opts, - method: 'POST', - body: { type, name, endpoint, secret }, - }) -} - -cmd.rm = (id, opts = {}) => { - validate('SO', [id, opts]) - return fetch.json(`/-/npm/v1/hooks/hook/${eu(id)}`, { - ...opts, - method: 'DELETE', - }).catch(err => { - if (err.code === 'E404') { - return null - } else { - throw err - } - }) -} - -cmd.update = (id, endpoint, secret, opts = {}) => { - validate('SSSO', [id, endpoint, secret, opts]) - return fetch.json(`/-/npm/v1/hooks/hook/${eu(id)}`, { - ...opts, - method: 'PUT', - body: { endpoint, secret }, - }) -} - -cmd.find = (id, opts = {}) => { - validate('SO', [id, opts]) - return fetch.json(`/-/npm/v1/hooks/hook/${eu(id)}`, opts) -} - -cmd.ls = (opts = {}) => { - return cmd.ls.stream(opts).collect() -} - -cmd.ls.stream = (opts = {}) => { - const { package: pkg, limit, offset } = opts - validate('S|Z', [pkg]) - validate('N|Z', [limit]) - validate('N|Z', [offset]) - return fetch.json.stream('/-/npm/v1/hooks', 'objects.*', { - ...opts, - query: { - package: pkg, - limit, - offset, - }, - }) -} diff --git a/workspaces/libnpmhook/package.json b/workspaces/libnpmhook/package.json deleted file mode 100644 index 098762c037dfd..0000000000000 --- a/workspaces/libnpmhook/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "libnpmhook", - "version": "10.0.5", - "description": "programmatic API for managing npm registry hooks", - "main": "lib/index.js", - "files": [ - "bin/", - "lib/" - ], - "scripts": { - "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/cli.git", - "directory": "workspaces/libnpmhook" - }, - "keywords": [ - "npm", - "hooks", - "registry", - "npm api" - ], - "author": "GitHub Inc.", - "license": "ISC", - "dependencies": { - "aproba": "^2.0.0", - "npm-registry-fetch": "^17.0.1" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "nock": "^13.3.3", - "tap": "^16.3.8" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "content": "../../scripts/template-oss/index.js" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/workspaces/libnpmhook/test/fixtures/tnock.js b/workspaces/libnpmhook/test/fixtures/tnock.js deleted file mode 100644 index 048639a504e08..0000000000000 --- a/workspaces/libnpmhook/test/fixtures/tnock.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -const nock = require('nock') - -module.exports = tnock -function tnock (t, host) { - const server = nock(host) - t.teardown(function () { - server.done() - }) - return server -} diff --git a/workspaces/libnpmhook/test/index.js b/workspaces/libnpmhook/test/index.js deleted file mode 100644 index 7ca3b06ae805d..0000000000000 --- a/workspaces/libnpmhook/test/index.js +++ /dev/null @@ -1,267 +0,0 @@ -'use strict' - -const test = require('tap').test -const tnock = require('./fixtures/tnock.js') - -const hooks = require('../lib/index.js') - -const OPTS = { - registry: 'https://mock.reg/', -} - -const HOOK_URL = 'https://my.hook.url/' -const REG = 'https://registry.npmjs.org/' - -test('add package hook with no options', t => { - const params = { - type: 'package', - name: 'mypkg', - endpoint: HOOK_URL, - secret: 'sekrit', - } - const hook = Object.assign({ - id: 'deadbeef', - status: 'active', - }, params) - tnock(t, REG) - .post('/-/npm/v1/hooks/hook', params) - .reply(200, hook) - return hooks.add('mypkg', HOOK_URL, 'sekrit') - .then(json => t.same(json, hook)) -}) - -test('add package hook', t => { - const params = { - type: 'package', - name: 'mypkg', - endpoint: HOOK_URL, - secret: 'sekrit', - } - const hook = Object.assign({ - id: 'deadbeef', - status: 'active', - }, params) - tnock(t, OPTS.registry) - .post('/-/npm/v1/hooks/hook', params) - .reply(200, hook) - return hooks.add('mypkg', HOOK_URL, 'sekrit', OPTS) - .then(json => t.same(json, hook)) -}) - -test('add scoped package hook', t => { - const params = { - type: 'package', - name: '@myscope/mypkg', - endpoint: HOOK_URL, - secret: 'sekrit', - } - const hook = Object.assign({ - id: 'deadbeef', - status: 'active', - }, params) - tnock(t, OPTS.registry) - .post('/-/npm/v1/hooks/hook', params) - .reply(200, hook) - return hooks.add('@myscope/mypkg', HOOK_URL, 'sekrit', OPTS) - .then(json => t.same(json, hook)) -}) - -test('add owner hook', t => { - const params = { - type: 'owner', - name: 'myuser', - endpoint: HOOK_URL, - secret: 'sekrit', - } - const hook = Object.assign({ - id: 'deadbeef', - status: 'active', - }, params) - tnock(t, OPTS.registry) - .post('/-/npm/v1/hooks/hook', params) - .reply(200, hook) - return hooks.add('~myuser', HOOK_URL, 'sekrit', OPTS) - .then(json => t.same(json, hook)) -}) - -test('add scope hook', t => { - const params = { - type: 'scope', - name: '@myscope', - endpoint: HOOK_URL, - secret: 'sekrit', - } - const hook = Object.assign({ - id: 'deadbeef', - status: 'active', - }, params) - tnock(t, OPTS.registry) - .post('/-/npm/v1/hooks/hook', params) - .reply(200, hook) - return hooks.add('@myscope', HOOK_URL, 'sekrit', OPTS) - .then(json => t.same(json, hook)) -}) - -test('rm with no options', t => { - tnock(t, REG) - .delete('/-/npm/v1/hooks/hook/hithere') - .reply(200, { id: 'hithere' }) - return hooks.rm('hithere') - .then(json => t.equal(json.id, 'hithere')) -}) - -test('rm', t => { - tnock(t, OPTS.registry) - .delete('/-/npm/v1/hooks/hook/hithere') - .reply(200, { id: 'hithere' }) - return hooks.rm('hithere', OPTS) - .then(json => t.equal(json.id, 'hithere')) -}) - -test('rm null on 404', t => { - tnock(t, OPTS.registry) - .delete('/-/npm/v1/hooks/hook/hithere') - .reply(404) - return hooks.rm('hithere', OPTS) - .then(json => t.equal(json, null)) -}) - -test('rm null on other err', t => { - tnock(t, OPTS.registry) - .delete('/-/npm/v1/hooks/hook/hithere') - .reply(401) - return hooks.rm('hithere', OPTS).then( - () => { - throw new Error('should not succees') - }, - err => t.equal(err.code, 'E401', 'got a proper error + code') - ) -}) - -test('find with no options', t => { - tnock(t, REG) - .get('/-/npm/v1/hooks/hook/hithere') - .reply(200, { id: 'hithere' }) - return hooks.find('hithere') - .then(json => t.equal(json.id, 'hithere')) -}) - -test('find', t => { - tnock(t, OPTS.registry) - .get('/-/npm/v1/hooks/hook/hithere') - .reply(200, { id: 'hithere' }) - return hooks.find('hithere', OPTS) - .then(json => t.equal(json.id, 'hithere')) -}) - -test('ls', t => { - const entries = [ - { id: 'first' }, - { id: 'second' }, - { id: 'third' }, - ] - tnock(t, REG) - .get('/-/npm/v1/hooks') - .reply(200, { objects: entries }) - return hooks.ls().then( - json => t.same(json, entries) - ) -}) - -test('ls.stream', t => { - const entries = [ - { id: 'first' }, - { id: 'second' }, - { id: 'third' }, - ] - tnock(t, REG) - .get('/-/npm/v1/hooks') - .reply(200, { objects: entries }) - - return hooks.ls.stream().collect().then( - json => t.same(json, entries) - ) -}) - -test('ls', t => { - const entries = [ - { id: 'first' }, - { id: 'second' }, - { id: 'third' }, - ] - tnock(t, OPTS.registry) - .get('/-/npm/v1/hooks') - .reply(200, { objects: entries }) - return hooks.ls(OPTS).then( - json => t.same(json, entries) - ) -}) - -test('ls package', t => { - const entries = [ - { id: 'first' }, - { id: 'second' }, - { id: 'third' }, - ] - tnock(t, OPTS.registry) - .get('/-/npm/v1/hooks?package=%40npm%2Fhooks') - .reply(200, { objects: entries }) - return hooks.ls({ - ...OPTS, - package: '@npm/hooks', - }).then(json => t.same(json, entries)) -}) - -test('ls limit+offset', t => { - const entries = [ - { id: 'first' }, - { id: 'second' }, - { id: 'third' }, - ] - tnock(t, OPTS.registry) - .get('/-/npm/v1/hooks?limit=10&offset=20') - .reply(200, { objects: entries }) - return hooks.ls({ - ...OPTS, - limit: 10, - offset: 20, - }).then(json => t.same(json, entries)) -}) - -test('ls package+limit+offset', t => { - const entries = [ - { id: 'first' }, - { id: 'second' }, - { id: 'third' }, - ] - tnock(t, OPTS.registry) - .get('/-/npm/v1/hooks?package=%40npm%2Fhooks&limit=10&offset=20') - .reply(200, { objects: entries }) - return hooks.ls({ - ...OPTS, - limit: 10, - offset: 20, - package: '@npm/hooks', - }).then(json => t.same(json, entries)) -}) -test('update with no options', t => { - tnock(t, REG) - .put('/-/npm/v1/hooks/hook/hi') - .reply(200, (uri, body) => body) - return hooks.update('hi', HOOK_URL, 'sekrit') - .then(json => t.same(json, { - endpoint: HOOK_URL, - secret: 'sekrit', - })) -}) - -test('update', t => { - tnock(t, OPTS.registry) - .put('/-/npm/v1/hooks/hook/hi') - .reply(200, (uri, body) => body) - return hooks.update('hi', HOOK_URL, 'sekrit', OPTS) - .then(json => t.same(json, { - endpoint: HOOK_URL, - secret: 'sekrit', - })) -}) diff --git a/workspaces/libnpmorg/.gitignore b/workspaces/libnpmorg/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/workspaces/libnpmorg/.gitignore +++ b/workspaces/libnpmorg/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/workspaces/libnpmorg/CHANGELOG.md b/workspaces/libnpmorg/CHANGELOG.md index d224546afd217..49e88c59cfdc4 100644 --- a/workspaces/libnpmorg/CHANGELOG.md +++ b/workspaces/libnpmorg/CHANGELOG.md @@ -1,5 +1,59 @@ # Changelog +## [9.0.0-pre.0](https://github.com/npm/cli/compare/libnpmorg-v8.0.1...libnpmorg-v9.0.0-pre.0) (2026-06-19) +### ⚠️ BREAKING CHANGES +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +### Features +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +### Dependencies +* [`1f9c567`](https://github.com/npm/cli/commit/1f9c56792493f80fb3b3d61710086ed748312f2a) [#9559](https://github.com/npm/cli/pull/9559) `npm-registry-fetch@20.0.1` +### Chores +* [`1453954`](https://github.com/npm/cli/commit/1453954f9328a6b2480c183f9d1903ac93764915) [#9559](https://github.com/npm/cli/pull/9559) `nock@14.0.0` (@owlstronaut) +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`40fcab4`](https://github.com/npm/cli/commit/40fcab45d356545f8db7f34df3e5630116d0dd40) [#8991](https://github.com/npm/cli/pull/8991) `@npmcli/template-oss@4.29.0` (@wraithgar) +* [`5e0909b`](https://github.com/npm/cli/commit/5e0909b74ea1510eaae348d66548c75030911ed8) [#8620](https://github.com/npm/cli/pull/8620) fix spelling in workspaces (#8620) (@jsoref) + +## [8.0.1](https://github.com/npm/cli/compare/libnpmorg-v8.0.0...libnpmorg-v8.0.1) (2025-09-23) +### Dependencies +* [`1149971`](https://github.com/npm/cli/commit/11499711e4c10e4ddb97bf3e1ef1652d151894fb) [#8576](https://github.com/npm/cli/pull/8576) `npm-registry-fetch@19.0.0` +### Chores +* [`402a0ab`](https://github.com/npm/cli/commit/402a0ab1b4e5d1a8414dd063d0cbde0c0bc5a192) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/template-oss@4.25.1` (@wraithgar) +* [`3f60b5f`](https://github.com/npm/cli/commit/3f60b5f9621b43ae0b8796d3a7160a603748f756) [#8383](https://github.com/npm/cli/pull/8383) `@npmcli/template-oss@4.24.4` (#8383) (@wraithgar) +* [`01f8cc6`](https://github.com/npm/cli/commit/01f8cc6f001e3211135fa0563f7129aed09dc46c) [#8381](https://github.com/npm/cli/pull/8381) `@npmcli/template-oss@4.24.3` (#8381) (@wraithgar) + +## [8.0.0](https://github.com/npm/cli/compare/libnpmorg-v8.0.0-pre.1...libnpmorg-v8.0.0) (2024-12-16) +### Features +* [`a7bfc6d`](https://github.com/npm/cli/commit/a7bfc6df76882996ebb834dbca785fdf33b8c50d) [#7972](https://github.com/npm/cli/pull/7972) trigger release process (#7972) (@wraithgar) +### Chores +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) + +## [8.0.0-pre.1](https://github.com/npm/cli/compare/libnpmorg-v8.0.0-pre.0...libnpmorg-v8.0.0-pre.1) (2024-12-06) +### ⚠️ BREAKING CHANGES +* Upon publishing, in order to apply a default "latest" dist tag, the command now retrieves all prior versions of the package. It will require that the version you're trying to publish is above the latest semver version in the registry, not including pre-release tags. +### Features +* [`f3ac7b7`](https://github.com/npm/cli/commit/f3ac7b7460e1d9e1f9d3d8056317e36bb9813d5d) [#7939](https://github.com/npm/cli/pull/7939) no implicit latest tag on publish when latest > version (#7939) (@reggi, @ljharb) + +## [8.0.0-pre.0](https://github.com/npm/cli/compare/libnpmorg-v7.0.0...libnpmorg-v8.0.0-pre.0) (2024-11-26) +### ⚠️ BREAKING CHANGES +* libnpmorg now supports node `^20.17.0 || >=22.9.0` +### Bug Fixes +* [`62c4604`](https://github.com/npm/cli/commit/62c4604c9c1fcdb511f922d40edb1aecb6f9943d) [#7831](https://github.com/npm/cli/pull/7831) for libnpmorg sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +### Chores +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) + +## [7.0.0](https://github.com/npm/cli/compare/libnpmorg-v6.0.6...libnpmorg-v7.0.0) (2024-10-03) +### ⚠️ BREAKING CHANGES +* `libnpmorg` now supports node `^18.17.0 || >=20.5.0` +### Bug Fixes +* [`47f6f76`](https://github.com/npm/cli/commit/47f6f764235fd9a268afc504b03038b22e97537d) [#7803](https://github.com/npm/cli/pull/7803) align libnpmorg to npm 10 node engine range (@reggi) +### Dependencies +* [`d13a20b`](https://github.com/npm/cli/commit/d13a20bebef1b9932f86c44741ea6d214ad6842b) [#7803](https://github.com/npm/cli/pull/7803) update `npm-registry-fetch@18.0.1` +### Chores +* [`2072705`](https://github.com/npm/cli/commit/2072705aa80d009dc077639adc305692f4a6c0b9) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/eslint-config@5.0.1` (@reggi) +* [`8035725`](https://github.com/npm/cli/commit/80357253ecd8483463cd66c783c4464c330d72df) [#7756](https://github.com/npm/cli/pull/7756) `@npmcli/template-oss@4.23.3` (@wraithgar) + ## [6.0.6](https://github.com/npm/cli/compare/libnpmorg-v6.0.5...libnpmorg-v6.0.6) (2024-05-15) ### Dependencies @@ -158,7 +212,7 @@ ## 2.0.0 (2020-03-02) ### BREAKING CHANGE -- Removed `figgy-pudding` as a dependecy +- Removed `figgy-pudding` as a dependency - Using native promises - Require node >= v10 diff --git a/workspaces/libnpmorg/lib/index.js b/workspaces/libnpmorg/lib/index.js index 4684b516d2b4a..f3d361b8be6d7 100644 --- a/workspaces/libnpmorg/lib/index.js +++ b/workspaces/libnpmorg/lib/index.js @@ -1,7 +1,7 @@ 'use strict' const eu = encodeURIComponent -const fetch = require('npm-registry-fetch') +const npmFetch = require('npm-registry-fetch') const validate = require('aproba') // From https://github.com/npm/registry/blob/master/docs/orgs/memberships.md @@ -19,7 +19,7 @@ cmd.set = (org, user, role, opts = {}) => { validate('SSSO|SSZO', [org, user, role, opts]) user = user.replace(/^@?/, '') org = org.replace(/^@?/, '') - return fetch.json(`/-/org/${eu(org)}/user`, { + return npmFetch.json(`/-/org/${eu(org)}/user`, { ...opts, method: 'PUT', body: { user, role }, @@ -30,7 +30,7 @@ cmd.rm = (org, user, opts = {}) => { validate('SSO', [org, user, opts]) user = user.replace(/^@?/, '') org = org.replace(/^@?/, '') - return fetch(`/-/org/${eu(org)}/user`, { + return npmFetch(`/-/org/${eu(org)}/user`, { ...opts, method: 'DELETE', body: { user }, @@ -55,7 +55,7 @@ cmd.ls = (org, opts = {}) => { cmd.ls.stream = (org, opts = {}) => { validate('SO', [org, opts]) org = org.replace(/^@?/, '') - return fetch.json.stream(`/-/org/${eu(org)}/user`, '*', { + return npmFetch.json.stream(`/-/org/${eu(org)}/user`, '*', { ...opts, mapJSON: (value, [key]) => { return [key, value] diff --git a/workspaces/libnpmorg/package.json b/workspaces/libnpmorg/package.json index aa3440de58369..5b81b78086261 100644 --- a/workspaces/libnpmorg/package.json +++ b/workspaces/libnpmorg/package.json @@ -1,6 +1,6 @@ { "name": "libnpmorg", - "version": "6.0.6", + "version": "9.0.0-pre.0", "description": "Programmatic api for `npm org` commands", "author": "GitHub Inc.", "main": "lib/index.js", @@ -14,23 +14,24 @@ ], "license": "ISC", "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "test": "tap", "posttest": "npm run lint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "files": [ "bin/", "lib/" ], "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "minipass": "^7.1.1", - "nock": "^13.3.3", + "nock": "^14.0.0", "tap": "^16.3.8" }, "repository": { @@ -42,17 +43,21 @@ "homepage": "https://npmjs.com/package/libnpmorg", "dependencies": { "aproba": "^2.0.0", - "npm-registry-fetch": "^17.0.1" + "npm-registry-fetch": "^20.0.1" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../../scripts/template-oss/index.js" }, "tap": { + "node-arg": [ + "--require", + "../../scripts/disable-agent-for-tests.js" + ], "nyc-arg": [ "--exclude", "tap-snapshots/**" diff --git a/workspaces/libnpmpack/.gitignore b/workspaces/libnpmpack/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/workspaces/libnpmpack/.gitignore +++ b/workspaces/libnpmpack/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/workspaces/libnpmpack/CHANGELOG.md b/workspaces/libnpmpack/CHANGELOG.md index 9537a5224fc47..7d7a2a1e2cf92 100644 --- a/workspaces/libnpmpack/CHANGELOG.md +++ b/workspaces/libnpmpack/CHANGELOG.md @@ -4,6 +4,168 @@ * [workspace](https://github.com/npm/cli/releases/tag/arborist-v7.5.4): `@npmcli/arborist@7.5.4` +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.1): `@npmcli/arborist@9.0.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.2): `@npmcli/arborist@9.0.2` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.0): `@npmcli/arborist@9.1.0` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.1): `@npmcli/arborist@9.1.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.2): `@npmcli/arborist@9.1.2` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.3): `@npmcli/arborist@9.1.3` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.4): `@npmcli/arborist@9.1.4` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.6): `@npmcli/arborist@9.1.6` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.7): `@npmcli/arborist@9.1.7` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.8): `@npmcli/arborist@9.1.8` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.9): `@npmcli/arborist@9.1.9` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.10): `@npmcli/arborist@9.1.10` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.3.0): `@npmcli/arborist@9.3.0` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.3.1): `@npmcli/arborist@9.3.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.0): `@npmcli/arborist@9.4.0` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.1): `@npmcli/arborist@9.4.1` + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.4.2): `@npmcli/arborist@9.4.2` + +## [10.0.0-pre.1](https://github.com/npm/cli/compare/libnpmpack-v10.0.0-pre.0...libnpmpack-v10.0.0-pre.1) (2026-06-19) +### ⚠️ BREAKING CHANGES +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +* allow-git and allow-remote now default to "none"; set them to "all" (or "root") to install git or user-supplied tarball-URL dependencies. +### Features +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +* [`caa3295`](https://github.com/npm/cli/commit/caa329568d32587e53f6e098f43b550dd2685034) [#9466](https://github.com/npm/cli/pull/9466) default allow-git and allow-remote to none (@owlstronaut) +### Bug Fixes +* [`76f8059`](https://github.com/npm/cli/commit/76f8059cd0d2482ef6c472b6c7058c51a1946d22) [#9446](https://github.com/npm/cli/pull/9446) flatten path separators in pack output filename (#9446) (@rootvector2) +* [`c5292fa`](https://github.com/npm/cli/commit/c5292fa8a09a56b25394d393faf21e47ffb096c0) [#9422](https://github.com/npm/cli/pull/9422) use prerelease strategy without a bug (@owlstronaut) +### Dependencies +* [`a44c1cf`](https://github.com/npm/cli/commit/a44c1cf1635de5ecda02ed80af70f5d7360111b6) [#9559](https://github.com/npm/cli/pull/9559) `pacote@22.0.0` +* [`d80859a`](https://github.com/npm/cli/commit/d80859a2dd97376e4ea621812b3bc7de6a218d21) [#9559](https://github.com/npm/cli/pull/9559) `npm-package-arg@14.0.0` +* [`9d13ebf`](https://github.com/npm/cli/commit/9d13ebfc2adca5543e4797632039adaa7a318985) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/run-script@11.0.0` +### Chores +* [`1453954`](https://github.com/npm/cli/commit/1453954f9328a6b2480c183f9d1903ac93764915) [#9559](https://github.com/npm/cli/pull/9559) `nock@14.0.0` (@owlstronaut) +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v10.0.0-pre.1): `@npmcli/arborist@10.0.0-pre.1` + +## [10.0.0-pre.0.0](https://github.com/npm/cli/compare/libnpmpack-v9.1.5...libnpmpack-v10.0.0-pre.0.0) (2026-05-20) +### ⚠️ BREAKING CHANGES +* npm pack and npm publish now error when a package's overrides apply to one or more of its bundled packages (bundledDependencies / bundleDependencies). Defining both fields is still allowed as long as no override actually targets a bundled package. To resolve the error, remove the affected entries from either overrides or the bundle. +### Bug Fixes +* [`b1965d6`](https://github.com/npm/cli/commit/b1965d6af116dff6edcec7f70524b483d554ec4f) [#9271](https://github.com/npm/cli/pull/9271) refuse to pack when overrides apply to bundled packages (@owlstronaut) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v10.0.0-pre.0.0): `@npmcli/arborist@10.0.0-pre.0.0` + +## [9.1.0](https://github.com/npm/cli/compare/libnpmpack-v9.0.13...libnpmpack-v9.1.0) (2026-02-04) +### Features +* [`f5f6cf7`](https://github.com/npm/cli/commit/f5f6cf7c9fc9315b96eb29c5c7d5ab63ad3a9122) [#8943](https://github.com/npm/cli/pull/8943) config: add --allow-git (@wraithgar) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.2.0): `@npmcli/arborist@9.2.0` + +## [9.0.8](https://github.com/npm/cli/compare/libnpmpack-v9.0.7...libnpmpack-v9.0.8) (2025-09-23) +### Dependencies +* [`bf6b686`](https://github.com/npm/cli/commit/bf6b6862731e03002cc6fa3b86b6f090df46b009) [#8576](https://github.com/npm/cli/pull/8576) `npm-package-arg@13.0.0` +* [`6b4c5f9`](https://github.com/npm/cli/commit/6b4c5f92865230ed9a260cd3e8486bf3991120eb) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/run-script@10.0.0` +* [`b6bb9ae`](https://github.com/npm/cli/commit/b6bb9aea4134c47f0593c111a734eda12ec3c20d) [#8576](https://github.com/npm/cli/pull/8576) `pacote@21.0.3` +### Chores +* [`402a0ab`](https://github.com/npm/cli/commit/402a0ab1b4e5d1a8414dd063d0cbde0c0bc5a192) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/template-oss@4.25.1` (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.1.5): `@npmcli/arborist@9.1.5` + +## [9.0.0](https://github.com/npm/cli/compare/libnpmpack-v9.0.0-pre.1...libnpmpack-v9.0.0) (2024-12-16) +### Features +* [`a7bfc6d`](https://github.com/npm/cli/commit/a7bfc6df76882996ebb834dbca785fdf33b8c50d) [#7972](https://github.com/npm/cli/pull/7972) trigger release process (#7972) (@wraithgar) +### Chores +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) + + +### Dependencies + +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0): `@npmcli/arborist@9.0.0` + +## [9.0.0-pre.1](https://github.com/npm/cli/compare/libnpmpack-v9.0.0-pre.0...libnpmpack-v9.0.0-pre.1) (2024-12-06) +### ⚠️ BREAKING CHANGES +* `bun.lockb` files are now included in the strict ignore list during packing +### Dependencies +* [`ca84b22`](https://github.com/npm/cli/commit/ca84b22a18806495c37ef6ee2aecd42a1c7bb7f6) [#7945](https://github.com/npm/cli/pull/7945) `pacote@21.0.0` +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0-pre.1): `@npmcli/arborist@9.0.0-pre.1` + +## [9.0.0-pre.0](https://github.com/npm/cli/compare/libnpmpack-v8.0.0...libnpmpack-v9.0.0-pre.0) (2024-11-26) +### ⚠️ BREAKING CHANGES +* libnpmpack now supports node `^20.17.0 || >=22.9.0` +### Bug Fixes +* [`7f541e8`](https://github.com/npm/cli/commit/7f541e82a0b2908cc0cfef9a36b714eeab40c029) [#7815](https://github.com/npm/cli/pull/7815) make pack and exec work with git hash refs (#7815) (@milaninfy) +* [`f7b41a3`](https://github.com/npm/cli/commit/f7b41a3ea257bf4a34e141802d7b0beaccd16f04) [#7831](https://github.com/npm/cli/pull/7831) for libnpmpack sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +### Dependencies +* [`7dbef6f`](https://github.com/npm/cli/commit/7dbef6f3a3ead089b1b8b9fe6b2fa25e24309000) [#7850](https://github.com/npm/cli/pull/7850) `pacote@20.0.0` +### Chores +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v9.0.0-pre.0): `@npmcli/arborist@9.0.0-pre.0` + +## [8.0.0](https://github.com/npm/cli/compare/libnpmpack-v7.0.4...libnpmpack-v8.0.0) (2024-10-03) +### ⚠️ BREAKING CHANGES +* `libnpmpack` now supports node `^18.17.0 || >=20.5.0` +### Bug Fixes +* [`1b61379`](https://github.com/npm/cli/commit/1b61379137f9253de76662bf0f9404c2ae5d033f) [#7803](https://github.com/npm/cli/pull/7803) align libnpmpack to npm 10 node engine range (@reggi) +### Dependencies +* [`e7ab206`](https://github.com/npm/cli/commit/e7ab206370e5fc62fefe6916e5dcc40b3e577d22) [#7803](https://github.com/npm/cli/pull/7803) update `pacote@19.0.0` +* [`50a7bc8`](https://github.com/npm/cli/commit/50a7bc8737bb4e0a8fbc5f00b8f580512153a5bc) [#7803](https://github.com/npm/cli/pull/7803) update `npm-package-arg@12.0.0` +* [`538a4cc`](https://github.com/npm/cli/commit/538a4cc1dd731a3643ab4477fe545db39997bcdf) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/run-script@9.0.1` +### Chores +* [`2072705`](https://github.com/npm/cli/commit/2072705aa80d009dc077639adc305692f4a6c0b9) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/eslint-config@5.0.1` (@reggi) +* [`8035725`](https://github.com/npm/cli/commit/80357253ecd8483463cd66c783c4464c330d72df) [#7756](https://github.com/npm/cli/pull/7756) `@npmcli/template-oss@4.23.3` (@wraithgar) +* [workspace](https://github.com/npm/cli/releases/tag/arborist-v8.0.0): `@npmcli/arborist@8.0.0` + ## [7.0.3](https://github.com/npm/cli/compare/libnpmpack-v7.0.2...libnpmpack-v7.0.3) (2024-05-29) ### Bug Fixes diff --git a/workspaces/libnpmpack/lib/index.js b/workspaces/libnpmpack/lib/index.js index b026ad1a935c7..2ef6391e439d7 100644 --- a/workspaces/libnpmpack/lib/index.js +++ b/workspaces/libnpmpack/lib/index.js @@ -12,7 +12,43 @@ async function pack (spec = 'file:.', opts = {}) { // gets spec spec = npa(spec) - const manifest = await pacote.manifest(spec, opts) + const manifest = await pacote.manifest(spec, { ...opts, Arborist, _isRoot: true }) + + if (spec.type === 'directory') { + const hasBundled = manifest.bundleDependencies?.length > 0 + const hasOverrides = manifest.overrides + && typeof manifest.overrides === 'object' + && Object.keys(manifest.overrides).length > 0 + if (hasBundled && hasOverrides) { + // Only refuse when an override rule actually applies to a package that is bundled by the root. + // Overrides targeting dev dependencies or any package outside the bundled tree are harmless to consumers, because consumers do not apply the publishing package's overrides. + // We rely on Arborist's own semantics (inBundle/inDepBundle/overridden) rather than reimplementing what npm-packlist/arborist already knows. + const arb = new Arborist({ path: spec.fetchSpec }) + const tree = await arb.loadActual() + const offenders = new Set() + for (const node of tree.inventory.values()) { + if (node.isRoot) { + continue + } + // Only packages bundled by the root are at risk: nested dep-bundles are published as-is and arborist already treats them as immune to the root's overrides (see Edge#satisfiedBy). + if (!node.inBundle || node.inDepBundle) { + continue + } + if (node.overridden) { + offenders.add(node.name) + } + } + if (offenders.size) { + const names = [...offenders].sort() + const list = names.join(', ') + const isOne = names.length === 1 + throw Object.assign( + new Error(`Cannot pack or publish: "overrides" ${isOne ? 'affects a bundled package' : 'affect bundled packages'} (${list}). Consumers do not apply your package's overrides, so the published bundle will produce invalid dependency edges. Remove ${isOne ? 'this package' : 'these packages'} from "bundledDependencies"/"bundleDependencies" or from "overrides" before publishing.`), + { code: 'EBUNDLEOVERRIDE', packages: names } + ) + } + } + } const stdio = opts.foregroundScripts ? 'inherit' : 'pipe' @@ -28,16 +64,23 @@ async function pack (spec = 'file:.', opts = {}) { } // packs tarball - const tarball = await pacote.tarball(manifest._resolved, { + const tarballOpts = { ...opts, Arborist, integrity: manifest._integrity, - }) + } + // pacote re-parses manifest._resolved as type=remote, so allow-remote=none + // would mis-fire on the tarball URL the registry just handed us. mirror + // arborist reify's carve-out: trust resolved tarballs for registry-typed specs. + if (spec.registry) { + tarballOpts.allowRemote = 'all' + } + const tarball = await pacote.tarball(manifest._resolved, tarballOpts) // 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(/\//, '-') + .replace(/^@/, '').replace(/[/\\]/g, '-') const destination = path.resolve(opts.packDestination, filename) await writeFile(destination, tarball) } diff --git a/workspaces/libnpmpack/package.json b/workspaces/libnpmpack/package.json index 03fc3cda5cb87..6bf7f174f9a26 100644 --- a/workspaces/libnpmpack/package.json +++ b/workspaces/libnpmpack/package.json @@ -1,6 +1,6 @@ { "name": "libnpmpack", - "version": "7.0.4", + "version": "10.0.0-pre.1", "description": "Programmatic API for the bits behind npm pack", "author": "GitHub Inc.", "main": "lib/index.js", @@ -13,18 +13,19 @@ ], "license": "ISC", "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "test": "tap", "posttest": "npm run lint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "nock": "^13.3.3", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", + "nock": "^14.0.0", "spawk": "^1.7.1", "tap": "^16.3.8" }, @@ -36,20 +37,24 @@ "bugs": "https://github.com/npm/libnpmpack/issues", "homepage": "https://npmjs.com/package/libnpmpack", "dependencies": { - "@npmcli/arborist": "^7.5.4", - "@npmcli/run-script": "^8.1.0", - "npm-package-arg": "^11.0.2", - "pacote": "^18.0.6" + "@npmcli/arborist": "^10.0.0-pre.1", + "@npmcli/run-script": "^11.0.0", + "npm-package-arg": "^14.0.0", + "pacote": "^22.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../../scripts/template-oss/index.js" }, "tap": { + "node-arg": [ + "--require", + "../../scripts/disable-agent-for-tests.js" + ], "nyc-arg": [ "--exclude", "tap-snapshots/**" diff --git a/workspaces/libnpmpack/test/fixtures/git-test.tgz b/workspaces/libnpmpack/test/fixtures/git-test.tgz new file mode 100644 index 0000000000000..cc2b701d7df30 Binary files /dev/null and b/workspaces/libnpmpack/test/fixtures/git-test.tgz differ diff --git a/workspaces/libnpmpack/test/index.js b/workspaces/libnpmpack/test/index.js index f5eb647e4153b..1dc07ac2295a7 100644 --- a/workspaces/libnpmpack/test/index.js +++ b/workspaces/libnpmpack/test/index.js @@ -7,6 +7,7 @@ const spawk = tspawk(t) const fs = require('node:fs') const path = require('node:path') +const { resolve } = require('node:path') const pack = require('../lib/index.js') const tnock = require('./fixtures/tnock.js') @@ -35,6 +36,29 @@ t.test('packs from local directory', async t => { }) }) +t.test('flattens path separators in name so tarball stays in packDestination', async t => { + const testDir = t.testdir({ + src: { + 'package.json': JSON.stringify({ + name: 'x/../../../../../../escaped', + version: '1.0.0', + }, null, 2), + }, + dest: {}, + }) + + const dest = path.join(testDir, 'dest') + await pack(`file:${path.join(testDir, 'src')}`, { + dryRun: false, + packDestination: dest, + silent: true, + }) + + const written = fs.readdirSync(dest) + t.same(written, ['x-..-..-..-..-..-..-escaped-1.0.0.tgz'], 'separators flattened to a single filename') + t.notOk(fs.existsSync(path.join(testDir, 'escaped-1.0.0.tgz')), 'nothing escaped the destination') +}) + t.test('writes tarball to file when dryRun === false', async t => { const testDir = t.testdir({ 'package.json': JSON.stringify({ @@ -133,6 +157,19 @@ t.test('packs from registry spec', async t => { t.ok(tarball) }) +t.test('packs from git spec', async t => { + const spec = 'test/test#111111aaaaaaaabbbbbbbbccccccdddddddeeeee' + const pkgPath = resolve(__dirname, 'fixtures/git-test.tgz') + + const srv = tnock(t, 'https://codeload.github.com') + srv.get('/test/test/tar.gz/111111aaaaaaaabbbbbbbbccccccdddddddeeeee') + .times(2) + .reply(200, fs.readFileSync(pkgPath)) + + const tarball = await pack(spec, { ...OPTS }) + t.ok(tarball) +}) + t.test('runs scripts in foreground when foregroundScripts === true', async t => { const testDir = t.testdir({ 'package.json': JSON.stringify({ @@ -198,3 +235,229 @@ t.test('doesn\'t run scripts when ignoreScripts === true', async t => { spawk.clean() }) }) + +t.test('refuses to pack when overrides affect a bundled package', async t => { + const testDir = t.testdir({ + 'package.json': JSON.stringify({ + name: 'my-cool-pkg', + version: '1.0.0', + bundledDependencies: ['foo'], + dependencies: { foo: '1.0.0' }, + overrides: { bar: '2.0.0' }, + }, null, 2), + node_modules: { + foo: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.0.0', + dependencies: { bar: '^1.0.0' }, + }), + node_modules: { + bar: { + 'package.json': JSON.stringify({ name: 'bar', version: '2.0.0' }), + }, + }, + }, + }, + }) + + const cwd = process.cwd() + process.chdir(testDir) + t.teardown(() => process.chdir(cwd)) + + await t.rejects( + pack('file:.'), + { + code: 'EBUNDLEOVERRIDE', + packages: ['bar'], + message: /affects a bundled package \(bar\)/, + }, + 'throws EBUNDLEOVERRIDE listing the offending bundled package' + ) +}) + +t.test('lists all offenders when multiple bundled packages are overridden', async t => { + const testDir = t.testdir({ + 'package.json': JSON.stringify({ + name: 'my-cool-pkg', + version: '1.0.0', + bundledDependencies: ['foo'], + dependencies: { foo: '1.0.0' }, + overrides: { bar: '2.0.0', baz: '3.0.0' }, + }, null, 2), + node_modules: { + foo: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.0.0', + dependencies: { bar: '^1.0.0', baz: '^1.0.0' }, + }), + node_modules: { + bar: { + 'package.json': JSON.stringify({ name: 'bar', version: '2.0.0' }), + }, + baz: { + 'package.json': JSON.stringify({ name: 'baz', version: '3.0.0' }), + }, + }, + }, + }, + }) + + const cwd = process.cwd() + process.chdir(testDir) + t.teardown(() => process.chdir(cwd)) + + await t.rejects( + pack('file:.'), + { + code: 'EBUNDLEOVERRIDE', + packages: ['bar', 'baz'], + message: /affect bundled packages \(bar, baz\)/, + }, + 'lists every overridden bundled package and uses plural wording' + ) +}) + +t.test('refuses to pack with bundleDependencies (alt spelling) + affected override', async t => { + const testDir = t.testdir({ + 'package.json': JSON.stringify({ + name: 'my-cool-pkg', + version: '1.0.0', + bundleDependencies: ['foo'], + dependencies: { foo: '1.0.0' }, + overrides: { bar: '2.0.0' }, + }, null, 2), + node_modules: { + foo: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.0.0', + dependencies: { bar: '^1.0.0' }, + }), + node_modules: { + bar: { + 'package.json': JSON.stringify({ name: 'bar', version: '2.0.0' }), + }, + }, + }, + }, + }) + + const cwd = process.cwd() + process.chdir(testDir) + t.teardown(() => process.chdir(cwd)) + + await t.rejects( + pack('file:.'), + { code: 'EBUNDLEOVERRIDE' }, + 'throws EBUNDLEOVERRIDE with alternate bundleDependencies spelling' + ) +}) + +t.test('packs when overrides target only a dev dependency (not bundled)', async t => { + const testDir = t.testdir({ + 'package.json': JSON.stringify({ + name: 'my-cool-pkg', + version: '1.0.0', + bundledDependencies: ['keep'], + dependencies: { keep: '1.0.0' }, + devDependencies: { dev: '1.0.0' }, + overrides: { transdev: '2.0.0' }, + }, null, 2), + node_modules: { + keep: { + 'package.json': JSON.stringify({ name: 'keep', version: '1.0.0' }), + }, + dev: { + 'package.json': JSON.stringify({ + name: 'dev', + version: '1.0.0', + dependencies: { transdev: '^1.0.0' }, + }), + node_modules: { + transdev: { + 'package.json': JSON.stringify({ name: 'transdev', version: '2.0.0' }), + }, + }, + }, + }, + }) + + const cwd = process.cwd() + process.chdir(testDir) + t.teardown(() => process.chdir(cwd)) + + const tarball = await pack('file:.') + t.ok(tarball, 'pack succeeds — overridden dev-only transitive dep is not in the bundle') +}) + +t.test('packs when overrides target a package outside the bundled subtree', async t => { + const testDir = t.testdir({ + 'package.json': JSON.stringify({ + name: 'my-cool-pkg', + version: '1.0.0', + bundledDependencies: ['foo'], + dependencies: { foo: '1.0.0', qux: '^1.0.0' }, + overrides: { baz: '2.0.0' }, + }, null, 2), + node_modules: { + foo: { + 'package.json': JSON.stringify({ name: 'foo', version: '1.0.0' }), + }, + qux: { + 'package.json': JSON.stringify({ + name: 'qux', + version: '1.0.0', + dependencies: { baz: '^1.0.0' }, + }), + node_modules: { + baz: { + 'package.json': JSON.stringify({ name: 'baz', version: '2.0.0' }), + }, + }, + }, + }, + }) + + const cwd = process.cwd() + process.chdir(testDir) + t.teardown(() => process.chdir(cwd)) + + const tarball = await pack('file:.') + t.ok(tarball, 'pack succeeds — overridden package is not bundled') +}) + +t.test('packs with only bundledDependencies (no overrides)', async t => { + const testDir = t.testdir({ + 'package.json': JSON.stringify({ + name: 'my-cool-pkg', + version: '1.0.0', + bundledDependencies: [], + }, null, 2), + }) + + const cwd = process.cwd() + process.chdir(testDir) + t.teardown(() => process.chdir(cwd)) + + const tarball = await pack('file:.') + t.ok(tarball) +}) + +t.test('packs with only overrides (no bundled)', async t => { + const testDir = t.testdir({ + 'package.json': JSON.stringify({ + name: 'my-cool-pkg', + version: '1.0.0', + overrides: { 'lru-cache': '6.0.0' }, + }, null, 2), + }) + + const cwd = process.cwd() + process.chdir(testDir) + t.teardown(() => process.chdir(cwd)) + + const tarball = await pack('file:.') + t.ok(tarball) +}) diff --git a/workspaces/libnpmpublish/.gitignore b/workspaces/libnpmpublish/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/workspaces/libnpmpublish/.gitignore +++ b/workspaces/libnpmpublish/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/workspaces/libnpmpublish/CHANGELOG.md b/workspaces/libnpmpublish/CHANGELOG.md index abc96d1db36de..77054ddc55a0d 100644 --- a/workspaces/libnpmpublish/CHANGELOG.md +++ b/workspaces/libnpmpublish/CHANGELOG.md @@ -1,5 +1,104 @@ # Changelog +## [12.0.0-pre.0](https://github.com/npm/cli/compare/libnpmpublish-v11.2.0-pre.0...libnpmpublish-v12.0.0-pre.0) (2026-06-19) +### ⚠️ BREAKING CHANGES +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +* `opts.access` now defaults to `null` instead of `'public'`. With `null`, libnpmpublish no longer sets an explicit access level in the publish payload, so new scoped packages are created as `restricted` (registry default) and republishes preserve the existing access level. Callers that want to force public access must now pass `access: 'public'` explicitly. +### Features +* [`ce7681f`](https://github.com/npm/cli/commit/ce7681fe7dbcc20abb5f1379558e14ddd069654f) [#9496](https://github.com/npm/cli/pull/9496) packageExtensions for root-owned dependency manifest repairs (#9496) (@manzoorwanijk) +* [`1db885c`](https://github.com/npm/cli/commit/1db885c84b2dfc5126ab663abb12262b533922c1) [#9439](https://github.com/npm/cli/pull/9439) native dependency patching (npm patch add/commit/update/ls/rm) (#9439) (@manzoorwanijk) +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +### Bug Fixes +* [`79b0c84`](https://github.com/npm/cli/commit/79b0c8490c708f12f87d9fee16878bc95ace31e6) [#9419](https://github.com/npm/cli/pull/9419) default opts.access to null to preserve registry behavior (@owlstronaut) +* [`c5292fa`](https://github.com/npm/cli/commit/c5292fa8a09a56b25394d393faf21e47ffb096c0) [#9422](https://github.com/npm/cli/pull/9422) use prerelease strategy without a bug (@owlstronaut) +### Dependencies +* [`428afa6`](https://github.com/npm/cli/commit/428afa666b96b54a69ae72b25ab6fa48d3d19e61) [#9559](https://github.com/npm/cli/pull/9559) `sigstore@5.0.0` +* [`1502286`](https://github.com/npm/cli/commit/15022869509f110510fa8336144500108cdc6677) [#9559](https://github.com/npm/cli/pull/9559) `ssri@14.0.0` +* [`21df0ab`](https://github.com/npm/cli/commit/21df0ab3c629496511a3c481ee721b0e62c16e92) [#9559](https://github.com/npm/cli/pull/9559) `proc-log@7.0.0` +* [`1f9c567`](https://github.com/npm/cli/commit/1f9c56792493f80fb3b3d61710086ed748312f2a) [#9559](https://github.com/npm/cli/pull/9559) `npm-registry-fetch@20.0.1` +* [`d80859a`](https://github.com/npm/cli/commit/d80859a2dd97376e4ea621812b3bc7de6a218d21) [#9559](https://github.com/npm/cli/pull/9559) `npm-package-arg@14.0.0` +* [`0be6ae2`](https://github.com/npm/cli/commit/0be6ae21c79eb3986a76d5d769d5dd5ef00283c2) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/package-json@8.0.0` +### Chores +* [`1453954`](https://github.com/npm/cli/commit/1453954f9328a6b2480c183f9d1903ac93764915) [#9559](https://github.com/npm/cli/pull/9559) `nock@14.0.0` (@owlstronaut) +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) + +## [11.2.0-pre.0.0](https://github.com/npm/cli/compare/libnpmpublish-v11.1.3...libnpmpublish-v11.2.0-pre.0.0) (2026-05-20) +### Features +* [`254809e`](https://github.com/npm/cli/commit/254809e318ee0046092d07d68a99154c3f672147) [#9201](https://github.com/npm/cli/pull/9201) npm stage (#9201) (@reggi, @Copilot) +### Chores +* [`40fcab4`](https://github.com/npm/cli/commit/40fcab45d356545f8db7f34df3e5630116d0dd40) [#8991](https://github.com/npm/cli/pull/8991) `@npmcli/template-oss@4.29.0` (@wraithgar) + +## [11.1.3](https://github.com/npm/cli/compare/libnpmpublish-v11.1.2...libnpmpublish-v11.1.3) (2025-11-19) +### Dependencies +* [`8cc9f70`](https://github.com/npm/cli/commit/8cc9f70c2769f068ea0ef77a602162cdd949998e) [#8723](https://github.com/npm/cli/pull/8723) `ssri@13.0.0` +* [`05ac7a7`](https://github.com/npm/cli/commit/05ac7a7ea2a4d258658537a19ba350e07df34fda) [#8723](https://github.com/npm/cli/pull/8723) `proc-log@6.0.0` + +## [11.1.2](https://github.com/npm/cli/compare/libnpmpublish-v11.1.1...libnpmpublish-v11.1.2) (2025-10-08) +### Dependencies +* [`fa7cc6f`](https://github.com/npm/cli/commit/fa7cc6f9338e6d9c0be1dbe7002d683fd389794a) [#8662](https://github.com/npm/cli/pull/8662) `ci-info@4.3.1` (#8662) +* [`b05461b`](https://github.com/npm/cli/commit/b05461b6b16f262179efdea45fccf388f88ddc51) [#8663](https://github.com/npm/cli/pull/8663) `@sigstore/sign@4.0.1` (#8663) +### Chores +* [`5e0909b`](https://github.com/npm/cli/commit/5e0909b74ea1510eaae348d66548c75030911ed8) [#8620](https://github.com/npm/cli/pull/8620) fix spelling in workspaces (#8620) (@jsoref) + +## [11.1.1](https://github.com/npm/cli/compare/libnpmpublish-v11.1.0...libnpmpublish-v11.1.1) (2025-09-23) +### Dependencies +* [`bf6b686`](https://github.com/npm/cli/commit/bf6b6862731e03002cc6fa3b86b6f090df46b009) [#8576](https://github.com/npm/cli/pull/8576) `npm-package-arg@13.0.0` +* [`a2bdecc`](https://github.com/npm/cli/commit/a2bdecc6677abcd58ed3037ab0edafb419ea86fa) [#8576](https://github.com/npm/cli/pull/8576) `sigstore@4.0.0` +* [`1149971`](https://github.com/npm/cli/commit/11499711e4c10e4ddb97bf3e1ef1652d151894fb) [#8576](https://github.com/npm/cli/pull/8576) `npm-registry-fetch@19.0.0` +* [`ceae674`](https://github.com/npm/cli/commit/ceae674c32a080b81e62d79003c2d537d7ca93d2) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/package-json@7.0.1` +### Chores +* [`402a0ab`](https://github.com/npm/cli/commit/402a0ab1b4e5d1a8414dd063d0cbde0c0bc5a192) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/template-oss@4.25.1` (@wraithgar) + +## [11.1.0](https://github.com/npm/cli/compare/libnpmpublish-v11.0.1...libnpmpublish-v11.1.0) (2025-07-24) +### Features +* [`1cce318`](https://github.com/npm/cli/commit/1cce31810eb5ff1e0f7c8ee4516e7c73cedb38a1) [#8336](https://github.com/npm/cli/pull/8336) adds support for oidc publish (#8336) (@reggi) +### Chores +* [`3f60b5f`](https://github.com/npm/cli/commit/3f60b5f9621b43ae0b8796d3a7160a603748f756) [#8383](https://github.com/npm/cli/pull/8383) `@npmcli/template-oss@4.24.4` (#8383) (@wraithgar) +* [`01f8cc6`](https://github.com/npm/cli/commit/01f8cc6f001e3211135fa0563f7129aed09dc46c) [#8381](https://github.com/npm/cli/pull/8381) `@npmcli/template-oss@4.24.3` (#8381) (@wraithgar) + +## [11.0.1](https://github.com/npm/cli/compare/libnpmpublish-v11.0.0...libnpmpublish-v11.0.1) (2025-06-11) +### Bug Fixes +* [`71cb65b`](https://github.com/npm/cli/commit/71cb65b3c551e663a7bbdb25f5b3c3ddebb1a8c8) [#8317](https://github.com/npm/cli/pull/8317) libnpmpublish: Remove dependence on deprecated library (@owlstronaut) +### Dependencies +* [`dda6f87`](https://github.com/npm/cli/commit/dda6f871331280eeb37493a4ccc57361a27949eb) [#8317](https://github.com/npm/cli/pull/8317) `@npmcli/package-json@6.2.0` +* [`bc08ac7`](https://github.com/npm/cli/commit/bc08ac7a82f047485885d9c41a8b6fc48e8981b0) [#8317](https://github.com/npm/cli/pull/8317) remove normalize-package-data + +## [11.0.0](https://github.com/npm/cli/compare/libnpmpublish-v11.0.0-pre.0...libnpmpublish-v11.0.0) (2024-12-16) +### Features +* [`a7bfc6d`](https://github.com/npm/cli/commit/a7bfc6df76882996ebb834dbca785fdf33b8c50d) [#7972](https://github.com/npm/cli/pull/7972) trigger release process (#7972) (@wraithgar) +### Chores +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) + +## [11.0.0-pre.0](https://github.com/npm/cli/compare/libnpmpublish-v10.0.0...libnpmpublish-v11.0.0-pre.0) (2024-11-26) +### ⚠️ BREAKING CHANGES +* Attestations made by this package will no longer validate in npm versions prior to 10.6.0 +* libnpmpublish now supports node `^20.17.0 || >=22.9.0` +### Bug Fixes +* [`f75da94`](https://github.com/npm/cli/commit/f75da94f3bed6c0b637044e88098ec354cf302b0) [#7833](https://github.com/npm/cli/pull/7833) update libnpmpublish tests for sigstore 3.0.0 (@bdehamer) +* [`a2f8af0`](https://github.com/npm/cli/commit/a2f8af0437a7d5a1219c3b01f0120ca45fae607d) [#7831](https://github.com/npm/cli/pull/7831) for libnpmpublish sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +### Dependencies +* [`75a3f12`](https://github.com/npm/cli/commit/75a3f1228865f426d8790be27f1258e501f2c450) [#7859](https://github.com/npm/cli/pull/7859) remove unused deps (#7859) +* [`7ee15bb`](https://github.com/npm/cli/commit/7ee15bbdc1da0ed85297f47952b66089f29ed3fd) [#7833](https://github.com/npm/cli/pull/7833) bump sigstore from 2.x to 3.0.0 (@bdehamer) +### Chores +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) + +## [10.0.0](https://github.com/npm/cli/compare/libnpmpublish-v9.0.9...libnpmpublish-v10.0.0) (2024-10-03) +### ⚠️ BREAKING CHANGES +* `libnpmpublish` now supports node `^18.17.0 || >=20.5.0` +### Bug Fixes +* [`96f4e4e`](https://github.com/npm/cli/commit/96f4e4e134364ad69b7abb1fa164aee3c0f602ee) [#7803](https://github.com/npm/cli/pull/7803) align libnpmpublish to npm 10 node engine range (@reggi) +### Dependencies +* [`8206c4f`](https://github.com/npm/cli/commit/8206c4f675937e855b60164946c086eb64d7ecb6) [#7803](https://github.com/npm/cli/pull/7803) update `ssri@12.0.0` +* [`f6909a0`](https://github.com/npm/cli/commit/f6909a022c9373c85d980c96a30f47a3a65aa4a9) [#7803](https://github.com/npm/cli/pull/7803) update `proc-log@5.0.0` +* [`d13a20b`](https://github.com/npm/cli/commit/d13a20bebef1b9932f86c44741ea6d214ad6842b) [#7803](https://github.com/npm/cli/pull/7803) update `npm-registry-fetch@18.0.1` +* [`50a7bc8`](https://github.com/npm/cli/commit/50a7bc8737bb4e0a8fbc5f00b8f580512153a5bc) [#7803](https://github.com/npm/cli/pull/7803) update `npm-package-arg@12.0.0` +* [`8d4060a`](https://github.com/npm/cli/commit/8d4060a661db50dc4d4a2f30cc57346f1d242599) [#7803](https://github.com/npm/cli/pull/7803) update `normalize-package-data@7.0.0` +### Chores +* [`2072705`](https://github.com/npm/cli/commit/2072705aa80d009dc077639adc305692f4a6c0b9) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/eslint-config@5.0.1` (@reggi) +* [`8035725`](https://github.com/npm/cli/commit/80357253ecd8483463cd66c783c4464c330d72df) [#7756](https://github.com/npm/cli/pull/7756) `@npmcli/template-oss@4.23.3` (@wraithgar) + ## [9.0.9](https://github.com/npm/cli/compare/libnpmpublish-v9.0.8...libnpmpublish-v9.0.9) (2024-05-29) ### Bug Fixes @@ -357,7 +456,7 @@ * [`f6bf2b8`](https://github.com/npm/libnpmpublish/commit/f6bf2b8) feat: unpublish code refactor ([@claudiahdz](https://github.com/claudiahdz)) -### Miscellaneuous +### Miscellaneous * [`5cea10f`](https://github.com/npm/libnpmpublish/commit/5cea10f) chore: basic project updates ([@claudiahdz](https://github.com/claudiahdz)) * [`3010b93`](https://github.com/npm/libnpmpublish/commit/3010b93) chore: cleanup badges + contributing ([@ruyadorno](https://github.com/ruyadorno)) diff --git a/workspaces/libnpmpublish/README.md b/workspaces/libnpmpublish/README.md index 90b1f7c68ab4f..69b747d92dcfc 100644 --- a/workspaces/libnpmpublish/README.md +++ b/workspaces/libnpmpublish/README.md @@ -44,8 +44,13 @@ A couple of options of note: 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`. + published as `'public'` or `'restricted'`. May also be `null`, which + preserves the existing access level on already-published packages and + defers to the registry's default for new packages (the registry treats + scoped packages as `restricted` and unscoped packages as `public` by + default). Only `'restricted'` and `null` are meaningful for scoped + packages; `'restricted'` is rejected for unscoped packages. Defaults to + `null`. * `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 @@ -62,6 +67,13 @@ A couple of options of note: containing a [DSSE](https://github.com/secure-systems-lab/dsse)-packaged provenance statement. +* `opts.stage` - when `true`, publishes the package to a staging area instead + of making it immediately available. The registry response will include a + `stageId` (UUID) that can be used to approve or reject the staged version + later. Changes the request method to `POST` and the endpoint to + `/-/stage/package/`. The returned Response object will have a + `stageId` property. + #### `> libpub.publish(manifest, tarData, [opts]) -> Promise` Sends the package represented by the `manifest` and `tarData` to the diff --git a/workspaces/libnpmpublish/lib/publish.js b/workspaces/libnpmpublish/lib/publish.js index 93d546efb5f0e..796cef6aa392a 100644 --- a/workspaces/libnpmpublish/lib/publish.js +++ b/workspaces/libnpmpublish/lib/publish.js @@ -1,6 +1,6 @@ -const { fixer } = require('normalize-package-data') const npmFetch = require('npm-registry-fetch') const npa = require('npm-package-arg') +const PackageJson = require('@npmcli/package-json') const { log } = require('proc-log') const semver = require('semver') const { URL } = require('node:url') @@ -20,10 +20,18 @@ Remove the 'private' field from the package.json to publish it.`), ) } + // packageExtensions is root-only project policy and must never reach the registry manifest or the published tarball + if (manifest.packageExtensions !== undefined) { + throw Object.assign( + new Error('packageExtensions is only honored at the project root and must not be published.'), + { code: 'EPACKAGEEXTENSIONS' } + ) + } + // spec is used to pick the appropriate registry/auth combo const spec = npa.resolve(manifest.name, manifest.version) opts = { - access: 'public', + access: null, algorithms: ['sha512'], defaultTag: 'latest', ...opts, @@ -31,7 +39,7 @@ Remove the 'private' field from the package.json to publish it.`), } const reg = npmFetch.pickRegistry(spec, opts) - const pubManifest = patchManifest(manifest, opts) + const pubManifest = await patchManifest(manifest, opts) // registry-frontdoor cares about the access level, // which is only configurable for scoped packages @@ -50,29 +58,35 @@ Remove the 'private' field from the package.json to publish it.`), opts ) - const res = await npmFetch(spec.escapedName, { + const stageRoute = `/-/stage/package/${spec.escapedName}` + const res = await npmFetch(opts.stage ? stageRoute : spec.escapedName, { ...opts, - method: 'PUT', + method: opts.stage ? 'POST' : 'PUT', body: metadata, - ignoreBody: true, + ignoreBody: !opts.stage, }) if (transparencyLogUrl) { res.transparencyLogUrl = transparencyLogUrl } + if (opts.stage) { + const json = await res.json() + res.stageId = json.stageId + } return res } -const patchManifest = (_manifest, opts) => { +const patchManifest = async (_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 + const steps = ['fixName'] + const manifestInput = { ..._manifest, _nodeVersion: process.versions.node } + if (npmVersion != null) { + manifestInput._npmVersion = npmVersion } + const manifest = await new PackageJson() + .fromContent(manifestInput) + .normalize({ steps }) + .then(p => p.content) - fixer.fixNameField(manifest, { strict: true, allowLegacyCase: true }) const version = semver.clean(manifest.version) if (!version) { throw Object.assign( @@ -81,11 +95,13 @@ const patchManifest = (_manifest, opts) => { ) } manifest.version = version + // patchedDependencies is consumer-side state and must never be published + delete manifest.patchedDependencies return manifest } const buildMetadata = async (registry, manifest, tarballData, spec, opts) => { - const { access, defaultTag, algorithms, provenance, provenanceFile } = opts + const { access, defaultTag, algorithms, provenance, provenanceFile, command = 'publish' } = opts const root = { _id: manifest.name, name: manifest.name, @@ -140,14 +156,14 @@ const buildMetadata = async (registry, manifest, tarballData, 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}`) + log.notice(command, `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', + command, `Provenance statement published to transparency log: ${transparencyLogUrl}` ) } @@ -204,7 +220,7 @@ const ensureProvenanceGeneration = async (registry, spec, opts) => { if (opts.access !== 'public') { try { const res = await npmFetch - .json(`${registry}/-/package/${spec.escapedName}/visibility`, opts) + .json(`/-/package/${spec.escapedName}/visibility`, { ...opts, registry }) visibility = res } catch (err) { if (err.code !== 'E404') { diff --git a/workspaces/libnpmpublish/package.json b/workspaces/libnpmpublish/package.json index 87fc8215dcab8..6ef07f1be15aa 100644 --- a/workspaces/libnpmpublish/package.json +++ b/workspaces/libnpmpublish/package.json @@ -1,6 +1,6 @@ { "name": "libnpmpublish", - "version": "9.0.9", + "version": "12.0.0-pre.0", "description": "Programmatic API for the bits behind npm publish and unpublish", "author": "GitHub Inc.", "main": "lib/index.js", @@ -14,20 +14,20 @@ ], "license": "ISC", "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "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" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", + "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-globals": "^1.0.0", "@npmcli/mock-registry": "^1.0.0", - "@npmcli/template-oss": "4.22.0", - "nock": "^13.3.3", + "@npmcli/template-oss": "5.1.1", "tap": "^16.3.8" }, "repository": { @@ -38,24 +38,28 @@ "bugs": "https://github.com/npm/cli/issues", "homepage": "https://npmjs.com/package/libnpmpublish", "dependencies": { + "@npmcli/package-json": "^8.0.0", "ci-info": "^4.0.0", - "normalize-package-data": "^6.0.1", - "npm-package-arg": "^11.0.2", - "npm-registry-fetch": "^17.0.1", - "proc-log": "^4.2.0", + "npm-package-arg": "^14.0.0", + "npm-registry-fetch": "^20.0.1", + "proc-log": "^7.0.0", "semver": "^7.3.7", - "sigstore": "^2.2.0", - "ssri": "^10.0.6" + "sigstore": "^5.0.0", + "ssri": "^14.0.0" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../../scripts/template-oss/index.js" }, "tap": { + "node-arg": [ + "--require", + "../../scripts/disable-agent-for-tests.js" + ], "nyc-arg": [ "--exclude", "tap-snapshots/**" diff --git a/workspaces/libnpmpublish/test/publish.js b/workspaces/libnpmpublish/test/publish.js index a3355df7417a9..3b41656bef17a 100644 --- a/workspaces/libnpmpublish/test/publish.js +++ b/workspaces/libnpmpublish/test/publish.js @@ -1,5 +1,7 @@ 'use strict' +// Comment to trigger tests + const crypto = require('node:crypto') const fs = require('node:fs') const npa = require('npm-package-arg') @@ -55,7 +57,7 @@ t.test('basic publish - no npmVersion', async t => { }, }, }, - access: 'public', + access: null, _attachments: { 'libnpmpublish-test-1.0.0.tgz': { content_type: 'application/octet-stream', @@ -73,6 +75,77 @@ t.test('basic publish - no npmVersion', async t => { t.ok(ret, 'publish succeeded') }) +t.test('publish strips patchedDependencies from the registry manifest', async t => { + const { publish } = t.mock('..') + const registry = new MockRegistry({ + tap: t, + registry: opts.registry, + authorization: token, + }) + const manifest = { + name: 'libnpmpublish-test', + version: '1.0.0', + description: 'test libnpmpublish package', + patchedDependencies: { 'lodash@4.17.21': 'patches/lodash@4.17.21.patch' }, + } + const spec = npa(manifest.name) + // patchedDependencies must not appear in the published version metadata + const { patchedDependencies, ...clean } = manifest + + const packument = { + _id: manifest.name, + name: manifest.name, + description: manifest.description, + 'dist-tags': { + latest: '1.0.0', + }, + versions: { + '1.0.0': { + _id: `${manifest.name}@${manifest.version}`, + _nodeVersion: process.versions.node, + ...clean, + dist: { + shasum, + integrity: integrity.sha512[0].toString(), + tarball: 'http://mock.reg/libnpmpublish-test/-/libnpmpublish-test-1.0.0.tgz', + }, + }, + }, + access: null, + _attachments: { + 'libnpmpublish-test-1.0.0.tgz': { + content_type: 'application/octet-stream', + data: tarData.toString('base64'), + length: tarData.length, + }, + }, + } + + registry.nock.put(`/${spec.escapedName}`, packument).reply(201, {}) + const ret = await publish(manifest, tarData, { + ...opts, + npmVersion: null, + }) + t.ok(ret, 'publish succeeded with patchedDependencies stripped') +}) + +t.test('fails when publishing a package with packageExtensions', async t => { + const { publish } = t.mock('..') + // no registry interceptor: the publish must fail before any request is made + const manifest = { + name: 'libnpmpublish-test', + version: '1.0.0', + description: 'test libnpmpublish package', + packageExtensions: { 'foo@1': { dependencies: { bar: '^1.0.0' } } }, + } + + await t.rejects( + publish(manifest, tarData, { ...opts, npmVersion: null }), + { code: 'EPACKAGEEXTENSIONS', message: /must not be published/ }, + 'refuses to publish a package containing packageExtensions' + ) +}) + t.test('scoped publish', async t => { const { publish } = t.mock('..') const registry = new MockRegistry({ @@ -108,7 +181,7 @@ t.test('scoped publish', async t => { }, }, }, - access: 'public', + access: null, _attachments: { '@npmcli/libnpmpublish-test-1.0.0.tgz': { content_type: 'application/octet-stream', @@ -300,7 +373,7 @@ t.test('other error code', async t => { const packument = { name: 'libnpmpublish', description: 'some stuff', - access: 'public', + access: null, _id: 'libnpmpublish', 'dist-tags': { latest: '1.0.0', @@ -403,10 +476,11 @@ t.test('publish existing package with provenance in gha', async t => { const oidcClaims = { iss: 'https://oauth2.sigstore.dev/auth', email: 'foo@bar.com', + email_verified: true, } const idToken = `.${Buffer.from(JSON.stringify(oidcClaims)).toString('base64')}.` - // Data for mocking Fulcio certifcate request + // Data for mocking Fulcio certificate request const fulcioURL = 'https://mock.fulcio' const leafCertificate = `-----BEGIN CERTIFICATE-----\nabc\n-----END CERTIFICATE-----\n` const rootCertificate = `-----BEGIN CERTIFICATE-----\nxyz\n-----END CERTIFICATE-----\n` @@ -486,7 +560,7 @@ t.test('publish existing package with provenance in gha', async t => { // Can't match length because in github actions certain environment // variables are present that are not present when running locally, // changing the payload size. - content_type: 'application/vnd.dev.sigstore.bundle+json;version=0.2', + content_type: 'application/vnd.dev.sigstore.bundle.v0.3+json', }, }, } @@ -543,6 +617,7 @@ t.test('publish existing package with provenance in gha', async t => { const ret = await publish(manifest, tarData, { ...opts, + access: 'public', provenance: true, fulcioURL: fulcioURL, rekorURL: rekorURL, @@ -700,7 +775,7 @@ t.test('automatic provenance in unsupported environment', async t => { t.test('automatic provenance with incorrect permissions', async t => { mockGlobals(t, { 'process.env': { - CI: false, + CI: true, GITHUB_ACTIONS: true, ACTIONS_ID_TOKEN_REQUEST_URL: undefined, }, @@ -763,7 +838,7 @@ t.test('user-supplied provenance - success', async t => { }, }, }, - access: 'public', + access: null, _attachments: { '@npmcli/libnpmpublish-test-1.0.0.tgz': { content_type: 'application/octet-stream', @@ -911,6 +986,7 @@ t.test('publish existing package with provenance in gitlab', async t => { const oidcClaims = { iss: 'https://oauth2.sigstore.dev/auth', email: 'foo@bar.com', + email_verified: true, } const idToken = `.${Buffer.from(JSON.stringify(oidcClaims)).toString('base64')}.` @@ -958,7 +1034,7 @@ t.test('publish existing package with provenance in gitlab', async t => { } const spec = npa(manifest.name) - // Data for mocking Fulcio certifcate request + // Data for mocking Fulcio certificate request const fulcioURL = 'https://mock.fulcio' const leafCertificate = `-----BEGIN CERTIFICATE-----\nabc\n-----END CERTIFICATE-----\n` const rootCertificate = `-----BEGIN CERTIFICATE-----\nxyz\n-----END CERTIFICATE-----\n` @@ -1038,7 +1114,7 @@ t.test('publish existing package with provenance in gitlab', async t => { // Can't match length because in github actions certain environment // variables are present that are not present when running locally, // changing the payload size. - content_type: 'application/vnd.dev.sigstore.bundle+json;version=0.2', + content_type: 'application/vnd.dev.sigstore.bundle.v0.3+json', }, }, } @@ -1087,6 +1163,7 @@ t.test('publish existing package with provenance in gitlab', async t => { const ret = await publish(manifest, tarData, { ...opts, + access: 'public', provenance: true, fulcioURL: fulcioURL, rekorURL: rekorURL, @@ -1101,6 +1178,31 @@ t.test('publish existing package with provenance in gitlab', async t => { ]) }) +t.test('stage publish returns stageId', async t => { + const { publish } = t.mock('..') + const registry = new MockRegistry({ + tap: t, + registry: opts.registry, + authorization: token, + }) + const manifest = { + name: '@npmcli/libnpmpublish-test', + version: '1.0.0', + description: 'test libnpmpublish package', + } + const spec = npa(manifest.name) + + registry.nock + .post(`/-/stage/package/${spec.escapedName}`) + .reply(201, { stageId: 'test-stage-id' }) + + const ret = await publish(manifest, tarData, { + ...opts, + stage: true, + }) + t.equal(ret.stageId, 'test-stage-id', 'stageId returned from response') +}) + t.test('gitlab provenance, no token available', async t => { mockGlobals(t, { 'process.env': { diff --git a/workspaces/libnpmsearch/.gitignore b/workspaces/libnpmsearch/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/workspaces/libnpmsearch/.gitignore +++ b/workspaces/libnpmsearch/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/workspaces/libnpmsearch/CHANGELOG.md b/workspaces/libnpmsearch/CHANGELOG.md index 48a12e8ea9d76..99210dd0bed2d 100644 --- a/workspaces/libnpmsearch/CHANGELOG.md +++ b/workspaces/libnpmsearch/CHANGELOG.md @@ -1,5 +1,53 @@ # Changelog +## [10.0.0-pre.0](https://github.com/npm/cli/compare/libnpmsearch-v9.0.1...libnpmsearch-v10.0.0-pre.0) (2026-06-19) +### ⚠️ BREAKING CHANGES +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +### Features +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +### Dependencies +* [`1f9c567`](https://github.com/npm/cli/commit/1f9c56792493f80fb3b3d61710086ed748312f2a) [#9559](https://github.com/npm/cli/pull/9559) `npm-registry-fetch@20.0.1` +### Chores +* [`1453954`](https://github.com/npm/cli/commit/1453954f9328a6b2480c183f9d1903ac93764915) [#9559](https://github.com/npm/cli/pull/9559) `nock@14.0.0` (@owlstronaut) +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`40fcab4`](https://github.com/npm/cli/commit/40fcab45d356545f8db7f34df3e5630116d0dd40) [#8991](https://github.com/npm/cli/pull/8991) `@npmcli/template-oss@4.29.0` (@wraithgar) +* [`5e0909b`](https://github.com/npm/cli/commit/5e0909b74ea1510eaae348d66548c75030911ed8) [#8620](https://github.com/npm/cli/pull/8620) fix spelling in workspaces (#8620) (@jsoref) + +## [9.0.1](https://github.com/npm/cli/compare/libnpmsearch-v9.0.0...libnpmsearch-v9.0.1) (2025-09-23) +### Dependencies +* [`1149971`](https://github.com/npm/cli/commit/11499711e4c10e4ddb97bf3e1ef1652d151894fb) [#8576](https://github.com/npm/cli/pull/8576) `npm-registry-fetch@19.0.0` +### Chores +* [`402a0ab`](https://github.com/npm/cli/commit/402a0ab1b4e5d1a8414dd063d0cbde0c0bc5a192) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/template-oss@4.25.1` (@wraithgar) +* [`3f60b5f`](https://github.com/npm/cli/commit/3f60b5f9621b43ae0b8796d3a7160a603748f756) [#8383](https://github.com/npm/cli/pull/8383) `@npmcli/template-oss@4.24.4` (#8383) (@wraithgar) +* [`01f8cc6`](https://github.com/npm/cli/commit/01f8cc6f001e3211135fa0563f7129aed09dc46c) [#8381](https://github.com/npm/cli/pull/8381) `@npmcli/template-oss@4.24.3` (#8381) (@wraithgar) + +## [9.0.0](https://github.com/npm/cli/compare/libnpmsearch-v9.0.0-pre.0...libnpmsearch-v9.0.0) (2024-12-16) +### Features +* [`a7bfc6d`](https://github.com/npm/cli/commit/a7bfc6df76882996ebb834dbca785fdf33b8c50d) [#7972](https://github.com/npm/cli/pull/7972) trigger release process (#7972) (@wraithgar) +### Chores +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) + +## [9.0.0-pre.0](https://github.com/npm/cli/compare/libnpmsearch-v8.0.0...libnpmsearch-v9.0.0-pre.0) (2024-11-26) +### ⚠️ BREAKING CHANGES +* libnpmsearch now supports node `^20.17.0 || >=22.9.0` +### Bug Fixes +* [`2f2ee15`](https://github.com/npm/cli/commit/2f2ee1541db6c9c24582ce8a24dfb4702d22b759) [#7831](https://github.com/npm/cli/pull/7831) for libnpmsearch sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +### Chores +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) + +## [8.0.0](https://github.com/npm/cli/compare/libnpmsearch-v7.0.6...libnpmsearch-v8.0.0) (2024-10-03) +### ⚠️ BREAKING CHANGES +* `libnpmsearch` now supports node `^18.17.0 || >=20.5.0` +### Bug Fixes +* [`ecfa213`](https://github.com/npm/cli/commit/ecfa21361888012d7608645271cdaa2fe37ed270) [#7803](https://github.com/npm/cli/pull/7803) align libnpmsearch to npm 10 node engine range (@reggi) +### Dependencies +* [`d13a20b`](https://github.com/npm/cli/commit/d13a20bebef1b9932f86c44741ea6d214ad6842b) [#7803](https://github.com/npm/cli/pull/7803) update `npm-registry-fetch@18.0.1` +### Chores +* [`2072705`](https://github.com/npm/cli/commit/2072705aa80d009dc077639adc305692f4a6c0b9) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/eslint-config@5.0.1` (@reggi) +* [`8035725`](https://github.com/npm/cli/commit/80357253ecd8483463cd66c783c4464c330d72df) [#7756](https://github.com/npm/cli/pull/7756) `@npmcli/template-oss@4.23.3` (@wraithgar) + ## [7.0.6](https://github.com/npm/cli/compare/libnpmsearch-v7.0.5...libnpmsearch-v7.0.6) (2024-05-29) ### Bug Fixes @@ -140,7 +188,7 @@ * [`45f4db1`](https://github.com/npm/libnpmsearch/commit/45f4db1) fix: remove figgy-pudding ([@claudiahdz](https://github.com/claudiahdz)) -### Miscellaneuous +### Miscellaneous * [`b413aae`](https://github.com/npm/libnpmsearch/commit/b413aae) chore: basic project updates ([@claudiahdz](https://github.com/claudiahdz)) * [`534983c`](https://github.com/npm/libnpmsearch/commit/534983c) chore: remove pr temmsearch ([@ruyadorno](https://github.com/ruyadorno)) diff --git a/workspaces/libnpmsearch/package.json b/workspaces/libnpmsearch/package.json index 795a6ae076831..26e4be70271f0 100644 --- a/workspaces/libnpmsearch/package.json +++ b/workspaces/libnpmsearch/package.json @@ -1,6 +1,6 @@ { "name": "libnpmsearch", - "version": "7.0.6", + "version": "10.0.0-pre.0", "description": "Programmatic API for searching in npm and compatible registries.", "author": "GitHub Inc.", "main": "lib/index.js", @@ -18,16 +18,17 @@ "scripts": { "posttest": "npm run lint", "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "nock": "^13.3.3", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", + "nock": "^14.0.0", "tap": "^16.3.8" }, "repository": { @@ -38,17 +39,21 @@ "bugs": "https://github.com/npm/libnpmsearch/issues", "homepage": "https://npmjs.com/package/libnpmsearch", "dependencies": { - "npm-registry-fetch": "^17.0.1" + "npm-registry-fetch": "^20.0.1" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../../scripts/template-oss/index.js" }, "tap": { + "node-arg": [ + "--require", + "../../scripts/disable-agent-for-tests.js" + ], "nyc-arg": [ "--exclude", "tap-snapshots/**" diff --git a/workspaces/libnpmsearch/test/index.js b/workspaces/libnpmsearch/test/index.js index 2aba48611c5e6..5d8b18443fa72 100644 --- a/workspaces/libnpmsearch/test/index.js +++ b/workspaces/libnpmsearch/test/index.js @@ -157,7 +157,7 @@ test('accepts a from option', async t => { t.equal(results.length, 4, 'returns more results if endpoint does so') }) -test('accepts quality/mainenance/popularity options', async t => { +test('accepts quality/maintenance/popularity options', async t => { const query = qs.stringify({ text: 'oo', size: 20, diff --git a/workspaces/libnpmteam/.gitignore b/workspaces/libnpmteam/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/workspaces/libnpmteam/.gitignore +++ b/workspaces/libnpmteam/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/workspaces/libnpmteam/CHANGELOG.md b/workspaces/libnpmteam/CHANGELOG.md index f3f467c56fd6f..2febb2d51eedd 100644 --- a/workspaces/libnpmteam/CHANGELOG.md +++ b/workspaces/libnpmteam/CHANGELOG.md @@ -1,5 +1,57 @@ # Changelog +## [9.0.0-pre.0](https://github.com/npm/cli/compare/libnpmteam-v8.0.2...libnpmteam-v9.0.0-pre.0) (2026-06-19) +### ⚠️ BREAKING CHANGES +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +### Features +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +### Dependencies +* [`1f9c567`](https://github.com/npm/cli/commit/1f9c56792493f80fb3b3d61710086ed748312f2a) [#9559](https://github.com/npm/cli/pull/9559) `npm-registry-fetch@20.0.1` +### Chores +* [`1453954`](https://github.com/npm/cli/commit/1453954f9328a6b2480c183f9d1903ac93764915) [#9559](https://github.com/npm/cli/pull/9559) `nock@14.0.0` (@owlstronaut) +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`40fcab4`](https://github.com/npm/cli/commit/40fcab45d356545f8db7f34df3e5630116d0dd40) [#8991](https://github.com/npm/cli/pull/8991) `@npmcli/template-oss@4.29.0` (@wraithgar) +* [`5e0909b`](https://github.com/npm/cli/commit/5e0909b74ea1510eaae348d66548c75030911ed8) [#8620](https://github.com/npm/cli/pull/8620) fix spelling in workspaces (#8620) (@jsoref) + +## [8.0.2](https://github.com/npm/cli/compare/libnpmteam-v8.0.1...libnpmteam-v8.0.2) (2025-09-23) +### Dependencies +* [`1149971`](https://github.com/npm/cli/commit/11499711e4c10e4ddb97bf3e1ef1652d151894fb) [#8576](https://github.com/npm/cli/pull/8576) `npm-registry-fetch@19.0.0` +### Chores +* [`402a0ab`](https://github.com/npm/cli/commit/402a0ab1b4e5d1a8414dd063d0cbde0c0bc5a192) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/template-oss@4.25.1` (@wraithgar) +* [`3f60b5f`](https://github.com/npm/cli/commit/3f60b5f9621b43ae0b8796d3a7160a603748f756) [#8383](https://github.com/npm/cli/pull/8383) `@npmcli/template-oss@4.24.4` (#8383) (@wraithgar) +* [`01f8cc6`](https://github.com/npm/cli/commit/01f8cc6f001e3211135fa0563f7129aed09dc46c) [#8381](https://github.com/npm/cli/pull/8381) `@npmcli/template-oss@4.24.3` (#8381) (@wraithgar) + +## [8.0.1](https://github.com/npm/cli/compare/libnpmteam-v8.0.0...libnpmteam-v8.0.1) (2025-05-15) +### Bug Fixes +* [`b734099`](https://github.com/npm/cli/commit/b7340990db22e89c1e9c4571835b3c738bec8742) [#8291](https://github.com/npm/cli/pull/8291) libnpmteam: update README (#8291) (@mbtools) + +## [8.0.0](https://github.com/npm/cli/compare/libnpmteam-v8.0.0-pre.0...libnpmteam-v8.0.0) (2024-12-16) +### Features +* [`a7bfc6d`](https://github.com/npm/cli/commit/a7bfc6df76882996ebb834dbca785fdf33b8c50d) [#7972](https://github.com/npm/cli/pull/7972) trigger release process (#7972) (@wraithgar) +### Chores +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) + +## [8.0.0-pre.0](https://github.com/npm/cli/compare/libnpmteam-v7.0.0...libnpmteam-v8.0.0-pre.0) (2024-11-26) +### ⚠️ BREAKING CHANGES +* libnpmteam now supports node `^20.17.0 || >=22.9.0` +### Bug Fixes +* [`9561fa7`](https://github.com/npm/cli/commit/9561fa7fde679bd7bd8b2da40ed40959a9680b2d) [#7831](https://github.com/npm/cli/pull/7831) for libnpmteam sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +### Chores +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) + +## [7.0.0](https://github.com/npm/cli/compare/libnpmteam-v6.0.5...libnpmteam-v7.0.0) (2024-10-03) +### ⚠️ BREAKING CHANGES +* `libnpmteam` now supports node `^18.17.0 || >=20.5.0` +### Bug Fixes +* [`61d9a90`](https://github.com/npm/cli/commit/61d9a901b7a7bc2a91d42ccd03e9c26c7fd98b6b) [#7803](https://github.com/npm/cli/pull/7803) align libnpmteam to npm 10 node engine range (@reggi) +### Dependencies +* [`d13a20b`](https://github.com/npm/cli/commit/d13a20bebef1b9932f86c44741ea6d214ad6842b) [#7803](https://github.com/npm/cli/pull/7803) update `npm-registry-fetch@18.0.1` +### Chores +* [`2072705`](https://github.com/npm/cli/commit/2072705aa80d009dc077639adc305692f4a6c0b9) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/eslint-config@5.0.1` (@reggi) +* [`8035725`](https://github.com/npm/cli/commit/80357253ecd8483463cd66c783c4464c330d72df) [#7756](https://github.com/npm/cli/pull/7756) `@npmcli/template-oss@4.23.3` (@wraithgar) + ## [6.0.5](https://github.com/npm/cli/compare/libnpmteam-v6.0.4...libnpmteam-v6.0.5) (2024-05-15) ### Dependencies @@ -144,7 +196,7 @@ ## [2.0.0](https://github.com/npm/libnpmteam/compare/v1.0.2...v2.0.0) (2020-03-02) ### BREAKING CHANGE -- Removed `figgy-pudding` as a dependecy +- Removed `figgy-pudding` as a dependency - Using native promises - Require node >= v10 diff --git a/workspaces/libnpmteam/README.md b/workspaces/libnpmteam/README.md index 97323f82a646f..f61032514bf82 100644 --- a/workspaces/libnpmteam/README.md +++ b/workspaces/libnpmteam/README.md @@ -8,31 +8,6 @@ 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) @@ -52,6 +27,15 @@ console.log(await team.lsTeams('npm')) `$ npm install libnpmteam` +### Example + +```javascript +const team = require('libnpmteam') + +// List all teams for the @npm org. +console.log(await team.lsTeams('npm')) +``` + ### API #### `opts` for `libnpmteam` commands diff --git a/workspaces/libnpmteam/package.json b/workspaces/libnpmteam/package.json index 4900435c5b27a..62073dac75c6b 100644 --- a/workspaces/libnpmteam/package.json +++ b/workspaces/libnpmteam/package.json @@ -1,23 +1,24 @@ { "name": "libnpmteam", "description": "npm Team management APIs", - "version": "6.0.5", + "version": "9.0.0-pre.0", "author": "GitHub Inc.", "license": "ISC", "main": "lib/index.js", "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "test": "tap", "posttest": "npm run lint", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", + "lintfix": "npm run eslint -- --fix", "snap": "tap", - "template-oss-apply": "template-oss-apply --force" + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "nock": "^13.3.3", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", + "nock": "^14.0.0", "tap": "^16.3.8" }, "repository": { @@ -32,17 +33,21 @@ "homepage": "https://npmjs.com/package/libnpmteam", "dependencies": { "aproba": "^2.0.0", - "npm-registry-fetch": "^17.0.1" + "npm-registry-fetch": "^20.0.1" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../../scripts/template-oss/index.js" }, "tap": { + "node-arg": [ + "--require", + "../../scripts/disable-agent-for-tests.js" + ], "nyc-arg": [ "--exclude", "tap-snapshots/**" diff --git a/workspaces/libnpmteam/test/index.js b/workspaces/libnpmteam/test/index.js index 6a05519e3f71a..54126625f8247 100644 --- a/workspaces/libnpmteam/test/index.js +++ b/workspaces/libnpmteam/test/index.js @@ -20,7 +20,7 @@ test('create', async t => { test('create - no options', async t => { // NOTE: mocking real url, because no opts variable means `registry` value - // will be defauled to real registry url in `npm-registry-fetch` + // will be defaulted to real registry url in `npm-registry-fetch` tnock(t, 'https://registry.npmjs.org') .put('/-/org/foo/team', { name: 'cli' }) .reply(201, { name: 'cli' }) @@ -61,7 +61,7 @@ test('destroy', async t => { test('destroy - no options', async t => { // NOTE: mocking real url, because no opts variable means `registry` value - // will be defauled to real registry url in `npm-registry-fetch` + // will be defaulted to real registry url in `npm-registry-fetch` tnock(t, 'https://registry.npmjs.org') .delete('/-/team/foo/cli') .reply(204) @@ -82,7 +82,7 @@ test('add', async t => { test('add - no options', async t => { // NOTE: mocking real url, because no opts variable means `registry` value - // will be defauled to real registry url in `npm-registry-fetch` + // will be defaulted to real registry url in `npm-registry-fetch` tnock(t, 'https://registry.npmjs.org') .put('/-/team/foo/cli/user', { user: 'zkat' }) .reply(201, {}) @@ -103,7 +103,7 @@ test('rm', async t => { test('rm - no options', async t => { // NOTE: mocking real url, because no opts variable means `registry` value - // will be defauled to real registry url in `npm-registry-fetch` + // will be defaulted to real registry url in `npm-registry-fetch` tnock(t, 'https://registry.npmjs.org') .delete('/-/team/foo/cli/user', { user: 'zkat' }) .reply(204) @@ -124,7 +124,7 @@ test('lsTeams', async t => { test('lsTeams - no options', async t => { // NOTE: mocking real url, because no opts variable means `registry` value - // will be defauled to real registry url in `npm-registry-fetch` + // will be defaulted to real registry url in `npm-registry-fetch` tnock(t, 'https://registry.npmjs.org') .get('/-/org/foo/team?format=cli') .reply(200, ['foo:bar', 'foo:cli']) @@ -153,7 +153,7 @@ test('lsTeams.stream', async t => { test('lsTeams.stream - no options', async t => { // NOTE: mocking real url, because no opts variable means `registry` value - // will be defauled to real registry url in `npm-registry-fetch` + // will be defaulted to real registry url in `npm-registry-fetch` tnock(t, 'https://registry.npmjs.org') .get('/-/org/foo/team?format=cli') .reply(200, ['foo:bar', 'foo:cli']) @@ -174,7 +174,7 @@ test('lsUsers', async t => { test('lsUsers - no options', async t => { // NOTE: mocking real url, because no opts variable means `registry` value - // will be defauled to real registry url in `npm-registry-fetch` + // will be defaulted to real registry url in `npm-registry-fetch` tnock(t, 'https://registry.npmjs.org') .get('/-/team/foo/cli/user?format=cli') .reply(500) @@ -203,7 +203,7 @@ test('lsUsers.stream', async t => { test('lsUsers.stream - no options', async t => { // NOTE: mocking real url, because no opts variable means `registry` value - // will be defauled to real registry url in `npm-registry-fetch` + // will be defaulted to real registry url in `npm-registry-fetch` tnock(t, 'https://registry.npmjs.org') .get('/-/team/foo/cli/user?format=cli') .reply(200, ['iarna', 'zkat']) diff --git a/workspaces/libnpmversion/.gitignore b/workspaces/libnpmversion/.gitignore index a96d056a7064e..08e5141aa731c 100644 --- a/workspaces/libnpmversion/.gitignore +++ b/workspaces/libnpmversion/.gitignore @@ -2,13 +2,12 @@ # ignore everything in the root /* -# transient test directories -tap-testdir*/ -# keep these !**/.gitignore +!/.eslint.config.js !/.eslintrc.js !/.eslintrc.local.* +!/.git-blame-ignore-revs !/.gitignore !/bin/ !/CHANGELOG* @@ -21,3 +20,4 @@ tap-testdir*/ !/scripts/ !/tap-snapshots/ !/test/ +tap-testdir*/ diff --git a/workspaces/libnpmversion/CHANGELOG.md b/workspaces/libnpmversion/CHANGELOG.md index 3060fec317bbe..09ae57e302451 100644 --- a/workspaces/libnpmversion/CHANGELOG.md +++ b/workspaces/libnpmversion/CHANGELOG.md @@ -1,5 +1,80 @@ # Changelog +## [9.0.0-pre.1](https://github.com/npm/cli/compare/libnpmversion-v9.0.0-pre.0...libnpmversion-v9.0.0-pre.1) (2026-06-19) +### ⚠️ BREAKING CHANGES +* `npm` now supports node `^22.22.2 || ^24.15.0 || >=26.0.0` +### Features +* [`18eb967`](https://github.com/npm/cli/commit/18eb9672dc884be4412752fb6e55e9d33c261c65) [#9559](https://github.com/npm/cli/pull/9559) bump to new node engine range (@owlstronaut) +### Bug Fixes +* [`c5292fa`](https://github.com/npm/cli/commit/c5292fa8a09a56b25394d393faf21e47ffb096c0) [#9422](https://github.com/npm/cli/pull/9422) use prerelease strategy without a bug (@owlstronaut) +### Documentation +* [`d124c08`](https://github.com/npm/cli/commit/d124c0858da0b138cda2addcb0987b063ca86a47) [#9385](https://github.com/npm/cli/pull/9385) Document `npm_old_version` and `npm_new_version` environment variables (#9385) (@36degrees) +### Dependencies +* [`3dc18e5`](https://github.com/npm/cli/commit/3dc18e561b3304778f38f9e7637ab5e0b696797e) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/git@8.0.0` +* [`21df0ab`](https://github.com/npm/cli/commit/21df0ab3c629496511a3c481ee721b0e62c16e92) [#9559](https://github.com/npm/cli/pull/9559) `proc-log@7.0.0` +* [`30e89d9`](https://github.com/npm/cli/commit/30e89d922c0ee790524151a98049aad47de70773) [#9559](https://github.com/npm/cli/pull/9559) `json-parse-even-better-errors@6.0.0` +* [`9d13ebf`](https://github.com/npm/cli/commit/9d13ebfc2adca5543e4797632039adaa7a318985) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/run-script@11.0.0` +### Chores +* [`0323f2d`](https://github.com/npm/cli/commit/0323f2d74bf2e747957c74992d9431e3fca35f85) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) +* [`ee3d87f`](https://github.com/npm/cli/commit/ee3d87fe521bc144493b93a94d456c22eb147dbf) [#9559](https://github.com/npm/cli/pull/9559) `@npmcli/template-oss@5.1.1` (@owlstronaut) +* [`d25a179`](https://github.com/npm/cli/commit/d25a1798f3ba8ff80437f491afc17e98ef07c77f) [#9559](https://github.com/npm/cli/pull/9559) template-oss-apply (@owlstronaut) + +## [9.0.0-pre.0.0](https://github.com/npm/cli/compare/libnpmversion-v8.0.3...libnpmversion-v9.0.0-pre.0.0) (2026-05-20) +### ⚠️ BREAKING CHANGES +* `npm shrinkwrap` is removed, the `shrinkwrap` config alias is removed, and `npm-shrinkwrap.json` is no longer loaded or honored at the project root or from inside dependency tarballs. Rename project-root `npm-shrinkwrap.json` to `package-lock.json`; use `bundleDependencies` if you need to ship a locked dependency tree. +### Features +* [`2e5dcad`](https://github.com/npm/cli/commit/2e5dcad17a59ee9f69eeec27fc5b087b5b032df7) [#9262](https://github.com/npm/cli/pull/9262) drop npm-shrinkwrap.json support (@owlstronaut) +### Chores +* [`40fcab4`](https://github.com/npm/cli/commit/40fcab45d356545f8db7f34df3e5630116d0dd40) [#8991](https://github.com/npm/cli/pull/8991) `@npmcli/template-oss@4.29.0` (@wraithgar) + +## [8.0.3](https://github.com/npm/cli/compare/libnpmversion-v8.0.2...libnpmversion-v8.0.3) (2025-11-19) +### Dependencies +* [`05ac7a7`](https://github.com/npm/cli/commit/05ac7a7ea2a4d258658537a19ba350e07df34fda) [#8723](https://github.com/npm/cli/pull/8723) `proc-log@6.0.0` +* [`9c0cefa`](https://github.com/npm/cli/commit/9c0cefa8417d9e14ee19dd5e833019f0f99ce837) [#8723](https://github.com/npm/cli/pull/8723) `json-parse-even-better-errors@5.0.0` +### Chores +* [`5e0909b`](https://github.com/npm/cli/commit/5e0909b74ea1510eaae348d66548c75030911ed8) [#8620](https://github.com/npm/cli/pull/8620) fix spelling in workspaces (#8620) (@jsoref) + +## [8.0.2](https://github.com/npm/cli/compare/libnpmversion-v8.0.1...libnpmversion-v8.0.2) (2025-09-23) +### Dependencies +* [`521823b`](https://github.com/npm/cli/commit/521823bc398de0eb85135a3ef09e217db93ed1ce) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/git@7.0.0` +* [`6b4c5f9`](https://github.com/npm/cli/commit/6b4c5f92865230ed9a260cd3e8486bf3991120eb) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/run-script@10.0.0` +### Chores +* [`402a0ab`](https://github.com/npm/cli/commit/402a0ab1b4e5d1a8414dd063d0cbde0c0bc5a192) [#8576](https://github.com/npm/cli/pull/8576) `@npmcli/template-oss@4.25.1` (@wraithgar) +* [`3f60b5f`](https://github.com/npm/cli/commit/3f60b5f9621b43ae0b8796d3a7160a603748f756) [#8383](https://github.com/npm/cli/pull/8383) `@npmcli/template-oss@4.24.4` (#8383) (@wraithgar) +* [`01f8cc6`](https://github.com/npm/cli/commit/01f8cc6f001e3211135fa0563f7129aed09dc46c) [#8381](https://github.com/npm/cli/pull/8381) `@npmcli/template-oss@4.24.3` (#8381) (@wraithgar) + +## [8.0.1](https://github.com/npm/cli/compare/libnpmversion-v8.0.0...libnpmversion-v8.0.1) (2025-05-15) +### Bug Fixes +* [`71bb817`](https://github.com/npm/cli/commit/71bb817599bbaabe8e05a2bc7dd32ec16622bd93) [#8279](https://github.com/npm/cli/pull/8279) version: include prerelease when retrieving tag (#8279) (@milaninfy) + +## [8.0.0](https://github.com/npm/cli/compare/libnpmversion-v8.0.0-pre.0...libnpmversion-v8.0.0) (2024-12-16) +### Features +* [`a7bfc6d`](https://github.com/npm/cli/commit/a7bfc6df76882996ebb834dbca785fdf33b8c50d) [#7972](https://github.com/npm/cli/pull/7972) trigger release process (#7972) (@wraithgar) +### Chores +* [`a07f4e0`](https://github.com/npm/cli/commit/a07f4e0d921f640be6aa87736debd550ec478f89) [#7976](https://github.com/npm/cli/pull/7976) `@npmcli/template-oss@4.23.6` (@wraithgar) + +## [8.0.0-pre.0](https://github.com/npm/cli/compare/libnpmversion-v7.0.0...libnpmversion-v8.0.0-pre.0) (2024-11-26) +### ⚠️ BREAKING CHANGES +* libnpmversion now supports node `^20.17.0 || >=22.9.0` +### Bug Fixes +* [`57eef8d`](https://github.com/npm/cli/commit/57eef8df822885ebc57096a591191bdbb3f0c95b) [#7831](https://github.com/npm/cli/pull/7831) for libnpmversion sets node engine range to `^20.17.0 || >=22.9.0` (@reggi) +### Chores +* [`6edfe2f`](https://github.com/npm/cli/commit/6edfe2f3a45169b6d194ccd8d366bb8d0e09b4a5) [#7937](https://github.com/npm/cli/pull/7937) `@npmcli/template-oss@4.23.5` (@wraithgar) + +## [7.0.0](https://github.com/npm/cli/compare/libnpmversion-v6.0.3...libnpmversion-v7.0.0) (2024-10-03) +### ⚠️ BREAKING CHANGES +* `libnpmversion` now supports node `^18.17.0 || >=20.5.0` +### Bug Fixes +* [`d3c0b1e`](https://github.com/npm/cli/commit/d3c0b1efca1431ee3dae24fdec96f7251b347614) [#7803](https://github.com/npm/cli/pull/7803) align libnpmversion to npm 10 node engine range (@reggi) +### Dependencies +* [`b84d907`](https://github.com/npm/cli/commit/b84d9079feaf9582763356e538c7247383b00e9f) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/git@6.0.1` +* [`f6909a0`](https://github.com/npm/cli/commit/f6909a022c9373c85d980c96a30f47a3a65aa4a9) [#7803](https://github.com/npm/cli/pull/7803) update `proc-log@5.0.0` +* [`7214149`](https://github.com/npm/cli/commit/72141496fbc7e5f0e0824d584b82690eeee45bb5) [#7803](https://github.com/npm/cli/pull/7803) update `json-parse-even-better-errors@4.0.0` +* [`538a4cc`](https://github.com/npm/cli/commit/538a4cc1dd731a3643ab4477fe545db39997bcdf) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/run-script@9.0.1` +### Chores +* [`2072705`](https://github.com/npm/cli/commit/2072705aa80d009dc077639adc305692f4a6c0b9) [#7803](https://github.com/npm/cli/pull/7803) update `@npmcli/eslint-config@5.0.1` (@reggi) +* [`8035725`](https://github.com/npm/cli/commit/80357253ecd8483463cd66c783c4464c330d72df) [#7756](https://github.com/npm/cli/pull/7756) `@npmcli/template-oss@4.23.3` (@wraithgar) + ## [6.0.3](https://github.com/npm/cli/compare/libnpmversion-v6.0.2...libnpmversion-v6.0.3) (2024-05-29) ### Bug Fixes diff --git a/workspaces/libnpmversion/README.md b/workspaces/libnpmversion/README.md index 857c4d52dc183..8f3f89e453a9b 100644 --- a/workspaces/libnpmversion/README.md +++ b/workspaces/libnpmversion/README.md @@ -15,8 +15,8 @@ const npmVersion = require('libnpmversion') // - 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) +// - 'from-git' (set to the latest tag in git that looks like semver - +// this skips gitTagVersion, but will still sign if asked) npmVersion(arg, { path: '/path/to/my/pkg', // defaults to cwd @@ -39,8 +39,7 @@ npmVersion(arg, { ## 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`. +back to `package.json` and `package-lock.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 @@ -86,6 +85,9 @@ The exact order of execution is as follows: 6. Run the `postversion` script. Use it to clean up the file system or automatically push the commit and/or tag. +For the `preversion`, `version` and `postversion` scripts, npm also sets the +environment variables `npm_old_version` and `npm_new_version`. + Take the following example: ```json @@ -114,7 +116,7 @@ all is well, or rejects if any errors are encountered. #### `path` String -The path to the package being versionified. Defaults to process.cwd(). +The path to the package being versioned. Defaults to process.cwd(). #### `allowSameVersion` Boolean diff --git a/workspaces/libnpmversion/lib/retrieve-tag.js b/workspaces/libnpmversion/lib/retrieve-tag.js index c5fb64e331198..230b631a16473 100644 --- a/workspaces/libnpmversion/lib/retrieve-tag.js +++ b/workspaces/libnpmversion/lib/retrieve-tag.js @@ -5,7 +5,7 @@ module.exports = async opts => { const tag = (await spawn( ['describe', '--tags', '--abbrev=0', '--match=*.*.*'], opts)).stdout.trim() - const ver = semver.coerce(tag, { loose: true }) + const ver = semver.coerce(tag, { loose: true, includePrerelease: true }) if (ver) { return ver.version } diff --git a/workspaces/libnpmversion/lib/version.js b/workspaces/libnpmversion/lib/version.js index bfcd8a521496d..df78e06c230e8 100644 --- a/workspaces/libnpmversion/lib/version.js +++ b/workspaces/libnpmversion/lib/version.js @@ -76,21 +76,19 @@ module.exports = async (newversion, opts) => { 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 + // try to update the lockfile, but ok if this fails + const lock = `${path}/package-lock.json` + let lockUpdated = false + try { + const sw = await readJson(lock) + sw.version = newV + if (sw.packages && sw.packages['']) { + sw.packages[''].version = newV } + await writeJson(lock, sw) + lockUpdated = true + } catch { + // ignore errors } if (!ignoreScripts) { @@ -110,7 +108,7 @@ module.exports = async (newversion, opts) => { // - git add, git commit, git tag await git.spawn(['add', `${path}/package.json`], opts) // sometimes people .gitignore their lockfiles - for (const lock of haveLocks) { + if (lockUpdated) { await git.spawn(['add', lock], opts).catch(() => {}) } await commit(newV, opts) diff --git a/workspaces/libnpmversion/package.json b/workspaces/libnpmversion/package.json index 3f251e4b63613..de87c55cd9516 100644 --- a/workspaces/libnpmversion/package.json +++ b/workspaces/libnpmversion/package.json @@ -1,6 +1,6 @@ { "name": "libnpmversion", - "version": "6.0.3", + "version": "9.0.0-pre.1", "main": "lib/index.js", "files": [ "bin/", @@ -15,13 +15,14 @@ "author": "GitHub Inc.", "license": "ISC", "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", "test": "tap", "posttest": "npm run lint", "snap": "tap", "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "template-oss-apply": "template-oss-apply --force" + "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", @@ -31,24 +32,24 @@ ] }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.1", + "@npmcli/template-oss": "5.1.1", "require-inject": "^1.4.4", "tap": "^16.3.8" }, "dependencies": { - "@npmcli/git": "^5.0.7", - "@npmcli/run-script": "^8.1.0", - "json-parse-even-better-errors": "^3.0.2", - "proc-log": "^4.2.0", + "@npmcli/git": "^8.0.0", + "@npmcli/run-script": "^11.0.0", + "json-parse-even-better-errors": "^6.0.0", + "proc-log": "^7.0.0", "semver": "^7.3.7" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "5.1.1", "content": "../../scripts/template-oss/index.js" } } diff --git a/workspaces/libnpmversion/test/retrieve-tag.js b/workspaces/libnpmversion/test/retrieve-tag.js index 78989ddd57054..03559162946aa 100644 --- a/workspaces/libnpmversion/test/retrieve-tag.js +++ b/workspaces/libnpmversion/test/retrieve-tag.js @@ -18,3 +18,8 @@ t.test('yes a valid semver tag', async t => { tag = 'this is a version tho: Release-1.2.3 candidate' t.equal(await retrieveTag(), '1.2.3') }) + +t.test('yes a valid semver pre-release tag', async t => { + tag = 'this is a prerelease version tho: Release-1.2.3-pre.1 candidate' + t.equal(await retrieveTag(), '1.2.3-pre.1') +}) diff --git a/workspaces/libnpmversion/test/version.js b/workspaces/libnpmversion/test/version.js index 4fee6f5cd2af9..50e9706bb9130 100644 --- a/workspaces/libnpmversion/test/version.js +++ b/workspaces/libnpmversion/test/version.js @@ -44,14 +44,7 @@ t.test('test out bumping the version in all the ways', async t => { git: { 'package-lock.json': JSON.stringify(lock, null, 2), }, - 'not-git': { - 'npm-shrinkwrap.json': JSON.stringify({ - ...lock, - packages: { - '': { ...pkg }, - }, - }, null, 2), - }, + 'not-git': {}, }) await t.test('git dir', async t => { @@ -246,7 +239,6 @@ t.test('test out bumping the version in all the ways', async t => { t.match(actionLog, [ ['run-script', 'preversion', { npm_old_version: '1.2.0', npm_new_version: '2.0.0' }], ['write-json', path + '/package.json', pkg], - ['write-json', path + '/npm-shrinkwrap.json', pkg], ['run-script', 'version', { npm_old_version: '1.2.0', npm_new_version: '2.0.0' }], ['verbose', 'version', 'Not tagging: not in a git repo or no git cmd'], ['run-script', 'postversion', { npm_old_version: '1.2.0', npm_new_version: '2.0.0' }], @@ -257,7 +249,6 @@ t.test('test out bumping the version in all the ways', async t => { t.equal(await version('minor', { path, pkg, ignoreScripts: true }), '2.1.0') t.match(actionLog, [ ['write-json', path + '/package.json', pkg], - ['write-json', path + '/npm-shrinkwrap.json', pkg], ['verbose', 'version', 'Not tagging: not in a git repo or no git cmd'], ]) t.equal(pkg.version, '2.1.0') @@ -267,7 +258,6 @@ t.test('test out bumping the version in all the ways', async t => { t.match(actionLog, [ ['run-script', 'preversion', { npm_old_version: '2.1.0', npm_new_version: '2.1.1' }], ['write-json', path + '/package.json', pkg], - ['write-json', path + '/npm-shrinkwrap.json', pkg], ['run-script', 'version', { npm_old_version: '2.1.0', npm_new_version: '2.1.1' }], ['verbose', 'version', 'Not tagging: not in a git repo or no git cmd'], ['run-script', 'postversion', { npm_old_version: '2.1.0', npm_new_version: '2.1.1' }], @@ -279,7 +269,6 @@ t.test('test out bumping the version in all the ways', async t => { t.match(actionLog, [ ['run-script', 'preversion', { npm_old_version: '2.1.1', npm_new_version: '2.1.1-0' }], ['write-json', path + '/package.json', pkg], - ['write-json', path + '/npm-shrinkwrap.json', pkg], ['run-script', 'version', { npm_old_version: '2.1.1', npm_new_version: '2.1.1-0' }], ['verbose', 'version', 'Not tagging: not in a git repo or no git cmd'], ['run-script', 'postversion', { npm_old_version: '2.1.1', npm_new_version: '2.1.1-0' }], @@ -292,7 +281,6 @@ t.test('test out bumping the version in all the ways', async t => { ['run-script', 'preversion', { npm_old_version: '2.1.1-0', npm_new_version: '2.1.1-alpha.0' }], ['write-json', path + '/package.json', pkg], - ['write-json', path + '/npm-shrinkwrap.json', pkg], ['run-script', 'version', { npm_old_version: '2.1.1-0', npm_new_version: '2.1.1-alpha.0' }], ['verbose', 'version', 'Not tagging: not in a git repo or no git cmd'], ['run-script', 'postversion', @@ -306,7 +294,6 @@ t.test('test out bumping the version in all the ways', async t => { ['run-script', 'preversion', { npm_old_version: '2.1.1-alpha.0', npm_new_version: '3.2.1' }], ['write-json', path + '/package.json', pkg], - ['write-json', path + '/npm-shrinkwrap.json', pkg], ['run-script', 'version', { npm_old_version: '2.1.1-alpha.0', npm_new_version: '3.2.1' }], ['verbose', 'version', 'Not tagging: not in a git repo or no git cmd'], ['run-script', 'postversion', @@ -335,7 +322,6 @@ t.test('test out bumping the version in all the ways', async t => { ['run-script', 'preversion', { npm_old_version: '3.2.1', npm_new_version: '3.2.1' }, {}], ['write-json', path + '/package.json', pkg], - ['write-json', path + '/npm-shrinkwrap.json', pkg], ['run-script', 'version', { npm_old_version: '3.2.1', npm_new_version: '3.2.1' }, {}], ['verbose', 'version', 'Not tagging: not in a git repo or no git cmd'], @@ -351,7 +337,6 @@ t.test('test out bumping the version in all the ways', async t => { ['run-script', 'preversion', { npm_old_version: '3.2.1', npm_new_version: '3.2.1' }, {}], ['write-json', path + '/package.json', pkg], - ['write-json', path + '/npm-shrinkwrap.json', pkg], ['run-script', 'version', { npm_old_version: '3.2.1', npm_new_version: '3.2.1' }, {}], ['verbose', 'version', 'Not tagging: not in a git repo or no git cmd'], @@ -367,3 +352,38 @@ t.test('test out bumping the version in all the ways', async t => { }) }) }) + +t.test('covers lockfile with packages[""] and git dir missing a lockfile', async t => { + const pkg = { name: 'foo', version: '1.2.0' } + const dir = t.testdir({ + 'git-with-packages-lock': { + 'package-lock.json': JSON.stringify({ + name: 'foo', + version: '1.2.0', + packages: { '': { name: 'foo', version: '1.2.0' } }, + }, null, 2), + }, + 'git-without-lock': {}, + }) + + const versionWithFailingLockAdd = requireInject('../lib/version.js', { + '../lib/enforce-clean.js': async () => true, + '../lib/write-json.js': async () => {}, + '../lib/commit.js': async () => {}, + '../lib/tag.js': async () => {}, + '../lib/retrieve-tag.js': async () => '1.2.3', + '@npmcli/git': { + is: async () => true, + spawn: async args => { + if (args[0] === 'add' && /package-lock\.json$/.test(args[1])) { + throw new Error('gitignored lockfile') + } + }, + }, + '@npmcli/run-script': async () => {}, + 'proc-log': { log: { verbose: () => {} } }, + }) + + await versionWithFailingLockAdd('patch', { path: `${dir}/git-with-packages-lock`, pkg: { ...pkg }, gitTagVersion: true }) + await version('patch', { path: `${dir}/git-without-lock`, pkg: { ...pkg }, gitTagVersion: true }) +})